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 parent_macro_rules_scope ident orig_ident_span",
            &self.decl, &self.parent_macro_rules_scope, &self.ident,
            &&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_struct_field1_finish(f, "Def",
                    &__self_0),
            Self::Invocation(__self_0) =>
                ::core::fmt::Formatter::debug_struct_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::unreachable_default_msg()unreachable!() };
303                let DelegationSuffixes::Glob(star_span) = deleg.suffixes else { ::core::panicking::unreachable_default_msg()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                if kind == MacroKind::Attr
696                    && let [tool, _second, ..] = path.segments.as_slice()
697                    && self.registered_attr_tool_decls.contains_key(&IdentKey::new(tool.ident))
698                {
699                    self.dcx().emit_err(diagnostics::ToolAttrAmbiguity {
700                        path_span: path.span,
701                        attr_path: pprust::path_to_string(path),
702                        tool: tool.ident.name,
703                    });
704                }
705            }
706            Res::NonMacroAttr(..) | Res::Err => {}
707            _ => {
    ::core::panicking::panic_fmt(format_args!("expected `DefKind::Macro` or `Res::NonMacroAttr`"));
}panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
708        };
709
710        self.check_stability_and_deprecation(&ext, path, node_id);
711
712        let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
713            Some((kind.article(), kind.descr_expected()))
714        } else if #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(..) => true,
    _ => false,
}matches!(res, Res::Def(..)) {
715            match supports_macro_expansion {
716                SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
717                SupportsMacroExpansion::Yes { supports_inner_attrs } => {
718                    if inner_attr && !supports_inner_attrs {
719                        Some(("a", "non-macro inner attribute"))
720                    } else {
721                        None
722                    }
723                }
724            }
725        } else {
726            None
727        };
728        if let Some((article, expected)) = unexpected_res {
729            let path_str = pprust::path_to_string(path);
730
731            let mut err = MacroExpectedFound {
732                span: path.span,
733                expected,
734                article,
735                found: res.descr(),
736                macro_path: &path_str,
737                remove_surrounding_derive: None,
738                add_as_non_derive: None,
739            };
740
741            // Suggest moving the macro out of the derive() if the macro isn't Derive
742            if !path.span.from_expansion()
743                && kind == MacroKind::Derive
744                && !ext.macro_kinds().contains(MacroKinds::DERIVE)
745                && ext.macro_kinds().contains(MacroKinds::ATTR)
746            {
747                err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
748                err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
749            }
750
751            self.dcx().emit_err(err);
752
753            return Ok((self.dummy_ext(kind), Res::Err));
754        }
755
756        // We are trying to avoid reporting this error if other related errors were reported.
757        if res != Res::Err && inner_attr && !self.features.custom_inner_attributes() {
758            let is_macro = match res {
759                Res::Def(..) => true,
760                Res::NonMacroAttr(..) => false,
761                _ => ::core::panicking::unreachable_default_msg()unreachable!(),
762            };
763            let msg = if is_macro {
764                "inner macro attributes are unstable"
765            } else {
766                "custom inner attributes are unstable"
767            };
768            feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
769        }
770
771        Ok((ext, res))
772    }
773
774    pub(crate) fn resolve_derive_macro_path<'r>(
775        self: CmResolver<'r, 'ra, 'tcx>,
776        path: &ast::Path,
777        parent_scope: &ParentScope<'ra>,
778        force: bool,
779        ignore_import: Option<Import<'ra>>,
780    ) -> Result<(Option<&'r Arc<SyntaxExtension>>, Res), Determinacy> {
781        self.resolve_macro_or_delegation_path(
782            path,
783            MacroKind::Derive,
784            parent_scope,
785            force,
786            None,
787            None,
788            ignore_import,
789            None,
790        )
791    }
792
793    fn resolve_macro_or_delegation_path<'r>(
794        mut self: CmResolver<'r, 'ra, 'tcx>,
795        ast_path: &ast::Path,
796        kind: MacroKind,
797        parent_scope: &ParentScope<'ra>,
798        force: bool,
799        deleg_impl: Option<(LocalDefId, Span)>,
800        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
801        ignore_import: Option<Import<'ra>>,
802        suggestion_span: Option<Span>,
803    ) -> Result<(Option<&'ra Arc<SyntaxExtension>>, Res), Determinacy> {
804        let path_span = ast_path.span;
805        let mut path = Segment::from_path(ast_path);
806
807        // Possibly apply the macro helper hack
808        if deleg_impl.is_none()
809            && kind == MacroKind::Bang
810            && let [segment] = path.as_slice()
811            && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
812        {
813            let root = Ident::new(kw::DollarCrate, segment.ident.span);
814            path.insert(0, Segment::from_ident(root));
815        }
816
817        let res = if deleg_impl.is_some() || path.len() > 1 {
818            let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
819            let res = match self.reborrow().maybe_resolve_path(
820                &path,
821                Some(ns),
822                parent_scope,
823                ignore_import,
824            ) {
825                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
826                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
827                PathResult::NonModule(..)
828                | PathResult::Indeterminate
829                | PathResult::Failed { .. } => Err(Determinacy::Determined),
830                PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
831                    Ok(module.res().unwrap())
832                }
833                PathResult::Module(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
834            };
835
836            self.multi_segment_macro_resolutions.borrow_mut_checked(&self).push((
837                path,
838                path_span,
839                kind,
840                *parent_scope,
841                res.ok(),
842                ns,
843            ));
844
845            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
846            res
847        } else {
848            let binding = self.reborrow().resolve_ident_in_scope_set(
849                path[0].ident,
850                ScopeSet::Macro(kind),
851                parent_scope,
852                None,
853                None,
854                None,
855            );
856            let binding = binding.map_err(|determinacy| {
857                Determinacy::determined(determinacy == Determinacy::Determined || force)
858            });
859            if let Err(Determinacy::Undetermined) = binding {
860                return Err(Determinacy::Undetermined);
861            }
862
863            self.single_segment_macro_resolutions.borrow_mut_checked(&self).push((
864                path[0].ident,
865                kind,
866                *parent_scope,
867                binding.ok(),
868                suggestion_span,
869            ));
870
871            let res = binding.map(|binding| binding.res());
872            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
873            self.reborrow().report_out_of_scope_macro_calls(
874                ast_path,
875                parent_scope,
876                invoc_in_mod_inert_attr,
877                binding.ok(),
878            );
879            res
880        };
881
882        let res = res?;
883        let ext = match deleg_impl {
884            Some((impl_def_id, star_span)) => match res {
885                Res::Def(DefKind::Trait, def_id) => {
886                    let edition = self.tcx.sess.edition();
887                    Some(self.arenas.alloc_macro(SyntaxExtension::glob_delegation(
888                        def_id,
889                        impl_def_id,
890                        star_span,
891                        edition,
892                    )))
893                }
894                _ => None,
895            },
896            None => self.get_macro(res),
897        };
898        Ok((ext, res))
899    }
900
901    pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
902        let check_consistency = |this: &Self,
903                                 path: &[Segment],
904                                 span,
905                                 kind: MacroKind,
906                                 initial_res: Option<Res>,
907                                 res: Res| {
908            if let Some(initial_res) = initial_res {
909                if res != initial_res {
910                    if this.ambiguity_errors.is_empty() {
911                        // Make sure compilation does not succeed if preferred macro resolution
912                        // has changed after the macro had been expanded. In theory all such
913                        // situations should be reported as errors, so this is a bug.
914                        this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
915                    }
916                }
917            } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
918                // It's possible that the macro was unresolved (indeterminate) and silently
919                // expanded into a dummy fragment for recovery during expansion.
920                // Now, post-expansion, the resolution may succeed, but we can't change the
921                // past and need to report an error.
922                // However, non-speculative `resolve_path` can successfully return private items
923                // even if speculative `resolve_path` returned nothing previously, so we skip this
924                // less informative error if no other error is reported elsewhere.
925
926                let err = this.dcx().create_err(CannotDetermineMacroResolution {
927                    span,
928                    kind: kind.descr(),
929                    path: Segment::names_to_string(path),
930                });
931                err.stash(span, StashKey::UndeterminedMacroResolution);
932            }
933        };
934
935        let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
936        for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
937            // FIXME: Path resolution will ICE if segment IDs present.
938            for seg in &mut path {
939                seg.id = None;
940            }
941            match self.cm_mut().resolve_path(
942                &path,
943                Some(ns),
944                &parent_scope,
945                Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
946                None,
947                None,
948            ) {
949                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
950                    check_consistency(self, &path, path_span, kind, initial_res, res)
951                }
952                // This may be a trait for glob delegation expansions.
953                PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
954                    self,
955                    &path,
956                    path_span,
957                    kind,
958                    initial_res,
959                    module.res().unwrap(),
960                ),
961                path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
962                    let mut suggestion = None;
963                    let (span, message, label, module, segment, help) = match path_res {
964                        PathResult::Failed {
965                            span, label, module, segment, message, help, ..
966                        } => {
967                            // try to suggest if it's not a macro, maybe a function
968                            if let PathResult::NonModule(partial_res) = self
969                                .cm()
970                                .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
971                                && partial_res.unresolved_segments() == 0
972                            {
973                                let sm = self.tcx.sess.source_map();
974                                let exclamation_span = sm.next_point(span);
975                                suggestion = Some((
976                                    ::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())],
977                                    ::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!(
978                                        "{} is not a macro, but a {}, try to remove `!`",
979                                        Segment::names_to_string(&path),
980                                        partial_res.base_res().descr()
981                                    ),
982                                    Applicability::MaybeIncorrect,
983                                ));
984                            }
985                            (span, message, label, module, segment.name, help)
986                        }
987                        PathResult::NonModule(partial_res) => {
988                            let found_an = partial_res.base_res().article();
989                            let found_descr = partial_res.base_res().descr();
990                            let scope = match &path[..partial_res.unresolved_segments()] {
991                                [.., prev] => {
992                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} `{0}`", prev.ident,
                found_descr))
    })format!("{found_descr} `{}`", prev.ident)
