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