]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
af3da94ced926cf679d3a3599790129fdd0b5596
[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         if let Ok(Def::NonMacroAttr(NonMacroAttrKind::Custom)) = result {} else {
536             return result;
537         }
538
539         // At this point we've found that the `attr` is determinately unresolved and thus can be
540         // interpreted as a custom attribute. Normally custom attributes are feature gated, but
541         // it may be a custom attribute whitelisted by a derive macro and they do not require
542         // a feature gate.
543         //
544         // So here we look through all of the derive annotations in scope and try to resolve them.
545         // If they themselves successfully resolve *and* one of the resolved derive macros
546         // whitelists this attribute's name, then this is a registered attribute and we can convert
547         // it from a "generic custom attrite" into a "known derive helper attribute".
548         assert!(kind == MacroKind::Attr);
549         enum ConvertToDeriveHelper { Yes, No, DontKnow }
550         let mut convert_to_derive_helper = ConvertToDeriveHelper::No;
551         for derive in &parent_scope.derives {
552             match self.resolve_macro_to_def(derive, MacroKind::Derive, parent_scope, force) {
553                 Ok((_, ext)) => if let SyntaxExtension::ProcMacroDerive(_, inert_attrs, _) = &*ext {
554                     if inert_attrs.contains(&path[0].name) {
555                         convert_to_derive_helper = ConvertToDeriveHelper::Yes;
556                         break
557                     }
558                 },
559                 Err(Determinacy::Undetermined) =>
560                     convert_to_derive_helper = ConvertToDeriveHelper::DontKnow,
561                 Err(Determinacy::Determined) => {}
562             }
563         }
564
565         match convert_to_derive_helper {
566             ConvertToDeriveHelper::Yes => Ok(Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)),
567             ConvertToDeriveHelper::No => result,
568             ConvertToDeriveHelper::DontKnow => Err(Determinacy::determined(force)),
569         }
570     }
571
572     // Resolve the initial segment of a non-global macro path
573     // (e.g. `foo` in `foo::bar!(); or `foo!();`).
574     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
575     // expansion and import resolution (perhaps they can be merged in the future).
576     crate fn resolve_lexical_macro_path_segment(
577         &mut self,
578         mut ident: Ident,
579         ns: Namespace,
580         kind: Option<MacroKind>,
581         parent_scope: &ParentScope<'a>,
582         record_used: bool,
583         force: bool,
584         path_span: Span,
585     ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
586         // General principles:
587         // 1. Not controlled (user-defined) names should have higher priority than controlled names
588         //    built into the language or standard library. This way we can add new names into the
589         //    language or standard library without breaking user code.
590         // 2. "Closed set" below means new names can appear after the current resolution attempt.
591         // Places to search (in order of decreasing priority):
592         // (Type NS)
593         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
594         //    (open set, not controlled).
595         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
596         //    (open, not controlled).
597         // 3. Extern prelude (closed, not controlled).
598         // 4. Tool modules (closed, controlled right now, but not in the future).
599         // 5. Standard library prelude (de-facto closed, controlled).
600         // 6. Language prelude (closed, controlled).
601         // (Macro NS)
602         // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
603         //    (open, not controlled).
604         // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
605         // 2a. User-defined prelude from macro-use
606         //    (open, the open part is from macro expansions, not controlled).
607         // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
608         // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
609         // 4. Language prelude: builtin attributes (closed, controlled).
610
611         assert!(ns == TypeNS  || ns == MacroNS);
612         assert!(force || !record_used); // `record_used` implies `force`
613         ident = ident.modern();
614
615         // This is *the* result, resolution from the scope closest to the resolved identifier.
616         // However, sometimes this result is "weak" because it comes from a glob import or
617         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
618         // mod m { ... } // solution in outer scope
619         // {
620         //     use prefix::*; // imports another `m` - innermost solution
621         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
622         //     m::mac!();
623         // }
624         // So we have to save the innermost solution and continue searching in outer scopes
625         // to detect potential ambiguities.
626         let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
627
628         enum WhereToResolve<'a> {
629             Module(Module<'a>),
630             MacroUsePrelude,
631             BuiltinMacros,
632             BuiltinAttrs,
633             ExternPrelude,
634             ToolPrelude,
635             StdLibPrelude,
636             BuiltinTypes,
637         }
638
639         // Go through all the scopes and try to resolve the name.
640         let mut where_to_resolve = WhereToResolve::Module(parent_scope.module);
641         let mut use_prelude = !parent_scope.module.no_implicit_prelude;
642         loop {
643             let result = match where_to_resolve {
644                 WhereToResolve::Module(module) => {
645                     let orig_current_module = mem::replace(&mut self.current_module, module);
646                     let binding = self.resolve_ident_in_module_unadjusted(
647                         ModuleOrUniformRoot::Module(module),
648                         ident,
649                         ns,
650                         true,
651                         record_used,
652                         path_span,
653                     );
654                     self.current_module = orig_current_module;
655                     binding.map(|binding| (binding, FromPrelude(false)))
656                 }
657                 WhereToResolve::MacroUsePrelude => {
658                     match self.macro_use_prelude.get(&ident.name).cloned() {
659                         Some(binding) => Ok((binding, FromPrelude(true))),
660                         None => Err(Determinacy::Determined),
661                     }
662                 }
663                 WhereToResolve::BuiltinMacros => {
664                     match self.builtin_macros.get(&ident.name).cloned() {
665                         Some(binding) => Ok((binding, FromPrelude(true))),
666                         None => Err(Determinacy::Determined),
667                     }
668                 }
669                 WhereToResolve::BuiltinAttrs => {
670                     // FIXME: Only built-in attributes are not considered as candidates for
671                     // non-attributes to fight off regressions on stable channel (#53205).
672                     // We need to come up with some more principled approach instead.
673                     if kind == Some(MacroKind::Attr) && is_builtin_attr_name(ident.name) {
674                         let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
675                                        ty::Visibility::Public, ident.span, Mark::root())
676                                        .to_name_binding(self.arenas);
677                         Ok((binding, FromPrelude(true)))
678                     } else {
679                         Err(Determinacy::Determined)
680                     }
681                 }
682                 WhereToResolve::ExternPrelude => {
683                     if use_prelude && self.extern_prelude.contains(&ident.name) {
684                         if !self.session.features_untracked().extern_prelude &&
685                            !self.ignore_extern_prelude_feature {
686                             feature_err(&self.session.parse_sess, "extern_prelude",
687                                         ident.span, GateIssue::Language,
688                                         "access to extern crates through prelude is experimental")
689                                         .emit();
690                         }
691
692                         let crate_id =
693                             self.crate_loader.process_path_extern(ident.name, ident.span);
694                         let crate_root =
695                             self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
696                         self.populate_module_if_necessary(crate_root);
697
698                         let binding = (crate_root, ty::Visibility::Public,
699                                        ident.span, Mark::root()).to_name_binding(self.arenas);
700                         Ok((binding, FromPrelude(true)))
701                     } else {
702                         Err(Determinacy::Determined)
703                     }
704                 }
705                 WhereToResolve::ToolPrelude => {
706                     if use_prelude && is_known_tool(ident.name) {
707                         let binding = (Def::ToolMod, ty::Visibility::Public,
708                                        ident.span, Mark::root()).to_name_binding(self.arenas);
709                         Ok((binding, FromPrelude(true)))
710                     } else {
711                         Err(Determinacy::Determined)
712                     }
713                 }
714                 WhereToResolve::StdLibPrelude => {
715                     let mut result = Err(Determinacy::Determined);
716                     if use_prelude {
717                         if let Some(prelude) = self.prelude {
718                             if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
719                                 ModuleOrUniformRoot::Module(prelude),
720                                 ident,
721                                 ns,
722                                 false,
723                                 false,
724                                 path_span,
725                             ) {
726                                 result = Ok((binding, FromPrelude(true)));
727                             }
728                         }
729                     }
730                     result
731                 }
732                 WhereToResolve::BuiltinTypes => {
733                     if let Some(prim_ty) =
734                             self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
735                         let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
736                                        ident.span, Mark::root()).to_name_binding(self.arenas);
737                         Ok((binding, FromPrelude(true)))
738                     } else {
739                         Err(Determinacy::Determined)
740                     }
741                 }
742             };
743
744             macro_rules! continue_search { () => {
745                 where_to_resolve = match where_to_resolve {
746                     WhereToResolve::Module(module) => {
747                         match self.hygienic_lexical_parent(module, &mut ident.span) {
748                             Some(parent_module) => WhereToResolve::Module(parent_module),
749                             None => {
750                                 use_prelude = !module.no_implicit_prelude;
751                                 if ns == MacroNS {
752                                     WhereToResolve::MacroUsePrelude
753                                 } else {
754                                     WhereToResolve::ExternPrelude
755                                 }
756                             }
757                         }
758                     }
759                     WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
760                     WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
761                     WhereToResolve::BuiltinAttrs => break, // nowhere else to search
762                     WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
763                     WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
764                     WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
765                     WhereToResolve::BuiltinTypes => break, // nowhere else to search
766                 };
767
768                 continue;
769             }}
770
771             match result {
772                 Ok(result) => {
773                     if macro_kind_mismatch(ident.name, kind, result.0.macro_kind()) {
774                         continue_search!();
775                     }
776
777                     if !record_used {
778                         return Ok(result);
779                     }
780
781                     if let Some(innermost_result) = innermost_result {
782                         // Found another solution, if the first one was "weak", report an error.
783                         if result.0.def() != innermost_result.0.def() &&
784                            (innermost_result.0.is_glob_import() ||
785                             innermost_result.0.may_appear_after(parent_scope.expansion, result.0)) {
786                             self.ambiguity_errors.push(AmbiguityError {
787                                 ident,
788                                 b1: innermost_result.0,
789                                 b2: result.0,
790                             });
791                             return Ok(innermost_result);
792                         }
793                     } else {
794                         // Found the first solution.
795                         innermost_result = Some(result);
796                     }
797
798                     continue_search!();
799                 },
800                 Err(Determinacy::Determined) => {
801                     continue_search!();
802                 }
803                 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
804             }
805         }
806
807         // The first found solution was the only one, return it.
808         if let Some(innermost_result) = innermost_result {
809             return Ok(innermost_result);
810         }
811
812         let determinacy = Determinacy::determined(force);
813         if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
814             // For single-segment attributes interpret determinate "no resolution" as a custom
815             // attribute. (Lexical resolution implies the first segment and attr kind should imply
816             // the last segment, so we are certainly working with a single-segment attribute here.)
817             assert!(ns == MacroNS);
818             let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
819                            ty::Visibility::Public, ident.span, Mark::root())
820                            .to_name_binding(self.arenas);
821             Ok((binding, FromPrelude(true)))
822         } else {
823             Err(determinacy)
824         }
825     }
826
827     fn resolve_legacy_scope(
828         &mut self,
829         ident: Ident,
830         kind: Option<MacroKind>,
831         parent_scope: &ParentScope<'a>,
832         record_used: bool,
833     ) -> Option<&'a NameBinding<'a>> {
834         if macro_kind_mismatch(ident.name, kind, Some(MacroKind::Bang)) {
835             return None;
836         }
837
838         let ident = ident.modern();
839
840         // This is *the* result, resolution from the scope closest to the resolved identifier.
841         // However, sometimes this result is "weak" because it comes from a macro expansion,
842         // and in this case it cannot shadow names from outer scopes, e.g.
843         // macro_rules! m { ... } // solution in outer scope
844         // {
845         //     define_m!(); // generates another `macro_rules! m` - innermost solution
846         //                  // weak, cannot shadow the outer `m`, need to report ambiguity error
847         //     m!();
848         // }
849         // So we have to save the innermost solution and continue searching in outer scopes
850         // to detect potential ambiguities.
851         let mut innermost_result: Option<&NameBinding> = None;
852
853         // Go through all the scopes and try to resolve the name.
854         let mut where_to_resolve = parent_scope.legacy;
855         loop {
856             let result = match where_to_resolve {
857                 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
858                     Some(legacy_binding.binding),
859                 _ => None,
860             };
861
862             macro_rules! continue_search { () => {
863                 where_to_resolve = match where_to_resolve {
864                     LegacyScope::Empty => break, // nowhere else to search
865                     LegacyScope::Binding(binding) => binding.parent_legacy_scope,
866                     LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
867                     LegacyScope::Uninitialized => unreachable!(),
868                 };
869
870                 continue;
871             }}
872
873             match result {
874                 Some(result) => {
875                     if !record_used {
876                         return Some(result);
877                     }
878
879                     if let Some(innermost_result) = innermost_result {
880                         // Found another solution, if the first one was "weak", report an error.
881                         if result.def() != innermost_result.def() &&
882                            innermost_result.may_appear_after(parent_scope.expansion, result) {
883                             self.ambiguity_errors.push(AmbiguityError {
884                                 ident,
885                                 b1: innermost_result,
886                                 b2: result,
887                             });
888                             return Some(innermost_result);
889                         }
890                     } else {
891                         // Found the first solution.
892                         innermost_result = Some(result);
893                     }
894
895                     continue_search!();
896                 }
897                 None => {
898                     continue_search!();
899                 }
900             }
901         }
902
903         // The first found solution was the only one (or there was no solution at all), return it.
904         innermost_result
905     }
906
907     pub fn finalize_current_module_macro_resolutions(&mut self) {
908         let module = self.current_module;
909         for &(ref path, span) in module.macro_resolutions.borrow().iter() {
910             match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
911                 PathResult::NonModule(_) => {},
912                 PathResult::Failed(span, msg, _) => {
913                     resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
914                 }
915                 _ => unreachable!(),
916             }
917         }
918
919         let legacy_macro_resolutions =
920             mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
921         for (ident, kind, parent_scope, def) in legacy_macro_resolutions {
922             let span = ident.span;
923             let legacy_resolution = self.resolve_legacy_scope(
924                 ident, Some(kind), &parent_scope, true
925             );
926             let resolution = self.resolve_lexical_macro_path_segment(
927                 ident, MacroNS, Some(kind), &parent_scope, true, true, span
928             );
929
930             let check_consistency = |this: &Self, new_def: Def| {
931                 if let Some(def) = def {
932                     if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
933                         // Make sure compilation does not succeed if preferred macro resolution
934                         // has changed after the macro had been expanded. In theory all such
935                         // situations should be reported as ambiguity errors, so this is span-bug.
936                         span_bug!(span, "inconsistent resolution for a macro");
937                     }
938                 } else {
939                     // It's possible that the macro was unresolved (indeterminate) and silently
940                     // expanded into a dummy fragment for recovery during expansion.
941                     // Now, post-expansion, the resolution may succeed, but we can't change the
942                     // past and need to report an error.
943                     let msg =
944                         format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
945                     let msg_note = "import resolution is stuck, try simplifying macro imports";
946                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
947                 }
948             };
949
950             match (legacy_resolution, resolution) {
951                 (None, Err(_)) => {
952                     assert!(def.is_none());
953                     let bang = if kind == MacroKind::Bang { "!" } else { "" };
954                     let msg =
955                         format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
956                     let mut err = self.session.struct_span_err(span, &msg);
957                     self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
958                     err.emit();
959                 },
960                 (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
961                         if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
962                            (!from_prelude ||
963                             legacy_binding.may_appear_after(parent_scope.expansion, binding)) => {
964                     self.report_ambiguity_error(ident, legacy_binding, binding);
965                 },
966                 // OK, non-macro-expanded legacy wins over prelude even if defs are different
967                 // Also, legacy and modern can co-exist if their defs are same
968                 (Some(legacy_binding), Ok(_)) |
969                 // OK, unambiguous resolution
970                 (Some(legacy_binding), Err(_)) => {
971                     check_consistency(self, legacy_binding.def());
972                 }
973                 // OK, unambiguous resolution
974                 (None, Ok((binding, FromPrelude(from_prelude)))) => {
975                     check_consistency(self, binding.def_ignoring_ambiguity());
976                     if from_prelude {
977                         self.record_use(ident, MacroNS, binding);
978                         self.err_if_macro_use_proc_macro(ident.name, span, binding);
979                     }
980                 }
981             };
982         }
983
984         let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
985         for (ident, parent_scope) in builtin_attrs {
986             let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
987                 ident, Some(MacroKind::Attr), &parent_scope, true
988             );
989             let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
990                 ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
991             ).map(|(binding, _)| binding).ok();
992
993             if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
994                 if binding.def_ignoring_ambiguity() !=
995                         Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
996                     let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
997                                            ty::Visibility::Public, ident.span, Mark::root())
998                                            .to_name_binding(self.arenas);
999                     self.report_ambiguity_error(ident, binding, builtin_binding);
1000                 }
1001             }
1002         }
1003     }
1004
1005     fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1006                           err: &mut DiagnosticBuilder<'a>, span: Span) {
1007         // First check if this is a locally-defined bang macro.
1008         let suggestion = if let MacroKind::Bang = kind {
1009             find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1010         } else {
1011             None
1012         // Then check global macros.
1013         }.or_else(|| {
1014             let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1015                                                   .filter_map(|(name, binding)| {
1016                 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1017             });
1018             find_best_match_for_name(names, name, None)
1019         // Then check modules.
1020         }).or_else(|| {
1021             let is_macro = |def| {
1022                 if let Def::Macro(_, def_kind) = def {
1023                     def_kind == kind
1024                 } else {
1025                     false
1026                 }
1027             };
1028             let ident = Ident::new(Symbol::intern(name), span);
1029             self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
1030         });
1031
1032         if let Some(suggestion) = suggestion {
1033             if suggestion != name {
1034                 if let MacroKind::Bang = kind {
1035                     err.span_suggestion_with_applicability(
1036                         span,
1037                         "you could try the macro",
1038                         suggestion.to_string(),
1039                         Applicability::MaybeIncorrect
1040                     );
1041                 } else {
1042                     err.span_suggestion_with_applicability(
1043                         span,
1044                         "try",
1045                         suggestion.to_string(),
1046                         Applicability::MaybeIncorrect
1047                     );
1048                 }
1049             } else {
1050                 err.help("have you added the `#[macro_use]` on the module/import?");
1051             }
1052         }
1053     }
1054
1055     fn collect_def_ids(&mut self,
1056                        mark: Mark,
1057                        invocation: &'a InvocationData<'a>,
1058                        fragment: &AstFragment) {
1059         let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1060         let InvocationData { def_index, .. } = *invocation;
1061
1062         let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1063             invocations.entry(invoc.mark).or_insert_with(|| {
1064                 arenas.alloc_invocation_data(InvocationData {
1065                     def_index: invoc.def_index,
1066                     module: Cell::new(graph_root),
1067                     parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1068                     output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1069                 })
1070             });
1071         };
1072
1073         let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1074         def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1075         def_collector.with_parent(def_index, |def_collector| {
1076             fragment.visit_with(def_collector)
1077         });
1078     }
1079
1080     pub fn define_macro(&mut self,
1081                         item: &ast::Item,
1082                         expansion: Mark,
1083                         current_legacy_scope: &mut LegacyScope<'a>) {
1084         self.local_macro_def_scopes.insert(item.id, self.current_module);
1085         let ident = item.ident;
1086         if ident.name == "macro_rules" {
1087             self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1088         }
1089
1090         let def_id = self.definitions.local_def_id(item.id);
1091         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1092                                                &self.session.features_untracked(),
1093                                                item, hygiene::default_edition()));
1094         self.macro_map.insert(def_id, ext);
1095
1096         let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1097         if def.legacy {
1098             let ident = ident.modern();
1099             self.macro_names.insert(ident);
1100             let def = Def::Macro(def_id, MacroKind::Bang);
1101             let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1102             let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1103             let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1104                 parent_legacy_scope: *current_legacy_scope, binding, ident
1105             });
1106             *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1107             self.all_macros.insert(ident.name, def);
1108             if attr::contains_name(&item.attrs, "macro_export") {
1109                 let module = self.graph_root;
1110                 let vis = ty::Visibility::Public;
1111                 self.define(module, ident, MacroNS,
1112                             (def, vis, item.span, expansion, IsMacroExport));
1113             } else {
1114                 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1115                     self.check_reserved_macro_name(ident, MacroNS);
1116                 }
1117                 self.unused_macros.insert(def_id);
1118             }
1119         } else {
1120             let module = self.current_module;
1121             let def = Def::Macro(def_id, MacroKind::Bang);
1122             let vis = self.resolve_visibility(&item.vis);
1123             if vis != ty::Visibility::Public {
1124                 self.unused_macros.insert(def_id);
1125             }
1126             self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1127         }
1128     }
1129
1130     /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1131     fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1132                                    binding: &NameBinding<'a>) {
1133         let krate = match binding.def() {
1134             Def::NonMacroAttr(..) | Def::Err => return,
1135             Def::Macro(def_id, _) => def_id.krate,
1136             _ => unreachable!(),
1137         };
1138
1139         // Plugin-based syntax extensions are exempt from this check
1140         if krate == BUILTIN_MACROS_CRATE { return; }
1141
1142         let ext = binding.get_macro(self);
1143
1144         match *ext {
1145             // If `ext` is a procedural macro, check if we've already warned about it
1146             SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1147                 if !self.warned_proc_macros.insert(name) { return; },
1148             _ => return,
1149         }
1150
1151         let warn_msg = match *ext {
1152             SyntaxExtension::AttrProcMacro(..) =>
1153                 "attribute procedural macros cannot be imported with `#[macro_use]`",
1154             SyntaxExtension::ProcMacro { .. } =>
1155                 "procedural macros cannot be imported with `#[macro_use]`",
1156             _ => return,
1157         };
1158
1159         let def_id = self.current_module.normal_ancestor_id;
1160         let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1161
1162         self.proc_mac_errors.push(ProcMacError {
1163             crate_name: self.cstore.crate_name_untracked(krate),
1164             name,
1165             module: node_id,
1166             use_span,
1167             warn_msg,
1168         });
1169     }
1170
1171     pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1172         for err in self.proc_mac_errors.drain(..) {
1173             let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1174
1175             if let Some(span) = span {
1176                 let found_use = if found_use { "" } else { "\n" };
1177                 self.session.struct_span_err(err.use_span, err.warn_msg)
1178                     .span_suggestion_with_applicability(
1179                         span,
1180                         "instead, import the procedural macro like any other item",
1181                         format!("use {}::{};{}", err.crate_name, err.name, found_use),
1182                         Applicability::MachineApplicable
1183                     ).emit();
1184             } else {
1185                 self.session.struct_span_err(err.use_span, err.warn_msg)
1186                     .help(&format!("instead, import the procedural macro like any other item: \
1187                                     `use {}::{};`", err.crate_name, err.name))
1188                     .emit();
1189             }
1190         }
1191     }
1192
1193     fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1194         if !self.session.features_untracked().custom_derive {
1195             let sess = &self.session.parse_sess;
1196             let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1197             emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1198         } else if !self.is_whitelisted_legacy_custom_derive(name) {
1199             self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);
1200         }
1201     }
1202 }