rustc_resolve/
macros.rs

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