rustc_resolve/
macros.rs

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