rustc_resolve/
macros.rs

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