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