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