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