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, DiagCtxtHandle, 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, UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
29 UNUSED_MACRO_RULES, UNUSED_MACROS,
30};
31use rustc_span::def_id::ModId;
32use rustc_span::edit_distance::find_best_match_for_name;
33use rustc_span::edition::Edition;
34use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
35use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
36
37use crate::Namespace::*;
38use crate::def_collector::collect_definitions;
39use crate::diagnostics::{
40 self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
41 MacroExpectedFound, RemoveSurroundingDerive,
42};
43use crate::hygiene::Macros20NormalizedSyntaxContext;
44use crate::imports::Import;
45use crate::{
46 BindingKey, CacheCell, CmResolver, Decl, DeclKind, DeriveData, Determinacy, Finalize, IdentKey,
47 InvocationParent, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, Res,
48 ResolutionError, Resolver, ScopeSet, Segment, Used,
49};
50
51#[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)]
54pub(crate) struct MacroRulesDecl<'ra> {
55 pub(crate) decl: Decl<'ra>,
56 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'ra>,
58 pub(crate) ident: IdentKey,
59 pub(crate) orig_ident_span: Span,
60}
61
62#[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)]
68pub(crate) enum MacroRulesScope<'ra> {
69 Empty,
71 Def(&'ra MacroRulesDecl<'ra>),
73 Invocation(LocalExpnId),
76}
77
78pub(crate) type MacroRulesScopeRef<'ra> = &'ra CacheCell<MacroRulesScope<'ra>>;
85
86pub(crate) fn sub_namespace_match(
90 candidate: Option<MacroKinds>,
91 requirement: Option<MacroKind>,
92) -> bool {
93 let (Some(candidate), Some(requirement)) = (candidate, requirement) else {
95 return true;
96 };
97 match requirement {
98 MacroKind::Bang => candidate.contains(MacroKinds::BANG),
99 MacroKind::Attr | MacroKind::Derive => {
100 candidate.intersects(MacroKinds::ATTR | MacroKinds::DERIVE)
101 }
102 }
103}
104
105fn fast_print_path(path: &ast::Path) -> Symbol {
109 if let [segment] = path.segments.as_slice() {
110 segment.ident.name
111 } else {
112 let mut path_str = String::with_capacity(64);
113 for (i, segment) in path.segments.iter().enumerate() {
114 if i != 0 {
115 path_str.push_str("::");
116 }
117 if segment.ident.name != kw::PathRoot {
118 path_str.push_str(segment.ident.as_str())
119 }
120 }
121 Symbol::intern(&path_str)
122 }
123}
124
125pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
126 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
127 registered_tools_ast(tcx.dcx(), pre_configured_attrs, tcx.sess)
128}
129
130pub fn registered_tools_ast(
131 dcx: DiagCtxtHandle<'_>,
132 pre_configured_attrs: &[ast::Attribute],
133 sess: &Session,
134) -> RegisteredTools {
135 let mut registered_tools = RegisteredTools::default();
136
137 if let Some(Attribute::Parsed(AttributeKind::RegisterTool(tools))) =
138 AttributeParser::parse_limited(sess, pre_configured_attrs, &[sym::register_tool])
139 {
140 for tool in tools {
141 if let Some(old_tool) = registered_tools.replace(tool) {
142 dcx.emit_err(diagnostics::ToolWasAlreadyRegistered {
143 span: tool.span,
144 tool,
145 old_ident_span: old_tool.span,
146 });
147 }
148 }
149 }
150
151 let predefined_tools =
154 [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
155 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
156 registered_tools
157}
158
159impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
160 fn next_node_id(&mut self) -> NodeId {
161 self.next_node_id()
162 }
163
164 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
165 self.invocation_parents[&id].parent_def
166 }
167
168 fn mark_scope_with_compile_error(&mut self, id: NodeId) {
169 if let Some(id) = self.owners.get(&id).map(|i| i.def_id)
170 && self.tcx.def_kind(id).is_module_like()
171 {
172 self.mods_with_parse_errors.insert(id.to_def_id());
173 }
174 }
175
176 fn resolve_dollar_crates(&self) {
177 hygiene::update_dollar_crate_names(|ctxt| {
178 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
179 self.resolve_crate_root(ident).name().unwrap_or(kw::Crate)
180 });
181 }
182
183 fn visit_ast_fragment_with_placeholders(
184 &mut self,
185 expansion: LocalExpnId,
186 fragment: &AstFragment,
187 ) {
188 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
191 let output_macro_rules_scope = collect_definitions(self, fragment, parent_scope);
192 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
193
194 let module = parent_scope.module.expect_local();
195 module.unexpanded_invocations.borrow_mut(self).remove(&expansion);
196 if let Some(unexpanded_invocations) =
197 self.impl_unexpanded_invocations.get_mut(&self.invocation_parent(expansion))
198 {
199 unexpanded_invocations.remove(&expansion);
200 }
201 }
202
203 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
204 if self.builtin_macros.insert(name, ext).is_some() {
205 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"));
206 }
207 }
208
209 fn expansion_for_ast_pass(
212 &mut self,
213 call_site: Span,
214 pass: AstPass,
215 features: &[Symbol],
216 parent_module_id: Option<NodeId>,
217 ) -> LocalExpnId {
218 let parent_module = parent_module_id
219 .map(|module_id| ModId::new_unchecked(self.owner_def_id(module_id).to_def_id()));
220 let expn_id = self.tcx.with_stable_hashing_context(|hcx| {
221 LocalExpnId::fresh(
222 ExpnData::allow_unstable(
223 ExpnKind::AstPass(pass),
224 call_site,
225 self.tcx.sess.edition(),
226 features.into(),
227 None,
228 parent_module,
229 ),
230 hcx,
231 )
232 });
233
234 let parent_scope = parent_module.map_or(self.empty_module, |mod_id| {
235 self.expect_module(mod_id.to_def_id()).expect_local()
236 });
237 self.ast_transform_scopes.insert(expn_id, parent_scope);
238
239 expn_id
240 }
241
242 fn resolve_imports(&mut self) {
243 self.resolve_imports()
244 }
245
246 fn resolve_macro_invocation(
247 &mut self,
248 invoc: &Invocation,
249 eager_expansion_root: LocalExpnId,
250 force: bool,
251 ) -> Result<Arc<SyntaxExtension>, Indeterminate> {
252 let invoc_id = invoc.expansion_data.id;
253 let (parent_scope, invocation_parent) = match (
254 self.invocation_parent_scopes.get(&invoc_id),
255 self.invocation_parents.get(&invoc_id),
256 ) {
257 (Some(parent_scope), Some(invocation_parent)) => (*parent_scope, *invocation_parent),
258 (None, None) => {
259 let parent_scope = *self
263 .invocation_parent_scopes
264 .get(&eager_expansion_root)
265 .expect("non-eager expansion without a parent scope");
266 let invocation_parent = *self
267 .invocation_parents
268 .get(&eager_expansion_root)
269 .expect("non-eager expansion without an invocation parent");
270 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
271 self.invocation_parents.insert(invoc_id, invocation_parent);
272 (parent_scope, invocation_parent)
273 }
274 _ => {
::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!(
275 "invocation parent tables must both contain or both miss an invocation"
276 ),
277 };
278
279 let (mut derives, mut inner_attr, mut deleg_impl) = (&[][..], false, None);
280 let (path, kind) = match invoc.kind {
281 InvocationKind::Attr { ref attr, derives: ref attr_derives, .. } => {
282 derives = self.arenas.alloc_ast_paths(attr_derives);
283 inner_attr = attr.style == ast::AttrStyle::Inner;
284 (&attr.get_normal_item().path, MacroKind::Attr)
285 }
286 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
287 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
288 InvocationKind::GlobDelegation { ref item, .. } => {
289 let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
290 let DelegationSuffixes::Glob(star_span) = deleg.suffixes else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
291 deleg_impl = Some((invocation_parent.parent_def, star_span));
292 (&deleg.prefix, MacroKind::Bang)
294 }
295 };
296
297 let parent_scope = &ParentScope { derives, ..parent_scope };
299 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
300 let node_id = invoc.expansion_data.lint_node_id;
301 let looks_like_invoc_in_mod_inert_attr = Some(invocation_parent)
303 .filter(|&InvocationParent { parent_def: mod_def_id, in_attr, .. }| {
304 in_attr
305 && invoc.fragment_kind == AstFragmentKind::Expr
306 && self.tcx.def_kind(mod_def_id) == DefKind::Mod
307 })
308 .map(|InvocationParent { parent_def: mod_def_id, .. }| mod_def_id);
309 let sugg_span = match &invoc.kind {
310 InvocationKind::Attr { item: Annotatable::Item(item), .. }
311 if !item.span.from_expansion() =>
312 {
313 Some(item.span.shrink_to_lo())
314 }
315 _ => None,
316 };
317 let (ext, res) = self.smart_resolve_macro_path(
318 path,
319 kind,
320 supports_macro_expansion,
321 inner_attr,
322 parent_scope,
323 node_id,
324 force,
325 deleg_impl,
326 looks_like_invoc_in_mod_inert_attr,
327 sugg_span,
328 )?;
329
330 let span = invoc.span();
331 let def_id = if deleg_impl.is_some() { None } else { res.opt_def_id() };
332 self.tcx.with_stable_hashing_context(|hcx| {
333 invoc_id.set_expn_data(
334 ext.expn_data(
335 parent_scope.expansion,
336 span,
337 fast_print_path(path),
338 kind,
339 def_id,
340 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
341 ),
342 hcx,
343 )
344 });
345
346 Ok(Arc::clone(ext))
347 }
348
349 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
350 if let Some((_, rules)) = self.unused_macro_rules.get_mut(&id) {
351 rules.remove(rule_i);
352 }
353 }
354
355 fn check_unused_macros(&mut self) {
356 for (_, &(node_id, ident)) in self.unused_macros.iter() {
357 self.lint_buffer.buffer_lint(
358 UNUSED_MACROS,
359 node_id,
360 ident.span,
361 diagnostics::UnusedMacroDefinition { name: ident.name },
362 );
363 self.unused_macro_rules.swap_remove(&node_id);
365 }
366
367 for (&node_id, (def_id, unused_arms)) in self.unused_macro_rules.iter() {
368 if unused_arms.is_empty() {
369 continue;
370 }
371 let ext = self.local_macro_map[&def_id];
372 let SyntaxExtensionKind::MacroRules(ref m) = ext.kind else {
373 continue;
374 };
375 for arm_i in unused_arms.iter() {
376 if let Some((ident, rule_span)) = m.get_unused_rule(arm_i) {
377 self.lint_buffer.buffer_lint(
378 UNUSED_MACRO_RULES,
379 node_id,
380 rule_span,
381 diagnostics::MacroRuleNeverUsed { n: arm_i + 1, name: ident.name },
382 );
383 }
384 }
385 }
386 }
387
388 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
389 self.containers_deriving_copy.contains(&expn_id)
390 }
391
392 fn has_derive_ord(&self, expn_id: LocalExpnId) -> bool {
393 self.containers_deriving_ord.contains(&expn_id)
394 }
395
396 fn resolve_derives(
397 &mut self,
398 expn_id: LocalExpnId,
399 force: bool,
400 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
401 ) -> Result<(), Indeterminate> {
402 let mut derive_data = mem::take(&mut self.derive_data);
411 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
412 resolutions: derive_paths(),
413 helper_attrs: Vec::new(),
414 has_derive_copy: false,
415 has_derive_ord: false,
416 });
417 let parent_scope = self.invocation_parent_scopes[&expn_id];
418 for (i, resolution) in entry.resolutions.iter_mut().enumerate() {
419 if resolution.exts.is_none() {
420 resolution.exts = Some(Arc::clone(
421 match self.cm().resolve_derive_macro_path(
422 &resolution.path,
423 &parent_scope,
424 force,
425 None,
426 ) {
427 Ok((Some(ext), _)) => {
428 if !ext.helper_attrs.is_empty() {
429 let span = resolution.path.segments.last().unwrap().ident.span;
430 let ctxt = Macros20NormalizedSyntaxContext::new(span.ctxt());
431 entry.helper_attrs.extend(
432 ext.helper_attrs
433 .iter()
434 .map(|&name| (i, IdentKey { name, ctxt }, span)),
435 );
436 }
437 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
438 entry.has_derive_ord |= ext.builtin_name == Some(sym::Ord);
439 ext
440 }
441 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
442 Err(Determinacy::Undetermined) => {
443 if !self.derive_data.is_empty() {
::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
444 self.derive_data = derive_data;
445 return Err(Indeterminate);
446 }
447 },
448 ));
449 }
450 }
451 entry.helper_attrs.sort_by_key(|(i, ..)| *i);
453 let helper_attrs = entry
454 .helper_attrs
455 .iter()
456 .map(|&(_, ident, orig_ident_span)| {
457 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
458 let decl = self.arenas.new_pub_def_decl(res, orig_ident_span, expn_id);
459 (ident, orig_ident_span, decl)
460 })
461 .collect();
462 self.helper_attrs.insert(expn_id, helper_attrs);
463 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
472 self.containers_deriving_copy.insert(expn_id);
473 }
474 if entry.has_derive_ord || self.has_derive_ord(parent_scope.expansion) {
478 self.containers_deriving_ord.insert(expn_id);
479 }
480 if !self.derive_data.is_empty() {
::core::panicking::panic("assertion failed: self.derive_data.is_empty()")
};assert!(self.derive_data.is_empty());
481 self.derive_data = derive_data;
482 Ok(())
483 }
484
485 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>> {
486 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
487 }
488
489 fn cfg_accessible(
494 &mut self,
495 expn_id: LocalExpnId,
496 path: &ast::Path,
497 ) -> Result<bool, Indeterminate> {
498 self.path_accessible(expn_id, path, &[TypeNS, ValueNS, MacroNS])
499 }
500
501 fn macro_accessible(
502 &mut self,
503 expn_id: LocalExpnId,
504 path: &ast::Path,
505 ) -> Result<bool, Indeterminate> {
506 self.path_accessible(expn_id, path, &[MacroNS])
507 }
508
509 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
510 self.cstore().get_proc_macro_quoted_span_untracked(self.tcx, krate, id)
511 }
512
513 fn declare_proc_macro(&mut self, id: NodeId) {
514 self.proc_macros.push(self.owner_def_id(id))
515 }
516
517 fn append_stripped_cfg_item(
518 &mut self,
519 parent_node: NodeId,
520 ident: Ident,
521 cfg: CfgEntry,
522 cfg_span: Span,
523 ) {
524 self.stripped_cfg_items.push(StrippedCfgItem {
525 parent_scope: parent_node,
526 ident,
527 cfg: (cfg, cfg_span),
528 });
529 }
530
531 fn registered_tools(&self) -> &RegisteredTools {
532 self.registered_tools
533 }
534
535 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId) {
536 self.glob_delegation_invoc_ids.insert(invoc_id);
537 }
538
539 fn glob_delegation_suffixes(
540 &self,
541 trait_def_id: DefId,
542 impl_def_id: LocalDefId,
543 star_span: Span,
544 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate> {
545 let target_trait = self.expect_module(trait_def_id);
546 if target_trait.has_unexpanded_invocations() {
547 return Err(Indeterminate);
548 }
549 if let Some(unexpanded_invocations) = self.impl_unexpanded_invocations.get(&impl_def_id)
556 && !unexpanded_invocations.is_empty()
557 {
558 return Err(Indeterminate);
559 }
560
561 let mut idents = Vec::new();
562 target_trait.for_each_child(self, |this, ident, orig_ident_span, ns, _binding| {
563 if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
564 && overriding_keys.contains(&BindingKey::new(ident, ns))
565 {
566 } else {
568 idents.push((ident.orig(star_span.with_ctxt(orig_ident_span.ctxt())), None));
570 }
571 });
572 Ok(idents)
573 }
574
575 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol) {
576 self.impl_trait_names.insert(id, name);
577 }
578}
579
580impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
581 fn smart_resolve_macro_path(
585 &mut self,
586 path: &ast::Path,
587 kind: MacroKind,
588 supports_macro_expansion: SupportsMacroExpansion,
589 inner_attr: bool,
590 parent_scope: &ParentScope<'ra>,
591 node_id: NodeId,
592 force: bool,
593 deleg_impl: Option<(LocalDefId, Span)>,
594 invoc_in_mod_inert_attr: Option<LocalDefId>,
595 suggestion_span: Option<Span>,
596 ) -> Result<(&'ra Arc<SyntaxExtension>, Res), Indeterminate> {
597 let (ext, res) = match self.cm().resolve_macro_or_delegation_path(
598 path,
599 kind,
600 parent_scope,
601 force,
602 deleg_impl,
603 invoc_in_mod_inert_attr.map(|def_id| (def_id, node_id)),
604 None,
605 suggestion_span,
606 ) {
607 Ok((Some(ext), res)) => (ext, res),
608 Ok((None, res)) => (self.dummy_ext(kind), res),
609 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
610 Err(Determinacy::Undetermined) => return Err(Indeterminate),
611 };
612
613 if deleg_impl.is_some() {
615 if !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::Err | Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Err | Res::Def(DefKind::Trait, _)) {
616 self.dcx().emit_err(MacroExpectedFound {
617 span: path.span,
618 expected: "trait",
619 article: "a",
620 found: res.descr(),
621 macro_path: &pprust::path_to_string(path),
622 remove_surrounding_derive: None,
623 add_as_non_derive: None,
624 });
625 return Ok((self.dummy_ext(kind), Res::Err));
626 }
627
628 return Ok((ext, res));
629 }
630
631 for (idx, segment) in path.segments.iter().enumerate() {
633 if let Some(args) = &segment.args {
634 self.dcx().emit_err(diagnostics::GenericArgumentsInMacroPath { span: args.span() });
635 }
636 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
637 if idx == 0 {
638 self.dcx().emit_err(diagnostics::AttributesStartingWithRustcAreReserved {
639 span: segment.ident.span,
640 });
641 } else {
642 self.dcx().emit_err(diagnostics::AttributesContainingRustcAreReserved {
643 span: segment.ident.span,
644 });
645 }
646 }
647 }
648
649 match res {
650 Res::Def(DefKind::Macro(_), def_id) => {
651 if let Some(def_id) = def_id.as_local() {
652 self.unused_macros.swap_remove(&def_id);
653 if self.proc_macro_stubs.contains(&def_id) {
654 self.dcx().emit_err(diagnostics::ProcMacroSameCrate {
655 span: path.span,
656 is_test: self.tcx.sess.is_test_crate(),
657 });
658 }
659 }
660 }
661 Res::NonMacroAttr(..) | Res::Err => {}
662 _ => {
::core::panicking::panic_fmt(format_args!("expected `DefKind::Macro` or `Res::NonMacroAttr`"));
}panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
663 };
664
665 self.check_stability_and_deprecation(&ext, path, node_id);
666
667 let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
668 Some((kind.article(), kind.descr_expected()))
669 } else if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(..) => true,
_ => false,
}matches!(res, Res::Def(..)) {
670 match supports_macro_expansion {
671 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
672 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
673 if inner_attr && !supports_inner_attrs {
674 Some(("a", "non-macro inner attribute"))
675 } else {
676 None
677 }
678 }
679 }
680 } else {
681 None
682 };
683 if let Some((article, expected)) = unexpected_res {
684 let path_str = pprust::path_to_string(path);
685
686 let mut err = MacroExpectedFound {
687 span: path.span,
688 expected,
689 article,
690 found: res.descr(),
691 macro_path: &path_str,
692 remove_surrounding_derive: None,
693 add_as_non_derive: None,
694 };
695
696 if !path.span.from_expansion()
698 && kind == MacroKind::Derive
699 && !ext.macro_kinds().contains(MacroKinds::DERIVE)
700 && ext.macro_kinds().contains(MacroKinds::ATTR)
701 {
702 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
703 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
704 }
705
706 self.dcx().emit_err(err);
707
708 return Ok((self.dummy_ext(kind), Res::Err));
709 }
710
711 if res != Res::Err && inner_attr && !self.features.custom_inner_attributes() {
713 let is_macro = match res {
714 Res::Def(..) => true,
715 Res::NonMacroAttr(..) => false,
716 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
717 };
718 let msg = if is_macro {
719 "inner macro attributes are unstable"
720 } else {
721 "custom inner attributes are unstable"
722 };
723 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
724 }
725
726 const DIAGNOSTIC_ATTRIBUTES: &[(Symbol, Option<Symbol>)] = &[
727 (sym::on_unimplemented, None),
728 (sym::do_not_recommend, None),
729 (sym::on_move, Some(sym::diagnostic_on_move)),
730 (sym::on_const, Some(sym::diagnostic_on_const)),
731 (sym::on_unknown, Some(sym::diagnostic_on_unknown)),
732 (sym::on_unmatched_args, Some(sym::diagnostic_on_unmatched_args)),
733 (sym::on_type_error, Some(sym::diagnostic_on_type_error)),
734 (sym::opaque, Some(sym::diagnostic_opaque)),
735 ];
736
737 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
738 && let [namespace, attribute, ..] = &*path.segments
739 && namespace.ident.name == sym::diagnostic
740 && !DIAGNOSTIC_ATTRIBUTES.iter().any(|(attr, feature)| {
741 attribute.ident.name == *attr && feature.is_none_or(|f| self.features.enabled(f))
742 })
743 {
744 let name = attribute.ident.name;
745 let span = attribute.span();
746
747 let help = 'help: {
748 if self.tcx.sess.is_nightly_build() {
749 for (attr, feature) in DIAGNOSTIC_ATTRIBUTES {
750 if let Some(feature) = *feature
751 && *attr == name
752 {
753 break 'help Some(
754 diagnostics::UnknownDiagnosticAttributeHelp::UseFeature { feature },
755 );
756 }
757 }
758 }
759
760 let candidates = DIAGNOSTIC_ATTRIBUTES
761 .iter()
762 .filter_map(|(attr, feature)| {
763 feature.is_none_or(|f| self.features.enabled(f)).then_some(*attr)
764 })
765 .collect::<Vec<_>>();
766
767 find_best_match_for_name(&candidates, name, None).map(|typo_name| {
768 diagnostics::UnknownDiagnosticAttributeHelp::Typo { span, typo_name }
769 })
770 };
771
772 self.tcx.sess.psess.buffer_lint(
773 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
774 span,
775 node_id,
776 diagnostics::UnknownDiagnosticAttribute { help },
777 );
778 }
779
780 Ok((ext, res))
781 }
782
783 pub(crate) fn resolve_derive_macro_path<'r>(
784 self: CmResolver<'r, 'ra, 'tcx>,
785 path: &ast::Path,
786 parent_scope: &ParentScope<'ra>,
787 force: bool,
788 ignore_import: Option<Import<'ra>>,
789 ) -> Result<(Option<&'r Arc<SyntaxExtension>>, Res), Determinacy> {
790 self.resolve_macro_or_delegation_path(
791 path,
792 MacroKind::Derive,
793 parent_scope,
794 force,
795 None,
796 None,
797 ignore_import,
798 None,
799 )
800 }
801
802 fn resolve_macro_or_delegation_path<'r>(
803 mut self: CmResolver<'r, 'ra, 'tcx>,
804 ast_path: &ast::Path,
805 kind: MacroKind,
806 parent_scope: &ParentScope<'ra>,
807 force: bool,
808 deleg_impl: Option<(LocalDefId, Span)>,
809 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
810 ignore_import: Option<Import<'ra>>,
811 suggestion_span: Option<Span>,
812 ) -> Result<(Option<&'ra Arc<SyntaxExtension>>, Res), Determinacy> {
813 let path_span = ast_path.span;
814 let mut path = Segment::from_path(ast_path);
815
816 if deleg_impl.is_none()
818 && kind == MacroKind::Bang
819 && let [segment] = path.as_slice()
820 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
821 {
822 let root = Ident::new(kw::DollarCrate, segment.ident.span);
823 path.insert(0, Segment::from_ident(root));
824 }
825
826 let res = if deleg_impl.is_some() || path.len() > 1 {
827 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
828 let res = match self.reborrow().maybe_resolve_path(
829 &path,
830 Some(ns),
831 parent_scope,
832 ignore_import,
833 ) {
834 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
835 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
836 PathResult::NonModule(..)
837 | PathResult::Indeterminate
838 | PathResult::Failed { .. } => Err(Determinacy::Determined),
839 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
840 Ok(module.res().unwrap())
841 }
842 PathResult::Module(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
843 };
844
845 self.multi_segment_macro_resolutions.borrow_mut(&self).push((
846 path,
847 path_span,
848 kind,
849 *parent_scope,
850 res.ok(),
851 ns,
852 ));
853
854 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
855 res
856 } else {
857 let binding = self.reborrow().resolve_ident_in_scope_set(
858 path[0].ident,
859 ScopeSet::Macro(kind),
860 parent_scope,
861 None,
862 None,
863 None,
864 );
865 let binding = binding.map_err(|determinacy| {
866 Determinacy::determined(determinacy == Determinacy::Determined || force)
867 });
868 if let Err(Determinacy::Undetermined) = binding {
869 return Err(Determinacy::Undetermined);
870 }
871
872 self.single_segment_macro_resolutions.borrow_mut(&self).push((
873 path[0].ident,
874 kind,
875 *parent_scope,
876 binding.ok(),
877 suggestion_span,
878 ));
879
880 let res = binding.map(|binding| binding.res());
881 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
882 self.reborrow().report_out_of_scope_macro_calls(
883 ast_path,
884 parent_scope,
885 invoc_in_mod_inert_attr,
886 binding.ok(),
887 );
888 res
889 };
890
891 let res = res?;
892 let ext = match deleg_impl {
893 Some((impl_def_id, star_span)) => match res {
894 Res::Def(DefKind::Trait, def_id) => {
895 let edition = self.tcx.sess.edition();
896 Some(self.arenas.alloc_macro(SyntaxExtension::glob_delegation(
897 def_id,
898 impl_def_id,
899 star_span,
900 edition,
901 )))
902 }
903 _ => None,
904 },
905 None => self.get_macro(res),
906 };
907 Ok((ext, res))
908 }
909
910 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
911 let check_consistency = |this: &Self,
912 path: &[Segment],
913 span,
914 kind: MacroKind,
915 initial_res: Option<Res>,
916 res: Res| {
917 if let Some(initial_res) = initial_res {
918 if res != initial_res {
919 if this.ambiguity_errors.is_empty() {
920 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
924 }
925 }
926 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
927 let err = this.dcx().create_err(CannotDetermineMacroResolution {
936 span,
937 kind: kind.descr(),
938 path: Segment::names_to_string(path),
939 });
940 err.stash(span, StashKey::UndeterminedMacroResolution);
941 }
942 };
943
944 let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
945 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
946 for seg in &mut path {
948 seg.id = None;
949 }
950 match self.cm().resolve_path(
951 &path,
952 Some(ns),
953 &parent_scope,
954 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
955 None,
956 None,
957 ) {
958 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
959 check_consistency(self, &path, path_span, kind, initial_res, res)
960 }
961 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
963 self,
964 &path,
965 path_span,
966 kind,
967 initial_res,
968 module.res().unwrap(),
969 ),
970 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
971 let mut suggestion = None;
972 let (span, message, label, module, segment) = match path_res {
973 PathResult::Failed { span, label, module, segment, message, .. } => {
974 if let PathResult::NonModule(partial_res) = self
976 .cm()
977 .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
978 && partial_res.unresolved_segments() == 0
979 {
980 let sm = self.tcx.sess.source_map();
981 let exclamation_span = sm.next_point(span);
982 suggestion = Some((
983 ::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())],
984 ::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!(
985 "{} is not a macro, but a {}, try to remove `!`",
986 Segment::names_to_string(&path),
987 partial_res.base_res().descr()
988 ),
989 Applicability::MaybeIncorrect,
990 ));
991 }
992 (span, message, label, module, segment.name)
993 }
994 PathResult::NonModule(partial_res) => {
995 let found_an = partial_res.base_res().article();
996 let found_descr = partial_res.base_res().descr();
997 let scope = match &path[..partial_res.unresolved_segments()] {
998 [.., prev] => {
999 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{0}`", prev.ident,
found_descr))
})format!("{found_descr} `{}`", prev.ident)
1000 }
1001 _ => found_descr.to_string(),
1002 };
1003 let expected_an = kind.article();
1004 let expected_descr = kind.descr();
1005 let expected_name = path[partial_res.unresolved_segments()].ident;
1006
1007 (
1008 path_span,
1009 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}",
expected_descr, expected_name, scope))
})format!(
1010 "cannot find {expected_descr} `{expected_name}` in {scope}"
1011 ),
1012 match partial_res.base_res() {
1013 Res::Def(
1014 DefKind::Mod | DefKind::Macro(..) | DefKind::ExternCrate,
1015 _,
1016 ) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("partially resolved path in {0} {1}",
expected_an, expected_descr))
})format!(
1017 "partially resolved path in {expected_an} {expected_descr}",
1018 ),
1019 _ => ::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!(
1020 "{expected_an} {expected_descr} can't exist within \
1021 {found_an} {found_descr}"
1022 ),
1023 },
1024 None,
1025 path.last().map(|segment| segment.ident.name).unwrap(),
1026 )
1027 }
1028 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1029 };
1030 self.report_error(
1031 span,
1032 ResolutionError::FailedToResolve {
1033 segment,
1034 label,
1035 suggestion,
1036 module,
1037 message,
1038 },
1039 );
1040 }
1041 PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")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().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().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 None,
1134 span,
1135 stability::UnstableKind::Regular,
1136 );
1137 }
1138 }
1139 if let Some(depr) = &ext.deprecation {
1140 let path = pprust::path_to_string(path);
1141 stability::early_report_macro_deprecation(
1142 &mut self.lint_buffer,
1143 depr,
1144 span,
1145 node_id,
1146 path,
1147 );
1148 }
1149 }
1150
1151 fn prohibit_imported_non_macro_attrs(
1152 &self,
1153 decl: Option<Decl<'ra>>,
1154 res: Option<Res>,
1155 span: Span,
1156 ) {
1157 if let Some(Res::NonMacroAttr(kind)) = res {
1158 if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1159 self.dcx().emit_err(diagnostics::CannotUseThroughAnImport {
1160 span,
1161 article: kind.article(),
1162 descr: kind.descr(),
1163 binding_span: decl.map(|d| d.span),
1164 });
1165 }
1166 }
1167 }
1168
1169 fn report_out_of_scope_macro_calls<'r>(
1170 mut self: CmResolver<'r, 'ra, 'tcx>,
1171 path: &ast::Path,
1172 parent_scope: &ParentScope<'ra>,
1173 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1174 decl: Option<Decl<'ra>>,
1175 ) {
1176 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1177 && let Some(decl) = decl
1178 && let DeclKind::Def(res) = decl.kind
1180 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1181 && kinds.contains(MacroKinds::BANG)
1182 && self.tcx.is_descendant_of(def_id, mod_def_id)
1185 {
1186 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1190 let ident = path.segments[0].ident;
1191 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1192 ident,
1193 ScopeSet::Macro(MacroKind::Bang),
1194 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1195 None,
1196 None,
1197 None,
1198 );
1199 if let Ok(fallback_binding) = fallback_binding
1200 && fallback_binding.res().opt_def_id() == Some(def_id)
1201 {
1202 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1204 } else {
1205 let location = match parent_scope.module.kind {
1206 ModuleKind::Def(kind, def_id, _, name) => {
1207 if let Some(name) = name {
1208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind.descr(def_id),
name))
})format!("{} `{name}`", kind.descr(def_id))
1209 } else {
1210 "the crate root".to_string()
1211 }
1212 }
1213 ModuleKind::Block => "this scope".to_string(),
1214 };
1215 self.tcx.sess.psess.buffer_lint(
1216 OUT_OF_SCOPE_MACRO_CALLS,
1217 path.span,
1218 node_id,
1219 diagnostics::OutOfScopeMacroCalls {
1220 span: path.span,
1221 path: pprust::path_to_string(path),
1222 location,
1223 },
1224 );
1225 }
1226 }
1227 }
1228
1229 pub(crate) fn check_reserved_macro_name(&self, name: Symbol, span: Span, res: Res) {
1230 if name == sym::cfg || name == sym::cfg_attr {
1233 let macro_kinds = res.macro_kinds();
1234 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1235 self.dcx()
1236 .emit_err(diagnostics::NameReservedInAttributeNamespace { span, ident: name });
1237 }
1238 }
1239 }
1240
1241 pub(crate) fn compile_macro(
1245 &self,
1246 macro_def: &ast::MacroDef,
1247 ident: Ident,
1248 attrs: &[rustc_hir::Attribute],
1249 span: Span,
1250 node_id: NodeId,
1251 edition: Edition,
1252 ) -> SyntaxExtension {
1253 let mut ext = compile_declarative_macro(
1254 self.tcx.sess,
1255 self.features,
1256 macro_def,
1257 ident,
1258 attrs,
1259 span,
1260 node_id,
1261 edition,
1262 );
1263
1264 if let Some(builtin_name) = ext.builtin_name {
1265 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1267 ext.kind = builtin_ext_kind.clone();
1270 } else {
1271 self.dcx().emit_err(diagnostics::CannotFindBuiltinMacroWithName { span, ident });
1272 }
1273 }
1274
1275 ext
1276 }
1277
1278 fn path_accessible(
1279 &mut self,
1280 expn_id: LocalExpnId,
1281 path: &ast::Path,
1282 namespaces: &[Namespace],
1283 ) -> Result<bool, Indeterminate> {
1284 let span = path.span;
1285 let path = &Segment::from_path(path);
1286 let parent_scope = self.invocation_parent_scopes[&expn_id];
1287
1288 let mut indeterminate = false;
1289 for ns in namespaces {
1290 match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1291 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1292 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1293 return Ok(true);
1294 }
1295 PathResult::NonModule(..) |
1296 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1298 self.dcx().emit_err(diagnostics::CfgAccessibleUnsure { span });
1299
1300 return Ok(false);
1303 }
1304 PathResult::Indeterminate => indeterminate = true,
1305 PathResult::Failed { .. } => {}
1308 PathResult::Module(_) => { ::core::panicking::panic_fmt(format_args!("unexpected path resolution")); }panic!("unexpected path resolution"),
1309 }
1310 }
1311
1312 if indeterminate {
1313 return Err(Indeterminate);
1314 }
1315
1316 Ok(false)
1317 }
1318}