1use std::mem;
5use std::sync::Arc;
6
7use rustc_ast::{self as ast, Crate, NodeId, attr};
8use rustc_ast_pretty::pprust;
9use rustc_errors::{Applicability, DiagCtxtHandle, StashKey};
10use rustc_expand::base::{
11 Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension,
12 SyntaxExtensionKind,
13};
14use rustc_expand::compile_declarative_macro;
15use rustc_expand::expand::{
16 AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion,
17};
18use rustc_hir::StabilityLevel;
19use rustc_hir::attrs::{CfgEntry, StrippedCfgItem};
20use rustc_hir::def::{self, DefKind, MacroKinds, 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::builtin::{
25 LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
26 UNUSED_MACRO_RULES, UNUSED_MACROS,
27};
28use rustc_session::parse::feature_err;
29use rustc_span::edit_distance::find_best_match_for_name;
30use rustc_span::edition::Edition;
31use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
32use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
33
34use crate::Namespace::*;
35use crate::errors::{
36 self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
37 MacroExpectedFound, RemoveSurroundingDerive,
38};
39use crate::imports::Import;
40use crate::{
41 BindingKey, CacheCell, CmResolver, Decl, DeclKind, DeriveData, Determinacy, Finalize,
42 InvocationParent, MacroData, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult,
43 ResolutionError, Resolver, ScopeSet, Segment, Used,
44};
45
46type Res = def::Res<NodeId>;
47
48#[derive(Debug)]
51pub(crate) struct MacroRulesDecl<'ra> {
52 pub(crate) decl: Decl<'ra>,
53 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
55 pub(crate) ident: Ident,
56}
57
58#[derive(Copy, Clone, Debug)]
64pub(crate) enum MacroRulesScope<'ra> {
65 Empty,
67 Def(&'ra MacroRulesDecl<'ra>),
69 Invocation(LocalExpnId),
72}
73
74pub(crate) type MacroRulesScopeRef<'ra> = &'ra CacheCell<MacroRulesScope<'ra>>;
81
82pub(crate) fn sub_namespace_match(
86 candidate: Option<MacroKinds>,
87 requirement: Option<MacroKind>,
88) -> bool {
89 let (Some(candidate), Some(requirement)) = (candidate, requirement) else {
91 return true;
92 };
93 match requirement {
94 MacroKind::Bang => candidate.contains(MacroKinds::BANG),
95 MacroKind::Attr | MacroKind::Derive => {
96 candidate.intersects(MacroKinds::ATTR | MacroKinds::DERIVE)
97 }
98 }
99}
100
101fn fast_print_path(path: &ast::Path) -> Symbol {
105 if let [segment] = path.segments.as_slice() {
106 segment.ident.name
107 } else {
108 let mut path_str = String::with_capacity(64);
109 for (i, segment) in path.segments.iter().enumerate() {
110 if i != 0 {
111 path_str.push_str("::");
112 }
113 if segment.ident.name != kw::PathRoot {
114 path_str.push_str(segment.ident.as_str())
115 }
116 }
117 Symbol::intern(&path_str)
118 }
119}
120
121pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
122 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
123 registered_tools_ast(tcx.dcx(), pre_configured_attrs)
124}
125
126pub fn registered_tools_ast(
127 dcx: DiagCtxtHandle<'_>,
128 pre_configured_attrs: &[ast::Attribute],
129) -> RegisteredTools {
130 let mut registered_tools = RegisteredTools::default();
131 for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
132 for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
133 match meta_item_inner.ident() {
134 Some(ident) => {
135 if let Some(old_ident) = registered_tools.replace(ident) {
136 dcx.emit_err(errors::ToolWasAlreadyRegistered {
137 span: ident.span,
138 tool: ident,
139 old_ident_span: old_ident.span,
140 });
141 }
142 }
143 None => {
144 dcx.emit_err(errors::ToolOnlyAcceptsIdentifiers {
145 span: meta_item_inner.span(),
146 tool: sym::register_tool,
147 });
148 }
149 }
150 }
151 }
152 let predefined_tools =
155 [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
156 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
157 registered_tools
158}
159
160impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
161 fn next_node_id(&mut self) -> NodeId {
162 self.next_node_id()
163 }
164
165 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
166 self.invocation_parents[&id].parent_def
167 }
168
169 fn resolve_dollar_crates(&self) {
170 hygiene::update_dollar_crate_names(|ctxt| {
171 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
172 match self.resolve_crate_root(ident).kind {
173 ModuleKind::Def(.., name) if let Some(name) = name => name,
174 _ => kw::Crate,
175 }
176 });
177 }
178
179 fn visit_ast_fragment_with_placeholders(
180 &mut self,
181 expansion: LocalExpnId,
182 fragment: &AstFragment,
183 ) {
184 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
187 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
188 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
189
190 parent_scope.module.unexpanded_invocations.borrow_mut(self).remove(&expansion);
191 if let Some(unexpanded_invocations) =
192 self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
193 {
194 unexpanded_invocations.remove(&expansion);
195 }
196 }
197
198 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
199 if self.builtin_macros.insert(name, ext).is_some() {
200 self.dcx().bug(format!("built-in macro `{name}` was already registered"));
201 }
202 }
203
204 fn expansion_for_ast_pass(
207 &mut self,
208 call_site: Span,
209 pass: AstPass,
210 features: &[Symbol],
211 parent_module_id: Option<NodeId>,
212 ) -> LocalExpnId {
213 let parent_module =
214 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
215 let expn_id = LocalExpnId::fresh(
216 ExpnData::allow_unstable(
217 ExpnKind::AstPass(pass),
218 call_site,
219 self.tcx.sess.edition(),
220 features.into(),
221 None,
222 parent_module,
223 ),
224 self.create_stable_hashing_context(),
225 );
226
227 let parent_scope =
228 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
229 self.ast_transform_scopes.insert(expn_id, parent_scope);
230
231 expn_id
232 }
233
234 fn resolve_imports(&mut self) {
235 self.resolve_imports()
236 }
237
238 fn resolve_macro_invocation(
239 &mut self,
240 invoc: &Invocation,
241 eager_expansion_root: LocalExpnId,
242 force: bool,
243 ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
244 let invoc_id = invoc.expansion_data.id;
245 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
246 Some(parent_scope) => *parent_scope,
247 None => {
248 let parent_scope = *self
252 .invocation_parent_scopes
253 .get(&eager_expansion_root)
254 .expect("non-eager expansion without a parent scope");
255 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
256 parent_scope
257 }
258 };
259
260 let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
261 let (path, kind) = match invoc.kind {
262 InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
263 derives = self.arenas.alloc_ast_paths(attr_derives);
264 inner_attr = attr.style == ast::AttrStyle::Inner;
265 (&attr.get_normal_item().path, MacroKind::Attr)
266 }
267 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
268 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
269 InvocationKind::GlobDelegation { ref item, .. } => {
270 let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() };
271 deleg_impl = Some(self.invocation_parent(invoc_id));
272 (&deleg.prefix, MacroKind::Bang)
274 }
275 };
276
277 let parent_scope = &ParentScope { derives, ..parent_scope };
279 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
280 let node_id = invoc.expansion_data.lint_node_id;
281 let looks_like_invoc_in_mod_inert_attr = self
283 .invocation_parents
284 .get(&invoc_id)
285 .or_else(|| self.invocation_parents.get(&eager_expansion_root))
286 .filter(|&&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
287 in_attr
288 && invoc.fragment_kind == AstFragmentKind::Expr
289 && self.tcx.def_kind(mod_def_id) == DefKind::Mod
290 })
291 .map(|&InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
292 let sugg_span = match &invoc.kind {
293 InvocationKind::Attr { item: Annotatable::Item(item), .. }
294 if !item.span.from_expansion() =>
295 {
296 Some(item.span.shrink_to_lo())
297 }
298 _ => None,
299 };
300 let (ext, res) = self.smart_resolve_macro_path(
301 path,
302 kind,
303 supports_macro_expansion,
304 inner_attr,
305 parent_scope,
306 node_id,
307 force,
308 deleg_impl,
309 looks_like_invoc_in_mod_inert_attr,
310 sugg_span,
311 )?;
312
313 let span = invoc.span();
314 let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
315 invoc_id.set_expn_data(
316 ext.expn_data(
317 parent_scope.expansion,
318 span,
319 fast_print_path(path),
320 kind,
321 def_id,
322 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
323 ),
324 self.create_stable_hashing_context(),
325 );
326
327 Ok(ext)
328 }
329
330 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
331 if let Some(rules) = self.unused_macro_rules.get_mut(&id) {
332 rules.remove(rule_i);
333 }
334 }
335
336 fn check_unused_macros(&mut self) {
337 for (_, &(node_id, ident)) in self.unused_macros.iter() {
338 self.lint_buffer.buffer_lint(
339 UNUSED_MACROS,
340 node_id,
341 ident.span,
342 errors::UnusedMacroDefinition { name: ident.name },
343 );
344 self.unused_macro_rules.swap_remove(&node_id);
346 }
347
348 for (&node_id, unused_arms) in self.unused_macro_rules.iter() {
349 if unused_arms.is_empty() {
350 continue;
351 }
352 let def_id = self.local_def_id(node_id);
353 let m = &self.local_macro_map[&def_id];
354 let SyntaxExtensionKind::MacroRules(ref m) = m.ext.kind else {
355 continue;
356 };
357 for arm_i in unused_arms.iter() {
358 if let Some((ident, rule_span)) = m.get_unused_rule(arm_i) {
359 self.lint_buffer.buffer_lint(
360 UNUSED_MACRO_RULES,
361 node_id,
362 rule_span,
363 errors::MacroRuleNeverUsed { n: arm_i + 1, name: ident.name },
364 );
365 }
366 }
367 }
368 }
369
370 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
371 self.containers_deriving_copy.contains(&expn_id)
372 }
373
374 fn resolve_derives(
375 &mut self,
376 expn_id: LocalExpnId,
377 force: bool,
378 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
379 ) -> Result<(), Indeterminate> {
380 let mut derive_data = mem::take(&mut self.derive_data);
389 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
390 resolutions: derive_paths(),
391 helper_attrs: Vec::new(),
392 has_derive_copy: false,
393 });
394 let parent_scope = self.invocation_parent_scopes[&expn_id];
395 for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
396 if resolution.exts.is_none() {
397 resolution.exts = Some(
398 match self.cm().resolve_derive_macro_path(
399 &resolution.path,
400 &parent_scope,
401 force,
402 None,
403 ) {
404 Ok((Some(ext), _)) => {
405 if !ext.helper_attrs.is_empty() {
406 let last_seg = resolution.path.segments.last().unwrap();
407 let span = last_seg.ident.span.normalize_to_macros_2_0();
408 entry.helper_attrs.extend(
409 ext.helper_attrs
410 .iter()
411 .map(|name| (i, Ident::new(*name, span))),
412 );
413 }
414 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
415 ext
416 }
417 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
418 Err(Determinacy::Undetermined) => {
419 assert!(self.derive_data.is_empty());
420 self.derive_data = derive_data;
421 return Err(Indeterminate);
422 }
423 },
424 );
425 }
426 }
427 entry.helper_attrs.sort_by_key(|(i, _)| *i);
429 let helper_attrs = entry
430 .helper_attrs
431 .iter()
432 .map(|(_, ident)| {
433 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
434 (*ident, self.arenas.new_pub_def_decl(res, ident.span, expn_id))
435 })
436 .collect();
437 self.helper_attrs.insert(expn_id, helper_attrs);
438 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(self.tcx, krate, id)
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 &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.0, ns))
534 {
535 } else {
537 idents.push((ident.0, 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.cm().resolve_macro_or_delegation_path(
566 path,
567 kind,
568 parent_scope,
569 force,
570 deleg_impl,
571 invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
572 None,
573 suggestion_span,
574 ) {
575 Ok((Some(ext), res)) => (ext, res),
576 Ok((None, res)) => (self.dummy_ext(kind), res),
577 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
578 Err(Determinacy::Undetermined) => return Err(Indeterminate),
579 };
580
581 if deleg_impl.is_some() {
583 if !matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
584 self.dcx().emit_err(MacroExpectedFound {
585 span: path.span,
586 expected: "trait",
587 article: "a",
588 found: res.descr(),
589 macro_path: &pprust::path_to_string(path),
590 remove_surrounding_derive: None,
591 add_as_non_derive: None,
592 });
593 return Ok((self.dummy_ext(kind), Res::Err));
594 }
595
596 return Ok((ext, res));
597 }
598
599 for segment in &path.segments {
601 if let Some(args) = &segment.args {
602 self.dcx().emit_err(errors::GenericArgumentsInMacroPath { span: args.span() });
603 }
604 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
605 self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
606 span: segment.ident.span,
607 });
608 }
609 }
610
611 match res {
612 Res::Def(DefKind::Macro(_), def_id) => {
613 if let Some(def_id) = def_id.as_local() {
614 self.unused_macros.swap_remove(&def_id);
615 if self.proc_macro_stubs.contains(&def_id) {
616 self.dcx().emit_err(errors::ProcMacroSameCrate {
617 span: path.span,
618 is_test: self.tcx.sess.is_test_crate(),
619 });
620 }
621 }
622 }
623 Res::NonMacroAttr(..) | Res::Err => {}
624 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
625 };
626
627 self.check_stability_and_deprecation(&ext, path, node_id);
628
629 let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
630 Some((kind.article(), kind.descr_expected()))
631 } else if matches!(res, Res::Def(..)) {
632 match supports_macro_expansion {
633 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
634 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
635 if inner_attr && !supports_inner_attrs {
636 Some(("a", "non-macro inner attribute"))
637 } else {
638 None
639 }
640 }
641 }
642 } else {
643 None
644 };
645 if let Some((article, expected)) = unexpected_res {
646 let path_str = pprust::path_to_string(path);
647
648 let mut err = MacroExpectedFound {
649 span: path.span,
650 expected,
651 article,
652 found: res.descr(),
653 macro_path: &path_str,
654 remove_surrounding_derive: None,
655 add_as_non_derive: None,
656 };
657
658 if !path.span.from_expansion()
660 && kind == MacroKind::Derive
661 && !ext.macro_kinds().contains(MacroKinds::DERIVE)
662 && ext.macro_kinds().contains(MacroKinds::ATTR)
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 const DIAG_ATTRS: &[Symbol] =
689 &[sym::on_unimplemented, sym::do_not_recommend, sym::on_const];
690
691 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
692 && let [namespace, attribute, ..] = &*path.segments
693 && namespace.ident.name == sym::diagnostic
694 && !DIAG_ATTRS.contains(&attribute.ident.name)
695 {
696 let span = attribute.span();
697
698 let typo = find_best_match_for_name(DIAG_ATTRS, attribute.ident.name, Some(5))
699 .map(|typo_name| errors::UnknownDiagnosticAttributeTypoSugg { span, typo_name });
700
701 self.tcx.sess.psess.buffer_lint(
702 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
703 span,
704 node_id,
705 errors::UnknownDiagnosticAttribute { typo },
706 );
707 }
708
709 Ok((ext, res))
710 }
711
712 pub(crate) fn resolve_derive_macro_path<'r>(
713 self: CmResolver<'r, 'ra, 'tcx>,
714 path: &ast::Path,
715 parent_scope: &ParentScope<'ra>,
716 force: bool,
717 ignore_import: Option<Import<'ra>>,
718 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
719 self.resolve_macro_or_delegation_path(
720 path,
721 MacroKind::Derive,
722 parent_scope,
723 force,
724 None,
725 None,
726 ignore_import,
727 None,
728 )
729 }
730
731 fn resolve_macro_or_delegation_path<'r>(
732 mut self: CmResolver<'r, 'ra, 'tcx>,
733 ast_path: &ast::Path,
734 kind: MacroKind,
735 parent_scope: &ParentScope<'ra>,
736 force: bool,
737 deleg_impl: Option<LocalDefId>,
738 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
739 ignore_import: Option<Import<'ra>>,
740 suggestion_span: Option<Span>,
741 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
742 let path_span = ast_path.span;
743 let mut path = Segment::from_path(ast_path);
744
745 if deleg_impl.is_none()
747 && kind == MacroKind::Bang
748 && let [segment] = path.as_slice()
749 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
750 {
751 let root = Ident::new(kw::DollarCrate, segment.ident.span);
752 path.insert(0, Segment::from_ident(root));
753 }
754
755 let res = if deleg_impl.is_some() || path.len() > 1 {
756 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
757 let res = match self.reborrow().maybe_resolve_path(
758 &path,
759 Some(ns),
760 parent_scope,
761 ignore_import,
762 ) {
763 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
764 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
765 PathResult::NonModule(..)
766 | PathResult::Indeterminate
767 | PathResult::Failed { .. } => Err(Determinacy::Determined),
768 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
769 Ok(module.res().unwrap())
770 }
771 PathResult::Module(..) => unreachable!(),
772 };
773
774 self.multi_segment_macro_resolutions.borrow_mut(&self).push((
775 path,
776 path_span,
777 kind,
778 *parent_scope,
779 res.ok(),
780 ns,
781 ));
782
783 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
784 res
785 } else {
786 let binding = self.reborrow().resolve_ident_in_scope_set(
787 path[0].ident,
788 ScopeSet::Macro(kind),
789 parent_scope,
790 None,
791 force,
792 None,
793 None,
794 );
795 if let Err(Determinacy::Undetermined) = binding {
796 return Err(Determinacy::Undetermined);
797 }
798
799 self.single_segment_macro_resolutions.borrow_mut(&self).push((
800 path[0].ident,
801 kind,
802 *parent_scope,
803 binding.ok(),
804 suggestion_span,
805 ));
806
807 let res = binding.map(|binding| binding.res());
808 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
809 self.reborrow().report_out_of_scope_macro_calls(
810 ast_path,
811 parent_scope,
812 invoc_in_mod_inert_attr,
813 binding.ok(),
814 );
815 res
816 };
817
818 let res = res?;
819 let ext = match deleg_impl {
820 Some(impl_def_id) => match res {
821 def::Res::Def(DefKind::Trait, def_id) => {
822 let edition = self.tcx.sess.edition();
823 Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
824 }
825 _ => None,
826 },
827 None => self.get_macro(res).map(|macro_data| Arc::clone(¯o_data.ext)),
828 };
829 Ok((ext, res))
830 }
831
832 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
833 let check_consistency = |this: &Self,
834 path: &[Segment],
835 span,
836 kind: MacroKind,
837 initial_res: Option<Res>,
838 res: Res| {
839 if let Some(initial_res) = initial_res {
840 if res != initial_res {
841 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
845 }
846 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
847 let err = this.dcx().create_err(CannotDetermineMacroResolution {
856 span,
857 kind: kind.descr(),
858 path: Segment::names_to_string(path),
859 });
860 err.stash(span, StashKey::UndeterminedMacroResolution);
861 }
862 };
863
864 let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
865 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
866 for seg in &mut path {
868 seg.id = None;
869 }
870 match self.cm().resolve_path(
871 &path,
872 Some(ns),
873 &parent_scope,
874 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
875 None,
876 None,
877 ) {
878 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
879 check_consistency(self, &path, path_span, kind, initial_res, res)
880 }
881 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
883 self,
884 &path,
885 path_span,
886 kind,
887 initial_res,
888 module.res().unwrap(),
889 ),
890 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
891 let mut suggestion = None;
892 let (span, label, module, segment) =
893 if let PathResult::Failed { span, label, module, segment_name, .. } =
894 path_res
895 {
896 if let PathResult::NonModule(partial_res) = self
898 .cm()
899 .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
900 && partial_res.unresolved_segments() == 0
901 {
902 let sm = self.tcx.sess.source_map();
903 let exclamation_span = sm.next_point(span);
904 suggestion = Some((
905 vec![(exclamation_span, "".to_string())],
906 format!(
907 "{} is not a macro, but a {}, try to remove `!`",
908 Segment::names_to_string(&path),
909 partial_res.base_res().descr()
910 ),
911 Applicability::MaybeIncorrect,
912 ));
913 }
914 (span, label, module, segment_name)
915 } else {
916 (
917 path_span,
918 format!(
919 "partially resolved path in {} {}",
920 kind.article(),
921 kind.descr()
922 ),
923 None,
924 path.last().map(|segment| segment.ident.name).unwrap(),
925 )
926 };
927 self.report_error(
928 span,
929 ResolutionError::FailedToResolve {
930 segment: Some(segment),
931 label,
932 suggestion,
933 module,
934 },
935 );
936 }
937 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
938 }
939 }
940
941 let macro_resolutions = self.single_segment_macro_resolutions.take(self);
942 for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
943 match self.cm().resolve_ident_in_scope_set(
944 ident,
945 ScopeSet::Macro(kind),
946 &parent_scope,
947 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
948 true,
949 None,
950 None,
951 ) {
952 Ok(binding) => {
953 let initial_res = initial_binding.map(|initial_binding| {
954 self.record_use(ident, initial_binding, Used::Other);
955 initial_binding.res()
956 });
957 let res = binding.res();
958 let seg = Segment::from_ident(ident);
959 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
960 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
961 let node_id = self
962 .invocation_parents
963 .get(&parent_scope.expansion)
964 .map_or(ast::CRATE_NODE_ID, |parent| {
965 self.def_id_to_node_id(parent.parent_def)
966 });
967 self.lint_buffer.buffer_lint(
968 LEGACY_DERIVE_HELPERS,
969 node_id,
970 ident.span,
971 errors::LegacyDeriveHelpers { span: binding.span },
972 );
973 }
974 }
975 Err(..) => {
976 let expected = kind.descr_expected();
977
978 let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
979 span: ident.span,
980 expected,
981 ident,
982 });
983 self.unresolved_macro_suggestions(
984 &mut err,
985 kind,
986 &parent_scope,
987 ident,
988 krate,
989 sugg_span,
990 );
991 err.emit();
992 }
993 }
994 }
995
996 let builtin_attrs = mem::take(&mut self.builtin_attrs);
997 for (ident, parent_scope) in builtin_attrs {
998 let _ = self.cm().resolve_ident_in_scope_set(
999 ident,
1000 ScopeSet::Macro(MacroKind::Attr),
1001 &parent_scope,
1002 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1003 true,
1004 None,
1005 None,
1006 );
1007 }
1008 }
1009
1010 fn check_stability_and_deprecation(
1011 &mut self,
1012 ext: &SyntaxExtension,
1013 path: &ast::Path,
1014 node_id: NodeId,
1015 ) {
1016 let span = path.span;
1017 if let Some(stability) = &ext.stability
1018 && let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } =
1019 stability.level
1020 {
1021 let feature = stability.feature;
1022
1023 let is_allowed =
1024 |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1025 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1026 if !is_allowed(feature) && !allowed_by_implication {
1027 let lint_buffer = &mut self.lint_buffer;
1028 let soft_handler = |lint, span, msg: String| {
1029 lint_buffer.buffer_lint(
1030 lint,
1031 node_id,
1032 span,
1033 errors::UnstableFeature { msg: msg.into() },
1035 )
1036 };
1037 stability::report_unstable(
1038 self.tcx.sess,
1039 feature,
1040 reason.to_opt_reason(),
1041 issue,
1042 None,
1043 is_soft,
1044 span,
1045 soft_handler,
1046 stability::UnstableKind::Regular,
1047 );
1048 }
1049 }
1050 if let Some(depr) = &ext.deprecation {
1051 let path = pprust::path_to_string(path);
1052 stability::early_report_macro_deprecation(
1053 &mut self.lint_buffer,
1054 depr,
1055 span,
1056 node_id,
1057 path,
1058 );
1059 }
1060 }
1061
1062 fn prohibit_imported_non_macro_attrs(
1063 &self,
1064 decl: Option<Decl<'ra>>,
1065 res: Option<Res>,
1066 span: Span,
1067 ) {
1068 if let Some(Res::NonMacroAttr(kind)) = res {
1069 if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1070 self.dcx().emit_err(errors::CannotUseThroughAnImport {
1071 span,
1072 article: kind.article(),
1073 descr: kind.descr(),
1074 binding_span: decl.map(|d| d.span),
1075 });
1076 }
1077 }
1078 }
1079
1080 fn report_out_of_scope_macro_calls<'r>(
1081 mut self: CmResolver<'r, 'ra, 'tcx>,
1082 path: &ast::Path,
1083 parent_scope: &ParentScope<'ra>,
1084 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1085 decl: Option<Decl<'ra>>,
1086 ) {
1087 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1088 && let Some(decl) = decl
1089 && let DeclKind::Def(res) = decl.kind
1091 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1092 && kinds.contains(MacroKinds::BANG)
1093 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1096 {
1097 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1101 let ident = path.segments[0].ident;
1102 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1103 ident,
1104 ScopeSet::Macro(MacroKind::Bang),
1105 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1106 None,
1107 false,
1108 None,
1109 None,
1110 );
1111 if let Ok(fallback_binding) = fallback_binding
1112 && fallback_binding.res().opt_def_id() == Some(def_id)
1113 {
1114 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1116 } else {
1117 let location = match parent_scope.module.kind {
1118 ModuleKind::Def(kind, def_id, name) => {
1119 if let Some(name) = name {
1120 format!("{} `{name}`", kind.descr(def_id))
1121 } else {
1122 "the crate root".to_string()
1123 }
1124 }
1125 ModuleKind::Block => "this scope".to_string(),
1126 };
1127 self.tcx.sess.psess.buffer_lint(
1128 OUT_OF_SCOPE_MACRO_CALLS,
1129 path.span,
1130 node_id,
1131 errors::OutOfScopeMacroCalls {
1132 span: path.span,
1133 path: pprust::path_to_string(path),
1134 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_kinds = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kinds());
1147 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, 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.cm().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}