]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/macros.rs
Rollup merge of #95591 - jackh726:nll-revisions-1, r=oli-obk
[rust.git] / compiler / rustc_resolve / src / macros.rs
1 //! A bunch of methods and structures more or less related to resolving macros and
2 //! interface provided by `Resolver` to macro expander.
3
4 use crate::imports::ImportResolver;
5 use crate::Namespace::*;
6 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BuiltinMacroState, Determinacy};
7 use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Weak};
8 use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
9 use rustc_ast::{self as ast, Inline, ItemKind, ModKind, NodeId};
10 use rustc_ast_lowering::ResolverAstLowering;
11 use rustc_ast_pretty::pprust;
12 use rustc_attr::StabilityLevel;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_data_structures::intern::Interned;
15 use rustc_data_structures::sync::Lrc;
16 use rustc_errors::struct_span_err;
17 use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
18 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
19 use rustc_expand::compile_declarative_macro;
20 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
21 use rustc_feature::is_builtin_attr_name;
22 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
23 use rustc_hir::def_id::{CrateNum, LocalDefId};
24 use rustc_hir::PrimTy;
25 use rustc_middle::middle::stability;
26 use rustc_middle::ty::{self, RegisteredTools};
27 use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, PROC_MACRO_DERIVE_RESOLUTION_FALLBACK};
28 use rustc_session::lint::builtin::{SOFT_UNSTABLE, UNUSED_MACROS};
29 use rustc_session::lint::BuiltinLintDiagnostics;
30 use rustc_session::parse::feature_err;
31 use rustc_session::Session;
32 use rustc_span::edition::Edition;
33 use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
34 use rustc_span::hygiene::{AstPass, MacroKind};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::{Span, DUMMY_SP};
37 use std::cell::Cell;
38 use std::{mem, ptr};
39
40 type Res = def::Res<NodeId>;
41
42 /// Binding produced by a `macro_rules` item.
43 /// Not modularized, can shadow previous `macro_rules` bindings, etc.
44 #[derive(Debug)]
45 pub struct MacroRulesBinding<'a> {
46     crate binding: &'a NameBinding<'a>,
47     /// `macro_rules` scope into which the `macro_rules` item was planted.
48     crate parent_macro_rules_scope: MacroRulesScopeRef<'a>,
49     crate ident: Ident,
50 }
51
52 /// The scope introduced by a `macro_rules!` macro.
53 /// This starts at the macro's definition and ends at the end of the macro's parent
54 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
55 /// Some macro invocations need to introduce `macro_rules` scopes too because they
56 /// can potentially expand into macro definitions.
57 #[derive(Copy, Clone, Debug)]
58 pub enum MacroRulesScope<'a> {
59     /// Empty "root" scope at the crate start containing no names.
60     Empty,
61     /// The scope introduced by a `macro_rules!` macro definition.
62     Binding(&'a MacroRulesBinding<'a>),
63     /// The scope introduced by a macro invocation that can potentially
64     /// create a `macro_rules!` macro definition.
65     Invocation(LocalExpnId),
66 }
67
68 /// `macro_rules!` scopes are always kept by reference and inside a cell.
69 /// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
70 /// in-place after `invoc_id` gets expanded.
71 /// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
72 /// which usually grow linearly with the number of macro invocations
73 /// in a module (including derives) and hurt performance.
74 pub(crate) type MacroRulesScopeRef<'a> = Interned<'a, Cell<MacroRulesScope<'a>>>;
75
76 // Macro namespace is separated into two sub-namespaces, one for bang macros and
77 // one for attribute-like macros (attributes, derives).
78 // We ignore resolutions from one sub-namespace when searching names in scope for another.
79 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
80     #[derive(PartialEq)]
81     enum SubNS {
82         Bang,
83         AttrLike,
84     }
85     let sub_ns = |kind| match kind {
86         MacroKind::Bang => SubNS::Bang,
87         MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
88     };
89     let candidate = candidate.map(sub_ns);
90     let requirement = requirement.map(sub_ns);
91     // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
92     candidate.is_none() || requirement.is_none() || candidate == requirement
93 }
94
95 // We don't want to format a path using pretty-printing,
96 // `format!("{}", path)`, because that tries to insert
97 // line-breaks and is slow.
98 fn fast_print_path(path: &ast::Path) -> Symbol {
99     if path.segments.len() == 1 {
100         path.segments[0].ident.name
101     } else {
102         let mut path_str = String::with_capacity(64);
103         for (i, segment) in path.segments.iter().enumerate() {
104             if i != 0 {
105                 path_str.push_str("::");
106             }
107             if segment.ident.name != kw::PathRoot {
108                 path_str.push_str(segment.ident.as_str())
109             }
110         }
111         Symbol::intern(&path_str)
112     }
113 }
114
115 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
116 fn registered_idents(
117     sess: &Session,
118     attrs: &[ast::Attribute],
119     attr_name: Symbol,
120     descr: &str,
121 ) -> FxHashSet<Ident> {
122     let mut registered = FxHashSet::default();
123     for attr in sess.filter_by_name(attrs, attr_name) {
124         for nested_meta in attr.meta_item_list().unwrap_or_default() {
125             match nested_meta.ident() {
126                 Some(ident) => {
127                     if let Some(old_ident) = registered.replace(ident) {
128                         let msg = format!("{} `{}` was already registered", descr, ident);
129                         sess.struct_span_err(ident.span, &msg)
130                             .span_label(old_ident.span, "already registered here")
131                             .emit();
132                     }
133                 }
134                 None => {
135                     let msg = format!("`{}` only accepts identifiers", attr_name);
136                     let span = nested_meta.span();
137                     sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
138                 }
139             }
140         }
141     }
142     registered
143 }
144
145 crate fn registered_attrs_and_tools(
146     sess: &Session,
147     attrs: &[ast::Attribute],
148 ) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
149     let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
150     let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
151     // We implicitly add `rustfmt` and `clippy` to known tools,
152     // but it's not an error to register them explicitly.
153     let predefined_tools = [sym::clippy, sym::rustfmt];
154     registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
155     (registered_attrs, registered_tools)
156 }
157
158 // Some feature gates for inner attributes are reported as lints for backward compatibility.
159 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
160     match &path.segments[..] {
161         // `#![test]`
162         [seg] if seg.ident.name == sym::test => return true,
163         // `#![rustfmt::skip]` on out-of-line modules
164         [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
165             if let InvocationKind::Attr { item, .. } = &invoc.kind {
166                 if let Annotatable::Item(item) = item {
167                     if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
168                         return true;
169                     }
170                 }
171             }
172         }
173         _ => {}
174     }
175     false
176 }
177
178 impl<'a> ResolverExpand for Resolver<'a> {
179     fn next_node_id(&mut self) -> NodeId {
180         self.next_node_id()
181     }
182
183     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
184         self.invocation_parents[&id].0
185     }
186
187     fn resolve_dollar_crates(&mut self) {
188         hygiene::update_dollar_crate_names(|ctxt| {
189             let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
190             match self.resolve_crate_root(ident).kind {
191                 ModuleKind::Def(.., name) if name != kw::Empty => name,
192                 _ => kw::Crate,
193             }
194         });
195     }
196
197     fn visit_ast_fragment_with_placeholders(
198         &mut self,
199         expansion: LocalExpnId,
200         fragment: &AstFragment,
201     ) {
202         // Integrate the new AST fragment into all the definition and module structures.
203         // We are inside the `expansion` now, but other parent scope components are still the same.
204         let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
205         let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
206         self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
207
208         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
209     }
210
211     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
212         if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
213             self.session
214                 .diagnostic()
215                 .bug(&format!("built-in macro `{}` was already registered", name));
216         }
217     }
218
219     // Create a new Expansion with a definition site of the provided module, or
220     // a fake empty `#[no_implicit_prelude]` module if no module is provided.
221     fn expansion_for_ast_pass(
222         &mut self,
223         call_site: Span,
224         pass: AstPass,
225         features: &[Symbol],
226         parent_module_id: Option<NodeId>,
227     ) -> LocalExpnId {
228         let parent_module =
229             parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
230         let expn_id = LocalExpnId::fresh(
231             ExpnData::allow_unstable(
232                 ExpnKind::AstPass(pass),
233                 call_site,
234                 self.session.edition(),
235                 features.into(),
236                 None,
237                 parent_module,
238             ),
239             self.create_stable_hashing_context(),
240         );
241
242         let parent_scope =
243             parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
244         self.ast_transform_scopes.insert(expn_id, parent_scope);
245
246         expn_id
247     }
248
249     fn resolve_imports(&mut self) {
250         ImportResolver { r: self }.resolve_imports()
251     }
252
253     fn resolve_macro_invocation(
254         &mut self,
255         invoc: &Invocation,
256         eager_expansion_root: LocalExpnId,
257         force: bool,
258     ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
259         let invoc_id = invoc.expansion_data.id;
260         let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
261             Some(parent_scope) => *parent_scope,
262             None => {
263                 // If there's no entry in the table, then we are resolving an eagerly expanded
264                 // macro, which should inherit its parent scope from its eager expansion root -
265                 // the macro that requested this eager expansion.
266                 let parent_scope = *self
267                     .invocation_parent_scopes
268                     .get(&eager_expansion_root)
269                     .expect("non-eager expansion without a parent scope");
270                 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
271                 parent_scope
272             }
273         };
274
275         let (path, kind, inner_attr, derives) = match invoc.kind {
276             InvocationKind::Attr { ref attr, ref derives, .. } => (
277                 &attr.get_normal_item().path,
278                 MacroKind::Attr,
279                 attr.style == ast::AttrStyle::Inner,
280                 self.arenas.alloc_ast_paths(derives),
281             ),
282             InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
283             InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
284         };
285
286         // Derives are not included when `invocations` are collected, so we have to add them here.
287         let parent_scope = &ParentScope { derives, ..parent_scope };
288         let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
289         let node_id = invoc.expansion_data.lint_node_id;
290         let (ext, res) = self.smart_resolve_macro_path(
291             path,
292             kind,
293             supports_macro_expansion,
294             inner_attr,
295             parent_scope,
296             node_id,
297             force,
298             soft_custom_inner_attributes_gate(path, invoc),
299         )?;
300
301         let span = invoc.span();
302         let def_id = res.opt_def_id();
303         invoc_id.set_expn_data(
304             ext.expn_data(
305                 parent_scope.expansion,
306                 span,
307                 fast_print_path(path),
308                 def_id,
309                 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
310             ),
311             self.create_stable_hashing_context(),
312         );
313
314         Ok(ext)
315     }
316
317     fn check_unused_macros(&mut self) {
318         for (_, &(node_id, ident)) in self.unused_macros.iter() {
319             self.lint_buffer.buffer_lint(
320                 UNUSED_MACROS,
321                 node_id,
322                 ident.span,
323                 &format!("unused macro definition: `{}`", ident.as_str()),
324             );
325         }
326     }
327
328     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
329         self.containers_deriving_copy.contains(&expn_id)
330     }
331
332     fn resolve_derives(
333         &mut self,
334         expn_id: LocalExpnId,
335         force: bool,
336         derive_paths: &dyn Fn() -> DeriveResolutions,
337     ) -> Result<(), Indeterminate> {
338         // Block expansion of the container until we resolve all derives in it.
339         // This is required for two reasons:
340         // - Derive helper attributes are in scope for the item to which the `#[derive]`
341         //   is applied, so they have to be produced by the container's expansion rather
342         //   than by individual derives.
343         // - Derives in the container need to know whether one of them is a built-in `Copy`.
344         // Temporarily take the data to avoid borrow checker conflicts.
345         let mut derive_data = mem::take(&mut self.derive_data);
346         let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
347             resolutions: derive_paths(),
348             helper_attrs: Vec::new(),
349             has_derive_copy: false,
350         });
351         let parent_scope = self.invocation_parent_scopes[&expn_id];
352         for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
353             if opt_ext.is_none() {
354                 *opt_ext = Some(
355                     match self.resolve_macro_path(
356                         &path,
357                         Some(MacroKind::Derive),
358                         &parent_scope,
359                         true,
360                         force,
361                     ) {
362                         Ok((Some(ext), _)) => {
363                             if !ext.helper_attrs.is_empty() {
364                                 let last_seg = path.segments.last().unwrap();
365                                 let span = last_seg.ident.span.normalize_to_macros_2_0();
366                                 entry.helper_attrs.extend(
367                                     ext.helper_attrs
368                                         .iter()
369                                         .map(|name| (i, Ident::new(*name, span))),
370                                 );
371                             }
372                             entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
373                             ext
374                         }
375                         Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
376                         Err(Determinacy::Undetermined) => {
377                             assert!(self.derive_data.is_empty());
378                             self.derive_data = derive_data;
379                             return Err(Indeterminate);
380                         }
381                     },
382                 );
383             }
384         }
385         // Sort helpers in a stable way independent from the derive resolution order.
386         entry.helper_attrs.sort_by_key(|(i, _)| *i);
387         self.helper_attrs
388             .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
389         // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
390         // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
391         if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
392             self.containers_deriving_copy.insert(expn_id);
393         }
394         assert!(self.derive_data.is_empty());
395         self.derive_data = derive_data;
396         Ok(())
397     }
398
399     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
400         self.derive_data.remove(&expn_id).map(|data| data.resolutions)
401     }
402
403     // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
404     // Returns true if the path can certainly be resolved in one of three namespaces,
405     // returns false if the path certainly cannot be resolved in any of the three namespaces.
406     // Returns `Indeterminate` if we cannot give a certain answer yet.
407     fn cfg_accessible(
408         &mut self,
409         expn_id: LocalExpnId,
410         path: &ast::Path,
411     ) -> Result<bool, Indeterminate> {
412         let span = path.span;
413         let path = &Segment::from_path(path);
414         let parent_scope = self.invocation_parent_scopes[&expn_id];
415
416         let mut indeterminate = false;
417         for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
418             match self.resolve_path(path, Some(ns), &parent_scope, Finalize::No) {
419                 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
420                 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
421                     return Ok(true);
422                 }
423                 PathResult::Indeterminate => indeterminate = true,
424                 // FIXME: `resolve_path` is not ready to report partially resolved paths
425                 // correctly, so we just report an error if the path was reported as unresolved.
426                 // This needs to be fixed for `cfg_accessible` to be useful.
427                 PathResult::NonModule(..) | PathResult::Failed { .. } => {}
428                 PathResult::Module(_) => panic!("unexpected path resolution"),
429             }
430         }
431
432         if indeterminate {
433             return Err(Indeterminate);
434         }
435
436         self.session
437             .struct_span_err(span, "not sure whether the path is accessible or not")
438             .span_note(span, "`cfg_accessible` is not fully implemented")
439             .emit();
440         Ok(false)
441     }
442
443     fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
444         self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
445     }
446
447     fn declare_proc_macro(&mut self, id: NodeId) {
448         self.proc_macros.push(id)
449     }
450
451     fn registered_tools(&self) -> &RegisteredTools {
452         &self.registered_tools
453     }
454 }
455
456 impl<'a> Resolver<'a> {
457     /// Resolve macro path with error reporting and recovery.
458     /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
459     /// for better error recovery.
460     fn smart_resolve_macro_path(
461         &mut self,
462         path: &ast::Path,
463         kind: MacroKind,
464         supports_macro_expansion: SupportsMacroExpansion,
465         inner_attr: bool,
466         parent_scope: &ParentScope<'a>,
467         node_id: NodeId,
468         force: bool,
469         soft_custom_inner_attributes_gate: bool,
470     ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
471         let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
472         {
473             Ok((Some(ext), res)) => (ext, res),
474             Ok((None, res)) => (self.dummy_ext(kind), res),
475             Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
476             Err(Determinacy::Undetermined) => return Err(Indeterminate),
477         };
478
479         // Report errors for the resolved macro.
480         for segment in &path.segments {
481             if let Some(args) = &segment.args {
482                 self.session.span_err(args.span(), "generic arguments in macro path");
483             }
484             if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
485                 self.session.span_err(
486                     segment.ident.span,
487                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
488                 );
489             }
490         }
491
492         match res {
493             Res::Def(DefKind::Macro(_), def_id) => {
494                 if let Some(def_id) = def_id.as_local() {
495                     self.unused_macros.remove(&def_id);
496                     if self.proc_macro_stubs.contains(&def_id) {
497                         self.session.span_err(
498                             path.span,
499                             "can't use a procedural macro from the same crate that defines it",
500                         );
501                     }
502                 }
503             }
504             Res::NonMacroAttr(..) | Res::Err => {}
505             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
506         };
507
508         self.check_stability_and_deprecation(&ext, path, node_id);
509
510         let unexpected_res = if ext.macro_kind() != kind {
511             Some((kind.article(), kind.descr_expected()))
512         } else if matches!(res, Res::Def(..)) {
513             match supports_macro_expansion {
514                 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
515                 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
516                     if inner_attr && !supports_inner_attrs {
517                         Some(("a", "non-macro inner attribute"))
518                     } else {
519                         None
520                     }
521                 }
522             }
523         } else {
524             None
525         };
526         if let Some((article, expected)) = unexpected_res {
527             let path_str = pprust::path_to_string(path);
528             let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
529             self.session
530                 .struct_span_err(path.span, &msg)
531                 .span_label(path.span, format!("not {} {}", article, expected))
532                 .emit();
533             return Ok((self.dummy_ext(kind), Res::Err));
534         }
535
536         // We are trying to avoid reporting this error if other related errors were reported.
537         if res != Res::Err
538             && inner_attr
539             && !self.session.features_untracked().custom_inner_attributes
540         {
541             let msg = match res {
542                 Res::Def(..) => "inner macro attributes are unstable",
543                 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
544                 _ => unreachable!(),
545             };
546             if soft_custom_inner_attributes_gate {
547                 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
548             } else {
549                 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
550                     .emit();
551             }
552         }
553
554         Ok((ext, res))
555     }
556
557     pub fn resolve_macro_path(
558         &mut self,
559         path: &ast::Path,
560         kind: Option<MacroKind>,
561         parent_scope: &ParentScope<'a>,
562         trace: bool,
563         force: bool,
564     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
565         let path_span = path.span;
566         let mut path = Segment::from_path(path);
567
568         // Possibly apply the macro helper hack
569         if kind == Some(MacroKind::Bang)
570             && path.len() == 1
571             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
572         {
573             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
574             path.insert(0, Segment::from_ident(root));
575         }
576
577         let res = if path.len() > 1 {
578             let res = match self.resolve_path(&path, Some(MacroNS), parent_scope, Finalize::No) {
579                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
580                     Ok(path_res.base_res())
581                 }
582                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
583                 PathResult::NonModule(..)
584                 | PathResult::Indeterminate
585                 | PathResult::Failed { .. } => Err(Determinacy::Determined),
586                 PathResult::Module(..) => unreachable!(),
587             };
588
589             if trace {
590                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
591                 self.multi_segment_macro_resolutions.push((
592                     path,
593                     path_span,
594                     kind,
595                     *parent_scope,
596                     res.ok(),
597                 ));
598             }
599
600             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
601             res
602         } else {
603             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
604             let binding = self.early_resolve_ident_in_lexical_scope(
605                 path[0].ident,
606                 scope_set,
607                 parent_scope,
608                 None,
609                 force,
610             );
611             if let Err(Determinacy::Undetermined) = binding {
612                 return Err(Determinacy::Undetermined);
613             }
614
615             if trace {
616                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
617                 self.single_segment_macro_resolutions.push((
618                     path[0].ident,
619                     kind,
620                     *parent_scope,
621                     binding.ok(),
622                 ));
623             }
624
625             let res = binding.map(|binding| binding.res());
626             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
627             res
628         };
629
630         res.map(|res| (self.get_macro(res), res))
631     }
632
633     // Resolve an identifier in lexical scope.
634     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
635     // expansion and import resolution (perhaps they can be merged in the future).
636     // The function is used for resolving initial segments of macro paths (e.g., `foo` in
637     // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
638     crate fn early_resolve_ident_in_lexical_scope(
639         &mut self,
640         orig_ident: Ident,
641         scope_set: ScopeSet<'a>,
642         parent_scope: &ParentScope<'a>,
643         finalize: Option<Span>,
644         force: bool,
645     ) -> Result<&'a NameBinding<'a>, Determinacy> {
646         bitflags::bitflags! {
647             struct Flags: u8 {
648                 const MACRO_RULES          = 1 << 0;
649                 const MODULE               = 1 << 1;
650                 const MISC_SUGGEST_CRATE   = 1 << 2;
651                 const MISC_SUGGEST_SELF    = 1 << 3;
652                 const MISC_FROM_PRELUDE    = 1 << 4;
653             }
654         }
655
656         assert!(force || !finalize.is_some()); // `finalize` implies `force`
657
658         // Make sure `self`, `super` etc produce an error when passed to here.
659         if orig_ident.is_path_segment_keyword() {
660             return Err(Determinacy::Determined);
661         }
662
663         let (ns, macro_kind, is_import) = match scope_set {
664             ScopeSet::All(ns, is_import) => (ns, None, is_import),
665             ScopeSet::AbsolutePath(ns) => (ns, None, false),
666             ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
667             ScopeSet::Late(ns, ..) => (ns, None, false),
668         };
669
670         // This is *the* result, resolution from the scope closest to the resolved identifier.
671         // However, sometimes this result is "weak" because it comes from a glob import or
672         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
673         // mod m { ... } // solution in outer scope
674         // {
675         //     use prefix::*; // imports another `m` - innermost solution
676         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
677         //     m::mac!();
678         // }
679         // So we have to save the innermost solution and continue searching in outer scopes
680         // to detect potential ambiguities.
681         let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
682         let mut determinacy = Determinacy::Determined;
683
684         // Go through all the scopes and try to resolve the name.
685         let break_result = self.visit_scopes(
686             scope_set,
687             parent_scope,
688             orig_ident.span.ctxt(),
689             |this, scope, use_prelude, ctxt| {
690                 let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
691                 let ok = |res, span, arenas| {
692                     Ok((
693                         (res, ty::Visibility::Public, span, LocalExpnId::ROOT)
694                             .to_name_binding(arenas),
695                         Flags::empty(),
696                     ))
697                 };
698                 let result = match scope {
699                     Scope::DeriveHelpers(expn_id) => {
700                         if let Some(attr) = this
701                             .helper_attrs
702                             .get(&expn_id)
703                             .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
704                         {
705                             let binding = (
706                                 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
707                                 ty::Visibility::Public,
708                                 attr.span,
709                                 expn_id,
710                             )
711                                 .to_name_binding(this.arenas);
712                             Ok((binding, Flags::empty()))
713                         } else {
714                             Err(Determinacy::Determined)
715                         }
716                     }
717                     Scope::DeriveHelpersCompat => {
718                         let mut result = Err(Determinacy::Determined);
719                         for derive in parent_scope.derives {
720                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
721                             match this.resolve_macro_path(
722                                 derive,
723                                 Some(MacroKind::Derive),
724                                 parent_scope,
725                                 true,
726                                 force,
727                             ) {
728                                 Ok((Some(ext), _)) => {
729                                     if ext.helper_attrs.contains(&ident.name) {
730                                         result = ok(
731                                             Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
732                                             derive.span,
733                                             this.arenas,
734                                         );
735                                         break;
736                                     }
737                                 }
738                                 Ok(_) | Err(Determinacy::Determined) => {}
739                                 Err(Determinacy::Undetermined) => {
740                                     result = Err(Determinacy::Undetermined)
741                                 }
742                             }
743                         }
744                         result
745                     }
746                     Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
747                         MacroRulesScope::Binding(macro_rules_binding)
748                             if ident == macro_rules_binding.ident =>
749                         {
750                             Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
751                         }
752                         MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
753                         _ => Err(Determinacy::Determined),
754                     },
755                     Scope::CrateRoot => {
756                         let root_ident = Ident::new(kw::PathRoot, ident.span);
757                         let root_module = this.resolve_crate_root(root_ident);
758                         let binding = this.resolve_ident_in_module_ext(
759                             ModuleOrUniformRoot::Module(root_module),
760                             ident,
761                             ns,
762                             parent_scope,
763                             finalize,
764                         );
765                         match binding {
766                             Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
767                             Err((Determinacy::Undetermined, Weak::No)) => {
768                                 return Some(Err(Determinacy::determined(force)));
769                             }
770                             Err((Determinacy::Undetermined, Weak::Yes)) => {
771                                 Err(Determinacy::Undetermined)
772                             }
773                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
774                         }
775                     }
776                     Scope::Module(module, derive_fallback_lint_id) => {
777                         let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
778                         let binding = this.resolve_ident_in_module_unadjusted_ext(
779                             ModuleOrUniformRoot::Module(module),
780                             ident,
781                             ns,
782                             adjusted_parent_scope,
783                             !matches!(scope_set, ScopeSet::Late(..)),
784                             finalize,
785                         );
786                         match binding {
787                             Ok(binding) => {
788                                 if let Some(lint_id) = derive_fallback_lint_id {
789                                     this.lint_buffer.buffer_lint_with_diagnostic(
790                                         PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
791                                         lint_id,
792                                         orig_ident.span,
793                                         &format!(
794                                             "cannot find {} `{}` in this scope",
795                                             ns.descr(),
796                                             ident
797                                         ),
798                                         BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(
799                                             orig_ident.span,
800                                         ),
801                                     );
802                                 }
803                                 let misc_flags = if ptr::eq(module, this.graph_root) {
804                                     Flags::MISC_SUGGEST_CRATE
805                                 } else if module.is_normal() {
806                                     Flags::MISC_SUGGEST_SELF
807                                 } else {
808                                     Flags::empty()
809                                 };
810                                 Ok((binding, Flags::MODULE | misc_flags))
811                             }
812                             Err((Determinacy::Undetermined, Weak::No)) => {
813                                 return Some(Err(Determinacy::determined(force)));
814                             }
815                             Err((Determinacy::Undetermined, Weak::Yes)) => {
816                                 Err(Determinacy::Undetermined)
817                             }
818                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
819                         }
820                     }
821                     Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
822                         Some(ident) => ok(
823                             Res::NonMacroAttr(NonMacroAttrKind::Registered),
824                             ident.span,
825                             this.arenas,
826                         ),
827                         None => Err(Determinacy::Determined),
828                     },
829                     Scope::MacroUsePrelude => {
830                         match this.macro_use_prelude.get(&ident.name).cloned() {
831                             Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
832                             None => Err(Determinacy::determined(
833                                 this.graph_root.unexpanded_invocations.borrow().is_empty(),
834                             )),
835                         }
836                     }
837                     Scope::BuiltinAttrs => {
838                         if is_builtin_attr_name(ident.name) {
839                             ok(
840                                 Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)),
841                                 DUMMY_SP,
842                                 this.arenas,
843                             )
844                         } else {
845                             Err(Determinacy::Determined)
846                         }
847                     }
848                     Scope::ExternPrelude => {
849                         match this.extern_prelude_get(ident, finalize.is_some()) {
850                             Some(binding) => Ok((binding, Flags::empty())),
851                             None => Err(Determinacy::determined(
852                                 this.graph_root.unexpanded_invocations.borrow().is_empty(),
853                             )),
854                         }
855                     }
856                     Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
857                         Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
858                         None => Err(Determinacy::Determined),
859                     },
860                     Scope::StdLibPrelude => {
861                         let mut result = Err(Determinacy::Determined);
862                         if let Some(prelude) = this.prelude {
863                             if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
864                                 ModuleOrUniformRoot::Module(prelude),
865                                 ident,
866                                 ns,
867                                 parent_scope,
868                                 None,
869                             ) {
870                                 if use_prelude || this.is_builtin_macro(binding.res()) {
871                                     result = Ok((binding, Flags::MISC_FROM_PRELUDE));
872                                 }
873                             }
874                         }
875                         result
876                     }
877                     Scope::BuiltinTypes => match PrimTy::from_name(ident.name) {
878                         Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
879                         None => Err(Determinacy::Determined),
880                     },
881                 };
882
883                 match result {
884                     Ok((binding, flags))
885                         if sub_namespace_match(binding.macro_kind(), macro_kind) =>
886                     {
887                         if finalize.is_none() || matches!(scope_set, ScopeSet::Late(..)) {
888                             return Some(Ok(binding));
889                         }
890
891                         if let Some((innermost_binding, innermost_flags)) = innermost_result {
892                             // Found another solution, if the first one was "weak", report an error.
893                             let (res, innermost_res) = (binding.res(), innermost_binding.res());
894                             if res != innermost_res {
895                                 let is_builtin = |res| {
896                                     matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
897                                 };
898                                 let derive_helper =
899                                     Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
900                                 let derive_helper_compat =
901                                     Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
902
903                                 let ambiguity_error_kind = if is_import {
904                                     Some(AmbiguityKind::Import)
905                                 } else if is_builtin(innermost_res) || is_builtin(res) {
906                                     Some(AmbiguityKind::BuiltinAttr)
907                                 } else if innermost_res == derive_helper_compat
908                                     || res == derive_helper_compat && innermost_res != derive_helper
909                                 {
910                                     Some(AmbiguityKind::DeriveHelper)
911                                 } else if innermost_flags.contains(Flags::MACRO_RULES)
912                                     && flags.contains(Flags::MODULE)
913                                     && !this.disambiguate_macro_rules_vs_modularized(
914                                         innermost_binding,
915                                         binding,
916                                     )
917                                     || flags.contains(Flags::MACRO_RULES)
918                                         && innermost_flags.contains(Flags::MODULE)
919                                         && !this.disambiguate_macro_rules_vs_modularized(
920                                             binding,
921                                             innermost_binding,
922                                         )
923                                 {
924                                     Some(AmbiguityKind::MacroRulesVsModularized)
925                                 } else if innermost_binding.is_glob_import() {
926                                     Some(AmbiguityKind::GlobVsOuter)
927                                 } else if innermost_binding
928                                     .may_appear_after(parent_scope.expansion, binding)
929                                 {
930                                     Some(AmbiguityKind::MoreExpandedVsOuter)
931                                 } else {
932                                     None
933                                 };
934                                 if let Some(kind) = ambiguity_error_kind {
935                                     let misc = |f: Flags| {
936                                         if f.contains(Flags::MISC_SUGGEST_CRATE) {
937                                             AmbiguityErrorMisc::SuggestCrate
938                                         } else if f.contains(Flags::MISC_SUGGEST_SELF) {
939                                             AmbiguityErrorMisc::SuggestSelf
940                                         } else if f.contains(Flags::MISC_FROM_PRELUDE) {
941                                             AmbiguityErrorMisc::FromPrelude
942                                         } else {
943                                             AmbiguityErrorMisc::None
944                                         }
945                                     };
946                                     this.ambiguity_errors.push(AmbiguityError {
947                                         kind,
948                                         ident: orig_ident,
949                                         b1: innermost_binding,
950                                         b2: binding,
951                                         misc1: misc(innermost_flags),
952                                         misc2: misc(flags),
953                                     });
954                                     return Some(Ok(innermost_binding));
955                                 }
956                             }
957                         } else {
958                             // Found the first solution.
959                             innermost_result = Some((binding, flags));
960                         }
961                     }
962                     Ok(..) | Err(Determinacy::Determined) => {}
963                     Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
964                 }
965
966                 None
967             },
968         );
969
970         if let Some(break_result) = break_result {
971             return break_result;
972         }
973
974         // The first found solution was the only one, return it.
975         if let Some((binding, _)) = innermost_result {
976             return Ok(binding);
977         }
978
979         Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
980     }
981
982     crate fn finalize_macro_resolutions(&mut self) {
983         let check_consistency = |this: &mut Self,
984                                  path: &[Segment],
985                                  span,
986                                  kind: MacroKind,
987                                  initial_res: Option<Res>,
988                                  res: Res| {
989             if let Some(initial_res) = initial_res {
990                 if res != initial_res {
991                     // Make sure compilation does not succeed if preferred macro resolution
992                     // has changed after the macro had been expanded. In theory all such
993                     // situations should be reported as errors, so this is a bug.
994                     this.session.delay_span_bug(span, "inconsistent resolution for a macro");
995                 }
996             } else {
997                 // It's possible that the macro was unresolved (indeterminate) and silently
998                 // expanded into a dummy fragment for recovery during expansion.
999                 // Now, post-expansion, the resolution may succeed, but we can't change the
1000                 // past and need to report an error.
1001                 // However, non-speculative `resolve_path` can successfully return private items
1002                 // even if speculative `resolve_path` returned nothing previously, so we skip this
1003                 // less informative error if the privacy error is reported elsewhere.
1004                 if this.privacy_errors.is_empty() {
1005                     let msg = format!(
1006                         "cannot determine resolution for the {} `{}`",
1007                         kind.descr(),
1008                         Segment::names_to_string(path)
1009                     );
1010                     let msg_note = "import resolution is stuck, try simplifying macro imports";
1011                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
1012                 }
1013             }
1014         };
1015
1016         let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
1017         for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
1018             // FIXME: Path resolution will ICE if segment IDs present.
1019             for seg in &mut path {
1020                 seg.id = None;
1021             }
1022             match self.resolve_path(
1023                 &path,
1024                 Some(MacroNS),
1025                 &parent_scope,
1026                 Finalize::SimplePath(ast::CRATE_NODE_ID, path_span),
1027             ) {
1028                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1029                     let res = path_res.base_res();
1030                     check_consistency(self, &path, path_span, kind, initial_res, res);
1031                 }
1032                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
1033                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
1034                         (span, label)
1035                     } else {
1036                         (
1037                             path_span,
1038                             format!(
1039                                 "partially resolved path in {} {}",
1040                                 kind.article(),
1041                                 kind.descr()
1042                             ),
1043                         )
1044                     };
1045                     self.report_error(
1046                         span,
1047                         ResolutionError::FailedToResolve { label, suggestion: None },
1048                     );
1049                 }
1050                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1051             }
1052         }
1053
1054         let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
1055         for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
1056             match self.early_resolve_ident_in_lexical_scope(
1057                 ident,
1058                 ScopeSet::Macro(kind),
1059                 &parent_scope,
1060                 Some(ident.span),
1061                 true,
1062             ) {
1063                 Ok(binding) => {
1064                     let initial_res = initial_binding.map(|initial_binding| {
1065                         self.record_use(ident, initial_binding, false);
1066                         initial_binding.res()
1067                     });
1068                     let res = binding.res();
1069                     let seg = Segment::from_ident(ident);
1070                     check_consistency(self, &[seg], ident.span, kind, initial_res, res);
1071                     if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
1072                         let node_id = self
1073                             .invocation_parents
1074                             .get(&parent_scope.expansion)
1075                             .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
1076                         self.lint_buffer.buffer_lint_with_diagnostic(
1077                             LEGACY_DERIVE_HELPERS,
1078                             node_id,
1079                             ident.span,
1080                             "derive helper attribute is used before it is introduced",
1081                             BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
1082                         );
1083                     }
1084                 }
1085                 Err(..) => {
1086                     let expected = kind.descr_expected();
1087                     let msg = format!("cannot find {} `{}` in this scope", expected, ident);
1088                     let mut err = self.session.struct_span_err(ident.span, &msg);
1089                     self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
1090                     err.emit();
1091                 }
1092             }
1093         }
1094
1095         let builtin_attrs = mem::take(&mut self.builtin_attrs);
1096         for (ident, parent_scope) in builtin_attrs {
1097             let _ = self.early_resolve_ident_in_lexical_scope(
1098                 ident,
1099                 ScopeSet::Macro(MacroKind::Attr),
1100                 &parent_scope,
1101                 Some(ident.span),
1102                 true,
1103             );
1104         }
1105     }
1106
1107     fn check_stability_and_deprecation(
1108         &mut self,
1109         ext: &SyntaxExtension,
1110         path: &ast::Path,
1111         node_id: NodeId,
1112     ) {
1113         let span = path.span;
1114         if let Some(stability) = &ext.stability {
1115             if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
1116                 let feature = stability.feature;
1117                 if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
1118                     let lint_buffer = &mut self.lint_buffer;
1119                     let soft_handler =
1120                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
1121                     stability::report_unstable(
1122                         self.session,
1123                         feature,
1124                         reason,
1125                         issue,
1126                         None,
1127                         is_soft,
1128                         span,
1129                         soft_handler,
1130                     );
1131                 }
1132             }
1133         }
1134         if let Some(depr) = &ext.deprecation {
1135             let path = pprust::path_to_string(&path);
1136             let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
1137             stability::early_report_deprecation(
1138                 &mut self.lint_buffer,
1139                 &message,
1140                 depr.suggestion,
1141                 lint,
1142                 span,
1143                 node_id,
1144             );
1145         }
1146     }
1147
1148     fn prohibit_imported_non_macro_attrs(
1149         &self,
1150         binding: Option<&'a NameBinding<'a>>,
1151         res: Option<Res>,
1152         span: Span,
1153     ) {
1154         if let Some(Res::NonMacroAttr(kind)) = res {
1155             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1156                 let msg =
1157                     format!("cannot use {} {} through an import", kind.article(), kind.descr());
1158                 let mut err = self.session.struct_span_err(span, &msg);
1159                 if let Some(binding) = binding {
1160                     err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1161                 }
1162                 err.emit();
1163             }
1164         }
1165     }
1166
1167     crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
1168         // Reserve some names that are not quite covered by the general check
1169         // performed on `Resolver::builtin_attrs`.
1170         if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1171             let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
1172             if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
1173                 self.session.span_err(
1174                     ident.span,
1175                     &format!("name `{}` is reserved in attribute namespace", ident),
1176                 );
1177             }
1178         }
1179     }
1180
1181     /// Compile the macro into a `SyntaxExtension` and possibly replace
1182     /// its expander to a pre-defined one for built-in macros.
1183     crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
1184         let mut result = compile_declarative_macro(
1185             &self.session,
1186             self.session.features_untracked(),
1187             item,
1188             edition,
1189         );
1190
1191         if let Some(builtin_name) = result.builtin_name {
1192             // The macro was marked with `#[rustc_builtin_macro]`.
1193             if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
1194                 // The macro is a built-in, replace its expander function
1195                 // while still taking everything else from the source code.
1196                 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
1197                 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
1198                     BuiltinMacroState::NotYetSeen(ext) => {
1199                         result.kind = ext;
1200                         if item.id != ast::DUMMY_NODE_ID {
1201                             self.builtin_macro_kinds
1202                                 .insert(self.local_def_id(item.id), result.macro_kind());
1203                         }
1204                     }
1205                     BuiltinMacroState::AlreadySeen(span) => {
1206                         struct_span_err!(
1207                             self.session,
1208                             item.span,
1209                             E0773,
1210                             "attempted to define built-in macro more than once"
1211                         )
1212                         .span_note(span, "previously defined here")
1213                         .emit();
1214                     }
1215                 }
1216             } else {
1217                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
1218                 self.session.span_err(item.span, &msg);
1219             }
1220         }
1221
1222         result
1223     }
1224 }