Skip to content

Commit 87e1957

Browse files
committed
Auto merge of #54750 - pietroalbini:beta-backports, r=pietroalbini
[beta] Rollup backports Merged and approved: * #54650: Don't lint non-extern-prelude extern crate's in Rust 2018. * #54338: Use full name to identify a macro in a `FileName`. * #54518: resolve: Do not block derive helper resolutions on single import resolutions * #54581: Accept trailing comma in `cfg_attr` r? @ghost
2 parents a18eb48 + 2280d59 commit 87e1957

30 files changed

+223
-146
lines changed

src/librustc/hir/map/definitions.rs

+25
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,31 @@ impl DefPath {
287287
s
288288
}
289289

290+
/// Return filename friendly string of the DefPah with the
291+
/// crate-prefix.
292+
pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
293+
where F: FnOnce(CrateNum) -> Symbol
294+
{
295+
let crate_name_str = crate_imported_name(self.krate).as_str();
296+
let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
297+
298+
write!(s, "::{}", crate_name_str).unwrap();
299+
300+
for component in &self.data {
301+
if component.disambiguator == 0 {
302+
write!(s, "::{}", component.data.as_interned_str()).unwrap();
303+
} else {
304+
write!(s,
305+
"{}[{}]",
306+
component.data.as_interned_str(),
307+
component.disambiguator)
308+
.unwrap();
309+
}
310+
}
311+
312+
s
313+
}
314+
290315
/// Return filename friendly string of the DefPah without
291316
/// the crate-prefix. This method is useful if you don't have
292317
/// a TyCtxt available.

src/librustc/session/mod.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use syntax::parse;
3737
use syntax::parse::ParseSess;
3838
use syntax::{ast, source_map};
3939
use syntax::feature_gate::AttributeType;
40-
use syntax_pos::{MultiSpan, Span};
40+
use syntax_pos::{MultiSpan, Span, symbol::Symbol};
4141
use util::profiling::SelfProfiler;
4242

4343
use rustc_target::spec::PanicStrategy;
@@ -164,6 +164,10 @@ pub struct Session {
164164

165165
/// Cap lint level specified by a driver specifically.
166166
pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
167+
168+
/// All the crate names specified with `--extern`, and the builtin ones.
169+
/// Starting with the Rust 2018 edition, absolute paths resolve in this set.
170+
pub extern_prelude: FxHashSet<Symbol>,
167171
}
168172

