Skip to content

Commit 0b7a598

Browse files
committed
Auto merge of #72603 - jsgf:extern-loc, r=nikomatsakis
Implement `--extern-location` This PR implements `--extern-location` as a followup to #72342 as part of the implementation of #57274. The goal of this PR is to allow rustc, in coordination with the build system, to present a useful diagnostic about how to remove an unnecessary dependency from a dependency specification file (eg Cargo.toml). EDIT: Updated to current PR state. The location is specified for each named crate - that is, for a given `--extern foo[=path]` there can also be `--extern-location foo=<location>`. It supports ~~three~~ two styles of location: ~~1. `--extern-location foo=file:<path>:<line>` - a file path and line specification 1. `--extern-location foo=span:<path>:<start>:<end>` - a span specified as a file and start and end byte offsets~~ 1. `--extern-location foo=raw:<anything>` - a raw string which is included in the output 1. `--extern-location foo=json:<anything>` - an arbitrary Json structure which is emitted via Json diagnostics in a `tool_metadata` field. ~~1 & 2 are turned into an internal `Span`, so long as the path exists and is readable, and the location is meaningful (within the file, etc). This is used as the `Span` for a fix suggestion which is reported like other fix suggestions.~~ `raw` and `json` are for the case where the location isn't best expressed as a file and location within that file. For example, it could be a rule name and the name of a dependency within that rule. `rustc` makes no attempt to parse the raw string, and simply includes it in the output diagnostic text. `json` is only included in json diagnostics. `raw` is emitted as text and also as a json string in `tool_metadata`. If no `--extern-location` option is specified then it will emit a default json structure consisting of `{"name": name, "path": path}` corresponding to the name and path in `--extern name=path`. This is a prototype/RFC to make some of the earlier conversations more concrete. It doesn't stand on its own - it's only useful if implemented by Cargo and other build systems. There's also a ton of implementation details which I'd appreciate a second eye on as well. ~~**NOTE** The first commit in this PR is #72342 and should be ignored for the purposes of review. The first commit is a very simplistic implementation which is basically raw-only, presented as a MVP. The second implements the full thing, and subsequent commits are incremental fixes.~~ cc `@ehuss` `@est31` `@petrochenkov` `@estebank`
2 parents bb587b1 + 91d8c3b commit 0b7a598

37 files changed

+534
-10
lines changed

Cargo.lock

+3-2
Original file line numberDiff line numberDiff line change
@@ -726,9 +726,9 @@ dependencies = [
726726

727727
[[package]]
728728
name = "const_fn"
729-
version = "0.4.2"
729+
version = "0.4.3"
730730
source = "registry+https://github.com/rust-lang/crates.io-index"
731-
checksum = "ce90df4c658c62f12d78f7508cf92f9173e5184a539c10bfe54a3107b3ffd0f2"
731+
checksum = "c478836e029dcef17fb47c89023448c64f781a046e0300e257ad8225ae59afab"
732732

733733
[[package]]
734734
name = "constant_time_eq"
@@ -3914,6 +3914,7 @@ dependencies = [
39143914
"rustc_index",
39153915
"rustc_middle",
39163916
"rustc_parse_format",
3917+
"rustc_serialize",
39173918
"rustc_session",
39183919
"rustc_span",
39193920
"rustc_target",

compiler/rustc_errors/src/diagnostic.rs

+24
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ use crate::Level;
44
use crate::Substitution;
55
use crate::SubstitutionPart;
66
use crate::SuggestionStyle;
7+
use crate::ToolMetadata;
78
use rustc_lint_defs::Applicability;
9+
use rustc_serialize::json::Json;
810
use rustc_span::{MultiSpan, Span, DUMMY_SP};
911
use std::fmt;
1012

@@ -303,6 +305,7 @@ impl Diagnostic {
303305
msg: msg.to_owned(),
304306
style: SuggestionStyle::ShowCode,
305307
applicability,
308+
tool_metadata: Default::default(),
306309
});
307310
self
308311
}
@@ -328,6 +331,7 @@ impl Diagnostic {
328331
msg: msg.to_owned(),
329332
style: SuggestionStyle::ShowCode,
330333
applicability,
334+
tool_metadata: Default::default(),
331335
});
332336
self
333337
}
@@ -354,6 +358,7 @@ impl Diagnostic {
354358
msg: msg.to_owned(),
355359
style: SuggestionStyle::CompletelyHidden,
356360
applicability,
361+
tool_metadata: Default::default(),
357362
});
358363
self
359364
}
@@ -408,6 +413,7 @@ impl Diagnostic {
408413
msg: msg.to_owned(),
409414
style,
410415
applicability,
416+
tool_metadata: Default::default(),
411417
});
412418
self
413419
}
@@ -446,6 +452,7 @@ impl Diagnostic {
446452
msg: msg.to_owned(),
447453
style: SuggestionStyle::ShowCode,
448454
applicability,
455+
tool_metadata: Default::default(),
449456
});
450457
self
451458
}
@@ -515,6 +522,23 @@ impl Diagnostic {
515522
self
516523
}
517524

