Skip to main content

rustc_resolve/
macros.rs

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