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