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