525+
/// Adds a suggestion intended only for a tool. The intent is that the metadata encodes
526+
/// the suggestion in a tool-specific way, as it may not even directly involve Rust code.
527+
pub fn tool_only_suggestion_with_metadata(
528+
&mut self,
529+
msg: &str,
530+
applicability: Applicability,
531+
tool_metadata: Json,
532+
) {
533+
self.suggestions.push(CodeSuggestion {
534+
substitutions: vec![],
535+
msg: msg.to_owned(),
536+
style: SuggestionStyle::CompletelyHidden,
537+
applicability,
538+
tool_metadata: ToolMetadata::new(tool_metadata),
539+
})
540+
}
541+
518542
pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
519543
self.span = sp.into();
520544
if let Some(span) = self.span.primary_span() {

compiler/rustc_errors/src/json.rs

+66-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_span::source_map::{FilePathMapping, SourceMap};
1414
use crate::emitter::{Emitter, HumanReadableErrorType};
1515
use crate::registry::Registry;
1616
use crate::DiagnosticId;
17+
use crate::ToolMetadata;
1718
use crate::{CodeSuggestion, SubDiagnostic};
1819
use rustc_lint_defs::{Applicability, FutureBreakage};
1920

@@ -26,6 +27,7 @@ use std::sync::{Arc, Mutex};
2627
use std::vec;
2728

2829
use rustc_serialize::json::{as_json, as_pretty_json};
30+
use rustc_serialize::{Encodable, Encoder};
2931

3032
#[cfg(test)]
3133
mod tests;
@@ -168,7 +170,8 @@ impl Emitter for JsonEmitter {
168170

169171
// The following data types are provided just for serialisation.
170172

171-
#[derive(Encodable)]
173+
// NOTE: this has a manual implementation of Encodable which needs to be updated in
174+
// parallel.
172175
struct Diagnostic {
173176
/// The primary error message.
174177
message: String,
@@ -180,6 +183,65 @@ struct Diagnostic {
180183
children: Vec<Diagnostic>,
181184
/// The message as rustc would render it.
182185
rendered: Option<String>,
186+
/// Extra tool metadata
187+
tool_metadata: ToolMetadata,
188+
}
189+
190+
macro_rules! encode_fields {
191+
(
192+
$enc:expr, // encoder
193+
$idx:expr, // starting field index
194+
$struct:expr, // struct we're serializing
195+
$struct_name:ident, // struct name
196+
[ $($name:ident),+$(,)? ], // fields to encode
197+
[ $($ignore:ident),+$(,)? ] // fields we're skipping
198+
) => {
199+
{
200+
// Pattern match to make sure all fields are accounted for
201+
let $struct_name { $($name,)+ $($ignore: _,)+ } = $struct;
202+
let mut idx = $idx;
203+
$(
204+
$enc.emit_struct_field(
205+
stringify!($name),
206+
idx,
207+
|enc| $name.encode(enc),
208+
)?;
209+
idx += 1;
210+
)+
211+
idx
212+
}
213+
};
214+
}
215+
216+
// Special-case encoder to skip tool_metadata if not set
217+
impl<E: Encoder> Encodable<E> for Diagnostic {
218+
fn encode(&self, s: &mut E) -> Result<(), E::Error> {
219+
s.emit_struct("diagnostic", 7, |s| {
220+
let mut idx = 0;
221+
222+
idx = encode_fields!(
223+
s,
224+
idx,
225+
self,
226+
Self,
227+
[message, code, level, spans, children, rendered],
228+
[tool_metadata]
229+
);
230+
if self.tool_metadata.is_set() {
231+
idx = encode_fields!(
232+
s,
233+
idx,
234+
self,
235+
Self,
236+
[tool_metadata],
237+
[message, code, level, spans, children, rendered]
238+
);
239+
}
240+
241+
let _ = idx;
242+
Ok(())
243+
})
244+
}
183245
}
184246

185247
#[derive(Encodable)]
@@ -269,6 +331,7 @@ impl Diagnostic {
269331
spans: DiagnosticSpan::from_suggestion(sugg, je),
270332
children: vec![],
271333
rendered: None,
334+
tool_metadata: sugg.tool_metadata.clone(),
272335
});
273336

274337
// generate regular command line output and store it in the json
@@ -312,6 +375,7 @@ impl Diagnostic {
312375
.chain(sugg)
313376
.collect(),
314377
rendered: Some(output),
378+
tool_metadata: ToolMetadata::default(),
315379
}
316380
}
317381

@@ -327,6 +391,7 @@ impl Diagnostic {
327391
.unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
328392
children: vec![],
329393
rendered: None,
394+
tool_metadata: ToolMetadata::default(),
330395
}
331396
}
332397
}

