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_data_structures::StabilityLevel;
12use rustc_data_structures::intern::Interned;
13use rustc_errors::{Applicability, DiagCtxtHandle, StashKey};
14use rustc_expand::base::{
15    Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension,
16    SyntaxExtensionKind,
17};
18use rustc_expand::compile_declarative_macro;
19use rustc_expand::expand::{
20    AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion,
21};
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, Visibility};
26use rustc_session::lint::BuiltinLintDiag;
27use rustc_session::lint::builtin::{
28    LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNKNOWN_OR_MALFORMED_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, ToNameBinding, 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> = Interned<'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(&mut 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            for (&arm_i, &(ident, rule_span)) in unused_arms.to_sorted_stable_ord() {
355                self.lint_buffer.buffer_lint(
356                    UNUSED_MACRO_RULES,
357                    node_id,
358                    rule_span,
359                    BuiltinLintDiag::MacroRuleNeverUsed(arm_i, ident.name),
360                );
361            }
362        }
363    }
364
365    fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
366        self.containers_deriving_copy.contains(&expn_id)
367    }
368
369    fn resolve_derives(
370        &mut self,
371        expn_id: LocalExpnId,
372        force: bool,
373        derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
374    ) -> Result<(), Indeterminate> {
375        // Block expansion of the container until we resolve all derives in it.
376        // This is required for two reasons:
377        // - Derive helper attributes are in scope for the item to which the `#[derive]`
378        //   is applied, so they have to be produced by the container's expansion rather
379        //   than by individual derives.
380        // - Derives in the container need to know whether one of them is a built-in `Copy`.
381        // Temporarily take the data to avoid borrow checker conflicts.
382        let mut derive_data = mem::take(&mut self.derive_data);
383        let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
384            resolutions: derive_paths(),
385            helper_attrs: Vec::new(),
386            has_derive_copy: false,
387        });
388        let parent_scope = self.invocation_parent_scopes[&expn_id];
389        for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
390            if resolution.exts.is_none() {
391                resolution.exts = Some(
392                    match self.resolve_macro_path(
393                        &resolution.path,
394                        Some(MacroKind::Derive),
395                        &parent_scope,
396                        true,
397                        force,
398                        None,
399                        None,
400                    ) {
401                        Ok((Some(ext), _)) => {
402                            if !ext.helper_attrs.is_empty() {
403                                let last_seg = resolution.path.segments.last().unwrap();
404                                let span = last_seg.ident.span.normalize_to_macros_2_0();
405                                entry.helper_attrs.extend(
406                                    ext.helper_attrs
407                                        .iter()
408                                        .map(|name| (i, Ident::new(*name, span))),
409                                );
410                            }
411                            entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
412                            ext
413                        }
414                        Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
415                        Err(Determinacy::Undetermined) => {
416                            assert!(self.derive_data.is_empty());
417                            self.derive_data = derive_data;
418                            return Err(Indeterminate);
419                        }
420                    },
421                );
422            }
423        }
424        // Sort helpers in a stable way independent from the derive resolution order.
425        entry.helper_attrs.sort_by_key(|(i, _)| *i);
426        let helper_attrs = entry
427            .helper_attrs
428            .iter()
429            .map(|(_, ident)| {
430                let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
431                let binding = (res, Visibility::<DefId>::Public, ident.span, expn_id)
432                    .to_name_binding(self.arenas);
433                (*ident, binding)
434            })
435            .collect();
436        self.helper_attrs.insert(expn_id, helper_attrs);
437        // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
438        // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
439        if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
440            self.containers_deriving_copy.insert(expn_id);
441        }
442        assert!(self.derive_data.is_empty());
443        self.derive_data = derive_data;
444        Ok(())
445    }
446
447    fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
448        self.derive_data.remove(&expn_id).map(|data| data.resolutions)
449    }
450
451    // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
452    // Returns true if the path can certainly be resolved in one of three namespaces,
453    // returns false if the path certainly cannot be resolved in any of the three namespaces.
454    // Returns `Indeterminate` if we cannot give a certain answer yet.
455    fn cfg_accessible(
456        &mut self,
457        expn_id: LocalExpnId,
458        path: &ast::Path,
459    ) -> Result<bool, Indeterminate> {
460        self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
461    }
462
463    fn macro_accessible(
464        &mut self,
465        expn_id: LocalExpnId,
466        path: &ast::Path,
467    ) -> Result<bool, Indeterminate> {
468        self.path_accessible(expn_id, path, &[MacroNS])
469    }
470
471    fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
472        self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.tcx.sess)
473    }
474
475    fn declare_proc_macro(&mut self, id: NodeId) {
476        self.proc_macros.push(self.local_def_id(id))
477    }
478
479    fn append_stripped_cfg_item(&mut self, parent_node: NodeId, ident: Ident, cfg: ast::MetaItem) {
480        self.stripped_cfg_items.push(StrippedCfgItem { parent_module: parent_node, ident, cfg });
481    }
482
483    fn registered_tools(&self) -> &RegisteredTools {
484        self.registered_tools
485    }
486
487    fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
488        self.glob_delegation_invoc_ids.insert(invoc_id);
489    }
490
491    fn glob_delegation_suffixes(
492        &mut self,
493        trait_def_id: DefId,
494        impl_def_id: LocalDefId,
495    ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
496        let target_trait = self.expect_module(trait_def_id);
497        if !target_trait.unexpanded_invocations.borrow().is_empty() {
498            return Err(Indeterminate);
499        }
500        // FIXME: Instead of waiting try generating all trait methods, and pruning
501        // the shadowed ones a bit later, e.g. when all macro expansion completes.
502        // Pros: expansion will be stuck less (but only in exotic cases), the implementation may be
503        // less hacky.
504        // Cons: More code is generated just to be deleted later, deleting already created `DefId`s
505        // may be nontrivial.
506        if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
507            && !unexpanded_invocations.is_empty()
508        {
509            return Err(Indeterminate);
510        }
511
512        let mut idents = Vec::new();
513        target_trait.for_each_child(self, |this, ident, ns, _binding| {
514            // FIXME: Adjust hygiene for idents from globs, like for glob imports.
515            if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
516                && overriding_keys.contains(&BindingKey::new(ident.normalize_to_macros_2_0(), ns))
517            {
518                // The name is overridden, do not produce it from the glob delegation.
519            } else {
520                idents.push((ident, None));
521            }
522        });
523        Ok(idents)
524    }
525}
526
527impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
528    /// Resolve macro path with error reporting and recovery.
529    /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
530    /// for better error recovery.
531    fn smart_resolve_macro_path(
532        &mut self,
533        path: &ast::Path,
534        kind: MacroKind,
535        supports_macro_expansion: SupportsMacroExpansion,
536        inner_attr: bool,
537        parent_scope: &ParentScope<'ra>,
538        node_id: NodeId,
539        force: bool,
540        deleg_impl: Option<LocalDefId>,
541        invoc_in_mod_inert_attr: Option<LocalDefId>,
542        suggestion_span: Option<Span>,
543    ) -> Result<(Arc<SyntaxExtension>, Res), Indeterminate> {
544        let (ext, res) = match self.resolve_macro_or_delegation_path(
545            path,
546            Some(kind),
547            parent_scope,
548            true,
549            force,
550            deleg_impl,
551            invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
552            None,
553            suggestion_span,
554        ) {
555            Ok((Some(ext), res)) => (ext, res),
556            Ok((None, res)) => (self.dummy_ext(kind), res),
557            Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
558            Err(Determinacy::Undetermined) => return Err(Indeterminate),
559        };
560
561        // Everything below is irrelevant to glob delegation, take a shortcut.
562        if deleg_impl.is_some() {
563            if !matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
564                self.dcx().emit_err(MacroExpectedFound {
565                    span: path.span,
566                    expected: "trait",
567                    article: "a",
568                    found: res.descr(),
569                    macro_path: &pprust::path_to_string(path),
570                    remove_surrounding_derive: None,
571                    add_as_non_derive: None,
572                });
573                return Ok((self.dummy_ext(kind), Res::Err));
574            }
575
576            return Ok((ext, res));
577        }
578
579        // Report errors for the resolved macro.
580        for segment in &path.segments {
581            if let Some(args) = &segment.args {
582                self.dcx().emit_err(errors::GenericArgumentsInMacroPath { span: args.span() });
583            }
584            if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
585                self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
586                    span: segment.ident.span,
587                });
588            }
589        }
590
591        match res {
592            Res::Def(DefKind::Macro(_), def_id) => {
593                if let Some(def_id) = def_id.as_local() {
594                    self.unused_macros.swap_remove(&def_id);
595                    if self.proc_macro_stubs.contains(&def_id) {
596                        self.dcx().emit_err(errors::ProcMacroSameCrate {
597                            span: path.span,
598                            is_test: self.tcx.sess.is_test_crate(),
599                        });
600                    }
601                }
602            }
603            Res::NonMacroAttr(..) | Res::Err => {}
604            _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
605        };
606
607        self.check_stability_and_deprecation(&ext, path, node_id);
608
609        let unexpected_res = if ext.macro_kind() != kind {
610            Some((kind.article(), kind.descr_expected()))
611        } else if matches!(res, Res::Def(..)) {
612            match supports_macro_expansion {
613                SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
614                SupportsMacroExpansion::Yes { supports_inner_attrs } => {
615                    if inner_attr && !supports_inner_attrs {
616                        Some(("a", "non-macro inner attribute"))
617                    } else {
618                        None
619                    }
620                }
621            }
622        } else {
623            None
624        };
625        if let Some((article, expected)) = unexpected_res {
626            let path_str = pprust::path_to_string(path);
627
628            let mut err = MacroExpectedFound {
629                span: path.span,
630                expected,
631                article,
632                found: res.descr(),
633                macro_path: &path_str,
634                remove_surrounding_derive: None,
635                add_as_non_derive: None,
636            };
637
638            // Suggest moving the macro out of the derive() if the macro isn't Derive
639            if !path.span.from_expansion()
640                && kind == MacroKind::Derive
641                && ext.macro_kind() != MacroKind::Derive
642            {
643                err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
644                err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
645            }
646
647            self.dcx().emit_err(err);
648
649            return Ok((self.dummy_ext(kind), Res::Err));
650        }
651
652        // We are trying to avoid reporting this error if other related errors were reported.
653        if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
654            let is_macro = match res {
655                Res::Def(..) => true,
656                Res::NonMacroAttr(..) => false,
657                _ => unreachable!(),
658            };
659            let msg = if is_macro {
660                "inner macro attributes are unstable"
661            } else {
662                "custom inner attributes are unstable"
663            };
664            feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
665        }
666
667        if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
668            && let [namespace, attribute, ..] = &*path.segments
669            && namespace.ident.name == sym::diagnostic
670            && ![sym::on_unimplemented, sym::do_not_recommend].contains(&attribute.ident.name)
671        {
672            let typo_name = find_best_match_for_name(
673                &[sym::on_unimplemented, sym::do_not_recommend],
674                attribute.ident.name,
675                Some(5),
676            );
677
678            self.tcx.sess.psess.buffer_lint(
679                UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES,
680                attribute.span(),
681                node_id,
682                BuiltinLintDiag::UnknownDiagnosticAttribute { span: attribute.span(), typo_name },
683            );
684        }
685
686        Ok((ext, res))
687    }
688
689    pub(crate) fn resolve_macro_path(
690        &mut self,
691        path: &ast::Path,
692        kind: Option<MacroKind>,
693        parent_scope: &ParentScope<'ra>,
694        trace: bool,
695        force: bool,
696        ignore_import: Option<Import<'ra>>,
697        suggestion_span: Option<Span>,
698    ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
699        self.resolve_macro_or_delegation_path(
700            path,
701            kind,
702            parent_scope,
703            trace,
704            force,
705            None,
706            None,
707            ignore_import,
708            suggestion_span,
709        )
710    }
711
712    fn resolve_macro_or_delegation_path(
713        &mut self,
714        ast_path: &ast::Path,
715        kind: Option<MacroKind>,
716        parent_scope: &ParentScope<'ra>,
717        trace: bool,
718        force: bool,
719        deleg_impl: Option<LocalDefId>,
720        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
721        ignore_import: Option<Import<'ra>>,
722        suggestion_span: Option<Span>,
723    ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
724        let path_span = ast_path.span;
725        let mut path = Segment::from_path(ast_path);
726
727        // Possibly apply the macro helper hack
728        if deleg_impl.is_none()
729            && kind == Some(MacroKind::Bang)
730            && let [segment] = path.as_slice()
731            && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
732        {
733            let root = Ident::new(kw::DollarCrate, segment.ident.span);
734            path.insert(0, Segment::from_ident(root));
735        }
736
737        let res = if deleg_impl.is_some() || path.len() > 1 {
738            let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
739            let res = match self.maybe_resolve_path(&path, Some(ns), parent_scope, ignore_import) {
740                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
741                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
742                PathResult::NonModule(..)
743                | PathResult::Indeterminate
744                | PathResult::Failed { .. } => Err(Determinacy::Determined),
745                PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
746                    Ok(module.res().unwrap())
747                }
748                PathResult::Module(..) => unreachable!(),
749            };
750
751            if trace {
752                let kind = kind.expect("macro kind must be specified if tracing is enabled");
753                self.multi_segment_macro_resolutions.push((
754                    path,
755                    path_span,
756                    kind,
757                    *parent_scope,
758                    res.ok(),
759                    ns,
760                ));
761            }
762
763            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
764            res
765        } else {
766            let scope_set = kind.map_or(ScopeSet::All(MacroNS), ScopeSet::Macro);
767            let binding = self.early_resolve_ident_in_lexical_scope(
768                path[0].ident,
769                scope_set,
770                parent_scope,
771                None,
772                force,
773                None,
774                None,
775            );
776            if let Err(Determinacy::Undetermined) = binding {
777                return Err(Determinacy::Undetermined);
778            }
779
780            if trace {
781                let kind = kind.expect("macro kind must be specified if tracing is enabled");
782                self.single_segment_macro_resolutions.push((
783                    path[0].ident,
784                    kind,
785                    *parent_scope,
786                    binding.ok(),
787                    suggestion_span,
788                ));
789            }
790
791            let res = binding.map(|binding| binding.res());
792            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
793            self.report_out_of_scope_macro_calls(
794                ast_path,
795                parent_scope,
796                invoc_in_mod_inert_attr,
797                binding.ok(),
798            );
799            res
800        };
801
802        let res = res?;
803        let ext = match deleg_impl {
804            Some(impl_def_id) => match res {
805                def::Res::Def(DefKind::Trait, def_id) => {
806                    let edition = self.tcx.sess.edition();
807                    Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
808                }
809                _ => None,
810            },
811            None => self.get_macro(res).map(|macro_data| Arc::clone(&macro_data.ext)),
812        };
813        Ok((ext, res))
814    }
815
816    pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
817        let check_consistency = |this: &mut Self,
818                                 path: &[Segment],
819                                 span,
820                                 kind: MacroKind,
821                                 initial_res: Option<Res>,
822                                 res: Res| {
823            if let Some(initial_res) = initial_res {
824                if res != initial_res {
825                    // Make sure compilation does not succeed if preferred macro resolution
826                    // has changed after the macro had been expanded. In theory all such
827                    // situations should be reported as errors, so this is a bug.
828                    this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
829                }
830            } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
831                // It's possible that the macro was unresolved (indeterminate) and silently
832                // expanded into a dummy fragment for recovery during expansion.
833                // Now, post-expansion, the resolution may succeed, but we can't change the
834                // past and need to report an error.
835                // However, non-speculative `resolve_path` can successfully return private items
836                // even if speculative `resolve_path` returned nothing previously, so we skip this
837                // less informative error if no other error is reported elsewhere.
838
839                let err = this.dcx().create_err(CannotDetermineMacroResolution {
840                    span,
841                    kind: kind.descr(),
842                    path: Segment::names_to_string(path),
843                });
844                err.stash(span, StashKey::UndeterminedMacroResolution);
845            }
846        };
847
848        let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
849        for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
850            // FIXME: Path resolution will ICE if segment IDs present.
851            for seg in &mut path {
852                seg.id = None;
853            }
854            match self.resolve_path(
855                &path,
856                Some(ns),
857                &parent_scope,
858                Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
859                None,
860                None,
861            ) {
862                PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
863                    check_consistency(self, &path, path_span, kind, initial_res, res)
864                }
865                // This may be a trait for glob delegation expansions.
866                PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
867                    self,
868                    &path,
869                    path_span,
870                    kind,
871                    initial_res,
872                    module.res().unwrap(),
873                ),
874                path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
875                    let mut suggestion = None;
876                    let (span, label, module, segment) =
877                        if let PathResult::Failed { span, label, module, segment_name, .. } =
878                            path_res
879                        {
880                            // try to suggest if it's not a macro, maybe a function
881                            if let PathResult::NonModule(partial_res) =
882                                self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
883                                && partial_res.unresolved_segments() == 0
884                            {
885                                let sm = self.tcx.sess.source_map();
886                                let exclamation_span = sm.next_point(span);
887                                suggestion = Some((
888                                    vec![(exclamation_span, "".to_string())],
889                                    format!(
890                                        "{} is not a macro, but a {}, try to remove `!`",
891                                        Segment::names_to_string(&path),
892                                        partial_res.base_res().descr()
893                                    ),
894                                    Applicability::MaybeIncorrect,
895                                ));
896                            }
897                            (span, label, module, segment_name)
898                        } else {
899                            (
900                                path_span,
901                                format!(
902                                    "partially resolved path in {} {}",
903                                    kind.article(),
904                                    kind.descr()
905                                ),
906                                None,
907                                path.last().map(|segment| segment.ident.name).unwrap(),
908                            )
909                        };
910                    self.report_error(
911                        span,
912                        ResolutionError::FailedToResolve {
913                            segment: Some(segment),
914                            label,
915                            suggestion,
916                            module,
917                        },
918                    );
919                }
920                PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
921            }
922        }
923
924        let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
925        for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
926            match self.early_resolve_ident_in_lexical_scope(
927                ident,
928                ScopeSet::Macro(kind),
929                &parent_scope,
930                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
931                true,
932                None,
933                None,
934            ) {
935                Ok(binding) => {
936                    let initial_res = initial_binding.map(|initial_binding| {
937                        self.record_use(ident, initial_binding, Used::Other);
938                        initial_binding.res()
939                    });
940                    let res = binding.res();
941                    let seg = Segment::from_ident(ident);
942                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
943                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
944                        let node_id = self
945                            .invocation_parents
946                            .get(&parent_scope.expansion)
947                            .map_or(ast::CRATE_NODE_ID, |parent| {
948                                self.def_id_to_node_id(parent.parent_def)
949                            });
950                        self.lint_buffer.buffer_lint(
951                            LEGACY_DERIVE_HELPERS,
952                            node_id,
953                            ident.span,
954                            BuiltinLintDiag::LegacyDeriveHelpers(binding.span),
955                        );
956                    }
957                }
958                Err(..) => {
959                    let expected = kind.descr_expected();
960
961                    let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
962                        span: ident.span,
963                        expected,
964                        ident,
965                    });
966                    self.unresolved_macro_suggestions(
967                        &mut err,
968                        kind,
969                        &parent_scope,
970                        ident,
971                        krate,
972                        sugg_span,
973                    );
974                    err.emit();
975                }
976            }
977        }
978
979        let builtin_attrs = mem::take(&mut self.builtin_attrs);
980        for (ident, parent_scope) in builtin_attrs {
981            let _ = self.early_resolve_ident_in_lexical_scope(
982                ident,
983                ScopeSet::Macro(MacroKind::Attr),
984                &parent_scope,
985                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
986                true,
987                None,
988                None,
989            );
990        }
991    }
992
993    fn check_stability_and_deprecation(
994        &mut self,
995        ext: &SyntaxExtension,
996        path: &ast::Path,
997        node_id: NodeId,
998    ) {
999        let span = path.span;
1000        if let Some(stability) = &ext.stability {
1001            if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } =
1002                stability.level
1003            {
1004                let feature = stability.feature;
1005
1006                let is_allowed =
1007                    |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1008                let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1009                if !is_allowed(feature) && !allowed_by_implication {
1010                    let lint_buffer = &mut self.lint_buffer;
1011                    let soft_handler = |lint, span, msg: String| {
1012                        lint_buffer.buffer_lint(
1013                            lint,
1014                            node_id,
1015                            span,
1016                            BuiltinLintDiag::UnstableFeature(
1017                                // FIXME make this translatable
1018                                msg.into(),
1019                            ),
1020                        )
1021                    };
1022                    stability::report_unstable(
1023                        self.tcx.sess,
1024                        feature,
1025                        reason.to_opt_reason(),
1026                        issue,
1027                        None,
1028                        is_soft,
1029                        span,
1030                        soft_handler,
1031                        stability::UnstableKind::Regular,
1032                    );
1033                }
1034            }
1035        }
1036        if let Some(depr) = &ext.deprecation {
1037            let path = pprust::path_to_string(path);
1038            stability::early_report_macro_deprecation(
1039                &mut self.lint_buffer,
1040                depr,
1041                span,
1042                node_id,
1043                path,
1044            );
1045        }
1046    }
1047
1048    fn prohibit_imported_non_macro_attrs(
1049        &self,
1050        binding: Option<NameBinding<'ra>>,
1051        res: Option<Res>,
1052        span: Span,
1053    ) {
1054        if let Some(Res::NonMacroAttr(kind)) = res {
1055            if kind != NonMacroAttrKind::Tool && binding.is_none_or(|b| b.is_import()) {
1056                let binding_span = binding.map(|binding| binding.span);
1057                self.dcx().emit_err(errors::CannotUseThroughAnImport {
1058                    span,
1059                    article: kind.article(),
1060                    descr: kind.descr(),
1061                    binding_span,
1062                });
1063            }
1064        }
1065    }
1066
1067    fn report_out_of_scope_macro_calls(
1068        &mut self,
1069        path: &ast::Path,
1070        parent_scope: &ParentScope<'ra>,
1071        invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1072        binding: Option<NameBinding<'ra>>,
1073    ) {
1074        if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1075            && let Some(binding) = binding
1076            // This is a `macro_rules` itself, not some import.
1077            && let NameBindingKind::Res(res) = binding.kind
1078            && let Res::Def(DefKind::Macro(MacroKind::Bang), def_id) = res
1079            // And the `macro_rules` is defined inside the attribute's module,
1080            // so it cannot be in scope unless imported.
1081            && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1082        {
1083            // Try to resolve our ident ignoring `macro_rules` scopes.
1084            // If such resolution is successful and gives the same result
1085            // (e.g. if the macro is re-imported), then silence the lint.
1086            let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1087            let fallback_binding = self.early_resolve_ident_in_lexical_scope(
1088                path.segments[0].ident,
1089                ScopeSet::Macro(MacroKind::Bang),
1090                &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1091                None,
1092                false,
1093                None,
1094                None,
1095            );
1096            if fallback_binding.ok().and_then(|b| b.res().opt_def_id()) != Some(def_id) {
1097                let location = match parent_scope.module.kind {
1098                    ModuleKind::Def(kind, def_id, name) => {
1099                        if let Some(name) = name {
1100                            format!("{} `{name}`", kind.descr(def_id))
1101                        } else {
1102                            "the crate root".to_string()
1103                        }
1104                    }
1105                    ModuleKind::Block => "this scope".to_string(),
1106                };
1107                self.tcx.sess.psess.buffer_lint(
1108                    OUT_OF_SCOPE_MACRO_CALLS,
1109                    path.span,
1110                    node_id,
1111                    BuiltinLintDiag::OutOfScopeMacroCalls {
1112                        span: path.span,
1113                        path: pprust::path_to_string(path),
1114                        location,
1115                    },
1116                );
1117            }
1118        }
1119    }
1120
1121    pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
1122        // Reserve some names that are not quite covered by the general check
1123        // performed on `Resolver::builtin_attrs`.
1124        if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1125            let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
1126            if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
1127                self.dcx()
1128                    .emit_err(errors::NameReservedInAttributeNamespace { span: ident.span, ident });
1129            }
1130        }
1131    }
1132
1133    /// Compile the macro into a `SyntaxExtension` and its rule spans.
1134    ///
1135    /// Possibly replace its expander to a pre-defined one for built-in macros.
1136    pub(crate) fn compile_macro(
1137        &mut self,
1138        macro_def: &ast::MacroDef,
1139        ident: Ident,
1140        attrs: &[rustc_hir::Attribute],
1141        span: Span,
1142        node_id: NodeId,
1143        edition: Edition,
1144    ) -> MacroData {
1145        let (mut ext, mut rule_spans) = compile_declarative_macro(
1146            self.tcx.sess,
1147            self.tcx.features(),
1148            macro_def,
1149            ident,
1150            attrs,
1151            span,
1152            node_id,
1153            edition,
1154        );
1155
1156        if let Some(builtin_name) = ext.builtin_name {
1157            // The macro was marked with `#[rustc_builtin_macro]`.
1158            if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1159                // The macro is a built-in, replace its expander function
1160                // while still taking everything else from the source code.
1161                ext.kind = builtin_ext_kind.clone();
1162                rule_spans = Vec::new();
1163            } else {
1164                self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1165            }
1166        }
1167
1168        MacroData { ext: Arc::new(ext), rule_spans, macro_rules: macro_def.macro_rules }
1169    }
1170
1171    fn path_accessible(
1172        &mut self,
1173        expn_id: LocalExpnId,
1174        path: &ast::Path,
1175        namespaces: &[Namespace],
1176    ) -> Result<bool, Indeterminate> {
1177        let span = path.span;
1178        let path = &Segment::from_path(path);
1179        let parent_scope = self.invocation_parent_scopes[&expn_id];
1180
1181        let mut indeterminate = false;
1182        for ns in namespaces {
1183            match self.maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1184                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1185                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1186                    return Ok(true);
1187                }
1188                PathResult::NonModule(..) |
1189                // HACK(Urgau): This shouldn't be necessary
1190                PathResult::Failed { is_error_from_last_segment: false, .. } => {
1191                    self.dcx()
1192                        .emit_err(errors::CfgAccessibleUnsure { span });
1193
1194                    // If we get a partially resolved NonModule in one namespace, we should get the
1195                    // same result in any other namespaces, so we can return early.
1196                    return Ok(false);
1197                }
1198                PathResult::Indeterminate => indeterminate = true,
1199                // We can only be sure that a path doesn't exist after having tested all the
1200                // possibilities, only at that time we can return false.
1201                PathResult::Failed { .. } => {}
1202                PathResult::Module(_) => panic!("unexpected path resolution"),
1203            }
1204        }
1205
1206        if indeterminate {
1207            return Err(Indeterminate);
1208        }
1209
1210        Ok(false)
1211    }
1212}