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, DeriveData, Determinacy, Finalize, InvocationParent,
42 MacroData, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope,
43 PathResult, ResolutionError, Resolver, ScopeSet, Segment, Used,
44};
45
46type Res = def::Res<NodeId>;
47
48#[derive(Debug)]
51pub(crate) struct MacroRulesBinding<'ra> {
52 pub(crate) binding: NameBinding<'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 Binding(&'ra MacroRulesBinding<'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 let binding = self.arenas.new_pub_res_binding(res, ident.span, expn_id);
435 (*ident, binding)
436 })
437 .collect();
438 self.helper_attrs.insert(expn_id, helper_attrs);
439 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
448 self.containers_deriving_copy.insert(expn_id);
449 }
450 assert!(self.derive_data.is_empty());
451 self.derive_data = derive_data;
452 Ok(())
453 }
454
455 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
456 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
457 }
458
459 fn cfg_accessible(
464 &mut self,
465 expn_id: LocalExpnId,
466 path: &ast::Path,
467 ) -> Result<bool, Indeterminate> {
468 self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
469 }
470
471 fn macro_accessible(
472 &mut self,
473 expn_id: LocalExpnId,
474 path: &ast::Path,
475 ) -> Result<bool, Indeterminate> {
476 self.path_accessible(expn_id, path, &[MacroNS])
477 }
478
479 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
480 self.cstore().get_proc_macro_quoted_span_untracked(self.tcx, krate, id)
481 }
482
483 fn declare_proc_macro(&mut self, id: NodeId) {
484 self.proc_macros.push(self.local_def_id(id))
485 }
486
487 fn append_stripped_cfg_item(
488 &mut self,
489 parent_node: NodeId,
490 ident: Ident,
491 cfg: CfgEntry,
492 cfg_span: Span,
493 ) {
494 self.stripped_cfg_items.push(StrippedCfgItem {
495 parent_module: parent_node,
496 ident,
497 cfg: (cfg, cfg_span),
498 });
499 }
500
501 fn registered_tools(&self) -> &RegisteredTools {
502 self.registered_tools
503 }
504
505 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
506 self.glob_delegation_invoc_ids.insert(invoc_id);
507 }
508
509 fn glob_delegation_suffixes(
510 &self,
511 trait_def_id: DefId,
512 impl_def_id: LocalDefId,
513 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
514 let target_trait = self.expect_module(trait_def_id);
515 if !target_trait.unexpanded_invocations.borrow().is_empty() {
516 return Err(Indeterminate);
517 }
518 if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
525 && !unexpanded_invocations.is_empty()
526 {
527 return Err(Indeterminate);
528 }
529
530 let mut idents = Vec::new();
531 target_trait.for_each_child(self, |this, ident, ns, _binding| {
532 if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
534 && overriding_keys.contains(&BindingKey::new(ident.0, ns))
535 {
536 } else {
538 idents.push((ident.0, None));
539 }
540 });
541 Ok(idents)
542 }
543
544 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
545 self.impl_trait_names.insert(id, name);
546 }
547}
548
549impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
550 fn smart_resolve_macro_path(
554 &mut self,
555 path: &ast::Path,
556 kind: MacroKind,
557 supports_macro_expansion: SupportsMacroExpansion,
558 inner_attr: bool,
559 parent_scope: &ParentScope<'ra>,
560 node_id: NodeId,
561 force: bool,
562 deleg_impl: Option<LocalDefId>,
563 invoc_in_mod_inert_attr: Option<LocalDefId>,
564 suggestion_span: Option<Span>,
565 ) -> Result<(Arc<SyntaxExtension>, Res), Indeterminate> {
566 let (ext, res) = match self.cm().resolve_macro_or_delegation_path(
567 path,
568 kind,
569 parent_scope,
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_kinds().contains(kind.into()) {
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_kinds().contains(MacroKinds::DERIVE)
663 && ext.macro_kinds().contains(MacroKinds::ATTR)
664 {
665 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
666 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
667 }
668
669 self.dcx().emit_err(err);
670
671 return Ok((self.dummy_ext(kind), Res::Err));
672 }
673
674 if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
676 let is_macro = match res {
677 Res::Def(..) => true,
678 Res::NonMacroAttr(..) => false,
679 _ => unreachable!(),
680 };
681 let msg = if is_macro {
682 "inner macro attributes are unstable"
683 } else {
684 "custom inner attributes are unstable"
685 };
686 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
687 }
688
689 const DIAG_ATTRS: &[Symbol] =
690 &[sym::on_unimplemented, sym::do_not_recommend, sym::on_const];
691
692 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
693 && let [namespace, attribute, ..] = &*path.segments
694 && namespace.ident.name == sym::diagnostic
695 && !DIAG_ATTRS.contains(&attribute.ident.name)
696 {
697 let span = attribute.span();
698
699 let typo = find_best_match_for_name(DIAG_ATTRS, attribute.ident.name, Some(5))
700 .map(|typo_name| errors::UnknownDiagnosticAttributeTypoSugg { span, typo_name });
701
702 self.tcx.sess.psess.buffer_lint(
703 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
704 span,
705 node_id,
706 errors::UnknownDiagnosticAttribute { typo },
707 );
708 }
709
710 Ok((ext, res))
711 }
712
713 pub(crate) fn resolve_derive_macro_path<'r>(
714 self: CmResolver<'r, 'ra, 'tcx>,
715 path: &ast::Path,
716 parent_scope: &ParentScope<'ra>,
717 force: bool,
718 ignore_import: Option<Import<'ra>>,
719 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
720 self.resolve_macro_or_delegation_path(
721 path,
722 MacroKind::Derive,
723 parent_scope,
724 force,
725 None,
726 None,
727 ignore_import,
728 None,
729 )
730 }
731
732 fn resolve_macro_or_delegation_path<'r>(
733 mut self: CmResolver<'r, 'ra, 'tcx>,
734 ast_path: &ast::Path,
735 kind: MacroKind,
736 parent_scope: &ParentScope<'ra>,
737 force: bool,
738 deleg_impl: Option<LocalDefId>,
739 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
740 ignore_import: Option<Import<'ra>>,
741 suggestion_span: Option<Span>,
742 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
743 let path_span = ast_path.span;
744 let mut path = Segment::from_path(ast_path);
745
746 if deleg_impl.is_none()
748 && kind == MacroKind::Bang
749 && let [segment] = path.as_slice()
750 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
751 {
752 let root = Ident::new(kw::DollarCrate, segment.ident.span);
753 path.insert(0, Segment::from_ident(root));
754 }
755
756 let res = if deleg_impl.is_some() || path.len() > 1 {
757 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
758 let res = match self.reborrow().maybe_resolve_path(
759 &path,
760 Some(ns),
761 parent_scope,
762 ignore_import,
763 ) {
764 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
765 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
766 PathResult::NonModule(..)
767 | PathResult::Indeterminate
768 | PathResult::Failed { .. } => Err(Determinacy::Determined),
769 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
770 Ok(module.res().unwrap())
771 }
772 PathResult::Module(..) => unreachable!(),
773 };
774
775 self.multi_segment_macro_resolutions.borrow_mut(&self).push((
776 path,
777 path_span,
778 kind,
779 *parent_scope,
780 res.ok(),
781 ns,
782 ));
783
784 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
785 res
786 } else {
787 let binding = self.reborrow().resolve_ident_in_scope_set(
788 path[0].ident,
789 ScopeSet::Macro(kind),
790 parent_scope,
791 None,
792 force,
793 None,
794 None,
795 );
796 if let Err(Determinacy::Undetermined) = binding {
797 return Err(Determinacy::Undetermined);
798 }
799
800 self.single_segment_macro_resolutions.borrow_mut(&self).push((
801 path[0].ident,
802 kind,
803 *parent_scope,
804 binding.ok(),
805 suggestion_span,
806 ));
807
808 let res = binding.map(|binding| binding.res());
809 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
810 self.reborrow().report_out_of_scope_macro_calls(
811 ast_path,
812 parent_scope,
813 invoc_in_mod_inert_attr,
814 binding.ok(),
815 );
816 res
817 };
818
819 let res = res?;
820 let ext = match deleg_impl {
821 Some(impl_def_id) => match res {
822 def::Res::Def(DefKind::Trait, def_id) => {
823 let edition = self.tcx.sess.edition();
824 Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
825 }
826 _ => None,
827 },
828 None => self.get_macro(res).map(|macro_data| Arc::clone(¯o_data.ext)),
829 };
830 Ok((ext, res))
831 }
832
833 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
834 let check_consistency = |this: &Self,
835 path: &[Segment],
836 span,
837 kind: MacroKind,
838 initial_res: Option<Res>,
839 res: Res| {
840 if let Some(initial_res) = initial_res {
841 if res != initial_res {
842 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
846 }
847 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
848 let err = this.dcx().create_err(CannotDetermineMacroResolution {
857 span,
858 kind: kind.descr(),
859 path: Segment::names_to_string(path),
860 });
861 err.stash(span, StashKey::UndeterminedMacroResolution);
862 }
863 };
864
865 let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
866 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
867 for seg in &mut path {
869 seg.id = None;
870 }
871 match self.cm().resolve_path(
872 &path,
873 Some(ns),
874 &parent_scope,
875 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
876 None,
877 None,
878 ) {
879 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
880 check_consistency(self, &path, path_span, kind, initial_res, res)
881 }
882 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
884 self,
885 &path,
886 path_span,
887 kind,
888 initial_res,
889 module.res().unwrap(),
890 ),
891 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
892 let mut suggestion = None;
893 let (span, label, module, segment) =
894 if let PathResult::Failed { span, label, module, segment_name, .. } =
895 path_res
896 {
897 if let PathResult::NonModule(partial_res) = self
899 .cm()
900 .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
901 && partial_res.unresolved_segments() == 0
902 {
903 let sm = self.tcx.sess.source_map();
904 let exclamation_span = sm.next_point(span);
905 suggestion = Some((
906 vec![(exclamation_span, "".to_string())],
907 format!(
908 "{} is not a macro, but a {}, try to remove `!`",
909 Segment::names_to_string(&path),
910 partial_res.base_res().descr()
911 ),
912 Applicability::MaybeIncorrect,
913 ));
914 }
915 (span, label, module, segment_name)
916 } else {
917 (
918 path_span,
919 format!(
920 "partially resolved path in {} {}",
921 kind.article(),
922 kind.descr()
923 ),
924 None,
925 path.last().map(|segment| segment.ident.name).unwrap(),
926 )
927 };
928 self.report_error(
929 span,
930 ResolutionError::FailedToResolve {
931 segment: Some(segment),
932 label,
933 suggestion,
934 module,
935 },
936 );
937 }
938 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
939 }
940 }
941
942 let macro_resolutions = self.single_segment_macro_resolutions.take(self);
943 for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
944 match self.cm().resolve_ident_in_scope_set(
945 ident,
946 ScopeSet::Macro(kind),
947 &parent_scope,
948 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
949 true,
950 None,
951 None,
952 ) {
953 Ok(binding) => {
954 let initial_res = initial_binding.map(|initial_binding| {
955 self.record_use(ident, initial_binding, Used::Other);
956 initial_binding.res()
957 });
958 let res = binding.res();
959 let seg = Segment::from_ident(ident);
960 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
961 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
962 let node_id = self
963 .invocation_parents
964 .get(&parent_scope.expansion)
965 .map_or(ast::CRATE_NODE_ID, |parent| {
966 self.def_id_to_node_id(parent.parent_def)
967 });
968 self.lint_buffer.buffer_lint(
969 LEGACY_DERIVE_HELPERS,
970 node_id,
971 ident.span,
972 errors::LegacyDeriveHelpers { span: binding.span },
973 );
974 }
975 }
976 Err(..) => {
977 let expected = kind.descr_expected();
978
979 let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
980 span: ident.span,
981 expected,
982 ident,
983 });
984 self.unresolved_macro_suggestions(
985 &mut err,
986 kind,
987 &parent_scope,
988 ident,
989 krate,
990 sugg_span,
991 );
992 err.emit();
993 }
994 }
995 }
996
997 let builtin_attrs = mem::take(&mut self.builtin_attrs);
998 for (ident, parent_scope) in builtin_attrs {
999 let _ = self.cm().resolve_ident_in_scope_set(
1000 ident,
1001 ScopeSet::Macro(MacroKind::Attr),
1002 &parent_scope,
1003 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1004 true,
1005 None,
1006 None,
1007 );
1008 }
1009 }
1010
1011 fn check_stability_and_deprecation(
1012 &mut self,
1013 ext: &SyntaxExtension,
1014 path: &ast::Path,
1015 node_id: NodeId,
1016 ) {
1017 let span = path.span;
1018 if let Some(stability) = &ext.stability
1019 && let StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. } =
1020 stability.level
1021 {
1022 let feature = stability.feature;
1023
1024 let is_allowed =
1025 |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1026 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1027 if !is_allowed(feature) && !allowed_by_implication {
1028 let lint_buffer = &mut self.lint_buffer;
1029 let soft_handler = |lint, span, msg: String| {
1030 lint_buffer.buffer_lint(
1031 lint,
1032 node_id,
1033 span,
1034 errors::UnstableFeature { msg: msg.into() },
1036 )
1037 };
1038 stability::report_unstable(
1039 self.tcx.sess,
1040 feature,
1041 reason.to_opt_reason(),
1042 issue,
1043 None,
1044 is_soft,
1045 span,
1046 soft_handler,
1047 stability::UnstableKind::Regular,
1048 );
1049 }
1050 }
1051 if let Some(depr) = &ext.deprecation {
1052 let path = pprust::path_to_string(path);
1053 stability::early_report_macro_deprecation(
1054 &mut self.lint_buffer,
1055 depr,
1056 span,
1057 node_id,
1058 path,
1059 );
1060 }
1061 }
1062
1063 fn prohibit_imported_non_macro_attrs(
1064 &self,
1065 binding: Option<NameBinding<'ra>>,
1066 res: Option<Res>,
1067 span: Span,
1068 ) {
1069 if let Some(Res::NonMacroAttr(kind)) = res {
1070 if kind != NonMacroAttrKind::Tool && binding.is_none_or(|b| b.is_import()) {
1071 let binding_span = binding.map(|binding| binding.span);
1072 self.dcx().emit_err(errors::CannotUseThroughAnImport {
1073 span,
1074 article: kind.article(),
1075 descr: kind.descr(),
1076 binding_span,
1077 });
1078 }
1079 }
1080 }
1081
1082 fn report_out_of_scope_macro_calls<'r>(
1083 mut self: CmResolver<'r, 'ra, 'tcx>,
1084 path: &ast::Path,
1085 parent_scope: &ParentScope<'ra>,
1086 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1087 binding: Option<NameBinding<'ra>>,
1088 ) {
1089 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1090 && let Some(binding) = binding
1091 && let NameBindingKind::Res(res) = binding.kind
1093 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1094 && kinds.contains(MacroKinds::BANG)
1095 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1098 {
1099 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1103 let ident = path.segments[0].ident;
1104 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1105 ident,
1106 ScopeSet::Macro(MacroKind::Bang),
1107 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1108 None,
1109 false,
1110 None,
1111 None,
1112 );
1113 if let Ok(fallback_binding) = fallback_binding
1114 && fallback_binding.res().opt_def_id() == Some(def_id)
1115 {
1116 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1118 } else {
1119 let location = match parent_scope.module.kind {
1120 ModuleKind::Def(kind, def_id, name) => {
1121 if let Some(name) = name {
1122 format!("{} `{name}`", kind.descr(def_id))
1123 } else {
1124 "the crate root".to_string()
1125 }
1126 }
1127 ModuleKind::Block => "this scope".to_string(),
1128 };
1129 self.tcx.sess.psess.buffer_lint(
1130 OUT_OF_SCOPE_MACRO_CALLS,
1131 path.span,
1132 node_id,
1133 errors::OutOfScopeMacroCalls {
1134 span: path.span,
1135 path: pprust::path_to_string(path),
1136 location,
1138 },
1139 );
1140 }
1141 }
1142 }
1143
1144 pub(crate) fn check_reserved_macro_name(&self, ident: Ident, res: Res) {
1145 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1148 let macro_kinds = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kinds());
1149 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1150 self.dcx()
1151 .emit_err(errors::NameReservedInAttributeNamespace { span: ident.span, ident });
1152 }
1153 }
1154 }
1155
1156 pub(crate) fn compile_macro(
1160 &self,
1161 macro_def: &ast::MacroDef,
1162 ident: Ident,
1163 attrs: &[rustc_hir::Attribute],
1164 span: Span,
1165 node_id: NodeId,
1166 edition: Edition,
1167 ) -> MacroData {
1168 let (mut ext, mut nrules) = compile_declarative_macro(
1169 self.tcx.sess,
1170 self.tcx.features(),
1171 macro_def,
1172 ident,
1173 attrs,
1174 span,
1175 node_id,
1176 edition,
1177 );
1178
1179 if let Some(builtin_name) = ext.builtin_name {
1180 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1182 ext.kind = builtin_ext_kind.clone();
1185 nrules = 0;
1186 } else {
1187 self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1188 }
1189 }
1190
1191 MacroData { ext: Arc::new(ext), nrules, macro_rules: macro_def.macro_rules }
1192 }
1193
1194 fn path_accessible(
1195 &mut self,
1196 expn_id: LocalExpnId,
1197 path: &ast::Path,
1198 namespaces: &[Namespace],
1199 ) -> Result<bool, Indeterminate> {
1200 let span = path.span;
1201 let path = &Segment::from_path(path);
1202 let parent_scope = self.invocation_parent_scopes[&expn_id];
1203
1204 let mut indeterminate = false;
1205 for ns in namespaces {
1206 match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1207 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1208 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1209 return Ok(true);
1210 }
1211 PathResult::NonModule(..) |
1212 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1214 self.dcx()
1215 .emit_err(errors::CfgAccessibleUnsure { span });
1216
1217 return Ok(false);
1220 }
1221 PathResult::Indeterminate => indeterminate = true,
1222 PathResult::Failed { .. } => {}
1225 PathResult::Module(_) => panic!("unexpected path resolution"),
1226 }
1227 }
1228
1229 if indeterminate {
1230 return Err(Indeterminate);
1231 }
1232
1233 Ok(false)
1234 }
1235}