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