993                                }
994                                _ => found_descr.to_string(),
995                            };
996                            let expected_an = kind.article();
997                            let expected_descr = kind.descr();
998                            let expected_name = path[partial_res.unresolved_segments()].ident;
999
1000                            (
1001                                path_span,
1002                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}",
                expected_descr, expected_name, scope))
    })format!(
1003                                    "cannot find {expected_descr} `{expected_name}` in {scope}"
1004                                ),
1005                                match partial_res.base_res() {
1006                                    Res::Def(
1007                                        DefKind::Mod | DefKind::Macro(..) | DefKind::ExternCrate,
1008                                        _,
1009                                    ) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("partially resolved path in {0} {1}",
                expected_an, expected_descr))
    })format!(
1010                                        "partially resolved path in {expected_an} {expected_descr}",
1011                                    ),
1012                                    _ => ::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!(
1013                                        "{expected_an} {expected_descr} can't exist within \
1014                                         {found_an} {found_descr}"
1015                                    ),
1016                                },
1017                                None,
1018                                path.last().map(|segment| segment.ident.name).unwrap(),
1019                                None,
1020                            )
1021                        }
1022                        _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1023                    };
1024                    self.report_error(
1025                        span,
1026                        ResolutionError::FailedToResolve {
1027                            segment,
1028                            label,
1029                            suggestion,
1030                            help,
1031                            module,
1032                            message,
1033                        },
1034                    );
1035                }
1036                PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::unreachable_default_msg()unreachable!(),
1037            }
1038        }
1039
1040        let macro_resolutions = self.single_segment_macro_resolutions.take(self);
1041        for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
1042            match self.cm_mut().resolve_ident_in_scope_set(
1043                ident,
1044                ScopeSet::Macro(kind),
1045                &parent_scope,
1046                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1047                None,
1048                None,
1049            ) {
1050                Ok(binding) => {
1051                    let initial_res = initial_binding.map(|initial_binding| {
1052                        self.record_use(ident, initial_binding, Used::Other);
1053                        initial_binding.res()
1054                    });
1055                    let res = binding.res();
1056                    let seg = Segment::from_ident(ident);
1057                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
1058                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
1059                        let node_id = self
1060                            .invocation_parents
1061                            .get(&parent_scope.expansion)
1062                            .map_or(ast::CRATE_NODE_ID, |parent| {
1063                                self.def_id_to_node_id(parent.parent_def)
1064                            });
1065                        self.lint_buffer.buffer_lint(
1066                            LEGACY_DERIVE_HELPERS,
1067                            node_id,
1068                            ident.span,
1069                            diagnostics::LegacyDeriveHelpers { span: binding.span },
1070                        );
1071                    }
1072                }
1073                Err(..) => {
1074                    let expected = kind.descr_expected();
1075
1076                    let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
1077                        span: ident.span,
1078                        expected,
1079                        ident,
1080                    });
1081                    self.unresolved_macro_suggestions(
1082                        &mut err,
1083                        kind,
1084                        &parent_scope,
1085                        ident,
1086                        krate,
1087                        sugg_span,
1088                    );
1089                    err.emit();
1090                }
1091            }
1092        }
1093
1094        let builtin_attrs = mem::take(&mut self.builtin_attrs);
1095        for (ident, parent_scope) in builtin_attrs {
1096            let _ = self.cm_mut().resolve_ident_in_scope_set(
1097                ident,
1098                ScopeSet::Macro(MacroKind::Attr),
1099                &parent_scope,
1100                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1101                None,
1102                None,
1103            );
1104        }
1105    }
1106
1107    fn check_stability_and_deprecation(
1108        &mut self,
1109        ext: &SyntaxExtension,
1110        path: &ast::Path,
1111        node_id: NodeId,
1112    ) {
1113        let span = path.span;
1114        if let Some(stability) = &ext.stability
1115            && let StabilityLevel::Unstable { reason, issue, implied_by, .. } = stability.level
1116        {
1117            let feature = stability.feature;
1118
1119            let is_allowed =
1120                |feature| self.features.enabled(feature) || span.allows_unstable(feature);
1121            let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1122            if !is_allowed(feature) && !allowed_by_implication {
1123                stability::report_unstable(
1124                    self.tcx.sess,
1125                    feature,
1126                    reason.to_opt_reason(),
1127                    issue,
1128                    span,
1129                    stability::UnstableKind::Regular,
1130                );
1131            }
1132        }
1133        if let Some(depr) = &ext.deprecation {
1134            let path = pprust::path_to_string(path);
1135            stability::early_report_macro_deprecation(
1136                &mut self.lint_buffer,
1137                depr,
1138                span,
1139                node_id,
1140                path,
1141            );
1142        }
1143    }
1144
1145    fn prohibit_imported_non_macro_attrs(
1146        &self,
1147        decl: Option<Decl<'ra>>,
1148        res: Option<Res>,
1149        span: Span,
1150    ) {
1151        if let Some(Res::NonMacroAttr(kind)) = res {
1152            if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1153                self.dcx().emit_err(diagnostics::CannotUseThroughAnImport {
1154                    span,
1155                    article: kind.article(),
1156                    descr: kind.descr(),
1157                    binding_span: decl.map(|d| d.span),
1158                });
1159            }
1160        }
1161    }
1162
1163    fn report_out_of_scope_macro_calls<'r>(
1164        mut self: CmResolver<'r, 'ra, 'tcx>,
1165        path: &ast::Path,
1166        parent_scope: &ParentScope<'ra>,
1167        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1168        decl: Option<Decl<'ra>>,
1169    ) {
1170        if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1171            && let Some(decl) = decl
1172            // This is a `macro_rules` itself, not some import.
1173            && let DeclKind::Def(res, _) = decl.kind
1174            && let Res::Def(DefKind::Macro(kinds), def_id) = res
1175            && kinds.contains(MacroKinds::BANG)
1176            // And the `macro_rules` is defined inside the attribute's module,
1177            // so it cannot be in scope unless imported.
1178            && self.tcx.is_descendant_of(def_id, mod_def_id)
1179        {
1180            // Try to resolve our ident ignoring `macro_rules` scopes.
1181            // If such resolution is successful and gives the same result
1182            // (e.g. if the macro is re-imported), then silence the lint.
1183            let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1184            let ident = path.segments[0].ident;
1185            let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1186                ident,
1187                ScopeSet::Macro(MacroKind::Bang),
1188                &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1189                None,
1190                None,
1191                None,
1192            );
1193            if let Ok(fallback_binding) = fallback_binding
1194                && fallback_binding.res().opt_def_id() == Some(def_id)
1195            {
1196                // Silence `unused_imports` on the fallback import as well.
1197                self.get_mut().record_use(ident, fallback_binding, Used::Other);
1198            } else {
1199                let location = match parent_scope.module.kind {
1200                    ModuleKind::Def(kind, def_id, _, name) => {
1201                        if let Some(name) = name {
1202                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}`", kind.descr(def_id),
                name))
    })format!("{} `{name}`", kind.descr(def_id))
1203                        } else {
1204                            "the crate root".to_string()
1205                        }
1206                    }
1207                    ModuleKind::Block => "this scope".to_string(),
1208                };
1209                self.tcx.sess.psess.buffer_lint(
1210                    OUT_OF_SCOPE_MACRO_CALLS,
1211                    path.span,
1212                    node_id,
1213                    diagnostics::OutOfScopeMacroCalls {
1214                        span: path.span,
1215                        path: pprust::path_to_string(path),
1216                        location,
1217                    },
1218                );
1219            }
1220        }
1221    }
1222
1223    pub(crate) fn check_reserved_macro_name(&self, name: Symbol, span: Span, res: Res) {
1224        // Reserve some names that are not quite covered by the general check
1225        // performed on `Resolver::builtin_attrs`.
1226        if name == sym::cfg || name == sym::cfg_attr {
1227            let macro_kinds = res.macro_kinds();
1228            if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1229                self.dcx()
1230                    .emit_err(diagnostics::NameReservedInAttributeNamespace { span, ident: name });
1231            }
1232        }
1233    }
1234
1235    /// Compile the macro into a `SyntaxExtension` and its rule spans.
1236    ///
1237    /// Possibly replace its expander to a pre-defined one for built-in macros.
1238    pub(crate) fn compile_macro(
1239        &self,
1240        macro_def: &ast::MacroDef,
1241        ident: Ident,
1242        attrs: &[rustc_attr_ir::Attribute],
1243        span: Span,
1244        node_id: NodeId,
1245        edition: Edition,
1246    ) -> SyntaxExtension {
1247        let mut ext = compile_declarative_macro(
1248            self.tcx.sess,
1249            self.features,
1250            macro_def,
1251            ident,
1252            attrs,
1253            span,
1254            node_id,
1255            edition,
1256        );
1257
1258        if let Some(builtin_name) = ext.builtin_name {
1259            // The macro was marked with `#[rustc_builtin_macro]`.
1260            if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1261                // The macro is a built-in, replace its expander function
1262                // while still taking everything else from the source code.
1263                ext.kind = builtin_ext_kind.clone();
1264            } else {
1265                self.dcx().emit_err(diagnostics::CannotFindBuiltinMacroWithName { span, ident });
1266            }
1267        }
1268
1269        ext
1270    }
1271
1272    fn path_accessible(
1273        &self,
1274        expn_id: LocalExpnId,
1275        path: &ast::Path,
1276        namespaces: &[Namespace],
1277    ) -> Result<bool, Indeterminate> {
1278        let span = path.span;
1279        let path = &Segment::from_path(path);
1280        let parent_scope = self.invocation_parent_scopes[&expn_id];
1281
1282        let mut indeterminate = false;
1283        for ns in namespaces {
1284            match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1285                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1286                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1287                    return Ok(true);
1288                }
1289                PathResult::NonModule(..) |
1290                // HACK(Urgau): This shouldn't be necessary
1291                PathResult::Failed { is_error_from_last_segment: false, .. } => {
1292                    self.dcx().emit_err(diagnostics::CfgAccessibleUnsure { span });
1293
1294                    // If we get a partially resolved NonModule in one namespace, we should get the
1295                    // same result in any other namespaces, so we can return early.
1296                    return Ok(false);
1297                }
1298                PathResult::Indeterminate => indeterminate = true,
1299                // We can only be sure that a path doesn't exist after having tested all the
1300                // possibilities, only at that time we can return false.
1301                PathResult::Failed { .. } => {}
1302                PathResult::Module(_) => { ::core::panicking::panic_fmt(format_args!("unexpected path resolution")); }panic!("unexpected path resolution"),
1303            }
1304        }
1305
1306        if indeterminate {
1307            return Err(Indeterminate);
1308        }
1309
1310        Ok(false)
1311    }
1312}