Skip to main content

rustc_resolve/
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
4use std::mem;
5use std::sync::Arc;
6
7use rustc_ast::{self as ast, Crate, NodeId, attr};
8use rustc_ast_pretty::pprust;
9use rustc_errors::{Applicability, DiagCtxtHandle, StashKey};
10use rustc_expand::base::{
11    Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension,
12    SyntaxExtensionKind,
13};
14use rustc_expand::compile_declarative_macro;
15use rustc_expand::expand::{
16    AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion,
17};
18use rustc_hir::StabilityLevel;
19use rustc_hir::attrs::{CfgEntry, StrippedCfgItem};
20use rustc_hir::def::{self, DefKind, MacroKinds, Namespace, NonMacroAttrKind};
21use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
22use rustc_middle::middle::stability;
23use rustc_middle::ty::{RegisteredTools, TyCtxt};
24use rustc_session::lint::builtin::{
25    LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
26    UNUSED_MACRO_RULES, UNUSED_MACROS,
27};
28use rustc_session::parse::feature_err;
29use rustc_span::edit_distance::find_best_match_for_name;
30use rustc_span::edition::Edition;
31use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
32use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
33
34use crate::Namespace::*;
35use crate::errors::{
36    self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
37    MacroExpectedFound, RemoveSurroundingDerive,
38};
39use crate::hygiene::Macros20NormalizedSyntaxContext;
40use crate::imports::Import;
41use crate::{
42    BindingKey, CacheCell, CmResolver, Decl, DeclKind, DeriveData, Determinacy, Finalize, IdentKey,
43    InvocationParent, MacroData, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult,
44    ResolutionError, Resolver, ScopeSet, Segment, Used,
45};
46
47type Res = def::Res<NodeId>;
48
49/// Name declaration produced by a `macro_rules` item definition.
50/// Not modularized, can shadow previous `macro_rules` definitions, etc.
51#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for MacroRulesDecl<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "MacroRulesDecl", "decl", &self.decl, "parent_macro_rules_scope",
            &self.parent_macro_rules_scope, "ident", &self.ident,
            "orig_ident_span", &&self.orig_ident_span)
    }
}Debug)]
52pub(crate) struct MacroRulesDecl<'ra> {
53    pub(crate) decl: Decl<'ra>,
54    /// `macro_rules` scope into which the `macro_rules` item was planted.
55    pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
56    pub(crate) ident: IdentKey,
57    pub(crate) orig_ident_span: Span,
58}
59
60/// The scope introduced by a `macro_rules!` macro.
61/// This starts at the macro's definition and ends at the end of the macro's parent
62/// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
63/// Some macro invocations need to introduce `macro_rules` scopes too because they
64/// can potentially expand into macro definitions.
65#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for MacroRulesScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for MacroRulesScope<'ra> {
    #[inline]
    fn clone(&self) -> MacroRulesScope<'ra> {
        let _: ::core::clone::AssertParamIsClone<&'ra MacroRulesDecl<'ra>>;
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for MacroRulesScope<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MacroRulesScope::Empty =>
                ::core::fmt::Formatter::write_str(f, "Empty"),
            MacroRulesScope::Def(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
                    &__self_0),
            MacroRulesScope::Invocation(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Invocation", &__self_0),
        }
    }
}Debug)]
66pub(crate) enum MacroRulesScope<'ra> {
67    /// Empty "root" scope at the crate start containing no names.
68    Empty,
69    /// The scope introduced by a `macro_rules!` macro definition.
70    Def(&'ra MacroRulesDecl<'ra>),
71    /// The scope introduced by a macro invocation that can potentially
72    /// create a `macro_rules!` macro definition.
73    Invocation(LocalExpnId),
74}
75
76/// `macro_rules!` scopes are always kept by reference and inside a cell.
77/// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
78/// in-place after `invoc_id` gets expanded.
79/// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
80/// which usually grow linearly with the number of macro invocations
81/// in a module (including derives) and hurt performance.
82pub(crate) type MacroRulesScopeRef<'ra> = &'ra CacheCell<MacroRulesScope<'ra>>;
83
84/// Macro namespace is separated into two sub-namespaces, one for bang macros and
85/// one for attribute-like macros (attributes, derives).
86/// We ignore resolutions from one sub-namespace when searching names in scope for another.
87pub(crate) fn sub_namespace_match(
88    candidate: Option<MacroKinds>,
89    requirement: Option<MacroKind>,
90) -> bool {
91    // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
92    let (Some(candidate), Some(requirement)) = (candidate, requirement) else {
93        return true;
94    };
95    match requirement {
96        MacroKind::Bang => candidate.contains(MacroKinds::BANG),
97        MacroKind::Attr | MacroKind::Derive => {
98            candidate.intersects(MacroKinds::ATTR | MacroKinds::DERIVE)
99        }
100    }
101}
102
103// We don't want to format a path using pretty-printing,
104// `format!("{}", path)`, because that tries to insert
105// line-breaks and is slow.
106fn fast_print_path(path: &ast::Path) -> Symbol {
107    if let [segment] = path.segments.as_slice() {
108        segment.ident.name
109    } else {
110        let mut path_str = String::with_capacity(64);
111        for (i, segment) in path.segments.iter().enumerate() {
112            if i != 0 {
113                path_str.push_str("::");
114            }
115            if segment.ident.name != kw::PathRoot {
116                path_str.push_str(segment.ident.as_str())
117            }
118        }
119        Symbol::intern(&path_str)
120    }
121}
122
123pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
124    let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
125    registered_tools_ast(tcx.dcx(), pre_configured_attrs)
126}
127
128pub fn registered_tools_ast(
129    dcx: DiagCtxtHandle<'_>,
130    pre_configured_attrs: &[ast::Attribute],
131) -> RegisteredTools {
132    let mut registered_tools = RegisteredTools::default();
133    for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
134        for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
135            match meta_item_inner.ident() {
136                Some(ident) => {
137                    if let Some(old_ident) = registered_tools.replace(ident) {
138                        dcx.emit_err(errors::ToolWasAlreadyRegistered {
139                            span: ident.span,
140                            tool: ident,
141                            old_ident_span: old_ident.span,
142                        });
143                    }
144                }
145                None => {
146                    dcx.emit_err(errors::ToolOnlyAcceptsIdentifiers {
147                        span: meta_item_inner.span(),
148                        tool: sym::register_tool,
149                    });
150                }
151            }
152        }
153    }
154    // We implicitly add `rustfmt`, `clippy`, `diagnostic`, `miri` and `rust_analyzer` to known
155    // tools, but it's not an error to register them explicitly.
156    let predefined_tools =
157        [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
158    registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
159    registered_tools
160}
161
162impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
163    fn next_node_id(&mut self) -> NodeId {
164        self.next_node_id()
165    }
166
167    fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
168        self.invocation_parents[&id].parent_def
169    }
170
171    fn mark_scope_with_compile_error(&mut self, id: NodeId) {
172        if let Some(id) = self.opt_local_def_id(id)
173            && self.tcx.def_kind(id).is_module_like()
174        {
175            self.mods_with_parse_errors.insert(id.to_def_id());
176        }
177    }
178
179    fn resolve_dollar_crates(&self) {
180        hygiene::update_dollar_crate_names(|ctxt| {
181            let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
182            match self.resolve_crate_root(ident).kind {
183                ModuleKind::Def(.., name) if let Some(name) = name => name,
184                _ => kw::Crate,
185            }
186        });
187    }
188
189    fn visit_ast_fragment_with_placeholders(
190        &mut self,
191        expansion: LocalExpnId,
192        fragment: &AstFragment,
193    ) {
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(self).remove(&expansion);
201        if let Some(unexpanded_invocations) =
202            self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
203        {
204            unexpanded_invocations.remove(&expansion);
205        }
206    }
207
208    fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
209        if self.builtin_macros.insert(name, ext).is_some() {
210            self.dcx().bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("built-in macro `{0}` was already registered",
                name))
    })format!("built-in macro `{name}` was already registered"));