169173
pub struct PerfStats {
@@ -1109,6 +1113,17 @@ pub fn build_session_(
11091113
};
11101114
let working_dir = file_path_mapping.map_prefix(working_dir);
11111115

1116+
let mut extern_prelude: FxHashSet<Symbol> =
1117+
sopts.externs.iter().map(|kv| Symbol::intern(kv.0)).collect();
1118+
1119+
// HACK(eddyb) this ignores the `no_{core,std}` attributes.
1120+
// FIXME(eddyb) warn (somewhere) if core/std is used with `no_{core,std}`.
1121+
// if !attr::contains_name(&krate.attrs, "no_core") {
1122+
// if !attr::contains_name(&krate.attrs, "no_std") {
1123+
extern_prelude.insert(Symbol::intern("core"));
1124+
extern_prelude.insert(Symbol::intern("std"));
1125+
extern_prelude.insert(Symbol::intern("meta"));
1126+
11121127
let sess = Session {
11131128
target: target_cfg,
11141129
host,
@@ -1183,6 +1198,7 @@ pub fn build_session_(
11831198
has_global_allocator: Once::new(),
11841199
has_panic_handler: Once::new(),
11851200
driver_lint_caps: FxHashMap(),
1201+
extern_prelude,
11861202
};
11871203

11881204
validate_commandline_args_with_session_available(&sess);

src/librustc/ty/query/on_disk_cache.rs

+1
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ impl<'a, 'tcx, 'x> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, '
606606
alloc_decoding_session.decode_alloc_id(self)
607607
}
608608
}
609+
609610
impl<'a, 'tcx, 'x> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx, 'x> {
610611
fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
611612
let tag: u8 = Decodable::decode(self)?;

src/librustc_metadata/creader.rs

+1
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ impl<'a> CrateLoader<'a> {
256256

257257
let cmeta = cstore::CrateMetadata {
258258
name: crate_root.name,
259+
imported_name: ident,
259260
extern_crate: Lock::new(None),
260261
def_path_table: Lrc::new(def_path_table),
261262
trait_impls,

src/librustc_metadata/cstore.rs

+5
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,13 @@ pub struct ImportedSourceFile {
5353
}
5454

5555
pub struct CrateMetadata {
56+
/// Original name of the crate.
5657
pub name: Symbol,
5758

59+
/// Name of the crate as imported. I.e. if imported with
60+
/// `extern crate foo as bar;` this will be `bar`.
61+
pub imported_name: Symbol,
62+
5863
/// Information about the extern crate that caused this crate to
5964
/// be loaded. If this is `None`, then the crate was injected
6065
/// (e.g., by the allocator)

src/librustc_metadata/cstore_impl.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -441,8 +441,7 @@ impl cstore::CStore {
441441
let data = self.get_crate_data(id.krate);
442442
if let Some(ref proc_macros) = data.proc_macros {
443443
return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
444-
} else if data.name == "proc_macro" &&
445-
self.get_crate_data(id.krate).item_name(id.index) == "quote" {
444+
} else if data.name == "proc_macro" && data.item_name(id.index) == "quote" {
446445
use syntax::ext::base::SyntaxExtension;
447446
use syntax_ext::proc_macro_impl::BangProcMacro;
448447

@@ -454,8 +453,9 @@ impl cstore::CStore {
454453
return LoadedMacro::ProcMacro(Lrc::new(ext));
455454
}
456455

457-
let (name, def) = data.get_macro(id.index);
458-
let source_name = FileName::Macros(name.to_string());
456+
let def = data.get_macro(id.index);
457+
let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.imported_name);
458+
let source_name = FileName::Macros(macro_full_name);
459459

460460
let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
461461
let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);

src/librustc_metadata/decoder.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1101,10 +1101,10 @@ impl<'a, 'tcx> CrateMetadata {
11011101
}
11021102
}
11031103

1104-
pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1104+
pub fn get_macro(&self, id: DefIndex) -> MacroDef {
11051105
let entry = self.entry(id);
11061106
match entry.kind {
1107-
EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1107+
EntryKind::MacroDef(macro_def) => macro_def.decode(self),
11081108
_ => bug!(),
11091109
}
11101110
}

src/librustc_resolve/lib.rs

+3-17
Original file line numberDiff line numberDiff line change
@@ -1350,7 +1350,6 @@ pub struct Resolver<'a, 'b: 'a> {
13501350
graph_root: Module<'a>,
13511351

13521352
prelude: Option<Module<'a>>,
1353-
extern_prelude: FxHashSet<Name>,
13541353

13551354
/// n.b. This is used only for better diagnostics, not name resolution itself.
13561355
has_self: FxHashSet<DefId>,
@@ -1663,17 +1662,6 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
16631662
DefCollector::new(&mut definitions, Mark::root())
16641663
.collect_root(crate_name, session.local_crate_disambiguator());
16651664

1666-
let mut extern_prelude: FxHashSet<Name> =
1667-
session.opts.externs.iter().map(|kv| Symbol::intern(kv.0)).collect();
1668-
1669-
// HACK(eddyb) this ignore the `no_{core,std}` attributes.
1670-
// FIXME(eddyb) warn (elsewhere) if core/std is used with `no_{core,std}`.
1671-
// if !attr::contains_name(&krate.attrs, "no_core") {
1672-
// if !attr::contains_name(&krate.attrs, "no_std") {
1673-
extern_prelude.insert(Symbol::intern("core"));
1674-
extern_prelude.insert(Symbol::intern("std"));
1675-
extern_prelude.insert(Symbol::intern("meta"));
1676-
16771665
let mut invocations = FxHashMap();
16781666
invocations.insert(Mark::root(),
16791667
arenas.alloc_invocation_data(InvocationData::root(graph_root)));
@@ -1692,7 +1680,6 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
16921680
// AST.
16931681
graph_root,
16941682
prelude: None,
1695-
extern_prelude,
16961683

16971684
has_self: FxHashSet(),
16981685
field_names: FxHashMap(),
@@ -1963,7 +1950,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
19631950

19641951
if !module.no_implicit_prelude {
19651952
// `record_used` means that we don't try to load crates during speculative resolution
1966-
if record_used && ns == TypeNS && self.extern_prelude.contains(&ident.name) {
1953+
if record_used && ns == TypeNS && self.session.extern_prelude.contains(&ident.name) {
19671954
let crate_id = self.crate_loader.process_path_extern(ident.name, ident.span);
19681955
let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
19691956
self.populate_module_if_necessary(&crate_root);
@@ -3950,7 +3937,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
39503937
} else {
39513938
// Items from the prelude
39523939
if !module.no_implicit_prelude {
3953-
names.extend(self.extern_prelude.iter().cloned());
3940+
names.extend(self.session.extern_prelude.iter().cloned());
39543941
if let Some(prelude) = self.prelude {
39553942
add_module_candidates(prelude, &mut names);
39563943
}
@@ -4396,8 +4383,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
43964383
);
43974384

43984385
if self.session.rust_2018() {
4399-
let extern_prelude_names = self.extern_prelude.clone();
4400-
for &name in extern_prelude_names.iter() {
4386+
for &name in &self.session.extern_prelude {
44014387
let ident = Ident::with_empty_ctxt(name);
44024388
match self.crate_loader.maybe_process_path_extern(name, ident.span) {
44034389
Some(crate_id) => {

src/librustc_resolve/macros.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,13 @@ impl<'a, 'cl> Resolver<'a, 'cl> {
575575
// 5. Standard library prelude (de-facto closed, controlled).
576576
// 6. Language prelude (closed, controlled).
577577
// (Macro NS)
578+
// 0. Derive helpers (open, not controlled). All ambiguities with other names
579+
// are currently reported as errors. They should be higher in priority than preludes
580+
// and probably even names in modules according to the "general principles" above. They
581+
// also should be subject to restricted shadowing because are effectively produced by
582+
// derives (you need to resolve the derive first to add helpers into scope), but they
583+
// should be available before the derive is expanded for compatibility.
584+
// It's mess in general, so we are being conservative for now.
578585
// 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
579586
// (open, not controlled).
580587
// 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
@@ -583,13 +590,6 @@ impl<'a, 'cl> Resolver<'a, 'cl> {
583590
// 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
584591
// 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
585592
// 4. Language prelude: builtin attributes (closed, controlled).
586-
// N (unordered). Derive helpers (open, not controlled). All ambiguities with other names
587-
// are currently reported as errors. They should be higher in priority than preludes
588-
// and maybe even names in modules according to the "general principles" above. They
589-
// also should be subject to restricted shadowing because are effectively produced by
590-
// derives (you need to resolve the derive first to add helpers into scope), but they
591-
// should be available before the derive is expanded for compatibility.
592-
// It's mess in general, so we are being conservative for now.
593593

594594
assert!(ns == TypeNS || ns == MacroNS);
595595
assert!(force || !record_used); // `record_used` implies `force`
@@ -621,7 +621,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> {
621621
}
622622

623623
// Go through all the scopes and try to resolve the name.
624-
let mut where_to_resolve = WhereToResolve::Module(parent_scope.module);
624+
let mut where_to_resolve = WhereToResolve::DeriveHelpers;
625625
let mut use_prelude = !parent_scope.module.no_implicit_prelude;
626626
loop {
627627
let result = match where_to_resolve {
@@ -681,7 +681,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> {
681681
result
682682
}
683683
WhereToResolve::ExternPrelude => {
684-
if use_prelude && self.extern_prelude.contains(&ident.name) {
684+
if use_prelude && self.session.extern_prelude.contains(&ident.name) {
685685
let crate_id =
686686
self.crate_loader.process_path_extern(ident.name, ident.span);
687687
let crate_root =
@@ -751,8 +751,8 @@ impl<'a, 'cl> Resolver<'a, 'cl> {
751751
}
752752
WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
753753
WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
754-
WhereToResolve::BuiltinAttrs => WhereToResolve::DeriveHelpers,
755-
WhereToResolve::DeriveHelpers => break, // nowhere else to search
754+
WhereToResolve::BuiltinAttrs => break, // nowhere else to search
755+
WhereToResolve::DeriveHelpers => WhereToResolve::Module(parent_scope.module),
756756
WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
757757
WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
758758
WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,

src/librustc_resolve/resolve_imports.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
199199
if !(
200200
ns == TypeNS &&
201201
!ident.is_path_segment_keyword() &&
202-
self.extern_prelude.contains(&ident.name)
202+
self.session.extern_prelude.contains(&ident.name)
203203
) {
204204
// ... unless the crate name is not in the `extern_prelude`.
205205
return binding;
@@ -218,7 +218,7 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
218218
} else if
219219
ns == TypeNS &&
220220
!ident.is_path_segment_keyword() &&
221-
self.extern_prelude.contains(&ident.name)
221+
self.session.extern_prelude.contains(&ident.name)
222222
{
223223
let crate_id =
224224
self.crate_loader.process_path_extern(ident.name, ident.span);
@@ -735,7 +735,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
735735
let uniform_paths_feature = self.session.features_untracked().uniform_paths;
736736
for ((span, _, ns), results) in uniform_paths_canaries {
737737
let name = results.name;
738-
let external_crate = if ns == TypeNS && self.extern_prelude.contains(&name) {
738+
let external_crate = if ns == TypeNS && self.session.extern_prelude.contains(&name) {
739739
let crate_id =
740740
self.crate_loader.process_path_extern(name, span);
741741
Some(Def::Mod(DefId { krate: crate_id, index: CRATE_DEF_INDEX }))

src/librustc_typeck/check_unused.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -130,15 +130,13 @@ fn unused_crates_lint<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) {
130130
});
131131

132132
for extern_crate in &crates_to_lint {
133-
assert!(extern_crate.def_id.is_local());
133+
let id = tcx.hir.as_local_node_id(extern_crate.def_id).unwrap();
134+
let item = tcx.hir.expect_item(id);
134135

135136
// If the crate is fully unused, we suggest removing it altogether.
136137
// We do this in any edition.
137138
if extern_crate.warn_if_unused {
138139
if let Some(&span) = unused_extern_crates.get(&extern_crate.def_id) {
139-
assert_eq!(extern_crate.def_id.krate, LOCAL_CRATE);
140-
let hir_id = tcx.hir.definitions().def_index_to_hir_id(extern_crate.def_id.index);
141-
let id = tcx.hir.hir_to_node_id(hir_id);
142140
let msg = "unused extern crate";
143141
tcx.struct_span_lint_node(lint, id, span, msg)
144142
.span_suggestion_short_with_applicability(
@@ -157,6 +155,13 @@ fn unused_crates_lint<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) {
157155
continue;
158156
}
159157

158+
// If the extern crate isn't in the extern prelude,
159+
// there is no way it can be written as an `use`.
160+
let orig_name = extern_crate.orig_name.unwrap_or(item.name);
161+
if !tcx.sess.extern_prelude.contains(&orig_name) {
162+
continue;
163+
}
164+
160165
// If the extern crate has any attributes, they may have funky
161166
// semantics we can't faithfully represent using `use` (most
162167
// notably `#[macro_use]`). Ignore it.
@@ -165,9 +170,6 @@ fn unused_crates_lint<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) {
165170
}
166171

167172
// Otherwise, we can convert it into a `use` of some kind.
168-
let hir_id = tcx.hir.definitions().def_index_to_hir_id(extern_crate.def_id.index);
169-
let id = tcx.hir.hir_to_node_id(hir_id);
170-
let item = tcx.hir.expect_item(id);
171173
let msg = "`extern crate` is not idiomatic in the new edition";
172174
let help = format!(
173175
"convert it to a `{}`",

src/libsyntax/config.rs

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ impl<'a> StripUnconfigured<'a> {
8989
parser.expect(&token::Comma)?;
9090
let lo = parser.span.lo();
9191
let (path, tokens) = parser.parse_meta_item_unrestricted()?;
92+
parser.eat(&token::Comma); // Optional trailing comma
9293
parser.expect(&token::CloseDelim(token::Paren))?;
9394
Ok((cfg, path, tokens, parser.prev_span.with_lo(lo)))
9495
}) {

src/libsyntax_pos/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ scoped_thread_local!(pub static GLOBALS: Globals);
8787
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
8888
pub enum FileName {
8989
Real(PathBuf),
90-
/// e.g. "std" macros
90+
/// A macro. This includes the full name of the macro, so that there are no clashes.
9191
Macros(String),
9292
/// call to `quote!`
9393
QuoteExpansion,

src/test/compile-fail-fulldeps/proc-macro/proc-macro-attributes.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,11 @@
1111
// aux-build:derive-b.rs
1212
// ignore-stage1
1313

14-
#![allow(warnings)]
15-
1614
#[macro_use]
1715
extern crate derive_b;
1816

19-
#[B] //~ ERROR `B` is a derive mode
20-
#[C]
17+
#[B]
18+
#[C] //~ ERROR attribute `C` is currently unknown to the compiler
2119
#[B(D)]
2220
#[B(E = "foo")]
2321
#[B(arbitrary tokens)]

src/test/ui-fulldeps/custom-derive/auxiliary/plugin.rs

+10
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,13 @@ pub fn derive_foo(input: TokenStream) -> TokenStream {
2525
pub fn derive_bar(input: TokenStream) -> TokenStream {
2626
panic!("lolnope");
2727
}
28+
29+
#[proc_macro_derive(WithHelper, attributes(helper))]
30+
pub fn with_helper(input: TokenStream) -> TokenStream {
31+
TokenStream::new()
32+
}
33+
34+
#[proc_macro_attribute]
35+
pub fn helper(_: TokenStream, input: TokenStream) -> TokenStream {
36+
input
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// aux-build:plugin.rs
2+
// ignore-stage1
3+
4+
#[macro_use(WithHelper)]
5+
extern crate plugin;
6+
7+
use plugin::helper;
8+
9+
#[derive(WithHelper)]
10+
#[helper] //~ ERROR `helper` is ambiguous
11+
struct S;
12+
13+
fn main() {}

0 commit comments

Comments
 (0)