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_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 ) -> 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 (idx, segment) in path.segments.iter().enumerate() {
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 if idx == 0 {
627 self.dcx().emit_err(errors::AttributesStartingWithRustcAreReserved {
628 span: segment.ident.span,
629 });
630 } else {
631 self.dcx().emit_err(errors::AttributesContainingRustcAreReserved {
632 span: segment.ident.span,
633 });
634 }
635 }
636 }
637
638 match res {
639 Res::Def(DefKind::Macro(_), def_id) => {
640 if let Some(def_id) = def_id.as_local() {
641 self.unused_macros.swap_remove(&def_id);
642 if self.proc_macro_stubs.contains(&def_id) {
643 self.dcx().emit_err(errors::ProcMacroSameCrate {
644 span: path.span,
645 is_test: self.tcx.sess.is_test_crate(),
646 });
647 }
648 }
649 }
650 Res::NonMacroAttr(..) | Res::Err => {}
651 _ => {
::core::panicking::panic_fmt(format_args!("expected `DefKind::Macro` or `Res::NonMacroAttr`"));
}panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
652 };
653
654 self.check_stability_and_deprecation(&ext, path, node_id);
655
656 let unexpected_res = if !ext.macro_kinds().contains(kind.into()) {
657 Some((kind.article(), kind.descr_expected()))
658 } else if #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(..) => true,
_ => false,
}matches!(res, Res::Def(..)) {
659 match supports_macro_expansion {
660 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
661 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
662 if inner_attr && !supports_inner_attrs {
663 Some(("a", "non-macro inner attribute"))
664 } else {
665 None
666 }
667 }
668 }
669 } else {
670 None
671 };
672 if let Some((article, expected)) = unexpected_res {
673 let path_str = pprust::path_to_string(path);
674
675 let mut err = MacroExpectedFound {
676 span: path.span,
677 expected,
678 article,
679 found: res.descr(),
680 macro_path: &path_str,
681 remove_surrounding_derive: None,
682 add_as_non_derive: None,
683 };
684
685 if !path.span.from_expansion()
687 && kind == MacroKind::Derive
688 && !ext.macro_kinds().contains(MacroKinds::DERIVE)
689 && ext.macro_kinds().contains(MacroKinds::ATTR)
690 {
691 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
692 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
693 }
694
695 self.dcx().emit_err(err);
696
697 return Ok((self.dummy_ext(kind), Res::Err));
698 }
699
700 if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes() {
702 let is_macro = match res {
703 Res::Def(..) => true,
704 Res::NonMacroAttr(..) => false,
705 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
706 };
707 let msg = if is_macro {
708 "inner macro attributes are unstable"
709 } else {
710 "custom inner attributes are unstable"
711 };
712 feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit();
713 }
714
715 const DIAG_ATTRS: &[Symbol] =
716 &[sym::on_unimplemented, sym::do_not_recommend, sym::on_const, sym::on_move];
717
718 if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
719 && let [namespace, attribute, ..] = &*path.segments
720 && namespace.ident.name == sym::diagnostic
721 && !DIAG_ATTRS.contains(&attribute.ident.name)
722 {
723 let span = attribute.span();
724
725 let typo = find_best_match_for_name(DIAG_ATTRS, attribute.ident.name, Some(5))
726 .map(|typo_name| errors::UnknownDiagnosticAttributeTypoSugg { span, typo_name });
727
728 self.tcx.sess.psess.buffer_lint(
729 UNKNOWN_DIAGNOSTIC_ATTRIBUTES,
730 span,
731 node_id,
732 errors::UnknownDiagnosticAttribute { typo },
733 );
734 }
735
736 Ok((ext, res))
737 }
738
739 pub(crate) fn resolve_derive_macro_path<'r>(
740 self: CmResolver<'r, 'ra, 'tcx>,
741 path: &ast::Path,
742 parent_scope: &ParentScope<'ra>,
743 force: bool,
744 ignore_import: Option<Import<'ra>>,
745 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
746 self.resolve_macro_or_delegation_path(
747 path,
748 MacroKind::Derive,
749 parent_scope,
750 force,
751 None,
752 None,
753 ignore_import,
754 None,
755 )
756 }
757
758 fn resolve_macro_or_delegation_path<'r>(
759 mut self: CmResolver<'r, 'ra, 'tcx>,
760 ast_path: &ast::Path,
761 kind: MacroKind,
762 parent_scope: &ParentScope<'ra>,
763 force: bool,
764 deleg_impl: Option<LocalDefId>,
765 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
766 ignore_import: Option<Import<'ra>>,
767 suggestion_span: Option<Span>,
768 ) -> Result<(Option<Arc<SyntaxExtension>>, Res), Determinacy> {
769 let path_span = ast_path.span;
770 let mut path = Segment::from_path(ast_path);
771
772 if deleg_impl.is_none()
774 && kind == MacroKind::Bang
775 && let [segment] = path.as_slice()
776 && segment.ident.span.ctxt().outer_expn_data().local_inner_macros
777 {
778 let root = Ident::new(kw::DollarCrate, segment.ident.span);
779 path.insert(0, Segment::from_ident(root));
780 }
781
782 let res = if deleg_impl.is_some() || path.len() > 1 {
783 let ns = if deleg_impl.is_some() { TypeNS } else { MacroNS };
784 let res = match self.reborrow().maybe_resolve_path(
785 &path,
786 Some(ns),
787 parent_scope,
788 ignore_import,
789 ) {
790 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
791 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
792 PathResult::NonModule(..)
793 | PathResult::Indeterminate
794 | PathResult::Failed { .. } => Err(Determinacy::Determined),
795 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
796 Ok(module.res().unwrap())
797 }
798 PathResult::Module(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
799 };
800
801 self.multi_segment_macro_resolutions.borrow_mut(&self).push((
802 path,
803 path_span,
804 kind,
805 *parent_scope,
806 res.ok(),
807 ns,
808 ));
809
810 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
811 res
812 } else {
813 let binding = self.reborrow().resolve_ident_in_scope_set(
814 path[0].ident,
815 ScopeSet::Macro(kind),
816 parent_scope,
817 None,
818 None,
819 None,
820 );
821 let binding = binding.map_err(|determinacy| {
822 Determinacy::determined(determinacy == Determinacy::Determined || force)
823 });
824 if let Err(Determinacy::Undetermined) = binding {
825 return Err(Determinacy::Undetermined);
826 }
827
828 self.single_segment_macro_resolutions.borrow_mut(&self).push((
829 path[0].ident,
830 kind,
831 *parent_scope,
832 binding.ok(),
833 suggestion_span,
834 ));
835
836 let res = binding.map(|binding| binding.res());
837 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
838 self.reborrow().report_out_of_scope_macro_calls(
839 ast_path,
840 parent_scope,
841 invoc_in_mod_inert_attr,
842 binding.ok(),
843 );
844 res
845 };
846
847 let res = res?;
848 let ext = match deleg_impl {
849 Some(impl_def_id) => match res {
850 def::Res::Def(DefKind::Trait, def_id) => {
851 let edition = self.tcx.sess.edition();
852 Some(Arc::new(SyntaxExtension::glob_delegation(def_id, impl_def_id, edition)))
853 }
854 _ => None,
855 },
856 None => self.get_macro(res).map(|macro_data| Arc::clone(¯o_data.ext)),
857 };
858 Ok((ext, res))
859 }
860
861 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
862 let check_consistency = |this: &Self,
863 path: &[Segment],
864 span,
865 kind: MacroKind,
866 initial_res: Option<Res>,
867 res: Res| {
868 if let Some(initial_res) = initial_res {
869 if res != initial_res {
870 if this.ambiguity_errors.is_empty() {
871 this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro");
875 }
876 }
877 } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() {
878 let err = this.dcx().create_err(CannotDetermineMacroResolution {
887 span,
888 kind: kind.descr(),
889 path: Segment::names_to_string(path),
890 });
891 err.stash(span, StashKey::UndeterminedMacroResolution);
892 }
893 };
894
895 let macro_resolutions = self.multi_segment_macro_resolutions.take(self);
896 for (mut path, path_span, kind, parent_scope, initial_res, ns) in macro_resolutions {
897 for seg in &mut path {
899 seg.id = None;
900 }
901 match self.cm().resolve_path(
902 &path,
903 Some(ns),
904 &parent_scope,
905 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
906 None,
907 None,
908 ) {
909 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
910 check_consistency(self, &path, path_span, kind, initial_res, res)
911 }
912 PathResult::Module(ModuleOrUniformRoot::Module(module)) => check_consistency(
914 self,
915 &path,
916 path_span,
917 kind,
918 initial_res,
919 module.res().unwrap(),
920 ),
921 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
922 let mut suggestion = None;
923 let (span, message, label, module, segment) = match path_res {
924 PathResult::Failed {
925 span, label, module, segment_name, message, ..
926 } => {
927 if let PathResult::NonModule(partial_res) = self
929 .cm()
930 .maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
931 && partial_res.unresolved_segments() == 0
932 {
933 let sm = self.tcx.sess.source_map();
934 let exclamation_span = sm.next_point(span);
935 suggestion = Some((
936 ::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())],
937 ::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!(
938 "{} is not a macro, but a {}, try to remove `!`",
939 Segment::names_to_string(&path),
940 partial_res.base_res().descr()
941 ),
942 Applicability::MaybeIncorrect,
943 ));
944 }
945 (span, message, label, module, segment_name)
946 }
947 PathResult::NonModule(partial_res) => {
948 let found_an = partial_res.base_res().article();
949 let found_descr = partial_res.base_res().descr();
950 let scope = match &path[..partial_res.unresolved_segments()] {
951 [.., prev] => {
952 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} `{0}`", prev.ident,
found_descr))
})format!("{found_descr} `{}`", prev.ident)
953 }
954 _ => found_descr.to_string(),
955 };
956 let expected_an = kind.article();
957 let expected_descr = kind.descr();
958 let expected_name = path[partial_res.unresolved_segments()].ident;
959
960 (
961 path_span,
962 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}",
expected_descr, expected_name, scope))
})format!(
963 "cannot find {expected_descr} `{expected_name}` in {scope}"
964 ),
965 match partial_res.base_res() {
966 Res::Def(
967 DefKind::Mod | DefKind::Macro(..) | DefKind::ExternCrate,
968 _,
969 ) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("partially resolved path in {0} {1}",
expected_an, expected_descr))
})format!(
970 "partially resolved path in {expected_an} {expected_descr}",
971 ),
972 _ => ::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!(
973 "{expected_an} {expected_descr} can't exist within \
974 {found_an} {found_descr}"
975 ),
976 },
977 None,
978 path.last().map(|segment| segment.ident.name).unwrap(),
979 )
980 }
981 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
982 };
983 self.report_error(
984 span,
985 ResolutionError::FailedToResolve {
986 segment,
987 label,
988 suggestion,
989 module,
990 message,
991 },
992 );
993 }
994 PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
995 }
996 }
997
998 let macro_resolutions = self.single_segment_macro_resolutions.take(self);
999 for (ident, kind, parent_scope, initial_binding, sugg_span) in macro_resolutions {
1000 match self.cm().resolve_ident_in_scope_set(
1001 ident,
1002 ScopeSet::Macro(kind),
1003 &parent_scope,
1004 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1005 None,
1006 None,
1007 ) {
1008 Ok(binding) => {
1009 let initial_res = initial_binding.map(|initial_binding| {
1010 self.record_use(ident, initial_binding, Used::Other);
1011 initial_binding.res()
1012 });
1013 let res = binding.res();
1014 let seg = Segment::from_ident(ident);
1015 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
1016 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
1017 let node_id = self
1018 .invocation_parents
1019 .get(&parent_scope.expansion)
1020 .map_or(ast::CRATE_NODE_ID, |parent| {
1021 self.def_id_to_node_id(parent.parent_def)
1022 });
1023 self.lint_buffer.buffer_lint(
1024 LEGACY_DERIVE_HELPERS,
1025 node_id,
1026 ident.span,
1027 errors::LegacyDeriveHelpers { span: binding.span },
1028 );
1029 }
1030 }
1031 Err(..) => {
1032 let expected = kind.descr_expected();
1033
1034 let mut err = self.dcx().create_err(CannotFindIdentInThisScope {
1035 span: ident.span,
1036 expected,
1037 ident,
1038 });
1039 self.unresolved_macro_suggestions(
1040 &mut err,
1041 kind,
1042 &parent_scope,
1043 ident,
1044 krate,
1045 sugg_span,
1046 );
1047 err.emit();
1048 }
1049 }
1050 }
1051
1052 let builtin_attrs = mem::take(&mut self.builtin_attrs);
1053 for (ident, parent_scope) in builtin_attrs {
1054 let _ = self.cm().resolve_ident_in_scope_set(
1055 ident,
1056 ScopeSet::Macro(MacroKind::Attr),
1057 &parent_scope,
1058 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
1059 None,
1060 None,
1061 );
1062 }
1063 }
1064
1065 fn check_stability_and_deprecation(
1066 &mut self,
1067 ext: &SyntaxExtension,
1068 path: &ast::Path,
1069 node_id: NodeId,
1070 ) {
1071 let span = path.span;
1072 if let Some(stability) = &ext.stability
1073 && let StabilityLevel::Unstable { reason, issue, implied_by, .. } = stability.level
1074 {
1075 let feature = stability.feature;
1076
1077 let is_allowed =
1078 |feature| self.tcx.features().enabled(feature) || span.allows_unstable(feature);
1079 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
1080 if !is_allowed(feature) && !allowed_by_implication {
1081 stability::report_unstable(
1082 self.tcx.sess,
1083 feature,
1084 reason.to_opt_reason(),
1085 issue,
1086 None,
1087 span,
1088 stability::UnstableKind::Regular,
1089 );
1090 }
1091 }
1092 if let Some(depr) = &ext.deprecation {
1093 let path = pprust::path_to_string(path);
1094 stability::early_report_macro_deprecation(
1095 &mut self.lint_buffer,
1096 depr,
1097 span,
1098 node_id,
1099 path,
1100 );
1101 }
1102 }
1103
1104 fn prohibit_imported_non_macro_attrs(
1105 &self,
1106 decl: Option<Decl<'ra>>,
1107 res: Option<Res>,
1108 span: Span,
1109 ) {
1110 if let Some(Res::NonMacroAttr(kind)) = res {
1111 if kind != NonMacroAttrKind::Tool && decl.is_none_or(|b| b.is_import()) {
1112 self.dcx().emit_err(errors::CannotUseThroughAnImport {
1113 span,
1114 article: kind.article(),
1115 descr: kind.descr(),
1116 binding_span: decl.map(|d| d.span),
1117 });
1118 }
1119 }
1120 }
1121
1122 fn report_out_of_scope_macro_calls<'r>(
1123 mut self: CmResolver<'r, 'ra, 'tcx>,
1124 path: &ast::Path,
1125 parent_scope: &ParentScope<'ra>,
1126 invoc_in_mod_inert_attr: Option<(LocalDefId, NodeId)>,
1127 decl: Option<Decl<'ra>>,
1128 ) {
1129 if let Some((mod_def_id, node_id)) = invoc_in_mod_inert_attr
1130 && let Some(decl) = decl
1131 && let DeclKind::Def(res) = decl.kind
1133 && let Res::Def(DefKind::Macro(kinds), def_id) = res
1134 && kinds.contains(MacroKinds::BANG)
1135 && self.tcx.is_descendant_of(def_id, mod_def_id.to_def_id())
1138 {
1139 let no_macro_rules = self.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty);
1143 let ident = path.segments[0].ident;
1144 let fallback_binding = self.reborrow().resolve_ident_in_scope_set(
1145 ident,
1146 ScopeSet::Macro(MacroKind::Bang),
1147 &ParentScope { macro_rules: no_macro_rules, ..*parent_scope },
1148 None,
1149 None,
1150 None,
1151 );
1152 if let Ok(fallback_binding) = fallback_binding
1153 && fallback_binding.res().opt_def_id() == Some(def_id)
1154 {
1155 self.get_mut().record_use(ident, fallback_binding, Used::Other);
1157 } else {
1158 let location = match parent_scope.module.kind {
1159 ModuleKind::Def(kind, def_id, name) => {
1160 if let Some(name) = name {
1161 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}`", kind.descr(def_id),
name))
})format!("{} `{name}`", kind.descr(def_id))
1162 } else {
1163 "the crate root".to_string()
1164 }
1165 }
1166 ModuleKind::Block => "this scope".to_string(),
1167 };
1168 self.tcx.sess.psess.buffer_lint(
1169 OUT_OF_SCOPE_MACRO_CALLS,
1170 path.span,
1171 node_id,
1172 errors::OutOfScopeMacroCalls {
1173 span: path.span,
1174 path: pprust::path_to_string(path),
1175 location,
1176 },
1177 );
1178 }
1179 }
1180 }
1181
1182 pub(crate) fn check_reserved_macro_name(&self, name: Symbol, span: Span, res: Res) {
1183 if name == sym::cfg || name == sym::cfg_attr {
1186 let macro_kinds = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kinds());
1187 if macro_kinds.is_some() && sub_namespace_match(macro_kinds, Some(MacroKind::Attr)) {
1188 self.dcx().emit_err(errors::NameReservedInAttributeNamespace { span, ident: name });
1189 }
1190 }
1191 }
1192
1193 pub(crate) fn compile_macro(
1197 &self,
1198 macro_def: &ast::MacroDef,
1199 ident: Ident,
1200 attrs: &[rustc_hir::Attribute],
1201 span: Span,
1202 node_id: NodeId,
1203 edition: Edition,
1204 ) -> MacroData {
1205 let (mut ext, mut nrules) = compile_declarative_macro(
1206 self.tcx.sess,
1207 self.tcx.features(),
1208 macro_def,
1209 ident,
1210 attrs,
1211 span,
1212 node_id,
1213 edition,
1214 );
1215
1216 if let Some(builtin_name) = ext.builtin_name {
1217 if let Some(builtin_ext_kind) = self.builtin_macros.get(&builtin_name) {
1219 ext.kind = builtin_ext_kind.clone();
1222 nrules = 0;
1223 } else {
1224 self.dcx().emit_err(errors::CannotFindBuiltinMacroWithName { span, ident });
1225 }
1226 }
1227
1228 MacroData { ext: Arc::new(ext), nrules, macro_rules: macro_def.macro_rules }
1229 }
1230
1231 fn path_accessible(
1232 &mut self,
1233 expn_id: LocalExpnId,
1234 path: &ast::Path,
1235 namespaces: &[Namespace],
1236 ) -> Result<bool, Indeterminate> {
1237 let span = path.span;
1238 let path = &Segment::from_path(path);
1239 let parent_scope = self.invocation_parent_scopes[&expn_id];
1240
1241 let mut indeterminate = false;
1242 for ns in namespaces {
1243 match self.cm().maybe_resolve_path(path, Some(*ns), &parent_scope, None) {
1244 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
1245 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
1246 return Ok(true);
1247 }
1248 PathResult::NonModule(..) |
1249 PathResult::Failed { is_error_from_last_segment: false, .. } => {
1251 self.dcx()
1252 .emit_err(errors::CfgAccessibleUnsure { span });
1253
1254 return Ok(false);
1257 }
1258 PathResult::Indeterminate => indeterminate = true,
1259 PathResult::Failed { .. } => {}
1262 PathResult::Module(_) => { ::core::panicking::panic_fmt(format_args!("unexpected path resolution")); }panic!("unexpected path resolution"),
1263 }
1264 }
1265
1266 if indeterminate {
1267 return Err(Indeterminate);
1268 }
1269
1270 Ok(false)
1271 }
1272}