1use std::mem;
5use std::sync::Arc;
6
7use rustc_ast::{self as ast, Crate, DelegationSuffixes, NodeId};
8use rustc_ast_pretty::pprust;
9use rustc_attr_ir::{Attribute, AttributeKind, CfgEntry, StabilityLevel, StrippedCfgItem};
10use rustc_attr_parsing::{AttributeParser, PREDEFINED_TOOLS};
11use rustc_data_structures::sync::RwLock;
12use rustc_errors::{Applicability, StashKey};
13use rustc_expand::base::{
14 Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension,
15 SyntaxExtensionKind,
16};
17use rustc_expand::compile_declarative_macro;
18use rustc_expand::expand::{
19 AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion,
20};
21use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind};
22use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
23use rustc_lint_defs::builtin::{
24 LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNUSED_MACRO_RULES, UNUSED_MACROS,
25};
26use rustc_lint_defs::{Reflectiveness, ToolOptions};
27use rustc_middle::middle::stability;
28use rustc_middle::ty::{RegisteredTools, TyCtxt};
29use rustc_session::Session;
30use rustc_session::diagnostics::feature_err;
31use rustc_span::def_id::ModId;
32use rustc_span::edition::Edition;
33use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
34use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
35
36use crate::Namespace::*;
37use crate::def_collector::collect_definitions;
38use crate::diagnostics::{
39 self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
40 MacroExpectedFound, RemoveSurroundingDerive,
41};
42use crate::hygiene::Macros20NormalizedSyntaxContext;
43use crate::imports::Import;
44use crate::{
45 BindingKey, CmResolver, Decl, DeclKind, DeriveData, Determinacy, Finalize, IdentKey,
46 InvocationParent, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, Res,
47 ResolutionError, Resolver, ScopeSet, Segment, Used,
48};
49
50#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for MacroRulesDecl<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"MacroRulesDecl decl parent_macro_rules_scope ident orig_ident_span",
&self.decl, &self.parent_macro_rules_scope, &self.ident,
&&self.orig_ident_span)
}
}Debug)]
53pub(crate) struct MacroRulesDecl<'ra> {
54 pub(crate) decl: Decl<'ra>,
55 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
57 pub(crate) ident: IdentKey,
58 pub(crate) orig_ident_span: Span,
59}
60
61#[derive(#[automatically_derived]impl<'ra> ::core::marker::Copy for
MacroRulesScope<'ra> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'ra>
::core::clone::TrivialClone for MacroRulesScope<'ra> {
}
#[automatically_derived]impl<'ra> ::core::clone::Clone for
MacroRulesScope<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'ra MacroRulesDecl<'ra>>;
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
*self
}
}Clone, #[automatically_derived]impl<'ra> ::core::fmt::Debug for MacroRulesScope<'ra>
{
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Empty => ::core::fmt::Formatter::write_str(f, "Empty"),
Self::Def(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Def",
&__self_0),
Self::Invocation(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Invocation", &__self_0),
}
}
}Debug)]
67pub(crate) enum MacroRulesScope<'ra> {
68 Empty,
70 Def(&'ra MacroRulesDecl<'ra>),
72 Invocation(LocalExpnId),
75}
76
77pub(crate) type MacroRulesScopeRef<'ra> = &'ra RwLock<MacroRulesScope<'ra>>;
84
85pub(crate) fn sub_namespace_match(
89 candidate: Option<MacroKinds>,
90 requirement: Option<MacroKind>,
91) -> bool {
92 let (Some(candidate), Some(requirement)) = (candidate, requirement) else {
94 return true;
95 };
96 match requirement {
97 MacroKind::Bang => candidate.contains(MacroKinds::BANG),
98 MacroKind::Attr | MacroKind::Derive => {
99 candidate.intersects(MacroKinds::ATTR | MacroKinds::DERIVE)
100 }
101 }
102}
103
104fn fast_print_path(path: &ast::Path) -> Symbol {
108 if let [segment] = path.segments.as_slice() {
109 segment.ident.name
110 } else {
111 let mut path_str = String::with_capacity(64);
112 for (i, segment) in path.segments.iter().enumerate() {
113 if i != 0 {
114 path_str.push_str("::");
115 }
116 if segment.ident.name != kw::PathRoot {
117 path_str.push_str(segment.ident.as_str())
118 }
119 }
120 Symbol::intern(&path_str)
121 }
122}
123
124pub(crate) fn registered_attr_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
125 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
126
127 let mut registered_tools =
128 if let Some(Attribute::Parsed(AttributeKind::RegisterTool { attr_tools, .. })) =
129 AttributeParser::parse_limited(tcx.sess, pre_configured_attrs, &|attr| {
130 attr.path_matches(&[sym::register_tool])
131 || attr.path_matches(&[sym::register_attribute_tool])
132 })
133 {
134 attr_tools.into_iter().collect::<RegisteredTools>()
135 } else {
136 Default::default()
137 };
138
139 registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(|n| {
141 (Ident::with_dummy_span(n), ToolOptions { reflectiveness: Reflectiveness::NonReflective })
142 }));
143 registered_tools
144}
145
146pub(crate) fn registered_lint_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
147 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
148 registered_lint_tools_ast(tcx.sess, pre_configured_attrs)
149}
150
151pub fn registered_lint_tools_ast(
152 sess: &Session,
153 pre_configured_attrs: &[ast::Attribute],
154) -> RegisteredTools {
155 let mut registered_tools =
156 if let Some(Attribute::Parsed(AttributeKind::RegisterTool { lint_tools, .. })) =
157 AttributeParser::parse_limited(sess, pre_configured_attrs, &|attr| {
158 attr.path_matches(&[sym::register_tool])
159 || attr.path_matches(&[sym::register_lint_tool])
160 })
161 {
162 lint_tools.into_iter().collect::<RegisteredTools>()
163 } else {
164 Default::default()
165 };
166
167 registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(|ident| {
169 (
170 Ident::with_dummy_span(ident),
171 ToolOptions { reflectiveness: Reflectiveness::NonReflective },
172 )
173 }));
174 registered_tools
175}
176
177impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
178 fn next_node_id(&mut self) -> NodeId {
179 self.next_node_id()
180 }
181
182 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
183 self.invocation_parents[&id].parent_def
184 }
185
186 fn mark_scope_with_compile_error(&mut self, id: NodeId) {
187 if let Some(id) = self.owners.get(&id).map(|i| i.def_id)
188 && self.tcx.def_kind(id).is_module_like()
189 {
190 self.mods_with_parse_errors.insert(id.to_def_id());
191 }
192 }
193
194 fn resolve_dollar_crates(&self) {
195 hygiene::update_dollar_crate_names(|ctxt| {
196 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
197 self.resolve_crate_root(ident).name().unwrap_or(kw::Crate)
198 });
199 }
200
201 fn visit_ast_fragment_with_placeholders(
202 &mut self,
203 expansion: LocalExpnId,
204 fragment: &AstFragment,
205 ) {
206 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
209 let output_macro_rules_scope = collect_definitions(self, fragment, parent_scope);
210 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
211
212 let module = parent_scope.module.expect_local();
213 module.unexpanded_invocations.borrow_mut(self).remove(&expansion);
214 if let Some(unexpanded_invocations) =
215 self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
216 {
217 unexpanded_invocations.remove(&expansion);
218 }
219 }
220
221 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
222 if self.builtin_macros.insert(name, ext).is_some() {
223 self.dcx().bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("built-in macro `{0}` was already registered",
name))
})format!("built-in macro `{name}` was already registered"));
224 }
225 }
226
227 fn expansion_for_ast_pass(
230 &mut self,
231 call_site: Span,
232 pass: AstPass,
233 features: &[Symbol],
234 parent_module_id: Option<NodeId>,
235 ) -> LocalExpnId {
236 let parent_module = parent_module_id
237 .map(|module_id| ModId::new_unchecked(self.owner_def_id(module_id).to_def_id()));
238 let expn_id = self.tcx.with_stable_hashing_context(|hcx| {
239 LocalExpnId::fresh(
240 ExpnData::allow_unstable(
241 ExpnKind::AstPass(pass),
242 call_site,
243 self.tcx.sess.edition(),
244 features.into(),
245 None,
246 parent_module,
247 ),
248 hcx,
249 )
250 });
251
252 let parent_scope = parent_module.map_or(self.empty_module, |mod_id| {
253 self.expect_module(mod_id.to_def_id()).expect_local()
254 });
255 self.ast_transform_scopes.insert(expn_id, parent_scope);
256
257 expn_id
258 }
259
260 fn resolve_imports(&mut self) {
261 self.resolve_imports()
262 }
263
264 fn resolve_macro_invocation(
265 &mut self,
266 invoc: &Invocation,
267 eager_expansion_root: LocalExpnId,
268 force: bool,
269 ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
270 let invoc_id = invoc.expansion_data.id;
271 let (parent_scope, invocation_parent) = match (
272 self.invocation_parent_scopes.get(&invoc_id),
273 self.invocation_parents.get(&invoc_id),
274 ) {
275 (Some(parent_scope), Some(invocation_parent)) => (*parent_scope, *invocation_parent),
276 (None, None) => {
277 let parent_scope = *self
281 .invocation_parent_scopes
282 .get(&eager_expansion_root)
283 .expect("non-eager expansion without a parent scope");
284 let invocation_parent = *self
285 .invocation_parents
286 .get(&eager_expansion_root)
287 .expect("non-eager expansion without an invocation parent");
288 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
289 self.invocation_parents.insert(invoc_id, invocation_parent);
290 (parent_scope, invocation_parent)
291 }
292 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("invocation parent tables must both contain or both miss an invocation")));
}unreachable!(
293 "invocation parent tables must both contain or both miss an invocation"
294 ),
295 };
296
297 let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
298 let (path, kind) = match invoc.kind {
299 InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
300 derives = self.arenas.alloc_ast_paths(attr_derives);
301 inner_attr = attr.style == ast::AttrStyle::Inner;
302 (&attr.get_normal_item().path, MacroKind::Attr)
303 }
304 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
305 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
306 InvocationKind::GlobDelegation { ref item, .. } => {
307 let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { ::core::panicking::unreachable_default_msg()unreachable!() };
308 let DelegationSuffixes::Glob(star_span) = deleg.suffixes else { ::core::panicking::unreachable_default_msg()unreachable!() };
309 deleg_impl = Some((invocation_parent.parent_def, star_span));
310 (&deleg.prefix, MacroKind::Bang)
312 }
313 };
314
315 let parent_scope = &ParentScope { derives, ..parent_scope };
317 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
318 let node_id = invoc.expansion_data.lint_node_id;
319 let looks_like_invoc_in_mod_inert_attr = Some(invocation_parent)
321 .filter(|&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
322 in_attr
323 && invoc.fragment_kind == AstFragmentKind::Expr
324 && self.tcx.def_kind(mod_def_id) == DefKind::Mod
325 })
326 .map(|InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
327 let sugg_span = match &invoc.kind {
328 InvocationKind::Attr { item: Annotatable::Item(item), .. }
329 if !item.span.from_expansion() =>
330 {
331 Some(item.span.shrink_to_lo())
332 }
333 _ => None,
334 };
335 let (ext, res) = self.smart_resolve_macro_path(
336 path,
337 kind,
338 supports_macro_expansion,
339 inner_attr,
340 parent_scope,
341 node_id,
342 force,
343 deleg_impl,
344 looks_like_invoc_in_mod_inert_attr,
345 sugg_span,
346 )?;
347
348 let span = invoc.span();
349 let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
350 self.tcx.with_stable_hashing_context(|hcx| {
351 invoc_id.set_expn_data(
352 ext.expn_data(
353 parent_scope.expansion,
354 span,
355 fast_print_path(path),
356 kind,
357 def_id,
358 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
359 ),
360 hcx,
361 )
362 });
363
364 Ok(Arc::clone(ext))
365 }
366
367 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
368 if let Some((_, rules)) = self.unused_macro_rules.get_mut(&id) {
369 rules.remove(rule_i);
370 }
371 }
372
373 fn check_unused_macros(&mut self) {
374 for (_, &(node_id, ident, parent_def_id)) in self.unused_macros.iter() {
375 let mut unannotated_mod = None;
376 let mut annotated_mod = None;
377 if let Some(def_id) = parent_def_id {
378 let span = self.def_span(def_id);
379 let node_id = self.def_id_to_node_id(def_id.expect_local());
380 if ast::CRATE_NODE_ID != node_id {
381 if self.macro_use_mods.contains(&node_id) {
382 annotated_mod = Some(span);
383 } else {
384 unannotated_mod = Some(span.shrink_to_lo());
385 }
386 }
387 }
388
389 self.lint_buffer.buffer_lint(
390 UNUSED_MACROS,
391 node_id,
392 ident.span,
393 diagnostics::UnusedMacroDefinition {
394 name: ident.name,
395 unannotated_mod,
396 annotated_mod,
397 },
398 );
399 self.unused_macro_rules.swap_remove(&node_id);
401 }
402
403 for (&node_id, (def_id, unused_arms)) in self.unused_macro_rules.iter() {
404 if unused_arms.is_empty() {
405 continue;
406 }
407 let ext = self.local_macro_map[&def_id];
408 let SyntaxExtensionKind::MacroRules(ref m) = ext.kind else {
409 continue;
410 };
411 for arm_i in unused_arms.iter() {
412 if let Some((ident, rule_span)) = m.get_unused_rule(arm_i) {
413 self.lint_buffer.buffer_lint(
414 UNUSED_MACRO_RULES,
415 node_id,
416 rule_span,
417 diagnostics::MacroRuleNeverUsed { n: arm_i + 1, name: ident.name },
418 );
419 }
420 }
421 }
422 }
423
424 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
425 self.containers_deriving_copy.contains(&expn_id)
426 }
427
428 fn has_derive_ord(&self, expn_id: LocalExpnId) -> bool {
429 self.containers_deriving_ord.contains(&expn_id)
430 }
431
432 fn resolve_derives(
433 &mut self,
434 expn_id: LocalExpnId,
435 force: bool,
436 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
437 ) -> Result<(), Indeterminate> {
438 let mut derive_data = mem::take(&mut self.derive_data);
447 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
448 resolutions: derive_paths(),
449 helper_attrs: Vec::new(),
450 has_derive_copy: false,
451 has_derive_ord: false,
452 });
453 let parent_scope = self.invocation_parent_scopes[&expn_id];
454 for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
455 if resolution.exts.is_none() {
456 resolution.exts = Some(Arc::clone(
457 match self.cm().resolve_derive_macro_path(
458 &resolution.path,
459 &parent_scope,
460 force,
461 None,
462 ) {
463 Ok((Some(ext), _)) => {
464 if !ext.helper_attrs.is_empty() {
465 let span = resolution.path.segments.last().unwrap().ident.span;
466 let ctxt = Macros20NormalizedSyntaxContext::new(span.ctxt());
467 entry.helper_attrs.extend(
468 ext.helper_attrs
469 .iter()
470 .map(|&name| (i, IdentKey { name, ctxt }, span)),
471 );
472 }
473 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
474 entry.has_derive_ord |= ext.builtin_name == Some(sym::Ord);
475 ext
476 }
477 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
478 Err(Determinacy::Undetermined) => {
479 if !self.derive_data.is_empty() {
::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
480 self.derive_data = derive_data;
481 return Err(Indeterminate);
482 }
483 },
484 ));
485 }
486 }
487 entry.helper_attrs.sort_by_key(|(i, ..)| *i);
489 let helper_attrs = entry
490 .helper_attrs
491 .iter()
492 .map(|&(_, ident, orig_ident_span)| {
493 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
494 let decl = self.arenas.new_pub_def_decl(res, orig_ident_span, expn_id);
495 (ident, orig_ident_span, decl)
496 })
497 .collect();
498 self.helper_attrs.insert(expn_id, helper_attrs);
499 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
508 self.containers_deriving_copy.insert(expn_id);
509 }
510 if entry.has_derive_ord || self.has_derive_ord(parent_scope.expansion) {
514 self.containers_deriving_ord.insert(expn_id);
515 }
516 if !self.derive_data.is_empty() {
::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
517 self.derive_data = derive_data;
518 Ok(())
519 }
520
521 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
522 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
523 }
524
525 fn cfg_accessible(
530 &mut self,
531 expn_id: LocalExpnId,
532 path: &ast::Path,
533 ) -> Result<bool, Indeterminate> {
534 self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
535 }
536
537 fn macro_accessible(
538 &mut self,
539 expn_id: LocalExpnId,
540 path: &ast::Path,
541 ) -> Result<bool, Indeterminate> {
542 self.path_accessible(expn_id, path, &[MacroNS])
543 }
544
545 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
546 self.cstore().get_proc_macro_quoted_span_untracked(self.tcx, krate, id)
547 }
548
549 fn declare_proc_macro(&mut self, id: NodeId) {
550 self.proc_macros.push(self.owner_def_id(id))
551 }
552
553 fn append_stripped_cfg_item(
554 &mut self,
555 parent_node: NodeId,
556 ident: Ident,
557 cfg: CfgEntry,
558 cfg_span: Span,
559 ) {
560 self.stripped_cfg_items.push(StrippedCfgItem {
561 parent_scope: parent_node,
562 ident,
563 cfg: (cfg, cfg_span),
564 });
565 }
566
567 fn registered_attr_tools(&self) -> &RegisteredTools {
568 self.registered_attr_tools
569 }
570
571 fn registered_lint_tools(&self) -> &RegisteredTools {
572 self.registered_lint_tools
573 }
574
575 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
576 self.glob_delegation_invoc_ids.insert(invoc_id);
577 }
578
579 fn glob_delegation_suffixes(
580 &self,
581 trait_def_id: DefId,
582 impl_def_id: LocalDefId,
583 star_span: Span,
584 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
585 let target_trait = self.expect_module(trait_def_id);
586 if target_trait.has_unexpanded_invocations(self) {
587 return Err(Indeterminate);
588 }
589 if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
596 && !unexpanded_invocations.is_empty()
597 {
598 return Err(Indeterminate);
599 }
600
601 let mut idents = Vec::new();
602 target_trait.for_each_child(self, |this, ident, orig_ident_span, ns, _binding| {
603 if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
604 && overriding_keys.contains(&BindingKey::new(ident, ns))
605 {
606 } else {
608 idents.push((ident.orig(star_span.with_ctxt(orig_ident_span.ctxt())), None));
610 }
611 });
612 Ok(idents)
613 }
614
615 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
616 self.impl_trait_names.insert(id, name);
617 }
618}
619
620impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
621 fn smart_resolve_macro_path(
625 &mut self,
626 path: &ast::Path,
627 kind: MacroKind,
628 supports_macro_expansion: SupportsMacroExpansion,
629 inner_attr: bool,
630 parent_scope: &ParentScope<'ra>,
631 node_id: NodeId,
632 force: bool,
633 deleg_impl: Option<(LocalDefId, Span)>,
634 invoc_in_mod_inert_attr: Option<LocalDefId>,
635 suggestion_span: Option<Span>,
636 ) -> Result<(&'ra Arc<SyntaxExtension>, Res), Indeterminate> {
637 let (ext, res) = match self.cm_mut().resolve_macro_or_delegation_path(
638 path,
639 kind,
640 parent_scope,
641 force,
642 deleg_impl,
643 invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
644 None,
645 suggestion_span,
646 ) {
647 Ok((Some(ext), res)) => (ext, res),
648 Ok((None, res)) => (self.dummy_ext(kind), res),
649 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
650 Err(Determinacy::Undetermined) => return Err(Indeterminate),
651 };
652
653 if deleg_impl.is_some() {
655 if !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::Err | Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
656 self.dcx().emit_err(MacroExpectedFound {
657 span: path.span,
658 expected: "trait",
659 article: "a",
660 found: res.descr(),
661 macro_path: &pprust::path_to_string(path),
662 remove_surrounding_derive: None,
663 add_as_non_derive: None,
664 });
665 return Ok((self.dummy_ext(kind), Res::Err));
666 }
667
668 return Ok((ext, res));
669 }
670
671 for (idx, segment) in path.segments.iter().enumerate() {
673 if let Some(args) = &segment.args {
674 self.dcx().emit_err(diagnostics::GenericArgumentsInMacroPath { span: args.span() });
675 }
676 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
677 if idx == 0 {
678 self.dcx().emit_err(diagnostics::AttributesStartingWithRustcAreReserved {
679 span: segment.ident.span,
680 });
681 } else {
682 self.dcx().emit_err(diagnostics::AttributesContainingRustcAreReserved {
683 span: segment.ident.span,
684 });
685 }
686 }
687 }
688
689 match res {
690 Res::Def(DefKind::Macro(_), def_id) => {
691 if let Some(def_id) = def_id.as_local() {
692 self.unused_macros.swap_remove(&def_id);
693 if self.proc_macro_stubs.contains(&def_id) {
694 self.dcx().emit_err(diagnostics::ProcMacroSameCrate {
695 span: path.span,
696 is_test: self.tcx.sess.is_test_crate(),
697 });
698 }
699 }
700 if kind == MacroKind::Attr
701 && let [tool, _second, ..] = path.segments.as_slice()
702 && self.registered_attr_tool_decls.contains_key(&IdentKey::new(tool.ident))
703 {
704 self.dcx().emit_err(diagnostics::ToolAttrAmbiguity {
705 path_span: path.span,
706 attr_path: pprust::path_to_string(path),
707 tool: tool.ident.name,
708 });
709 }
710 }
711 Res::NonMacroAttr(..) | Res::Err => {}
712 _ => {
::core::panicking::panic_fmt(format_args!("expected `DefKind::Macro` or `Res::NonMacroAttr`"));
}panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
713 };
714
715 self.check_stability_and_deprecation(&ext, path, node_id);
716
717 let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
718 Some((kind.article(), kind.descr_expected()))
719 } else if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(..) => true,
_ => false,
}matches!(res, Res::Def(..)) {
720 match supports_macro_expansion {
721 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
722 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
723 if inner_attr && !supports_inner_attrs {
724 Some(("a", "non-macro inner attribute"))
725 } else {
726 None
727 }
728 }
729 }
730 } else {
731 None
732 };
733 if let Some((article, expected)) = unexpected_res {
734 let path_str = pprust::path_to_string(path);
735
736 let mut err = MacroExpectedFound {
737 span: path.span,
738 expected,
739 article,
740 found: res.descr(),
741 macro_path: &path_str,
742 remove_surrounding_derive: None,
743 add_as_non_derive: None,
744 };
745
746 if !path.span.from_expansion()
748 && kind == MacroKind::Derive
749 && !ext.macro_kinds().contains(MacroKinds::DERIVE)
750 && ext.macro_kinds().contains(MacroKinds::ATTR)
751 {
752 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
753 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
754 }
755
756 self.dcx().emit_err(err);
757
758 return Ok((self.dummy_ext(kind), Res::Err));
759 }
760
761 if res != Res::Err && inner_attr && !self.features.custom_inner_attributes() {
763 let is_macro = match res {
764 Res::Def(..) => true,
765 Res::NonMacroAttr(..) => false,
766 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
767 };
768 let msg = if is_macro {
769 "inner macro attributes are unstable"
770 } else {
771 "custom inner attributes are unstable"
772 };
773 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
774 }
775
776 Ok((ext, res))
777 }
778
779 pub(crate) fn resolve_derive_macro_path<'r>(
780 self: CmResolver<'r, 'ra, 'tcx>,
781 path: &ast::Path,
782 parent_scope: &ParentScope<'ra>,
783 force: bool,
784 ignore_import: Option<Import<'ra>>,
785 ) -> Result<(Option<&'r Arc<SyntaxExtension>>, Res), Determinacy> {
786 self.resolve_macro_or_delegation_path(
787 path,
788 MacroKind::Derive,
789 parent_scope,
790 force,
791 None,
792 None,
793 ignore_import,
794 None,
795 )
796 }
797
798 fn resolve_macro_or_delegation_path<'r>(
799 mut self: CmResolver<'r, 'ra, 'tcx>,
800 ast_path: &ast::Path,
801 kind: MacroKind,
802 parent_scope: &ParentScope<'ra>,
803 force: bool,
804 deleg_impl: Option<(LocalDefId, Span)>,
805 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
806 ignore_import: Option<Import<'ra>>,
807 suggestion_span: Option<Span>,
808 ) -> Result<(Option<&'ra Arc<SyntaxExtension>>, Res), Determinacy> {
809 let path_span = ast_path.span;
810 let mut path = Segment::from_path(ast_path);
811
812 if deleg_impl.is_none()
814 && kind == MacroKind::Bang
815 && let [segment] = path.as_slice()
816 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
817 {
818 let root = Ident::new(kw::DollarCrate, segment.ident.span);
819 path.insert(0, Segment::from_ident(root));
820 }
821
822 let res = if deleg_impl.is_some() || path.len() > 1 {
823 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
824 let res = match self.reborrow().maybe_resolve_path(
825 &path,
826 Some(ns),
827 parent_scope,
828 ignore_import,
829 ) {
830 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
831 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
832 PathResult::NonModule(..)
833 | PathResult::Indeterminate
834 | PathResult::Failed { .. } => Err(Determinacy::Determined),
835 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
836 Ok(module.res().unwrap())
837 }
838 PathResult::Module(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
839 };
840
841 self.multi_segment_macro_resolutions.borrow_mut_checked(&self).push((
842 path,
843 path_span,
844 kind,
845 *parent_scope,
846 res.ok(),
847 ns,
848 ));
849
850 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
851 res
852 } else {
853 let binding = self.reborrow().resolve_ident_in_scope_set(
854 path[0].ident,
855 ScopeSet::Macro(kind),
856 parent_scope,
857 None,
858 None,
859 None,
860 );
861 let binding = binding.map_err(|determinacy| {
862 Determinacy::determined(determinacy == Determinacy::Determined || force)
863 });
864 if let Err(Determinacy::Undetermined) = binding {
865 return Err(Determinacy::Undetermined);
866 }
867
868 self.single_segment_macro_resolutions.borrow_mut_checked(&self).push((
869 path[0].ident,
870 kind,
871 *parent_scope,
872 binding.ok(),
873 suggestion_span,
874 ));
875
876 let res = binding.map(|binding| binding.res());
877 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
878 self.reborrow().report_out_of_scope_macro_calls(
879 ast_path,
880 parent_scope,
881 invoc_in_mod_inert_attr,
882 binding.ok(),
883 );
884 res
885 };
886
887 let res = res?;
888 let ext = match deleg_impl {
889 Some((impl_def_id, star_span)) => match res {
890 Res::Def(DefKind::Trait, def_id) => {
891 let edition = self.tcx.sess.edition();
892 Some(self.arenas.alloc_macro(SyntaxExtension::glob_delegation(
893 def_id,
894 impl_def_id,
895 star_span,
896 edition,
897 )))
898 }
899 _ => None,
900 },
901 None => self.get_macro(res),
902 };
903 Ok((ext, res))
904 }
905
906 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
907 let check_consistency = |this: &Self,
908 path: &[Segment],
909 span,
910 kind: MacroKind,
911 initial_res: Option<Res>,
912 res: Res| {
913 if let Some(initial_res) = initial_res {
914 if res != initial_res {
915 if this.ambiguity_errors.is_empty() {
916 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
920 }
921 }
922 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
923 let err = this.dcx().create_err(CannotDetermineMacroResolution {
932 span,
933 kind: kind.descr(),
934 path: Segment::names_to_string(path),
935 });
936 err.stash(span, StashKey::UndeterminedMacroResolution);
937 }
938 };
939
940 let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
941 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
942 for seg in &mut path {
944 seg.id = None;
945 }
946 match self.cm_mut().resolve_path(
947 &path,
948 Some(ns),
949 &parent_scope,
950 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
951 None,
952 None,
953 ) {
954 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
955 check_consistency(self, &path, path_span, kind, initial_res, res)
956 }
957 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
959 self,
960 &path,
961 path_span,
962 kind,
963 initial_res,
964 module.res().unwrap(),
965 ),
966 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
967 let mut suggestion = None;
968 let (span, message, label, module, segment, help) = match path_res {
969 PathResult::Failed {
970 span, label, module, segment, message, help, ..
971 } => {
972 if let PathResult::NonModule(partial_res) = self
974 .cm()
975 .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
976 && partial_res.unresolved_segments() == 0
977 {
978 let sm = self.tcx.sess.source_map();
979 let exclamation_span = sm.next_point(span);
980 suggestion = Some((
981 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(exclamation_span, "".to_string())]))vec![(exclamation_span, "".to_string())],
982 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a macro, but a {1}, try to remove `!`",
Segment::names_to_string(&path),
partial_res.base_res().descr()))
})format!(
983 "{} is not a macro, but a {}, try to remove `!`",
984 Segment::names_to_string(&path),
985 partial_res.base_res().descr()
986 ),
987 Applicability::MaybeIncorrect,
988 ));
989 }
990 (span, message, label, module, segment.name, help)
991 }
992 PathResult::NonModule(partial_res) => {
993 let found_an = partial_res.base_res().article();
994 let found_descr = partial_res.base_res().descr();
995 let scope = match &path[..partial_res.unresolved_segments()] {
996 [.., prev] => {
997 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{0}`", prev.ident,
found_descr))
})format!("{found_descr} `{}`", prev.ident)
998 }
999 _ => found_descr.to_string(),
1000 };
1001 let expected_an = kind.article();
1002 let expected_descr = kind.descr();
1003 let expected_name = path[partial_res.unresolved_segments()].ident;
1004
1005 (
1006 path_span,
1007 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}",
expected_descr, expected_name, scope))
})format!(
1008 "cannot find {expected_descr} `{expected_name}` in {scope}"
1009 ),
1010 match partial_res.base_res() {
1011 Res::Def(
1012 DefKind::Mod | DefKind::Macro(..) | DefKind::ExternCrate,
1013 _,
1014 ) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("partially resolved path in {0} {1}",
expected_an, expected_descr))
})format!(
1015 "partially resolved path in {expected_an} {expected_descr}",
1016 ),
1017 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} can\'t exist within {2} {3}",
expected_an, expected_descr, found_an, found_descr))
})format!(
1018 "{expected_an} {expected_descr} can't exist within \
1019 {found_an} {found_descr}"
1020 ),
1021 },
1022 None,
1023 path.last().map(|segment| segment.ident.name).unwrap(),
1024 None,
1025 )
1026 }
1027 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1028 };
1029 self.report_error(
1030 span,
1031 ResolutionError::FailedToResolve {
1032 segment,
1033 label,
1034 suggestion,
1035 help,
1036 module,
1037 message,
1038 },
1039 );
1040 }
1041 PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::unreachable_default_msg()unreachable!(),
1042 }
1043 }
1044
1045 let macro_resolutions = self.single_segment_macro_resolutions.take(self);
1046 for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
1047 match self.cm_mut().resolve_ident_in_scope_set(
1048 ident,
1049 ScopeSet::Macro(kind),
1050 &parent_scope,
1051 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1052 None,
1053 None,
1054 ) {
1055 Ok(binding) => {
1056 let initial_res = initial_binding.map(|initial_binding| {
1057 self.record_use(ident, initial_binding, Used::Other);
1058 initial_binding.res()
1059 });
1060 let res = binding.res();
1061 let seg = Segment::from_ident(ident);
1062 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
1063 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
1064 let node_id = self
1065 .invocation_parents
1066 .get(&parent_scope.expansion)
1067 .map_or(ast::CRATE_NODE_ID, |parent| {
1068 self.def_id_to_node_id(parent.parent_def)
1069 });
1070 self.lint_buffer.buffer_lint(
1071 LEGACY_DERIVE_HELPERS,
1072 node_id,
1073 ident.span,
1074 diagnostics::LegacyDeriveHelpers { span: binding.span },
1075 );
1076 }
1077 }
1078 Err(..) => {
1079 let expected = kind.descr_expected();
1080
1081 let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
1082 span: ident.span,
1083 expected,
1084 ident,
1085 });
1086 self.unresolved_macro_suggestions(
1087 &mut err,
1088 kind,
1089 &parent_scope,
1090 ident,
1091 krate,
1092 sugg_span,
1093 );
1094 err.emit();
1095 }
1096 }
1097 }
1098
1099 let builtin_attrs = mem::take(&mut self.builtin_attrs);
1100 for (ident, parent_scope) in builtin_attrs {
1101 let _ = self.cm_mut().resolve_ident_in_scope_set(
1102 ident,
1103 ScopeSet::Macro(MacroKind::Attr),
1104 &parent_scope,
1105 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1106 None,
1107 None,
1108 );
1109 }
1110 }
1111
1112 fn check_stability_and_deprecation(
1113 &mut self,
1114 ext: &SyntaxExtension,
1115 path: &ast::Path,
1116 node_id: NodeId,
1117 ) {
1118 let span = path.span;
1119 if let Some(stability) = &ext.stability
1120 && let StabilityLevel::Unstable { reason, issue, implied_by, .. } = stability.level
1121 {
1122 let feature = stability.feature;
1123
1124 let is_allowed =
1125 |feature| self.features.enabled(feature) || span.allows_unstable(feature);
1126 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1127 if !is_allowed(feature) && !allowed_by_implication {
1128 stability::report_unstable(
1129 self.tcx.sess,
1130 feature,
1131 reason.to_opt_reason(),
1132 issue,
1133 span,
1134 stability::UnstableKind::Regular,
1135 );
1136 }
1137 }
1138 if let Some(depr) = &ext.deprecation {
1139 let path = pprust::path_to_string(path);
1140 stability::early_report_macro_deprecation(
1141 &mut self.lint_buffer,
1142 depr,
1143 span,
1144 node_id,
1145 path,
1146 );
1147 }
1148 }
1149
1150 fn prohibit_imported_non_macro_attrs(
1151 &self,
1152 decl: Option<Decl<'ra>>,
1153 res: Option<Res>,
1154 span: Span,
1155 ) {
1156 if let Some(Res::NonMacroAttr(kind)) = res {
1157 if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1158 self.dcx().emit_err(diagnostics::CannotUseThroughAnImport {
1159 span,
1160 article: kind.article(),
1161 descr: kind.descr(),
1162 binding_span: decl.map(|d| d.span),
1163 });
1164 }
1165 }
1166 }
1167
1168 fn report_out_of_scope_macro_calls<'r>(
1169 mut self: CmResolver<'r, 'ra, 'tcx>,
1170 path: &ast::Path,
1171 parent_scope: &ParentScope<'ra>,
1172 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1173 decl: Option<Decl<'ra>>,
1174 ) {
1175 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1176 && let Some(decl) = decl
1177 && let DeclKind::Def(res, _) = decl.kind
1179 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1180 && kinds.contains(MacroKinds::BANG)
1181 && self.tcx.is_descendant_of(def_id, mod_def_id)
1184 {
1185 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1189 let ident = path.segments[0].ident;
1190 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1191 ident,
1192 ScopeSet::Macro(MacroKind::Bang),
1193 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1194 None,
1195 None,
1196 None,
1197 );
1198 if let Ok(fallback_binding) = fallback_binding
1199 && fallback_binding.res().opt_def_id() == Some(def_id)
1200 {
1201 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1203 } else {
1204 let location = match parent_scope.module.kind {
1205 ModuleKind::Def(kind, def_id, _, name) => {
1206 if let Some(name) = name {
1207 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind.descr(def_id),
name))
})format!("{} `{name}`", kind.descr(def_id))
1208 } else {
1209 "the crate root".to_string()
1210 }
1211 }
1212 ModuleKind::Block => "this scope".to_string(),
1213 };
1214 self.tcx.sess.psess.buffer_lint(
1215 OUT_OF_SCOPE_MACRO_CALLS,
1216 path.span,
1217 node_id,
1218 diagnostics::OutOfScopeMacroCalls {
1219 span: path.span,
1220 path: pprust::path_to_string(path),
1221 location,
1222 },
1223 );
1224 }
1225 }
1226 }
1227
1228 pub(crate) fn check_reserved_macro_name(&self, name: Symbol, span: Span, res: Res) {
1229 if name == sym::cfg || name == sym::cfg_attr {
1232 let macro_kinds = res.macro_kinds();
1233 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1234 self.dcx()
1235 .emit_err(diagnostics::NameReservedInAttributeNamespace { span, ident: name });
1236 }
1237 }
1238 }
1239
1240 pub(crate) fn compile_macro(
1244 &self,
1245 macro_def: &ast::MacroDef,
1246 ident: Ident,
1247 attrs: &[rustc_attr_ir::Attribute],
1248 span: Span,
1249 node_id: NodeId,
1250 edition: Edition,
1251 ) -> SyntaxExtension {
1252 let mut ext = compile_declarative_macro(
1253 self.tcx.sess,
1254 self.features,
1255 macro_def,
1256 ident,
1257 attrs,
1258 span,
1259 node_id,
1260 edition,
1261 );
1262
1263 if let Some(builtin_name) = ext.builtin_name {
1264 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1266 ext.kind = builtin_ext_kind.clone();
1269 } else {
1270 self.dcx().emit_err(diagnostics::CannotFindBuiltinMacroWithName { span, ident });
1271 }
1272 }
1273
1274 ext
1275 }
1276
1277 fn path_accessible(
1278 &self,
1279 expn_id: LocalExpnId,
1280 path: &ast::Path,
1281 namespaces: &[Namespace],
1282 ) -> Result<bool, Indeterminate> {
1283 let span = path.span;
1284 let path = &Segment::from_path(path);
1285 let parent_scope = self.invocation_parent_scopes[&expn_id];
1286
1287 let mut indeterminate = false;
1288 for ns in namespaces {
1289 match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1290 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1291 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1292 return Ok(true);
1293 }
1294 PathResult::NonModule(..) |
1295 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1297 self.dcx().emit_err(diagnostics::CfgAccessibleUnsure { span });
1298
1299 return Ok(false);
1302 }
1303 PathResult::Indeterminate => indeterminate = true,
1304 PathResult::Failed { .. } => {}
1307 PathResult::Module(_) => { ::core::panicking::panic_fmt(format_args!("unexpected path resolution")); }panic!("unexpected path resolution"),
1308 }
1309 }
1310
1311 if indeterminate {
1312 return Err(Indeterminate);
1313 }
1314
1315 Ok(false)
1316 }
1317}