compiler/rustc_errors/src/lib.rs

+38-1
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,13 @@ use rustc_data_structures::sync::{self, Lock, Lrc};
2323
use rustc_data_structures::AtomicRef;
2424
use rustc_lint_defs::FutureBreakage;
2525
pub use rustc_lint_defs::{pluralize, Applicability};
26+
use rustc_serialize::json::Json;
27+
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
2628
use rustc_span::source_map::SourceMap;
2729
use rustc_span::{Loc, MultiSpan, Span};
2830

2931
use std::borrow::Cow;
32+
use std::hash::{Hash, Hasher};
3033
use std::panic;
3134
use std::path::Path;
3235
use std::{error, fmt};
@@ -73,6 +76,39 @@ impl SuggestionStyle {
7376
}
7477
}
7578

79+
#[derive(Clone, Debug, PartialEq, Default)]
80+
pub struct ToolMetadata(pub Option<Json>);
81+
82+
impl ToolMetadata {
83+
fn new(json: Json) -> Self {
84+
ToolMetadata(Some(json))
85+
}
86+
87+
fn is_set(&self) -> bool {
88+
self.0.is_some()
89+
}
90+
}
91+
92+
impl Hash for ToolMetadata {
93+
fn hash<H: Hasher>(&self, _state: &mut H) {}
94+
}
95+
96+
// Doesn't really need to round-trip
97+
impl<D: Decoder> Decodable<D> for ToolMetadata {
98+
fn decode(_d: &mut D) -> Result<Self, D::Error> {
99+
Ok(ToolMetadata(None))
100+
}
101+
}
102+
103+
impl<S: Encoder> Encodable<S> for ToolMetadata {
104+
fn encode(&self, e: &mut S) -> Result<(), S::Error> {
105+
match &self.0 {
106+
None => e.emit_unit(),
107+
Some(json) => json.encode(e),
108+
}
109+
}
110+
}
111+
76112
#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
77113
pub struct CodeSuggestion {
78114
/// Each substitute can have multiple variants due to multiple
@@ -106,6 +142,8 @@ pub struct CodeSuggestion {
106142
/// which are useful for users but not useful for
107143
/// tools like rustfix
108144
pub applicability: Applicability,
145+
/// Tool-specific metadata
146+
pub tool_metadata: ToolMetadata,
109147
}
110148

111149
#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
@@ -775,7 +813,6 @@ impl HandlerInner {
775813
}
776814

777815
let already_emitted = |this: &mut Self| {
778-
use std::hash::Hash;
779816
let mut hasher = StableHasher::new();
780817
diagnostic.hash(&mut hasher);
781818
let diagnostic_hash = hasher.finish();

compiler/rustc_lint/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,6 @@ rustc_data_structures = { path = "../rustc_data_structures" }
1919
rustc_feature = { path = "../rustc_feature" }
2020
rustc_index = { path = "../rustc_index" }
2121
rustc_session = { path = "../rustc_session" }
22+
rustc_serialize = { path = "../rustc_serialize" }
2223
rustc_trait_selection = { path = "../rustc_trait_selection" }
2324
rustc_parse_format = { path = "../rustc_parse_format" }

compiler/rustc_lint/src/context.rs

+29-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ use crate::passes::{EarlyLintPassObject, LateLintPassObject};
2121
use rustc_ast as ast;
2222
use rustc_data_structures::fx::FxHashMap;
2323
use rustc_data_structures::sync;
24-
use rustc_errors::{add_elided_lifetime_in_path_suggestion, struct_span_err, Applicability};
24+
use rustc_errors::{
25+
add_elided_lifetime_in_path_suggestion, struct_span_err, Applicability, SuggestionStyle,
26+
};
2527
use rustc_hir as hir;
2628
use rustc_hir::def::Res;
2729
use rustc_hir::def_id::{CrateNum, DefId};
@@ -32,7 +34,8 @@ use rustc_middle::middle::stability;
3234
use rustc_middle::ty::layout::{LayoutError, TyAndLayout};
3335
use rustc_middle::ty::print::with_no_trimmed_paths;
3436
use rustc_middle::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
35-
use rustc_session::lint::BuiltinLintDiagnostics;
37+
use rustc_serialize::json::Json;
38+
use rustc_session::lint::{BuiltinLintDiagnostics, ExternDepSpec};
3639
use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
3740
use rustc_session::Session;
3841
use rustc_session::SessionLintStore;
@@ -639,6 +642,30 @@ pub trait LintContext: Sized {
639642
BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
640643
db.span_label(span, "the attribute is introduced here");
641644
}
645+
BuiltinLintDiagnostics::ExternDepSpec(krate, loc) => {
646+
let json = match loc {
647+
ExternDepSpec::Json(json) => {
648+
db.help(&format!("remove unnecessary dependency `{}`", krate));
649+
json
650+
}
651+
ExternDepSpec::Raw(raw) => {
652+
db.help(&format!("remove unnecessary dependency `{}` at `{}`", krate, raw));
653+
db.span_suggestion_with_style(
654+
DUMMY_SP,
655+
"raw extern location",
656+
raw.clone(),
657+
Applicability::Unspecified,
658+
SuggestionStyle::CompletelyHidden,
659+
);
660+
Json::String(raw)
661+
}
662+
};
663+
db.tool_only_suggestion_with_metadata(
664+
"json extern location",
665+
Applicability::Unspecified,
666+
json
667+
);
668+
}
642669
}
643670
// Rewrap `db`, and pass control to the user.
644671
decorate(LintDiagnosticBuilder::new(db));

compiler/rustc_lint_defs/src/lib.rs

+9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ extern crate rustc_macros;
44
pub use self::Level::*;
55
use rustc_ast::node_id::{NodeId, NodeMap};
66
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
7+
use rustc_serialize::json::Json;
78
use rustc_span::edition::Edition;
89
use rustc_span::{sym, symbol::Ident, MultiSpan, Span, Symbol};
910
use rustc_target::spec::abi::Abi;
@@ -239,6 +240,13 @@ impl<HCX> ToStableHashKey<HCX> for LintId {
239240
}
240241
}
241242

243+
// Duplicated from rustc_session::config::ExternDepSpec to avoid cyclic dependency
244+
#[derive(PartialEq)]
245+
pub enum ExternDepSpec {
246+
Json(Json),
247+
Raw(String),
248+
}
249+
242250
// This could be a closure, but then implementing derive trait
243251
// becomes hacky (and it gets allocated).
244252
#[derive(PartialEq)]
@@ -257,6 +265,7 @@ pub enum BuiltinLintDiagnostics {
257265
UnusedDocComment(Span),
258266
PatternsInFnsWithoutBody(Span, Ident),
259267
LegacyDeriveHelpers(Span),
268+
ExternDepSpec(String, ExternDepSpec),
260269
}
261270

262271
/// Lints that are buffered up early on in the `Session` before the

0 commit comments

Comments
 (0)