1use std::cell::Cell;
5use std::mem;
6use std::sync::Arc;
7
8use rustc_ast::{self as ast, Crate, NodeId, attr};
9use rustc_ast_pretty::pprust;
10use rustc_attr_data_structures::{CfgEntry, StabilityLevel, StrippedCfgItem};
11use rustc_errors::{Applicability, DiagCtxtHandle, StashKey};
12use rustc_expand::base::{
13 Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension,
14 SyntaxExtensionKind,
15};
16use rustc_expand::compile_declarative_macro;
17use rustc_expand::expand::{
18 AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion,
19};
20use rustc_hir::def::{self, DefKind, Namespace, NonMacroAttrKind};
21use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
22use rustc_middle::middle::stability;
23use rustc_middle::ty::{RegisteredTools, TyCtxt};
24use rustc_session::lint::BuiltinLintDiag;
25use rustc_session::lint::builtin::{
26 LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
27 UNUSED_MACRO_RULES, UNUSED_MACROS,
28};
29use rustc_session::parse::feature_err;
30use rustc_span::edit_distance::find_best_match_for_name;
31use rustc_span::edition::Edition;
32use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
33use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
34
35use crate::Namespace::*;
36use crate::errors::{
37 self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
38 MacroExpectedFound, RemoveSurroundingDerive,
39};
40use crate::imports::Import;
41use crate::{
42 BindingKey, DeriveData, Determinacy, Finalize, InvocationParent, MacroData, ModuleKind,
43 ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, ResolutionError,
44 Resolver, ScopeSet, Segment, Used,
45};
46
47type Res = def::Res<NodeId>;
48
49#[derive(Debug)]
52pub(crate) struct MacroRulesBinding<'ra> {
53 pub(crate) binding: NameBinding<'ra>,
54 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
56 pub(crate) ident: Ident,
57}
58
59#[derive(Copy, Clone, Debug)]
65pub(crate) enum MacroRulesScope<'ra> {
66 Empty,
68 Binding(&'ra MacroRulesBinding<'ra>),
70 Invocation(LocalExpnId),
73}
74
75pub(crate) type MacroRulesScopeRef<'ra> = &'ra Cell<MacroRulesScope<'ra>>;
82
83pub(crate) fn sub_namespace_match(
87 candidate: Option<MacroKind>,
88 requirement: Option<MacroKind>,
89) -> bool {
90 #[derive(PartialEq)]
91 enum SubNS {
92 Bang,
93 AttrLike,
94 }
95 let sub_ns = |kind| match kind {
96 MacroKind::Bang => SubNS::Bang,
97 MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
98 };
99 let candidate = candidate.map(sub_ns);
100 let requirement = requirement.map(sub_ns);
101 candidate.is_none() || requirement.is_none() || candidate == requirement
103}
104
105fn fast_print_path(path: &ast::Path) -> Symbol {
109 if let [segment] = path.segments.as_slice() {
110 segment.ident.name
111 } else {
112 let mut path_str = String::with_capacity(64);
113 for (i, segment) in path.segments.iter().enumerate() {
114 if i != 0 {
115 path_str.push_str("::");
116 }
117 if segment.ident.name != kw::PathRoot {
118 path_str.push_str(segment.ident.as_str())
119 }
120 }
121 Symbol::intern(&path_str)
122 }
123}
124
125pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
126 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
127 registered_tools_ast(tcx.dcx(), pre_configured_attrs)
128}
129
130pub fn registered_tools_ast(
131 dcx: DiagCtxtHandle<'_>,
132 pre_configured_attrs: &[ast::Attribute],
133) -> RegisteredTools {
134 let mut registered_tools = RegisteredTools::default();
135 for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
136 for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
137 match meta_item_inner.ident() {
138 Some(ident) => {
139 if let Some(old_ident) = registered_tools.replace(ident) {
140 dcx.emit_err(errors::ToolWasAlreadyRegistered {
141 span: ident.span,
142 tool: ident,
143 old_ident_span: old_ident.span,
144 });
145 }
146 }
147 None => {
148 dcx.emit_err(errors::ToolOnlyAcceptsIdentifiers {
149 span: meta_item_inner.span(),
150 tool: sym::register_tool,
151 });
152 }
153 }
154 }
155 }
156 let predefined_tools =
159 [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
160 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
161 registered_tools
162}
163
164impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
165 fn next_node_id(&mut self) -> NodeId {
166 self.next_node_id()
167 }
168
169 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
170 self.invocation_parents[&id].parent_def
171 }
172
173 fn resolve_dollar_crates(&self) {
174 hygiene::update_dollar_crate_names(|ctxt| {
175 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
176 match self.resolve_crate_root(ident).kind {
177 ModuleKind::Def(.., name) if let Some(name) = name => name,
178 _ => kw::Crate,
179 }
180 });
181 }
182
183 fn visit_ast_fragment_with_placeholders(
184 &mut self,
185 expansion: LocalExpnId,
186 fragment: &AstFragment,
187 ) {
188 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
191 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
192 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
193
194 parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
195 if let Some(unexpanded_invocations) =
196 self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
197 {
198 unexpanded_invocations.remove(&expansion);
199 }
200 }
201
202 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
203 if self.builtin_macros.insert(name, ext).is_some() {
204 self.dcx().bug(format!("built-in macro `{name}` was already registered"));
205 }
206 }
207
208 fn expansion_for_ast_pass(
211 &mut self,
212 call_site: Span,
213 pass: AstPass,
214 features: &[Symbol],
215 parent_module_id: Option<NodeId>,
216 ) -> LocalExpnId {
217 let parent_module =
218 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
219 let expn_id = LocalExpnId::fresh(
220 ExpnData::allow_unstable(
221 ExpnKind::AstPass(pass),
222 call_site,
223 self.tcx.sess.edition(),
224 features.into(),
225 None,
226 parent_module,
227 ),
228 self.create_stable_hashing_context(),
229 );
230
231 let parent_scope =
232 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
233 self.ast_transform_scopes.insert(expn_id, parent_scope);
234
235 expn_id
236 }
237
238 fn resolve_imports(&mut self) {
239 self.resolve_imports()
240 }
241
242 fn resolve_macro_invocation(
243 &mut self,
244 invoc: &Invocation,
245 eager_expansion_root: LocalExpnId,
246 force: bool,
247 ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
248 let invoc_id = invoc.expansion_data.id;
249 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
250 Some(parent_scope) => *parent_scope,
251 None => {
252 let parent_scope = *self
256 .invocation_parent_scopes
257 .get(&eager_expansion_root)
258 .expect("non-eager expansion without a parent scope");
259 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
260 parent_scope
261 }
262 };
263
264 let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
265 let (path, kind) = match invoc.kind {
266 InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
267 derives = self.arenas.alloc_ast_paths(attr_derives);
268 inner_attr = attr.style == ast::AttrStyle::Inner;
269 (&attr.get_normal_item().path, MacroKind::Attr)
270 }
271 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
272 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
273 InvocationKind::GlobDelegation { ref item, .. } => {
274 let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() };
275 deleg_impl = Some(self.invocation_parent(invoc_id));
276 (&deleg.prefix, MacroKind::Bang)
278 }
279 };
280
281 let parent_scope = &ParentScope { derives, ..parent_scope };
283 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
284 let node_id = invoc.expansion_data.lint_node_id;
285 let looks_like_invoc_in_mod_inert_attr = self
287 .invocation_parents
288 .get(&invoc_id)
289 .or_else(|| self.invocation_parents.get(&eager_expansion_root))
290 .filter(|&&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
291 in_attr
292 && invoc.fragment_kind == AstFragmentKind::Expr
293 && self.tcx.def_kind(mod_def_id) == DefKind::Mod
294 })
295 .map(|&InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
296 let sugg_span = match &invoc.kind {
297 InvocationKind::Attr { item: Annotatable::Item(item), .. }
298 if !item.span.from_expansion() =>
299 {
300 Some(item.span.shrink_to_lo())
301 }
302 _ => None,
303 };
304 let (ext, res) = self.smart_resolve_macro_path(
305 path,
306 kind,
307 supports_macro_expansion,
308 inner_attr,
309 parent_scope,
310 node_id,
311 force,
312 deleg_impl,
313 looks_like_invoc_in_mod_inert_attr,
314 sugg_span,
315 )?;
316
317 let span = invoc.span();
318 let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
319 invoc_id.set_expn_data(
320 ext.expn_data(
321 parent_scope.expansion,
322 span,
323 fast_print_path(path),
324 def_id,
325 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
326 ),
327 self.create_stable_hashing_context(),
328 );
329
330 Ok(ext)
331 }
332
333 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
334 if let Some(rules) = self.unused_macro_rules.get_mut(&id) {
335 rules.remove(rule_i);
336 }
337 }
338
339 fn check_unused_macros(&mut self) {
340 for (_, &(node_id, ident)) in self.unused_macros.iter() {
341 self.lint_buffer.buffer_lint(
342 UNUSED_MACROS,
343 node_id,
344 ident.span,
345 BuiltinLintDiag::UnusedMacroDefinition(ident.name),
346 );
347 self.unused_macro_rules.swap_remove(&node_id);
349 }
350
351 for (&node_id, unused_arms) in self.unused_macro_rules.iter() {
352 if unused_arms.is_empty() {
353 continue;
354 }
355 let def_id = self.local_def_id(node_id);
356 let m = &self.local_macro_map[&def_id];
357 let SyntaxExtensionKind::LegacyBang(ref ext) = m.ext.kind else {
358 continue;
359 };
360 for arm_i in unused_arms.iter() {
361 if let Some((ident, rule_span)) = ext.get_unused_rule(arm_i) {
362 self.lint_buffer.buffer_lint(
363 UNUSED_MACRO_RULES,
364 node_id,
365 rule_span,
366 BuiltinLintDiag::MacroRuleNeverUsed(arm_i, ident.name),
367 );
368 }
369 }
370 }
371 }
372
373 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
374 self.containers_deriving_copy.contains(&expn_id)
375 }
376
377 fn resolve_derives(
378 &mut self,
379 expn_id: LocalExpnId,
380 force: bool,
381 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
382 ) -> Result<(), Indeterminate> {
383 let mut derive_data = mem::take(&mut self.derive_data);
391 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
392 resolutions: derive_paths(),
393 helper_attrs: Vec::new(),
394 has_derive_copy: false,
395 });
396 let parent_scope = self.invocation_parent_scopes[&expn_id];
397 for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
398 if resolution.exts.is_none() {
399 resolution.exts = Some(
400 match self.resolve_macro_path(
401 &resolution.path,
402 Some(MacroKind::Derive),
403 &parent_scope,
404 true,
405 force,
406 None,
407 None,
408 ) {
409 Ok((Some(ext), _)) => {
410 if !ext.helper_attrs.is_empty() {
411 let last_seg = resolution.path.segments.last().unwrap();
412 let span = last_seg.ident.span.normalize_to_macros_2_0();
413 entry.helper_attrs.extend(
414 ext.helper_attrs
415 .iter()
416 .map(|name| (i, Ident::new(*name, span))),
417 );
418 }
419 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
420 ext
421 }
422 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
423 Err(Determinacy::Undetermined) => {
424 assert!(self.derive_data.is_empty());
425 self.derive_data = derive_data;
426 return Err(Indeterminate);
427 }
428 },
429 );
430 }
431 }
432 entry.helper_attrs.sort_by_key(|(i, _)| *i);
434 let helper_attrs = entry
435 .helper_attrs
436 .iter()
437 .map(|(_, ident)| {
438 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
439 let binding = self.arenas.new_pub_res_binding(res, ident.span, expn_id);
440 (*ident, binding)
441 })
442 .collect();
443 self.helper_attrs.insert(expn_id, helper_attrs);
444 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
447 self.containers_deriving_copy.insert(expn_id);
448 }
449 assert!(self.derive_data.is_empty());
450 self.derive_data = derive_data;
451 Ok(())
452 }
453
454 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
455 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
456 }
457
458 fn cfg_accessible(
463 &mut self,
464 expn_id: LocalExpnId,
465 path: &ast::Path,
466 ) -> Result<bool, Indeterminate> {
467 self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
468 }
469
470 fn macro_accessible(
471 &mut self,
472 expn_id: LocalExpnId,
473 path: &ast::Path,
474 ) -> Result<bool, Indeterminate> {
475 self.path_accessible(expn_id, path, &[MacroNS])
476 }
477
478 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
479 self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.tcx.sess)
480 }
481
482 fn declare_proc_macro(&mut self, id: NodeId) {
483 self.proc_macros.push(self.local_def_id(id))
484 }
485
486 fn append_stripped_cfg_item(
487 &mut self,
488 parent_node: NodeId,
489 ident: Ident,
490 cfg: CfgEntry,
491 cfg_span: Span,
492 ) {
493 self.stripped_cfg_items.push(StrippedCfgItem {
494 parent_module: parent_node,
495 ident,
496 cfg: (cfg, cfg_span),
497 });
498 }
499
500 fn registered_tools(&self) -> &RegisteredTools {
501 self.registered_tools
502 }
503
504 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
505 self.glob_delegation_invoc_ids.insert(invoc_id);
506 }
507
508 fn glob_delegation_suffixes(
509 &mut self,
510 trait_def_id: DefId,
511 impl_def_id: LocalDefId,
512 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
513 let target_trait = self.expect_module(trait_def_id);
514 if !target_trait.unexpanded_invocations.borrow().is_empty() {
515 return Err(Indeterminate);
516 }
517 if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
524 && !unexpanded_invocations.is_empty()
525 {
526 return Err(Indeterminate);
527 }
528
529 let mut idents = Vec::new();
530 target_trait.for_each_child(self, |this, ident, ns, _binding| {
531 if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
533 && overriding_keys.contains(&BindingKey::new(ident, ns))
534 {
535 } else {
537 idents.push((ident, None));
538 }
539 });
540 Ok(idents)
541 }
542
543 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
544 self.impl_trait_names.insert(id, name);
545 }
546}
547
548impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
549 fn smart_resolve_macro_path(
553 &mut self,
554 path: &ast::Path,
555 kind: MacroKind,
556 supports_macro_expansion: SupportsMacroExpansion,
557 inner_attr: bool,
558 parent_scope: &ParentScope<'ra>,
559 node_id: NodeId,
560 force: bool,
561 deleg_impl: Option<LocalDefId>,
562 invoc_in_mod_inert_attr: Option<LocalDefId>,
563 suggestion_span: Option<Span>,
564 ) -> Result<(Arc<SyntaxExtension>, Res), Indeterminate> {
565 let (ext, res) = match self.resolve_macro_or_delegation_path(
566 path,
567 Some(kind),
568 parent_scope,
569 true,
570 force,
571 deleg_impl,
572 invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
573 None,
574 suggestion_span,
575 ) {
576 Ok((Some(ext), res)) => (ext, res),
577 Ok((None, res)) => (self.dummy_ext(kind), res),
578 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
579 Err(Determinacy::Undetermined) => return Err(Indeterminate),
580 };
581
582 if deleg_impl.is_some() {
584 if !matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
585 self.dcx().emit_err(MacroExpectedFound {
586 span: path.span,
587 expected: "trait",
588 article: "a",
589 found: res.descr(),
590 macro_path: &pprust::path_to_string(path),
591 remove_surrounding_derive: None,
592 add_as_non_derive: None,
593 });
594 return Ok((self.dummy_ext(kind), Res::Err));
595 }
596
597 return Ok((ext, res));
598 }
599
600 for segment in &path.segments {
602 if let Some(args) = &segment.args {
603 self.dcx().emit_err(errors::GenericArgumentsInMacroPath { span: args.span() });
604 }
605 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
606 self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
607 span: segment.ident.span,
608 });
609 }
610 }
611
612 match res {
613 Res::Def(DefKind::Macro(_), def_id) => {
614 if let Some(def_id) = def_id.as_local() {
615 self.unused_macros.swap_remove(&def_id);
616 if self.proc_macro_stubs.contains(&def_id) {
617 self.dcx().emit_err(errors::ProcMacroSameCrate {
618 span: path.span,
619 is_test: self.tcx.sess.is_test_crate(),
620 });
621 }
622 }
623 }
624 Res::NonMacroAttr(..) | Res::Err => {}
625 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
626 };
627
628 self.check_stability_and_deprecation(&ext, path, node_id);
629
630 let unexpected_res = if ext.macro_kind() != kind {
631 Some((kind.article(), kind.descr_expected()))
632 } else if matches!(res, Res::Def(..)) {
633 match supports_macro_expansion {
634 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
635 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
636 if inner_attr && !supports_inner_attrs {
637 Some(("a", "non-macro inner attribute"))
638 } else {
639 None
640 }
641 }
642 }
643 } else {
644 None
645 };
646 if let Some((article, expected)) = unexpected_res {
647 let path_str = pprust::path_to_string(path);
648
649 let mut err = MacroExpectedFound {
650 span: path.span,
651 expected,
652 article,
653 found: res.descr(),
654 macro_path: &path_str,
655 remove_surrounding_derive: None,
656 add_as_non_derive: None,
657 };
658
659 if !path.span.from_expansion()
661 && kind == MacroKind::Derive
662 && ext.macro_kind() != MacroKind::Derive
663 {
664 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
665 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
666 }
667
668 self.dcx().emit_err(err);
669
670 return Ok((self.dummy_ext(kind), Res::Err));
671 }
672
673 if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
675 let is_macro = match res {
676 Res::Def(..) => true,
677 Res::NonMacroAttr(..) => false,
678 _ => unreachable!(),
679 };
680 let msg = if is_macro {
681 "inner macro attributes are unstable"
682 } else {
683 "custom inner attributes are unstable"
684 };
685 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
686 }
687
688 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
689 && let [namespace, attribute, ..] = &*path.segments
690 && namespace.ident.name == sym::diagnostic
691 && ![sym::on_unimplemented, sym::do_not_recommend].contains(&attribute.ident.name)
692 {
693 let typo_name = find_best_match_for_name(
694 &[sym::on_unimplemented, sym::do_not_recommend],
695 attribute.ident.name,
696 Some(5),
697 );
698
699 self.tcx.sess.psess.buffer_lint(
700 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
701 attribute.span(),
702 node_id,
703 BuiltinLintDiag::UnknownDiagnosticAttribute { span: attribute.span(), typo_name },
704 );
705 }
706
707 Ok((ext, res))
708 }
709
710 pub(crate) fn resolve_macro_path(
711 &mut self,
712 path: &ast::Path,
713 kind: Option<MacroKind>,
714 parent_scope: &ParentScope<'ra>,
715 trace: bool,
716 force: bool,
717 ignore_import: Option<Import<'ra>>,
718 suggestion_span: Option<Span>,
719 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
720 self.resolve_macro_or_delegation_path(
721 path,
722 kind,
723 parent_scope,
724 trace,
725 force,
726 None,
727 None,
728 ignore_import,
729 suggestion_span,
730 )
731 }
732
733 fn resolve_macro_or_delegation_path(
734 &mut self,
735 ast_path: &ast::Path,
736 kind: Option<MacroKind>,
737 parent_scope: &ParentScope<'ra>,
738 trace: bool,
739 force: bool,
740 deleg_impl: Option<LocalDefId>,
741 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
742 ignore_import: Option<Import<'ra>>,
743 suggestion_span: Option<Span>,
744 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
745 let path_span = ast_path.span;
746 let mut path = Segment::from_path(ast_path);
747
748 if deleg_impl.is_none()
750 && kind == Some(MacroKind::Bang)
751 && let [segment] = path.as_slice()
752 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
753 {
754 let root = Ident::new(kw::DollarCrate, segment.ident.span);
755 path.insert(0, Segment::from_ident(root));
756 }
757
758 let res = if deleg_impl.is_some() || path.len() > 1 {
759 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
760 let res = match self.maybe_resolve_path(&path, Some(ns), parent_scope, ignore_import) {
761 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
762 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
763 PathResult::NonModule(..)
764 | PathResult::Indeterminate
765 | PathResult::Failed { .. } => Err(Determinacy::Determined),
766 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
767 Ok(module.res().unwrap())
768 }
769 PathResult::Module(..) => unreachable!(),
770 };
771
772 if trace {
773 let kind = kind.expect("macro kind must be specified if tracing is enabled");
774 self.multi_segment_macro_resolutions.push((
775 path,
776 path_span,
777 kind,
778 *parent_scope,
779 res.ok(),
780 ns,
781 ));
782 }
783
784 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
785 res
786 } else {
787 let scope_set = kind.map_or(ScopeSet::All(MacroNS), ScopeSet::Macro);
788 let binding = self.early_resolve_ident_in_lexical_scope(
789 path[0].ident,
790 scope_set,
791 parent_scope,
792 None,
793 force,
794 None,
795 None,
796 );
797 if let Err(Determinacy::Undetermined) = binding {
798 return Err(Determinacy::Undetermined);
799 }
800
801 if trace {
802 let kind = kind.expect("macro kind must be specified if tracing is enabled");
803 self.single_segment_macro_resolutions.push((
804 path[0].ident,
805 kind,
806 *parent_scope,
807 binding.ok(),
808 suggestion_span,
809 ));
810 }
811
812 let res = binding.map(|binding| binding.res());
813 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
814 self.report_out_of_scope_macro_calls(
815 ast_path,
816 parent_scope,
817 invoc_in_mod_inert_attr,
818 binding.ok(),
819 );
820 res
821 };
822
823 let res = res?;
824 let ext = match deleg_impl {
825 Some(impl_def_id) => match res {
826 def::Res::Def(DefKind::Trait, def_id) => {
827 let edition = self.tcx.sess.edition();
828 Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
829 }
830 _ => None,
831 },
832 None => self.get_macro(res).map(|macro_data| Arc::clone(¯o_data.ext)),
833 };
834 Ok((ext, res))
835 }
836
837 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
838 let check_consistency = |this: &Self,
839 path: &[Segment],
840 span,
841 kind: MacroKind,
842 initial_res: Option<Res>,
843 res: Res| {
844 if let Some(initial_res) = initial_res {
845 if res != initial_res {
846 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
850 }
851 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
852 let err = this.dcx().create_err(CannotDetermineMacroResolution {
861 span,
862 kind: kind.descr(),
863 path: Segment::names_to_string(path),
864 });
865 err.stash(span, StashKey::UndeterminedMacroResolution);
866 }
867 };
868
869 let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
870 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
871 for seg in &mut path {
873 seg.id = None;
874 }
875 match self.resolve_path(
876 &path,
877 Some(ns),
878 &parent_scope,
879 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
880 None,
881 None,
882 ) {
883 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
884 check_consistency(self, &path, path_span, kind, initial_res, res)
885 }
886 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
888 self,
889 &path,
890 path_span,
891 kind,
892 initial_res,
893 module.res().unwrap(),
894 ),
895 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
896 let mut suggestion = None;
897 let (span, label, module, segment) =
898 if let PathResult::Failed { span, label, module, segment_name, .. } =
899 path_res
900 {
901 if let PathResult::NonModule(partial_res) =
903 self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
904 && partial_res.unresolved_segments() == 0
905 {
906 let sm = self.tcx.sess.source_map();
907 let exclamation_span = sm.next_point(span);
908 suggestion = Some((
909 vec![(exclamation_span, "".to_string())],
910 format!(
911 "{} is not a macro, but a {}, try to remove `!`",
912 Segment::names_to_string(&path),
913 partial_res.base_res().descr()
914 ),
915 Applicability::MaybeIncorrect,
916 ));
917 }
918 (span, label, module, segment_name)
919 } else {
920 (
921 path_span,
922 format!(
923 "partially resolved path in {} {}",
924 kind.article(),
925 kind.descr()
926 ),
927 None,
928 path.last().map(|segment| segment.ident.name).unwrap(),
929 )
930 };
931 self.report_error(
932 span,
933 ResolutionError::FailedToResolve {
934 segment: Some(segment),
935 label,
936 suggestion,
937 module,
938 },
939 );
940 }
941 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
942 }
943 }
944
945 let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
946 for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
947 match self.early_resolve_ident_in_lexical_scope(
948 ident,
949 ScopeSet::Macro(kind),
950 &parent_scope,
951 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
952 true,
953 None,
954 None,
955 ) {
956 Ok(binding) => {
957 let initial_res = initial_binding.map(|initial_binding| {
958 self.record_use(ident, initial_binding, Used::Other);
959 initial_binding.res()
960 });
961 let res = binding.res();
962 let seg = Segment::from_ident(ident);
963 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
964 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
965 let node_id = self
966 .invocation_parents
967 .get(&parent_scope.expansion)
968 .map_or(ast::CRATE_NODE_ID, |parent| {
969 self.def_id_to_node_id(parent.parent_def)
970 });
971 self.lint_buffer.buffer_lint(
972 LEGACY_DERIVE_HELPERS,
973 node_id,
974 ident.span,
975 BuiltinLintDiag::LegacyDeriveHelpers(binding.span),
976 );
977 }
978 }
979 Err(..) => {
980 let expected = kind.descr_expected();
981
982 let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
983 span: ident.span,
984 expected,
985 ident,
986 });
987 self.unresolved_macro_suggestions(
988 &mut err,
989 kind,
990 &parent_scope,
991 ident,
992 krate,
993 sugg_span,
994 );
995 err.emit();
996 }
997 }
998 }
999
1000 let builtin_attrs = mem::take(&mut self.builtin_attrs);
1001 for (ident, parent_scope) in builtin_attrs {
1002 let _ = self.early_resolve_ident_in_lexical_scope(
1003 ident,
1004 ScopeSet::Macro(MacroKind::Attr),
1005 &parent_scope,
1006 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1007 true,
1008 None,
1009 None,
1010 );
1011 }
1012 }
1013
1014 fn check_stability_and_deprecation(
1015 &mut self,
1016 ext: &SyntaxExtension,
1017 path: &ast::Path,
1018 node_id: NodeId,
1019 ) {
1020 let span = path.span;
1021 if let Some(stability) = &ext.stability {
1022 if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } =
1023 stability.level
1024 {
1025 let feature = stability.feature;
1026
1027 let is_allowed =
1028 |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1029 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1030 if !is_allowed(feature) && !allowed_by_implication {
1031 let lint_buffer = &mut self.lint_buffer;
1032 let soft_handler = |lint, span, msg: String| {
1033 lint_buffer.buffer_lint(
1034 lint,
1035 node_id,
1036 span,
1037 BuiltinLintDiag::UnstableFeature(
1038 msg.into(),
1040 ),
1041 )
1042 };
1043 stability::report_unstable(
1044 self.tcx.sess,
1045 feature,
1046 reason.to_opt_reason(),
1047 issue,
1048 None,
1049 is_soft,
1050 span,
1051 soft_handler,
1052 stability::UnstableKind::Regular,
1053 );
1054 }
1055 }
1056 }
1057 if let Some(depr) = &ext.deprecation {
1058 let path = pprust::path_to_string(path);
1059 stability::early_report_macro_deprecation(
1060 &mut self.lint_buffer,
1061 depr,
1062 span,
1063 node_id,
1064 path,
1065 );
1066 }
1067 }
1068
1069 fn prohibit_imported_non_macro_attrs(
1070 &self,
1071 binding: Option<NameBinding<'ra>>,
1072 res: Option<Res>,
1073 span: Span,
1074 ) {
1075 if let Some(Res::NonMacroAttr(kind)) = res {
1076 if kind != NonMacroAttrKind::Tool && binding.is_none_or(|b| b.is_import()) {
1077 let binding_span = binding.map(|binding| binding.span);
1078 self.dcx().emit_err(errors::CannotUseThroughAnImport {
1079 span,
1080 article: kind.article(),
1081 descr: kind.descr(),
1082 binding_span,
1083 });
1084 }
1085 }
1086 }
1087
1088 fn report_out_of_scope_macro_calls(
1089 &mut self,
1090 path: &ast::Path,
1091 parent_scope: &ParentScope<'ra>,
1092 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1093 binding: Option<NameBinding<'ra>>,
1094 ) {
1095 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1096 && let Some(binding) = binding
1097 && let NameBindingKind::Res(res) = binding.kind
1099 && let Res::Def(DefKind::Macro(MacroKind::Bang), def_id) = res
1100 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1103 {
1104 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1108 let fallback_binding = self.early_resolve_ident_in_lexical_scope(
1109 path.segments[0].ident,
1110 ScopeSet::Macro(MacroKind::Bang),
1111 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1112 None,
1113 false,
1114 None,
1115 None,
1116 );
1117 if fallback_binding.ok().and_then(|b| b.res().opt_def_id()) != Some(def_id) {
1118 let location = match parent_scope.module.kind {
1119 ModuleKind::Def(kind, def_id, name) => {
1120 if let Some(name) = name {
1121 format!("{} `{name}`", kind.descr(def_id))
1122 } else {
1123 "the crate root".to_string()
1124 }
1125 }
1126 ModuleKind::Block => "this scope".to_string(),
1127 };
1128 self.tcx.sess.psess.buffer_lint(
1129 OUT_OF_SCOPE_MACRO_CALLS,
1130 path.span,
1131 node_id,
1132 BuiltinLintDiag::OutOfScopeMacroCalls {
1133 span: path.span,
1134 path: pprust::path_to_string(path),
1135 location,
1136 },
1137 );
1138 }
1139 }
1140 }
1141
1142 pub(crate) fn check_reserved_macro_name(&self, ident: Ident, res: Res) {
1143 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1146 let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
1147 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
1148 self.dcx()
1149 .emit_err(errors::NameReservedInAttributeNamespace { span: ident.span, ident });
1150 }
1151 }
1152 }
1153
1154 pub(crate) fn compile_macro(
1158 &self,
1159 macro_def: &ast::MacroDef,
1160 ident: Ident,
1161 attrs: &[rustc_hir::Attribute],
1162 span: Span,
1163 node_id: NodeId,
1164 edition: Edition,
1165 ) -> MacroData {
1166 let (mut ext, mut nrules) = compile_declarative_macro(
1167 self.tcx.sess,
1168 self.tcx.features(),
1169 macro_def,
1170 ident,
1171 attrs,
1172 span,
1173 node_id,
1174 edition,
1175 );
1176
1177 if let Some(builtin_name) = ext.builtin_name {
1178 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1180 ext.kind = builtin_ext_kind.clone();
1183 nrules = 0;
1184 } else {
1185 self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1186 }
1187 }
1188
1189 MacroData { ext: Arc::new(ext), nrules, macro_rules: macro_def.macro_rules }
1190 }
1191
1192 fn path_accessible(
1193 &mut self,
1194 expn_id: LocalExpnId,
1195 path: &ast::Path,
1196 namespaces: &[Namespace],
1197 ) -> Result<bool, Indeterminate> {
1198 let span = path.span;
1199 let path = &Segment::from_path(path);
1200 let parent_scope = self.invocation_parent_scopes[&expn_id];
1201
1202 let mut indeterminate = false;
1203 for ns in namespaces {
1204 match self.maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1205 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1206 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1207 return Ok(true);
1208 }
1209 PathResult::NonModule(..) |
1210 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1212 self.dcx()
1213 .emit_err(errors::CfgAccessibleUnsure { span });
1214
1215 return Ok(false);
1218 }
1219 PathResult::Indeterminate => indeterminate = true,
1220 PathResult::Failed { .. } => {}
1223 PathResult::Module(_) => panic!("unexpected path resolution"),
1224 }
1225 }
1226
1227 if indeterminate {
1228 return Err(Indeterminate);
1229 }
1230
1231 Ok(false)
1232 }
1233}