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