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