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