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