rustc_resolve/
macros.rs

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