1 //! A bunch of methods and structures more or less related to resolving macros and
2 //! interface provided by `Resolver` to macro expander.
3
4 use crate::errors::{
5 self, AddAsNonDerive, CannotFindIdentInThisScope, MacroExpectedFound, RemoveSurroundingDerive,
6 };
7 use crate::Namespace::*;
8 use crate::{BuiltinMacroState, Determinacy};
9 use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
10 use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment};
11 use rustc_ast::expand::StrippedCfgItem;
12 use rustc_ast::{self as ast, attr, Crate, Inline, ItemKind, ModKind, NodeId};
13 use rustc_ast_pretty::pprust;
14 use rustc_attr::StabilityLevel;
15 use rustc_data_structures::intern::Interned;
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::{struct_span_err, Applicability};
18 use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
19 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
20 use rustc_expand::compile_declarative_macro;
21 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
22 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
23 use rustc_hir::def_id::{CrateNum, LocalDefId};
24 use rustc_middle::middle::stability;
25 use rustc_middle::ty::RegisteredTools;
26 use rustc_middle::ty::TyCtxt;
27 use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
28 use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
29 use rustc_session::lint::BuiltinLintDiagnostics;
30 use rustc_session::parse::feature_err;
31 use rustc_span::edition::Edition;
32 use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
33 use rustc_span::hygiene::{AstPass, MacroKind};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{Span, DUMMY_SP};
36 use std::cell::Cell;
37 use std::mem;
38
39 type Res = def::Res<NodeId>;
40
41 /// Binding produced by a `macro_rules` item.
42 /// Not modularized, can shadow previous `macro_rules` bindings, etc.
43 #[derive(Debug)]
44 pub(crate) struct MacroRulesBinding<'a> {
45 pub(crate) binding: NameBinding<'a>,
46 /// `macro_rules` scope into which the `macro_rules` item was planted.
47 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'a>,
48 pub(crate) ident: Ident,
49 }
50
51 /// The scope introduced by a `macro_rules!` macro.
52 /// This starts at the macro's definition and ends at the end of the macro's parent
53 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
54 /// Some macro invocations need to introduce `macro_rules` scopes too because they
55 /// can potentially expand into macro definitions.
56 #[derive(Copy, Clone, Debug)]
57 pub(crate) enum MacroRulesScope<'a> {
58 /// Empty "root" scope at the crate start containing no names.
59 Empty,
60 /// The scope introduced by a `macro_rules!` macro definition.
61 Binding(&'a MacroRulesBinding<'a>),
62 /// The scope introduced by a macro invocation that can potentially
63 /// create a `macro_rules!` macro definition.
64 Invocation(LocalExpnId),
65 }
66
67 /// `macro_rules!` scopes are always kept by reference and inside a cell.
68 /// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
69 /// in-place after `invoc_id` gets expanded.
70 /// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
71 /// which usually grow linearly with the number of macro invocations
72 /// in a module (including derives) and hurt performance.
73 pub(crate) type MacroRulesScopeRef<'a> = Interned<'a, Cell<MacroRulesScope<'a>>>;
74
75 /// Macro namespace is separated into two sub-namespaces, one for bang macros and
76 /// one for attribute-like macros (attributes, derives).
77 /// We ignore resolutions from one sub-namespace when searching names in scope for another.
sub_namespace_match( candidate: Option<MacroKind>, requirement: Option<MacroKind>, ) -> bool78 pub(crate) fn sub_namespace_match(
79 candidate: Option<MacroKind>,
80 requirement: Option<MacroKind>,
81 ) -> bool {
82 #[derive(PartialEq)]
83 enum SubNS {
84 Bang,
85 AttrLike,
86 }
87 let sub_ns = |kind| match kind {
88 MacroKind::Bang => SubNS::Bang,
89 MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
90 };
91 let candidate = candidate.map(sub_ns);
92 let requirement = requirement.map(sub_ns);
93 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
94 candidate.is_none() || requirement.is_none() || candidate == requirement
95 }
96
97 // We don't want to format a path using pretty-printing,
98 // `format!("{}", path)`, because that tries to insert
99 // line-breaks and is slow.
fast_print_path(path: &ast::Path) -> Symbol100 fn fast_print_path(path: &ast::Path) -> Symbol {
101 if path.segments.len() == 1 {
102 path.segments[0].ident.name
103 } else {
104 let mut path_str = String::with_capacity(64);
105 for (i, segment) in path.segments.iter().enumerate() {
106 if i != 0 {
107 path_str.push_str("::");
108 }
109 if segment.ident.name != kw::PathRoot {
110 path_str.push_str(segment.ident.as_str())
111 }
112 }
113 Symbol::intern(&path_str)
114 }
115 }
116
registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools117 pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
118 let mut registered_tools = RegisteredTools::default();
119 let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
120 for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
121 for nested_meta in attr.meta_item_list().unwrap_or_default() {
122 match nested_meta.ident() {
123 Some(ident) => {
124 if let Some(old_ident) = registered_tools.replace(ident) {
125 let msg = format!("{} `{}` was already registered", "tool", ident);
126 tcx.sess
127 .struct_span_err(ident.span, msg)
128 .span_label(old_ident.span, "already registered here")
129 .emit();
130 }
131 }
132 None => {
133 let msg = format!("`{}` only accepts identifiers", sym::register_tool);
134 let span = nested_meta.span();
135 tcx.sess
136 .struct_span_err(span, msg)
137 .span_label(span, "not an identifier")
138 .emit();
139 }
140 }
141 }
142 }
143 // We implicitly add `rustfmt` and `clippy` to known tools,
144 // but it's not an error to register them explicitly.
145 let predefined_tools = [sym::clippy, sym::rustfmt];
146 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
147 registered_tools
148 }
149
150 // Some feature gates for inner attributes are reported as lints for backward compatibility.
soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool151 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
152 match &path.segments[..] {
153 // `#![test]`
154 [seg] if seg.ident.name == sym::test => return true,
155 // `#![rustfmt::skip]` on out-of-line modules
156 [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
157 if let InvocationKind::Attr { item, .. } = &invoc.kind {
158 if let Annotatable::Item(item) = item {
159 if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
160 return true;
161 }
162 }
163 }
164 }
165 _ => {}
166 }
167 false
168 }
169
170 impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> {
next_node_id(&mut self) -> NodeId171 fn next_node_id(&mut self) -> NodeId {
172 self.next_node_id()
173 }
174
invocation_parent(&self, id: LocalExpnId) -> LocalDefId175 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
176 self.invocation_parents[&id].0
177 }
178
resolve_dollar_crates(&mut self)179 fn resolve_dollar_crates(&mut self) {
180 hygiene::update_dollar_crate_names(|ctxt| {
181 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
182 match self.resolve_crate_root(ident).kind {
183 ModuleKind::Def(.., name) if name != kw::Empty => name,
184 _ => kw::Crate,
185 }
186 });
187 }
188
visit_ast_fragment_with_placeholders( &mut self, expansion: LocalExpnId, fragment: &AstFragment, )189 fn visit_ast_fragment_with_placeholders(
190 &mut self,
191 expansion: LocalExpnId,
192 fragment: &AstFragment,
193 ) {
194 // Integrate the new AST fragment into all the definition and module structures.
195 // We are inside the `expansion` now, but other parent scope components are still the same.
196 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
197 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
198 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
199
200 parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
201 }
202
register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind)203 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
204 if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
205 self.tcx
206 .sess
207 .diagnostic()
208 .bug(format!("built-in macro `{}` was already registered", name));
209 }
210 }
211
212 // Create a new Expansion with a definition site of the provided module, or
213 // a fake empty `#[no_implicit_prelude]` module if no module is provided.
expansion_for_ast_pass( &mut self, call_site: Span, pass: AstPass, features: &[Symbol], parent_module_id: Option<NodeId>, ) -> LocalExpnId214 fn expansion_for_ast_pass(
215 &mut self,
216 call_site: Span,
217 pass: AstPass,
218 features: &[Symbol],
219 parent_module_id: Option<NodeId>,
220 ) -> LocalExpnId {
221 let parent_module =
222 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
223 let expn_id = LocalExpnId::fresh(
224 ExpnData::allow_unstable(
225 ExpnKind::AstPass(pass),
226 call_site,
227 self.tcx.sess.edition(),
228 features.into(),
229 None,
230 parent_module,
231 ),
232 self.create_stable_hashing_context(),
233 );
234
235 let parent_scope =
236 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
237 self.ast_transform_scopes.insert(expn_id, parent_scope);
238
239 expn_id
240 }
241
resolve_imports(&mut self)242 fn resolve_imports(&mut self) {
243 self.resolve_imports()
244 }
245
resolve_macro_invocation( &mut self, invoc: &Invocation, eager_expansion_root: LocalExpnId, force: bool, ) -> Result<Lrc<SyntaxExtension>, Indeterminate>246 fn resolve_macro_invocation(
247 &mut self,
248 invoc: &Invocation,
249 eager_expansion_root: LocalExpnId,
250 force: bool,
251 ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
252 let invoc_id = invoc.expansion_data.id;
253 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
254 Some(parent_scope) => *parent_scope,
255 None => {
256 // If there's no entry in the table, then we are resolving an eagerly expanded
257 // macro, which should inherit its parent scope from its eager expansion root -
258 // the macro that requested this eager expansion.
259 let parent_scope = *self
260 .invocation_parent_scopes
261 .get(&eager_expansion_root)
262 .expect("non-eager expansion without a parent scope");
263 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
264 parent_scope
265 }
266 };
267
268 let (path, kind, inner_attr, derives) = match invoc.kind {
269 InvocationKind::Attr { ref attr, ref derives, .. } => (
270 &attr.get_normal_item().path,
271 MacroKind::Attr,
272 attr.style == ast::AttrStyle::Inner,
273 self.arenas.alloc_ast_paths(derives),
274 ),
275 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
276 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
277 };
278
279 // Derives are not included when `invocations` are collected, so we have to add them here.
280 let parent_scope = &ParentScope { derives, ..parent_scope };
281 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
282 let node_id = invoc.expansion_data.lint_node_id;
283 let (ext, res) = self.smart_resolve_macro_path(
284 path,
285 kind,
286 supports_macro_expansion,
287 inner_attr,
288 parent_scope,
289 node_id,
290 force,
291 soft_custom_inner_attributes_gate(path, invoc),
292 )?;
293
294 let span = invoc.span();
295 let def_id = res.opt_def_id();
296 invoc_id.set_expn_data(
297 ext.expn_data(
298 parent_scope.expansion,
299 span,
300 fast_print_path(path),
301 def_id,
302 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
303 ),
304 self.create_stable_hashing_context(),
305 );
306
307 Ok(ext)
308 }
309
record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize)310 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
311 let did = self.local_def_id(id);
312 self.unused_macro_rules.remove(&(did, rule_i));
313 }
314
check_unused_macros(&mut self)315 fn check_unused_macros(&mut self) {
316 for (_, &(node_id, ident)) in self.unused_macros.iter() {
317 self.lint_buffer.buffer_lint(
318 UNUSED_MACROS,
319 node_id,
320 ident.span,
321 format!("unused macro definition: `{}`", ident.name),
322 );
323 }
324 for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
325 if self.unused_macros.contains_key(&def_id) {
326 // We already lint the entire macro as unused
327 continue;
328 }
329 let node_id = self.def_id_to_node_id[def_id];
330 self.lint_buffer.buffer_lint(
331 UNUSED_MACRO_RULES,
332 node_id,
333 rule_span,
334 format!(
335 "{} rule of macro `{}` is never used",
336 crate::diagnostics::ordinalize(arm_i + 1),
337 ident.name
338 ),
339 );
340 }
341 }
342
has_derive_copy(&self, expn_id: LocalExpnId) -> bool343 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
344 self.containers_deriving_copy.contains(&expn_id)
345 }
346
resolve_derives( &mut self, expn_id: LocalExpnId, force: bool, derive_paths: &dyn Fn() -> DeriveResolutions, ) -> Result<(), Indeterminate>347 fn resolve_derives(
348 &mut self,
349 expn_id: LocalExpnId,
350 force: bool,
351 derive_paths: &dyn Fn() -> DeriveResolutions,
352 ) -> Result<(), Indeterminate> {
353 // Block expansion of the container until we resolve all derives in it.
354 // This is required for two reasons:
355 // - Derive helper attributes are in scope for the item to which the `#[derive]`
356 // is applied, so they have to be produced by the container's expansion rather
357 // than by individual derives.
358 // - Derives in the container need to know whether one of them is a built-in `Copy`.
359 // Temporarily take the data to avoid borrow checker conflicts.
360 let mut derive_data = mem::take(&mut self.derive_data);
361 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
362 resolutions: derive_paths(),
363 helper_attrs: Vec::new(),
364 has_derive_copy: false,
365 });
366 let parent_scope = self.invocation_parent_scopes[&expn_id];
367 for (i, (path, _, opt_ext, _)) in entry.resolutions.iter_mut().enumerate() {
368 if opt_ext.is_none() {
369 *opt_ext = Some(
370 match self.resolve_macro_path(
371 &path,
372 Some(MacroKind::Derive),
373 &parent_scope,
374 true,
375 force,
376 ) {
377 Ok((Some(ext), _)) => {
378 if !ext.helper_attrs.is_empty() {
379 let last_seg = path.segments.last().unwrap();
380 let span = last_seg.ident.span.normalize_to_macros_2_0();
381 entry.helper_attrs.extend(
382 ext.helper_attrs
383 .iter()
384 .map(|name| (i, Ident::new(*name, span))),
385 );
386 }
387 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
388 ext
389 }
390 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
391 Err(Determinacy::Undetermined) => {
392 assert!(self.derive_data.is_empty());
393 self.derive_data = derive_data;
394 return Err(Indeterminate);
395 }
396 },
397 );
398 }
399 }
400 // Sort helpers in a stable way independent from the derive resolution order.
401 entry.helper_attrs.sort_by_key(|(i, _)| *i);
402 self.helper_attrs
403 .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
404 // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
405 // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
406 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
407 self.containers_deriving_copy.insert(expn_id);
408 }
409 assert!(self.derive_data.is_empty());
410 self.derive_data = derive_data;
411 Ok(())
412 }
413
take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>414 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
415 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
416 }
417
418 // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
419 // Returns true if the path can certainly be resolved in one of three namespaces,
420 // returns false if the path certainly cannot be resolved in any of the three namespaces.
421 // Returns `Indeterminate` if we cannot give a certain answer yet.
cfg_accessible( &mut self, expn_id: LocalExpnId, path: &ast::Path, ) -> Result<bool, Indeterminate>422 fn cfg_accessible(
423 &mut self,
424 expn_id: LocalExpnId,
425 path: &ast::Path,
426 ) -> Result<bool, Indeterminate> {
427 let span = path.span;
428 let path = &Segment::from_path(path);
429 let parent_scope = self.invocation_parent_scopes[&expn_id];
430
431 let mut indeterminate = false;
432 for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
433 match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
434 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
435 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
436 return Ok(true);
437 }
438 PathResult::NonModule(..) |
439 // HACK(Urgau): This shouldn't be necessary
440 PathResult::Failed { is_error_from_last_segment: false, .. } => {
441 self.tcx.sess
442 .emit_err(errors::CfgAccessibleUnsure { span });
443
444 // If we get a partially resolved NonModule in one namespace, we should get the
445 // same result in any other namespaces, so we can return early.
446 return Ok(false);
447 }
448 PathResult::Indeterminate => indeterminate = true,
449 // We can only be sure that a path doesn't exist after having tested all the
450 // possibilities, only at that time we can return false.
451 PathResult::Failed { .. } => {}
452 PathResult::Module(_) => panic!("unexpected path resolution"),
453 }
454 }
455
456 if indeterminate {
457 return Err(Indeterminate);
458 }
459
460 Ok(false)
461 }
462
get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span463 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
464 self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.tcx.sess)
465 }
466
declare_proc_macro(&mut self, id: NodeId)467 fn declare_proc_macro(&mut self, id: NodeId) {
468 self.proc_macros.push(id)
469 }
470
append_stripped_cfg_item(&mut self, parent_node: NodeId, name: Ident, cfg: ast::MetaItem)471 fn append_stripped_cfg_item(&mut self, parent_node: NodeId, name: Ident, cfg: ast::MetaItem) {
472 self.stripped_cfg_items.push(StrippedCfgItem { parent_module: parent_node, name, cfg });
473 }
474
registered_tools(&self) -> &RegisteredTools475 fn registered_tools(&self) -> &RegisteredTools {
476 &self.registered_tools
477 }
478 }
479
480 impl<'a, 'tcx> Resolver<'a, 'tcx> {
481 /// Resolve macro path with error reporting and recovery.
482 /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
483 /// for better error recovery.
smart_resolve_macro_path( &mut self, path: &ast::Path, kind: MacroKind, supports_macro_expansion: SupportsMacroExpansion, inner_attr: bool, parent_scope: &ParentScope<'a>, node_id: NodeId, force: bool, soft_custom_inner_attributes_gate: bool, ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate>484 fn smart_resolve_macro_path(
485 &mut self,
486 path: &ast::Path,
487 kind: MacroKind,
488 supports_macro_expansion: SupportsMacroExpansion,
489 inner_attr: bool,
490 parent_scope: &ParentScope<'a>,
491 node_id: NodeId,
492 force: bool,
493 soft_custom_inner_attributes_gate: bool,
494 ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
495 let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
496 {
497 Ok((Some(ext), res)) => (ext, res),
498 Ok((None, res)) => (self.dummy_ext(kind), res),
499 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
500 Err(Determinacy::Undetermined) => return Err(Indeterminate),
501 };
502
503 // Report errors for the resolved macro.
504 for segment in &path.segments {
505 if let Some(args) = &segment.args {
506 self.tcx.sess.span_err(args.span(), "generic arguments in macro path");
507 }
508 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
509 self.tcx.sess.span_err(
510 segment.ident.span,
511 "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
512 );
513 }
514 }
515
516 match res {
517 Res::Def(DefKind::Macro(_), def_id) => {
518 if let Some(def_id) = def_id.as_local() {
519 self.unused_macros.remove(&def_id);
520 if self.proc_macro_stubs.contains(&def_id) {
521 self.tcx.sess.emit_err(errors::ProcMacroSameCrate {
522 span: path.span,
523 is_test: self.tcx.sess.is_test_crate(),
524 });
525 }
526 }
527 }
528 Res::NonMacroAttr(..) | Res::Err => {}
529 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
530 };
531
532 self.check_stability_and_deprecation(&ext, path, node_id);
533
534 let unexpected_res = if ext.macro_kind() != kind {
535 Some((kind.article(), kind.descr_expected()))
536 } else if matches!(res, Res::Def(..)) {
537 match supports_macro_expansion {
538 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
539 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
540 if inner_attr && !supports_inner_attrs {
541 Some(("a", "non-macro inner attribute"))
542 } else {
543 None
544 }
545 }
546 }
547 } else {
548 None
549 };
550 if let Some((article, expected)) = unexpected_res {
551 let path_str = pprust::path_to_string(path);
552
553 let mut err = MacroExpectedFound {
554 span: path.span,
555 expected,
556 found: res.descr(),
557 macro_path: &path_str,
558 ..Default::default() // Subdiagnostics default to None
559 };
560
561 // Suggest moving the macro out of the derive() if the macro isn't Derive
562 if !path.span.from_expansion()
563 && kind == MacroKind::Derive
564 && ext.macro_kind() != MacroKind::Derive
565 {
566 err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
567 err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
568 }
569
570 let mut err = self.tcx.sess.create_err(err);
571 err.span_label(path.span, format!("not {} {}", article, expected));
572
573 err.emit();
574
575 return Ok((self.dummy_ext(kind), Res::Err));
576 }
577
578 // We are trying to avoid reporting this error if other related errors were reported.
579 if res != Res::Err
580 && inner_attr
581 && !self.tcx.sess.features_untracked().custom_inner_attributes
582 {
583 let msg = match res {
584 Res::Def(..) => "inner macro attributes are unstable",
585 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
586 _ => unreachable!(),
587 };
588 if soft_custom_inner_attributes_gate {
589 self.tcx.sess.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
590 } else {
591 feature_err(
592 &self.tcx.sess.parse_sess,
593 sym::custom_inner_attributes,
594 path.span,
595 msg,
596 )
597 .emit();
598 }
599 }
600
601 Ok((ext, res))
602 }
603
resolve_macro_path( &mut self, path: &ast::Path, kind: Option<MacroKind>, parent_scope: &ParentScope<'a>, trace: bool, force: bool, ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy>604 pub(crate) fn resolve_macro_path(
605 &mut self,
606 path: &ast::Path,
607 kind: Option<MacroKind>,
608 parent_scope: &ParentScope<'a>,
609 trace: bool,
610 force: bool,
611 ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
612 let path_span = path.span;
613 let mut path = Segment::from_path(path);
614
615 // Possibly apply the macro helper hack
616 if kind == Some(MacroKind::Bang)
617 && path.len() == 1
618 && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
619 {
620 let root = Ident::new(kw::DollarCrate, path[0].ident.span);
621 path.insert(0, Segment::from_ident(root));
622 }
623
624 let res = if path.len() > 1 {
625 let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
626 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
627 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
628 PathResult::NonModule(..)
629 | PathResult::Indeterminate
630 | PathResult::Failed { .. } => Err(Determinacy::Determined),
631 PathResult::Module(..) => unreachable!(),
632 };
633
634 if trace {
635 let kind = kind.expect("macro kind must be specified if tracing is enabled");
636 self.multi_segment_macro_resolutions.push((
637 path,
638 path_span,
639 kind,
640 *parent_scope,
641 res.ok(),
642 ));
643 }
644
645 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
646 res
647 } else {
648 let scope_set = kind.map_or(ScopeSet::All(MacroNS), ScopeSet::Macro);
649 let binding = self.early_resolve_ident_in_lexical_scope(
650 path[0].ident,
651 scope_set,
652 parent_scope,
653 None,
654 force,
655 None,
656 );
657 if let Err(Determinacy::Undetermined) = binding {
658 return Err(Determinacy::Undetermined);
659 }
660
661 if trace {
662 let kind = kind.expect("macro kind must be specified if tracing is enabled");
663 self.single_segment_macro_resolutions.push((
664 path[0].ident,
665 kind,
666 *parent_scope,
667 binding.ok(),
668 ));
669 }
670
671 let res = binding.map(|binding| binding.res());
672 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
673 res
674 };
675
676 res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
677 }
678
finalize_macro_resolutions(&mut self, krate: &Crate)679 pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
680 let check_consistency = |this: &mut Self,
681 path: &[Segment],
682 span,
683 kind: MacroKind,
684 initial_res: Option<Res>,
685 res: Res| {
686 if let Some(initial_res) = initial_res {
687 if res != initial_res {
688 // Make sure compilation does not succeed if preferred macro resolution
689 // has changed after the macro had been expanded. In theory all such
690 // situations should be reported as errors, so this is a bug.
691 this.tcx.sess.delay_span_bug(span, "inconsistent resolution for a macro");
692 }
693 } else {
694 // It's possible that the macro was unresolved (indeterminate) and silently
695 // expanded into a dummy fragment for recovery during expansion.
696 // Now, post-expansion, the resolution may succeed, but we can't change the
697 // past and need to report an error.
698 // However, non-speculative `resolve_path` can successfully return private items
699 // even if speculative `resolve_path` returned nothing previously, so we skip this
700 // less informative error if the privacy error is reported elsewhere.
701 if this.privacy_errors.is_empty() {
702 let msg = format!(
703 "cannot determine resolution for the {} `{}`",
704 kind.descr(),
705 Segment::names_to_string(path)
706 );
707 let msg_note = "import resolution is stuck, try simplifying macro imports";
708 this.tcx.sess.struct_span_err(span, msg).note(msg_note).emit();
709 }
710 }
711 };
712
713 let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
714 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
715 // FIXME: Path resolution will ICE if segment IDs present.
716 for seg in &mut path {
717 seg.id = None;
718 }
719 match self.resolve_path(
720 &path,
721 Some(MacroNS),
722 &parent_scope,
723 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
724 None,
725 ) {
726 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
727 check_consistency(self, &path, path_span, kind, initial_res, res)
728 }
729 path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
730 let mut suggestion = None;
731 let (span, label, module) = if let PathResult::Failed { span, label, module, .. } = path_res {
732 // try to suggest if it's not a macro, maybe a function
733 if let PathResult::NonModule(partial_res) = self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope)
734 && partial_res.unresolved_segments() == 0 {
735 let sm = self.tcx.sess.source_map();
736 let exclamation_span = sm.next_point(span);
737 suggestion = Some((
738 vec![(exclamation_span, "".to_string())],
739 format!("{} is not a macro, but a {}, try to remove `!`", Segment::names_to_string(&path), partial_res.base_res().descr()),
740 Applicability::MaybeIncorrect
741 ));
742 }
743 (span, label, module)
744 } else {
745 (
746 path_span,
747 format!(
748 "partially resolved path in {} {}",
749 kind.article(),
750 kind.descr()
751 ),
752 None,
753 )
754 };
755 self.report_error(
756 span,
757 ResolutionError::FailedToResolve { last_segment: path.last().map(|segment| segment.ident.name), label, suggestion, module },
758 );
759 }
760 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
761 }
762 }
763
764 let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
765 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
766 match self.early_resolve_ident_in_lexical_scope(
767 ident,
768 ScopeSet::Macro(kind),
769 &parent_scope,
770 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
771 true,
772 None,
773 ) {
774 Ok(binding) => {
775 let initial_res = initial_binding.map(|initial_binding| {
776 self.record_use(ident, initial_binding, false);
777 initial_binding.res()
778 });
779 let res = binding.res();
780 let seg = Segment::from_ident(ident);
781 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
782 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
783 let node_id = self
784 .invocation_parents
785 .get(&parent_scope.expansion)
786 .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
787 self.lint_buffer.buffer_lint_with_diagnostic(
788 LEGACY_DERIVE_HELPERS,
789 node_id,
790 ident.span,
791 "derive helper attribute is used before it is introduced",
792 BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
793 );
794 }
795 }
796 Err(..) => {
797 let expected = kind.descr_expected();
798
799 let mut err = self.tcx.sess.create_err(CannotFindIdentInThisScope {
800 span: ident.span,
801 expected,
802 ident,
803 });
804
805 self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate);
806 err.emit();
807 }
808 }
809 }
810
811 let builtin_attrs = mem::take(&mut self.builtin_attrs);
812 for (ident, parent_scope) in builtin_attrs {
813 let _ = self.early_resolve_ident_in_lexical_scope(
814 ident,
815 ScopeSet::Macro(MacroKind::Attr),
816 &parent_scope,
817 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
818 true,
819 None,
820 );
821 }
822 }
823
check_stability_and_deprecation( &mut self, ext: &SyntaxExtension, path: &ast::Path, node_id: NodeId, )824 fn check_stability_and_deprecation(
825 &mut self,
826 ext: &SyntaxExtension,
827 path: &ast::Path,
828 node_id: NodeId,
829 ) {
830 let span = path.span;
831 if let Some(stability) = &ext.stability {
832 if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level
833 {
834 let feature = stability.feature;
835
836 let is_allowed = |feature| {
837 self.active_features.contains(&feature) || span.allows_unstable(feature)
838 };
839 let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
840 if !is_allowed(feature) && !allowed_by_implication {
841 let lint_buffer = &mut self.lint_buffer;
842 let soft_handler =
843 |lint, span, msg: String| lint_buffer.buffer_lint(lint, node_id, span, msg);
844 stability::report_unstable(
845 self.tcx.sess,
846 feature,
847 reason.to_opt_reason(),
848 issue,
849 None,
850 is_soft,
851 span,
852 soft_handler,
853 );
854 }
855 }
856 }
857 if let Some(depr) = &ext.deprecation {
858 let path = pprust::path_to_string(&path);
859 let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
860 stability::early_report_deprecation(
861 &mut self.lint_buffer,
862 message,
863 depr.suggestion,
864 lint,
865 span,
866 node_id,
867 );
868 }
869 }
870
prohibit_imported_non_macro_attrs( &self, binding: Option<NameBinding<'a>>, res: Option<Res>, span: Span, )871 fn prohibit_imported_non_macro_attrs(
872 &self,
873 binding: Option<NameBinding<'a>>,
874 res: Option<Res>,
875 span: Span,
876 ) {
877 if let Some(Res::NonMacroAttr(kind)) = res {
878 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
879 let msg =
880 format!("cannot use {} {} through an import", kind.article(), kind.descr());
881 let mut err = self.tcx.sess.struct_span_err(span, msg);
882 if let Some(binding) = binding {
883 err.span_note(binding.span, format!("the {} imported here", kind.descr()));
884 }
885 err.emit();
886 }
887 }
888 }
889
check_reserved_macro_name(&mut self, ident: Ident, res: Res)890 pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
891 // Reserve some names that are not quite covered by the general check
892 // performed on `Resolver::builtin_attrs`.
893 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
894 let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
895 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
896 self.tcx.sess.span_err(
897 ident.span,
898 format!("name `{}` is reserved in attribute namespace", ident),
899 );
900 }
901 }
902 }
903
904 /// Compile the macro into a `SyntaxExtension` and its rule spans.
905 ///
906 /// Possibly replace its expander to a pre-defined one for built-in macros.
compile_macro( &mut self, item: &ast::Item, edition: Edition, ) -> (SyntaxExtension, Vec<(usize, Span)>)907 pub(crate) fn compile_macro(
908 &mut self,
909 item: &ast::Item,
910 edition: Edition,
911 ) -> (SyntaxExtension, Vec<(usize, Span)>) {
912 let (mut result, mut rule_spans) = compile_declarative_macro(self.tcx.sess, item, edition);
913
914 if let Some(builtin_name) = result.builtin_name {
915 // The macro was marked with `#[rustc_builtin_macro]`.
916 if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
917 // The macro is a built-in, replace its expander function
918 // while still taking everything else from the source code.
919 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
920 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
921 BuiltinMacroState::NotYetSeen(ext) => {
922 result.kind = ext;
923 rule_spans = Vec::new();
924 if item.id != ast::DUMMY_NODE_ID {
925 self.builtin_macro_kinds
926 .insert(self.local_def_id(item.id), result.macro_kind());
927 }
928 }
929 BuiltinMacroState::AlreadySeen(span) => {
930 struct_span_err!(
931 self.tcx.sess,
932 item.span,
933 E0773,
934 "attempted to define built-in macro more than once"
935 )
936 .span_note(span, "previously defined here")
937 .emit();
938 }
939 }
940 } else {
941 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
942 self.tcx.sess.span_err(item.span, msg);
943 }
944 }
945
946 (result, rule_spans)
947 }
948 }
949