]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
resolve: Future proof derive helper attributes
[rust.git] / src / librustc_resolve / macros.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use {AmbiguityError, CrateLint, Resolver, ResolutionError, is_known_tool, resolve_error};
12 use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult, ToNameBinding};
13 use ModuleOrUniformRoot;
14 use Namespace::{self, TypeNS, MacroNS};
15 use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
16 use resolve_imports::ImportResolver;
17 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex,
18                          DefIndexAddressSpace};
19 use rustc::hir::def::{Def, NonMacroAttrKind};
20 use rustc::hir::map::{self, DefCollector};
21 use rustc::{ty, lint};
22 use rustc::middle::cstore::CrateStore;
23 use syntax::ast::{self, Name, Ident};
24 use syntax::attr;
25 use syntax::errors::DiagnosticBuilder;
26 use syntax::ext::base::{self, Determinacy, MultiModifier, MultiDecorator};
27 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
28 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
29 use syntax::ext::hygiene::{self, Mark};
30 use syntax::ext::tt::macro_rules;
31 use syntax::feature_gate::{self, feature_err, emit_feature_err, is_builtin_attr_name, GateIssue};
32 use syntax::feature_gate::EXPLAIN_DERIVE_UNDERSCORE;
33 use syntax::fold::{self, Folder};
34 use syntax::parse::parser::PathStyle;
35 use syntax::parse::token::{self, Token};
36 use syntax::ptr::P;
37 use syntax::symbol::{Symbol, keywords};
38 use syntax::tokenstream::{TokenStream, TokenTree, Delimited, DelimSpan};
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax_pos::{Span, DUMMY_SP};
41 use errors::Applicability;
42
43 use std::cell::Cell;
44 use std::mem;
45 use rustc_data_structures::sync::Lrc;
46 use rustc_data_structures::small_vec::ExpectOne;
47
48 #[derive(Clone, Copy)]
49 crate struct FromPrelude(bool);
50
51 #[derive(Clone)]
52 pub struct InvocationData<'a> {
53     def_index: DefIndex,
54     /// Module in which the macro was invoked.
55     crate module: Cell<Module<'a>>,
56     /// Legacy scope in which the macro was invoked.
57     /// The invocation path is resolved in this scope.
58     crate parent_legacy_scope: Cell<LegacyScope<'a>>,
59     /// Legacy scope *produced* by expanding this macro invocation,
60     /// includes all the macro_rules items, other invocations, etc generated by it.
61     /// Set to the parent scope if the macro is not expanded yet (as if the macro produced nothing).
62     crate output_legacy_scope: Cell<LegacyScope<'a>>,
63 }
64
65 impl<'a> InvocationData<'a> {
66     pub fn root(graph_root: Module<'a>) -> Self {
67         InvocationData {
68             module: Cell::new(graph_root),
69             def_index: CRATE_DEF_INDEX,
70             parent_legacy_scope: Cell::new(LegacyScope::Empty),
71             output_legacy_scope: Cell::new(LegacyScope::Empty),
72         }
73     }
74 }
75
76 /// Binding produced by a `macro_rules` item.
77 /// Not modularized, can shadow previous legacy bindings, etc.
78 pub struct LegacyBinding<'a> {
79     binding: &'a NameBinding<'a>,
80     /// Legacy scope into which the `macro_rules` item was planted.
81     parent_legacy_scope: LegacyScope<'a>,
82     ident: Ident,
83 }
84
85 /// Scope introduced by a `macro_rules!` macro.
86 /// Starts at the macro's definition and ends at the end of the macro's parent module
87 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
88 /// Some macro invocations need to introduce legacy scopes too because they
89 /// potentially can expand into macro definitions.
90 #[derive(Copy, Clone)]
91 pub enum LegacyScope<'a> {
92     /// Created when invocation data is allocated in the arena,
93     /// must be replaced with a proper scope later.
94     Uninitialized,
95     /// Empty "root" scope at the crate start containing no names.
96     Empty,
97     /// Scope introduced by a `macro_rules!` macro definition.
98     Binding(&'a LegacyBinding<'a>),
99     /// Scope introduced by a macro invocation that can potentially
100     /// create a `macro_rules!` macro definition.
101     Invocation(&'a InvocationData<'a>),
102 }
103
104 /// Everything you need to resolve a macro path.
105 #[derive(Clone)]
106 pub struct ParentScope<'a> {
107     crate module: Module<'a>,
108     crate expansion: Mark,
109     crate legacy: LegacyScope<'a>,
110     crate derives: Vec<ast::Path>,
111 }
112
113 pub struct ProcMacError {
114     crate_name: Symbol,
115     name: Symbol,
116     module: ast::NodeId,
117     use_span: Span,
118     warn_msg: &'static str,
119 }
120
121 // For compatibility bang macros are skipped when resolving potentially built-in attributes.
122 fn macro_kind_mismatch(name: Name, requirement: Option<MacroKind>, candidate: Option<MacroKind>)
123                        -> bool {
124     requirement == Some(MacroKind::Attr) && candidate == Some(MacroKind::Bang) &&
125     (name == "test" || name == "bench" || is_builtin_attr_name(name))
126 }
127
128 impl<'a, 'crateloader: 'a> base::Resolver for Resolver<'a, 'crateloader> {
129     fn next_node_id(&mut self) -> ast::NodeId {
130         self.session.next_node_id()
131     }
132
133     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
134         let mark = Mark::fresh(Mark::root());
135         let module = self.module_map[&self.definitions.local_def_id(id)];
136         self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
137             module: Cell::new(module),
138             def_index: module.def_id().unwrap().index,
139             parent_legacy_scope: Cell::new(LegacyScope::Empty),
140             output_legacy_scope: Cell::new(LegacyScope::Empty),
141         }));
142         mark
143     }
144
145     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
146         struct EliminateCrateVar<'b, 'a: 'b, 'crateloader: 'a>(
147             &'b mut Resolver<'a, 'crateloader>, Span
148         );
149
150         impl<'a, 'b, 'crateloader> Folder for EliminateCrateVar<'a, 'b, 'crateloader> {
151             fn fold_path(&mut self, path: ast::Path) -> ast::Path {
152                 match self.fold_qpath(None, path) {
153                     (None, path) => path,
154                     _ => unreachable!(),
155                 }
156             }
157
158             fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
159                           -> (Option<ast::QSelf>, ast::Path) {
160                 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
161                     ast::QSelf {
162                         ty: self.fold_ty(ty),
163                         path_span: self.new_span(path_span),
164                         position,
165                     }
166                 });
167
168                 if path.segments[0].ident.name == keywords::DollarCrate.name() {
169                     let module = self.0.resolve_crate_root(path.segments[0].ident);
170                     path.segments[0].ident.name = keywords::CrateRoot.name();
171                     if !module.is_local() {
172                         let span = path.segments[0].ident.span;
173                         path.segments.insert(1, match module.kind {
174                             ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
175                                 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
176                             ),
177                             _ => unreachable!(),
178                         });
179                         if let Some(qself) = &mut qself {
180                             qself.position += 1;
181                         }
182                     }
183                 }
184                 (qself, path)
185             }
186
187             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
188                 fold::noop_fold_mac(mac, self)
189             }
190         }
191
192         EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
193     }
194
195     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
196         self.whitelisted_legacy_custom_derives.contains(&name)
197     }
198
199     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
200                                             derives: &[Mark]) {
201         let invocation = self.invocations[&mark];
202         self.collect_def_ids(mark, invocation, fragment);
203
204         self.current_module = invocation.module.get();
205         self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
206         self.current_module.unresolved_invocations.borrow_mut().extend(derives);
207         for &derive in derives {
208             self.invocations.insert(derive, invocation);
209         }
210         let mut visitor = BuildReducedGraphVisitor {
211             resolver: self,
212             current_legacy_scope: invocation.parent_legacy_scope.get(),
213             expansion: mark,
214         };
215         fragment.visit_with(&mut visitor);
216         invocation.output_legacy_scope.set(visitor.current_legacy_scope);
217     }
218
219     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
220         let def_id = DefId {
221             krate: BUILTIN_MACROS_CRATE,
222             index: DefIndex::from_array_index(self.macro_map.len(),
223                                               DefIndexAddressSpace::Low),
224         };
225         let kind = ext.kind();
226         self.macro_map.insert(def_id, ext);
227         let binding = self.arenas.alloc_name_binding(NameBinding {
228             kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
229             span: DUMMY_SP,
230             vis: ty::Visibility::Invisible,
231             expansion: Mark::root(),
232         });
233         if self.builtin_macros.insert(ident.name, binding).is_some() {
234             self.session.span_err(ident.span,
235                                   &format!("built-in macro `{}` was already defined", ident));
236         }
237     }
238
239     fn resolve_imports(&mut self) {
240         ImportResolver { resolver: self }.resolve_imports()
241     }
242
243     // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
244     fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>, allow_derive: bool)
245                               -> Option<ast::Attribute> {
246         for i in 0..attrs.len() {
247             let name = attrs[i].name();
248
249             if self.session.plugin_attributes.borrow().iter()
250                     .any(|&(ref attr_nm, _)| name == &**attr_nm) {
251                 attr::mark_known(&attrs[i]);
252             }
253
254             match self.builtin_macros.get(&name).cloned() {
255                 Some(binding) => match *binding.get_macro(self) {
256                     MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
257                         return Some(attrs.remove(i))
258                     }
259                     _ => {}
260                 },
261                 None => {}
262             }
263         }
264
265         if !allow_derive { return None }
266
267         // Check for legacy derives
268         for i in 0..attrs.len() {
269             let name = attrs[i].name();
270
271             if name == "derive" {
272                 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
273                     parser.parse_path_allowing_meta(PathStyle::Mod)
274                 });
275
276                 let mut traits = match result {
277                     Ok(traits) => traits,
278                     Err(mut e) => {
279                         e.cancel();
280                         continue
281                     }
282                 };
283
284                 for j in 0..traits.len() {
285                     if traits[j].segments.len() > 1 {
286                         continue
287                     }
288                     let trait_name = traits[j].segments[0].ident.name;
289                     let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
290                     if !self.builtin_macros.contains_key(&legacy_name) {
291                         continue
292                     }
293                     let span = traits.remove(j).span;
294                     self.gate_legacy_custom_derive(legacy_name, span);
295                     if traits.is_empty() {
296                         attrs.remove(i);
297                     } else {
298                         let mut tokens = Vec::new();
299                         for (j, path) in traits.iter().enumerate() {
300                             if j > 0 {
301                                 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
302                             }
303                             for (k, segment) in path.segments.iter().enumerate() {
304                                 if k > 0 {
305                                     tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
306                                 }
307                                 let tok = Token::from_ast_ident(segment.ident);
308                                 tokens.push(TokenTree::Token(path.span, tok).into());
309                             }
310                         }
311                         let delim_span = DelimSpan::from_single(attrs[i].span);
312                         attrs[i].tokens = TokenTree::Delimited(delim_span, Delimited {
313                             delim: token::Paren,
314                             tts: TokenStream::concat(tokens).into(),
315                         }).into();
316                     }
317                     return Some(ast::Attribute {
318                         path: ast::Path::from_ident(Ident::new(legacy_name, span)),
319                         tokens: TokenStream::empty(),
320                         id: attr::mk_attr_id(),
321                         style: ast::AttrStyle::Outer,
322                         is_sugared_doc: false,
323                         span,
324                     });
325                 }
326             }
327         }
328
329         None
330     }
331
332     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
333                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
334         let (path, kind, derives_in_scope) = match invoc.kind {
335             InvocationKind::Attr { attr: None, .. } =>
336                 return Ok(None),
337             InvocationKind::Attr { attr: Some(ref attr), ref traits, .. } =>
338                 (&attr.path, MacroKind::Attr, traits.clone()),
339             InvocationKind::Bang { ref mac, .. } =>
340                 (&mac.node.path, MacroKind::Bang, Vec::new()),
341             InvocationKind::Derive { ref path, .. } =>
342                 (path, MacroKind::Derive, Vec::new()),
343         };
344
345         let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
346         let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, force)?;
347
348         if let Def::Macro(def_id, _) = def {
349             self.macro_defs.insert(invoc.expansion_data.mark, def_id);
350             let normal_module_def_id =
351                 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
352             self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
353                                                             normal_module_def_id);
354             invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
355             invoc.expansion_data.mark.set_is_builtin(def_id.krate == BUILTIN_MACROS_CRATE);
356         }
357
358         Ok(Some(ext))
359     }
360
361     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
362                           derives_in_scope: Vec<ast::Path>, force: bool)
363                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
364         let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
365         Ok(self.resolve_macro_to_def(path, kind, &parent_scope, force)?.1)
366     }
367
368     fn check_unused_macros(&self) {
369         for did in self.unused_macros.iter() {
370             let id_span = match *self.macro_map[did] {
371                 SyntaxExtension::NormalTT { def_info, .. } |
372                 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
373                 _ => None,
374             };
375             if let Some((id, span)) = id_span {
376                 let lint = lint::builtin::UNUSED_MACROS;
377                 let msg = "unused macro definition";
378                 self.session.buffer_lint(lint, id, span, msg);
379             } else {
380                 bug!("attempted to create unused macro error, but span not available");
381             }
382         }
383     }
384 }
385
386 impl<'a, 'cl> Resolver<'a, 'cl> {
387     pub fn dummy_parent_scope(&mut self) -> ParentScope<'a> {
388         self.invoc_parent_scope(Mark::root(), Vec::new())
389     }
390
391     fn invoc_parent_scope(&mut self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
392         let invoc = self.invocations[&invoc_id];
393         ParentScope {
394             module: invoc.module.get().nearest_item_scope(),
395             expansion: invoc_id.parent(),
396             legacy: invoc.parent_legacy_scope.get(),
397             derives,
398         }
399     }
400
401     fn resolve_macro_to_def(
402         &mut self,
403         path: &ast::Path,
404         kind: MacroKind,
405         parent_scope: &ParentScope<'a>,
406         force: bool,
407     ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
408         let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, force);
409
410         // Report errors and enforce feature gates for the resolved macro.
411         if def != Err(Determinacy::Undetermined) {
412             // Do not report duplicated errors on every undetermined resolution.
413             for segment in &path.segments {
414                 if let Some(args) = &segment.args {
415                     self.session.span_err(args.span(), "generic arguments in macro path");
416                 }
417             }
418         }
419
420         let def = def?;
421
422         match def {
423             Def::Macro(def_id, macro_kind) => {
424                 self.unused_macros.remove(&def_id);
425                 if macro_kind == MacroKind::ProcMacroStub {
426                     let msg = "can't use a procedural macro from the same crate that defines it";
427                     self.session.span_err(path.span, msg);
428                     return Err(Determinacy::Determined);
429                 }
430             }
431             Def::NonMacroAttr(attr_kind) => {
432                 if kind == MacroKind::Attr {
433                     let features = self.session.features_untracked();
434                     if attr_kind == NonMacroAttrKind::Custom {
435                         assert!(path.segments.len() == 1);
436                         let name = path.segments[0].ident.name.as_str();
437                         if name.starts_with("rustc_") {
438                             if !features.rustc_attrs {
439                                 let msg = "unless otherwise specified, attributes with the prefix \
440                                            `rustc_` are reserved for internal compiler diagnostics";
441                                 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
442                                             GateIssue::Language, &msg).emit();
443                             }
444                         } else if name.starts_with("derive_") {
445                             if !features.custom_derive {
446                                 feature_err(&self.session.parse_sess, "custom_derive", path.span,
447                                             GateIssue::Language, EXPLAIN_DERIVE_UNDERSCORE).emit();
448                             }
449                         } else if !features.custom_attribute {
450                             let msg = format!("The attribute `{}` is currently unknown to the \
451                                                compiler and may have meaning added to it in the \
452                                                future", path);
453                             feature_err(&self.session.parse_sess, "custom_attribute", path.span,
454                                         GateIssue::Language, &msg).emit();
455                         }
456                     }
457                 } else {
458                     // Not only attributes, but anything in macro namespace can result in
459                     // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
460                     // an error for those cases.
461                     let msg = format!("expected a macro, found {}", def.kind_name());
462                     self.session.span_err(path.span, &msg);
463                     return Err(Determinacy::Determined);
464                 }
465             }
466             _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
467         }
468
469         Ok((def, self.get_macro(def)))
470     }
471
472     pub fn resolve_macro_to_def_inner(
473         &mut self,
474         path: &ast::Path,
475         kind: MacroKind,
476         parent_scope: &ParentScope<'a>,
477         force: bool,
478     ) -> Result<Def, Determinacy> {
479         let ast::Path { ref segments, span } = *path;
480         let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect();
481
482         // Possibly apply the macro helper hack
483         if kind == MacroKind::Bang && path.len() == 1 &&
484            path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) {
485             let root = Ident::new(keywords::DollarCrate.name(), path[0].span);
486             path.insert(0, root);
487         }
488
489         if path.len() > 1 {
490             let def = match self.resolve_path_with_parent_scope(None, &path, Some(MacroNS),
491                                                                 parent_scope, false, span,
492                                                                 CrateLint::No) {
493                 PathResult::NonModule(path_res) => match path_res.base_def() {
494                     Def::Err => Err(Determinacy::Determined),
495                     def @ _ => {
496                         if path_res.unresolved_segments() > 0 {
497                             self.found_unresolved_macro = true;
498                             self.session.span_err(span, "fail to resolve non-ident macro path");
499                             Err(Determinacy::Determined)
500                         } else {
501                             Ok(def)
502                         }
503                     }
504                 },
505                 PathResult::Module(..) => unreachable!(),
506                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
507                 _ => {
508                     self.found_unresolved_macro = true;
509                     Err(Determinacy::Determined)
510                 },
511             };
512             parent_scope.module.macro_resolutions.borrow_mut()
513                 .push((path.into_boxed_slice(), span));
514             return def;
515         }
516
517         let result = if let Some(legacy_binding) = self.resolve_legacy_scope(path[0], Some(kind),
518                                                                              parent_scope, false) {
519             Ok(legacy_binding.def())
520         } else {
521             match self.resolve_lexical_macro_path_segment(path[0], MacroNS, Some(kind),
522                                                           parent_scope, false, force, span) {
523                 Ok((binding, _)) => Ok(binding.def_ignoring_ambiguity()),
524                 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
525                 Err(Determinacy::Determined) => {
526                     self.found_unresolved_macro = true;
527                     Err(Determinacy::Determined)
528                 }
529             }
530         };
531
532         parent_scope.module.legacy_macro_resolutions.borrow_mut()
533             .push((path[0], kind, parent_scope.clone(), result.ok()));
534
535         result
536     }
537
538     // Resolve the initial segment of a non-global macro path
539     // (e.g. `foo` in `foo::bar!(); or `foo!();`).
540     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
541     // expansion and import resolution (perhaps they can be merged in the future).
542     crate fn resolve_lexical_macro_path_segment(
543         &mut self,
544         mut ident: Ident,
545         ns: Namespace,
546         kind: Option<MacroKind>,
547         parent_scope: &ParentScope<'a>,
548         record_used: bool,
549         force: bool,
550         path_span: Span,
551     ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
552         // General principles:
553         // 1. Not controlled (user-defined) names should have higher priority than controlled names
554         //    built into the language or standard library. This way we can add new names into the
555         //    language or standard library without breaking user code.
556         // 2. "Closed set" below means new names can appear after the current resolution attempt.
557         // Places to search (in order of decreasing priority):
558         // (Type NS)
559         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
560         //    (open set, not controlled).
561         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
562         //    (open, not controlled).
563         // 3. Extern prelude (closed, not controlled).
564         // 4. Tool modules (closed, controlled right now, but not in the future).
565         // 5. Standard library prelude (de-facto closed, controlled).
566         // 6. Language prelude (closed, controlled).
567         // (Macro NS)
568         // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
569         //    (open, not controlled).
570         // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
571         // 2a. User-defined prelude from macro-use
572         //    (open, the open part is from macro expansions, not controlled).
573         // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
574         // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
575         // 4. Language prelude: builtin attributes (closed, controlled).
576         // N (unordered). Derive helpers (open, not controlled). All ambiguities with other names
577         //    are currently reported as errors. They should be higher in priority than preludes
578         //    and maybe even names in modules according to the "general principles" above. They
579         //    also should be subject to restricted shadowing because are effectively produced by
580         //    derives (you need to resolve the derive first to add helpers into scope), but they
581         //    should be available before the derive is expanded for compatibility.
582         //    It's mess in general, so we are being conservative for now.
583
584         assert!(ns == TypeNS  || ns == MacroNS);
585         assert!(force || !record_used); // `record_used` implies `force`
586         ident = ident.modern();
587
588         // This is *the* result, resolution from the scope closest to the resolved identifier.
589         // However, sometimes this result is "weak" because it comes from a glob import or
590         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
591         // mod m { ... } // solution in outer scope
592         // {
593         //     use prefix::*; // imports another `m` - innermost solution
594         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
595         //     m::mac!();
596         // }
597         // So we have to save the innermost solution and continue searching in outer scopes
598         // to detect potential ambiguities.
599         let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
600
601         enum WhereToResolve<'a> {
602             Module(Module<'a>),
603             MacroUsePrelude,
604             BuiltinMacros,
605             BuiltinAttrs,
606             DeriveHelpers,
607             ExternPrelude,
608             ToolPrelude,
609             StdLibPrelude,
610             BuiltinTypes,
611         }
612
613         // Go through all the scopes and try to resolve the name.
614         let mut where_to_resolve = WhereToResolve::Module(parent_scope.module);
615         let mut use_prelude = !parent_scope.module.no_implicit_prelude;
616         loop {
617             let result = match where_to_resolve {
618                 WhereToResolve::Module(module) => {
619                     let orig_current_module = mem::replace(&mut self.current_module, module);
620                     let binding = self.resolve_ident_in_module_unadjusted(
621                         ModuleOrUniformRoot::Module(module),
622                         ident,
623                         ns,
624                         true,
625                         record_used,
626                         path_span,
627                     );
628                     self.current_module = orig_current_module;
629                     binding.map(|binding| (binding, FromPrelude(false)))
630                 }
631                 WhereToResolve::MacroUsePrelude => {
632                     match self.macro_use_prelude.get(&ident.name).cloned() {
633                         Some(binding) => Ok((binding, FromPrelude(true))),
634                         None => Err(Determinacy::Determined),
635                     }
636                 }
637                 WhereToResolve::BuiltinMacros => {
638                     match self.builtin_macros.get(&ident.name).cloned() {
639                         Some(binding) => Ok((binding, FromPrelude(true))),
640                         None => Err(Determinacy::Determined),
641                     }
642                 }
643                 WhereToResolve::BuiltinAttrs => {
644                     // FIXME: Only built-in attributes are not considered as candidates for
645                     // non-attributes to fight off regressions on stable channel (#53205).
646                     // We need to come up with some more principled approach instead.
647                     if kind == Some(MacroKind::Attr) && is_builtin_attr_name(ident.name) {
648                         let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
649                                        ty::Visibility::Public, ident.span, Mark::root())
650                                        .to_name_binding(self.arenas);
651                         Ok((binding, FromPrelude(true)))
652                     } else {
653                         Err(Determinacy::Determined)
654                     }
655                 }
656                 WhereToResolve::DeriveHelpers => {
657                     let mut result = Err(Determinacy::Determined);
658                     for derive in &parent_scope.derives {
659                         let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
660                         if let Ok((_, ext)) = self.resolve_macro_to_def(derive, MacroKind::Derive,
661                                                                         &parent_scope, force) {
662                             if let SyntaxExtension::ProcMacroDerive(_, helper_attrs, _) = &*ext {
663                                 if helper_attrs.contains(&ident.name) {
664                                     let binding =
665                                         (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
666                                         ty::Visibility::Public, derive.span, Mark::root())
667                                         .to_name_binding(self.arenas);
668                                     result = Ok((binding, FromPrelude(false)));
669                                     break;
670                                 }
671                             }
672                         }
673                     }
674                     result
675                 }
676                 WhereToResolve::ExternPrelude => {
677                     if use_prelude && self.extern_prelude.contains(&ident.name) {
678                         if !self.session.features_untracked().extern_prelude &&
679                            !self.ignore_extern_prelude_feature {
680                             feature_err(&self.session.parse_sess, "extern_prelude",
681                                         ident.span, GateIssue::Language,
682                                         "access to extern crates through prelude is experimental")
683                                         .emit();
684                         }
685
686                         let crate_id =
687                             self.crate_loader.process_path_extern(ident.name, ident.span);
688                         let crate_root =
689                             self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
690                         self.populate_module_if_necessary(crate_root);
691
692                         let binding = (crate_root, ty::Visibility::Public,
693                                        ident.span, Mark::root()).to_name_binding(self.arenas);
694                         Ok((binding, FromPrelude(true)))
695                     } else {
696                         Err(Determinacy::Determined)
697                     }
698                 }
699                 WhereToResolve::ToolPrelude => {
700                     if use_prelude && is_known_tool(ident.name) {
701                         let binding = (Def::ToolMod, ty::Visibility::Public,
702                                        ident.span, Mark::root()).to_name_binding(self.arenas);
703                         Ok((binding, FromPrelude(true)))
704                     } else {
705                         Err(Determinacy::Determined)
706                     }
707                 }
708                 WhereToResolve::StdLibPrelude => {
709                     let mut result = Err(Determinacy::Determined);
710                     if use_prelude {
711                         if let Some(prelude) = self.prelude {
712                             if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
713                                 ModuleOrUniformRoot::Module(prelude),
714                                 ident,
715                                 ns,
716                                 false,
717                                 false,
718                                 path_span,
719                             ) {
720                                 result = Ok((binding, FromPrelude(true)));
721                             }
722                         }
723                     }
724                     result
725                 }
726                 WhereToResolve::BuiltinTypes => {
727                     if let Some(prim_ty) =
728                             self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
729                         let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
730                                        ident.span, Mark::root()).to_name_binding(self.arenas);
731                         Ok((binding, FromPrelude(true)))
732                     } else {
733                         Err(Determinacy::Determined)
734                     }
735                 }
736             };
737
738             macro_rules! continue_search { () => {
739                 where_to_resolve = match where_to_resolve {
740                     WhereToResolve::Module(module) => {
741                         match self.hygienic_lexical_parent(module, &mut ident.span) {
742                             Some(parent_module) => WhereToResolve::Module(parent_module),
743                             None => {
744                                 use_prelude = !module.no_implicit_prelude;
745                                 if ns == MacroNS {
746                                     WhereToResolve::MacroUsePrelude
747                                 } else {
748                                     WhereToResolve::ExternPrelude
749                                 }
750                             }
751                         }
752                     }
753                     WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
754                     WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
755                     WhereToResolve::BuiltinAttrs => WhereToResolve::DeriveHelpers,
756                     WhereToResolve::DeriveHelpers => break, // nowhere else to search
757                     WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
758                     WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
759                     WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
760                     WhereToResolve::BuiltinTypes => break, // nowhere else to search
761                 };
762
763                 continue;
764             }}
765
766             match result {
767                 Ok(result) => {
768                     if macro_kind_mismatch(ident.name, kind, result.0.macro_kind()) {
769                         continue_search!();
770                     }
771
772                     if !record_used {
773                         return Ok(result);
774                     }
775
776                     if let Some(innermost_result) = innermost_result {
777                         // Found another solution, if the first one was "weak", report an error.
778                         let (def, innermost_def) = (result.0.def(), innermost_result.0.def());
779                         if def != innermost_def &&
780                            (innermost_result.0.is_glob_import() ||
781                             innermost_result.0.may_appear_after(parent_scope.expansion, result.0) ||
782                             innermost_def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper) ||
783                             def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)) {
784                             self.ambiguity_errors.push(AmbiguityError {
785                                 ident,
786                                 b1: innermost_result.0,
787                                 b2: result.0,
788                             });
789                             return Ok(innermost_result);
790                         }
791                     } else {
792                         // Found the first solution.
793                         innermost_result = Some(result);
794                     }
795
796                     continue_search!();
797                 },
798                 Err(Determinacy::Determined) => {
799                     continue_search!();
800                 }
801                 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
802             }
803         }
804
805         // The first found solution was the only one, return it.
806         if let Some(innermost_result) = innermost_result {
807             return Ok(innermost_result);
808         }
809
810         let determinacy = Determinacy::determined(force);
811         if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
812             // For single-segment attributes interpret determinate "no resolution" as a custom
813             // attribute. (Lexical resolution implies the first segment and attr kind should imply
814             // the last segment, so we are certainly working with a single-segment attribute here.)
815             assert!(ns == MacroNS);
816             let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
817                            ty::Visibility::Public, ident.span, Mark::root())
818                            .to_name_binding(self.arenas);
819             Ok((binding, FromPrelude(true)))
820         } else {
821             Err(determinacy)
822         }
823     }
824
825     fn resolve_legacy_scope(
826         &mut self,
827         ident: Ident,
828         kind: Option<MacroKind>,
829         parent_scope: &ParentScope<'a>,
830         record_used: bool,
831     ) -> Option<&'a NameBinding<'a>> {
832         if macro_kind_mismatch(ident.name, kind, Some(MacroKind::Bang)) {
833             return None;
834         }
835
836         let ident = ident.modern();
837
838         // This is *the* result, resolution from the scope closest to the resolved identifier.
839         // However, sometimes this result is "weak" because it comes from a macro expansion,
840         // and in this case it cannot shadow names from outer scopes, e.g.
841         // macro_rules! m { ... } // solution in outer scope
842         // {
843         //     define_m!(); // generates another `macro_rules! m` - innermost solution
844         //                  // weak, cannot shadow the outer `m`, need to report ambiguity error
845         //     m!();
846         // }
847         // So we have to save the innermost solution and continue searching in outer scopes
848         // to detect potential ambiguities.
849         let mut innermost_result: Option<&NameBinding> = None;
850
851         // Go through all the scopes and try to resolve the name.
852         let mut where_to_resolve = parent_scope.legacy;
853         loop {
854             let result = match where_to_resolve {
855                 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
856                     Some(legacy_binding.binding),
857                 _ => None,
858             };
859
860             macro_rules! continue_search { () => {
861                 where_to_resolve = match where_to_resolve {
862                     LegacyScope::Empty => break, // nowhere else to search
863                     LegacyScope::Binding(binding) => binding.parent_legacy_scope,
864                     LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
865                     LegacyScope::Uninitialized => unreachable!(),
866                 };
867
868                 continue;
869             }}
870
871             match result {
872                 Some(result) => {
873                     if !record_used {
874                         return Some(result);
875                     }
876
877                     if let Some(innermost_result) = innermost_result {
878                         // Found another solution, if the first one was "weak", report an error.
879                         if result.def() != innermost_result.def() &&
880                            innermost_result.may_appear_after(parent_scope.expansion, result) {
881                             self.ambiguity_errors.push(AmbiguityError {
882                                 ident,
883                                 b1: innermost_result,
884                                 b2: result,
885                             });
886                             return Some(innermost_result);
887                         }
888                     } else {
889                         // Found the first solution.
890                         innermost_result = Some(result);
891                     }
892
893                     continue_search!();
894                 }
895                 None => {
896                     continue_search!();
897                 }
898             }
899         }
900
901         // The first found solution was the only one (or there was no solution at all), return it.
902         innermost_result
903     }
904
905     pub fn finalize_current_module_macro_resolutions(&mut self) {
906         let module = self.current_module;
907         for &(ref path, span) in module.macro_resolutions.borrow().iter() {
908             match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
909                 PathResult::NonModule(_) => {},
910                 PathResult::Failed(span, msg, _) => {
911                     resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
912                 }
913                 _ => unreachable!(),
914             }
915         }
916
917         let legacy_macro_resolutions =
918             mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
919         for (ident, kind, parent_scope, def) in legacy_macro_resolutions {
920             let span = ident.span;
921             let legacy_resolution = self.resolve_legacy_scope(
922                 ident, Some(kind), &parent_scope, true
923             );
924             let resolution = self.resolve_lexical_macro_path_segment(
925                 ident, MacroNS, Some(kind), &parent_scope, true, true, span
926             );
927
928             let check_consistency = |this: &Self, new_def: Def| {
929                 if let Some(def) = def {
930                     if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
931                         // Make sure compilation does not succeed if preferred macro resolution
932                         // has changed after the macro had been expanded. In theory all such
933                         // situations should be reported as ambiguity errors, so this is span-bug.
934                         span_bug!(span, "inconsistent resolution for a macro");
935                     }
936                 } else {
937                     // It's possible that the macro was unresolved (indeterminate) and silently
938                     // expanded into a dummy fragment for recovery during expansion.
939                     // Now, post-expansion, the resolution may succeed, but we can't change the
940                     // past and need to report an error.
941                     let msg =
942                         format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
943                     let msg_note = "import resolution is stuck, try simplifying macro imports";
944                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
945                 }
946             };
947
948             match (legacy_resolution, resolution) {
949                 (None, Err(_)) => {
950                     assert!(def.is_none());
951                     let bang = if kind == MacroKind::Bang { "!" } else { "" };
952                     let msg =
953                         format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
954                     let mut err = self.session.struct_span_err(span, &msg);
955                     self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
956                     err.emit();
957                 },
958                 (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
959                         if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
960                            (!from_prelude ||
961                             legacy_binding.may_appear_after(parent_scope.expansion, binding)) => {
962                     self.report_ambiguity_error(ident, legacy_binding, binding);
963                 },
964                 // OK, non-macro-expanded legacy wins over prelude even if defs are different
965                 // Also, legacy and modern can co-exist if their defs are same
966                 (Some(legacy_binding), Ok(_)) |
967                 // OK, unambiguous resolution
968                 (Some(legacy_binding), Err(_)) => {
969                     check_consistency(self, legacy_binding.def());
970                 }
971                 // OK, unambiguous resolution
972                 (None, Ok((binding, FromPrelude(from_prelude)))) => {
973                     check_consistency(self, binding.def_ignoring_ambiguity());
974                     if from_prelude {
975                         self.record_use(ident, MacroNS, binding);
976                         self.err_if_macro_use_proc_macro(ident.name, span, binding);
977                     }
978                 }
979             };
980         }
981
982         let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
983         for (ident, parent_scope) in builtin_attrs {
984             let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
985                 ident, Some(MacroKind::Attr), &parent_scope, true
986             );
987             let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
988                 ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
989             ).map(|(binding, _)| binding).ok();
990
991             if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
992                 if binding.def_ignoring_ambiguity() !=
993                         Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
994                     let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
995                                            ty::Visibility::Public, ident.span, Mark::root())
996                                            .to_name_binding(self.arenas);
997                     self.report_ambiguity_error(ident, binding, builtin_binding);
998                 }
999             }
1000         }
1001     }
1002
1003     fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1004                           err: &mut DiagnosticBuilder<'a>, span: Span) {
1005         // First check if this is a locally-defined bang macro.
1006         let suggestion = if let MacroKind::Bang = kind {
1007             find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1008         } else {
1009             None
1010         // Then check global macros.
1011         }.or_else(|| {
1012             let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1013                                                   .filter_map(|(name, binding)| {
1014                 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1015             });
1016             find_best_match_for_name(names, name, None)
1017         // Then check modules.
1018         }).or_else(|| {
1019             let is_macro = |def| {
1020                 if let Def::Macro(_, def_kind) = def {
1021                     def_kind == kind
1022                 } else {
1023                     false
1024                 }
1025             };
1026             let ident = Ident::new(Symbol::intern(name), span);
1027             self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
1028         });
1029
1030         if let Some(suggestion) = suggestion {
1031             if suggestion != name {
1032                 if let MacroKind::Bang = kind {
1033                     err.span_suggestion_with_applicability(
1034                         span,
1035                         "you could try the macro",
1036                         suggestion.to_string(),
1037                         Applicability::MaybeIncorrect
1038                     );
1039                 } else {
1040                     err.span_suggestion_with_applicability(
1041                         span,
1042                         "try",
1043                         suggestion.to_string(),
1044                         Applicability::MaybeIncorrect
1045                     );
1046                 }
1047             } else {
1048                 err.help("have you added the `#[macro_use]` on the module/import?");
1049             }
1050         }
1051     }
1052
1053     fn collect_def_ids(&mut self,
1054                        mark: Mark,
1055                        invocation: &'a InvocationData<'a>,
1056                        fragment: &AstFragment) {
1057         let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1058         let InvocationData { def_index, .. } = *invocation;
1059
1060         let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1061             invocations.entry(invoc.mark).or_insert_with(|| {
1062                 arenas.alloc_invocation_data(InvocationData {
1063                     def_index: invoc.def_index,
1064                     module: Cell::new(graph_root),
1065                     parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1066                     output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1067                 })
1068             });
1069         };
1070
1071         let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1072         def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1073         def_collector.with_parent(def_index, |def_collector| {
1074             fragment.visit_with(def_collector)
1075         });
1076     }
1077
1078     pub fn define_macro(&mut self,
1079                         item: &ast::Item,
1080                         expansion: Mark,
1081                         current_legacy_scope: &mut LegacyScope<'a>) {
1082         self.local_macro_def_scopes.insert(item.id, self.current_module);
1083         let ident = item.ident;
1084         if ident.name == "macro_rules" {
1085             self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1086         }
1087
1088         let def_id = self.definitions.local_def_id(item.id);
1089         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1090                                                &self.session.features_untracked(),
1091                                                item, hygiene::default_edition()));
1092         self.macro_map.insert(def_id, ext);
1093
1094         let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1095         if def.legacy {
1096             let ident = ident.modern();
1097             self.macro_names.insert(ident);
1098             let def = Def::Macro(def_id, MacroKind::Bang);
1099             let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1100             let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1101             let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1102                 parent_legacy_scope: *current_legacy_scope, binding, ident
1103             });
1104             *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1105             self.all_macros.insert(ident.name, def);
1106             if attr::contains_name(&item.attrs, "macro_export") {
1107                 let module = self.graph_root;
1108                 let vis = ty::Visibility::Public;
1109                 self.define(module, ident, MacroNS,
1110                             (def, vis, item.span, expansion, IsMacroExport));
1111             } else {
1112                 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1113                     self.check_reserved_macro_name(ident, MacroNS);
1114                 }
1115                 self.unused_macros.insert(def_id);
1116             }
1117         } else {
1118             let module = self.current_module;
1119             let def = Def::Macro(def_id, MacroKind::Bang);
1120             let vis = self.resolve_visibility(&item.vis);
1121             if vis != ty::Visibility::Public {
1122                 self.unused_macros.insert(def_id);
1123             }
1124             self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1125         }
1126     }
1127
1128     /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1129     fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1130                                    binding: &NameBinding<'a>) {
1131         let krate = match binding.def() {
1132             Def::NonMacroAttr(..) | Def::Err => return,
1133             Def::Macro(def_id, _) => def_id.krate,
1134             _ => unreachable!(),
1135         };
1136
1137         // Plugin-based syntax extensions are exempt from this check
1138         if krate == BUILTIN_MACROS_CRATE { return; }
1139
1140         let ext = binding.get_macro(self);
1141
1142         match *ext {
1143             // If `ext` is a procedural macro, check if we've already warned about it
1144             SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1145                 if !self.warned_proc_macros.insert(name) { return; },
1146             _ => return,
1147         }
1148
1149         let warn_msg = match *ext {
1150             SyntaxExtension::AttrProcMacro(..) =>
1151                 "attribute procedural macros cannot be imported with `#[macro_use]`",
1152             SyntaxExtension::ProcMacro { .. } =>
1153                 "procedural macros cannot be imported with `#[macro_use]`",
1154             _ => return,
1155         };
1156
1157         let def_id = self.current_module.normal_ancestor_id;
1158         let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1159
1160         self.proc_mac_errors.push(ProcMacError {
1161             crate_name: self.cstore.crate_name_untracked(krate),
1162             name,
1163             module: node_id,
1164             use_span,
1165             warn_msg,
1166         });
1167     }
1168
1169     pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1170         for err in self.proc_mac_errors.drain(..) {
1171             let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1172
1173             if let Some(span) = span {
1174                 let found_use = if found_use { "" } else { "\n" };
1175                 self.session.struct_span_err(err.use_span, err.warn_msg)
1176                     .span_suggestion_with_applicability(
1177                         span,
1178                         "instead, import the procedural macro like any other item",
1179                         format!("use {}::{};{}", err.crate_name, err.name, found_use),
1180                         Applicability::MachineApplicable
1181                     ).emit();
1182             } else {
1183                 self.session.struct_span_err(err.use_span, err.warn_msg)
1184                     .help(&format!("instead, import the procedural macro like any other item: \
1185                                     `use {}::{};`", err.crate_name, err.name))
1186                     .emit();
1187             }
1188         }
1189     }
1190
1191     fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1192         if !self.session.features_untracked().custom_derive {
1193             let sess = &self.session.parse_sess;
1194             let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1195             emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1196         } else if !self.is_whitelisted_legacy_custom_derive(name) {
1197             self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);
1198         }
1199     }
1200 }