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