1use 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#[derive(Debug)]
54pub(crate) struct MacroRulesBinding<'ra> {
55 pub(crate) binding: NameBinding<'ra>,
56 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
58 pub(crate) ident: Ident,
59}
60
61#[derive(Copy, Clone, Debug)]
67pub(crate) enum MacroRulesScope<'ra> {
68 Empty,
70 Binding(&'ra MacroRulesBinding<'ra>),
72 Invocation(LocalExpnId),
75}
76
77pub(crate) type MacroRulesScopeRef<'ra> = Interned<'ra, Cell<MacroRulesScope<'ra>>>;
84
85pub(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 candidate.is_none() || requirement.is_none() || candidate == requirement
105}
106
107fn 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 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 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 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 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 (&deleg.prefix, MacroKind::Bang)
280 }
281 };
282
283 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 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 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 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 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 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 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 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 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 } 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 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 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 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 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 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 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(¯o_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 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 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 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 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 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 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 && let NameBindingKind::Res(res) = binding.kind
1082 && let Res::Def(DefKind::Macro(MacroKind::Bang), def_id) = res
1083 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1086 {
1087 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 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 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 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1163 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 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1195 self.dcx()
1196 .emit_err(errors::CfgAccessibleUnsure { span });
1197
1198 return Ok(false);
1201 }
1202 PathResult::Indeterminate => indeterminate = true,
1203 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}