211        }
212    }
213
214    // Create a new Expansion with a definition site of the provided module, or
215    // a fake empty `#[no_implicit_prelude]` module if no module is provided.
216    fn expansion_for_ast_pass(
217        &mut self,
218        call_site: Span,
219        pass: AstPass,
220        features: &[Symbol],
221        parent_module_id: Option<NodeId>,
222    ) -> LocalExpnId {
223        let parent_module =
224            parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
225        let expn_id = LocalExpnId::fresh(
226            ExpnData::allow_unstable(
227                ExpnKind::AstPass(pass),
228                call_site,
229                self.tcx.sess.edition(),
230                features.into(),
231                None,
232                parent_module,
233            ),
234            self.create_stable_hashing_context(),
235        );
236
237        let parent_scope =
238            parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
239        self.ast_transform_scopes.insert(expn_id, parent_scope);
240
241        expn_id
242    }
243
244    fn resolve_imports(&mut self) {
245        self.resolve_imports()
246    }
247
248    fn resolve_macro_invocation(
249        &mut self,
250        invoc: &Invocation,
251        eager_expansion_root: LocalExpnId,
252        force: bool,
253    ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
254        let invoc_id = invoc.expansion_data.id;
255        let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
256            Some(parent_scope) => *parent_scope,
257            None => {
258                // If there's no entry in the table, then we are resolving an eagerly expanded
259                // macro, which should inherit its parent scope from its eager expansion root -
260                // the macro that requested this eager expansion.
261                let parent_scope = *self
262                    .invocation_parent_scopes
263                    .get(&eager_expansion_root)
264                    .expect("non-eager expansion without a parent scope");
265                self.invocation_parent_scopes.insert(invoc_id, parent_scope);
266                parent_scope
267            }
268        };
269
270        let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
271        let (path, kind) = match invoc.kind {
272            InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
273                derives = self.arenas.alloc_ast_paths(attr_derives);
274                inner_attr = attr.style == ast::AttrStyle::Inner;
275                (&attr.get_normal_item().path, MacroKind::Attr)
276            }
277            InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
278            InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
279            InvocationKind::GlobDelegation { ref item, .. } => {
280                let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
281                deleg_impl = Some(self.invocation_parent(invoc_id));
282                // It is sufficient to consider glob delegation a bang macro for now.
283                (&deleg.prefix, MacroKind::Bang)
284            }
285        };
286
287        // Derives are not included when `invocations` are collected, so we have to add them here.
288        let parent_scope = &ParentScope { derives, ..parent_scope };
289        let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
290        let node_id = invoc.expansion_data.lint_node_id;
291        // This is a heuristic, but it's good enough for the lint.
292        let looks_like_invoc_in_mod_inert_attr = self
293            .invocation_parents
294            .get(&invoc_id)
295            .or_else(|| self.invocation_parents.get(&eager_expansion_root))
296            .filter(|&&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
297                in_attr
298                    && invoc.fragment_kind == AstFragmentKind::Expr
299                    && self.tcx.def_kind(mod_def_id) == DefKind::Mod
300            })
301            .map(|&InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
302        let sugg_span = match &invoc.kind {
303            InvocationKind::Attr { item: Annotatable::Item(item), .. }
304                if !item.span.from_expansion() =>
305            {
306                Some(item.span.shrink_to_lo())
307            }
308            _ => None,
309        };
310        let (ext, res) = self.smart_resolve_macro_path(
311            path,
312            kind,
313            supports_macro_expansion,
314            inner_attr,
315            parent_scope,
316            node_id,
317            force,
318            deleg_impl,
319            looks_like_invoc_in_mod_inert_attr,
320            sugg_span,
321        )?;
322
323        let span = invoc.span();
324        let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
325        invoc_id.set_expn_data(
326            ext.expn_data(
327                parent_scope.expansion,
328                span,
329                fast_print_path(path),
330                kind,
331                def_id,
332                def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
333            ),
334            self.create_stable_hashing_context(),
335        );
336
337        Ok(ext)
338    }
339
340    fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
341        if let Some(rules) = self.unused_macro_rules.get_mut(&id) {
342            rules.remove(rule_i);
343        }
344    }
345
346    fn check_unused_macros(&mut self) {
347        for (_, &(node_id, ident)) in self.unused_macros.iter() {
348            self.lint_buffer.buffer_lint(
349                UNUSED_MACROS,
350                node_id,
351                ident.span,
352                errors::UnusedMacroDefinition { name: ident.name },
353            );
354            // Do not report unused individual rules if the entire macro is unused
355            self.unused_macro_rules.swap_remove(&node_id);
356        }
357
358        for (&node_id, unused_arms) in self.unused_macro_rules.iter() {
359            if unused_arms.is_empty() {
360                continue;
361            }
362            let def_id = self.local_def_id(node_id);
363            let m = &self.local_macro_map[&def_id];
364            let SyntaxExtensionKind::MacroRules(ref m) = m.ext.kind else {
365                continue;
366            };
367            for arm_i in unused_arms.iter() {
368                if let Some((ident, rule_span)) = m.get_unused_rule(arm_i) {
369                    self.lint_buffer.buffer_lint(
370                        UNUSED_MACRO_RULES,
371                        node_id,
372                        rule_span,
373                        errors::MacroRuleNeverUsed { n: arm_i + 1, name: ident.name },
374                    );
375                }
376            }
377        }
378    }
379
380    fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
381        self.containers_deriving_copy.contains(&expn_id)
382    }
383
384    fn resolve_derives(
385        &mut self,
386        expn_id: LocalExpnId,
387        force: bool,
388        derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
389    ) -> Result<(), Indeterminate> {
390        // Block expansion of the container until we resolve all derives in it.
391        // This is required for two reasons:
392        // - Derive helper attributes are in scope for the item to which the `#[derive]`
393        //   is applied, so they have to be produced by the container's expansion rather
394        //   than by individual derives.
395        // - Derives in the container need to know whether one of them is a built-in `Copy`.
396        //   (But see the comment mentioning #124794 below.)
397        // Temporarily take the data to avoid borrow checker conflicts.
398        let mut derive_data = mem::take(&mut self.derive_data);
399        let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
400            resolutions: derive_paths(),
401            helper_attrs: Vec::new(),
402            has_derive_copy: false,
403        });
404        let parent_scope = self.invocation_parent_scopes[&expn_id];
405        for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
406            if resolution.exts.is_none() {
407                resolution.exts = Some(
408                    match self.cm().resolve_derive_macro_path(
409                        &resolution.path,
410                        &parent_scope,
411                        force,
412                        None,
413                    ) {
414                        Ok((Some(ext), _)) => {
415                            if !ext.helper_attrs.is_empty() {
416                                let span = resolution.path.segments.last().unwrap().ident.span;
417                                let ctxt = Macros20NormalizedSyntaxContext::new(span.ctxt());
418                                entry.helper_attrs.extend(
419                                    ext.helper_attrs
420                                        .iter()
421                                        .map(|&name| (i, IdentKey { name, ctxt }, span)),
422                                );
423                            }
424                            entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
425                            ext
426                        }
427                        Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
428                        Err(Determinacy::Undetermined) => {
429                            if !self.derive_data.is_empty() {
    ::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
430                            self.derive_data = derive_data;
431                            return Err(Indeterminate);
432                        }
433                    },
434                );
435            }
436        }
437        // Sort helpers in a stable way independent from the derive resolution order.
438        entry.helper_attrs.sort_by_key(|(i, ..)| *i);
439        let helper_attrs = entry
440            .helper_attrs
441            .iter()
442            .map(|&(_, ident, orig_ident_span)| {
443                let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
444                let decl = self.arenas.new_pub_def_decl(res, orig_ident_span, expn_id);
445                (ident, orig_ident_span, decl)
446            })
447            .collect();
448        self.helper_attrs.insert(expn_id, helper_attrs);
449        // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
450        // has `Copy`, to support `#[derive(Copy, Clone)]`, `#[derive(Clone, Copy)]`, or
451        // `#[derive(Copy)] #[derive(Clone)]`. We do this because the code generated for
452        // `derive(Clone)` changes if `derive(Copy)` is also present.
453        //
454        // FIXME(#124794): unfortunately this doesn't work with `#[derive(Clone)] #[derive(Copy)]`.
455        // When the `Clone` impl is generated the `#[derive(Copy)]` hasn't been processed and
456        // `has_derive_copy` hasn't been set yet.
457        if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
458            self.containers_deriving_copy.insert(expn_id);
459        }
460        if !self.derive_data.is_empty() {
    ::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
461        self.derive_data = derive_data;
462        Ok(())
463    }
464
465    fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
466        self.derive_data.remove(&expn_id).map(|data| data.resolutions)
467    }
468
469    // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
470    // Returns true if the path can certainly be resolved in one of three namespaces,
471    // returns false if the path certainly cannot be resolved in any of the three namespaces.
472    // Returns `Indeterminate` if we cannot give a certain answer yet.
473    fn cfg_accessible(
474        &mut self,
475        expn_id: LocalExpnId,
476        path: &ast::Path,
477    ) -> Result<bool, Indeterminate> {
478        self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
479    }
480
481    fn macro_accessible(
482        &mut self,
483        expn_id: LocalExpnId,
484        path: &ast::Path,
485    ) -> Result<bool, Indeterminate> {
486        self.path_accessible(expn_id, path, &[MacroNS])
487    }
488
489    fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
490        self.cstore().get_proc_macro_quoted_span_untracked(self.tcx, krate, id)
491    }
492
493    fn declare_proc_macro(&mut self, id: NodeId) {
494        self.proc_macros.push(self.local_def_id(id))
495    }
496
497    fn append_stripped_cfg_item(
498        &mut self,
499        parent_node: NodeId,
500        ident: Ident,
501        cfg: CfgEntry,
502        cfg_span: Span,
503    ) {
504        self.stripped_cfg_items.push(StrippedCfgItem {
505            parent_module: parent_node,
506            ident,
507            cfg: (cfg, cfg_span),
508        });
509    }
510
511    fn registered_tools(&self) -> &RegisteredTools {
512        self.registered_tools
513    }
514
515    fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
516        self.glob_delegation_invoc_ids.insert(invoc_id);
517    }
518
519    fn glob_delegation_suffixes(
520        &self,
521        trait_def_id: DefId,
522        impl_def_id: LocalDefId,
523    ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
524        let target_trait = self.expect_module(trait_def_id);
525        if !target_trait.unexpanded_invocations.borrow().is_empty() {
526            return Err(Indeterminate);
527        }
528        // FIXME: Instead of waiting try generating all trait methods, and pruning
529        // the shadowed ones a bit later, e.g. when all macro expansion completes.
530        // Pros: expansion will be stuck less (but only in exotic cases), the implementation may be
531        // less hacky.
532        // Cons: More code is generated just to be deleted later, deleting already created `DefId`s
533        // may be nontrivial.
534        if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
535            && !unexpanded_invocations.is_empty()
536        {
537            return Err(Indeterminate);
538        }
539
540        let mut idents = Vec::new();
541        target_trait.for_each_child(self, |this, ident, orig_ident_span, ns, _binding| {
542            // FIXME: Adjust hygiene for idents from globs, like for glob imports.
543            if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
544                && overriding_keys.contains(&BindingKey::new(ident, ns))
545            {
546                // The name is overridden, do not produce it from the glob delegation.
547            } else {
548                idents.push((ident.orig(orig_ident_span), None));
549            }
550        });
551        Ok(idents)
552    }
553
554    fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
555        self.impl_trait_names.insert(id, name);
556    }
557}
558
559impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
560    /// Resolve macro path with error reporting and recovery.
561    /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
562    /// for better error recovery.
563    fn smart_resolve_macro_path(
564        &mut self,
565        path: &ast::Path,
566        kind: MacroKind,
567        supports_macro_expansion: SupportsMacroExpansion,
568        inner_attr: bool,
569        parent_scope: &ParentScope<'ra>,
570        node_id: NodeId,
571        force: bool,
572        deleg_impl: Option<LocalDefId>,
573        invoc_in_mod_inert_attr: Option<LocalDefId>,
574        suggestion_span: Option<Span>,
575    ) -> Result<(Arc<SyntaxExtension>, Res), Indeterminate> {
576        let (ext, res) = match self.cm().resolve_macro_or_delegation_path(
577            path,
578            kind,
579            parent_scope,
580            force,
581            deleg_impl,
582            invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
583            None,
584            suggestion_span,
585        ) {
586            Ok((Some(ext), res)) => (ext, res),
587            Ok((None, res)) => (self.dummy_ext(kind), res),
588            Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
589            Err(Determinacy::Undetermined) => return Err(Indeterminate),
590        };
591
592        // Everything below is irrelevant to glob delegation, take a shortcut.
593        if deleg_impl.is_some() {
594            if !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Err | Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
595                self.dcx().emit_err(MacroExpectedFound {
596                    span: path.span,
597                    expected: "trait",
598                    article: "a",
599                    found: res.descr(),
600                    macro_path: &pprust::path_to_string(path),
601                    remove_surrounding_derive: None,
602                    add_as_non_derive: None,
603                });
604                return Ok((self.dummy_ext(kind), Res::Err));
605            }
606
607            return Ok((ext, res));
608        }
609
610        // Report errors for the resolved macro.
611        for segment in &path.segments {
612            if let Some(args) = &segment.args {
613                self.dcx().emit_err(errors::GenericArgumentsInMacroPath { span: args.span() });
614            }
615            if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
616                self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
617                    span: segment.ident.span,
618                });
619            }
620        }
621
622        match res {
623            Res::Def(DefKind::Macro(_), def_id) => {
624                if let Some(def_id) = def_id.as_local() {
625                    self.unused_macros.swap_remove(&def_id);
626                    if self.proc_macro_stubs.contains(&def_id) {
627                        self.dcx().emit_err(errors::ProcMacroSameCrate {
628                            span: path.span,
629                            is_test: self.tcx.sess.is_test_crate(),
630                        });
631                    }
632                }
633            }
634            Res::NonMacroAttr(..) | Res::Err => {}
635            _ => {
    ::core::panicking::panic_fmt(format_args!("expected `DefKind::Macro` or `Res::NonMacroAttr`"));
}panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
636        };
637
638        self.check_stability_and_deprecation(&ext, path, node_id);
639
640        let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
641            Some((kind.article(), kind.descr_expected()))
642        } else if #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(..) => true,
    _ => false,
}matches!(res, Res::Def(..)) {
643            match supports_macro_expansion {
644                SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
645                SupportsMacroExpansion::Yes { supports_inner_attrs } => {
646                    if inner_attr && !supports_inner_attrs {
647                        Some(("a", "non-macro inner attribute"))
648                    } else {
649                        None
650                    }
651                }
652            }
653        } else {
654            None
655        };
656        if let Some((article, expected)) = unexpected_res {
657            let path_str = pprust::path_to_string(path);
658
659            let mut err = MacroExpectedFound {
660                span: path.span,
661                expected,
662                article,
663                found: res.descr(),
664                macro_path: &path_str,
665                remove_surrounding_derive: None,
666                add_as_non_derive: None,
667            };
668
669            // Suggest moving the macro out of the derive() if the macro isn't Derive
670            if !path.span.from_expansion()
671                && kind == MacroKind::Derive
672                && !ext.macro_kinds().contains(MacroKinds::DERIVE)
673                && ext.macro_kinds().contains(MacroKinds::ATTR)
674            {
675                err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
676                err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
677            }
678
679            self.dcx().emit_err(err);
680
681            return Ok((self.dummy_ext(kind), Res::Err));
682        }
683
684        // We are trying to avoid reporting this error if other related errors were reported.
685        if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
686            let is_macro = match res {
687                Res::Def(..) => true,
688                Res::NonMacroAttr(..) => false,
689                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
690            };
691            let msg = if is_macro {
692                "inner macro attributes are unstable"
693            } else {
694                "custom inner attributes are unstable"
695            };
696            feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
697        }
698
699        const DIAG_ATTRS: &[Symbol] =
700            &[sym::on_unimplemented, sym::do_not_recommend, sym::on_const];
701
702        if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
703            && let [namespace, attribute, ..] = &*path.segments
704            && namespace.ident.name == sym::diagnostic
705            && !DIAG_ATTRS.contains(&attribute.ident.name)
706        {
707            let span = attribute.span();
708
709            let typo = find_best_match_for_name(DIAG_ATTRS, attribute.ident.name, Some(5))
710                .map(|typo_name| errors::UnknownDiagnosticAttributeTypoSugg { span, typo_name });
711
712            self.tcx.sess.psess.buffer_lint(
713                UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
714                span,
715                node_id,
716                errors::UnknownDiagnosticAttribute { typo },
717            );
718        }
719
720        Ok((ext, res))
721    }
722
723    pub(crate) fn resolve_derive_macro_path<'r>(
724        self: CmResolver<'r, 'ra, 'tcx>,
725        path: &ast::Path,
726        parent_scope: &ParentScope<'ra>,
727        force: bool,
728        ignore_import: Option<Import<'ra>>,
729    ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
730        self.resolve_macro_or_delegation_path(
731            path,
732            MacroKind::Derive,
733            parent_scope,
734            force,
735            None,
736            None,
737            ignore_import,
738            None,
739        )
740    }
741
742    fn resolve_macro_or_delegation_path<'r>(
743        mut self: CmResolver<'r, 'ra, 'tcx>,
744        ast_path: &ast::Path,
745        kind: MacroKind,
746        parent_scope: &ParentScope<'ra>,
747        force: bool,
748        deleg_impl: Option<LocalDefId>,
749        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
750        ignore_import: Option<Import<'ra>>,
751        suggestion_span: Option<Span>,
752    ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
753        let path_span = ast_path.span;
754        let mut path = Segment::from_path(ast_path);
755
756        // Possibly apply the macro helper hack
757        if deleg_impl.is_none()
758            && kind == MacroKind::Bang
759            && let [segment] = path.as_slice()
760            && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
761        {
762            let root = Ident::new(kw::DollarCrate, segment.ident.span);
763            path.insert(0, Segment::from_ident(root));
764        }
765
766        let res = if deleg_impl.is_some() || path.len() > 1 {
767            let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
768            let res = match self.reborrow().maybe_resolve_path(
769                &path,
770                Some(ns),
771                parent_scope,
772                ignore_import,
773            ) {
774                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
775                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
776                PathResult::NonModule(..)
777                | PathResult::Indeterminate
778                | PathResult::Failed { .. } => Err(Determinacy::Determined),
779                PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
780                    Ok(module.res().unwrap())
781                }
782                PathResult::Module(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
783            };
784
785            self.multi_segment_macro_resolutions.borrow_mut(&self).push((
786                path,
787                path_span,
788                kind,
789                *parent_scope,
790                res.ok(),
791                ns,
792            ));
793
794            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
795            res
796        } else {
797            let binding = self.reborrow().resolve_ident_in_scope_set(
798                path[0].ident,
799                ScopeSet::Macro(kind),
800                parent_scope,
801                None,
802                None,
803                None,
804            );
805            let binding = binding.map_err(|determinacy| {
806                Determinacy::determined(determinacy == Determinacy::Determined || force)
807            });
808            if let Err(Determinacy::Undetermined) = binding {
809                return Err(Determinacy::Undetermined);
810            }
811
812            self.single_segment_macro_resolutions.borrow_mut(&self).push((
813                path[0].ident,
814                kind,
815                *parent_scope,
816                binding.ok(),
817                suggestion_span,
818            ));
819
820            let res = binding.map(|binding| binding.res());
821            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
822            self.reborrow().report_out_of_scope_macro_calls(
823                ast_path,
824                parent_scope,
825                invoc_in_mod_inert_attr,
826                binding.ok(),
827            );
828            res
829        };
830
831        let res = res?;
832        let ext = match deleg_impl {
833            Some(impl_def_id) => match res {
834                def::Res::Def(DefKind::Trait, def_id) => {
835                    let edition = self.tcx.sess.edition();
836                    Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
837                }
838                _ => None,
839            },
840            None => self.get_macro(res).map(|macro_data| Arc::clone(&macro_data.ext)),
841        };
842        Ok((ext, res))
843    }
844
845    pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
846        let check_consistency = |this: &Self,
847                                 path: &[Segment],
848                                 span,
849                                 kind: MacroKind,
850                                 initial_res: Option<Res>,
851                                 res: Res| {
852            if let Some(initial_res) = initial_res {
853                if res != initial_res {
854                    if this.ambiguity_errors.is_empty() {
855                        // Make sure compilation does not succeed if preferred macro resolution
856                        // has changed after the macro had been expanded. In theory all such
857                        // situations should be reported as errors, so this is a bug.
858                        this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
859                    }
860                }
861            } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
862                // It's possible that the macro was unresolved (indeterminate) and silently
863                // expanded into a dummy fragment for recovery during expansion.
864                // Now, post-expansion, the resolution may succeed, but we can't change the
865                // past and need to report an error.
866                // However, non-speculative `resolve_path` can successfully return private items
867                // even if speculative `resolve_path` returned nothing previously, so we skip this
868                // less informative error if no other error is reported elsewhere.
869
870                let err = this.dcx().create_err(CannotDetermineMacroResolution {
871                    span,
872                    kind: kind.descr(),
873                    path: Segment::names_to_string(path),
874                });
875                err.stash(span, StashKey::UndeterminedMacroResolution);
876            }
877        };
878
879        let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
880        for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
881            // FIXME: Path resolution will ICE if segment IDs present.
882            for seg in &mut path {
883                seg.id = None;
884            }
885            match self.cm().resolve_path(
886                &path,
887                Some(ns),
888                &parent_scope,
889                Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
890                None,
891                None,
892            ) {
893                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
894                    check_consistency(self, &path, path_span, kind, initial_res, res)
895                }
896                // This may be a trait for glob delegation expansions.
897                PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
898                    self,
899                    &path,
900                    path_span,
901                    kind,
902                    initial_res,
903                    module.res().unwrap(),
904                ),
905                path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
906                    let mut suggestion = None;
907                    let (span, label, module, segment) =
908                        if let PathResult::Failed { span, label, module, segment_name, .. } =
909                            path_res
910                        {
911                            // try to suggest if it's not a macro, maybe a function
912                            if let PathResult::NonModule(partial_res) = self
913                                .cm()
914                                .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
915                                && partial_res.unresolved_segments() == 0
916                            {
917                                let sm = self.tcx.sess.source_map();
918                                let exclamation_span = sm.next_point(span);
919                                suggestion = Some((
920                                    <[_]>::into_vec(::alloc::boxed::box_new([(exclamation_span, "".to_string())]))vec![(exclamation_span, "".to_string())],
921                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is not a macro, but a {1}, try to remove `!`",
                Segment::names_to_string(&path),
                partial_res.base_res().descr()))
    })format!(
922                                        "{} is not a macro, but a {}, try to remove `!`",
923                                        Segment::names_to_string(&path),
924                                        partial_res.base_res().descr()
925                                    ),
926                                    Applicability::MaybeIncorrect,
927                                ));
928                            }
929                            (span, label, module, segment_name)
930                        } else {
931                            (
932                                path_span,
933                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("partially resolved path in {0} {1}",
                kind.article(), kind.descr()))
    })format!(
934                                    "partially resolved path in {} {}",
935                                    kind.article(),
936                                    kind.descr()
937                                ),
938                                None,
939                                path.last().map(|segment| segment.ident.name).unwrap(),
940                            )
941                        };
942                    self.report_error(
943                        span,
944                        ResolutionError::FailedToResolve {
945                            segment: Some(segment),
946                            label,
947                            suggestion,
948                            module,
949                        },
950                    );
951                }
952                PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
953            }
954        }
955
956        let macro_resolutions = self.single_segment_macro_resolutions.take(self);
957        for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
958            match self.cm().resolve_ident_in_scope_set(
959                ident,
960                ScopeSet::Macro(kind),
961                &parent_scope,
962                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
963                None,
964                None,
965            ) {
966                Ok(binding) => {
967                    let initial_res = initial_binding.map(|initial_binding| {
968                        self.record_use(ident, initial_binding, Used::Other);
969                        initial_binding.res()
970                    });
971                    let res = binding.res();
972                    let seg = Segment::from_ident(ident);
973                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
974                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
975                        let node_id = self
976                            .invocation_parents
977                            .get(&parent_scope.expansion)
978                            .map_or(ast::CRATE_NODE_ID, |parent| {
979                                self.def_id_to_node_id(parent.parent_def)
980                            });
981                        self.lint_buffer.buffer_lint(
982                            LEGACY_DERIVE_HELPERS,
983                            node_id,
984                            ident.span,
985                            errors::LegacyDeriveHelpers { span: binding.span },
986                        );
987                    }
988                }
989                Err(..) => {
990                    let expected = kind.descr_expected();
991
992                    let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
993                        span: ident.span,
994                        expected,
995                        ident,
996                    });
997                    self.unresolved_macro_suggestions(
998                        &mut err,
999                        kind,
1000                        &parent_scope,
1001                        ident,
1002                        krate,
1003                        sugg_span,
1004                    );
1005                    err.emit();
1006                }
1007            }
1008        }
1009
1010        let builtin_attrs = mem::take(&mut self.builtin_attrs);
1011        for (ident, parent_scope) in builtin_attrs {
1012            let _ = self.cm().resolve_ident_in_scope_set(
1013                ident,
1014                ScopeSet::Macro(MacroKind::Attr),
1015                &parent_scope,
1016                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1017                None,
1018                None,
1019            );
1020        }
1021    }
1022
1023    fn check_stability_and_deprecation(
1024        &mut self,
1025        ext: &SyntaxExtension,
1026        path: &ast::Path,
1027        node_id: NodeId,
1028    ) {
1029        let span = path.span;
1030        if let Some(stability) = &ext.stability
1031            && let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } =
1032                stability.level
1033        {
1034            let feature = stability.feature;
1035
1036            let is_allowed =
1037                |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1038            let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1039            if !is_allowed(feature) && !allowed_by_implication {
1040                let lint_buffer = &mut self.lint_buffer;
1041                let soft_handler = |lint, span, msg: String| {
1042                    lint_buffer.buffer_lint(
1043                        lint,
1044                        node_id,
1045                        span,
1046                        // FIXME make this translatable
1047                        errors::UnstableFeature { msg: msg.into() },
1048                    )
1049                };
1050                stability::report_unstable(
1051                    self.tcx.sess,
1052                    feature,
1053                    reason.to_opt_reason(),
1054                    issue,
1055                    None,
1056                    is_soft,
1057                    span,
1058                    soft_handler,
1059                    stability::UnstableKind::Regular,
1060                );
1061            }
1062        }
1063        if let Some(depr) = &ext.deprecation {
1064            let path = pprust::path_to_string(path);
1065            stability::early_report_macro_deprecation(
1066                &mut self.lint_buffer,
1067                depr,
1068                span,
1069                node_id,
1070                path,
1071            );
1072        }
1073    }
1074
1075    fn prohibit_imported_non_macro_attrs(
1076        &self,
1077        decl: Option<Decl<'ra>>,
1078        res: Option<Res>,
1079        span: Span,
1080    ) {
1081        if let Some(Res::NonMacroAttr(kind)) = res {
1082            if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1083                self.dcx().emit_err(errors::CannotUseThroughAnImport {
1084                    span,
1085                    article: kind.article(),
1086                    descr: kind.descr(),
1087                    binding_span: decl.map(|d| d.span),
1088                });
1089            }
1090        }
1091    }
1092
1093    fn report_out_of_scope_macro_calls<'r>(
1094        mut self: CmResolver<'r, 'ra, 'tcx>,
1095        path: &ast::Path,
1096        parent_scope: &ParentScope<'ra>,
1097        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1098        decl: Option<Decl<'ra>>,
1099    ) {
1100        if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1101            && let Some(decl) = decl
1102            // This is a `macro_rules` itself, not some import.
1103            && let DeclKind::Def(res) = decl.kind
1104            && let Res::Def(DefKind::Macro(kinds), def_id) = res
1105            && kinds.contains(MacroKinds::BANG)
1106            // And the `macro_rules` is defined inside the attribute's module,
1107            // so it cannot be in scope unless imported.
1108            && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1109        {
1110            // Try to resolve our ident ignoring `macro_rules` scopes.
1111            // If such resolution is successful and gives the same result
1112            // (e.g. if the macro is re-imported), then silence the lint.
1113            let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1114            let ident = path.segments[0].ident;
1115            let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1116                ident,
1117                ScopeSet::Macro(MacroKind::Bang),
1118                &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1119                None,
1120                None,
1121                None,
1122            );
1123            if let Ok(fallback_binding) = fallback_binding
1124                && fallback_binding.res().opt_def_id() == Some(def_id)
1125            {
1126                // Silence `unused_imports` on the fallback import as well.
1127                self.get_mut().record_use(ident, fallback_binding, Used::Other);
1128            } else {
1129                let location = match parent_scope.module.kind {
1130                    ModuleKind::Def(kind, def_id, name) => {
1131                        if let Some(name) = name {
1132                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", kind.descr(def_id),
                name))
    })format!("{} `{name}`", kind.descr(def_id))
1133                        } else {
1134                            "the crate root".to_string()
1135                        }
1136                    }
1137                    ModuleKind::Block => "this scope".to_string(),
1138                };
1139                self.tcx.sess.psess.buffer_lint(
1140                    OUT_OF_SCOPE_MACRO_CALLS,
1141                    path.span,
1142                    node_id,
1143                    errors::OutOfScopeMacroCalls {
1144                        span: path.span,
1145                        path: pprust::path_to_string(path),
1146                        location,
1147                    },
1148                );
1149            }
1150        }
1151    }
1152
1153    pub(crate) fn check_reserved_macro_name(&self, name: Symbol, span: Span, res: Res) {
1154        // Reserve some names that are not quite covered by the general check
1155        // performed on `Resolver::builtin_attrs`.
1156        if name == sym::cfg || name == sym::cfg_attr {
1157            let macro_kinds = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kinds());
1158            if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1159                self.dcx().emit_err(errors::NameReservedInAttributeNamespace { span, ident: name });
1160            }
1161        }
1162    }
1163
1164    /// Compile the macro into a `SyntaxExtension` and its rule spans.
1165    ///
1166    /// Possibly replace its expander to a pre-defined one for built-in macros.
1167    pub(crate) fn compile_macro(
1168        &self,
1169        macro_def: &ast::MacroDef,
1170        ident: Ident,
1171        attrs: &[rustc_hir::Attribute],
1172        span: Span,
1173        node_id: NodeId,
1174        edition: Edition,
1175    ) -> MacroData {
1176        let (mut ext, mut nrules) = compile_declarative_macro(
1177            self.tcx.sess,
1178            self.tcx.features(),
1179            macro_def,
1180            ident,
1181            attrs,
1182            span,
1183            node_id,
1184            edition,
1185        );
1186
1187        if let Some(builtin_name) = ext.builtin_name {
1188            // The macro was marked with `#[rustc_builtin_macro]`.
1189            if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1190                // The macro is a built-in, replace its expander function
1191                // while still taking everything else from the source code.
1192                ext.kind = builtin_ext_kind.clone();
1193                nrules = 0;
1194            } else {
1195                self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1196            }
1197        }
1198
1199        MacroData { ext: Arc::new(ext), nrules, macro_rules: macro_def.macro_rules }
1200    }
1201
1202    fn path_accessible(
1203        &mut self,
1204        expn_id: LocalExpnId,
1205        path: &ast::Path,
1206        namespaces: &[Namespace],
1207    ) -> Result<bool, Indeterminate> {
1208        let span = path.span;
1209        let path = &Segment::from_path(path);
1210        let parent_scope = self.invocation_parent_scopes[&expn_id];
1211
1212        let mut indeterminate = false;
1213        for ns in namespaces {
1214            match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1215                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1216                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1217                    return Ok(true);
1218                }
1219                PathResult::NonModule(..) |
1220                // HACK(Urgau): This shouldn't be necessary
1221                PathResult::Failed { is_error_from_last_segment: false, .. } => {
1222                    self.dcx()
1223                        .emit_err(errors::CfgAccessibleUnsure { span });
1224
1225                    // If we get a partially resolved NonModule in one namespace, we should get the
1226                    // same result in any other namespaces, so we can return early.
1227                    return Ok(false);
1228                }
1229                PathResult::Indeterminate => indeterminate = true,
1230                // We can only be sure that a path doesn't exist after having tested all the
1231                // possibilities, only at that time we can return false.
1232                PathResult::Failed { .. } => {}
1233                PathResult::Module(_) => { ::core::panicking::panic_fmt(format_args!("unexpected path resolution")); }panic!("unexpected path resolution"),
1234            }
1235        }
1236
1237        if indeterminate {
1238            return Err(Indeterminate);
1239        }
1240
1241        Ok(false)
1242    }
1243}