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