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