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