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