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