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