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