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::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, CacheCell, CmResolver, DeriveData, Determinacy, Finalize, InvocationParent,
43 MacroData, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope,
44 PathResult, ResolutionError, 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 CacheCell<MacroRulesScope<'ra>>;
82
83pub(crate) fn sub_namespace_match(
87 candidate: Option<MacroKinds>,
88 requirement: Option<MacroKind>,
89) -> bool {
90 let (Some(candidate), Some(requirement)) = (candidate, requirement) else {
92 return true;
93 };
94 match requirement {
95 MacroKind::Bang => candidate.contains(MacroKinds::BANG),
96 MacroKind::Attr | MacroKind::Derive => {
97 candidate.intersects(MacroKinds::ATTR | MacroKinds::DERIVE)
98 }
99 }
100}
101
102fn fast_print_path(path: &ast::Path) -> Symbol {
106 if let [segment] = path.segments.as_slice() {
107 segment.ident.name
108 } else {
109 let mut path_str = String::with_capacity(64);
110 for (i, segment) in path.segments.iter().enumerate() {
111 if i != 0 {
112 path_str.push_str("::");
113 }
114 if segment.ident.name != kw::PathRoot {
115 path_str.push_str(segment.ident.as_str())
116 }
117 }
118 Symbol::intern(&path_str)
119 }
120}
121
122pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
123 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
124 registered_tools_ast(tcx.dcx(), pre_configured_attrs)
125}
126
127pub fn registered_tools_ast(
128 dcx: DiagCtxtHandle<'_>,
129 pre_configured_attrs: &[ast::Attribute],
130) -> RegisteredTools {
131 let mut registered_tools = RegisteredTools::default();
132 for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
133 for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
134 match meta_item_inner.ident() {
135 Some(ident) => {
136 if let Some(old_ident) = registered_tools.replace(ident) {
137 dcx.emit_err(errors::ToolWasAlreadyRegistered {
138 span: ident.span,
139 tool: ident,
140 old_ident_span: old_ident.span,
141 });
142 }
143 }
144 None => {
145 dcx.emit_err(errors::ToolOnlyAcceptsIdentifiers {
146 span: meta_item_inner.span(),
147 tool: sym::register_tool,
148 });
149 }
150 }
151 }
152 }
153 let predefined_tools =
156 [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
157 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
158 registered_tools
159}
160
161impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
162 fn next_node_id(&mut self) -> NodeId {
163 self.next_node_id()
164 }
165
166 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
167 self.invocation_parents[&id].parent_def
168 }
169
170 fn resolve_dollar_crates(&self) {
171 hygiene::update_dollar_crate_names(|ctxt| {
172 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
173 match self.resolve_crate_root(ident).kind {
174 ModuleKind::Def(.., name) if let Some(name) = name => name,
175 _ => kw::Crate,
176 }
177 });
178 }
179
180 fn visit_ast_fragment_with_placeholders(
181 &mut self,
182 expansion: LocalExpnId,
183 fragment: &AstFragment,
184 ) {
185 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
188 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
189 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
190
191 parent_scope.module.unexpanded_invocations.borrow_mut(self).remove(&expansion);
192 if let Some(unexpanded_invocations) =
193 self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
194 {
195 unexpanded_invocations.remove(&expansion);
196 }
197 }
198
199 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
200 if self.builtin_macros.insert(name, ext).is_some() {
201 self.dcx().bug(format!("built-in macro `{name}` was already registered"));
202 }
203 }
204
205 fn expansion_for_ast_pass(
208 &mut self,
209 call_site: Span,
210 pass: AstPass,
211 features: &[Symbol],
212 parent_module_id: Option<NodeId>,
213 ) -> LocalExpnId {
214 let parent_module =
215 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
216 let expn_id = LocalExpnId::fresh(
217 ExpnData::allow_unstable(
218 ExpnKind::AstPass(pass),
219 call_site,
220 self.tcx.sess.edition(),
221 features.into(),
222 None,
223 parent_module,
224 ),
225 self.create_stable_hashing_context(),
226 );
227
228 let parent_scope =
229 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
230 self.ast_transform_scopes.insert(expn_id, parent_scope);
231
232 expn_id
233 }
234
235 fn resolve_imports(&mut self) {
236 self.resolve_imports()
237 }
238
239 fn resolve_macro_invocation(
240 &mut self,
241 invoc: &Invocation,
242 eager_expansion_root: LocalExpnId,
243 force: bool,
244 ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
245 let invoc_id = invoc.expansion_data.id;
246 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
247 Some(parent_scope) => *parent_scope,
248 None => {
249 let parent_scope = *self
253 .invocation_parent_scopes
254 .get(&eager_expansion_root)
255 .expect("non-eager expansion without a parent scope");
256 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
257 parent_scope
258 }
259 };
260
261 let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
262 let (path, kind) = match invoc.kind {
263 InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
264 derives = self.arenas.alloc_ast_paths(attr_derives);
265 inner_attr = attr.style == ast::AttrStyle::Inner;
266 (&attr.get_normal_item().path, MacroKind::Attr)
267 }
268 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
269 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
270 InvocationKind::GlobDelegation { ref item, .. } => {
271 let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() };
272 deleg_impl = Some(self.invocation_parent(invoc_id));
273 (&deleg.prefix, MacroKind::Bang)
275 }
276 };
277
278 let parent_scope = &ParentScope { derives, ..parent_scope };
280 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
281 let node_id = invoc.expansion_data.lint_node_id;
282 let looks_like_invoc_in_mod_inert_attr = self
284 .invocation_parents
285 .get(&invoc_id)
286 .or_else(|| self.invocation_parents.get(&eager_expansion_root))
287 .filter(|&&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
288 in_attr
289 && invoc.fragment_kind == AstFragmentKind::Expr
290 && self.tcx.def_kind(mod_def_id) == DefKind::Mod
291 })
292 .map(|&InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
293 let sugg_span = match &invoc.kind {
294 InvocationKind::Attr { item: Annotatable::Item(item), .. }
295 if !item.span.from_expansion() =>
296 {
297 Some(item.span.shrink_to_lo())
298 }
299 _ => None,
300 };
301 let (ext, res) = self.smart_resolve_macro_path(
302 path,
303 kind,
304 supports_macro_expansion,
305 inner_attr,
306 parent_scope,
307 node_id,
308 force,
309 deleg_impl,
310 looks_like_invoc_in_mod_inert_attr,
311 sugg_span,
312 )?;
313
314 let span = invoc.span();
315 let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
316 invoc_id.set_expn_data(
317 ext.expn_data(
318 parent_scope.expansion,
319 span,
320 fast_print_path(path),
321 kind,
322 def_id,
323 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
324 ),
325 self.create_stable_hashing_context(),
326 );
327
328 Ok(ext)
329 }
330
331 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
332 if let Some(rules) = self.unused_macro_rules.get_mut(&id) {
333 rules.remove(rule_i);
334 }
335 }
336
337 fn check_unused_macros(&mut self) {
338 for (_, &(node_id, ident)) in self.unused_macros.iter() {
339 self.lint_buffer.buffer_lint(
340 UNUSED_MACROS,
341 node_id,
342 ident.span,
343 BuiltinLintDiag::UnusedMacroDefinition(ident.name),
344 );
345 self.unused_macro_rules.swap_remove(&node_id);
347 }
348
349 for (&node_id, unused_arms) in self.unused_macro_rules.iter() {
350 if unused_arms.is_empty() {
351 continue;
352 }
353 let def_id = self.local_def_id(node_id);
354 let m = &self.local_macro_map[&def_id];
355 let SyntaxExtensionKind::MacroRules(ref m) = m.ext.kind else {
356 continue;
357 };
358 for arm_i in unused_arms.iter() {
359 if let Some((ident, rule_span)) = m.get_unused_rule(arm_i) {
360 self.lint_buffer.buffer_lint(
361 UNUSED_MACRO_RULES,
362 node_id,
363 rule_span,
364 BuiltinLintDiag::MacroRuleNeverUsed(arm_i, ident.name),
365 );
366 }
367 }
368 }
369 }
370
371 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
372 self.containers_deriving_copy.contains(&expn_id)
373 }
374
375 fn resolve_derives(
376 &mut self,
377 expn_id: LocalExpnId,
378 force: bool,
379 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
380 ) -> Result<(), Indeterminate> {
381 let mut derive_data = mem::take(&mut self.derive_data);
390 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
391 resolutions: derive_paths(),
392 helper_attrs: Vec::new(),
393 has_derive_copy: false,
394 });
395 let parent_scope = self.invocation_parent_scopes[&expn_id];
396 for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
397 if resolution.exts.is_none() {
398 resolution.exts = Some(
399 match self.cm().resolve_derive_macro_path(
400 &resolution.path,
401 &parent_scope,
402 force,
403 None,
404 ) {
405 Ok((Some(ext), _)) => {
406 if !ext.helper_attrs.is_empty() {
407 let last_seg = resolution.path.segments.last().unwrap();
408 let span = last_seg.ident.span.normalize_to_macros_2_0();
409 entry.helper_attrs.extend(
410 ext.helper_attrs
411 .iter()
412 .map(|name| (i, Ident::new(*name, span))),
413 );
414 }
415 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
416 ext
417 }
418 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
419 Err(Determinacy::Undetermined) => {
420 assert!(self.derive_data.is_empty());
421 self.derive_data = derive_data;
422 return Err(Indeterminate);
423 }
424 },
425 );
426 }
427 }
428 entry.helper_attrs.sort_by_key(|(i, _)| *i);
430 let helper_attrs = entry
431 .helper_attrs
432 .iter()
433 .map(|(_, ident)| {
434 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
435 let binding = self.arenas.new_pub_res_binding(res, ident.span, expn_id);
436 (*ident, binding)
437 })
438 .collect();
439 self.helper_attrs.insert(expn_id, helper_attrs);
440 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
449 self.containers_deriving_copy.insert(expn_id);
450 }
451 assert!(self.derive_data.is_empty());
452 self.derive_data = derive_data;
453 Ok(())
454 }
455
456 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
457 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
458 }
459
460 fn cfg_accessible(
465 &mut self,
466 expn_id: LocalExpnId,
467 path: &ast::Path,
468 ) -> Result<bool, Indeterminate> {
469 self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
470 }
471
472 fn macro_accessible(
473 &mut self,
474 expn_id: LocalExpnId,
475 path: &ast::Path,
476 ) -> Result<bool, Indeterminate> {
477 self.path_accessible(expn_id, path, &[MacroNS])
478 }
479
480 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
481 self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.tcx.sess)
482 }
483
484 fn declare_proc_macro(&mut self, id: NodeId) {
485 self.proc_macros.push(self.local_def_id(id))
486 }
487
488 fn append_stripped_cfg_item(
489 &mut self,
490 parent_node: NodeId,
491 ident: Ident,
492 cfg: CfgEntry,
493 cfg_span: Span,
494 ) {
495 self.stripped_cfg_items.push(StrippedCfgItem {
496 parent_module: parent_node,
497 ident,
498 cfg: (cfg, cfg_span),
499 });
500 }
501
502 fn registered_tools(&self) -> &RegisteredTools {
503 self.registered_tools
504 }
505
506 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
507 self.glob_delegation_invoc_ids.insert(invoc_id);
508 }
509
510 fn glob_delegation_suffixes(
511 &self,
512 trait_def_id: DefId,
513 impl_def_id: LocalDefId,
514 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
515 let target_trait = self.expect_module(trait_def_id);
516 if !target_trait.unexpanded_invocations.borrow().is_empty() {
517 return Err(Indeterminate);
518 }
519 if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
526 && !unexpanded_invocations.is_empty()
527 {
528 return Err(Indeterminate);
529 }
530
531 let mut idents = Vec::new();
532 target_trait.for_each_child(self, |this, ident, ns, _binding| {
533 if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
535 && overriding_keys.contains(&BindingKey::new(ident.0, ns))
536 {
537 } else {
539 idents.push((ident.0, None));
540 }
541 });
542 Ok(idents)
543 }
544
545 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
546 self.impl_trait_names.insert(id, name);
547 }
548}
549
550impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
551 fn smart_resolve_macro_path(
555 &mut self,
556 path: &ast::Path,
557 kind: MacroKind,
558 supports_macro_expansion: SupportsMacroExpansion,
559 inner_attr: bool,
560 parent_scope: &ParentScope<'ra>,
561 node_id: NodeId,
562 force: bool,
563 deleg_impl: Option<LocalDefId>,
564 invoc_in_mod_inert_attr: Option<LocalDefId>,
565 suggestion_span: Option<Span>,
566 ) -> Result<(Arc<SyntaxExtension>, Res), Indeterminate> {
567 let (ext, res) = match self.cm().resolve_macro_or_delegation_path(
568 path,
569 kind,
570 parent_scope,
571 force,
572 deleg_impl,
573 invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
574 None,
575 suggestion_span,
576 ) {
577 Ok((Some(ext), res)) => (ext, res),
578 Ok((None, res)) => (self.dummy_ext(kind), res),
579 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
580 Err(Determinacy::Undetermined) => return Err(Indeterminate),
581 };
582
583 if deleg_impl.is_some() {
585 if !matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
586 self.dcx().emit_err(MacroExpectedFound {
587 span: path.span,
588 expected: "trait",
589 article: "a",
590 found: res.descr(),
591 macro_path: &pprust::path_to_string(path),
592 remove_surrounding_derive: None,
593 add_as_non_derive: None,
594 });
595 return Ok((self.dummy_ext(kind), Res::Err));
596 }
597
598 return Ok((ext, res));
599 }
600
601 for segment in &path.segments {
603 if let Some(args) = &segment.args {
604 self.dcx().emit_err(errors::GenericArgumentsInMacroPath { span: args.span() });
605 }
606 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
607 self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
608 span: segment.ident.span,
609 });
610 }
611 }
612
613 match res {
614 Res::Def(DefKind::Macro(_), def_id) => {
615 if let Some(def_id) = def_id.as_local() {
616 self.unused_macros.swap_remove(&def_id);
617 if self.proc_macro_stubs.contains(&def_id) {
618 self.dcx().emit_err(errors::ProcMacroSameCrate {
619 span: path.span,
620 is_test: self.tcx.sess.is_test_crate(),
621 });
622 }
623 }
624 }
625 Res::NonMacroAttr(..) | Res::Err => {}
626 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
627 };
628
629 self.check_stability_and_deprecation(&ext, path, node_id);
630
631 let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
632 Some((kind.article(), kind.descr_expected()))
633 } else if matches!(res, Res::Def(..)) {
634 match supports_macro_expansion {
635 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
636 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
637 if inner_attr && !supports_inner_attrs {
638 Some(("a", "non-macro inner attribute"))
639 } else {
640 None
641 }
642 }
643 }
644 } else {
645 None
646 };
647 if let Some((article, expected)) = unexpected_res {
648 let path_str = pprust::path_to_string(path);
649
650 let mut err = MacroExpectedFound {
651 span: path.span,
652 expected,
653 article,
654 found: res.descr(),
655 macro_path: &path_str,
656 remove_surrounding_derive: None,
657 add_as_non_derive: None,
658 };
659
660 if !path.span.from_expansion()
662 && kind == MacroKind::Derive
663 && !ext.macro_kinds().contains(MacroKinds::DERIVE)
664 && ext.macro_kinds().contains(MacroKinds::ATTR)
665 {
666 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
667 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
668 }
669
670 self.dcx().emit_err(err);
671
672 return Ok((self.dummy_ext(kind), Res::Err));
673 }
674
675 if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
677 let is_macro = match res {
678 Res::Def(..) => true,
679 Res::NonMacroAttr(..) => false,
680 _ => unreachable!(),
681 };
682 let msg = if is_macro {
683 "inner macro attributes are unstable"
684 } else {
685 "custom inner attributes are unstable"
686 };
687 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
688 }
689
690 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
691 && let [namespace, attribute, ..] = &*path.segments
692 && namespace.ident.name == sym::diagnostic
693 && ![sym::on_unimplemented, sym::do_not_recommend, sym::on_const]
694 .contains(&attribute.ident.name)
695 {
696 let typo_name = find_best_match_for_name(
697 &[sym::on_unimplemented, sym::do_not_recommend, sym::on_const],
698 attribute.ident.name,
699 Some(5),
700 );
701
702 self.tcx.sess.psess.buffer_lint(
703 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
704 attribute.span(),
705 node_id,
706 BuiltinLintDiag::UnknownDiagnosticAttribute { span: attribute.span(), typo_name },
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 BuiltinLintDiag::UnstableFeature(
1035 msg.into(),
1037 ),
1038 )
1039 };
1040 stability::report_unstable(
1041 self.tcx.sess,
1042 feature,
1043 reason.to_opt_reason(),
1044 issue,
1045 None,
1046 is_soft,
1047 span,
1048 soft_handler,
1049 stability::UnstableKind::Regular,
1050 );
1051 }
1052 }
1053 if let Some(depr) = &ext.deprecation {
1054 let path = pprust::path_to_string(path);
1055 stability::early_report_macro_deprecation(
1056 &mut self.lint_buffer,
1057 depr,
1058 span,
1059 node_id,
1060 path,
1061 );
1062 }
1063 }
1064
1065 fn prohibit_imported_non_macro_attrs(
1066 &self,
1067 binding: Option<NameBinding<'ra>>,
1068 res: Option<Res>,
1069 span: Span,
1070 ) {
1071 if let Some(Res::NonMacroAttr(kind)) = res {
1072 if kind != NonMacroAttrKind::Tool && binding.is_none_or(|b| b.is_import()) {
1073 let binding_span = binding.map(|binding| binding.span);
1074 self.dcx().emit_err(errors::CannotUseThroughAnImport {
1075 span,
1076 article: kind.article(),
1077 descr: kind.descr(),
1078 binding_span,
1079 });
1080 }
1081 }
1082 }
1083
1084 fn report_out_of_scope_macro_calls<'r>(
1085 mut self: CmResolver<'r, 'ra, 'tcx>,
1086 path: &ast::Path,
1087 parent_scope: &ParentScope<'ra>,
1088 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1089 binding: Option<NameBinding<'ra>>,
1090 ) {
1091 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1092 && let Some(binding) = binding
1093 && let NameBindingKind::Res(res) = binding.kind
1095 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1096 && kinds.contains(MacroKinds::BANG)
1097 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1100 {
1101 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1105 let ident = path.segments[0].ident;
1106 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1107 ident,
1108 ScopeSet::Macro(MacroKind::Bang),
1109 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1110 None,
1111 false,
1112 None,
1113 None,
1114 );
1115 if let Ok(fallback_binding) = fallback_binding
1116 && fallback_binding.res().opt_def_id() == Some(def_id)
1117 {
1118 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1120 } else {
1121 let location = match parent_scope.module.kind {
1122 ModuleKind::Def(kind, def_id, name) => {
1123 if let Some(name) = name {
1124 format!("{} `{name}`", kind.descr(def_id))
1125 } else {
1126 "the crate root".to_string()
1127 }
1128 }
1129 ModuleKind::Block => "this scope".to_string(),
1130 };
1131 self.tcx.sess.psess.buffer_lint(
1132 OUT_OF_SCOPE_MACRO_CALLS,
1133 path.span,
1134 node_id,
1135 BuiltinLintDiag::OutOfScopeMacroCalls {
1136 span: path.span,
1137 path: pprust::path_to_string(path),
1138 location,
1139 },
1140 );
1141 }
1142 }
1143 }
1144
1145 pub(crate) fn check_reserved_macro_name(&self, ident: Ident, res: Res) {
1146 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1149 let macro_kinds = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kinds());
1150 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1151 self.dcx()
1152 .emit_err(errors::NameReservedInAttributeNamespace { span: ident.span, ident });
1153 }
1154 }
1155 }
1156
1157 pub(crate) fn compile_macro(
1161 &self,
1162 macro_def: &ast::MacroDef,
1163 ident: Ident,
1164 attrs: &[rustc_hir::Attribute],
1165 span: Span,
1166 node_id: NodeId,
1167 edition: Edition,
1168 ) -> MacroData {
1169 let (mut ext, mut nrules) = compile_declarative_macro(
1170 self.tcx.sess,
1171 self.tcx.features(),
1172 macro_def,
1173 ident,
1174 attrs,
1175 span,
1176 node_id,
1177 edition,
1178 );
1179
1180 if let Some(builtin_name) = ext.builtin_name {
1181 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1183 ext.kind = builtin_ext_kind.clone();
1186 nrules = 0;
1187 } else {
1188 self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1189 }
1190 }
1191
1192 MacroData { ext: Arc::new(ext), nrules, macro_rules: macro_def.macro_rules }
1193 }
1194
1195 fn path_accessible(
1196 &mut self,
1197 expn_id: LocalExpnId,
1198 path: &ast::Path,
1199 namespaces: &[Namespace],
1200 ) -> Result<bool, Indeterminate> {
1201 let span = path.span;
1202 let path = &Segment::from_path(path);
1203 let parent_scope = self.invocation_parent_scopes[&expn_id];
1204
1205 let mut indeterminate = false;
1206 for ns in namespaces {
1207 match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1208 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1209 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1210 return Ok(true);
1211 }
1212 PathResult::NonModule(..) |
1213 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1215 self.dcx()
1216 .emit_err(errors::CfgAccessibleUnsure { span });
1217
1218 return Ok(false);
1221 }
1222 PathResult::Indeterminate => indeterminate = true,
1223 PathResult::Failed { .. } => {}
1226 PathResult::Module(_) => panic!("unexpected path resolution"),
1227 }
1228 }
1229
1230 if indeterminate {
1231 return Err(Indeterminate);
1232 }
1233
1234 Ok(false)
1235 }
1236}