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