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