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