2 use crate::config::StripUnconfigured;
3 use crate::hygiene::SyntaxContext;
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod};
6 use crate::placeholders::{placeholder, PlaceholderExpander};
9 use rustc_ast::mut_visit::*;
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Delimiter};
12 use rustc_ast::tokenstream::TokenStream;
13 use rustc_ast::visit::{self, AssocCtxt, Visitor};
14 use rustc_ast::{AssocItemKind, AstLike, AstLikeWrapper, AttrStyle, ExprKind, ForeignItemKind};
15 use rustc_ast::{Inline, ItemKind, MacArgs, MacStmtStyle, MetaItemKind, ModKind};
16 use rustc_ast::{NestedMetaItem, NodeId, PatKind, StmtKind, TyKind};
17 use rustc_ast_pretty::pprust;
18 use rustc_data_structures::map_in_place::MapInPlace;
19 use rustc_data_structures::sync::Lrc;
20 use rustc_errors::{Applicability, PResult};
21 use rustc_feature::Features;
22 use rustc_parse::parser::{
23 AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma,
25 use rustc_parse::validate_attr;
26 use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS};
27 use rustc_session::lint::BuiltinLintDiagnostics;
28 use rustc_session::parse::{feature_err, ParseSess};
29 use rustc_session::Limit;
30 use rustc_span::symbol::{sym, Ident};
31 use rustc_span::{FileName, LocalExpnId, Span};
33 use smallvec::SmallVec;
35 use std::path::PathBuf;
39 macro_rules! ast_fragments {
41 $($Kind:ident($AstTy:ty) {
43 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
44 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*);)?
48 /// A fragment of AST that can be produced by a single macro expansion.
49 /// Can also serve as an input and intermediate result for macro expansion operations.
50 pub enum AstFragment {
51 OptExpr(Option<P<ast::Expr>>),
55 /// "Discriminant" of an AST fragment.
56 #[derive(Copy, Clone, PartialEq, Eq)]
57 pub enum AstFragmentKind {
62 impl AstFragmentKind {
63 pub fn name(self) -> &'static str {
65 AstFragmentKind::OptExpr => "expression",
66 $(AstFragmentKind::$Kind => $kind_name,)*
70 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
72 AstFragmentKind::OptExpr =>
73 result.make_expr().map(Some).map(AstFragment::OptExpr),
74 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
80 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
81 if placeholders.is_empty() {
85 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
86 ${ignore(flat_map_ast_elt)}
87 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
89 _ => panic!("unexpected AST fragment kind")
93 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
95 AstFragment::OptExpr(expr) => expr,
96 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
100 $(pub fn $make_ast(self) -> $AstTy {
102 AstFragment::$Kind(ast) => ast,
103 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
107 fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
108 T::fragment_to_output(self)
111 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
113 AstFragment::OptExpr(opt_expr) => {
114 visit_clobber(opt_expr, |opt_expr| {
115 if let Some(expr) = opt_expr {
116 vis.filter_map_expr(expr)
122 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
123 $($(AstFragment::$Kind(ast) =>
124 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
128 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
130 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
131 AstFragment::OptExpr(None) => {}
132 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
133 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
134 visitor.$visit_ast_elt(ast_elt, $($args)*);
140 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
141 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
143 Some(self.make(AstFragmentKind::$Kind).$make_ast())
150 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
151 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
152 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
153 Stmts(SmallVec<[ast::Stmt; 1]>) {
154 "statement"; many fn flat_map_stmt; fn visit_stmt(); fn make_stmts;
156 Items(SmallVec<[P<ast::Item>; 1]>) {
157 "item"; many fn flat_map_item; fn visit_item(); fn make_items;
159 TraitItems(SmallVec<[P<ast::AssocItem>; 1]>) {
161 many fn flat_map_trait_item;
162 fn visit_assoc_item(AssocCtxt::Trait);
165 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
167 many fn flat_map_impl_item;
168 fn visit_assoc_item(AssocCtxt::Impl);
171 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
173 many fn flat_map_foreign_item;
174 fn visit_foreign_item();
175 fn make_foreign_items;
177 Arms(SmallVec<[ast::Arm; 1]>) {
178 "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms;
180 ExprFields(SmallVec<[ast::ExprField; 1]>) {
181 "field expression"; many fn flat_map_expr_field; fn visit_expr_field(); fn make_expr_fields;
183 PatFields(SmallVec<[ast::PatField; 1]>) {
185 many fn flat_map_pat_field;
186 fn visit_pat_field();
189 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
191 many fn flat_map_generic_param;
192 fn visit_generic_param();
193 fn make_generic_params;
195 Params(SmallVec<[ast::Param; 1]>) {
196 "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params;
198 FieldDefs(SmallVec<[ast::FieldDef; 1]>) {
200 many fn flat_map_field_def;
201 fn visit_field_def();
204 Variants(SmallVec<[ast::Variant; 1]>) {
205 "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants;
207 Crate(ast::Crate) { "crate"; one fn visit_crate; fn visit_crate; fn make_crate; }
210 pub enum SupportsMacroExpansion {
212 Yes { supports_inner_attrs: bool },
215 impl AstFragmentKind {
216 crate fn dummy(self, span: Span) -> AstFragment {
217 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
220 pub fn supports_macro_expansion(self) -> SupportsMacroExpansion {
222 AstFragmentKind::OptExpr
223 | AstFragmentKind::Expr
224 | AstFragmentKind::Stmts
225 | AstFragmentKind::Ty
226 | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false },
227 AstFragmentKind::Items
228 | AstFragmentKind::TraitItems
229 | AstFragmentKind::ImplItems
230 | AstFragmentKind::ForeignItems
231 | AstFragmentKind::Crate => SupportsMacroExpansion::Yes { supports_inner_attrs: true },
232 AstFragmentKind::Arms
233 | AstFragmentKind::ExprFields
234 | AstFragmentKind::PatFields
235 | AstFragmentKind::GenericParams
236 | AstFragmentKind::Params
237 | AstFragmentKind::FieldDefs
238 | AstFragmentKind::Variants => SupportsMacroExpansion::No,
242 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
246 let mut items = items.into_iter();
248 AstFragmentKind::Arms => {
249 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
251 AstFragmentKind::ExprFields => {
252 AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect())
254 AstFragmentKind::PatFields => {
255 AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect())
257 AstFragmentKind::GenericParams => {
258 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
260 AstFragmentKind::Params => {
261 AstFragment::Params(items.map(Annotatable::expect_param).collect())
263 AstFragmentKind::FieldDefs => {
264 AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect())
266 AstFragmentKind::Variants => {
267 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
269 AstFragmentKind::Items => {
270 AstFragment::Items(items.map(Annotatable::expect_item).collect())
272 AstFragmentKind::ImplItems => {
273 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
275 AstFragmentKind::TraitItems => {
276 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
278 AstFragmentKind::ForeignItems => {
279 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
281 AstFragmentKind::Stmts => {
282 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
284 AstFragmentKind::Expr => AstFragment::Expr(
285 items.next().expect("expected exactly one expression").expect_expr(),
287 AstFragmentKind::OptExpr => {
288 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
290 AstFragmentKind::Crate => {
291 AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate())
293 AstFragmentKind::Pat | AstFragmentKind::Ty => {
294 panic!("patterns and types aren't annotatable")
300 pub struct Invocation {
301 pub kind: InvocationKind,
302 pub fragment_kind: AstFragmentKind,
303 pub expansion_data: ExpansionData,
306 pub enum InvocationKind {
312 attr: ast::Attribute,
313 // Re-insertion position for inert attributes.
316 // Required for resolving derive helper attributes.
317 derives: Vec<ast::Path>,
325 impl InvocationKind {
326 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
327 // HACK: For unnamed fields placeholders should have the same visibility as the actual
328 // fields because for tuple structs/variants resolve determines visibilities of their
329 // constructor using these field visibilities before attributes on them are are expanded.
330 // The assumption is that the attribute expansion cannot change field visibilities,
331 // and it holds because only inert attributes are supported in this position.
333 InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
334 | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
335 if field.ident.is_none() =>
337 Some(field.vis.clone())
345 pub fn span(&self) -> Span {
347 InvocationKind::Bang { span, .. } => *span,
348 InvocationKind::Attr { attr, .. } => attr.span,
349 InvocationKind::Derive { path, .. } => path.span,
354 pub struct MacroExpander<'a, 'b> {
355 pub cx: &'a mut ExtCtxt<'b>,
356 monotonic: bool, // cf. `cx.monotonic_expander()`
359 impl<'a, 'b> MacroExpander<'a, 'b> {
360 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
361 MacroExpander { cx, monotonic }
364 pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate {
365 let file_path = match self.cx.source_map().span_to_filename(krate.spans.inner_span) {
366 FileName::Real(name) => name
368 .expect("attempting to resolve a file path in an external file"),
369 other => PathBuf::from(other.prefer_local().to_string()),
371 let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
372 self.cx.root_path = dir_path.clone();
373 self.cx.current_expansion.module = Rc::new(ModuleData {
374 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
375 file_path_stack: vec![file_path],
378 let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate();
379 assert_eq!(krate.id, ast::CRATE_NODE_ID);
380 self.cx.trace_macros_diag();
384 // Recursively expand all macro invocations in this AST fragment.
385 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
386 let orig_expansion_data = self.cx.current_expansion.clone();
387 let orig_force_mode = self.cx.force_mode;
389 // Collect all macro invocations and replace them with placeholders.
390 let (mut fragment_with_placeholders, mut invocations) =
391 self.collect_invocations(input_fragment, &[]);
393 // Optimization: if we resolve all imports now,
394 // we'll be able to immediately resolve most of imported macros.
395 self.resolve_imports();
397 // Resolve paths in all invocations and produce output expanded fragments for them, but
398 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
399 // The output fragments also go through expansion recursively until no invocations are left.
400 // Unresolved macros produce dummy outputs as a recovery measure.
401 invocations.reverse();
402 let mut expanded_fragments = Vec::new();
403 let mut undetermined_invocations = Vec::new();
404 let (mut progress, mut force) = (false, !self.monotonic);
406 let Some((invoc, ext)) = invocations.pop() else {
407 self.resolve_imports();
408 if undetermined_invocations.is_empty() {
411 invocations = mem::take(&mut undetermined_invocations);
412 force = !mem::replace(&mut progress, false);
413 if force && self.monotonic {
414 self.cx.sess.delay_span_bug(
415 invocations.last().unwrap().0.span(),
416 "expansion entered force mode without producing any errors",
422 let ext = match ext {
425 let eager_expansion_root = if self.monotonic {
426 invoc.expansion_data.id
428 orig_expansion_data.id
430 match self.cx.resolver.resolve_macro_invocation(
432 eager_expansion_root,
436 Err(Indeterminate) => {
437 // Cannot resolve, will retry this invocation later.
438 undetermined_invocations.push((invoc, None));
445 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
446 let depth = depth - orig_expansion_data.depth;
447 self.cx.current_expansion = invoc.expansion_data.clone();
448 self.cx.force_mode = force;
450 let fragment_kind = invoc.fragment_kind;
451 let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) {
452 ExpandResult::Ready(fragment) => {
453 let mut derive_invocations = Vec::new();
454 let derive_placeholders = self
457 .take_derive_resolutions(expn_id)
459 derive_invocations.reserve(derives.len());
462 .map(|(path, item, _exts)| {
463 // FIXME: Consider using the derive resolutions (`_exts`)
464 // instead of enqueuing the derives to be resolved again later.
465 let expn_id = LocalExpnId::fresh_empty();
466 derive_invocations.push((
468 kind: InvocationKind::Derive { path, item },
470 expansion_data: ExpansionData {
472 ..self.cx.current_expansion.clone()
477 NodeId::placeholder_from_expn_id(expn_id)
481 .unwrap_or_default();
483 let (fragment, collected_invocations) =
484 self.collect_invocations(fragment, &derive_placeholders);
485 // We choose to expand any derive invocations associated with this macro invocation
486 // *before* any macro invocations collected from the output fragment
487 derive_invocations.extend(collected_invocations);
488 (fragment, derive_invocations)
490 ExpandResult::Retry(invoc) => {
494 "expansion entered force mode but is still stuck",
497 // Cannot expand, will retry this invocation later.
498 undetermined_invocations.push((invoc, Some(ext)));
505 if expanded_fragments.len() < depth {
506 expanded_fragments.push(Vec::new());
508 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
509 invocations.extend(new_invocations.into_iter().rev());
512 self.cx.current_expansion = orig_expansion_data;
513 self.cx.force_mode = orig_force_mode;
515 // Finally incorporate all the expanded macros into the input AST fragment.
516 let mut placeholder_expander = PlaceholderExpander::default();
517 while let Some(expanded_fragments) = expanded_fragments.pop() {
518 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
520 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
523 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
524 fragment_with_placeholders
527 fn resolve_imports(&mut self) {
529 self.cx.resolver.resolve_imports();
533 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
534 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
535 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
536 /// prepares data for resolving paths of macro invocations.
537 fn collect_invocations(
539 mut fragment: AstFragment,
540 extra_placeholders: &[NodeId],
541 ) -> (AstFragment, Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>) {
542 // Resolve `$crate`s in the fragment for pretty-printing.
543 self.cx.resolver.resolve_dollar_crates();
545 let mut invocations = {
546 let mut collector = InvocationCollector {
547 // Non-derive macro invocations cannot see the results of cfg expansion - they
548 // will either be removed along with the item, or invoked before the cfg/cfg_attr
549 // attribute is expanded. Therefore, we don't need to configure the tokens
550 // Derive macros *can* see the results of cfg-expansion - they are handled
551 // specially in `fully_expand_fragment`
553 invocations: Vec::new(),
554 monotonic: self.monotonic,
556 fragment.mut_visit_with(&mut collector);
557 fragment.add_placeholders(extra_placeholders);
558 collector.invocations
564 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
566 if self.cx.sess.opts.debugging_opts.incremental_relative_spans {
567 for (invoc, _) in invocations.iter_mut() {
568 let expn_id = invoc.expansion_data.id;
569 let parent_def = self.cx.resolver.invocation_parent(expn_id);
570 let span = match &mut invoc.kind {
571 InvocationKind::Bang { ref mut span, .. } => span,
572 InvocationKind::Attr { attr, .. } => &mut attr.span,
573 InvocationKind::Derive { path, .. } => &mut path.span,
575 *span = span.with_parent(Some(parent_def));
580 (fragment, invocations)
583 fn error_recursion_limit_reached(&mut self) {
584 let expn_data = self.cx.current_expansion.id.expn_data();
585 let suggested_limit = match self.cx.ecfg.recursion_limit {
586 Limit(0) => Limit(2),
592 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
595 "consider increasing the recursion limit by adding a \
596 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
597 suggested_limit, self.cx.ecfg.crate_name,
600 self.cx.trace_macros_diag();
603 /// A macro's expansion does not fit in this fragment kind.
604 /// For example, a non-type macro in a type position.
605 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
607 "non-{kind} macro in {kind} position: {path}",
609 path = pprust::path_to_string(&mac.path),
611 self.cx.span_err(span, &msg);
612 self.cx.trace_macros_diag();
618 ext: &SyntaxExtensionKind,
619 ) -> ExpandResult<AstFragment, Invocation> {
620 let recursion_limit =
621 self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
622 if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
623 if self.cx.reduced_recursion_limit.is_none() {
624 self.error_recursion_limit_reached();
627 // Reduce the recursion limit by half each time it triggers.
628 self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
630 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
633 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
634 ExpandResult::Ready(match invoc.kind {
635 InvocationKind::Bang { mac, .. } => match ext {
636 SyntaxExtensionKind::Bang(expander) => {
637 let Ok(tok_result) = expander.expand(self.cx, span, mac.args.inner_tokens()) else {
638 return ExpandResult::Ready(fragment_kind.dummy(span));
640 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
642 SyntaxExtensionKind::LegacyBang(expander) => {
643 let prev = self.cx.current_expansion.prior_type_ascription;
644 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
645 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
646 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
649 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
650 fragment_kind.dummy(span)
652 self.cx.current_expansion.prior_type_ascription = prev;
657 InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
658 SyntaxExtensionKind::Attr(expander) => {
659 self.gate_proc_macro_input(&item);
660 self.gate_proc_macro_attr_item(span, &item);
661 let tokens = match &item {
662 // FIXME: Collect tokens and use them instead of generating
663 // fake ones. These are unstable, so it needs to be
664 // fixed prior to stabilization
665 // Fake tokens when we are invoking an inner attribute, and
666 // we are invoking it on an out-of-line module or crate.
667 Annotatable::Crate(krate) => rustc_parse::fake_token_stream_for_crate(
668 &self.cx.sess.parse_sess,
671 Annotatable::Item(item_inner)
672 if matches!(attr.style, AttrStyle::Inner)
677 ModKind::Unloaded | ModKind::Loaded(_, Inline::No, _),
681 rustc_parse::fake_token_stream(
682 &self.cx.sess.parse_sess,
683 &item.into_nonterminal(),
686 _ => item.into_tokens(&self.cx.sess.parse_sess),
688 let attr_item = attr.unwrap_normal_item();
689 if let MacArgs::Eq(..) = attr_item.args {
690 self.cx.span_err(span, "key-value macro attributes are not supported");
692 let inner_tokens = attr_item.args.inner_tokens();
693 let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) else {
694 return ExpandResult::Ready(fragment_kind.dummy(span));
696 self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
698 SyntaxExtensionKind::LegacyAttr(expander) => {
699 match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) {
701 let items = match expander.expand(self.cx, span, &meta, item) {
702 ExpandResult::Ready(items) => items,
703 ExpandResult::Retry(item) => {
704 // Reassemble the original invocation for retrying.
705 return ExpandResult::Retry(Invocation {
706 kind: InvocationKind::Attr { attr, pos, item, derives },
711 if fragment_kind == AstFragmentKind::Expr && items.is_empty() {
713 "removing an expression is not supported in this position";
714 self.cx.span_err(span, msg);
715 fragment_kind.dummy(span)
717 fragment_kind.expect_from_annotatables(items)
722 fragment_kind.dummy(span)
726 SyntaxExtensionKind::NonMacroAttr => {
727 self.cx.expanded_inert_attrs.mark(&attr);
728 item.visit_attrs(|attrs| attrs.insert(pos, attr));
729 fragment_kind.expect_from_annotatables(iter::once(item))
733 InvocationKind::Derive { path, item } => match ext {
734 SyntaxExtensionKind::Derive(expander)
735 | SyntaxExtensionKind::LegacyDerive(expander) => {
736 if let SyntaxExtensionKind::Derive(..) = ext {
737 self.gate_proc_macro_input(&item);
739 let meta = ast::MetaItem { kind: MetaItemKind::Word, span, path };
740 let items = match expander.expand(self.cx, span, &meta, item) {
741 ExpandResult::Ready(items) => items,
742 ExpandResult::Retry(item) => {
743 // Reassemble the original invocation for retrying.
744 return ExpandResult::Retry(Invocation {
745 kind: InvocationKind::Derive { path: meta.path, item },
750 fragment_kind.expect_from_annotatables(items)
757 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
758 let kind = match item {
760 | Annotatable::TraitItem(_)
761 | Annotatable::ImplItem(_)
762 | Annotatable::ForeignItem(_)
763 | Annotatable::Crate(..) => return,
764 Annotatable::Stmt(stmt) => {
765 // Attributes are stable on item statements,
766 // but unstable on all other kinds of statements
772 Annotatable::Expr(_) => "expressions",
774 | Annotatable::ExprField(..)
775 | Annotatable::PatField(..)
776 | Annotatable::GenericParam(..)
777 | Annotatable::Param(..)
778 | Annotatable::FieldDef(..)
779 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
781 if self.cx.ecfg.proc_macro_hygiene() {
785 &self.cx.sess.parse_sess,
786 sym::proc_macro_hygiene,
788 &format!("custom attributes cannot be applied to {}", kind),
793 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
794 struct GateProcMacroInput<'a> {
795 parse_sess: &'a ParseSess,
798 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
799 fn visit_item(&mut self, item: &'ast ast::Item) {
801 ItemKind::Mod(_, mod_kind)
802 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
806 sym::proc_macro_hygiene,
808 "non-inline modules in proc macro input are unstable",
815 visit::walk_item(self, item);
819 if !self.cx.ecfg.proc_macro_hygiene() {
821 .visit_with(&mut GateProcMacroInput { parse_sess: &self.cx.sess.parse_sess });
825 fn parse_ast_fragment(
828 kind: AstFragmentKind,
832 let mut parser = self.cx.new_parser_from_tts(toks);
833 match parse_ast_fragment(&mut parser, kind) {
835 ensure_complete_parse(&mut parser, path, kind.name(), span);
839 if err.span.is_dummy() {
842 annotate_err_with_kind(&mut err, kind, span);
844 self.cx.trace_macros_diag();
851 pub fn parse_ast_fragment<'a>(
852 this: &mut Parser<'a>,
853 kind: AstFragmentKind,
854 ) -> PResult<'a, AstFragment> {
856 AstFragmentKind::Items => {
857 let mut items = SmallVec::new();
858 while let Some(item) = this.parse_item(ForceCollect::No)? {
861 AstFragment::Items(items)
863 AstFragmentKind::TraitItems => {
864 let mut items = SmallVec::new();
865 while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
868 AstFragment::TraitItems(items)
870 AstFragmentKind::ImplItems => {
871 let mut items = SmallVec::new();
872 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
875 AstFragment::ImplItems(items)
877 AstFragmentKind::ForeignItems => {
878 let mut items = SmallVec::new();
879 while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
882 AstFragment::ForeignItems(items)
884 AstFragmentKind::Stmts => {
885 let mut stmts = SmallVec::new();
886 // Won't make progress on a `}`.
887 while this.token != token::Eof && this.token != token::CloseDelim(Delimiter::Brace) {
888 if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
892 AstFragment::Stmts(stmts)
894 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
895 AstFragmentKind::OptExpr => {
896 if this.token != token::Eof {
897 AstFragment::OptExpr(Some(this.parse_expr()?))
899 AstFragment::OptExpr(None)
902 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
903 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat_allow_top_alt(
907 CommaRecoveryMode::LikelyTuple,
909 AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?),
910 AstFragmentKind::Arms
911 | AstFragmentKind::ExprFields
912 | AstFragmentKind::PatFields
913 | AstFragmentKind::GenericParams
914 | AstFragmentKind::Params
915 | AstFragmentKind::FieldDefs
916 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
920 pub fn ensure_complete_parse<'a>(
921 this: &mut Parser<'a>,
922 macro_path: &ast::Path,
926 if this.token != token::Eof {
927 let token = pprust::token_to_string(&this.token);
928 let msg = format!("macro expansion ignores token `{}` and any following", token);
929 // Avoid emitting backtrace info twice.
930 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
931 let mut err = this.struct_span_err(def_site_span, &msg);
932 err.span_label(span, "caused by the macro expansion here");
934 "the usage of `{}!` is likely invalid in {} context",
935 pprust::path_to_string(macro_path),
939 let semi_span = this.sess.source_map().next_point(span);
941 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
942 match this.sess.source_map().span_to_snippet(semi_full_span) {
943 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
946 "you might be missing a semicolon here",
948 Applicability::MaybeIncorrect,
957 /// Wraps a call to `noop_visit_*` / `noop_flat_map_*`
958 /// for an AST node that supports attributes
959 /// (see the `Annotatable` enum)
960 /// This method assigns a `NodeId`, and sets that `NodeId`
961 /// as our current 'lint node id'. If a macro call is found
962 /// inside this AST node, we will use this AST node's `NodeId`
963 /// to emit lints associated with that macro (allowing
964 /// `#[allow]` / `#[deny]` to be applied close to
965 /// the macro invocation).
967 /// Do *not* call this for a macro AST node
968 /// (e.g. `ExprKind::MacCall`) - we cannot emit lints
969 /// at these AST nodes, since they are removed and
970 /// replaced with the result of macro expansion.
972 /// All other `NodeId`s are assigned by `visit_id`.
973 /// * `self` is the 'self' parameter for the current method,
974 /// * `id` is a mutable reference to the `NodeId` field
975 /// of the current AST node.
976 /// * `closure` is a closure that executes the
977 /// `noop_visit_*` / `noop_flat_map_*` method
978 /// for the current AST node.
979 macro_rules! assign_id {
980 ($self:ident, $id:expr, $closure:expr) => {{
981 let old_id = $self.cx.current_expansion.lint_node_id;
983 debug_assert_eq!(*$id, ast::DUMMY_NODE_ID);
984 let new_id = $self.cx.resolver.next_node_id();
986 $self.cx.current_expansion.lint_node_id = new_id;
988 let ret = ($closure)();
989 $self.cx.current_expansion.lint_node_id = old_id;
999 /// A trait implemented for all `AstFragment` nodes and providing all pieces
1000 /// of functionality used by `InvocationCollector`.
1001 trait InvocationCollectorNode: AstLike {
1002 type OutputTy = SmallVec<[Self; 1]>;
1003 type AttrsTy: Deref<Target = [ast::Attribute]> = Vec<ast::Attribute>;
1004 const KIND: AstFragmentKind;
1005 fn to_annotatable(self) -> Annotatable;
1006 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy;
1007 fn id(&mut self) -> &mut NodeId;
1008 fn descr() -> &'static str {
1011 fn noop_flat_map<V: MutVisitor>(self, _visitor: &mut V) -> Self::OutputTy {
1014 fn noop_visit<V: MutVisitor>(&mut self, _visitor: &mut V) {
1017 fn is_mac_call(&self) -> bool {
1020 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1023 fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {}
1024 fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) {
1026 fn wrap_flat_map_node_noop_flat_map(
1028 collector: &mut InvocationCollector<'_, '_>,
1029 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1030 ) -> Result<Self::OutputTy, Self> {
1031 Ok(noop_flat_map(node, collector))
1035 impl InvocationCollectorNode for P<ast::Item> {
1036 const KIND: AstFragmentKind = AstFragmentKind::Items;
1037 fn to_annotatable(self) -> Annotatable {
1038 Annotatable::Item(self)
1040 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1041 fragment.make_items()
1043 fn id(&mut self) -> &mut NodeId {
1046 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1047 noop_flat_map_item(self, visitor)
1049 fn is_mac_call(&self) -> bool {
1050 matches!(self.kind, ItemKind::MacCall(..))
1052 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1053 let node = self.into_inner();
1055 ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1056 _ => unreachable!(),
1059 fn wrap_flat_map_node_noop_flat_map(
1061 collector: &mut InvocationCollector<'_, '_>,
1062 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1063 ) -> Result<Self::OutputTy, Self> {
1064 if !matches!(node.kind, ItemKind::Mod(..)) {
1065 return Ok(noop_flat_map(node, collector));
1068 // Work around borrow checker not seeing through `P`'s deref.
1069 let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs));
1070 let ItemKind::Mod(_, mod_kind) = &mut node.kind else {
1074 let ecx = &mut collector.cx;
1075 let (file_path, dir_path, dir_ownership) = match mod_kind {
1076 ModKind::Loaded(_, inline, _) => {
1077 // Inline `mod foo { ... }`, but we still need to push directories.
1078 let (dir_path, dir_ownership) = mod_dir_path(
1082 &ecx.current_expansion.module,
1083 ecx.current_expansion.dir_ownership,
1087 (None, dir_path, dir_ownership)
1089 ModKind::Unloaded => {
1090 // We have an outline `mod foo;` so we need to parse the file.
1091 let old_attrs_len = attrs.len();
1092 let ParsedExternalMod { items, spans, file_path, dir_path, dir_ownership } =
1097 &ecx.current_expansion.module,
1098 ecx.current_expansion.dir_ownership,
1102 if let Some(lint_store) = ecx.lint_store {
1103 lint_store.pre_expansion_lint(
1105 ecx.resolver.registered_tools(),
1106 ecx.current_expansion.lint_node_id,
1109 ident.name.as_str(),
1113 *mod_kind = ModKind::Loaded(items, Inline::No, spans);
1115 if node.attrs.len() > old_attrs_len {
1116 // If we loaded an out-of-line module and added some inner attributes,
1117 // then we need to re-configure it and re-collect attributes for
1118 // resolution and expansion.
1121 (Some(file_path), dir_path, dir_ownership)
1125 // Set the module info before we flat map.
1126 let mut module = ecx.current_expansion.module.with_dir_path(dir_path);
1127 module.mod_path.push(ident);
1128 if let Some(file_path) = file_path {
1129 module.file_path_stack.push(file_path);
1132 let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module));
1133 let orig_dir_ownership =
1134 mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership);
1136 let res = Ok(noop_flat_map(node, collector));
1138 collector.cx.current_expansion.dir_ownership = orig_dir_ownership;
1139 collector.cx.current_expansion.module = orig_module;
1144 struct TraitItemTag;
1145 impl InvocationCollectorNode for AstLikeWrapper<P<ast::AssocItem>, TraitItemTag> {
1146 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1147 const KIND: AstFragmentKind = AstFragmentKind::TraitItems;
1148 fn to_annotatable(self) -> Annotatable {
1149 Annotatable::TraitItem(self.wrapped)
1151 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1152 fragment.make_trait_items()
1154 fn id(&mut self) -> &mut NodeId {
1155 &mut self.wrapped.id
1157 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1158 noop_flat_map_assoc_item(self.wrapped, visitor)
1160 fn is_mac_call(&self) -> bool {
1161 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1163 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1164 let item = self.wrapped.into_inner();
1166 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1167 _ => unreachable!(),
1173 impl InvocationCollectorNode for AstLikeWrapper<P<ast::AssocItem>, ImplItemTag> {
1174 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1175 const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
1176 fn to_annotatable(self) -> Annotatable {
1177 Annotatable::ImplItem(self.wrapped)
1179 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1180 fragment.make_impl_items()
1182 fn id(&mut self) -> &mut NodeId {
1183 &mut self.wrapped.id
1185 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1186 noop_flat_map_assoc_item(self.wrapped, visitor)
1188 fn is_mac_call(&self) -> bool {
1189 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1191 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1192 let item = self.wrapped.into_inner();
1194 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1195 _ => unreachable!(),
1200 impl InvocationCollectorNode for P<ast::ForeignItem> {
1201 const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
1202 fn to_annotatable(self) -> Annotatable {
1203 Annotatable::ForeignItem(self)
1205 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1206 fragment.make_foreign_items()
1208 fn id(&mut self) -> &mut NodeId {
1211 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1212 noop_flat_map_foreign_item(self, visitor)
1214 fn is_mac_call(&self) -> bool {
1215 matches!(self.kind, ForeignItemKind::MacCall(..))
1217 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1218 let node = self.into_inner();
1220 ForeignItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1221 _ => unreachable!(),
1226 impl InvocationCollectorNode for ast::Variant {
1227 const KIND: AstFragmentKind = AstFragmentKind::Variants;
1228 fn to_annotatable(self) -> Annotatable {
1229 Annotatable::Variant(self)
1231 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1232 fragment.make_variants()
1234 fn id(&mut self) -> &mut NodeId {
1237 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1238 noop_flat_map_variant(self, visitor)
1242 impl InvocationCollectorNode for ast::FieldDef {
1243 const KIND: AstFragmentKind = AstFragmentKind::FieldDefs;
1244 fn to_annotatable(self) -> Annotatable {
1245 Annotatable::FieldDef(self)
1247 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1248 fragment.make_field_defs()
1250 fn id(&mut self) -> &mut NodeId {
1253 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1254 noop_flat_map_field_def(self, visitor)
1258 impl InvocationCollectorNode for ast::PatField {
1259 const KIND: AstFragmentKind = AstFragmentKind::PatFields;
1260 fn to_annotatable(self) -> Annotatable {
1261 Annotatable::PatField(self)
1263 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1264 fragment.make_pat_fields()
1266 fn id(&mut self) -> &mut NodeId {
1269 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1270 noop_flat_map_pat_field(self, visitor)
1274 impl InvocationCollectorNode for ast::ExprField {
1275 const KIND: AstFragmentKind = AstFragmentKind::ExprFields;
1276 fn to_annotatable(self) -> Annotatable {
1277 Annotatable::ExprField(self)
1279 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1280 fragment.make_expr_fields()
1282 fn id(&mut self) -> &mut NodeId {
1285 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1286 noop_flat_map_expr_field(self, visitor)
1290 impl InvocationCollectorNode for ast::Param {
1291 const KIND: AstFragmentKind = AstFragmentKind::Params;
1292 fn to_annotatable(self) -> Annotatable {
1293 Annotatable::Param(self)
1295 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1296 fragment.make_params()
1298 fn id(&mut self) -> &mut NodeId {
1301 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1302 noop_flat_map_param(self, visitor)
1306 impl InvocationCollectorNode for ast::GenericParam {
1307 const KIND: AstFragmentKind = AstFragmentKind::GenericParams;
1308 fn to_annotatable(self) -> Annotatable {
1309 Annotatable::GenericParam(self)
1311 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1312 fragment.make_generic_params()
1314 fn id(&mut self) -> &mut NodeId {
1317 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1318 noop_flat_map_generic_param(self, visitor)
1322 impl InvocationCollectorNode for ast::Arm {
1323 const KIND: AstFragmentKind = AstFragmentKind::Arms;
1324 fn to_annotatable(self) -> Annotatable {
1325 Annotatable::Arm(self)
1327 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1328 fragment.make_arms()
1330 fn id(&mut self) -> &mut NodeId {
1333 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1334 noop_flat_map_arm(self, visitor)
1338 impl InvocationCollectorNode for ast::Stmt {
1339 type AttrsTy = ast::AttrVec;
1340 const KIND: AstFragmentKind = AstFragmentKind::Stmts;
1341 fn to_annotatable(self) -> Annotatable {
1342 Annotatable::Stmt(P(self))
1344 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1345 fragment.make_stmts()
1347 fn id(&mut self) -> &mut NodeId {
1350 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1351 noop_flat_map_stmt(self, visitor)
1353 fn is_mac_call(&self) -> bool {
1355 StmtKind::MacCall(..) => true,
1356 StmtKind::Item(item) => matches!(item.kind, ItemKind::MacCall(..)),
1357 StmtKind::Semi(expr) => matches!(expr.kind, ExprKind::MacCall(..)),
1358 StmtKind::Expr(..) => unreachable!(),
1359 StmtKind::Local(..) | StmtKind::Empty => false,
1362 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1363 // We pull macro invocations (both attributes and fn-like macro calls) out of their
1364 // `StmtKind`s and treat them as statement macro invocations, not as items or expressions.
1365 let (add_semicolon, mac, attrs) = match self.kind {
1366 StmtKind::MacCall(mac) => {
1367 let ast::MacCallStmt { mac, style, attrs, .. } = mac.into_inner();
1368 (style == MacStmtStyle::Semicolon, mac, attrs)
1370 StmtKind::Item(item) => match item.into_inner() {
1371 ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => {
1372 (mac.args.need_semicolon(), mac, attrs.into())
1374 _ => unreachable!(),
1376 StmtKind::Semi(expr) => match expr.into_inner() {
1377 ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => {
1378 (mac.args.need_semicolon(), mac, attrs)
1380 _ => unreachable!(),
1382 _ => unreachable!(),
1384 (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No })
1386 fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) {
1387 // If this is a macro invocation with a semicolon, then apply that
1388 // semicolon to the final statement produced by expansion.
1389 if matches!(add_semicolon, AddSemicolon::Yes) {
1390 if let Some(stmt) = stmts.pop() {
1391 stmts.push(stmt.add_trailing_semicolon());
1397 impl InvocationCollectorNode for ast::Crate {
1398 type OutputTy = ast::Crate;
1399 const KIND: AstFragmentKind = AstFragmentKind::Crate;
1400 fn to_annotatable(self) -> Annotatable {
1401 Annotatable::Crate(self)
1403 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1404 fragment.make_crate()
1406 fn id(&mut self) -> &mut NodeId {
1409 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1410 noop_visit_crate(self, visitor)
1414 impl InvocationCollectorNode for P<ast::Ty> {
1415 type OutputTy = P<ast::Ty>;
1416 const KIND: AstFragmentKind = AstFragmentKind::Ty;
1417 fn to_annotatable(self) -> Annotatable {
1420 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1423 fn id(&mut self) -> &mut NodeId {
1426 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1427 noop_visit_ty(self, visitor)
1429 fn is_mac_call(&self) -> bool {
1430 matches!(self.kind, ast::TyKind::MacCall(..))
1432 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1433 let node = self.into_inner();
1435 TyKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No),
1436 _ => unreachable!(),
1441 impl InvocationCollectorNode for P<ast::Pat> {
1442 type OutputTy = P<ast::Pat>;
1443 const KIND: AstFragmentKind = AstFragmentKind::Pat;
1444 fn to_annotatable(self) -> Annotatable {
1447 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1450 fn id(&mut self) -> &mut NodeId {
1453 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1454 noop_visit_pat(self, visitor)
1456 fn is_mac_call(&self) -> bool {
1457 matches!(self.kind, PatKind::MacCall(..))
1459 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1460 let node = self.into_inner();
1462 PatKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No),
1463 _ => unreachable!(),
1468 impl InvocationCollectorNode for P<ast::Expr> {
1469 type OutputTy = P<ast::Expr>;
1470 type AttrsTy = ast::AttrVec;
1471 const KIND: AstFragmentKind = AstFragmentKind::Expr;
1472 fn to_annotatable(self) -> Annotatable {
1473 Annotatable::Expr(self)
1475 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1476 fragment.make_expr()
1478 fn id(&mut self) -> &mut NodeId {
1481 fn descr() -> &'static str {
1484 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1485 noop_visit_expr(self, visitor)
1487 fn is_mac_call(&self) -> bool {
1488 matches!(self.kind, ExprKind::MacCall(..))
1490 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1491 let node = self.into_inner();
1493 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1494 _ => unreachable!(),
1500 impl InvocationCollectorNode for AstLikeWrapper<P<ast::Expr>, OptExprTag> {
1501 type OutputTy = Option<P<ast::Expr>>;
1502 type AttrsTy = ast::AttrVec;
1503 const KIND: AstFragmentKind = AstFragmentKind::OptExpr;
1504 fn to_annotatable(self) -> Annotatable {
1505 Annotatable::Expr(self.wrapped)
1507 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1508 fragment.make_opt_expr()
1510 fn id(&mut self) -> &mut NodeId {
1511 &mut self.wrapped.id
1513 fn noop_flat_map<V: MutVisitor>(mut self, visitor: &mut V) -> Self::OutputTy {
1514 noop_visit_expr(&mut self.wrapped, visitor);
1517 fn is_mac_call(&self) -> bool {
1518 matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1520 fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) {
1521 let node = self.wrapped.into_inner();
1523 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1524 _ => unreachable!(),
1527 fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) {
1528 cfg.maybe_emit_expr_attr_err(&attr);
1532 struct InvocationCollector<'a, 'b> {
1533 cx: &'a mut ExtCtxt<'b>,
1534 invocations: Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>,
1538 impl<'a, 'b> InvocationCollector<'a, 'b> {
1539 fn cfg(&self) -> StripUnconfigured<'_> {
1541 sess: &self.cx.sess,
1542 features: self.cx.ecfg.features,
1543 config_tokens: false,
1544 lint_node_id: self.cx.current_expansion.lint_node_id,
1548 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1549 let expn_id = LocalExpnId::fresh_empty();
1550 let vis = kind.placeholder_visibility();
1551 self.invocations.push((
1555 expansion_data: ExpansionData {
1557 depth: self.cx.current_expansion.depth + 1,
1558 ..self.cx.current_expansion.clone()
1563 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1566 fn collect_bang(&mut self, mac: ast::MacCall, kind: AstFragmentKind) -> AstFragment {
1567 // cache the macro call span so that it can be
1568 // easily adjusted for incremental compilation
1569 let span = mac.span();
1570 self.collect(kind, InvocationKind::Bang { mac, span })
1575 (attr, pos, derives): (ast::Attribute, usize, Vec<ast::Path>),
1577 kind: AstFragmentKind,
1579 self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
1582 /// If `item` is an attribute invocation, remove the attribute and return it together with
1583 /// its position and derives following it. We have to collect the derives in order to resolve
1584 /// legacy derive helpers (helpers written before derives that introduce them).
1587 item: &mut impl AstLike,
1588 ) -> Option<(ast::Attribute, usize, Vec<ast::Path>)> {
1589 let mut attr = None;
1591 let mut cfg_pos = None;
1592 let mut attr_pos = None;
1593 for (pos, attr) in item.attrs().iter().enumerate() {
1594 if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) {
1595 let name = attr.ident().map(|ident| ident.name);
1596 if name == Some(sym::cfg) || name == Some(sym::cfg_attr) {
1597 cfg_pos = Some(pos); // a cfg attr found, no need to search anymore
1599 } else if attr_pos.is_none()
1600 && !name.map_or(false, rustc_feature::is_builtin_attr_name)
1602 attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr
1607 item.visit_attrs(|attrs| {
1608 attr = Some(match (cfg_pos, attr_pos) {
1609 (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()),
1611 let attr = attrs.remove(pos);
1612 let following_derives = attrs[pos..]
1614 .filter(|a| a.has_name(sym::derive))
1615 .flat_map(|a| a.meta_item_list().unwrap_or_default())
1616 .filter_map(|nested_meta| match nested_meta {
1617 NestedMetaItem::MetaItem(ast::MetaItem {
1618 kind: MetaItemKind::Word,
1626 (attr, pos, following_derives)
1635 // Detect use of feature-gated or invalid attributes on macro invocations
1636 // since they will not be detected after macro expansion.
1637 fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
1638 let features = self.cx.ecfg.features.unwrap();
1639 let mut attrs = attrs.iter().peekable();
1640 let mut span: Option<Span> = None;
1641 while let Some(attr) = attrs.next() {
1642 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
1643 validate_attr::check_meta(&self.cx.sess.parse_sess, attr);
1645 let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
1646 span = Some(current_span);
1648 if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
1652 if attr.is_doc_comment() {
1653 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1654 &UNUSED_DOC_COMMENTS,
1656 self.cx.current_expansion.lint_node_id,
1657 "unused doc comment",
1658 BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1660 } else if rustc_attr::is_builtin_attr(attr) {
1661 let attr_name = attr.ident().unwrap().name;
1662 // `#[cfg]` and `#[cfg_attr]` are special - they are
1663 // eagerly evaluated.
1664 if attr_name != sym::cfg && attr_name != sym::cfg_attr {
1665 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1668 self.cx.current_expansion.lint_node_id,
1669 &format!("unused attribute `{}`", attr_name),
1670 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
1672 macro_name: pprust::path_to_string(&call.path),
1673 invoc_span: call.path.span,
1683 node: &mut impl AstLike,
1684 attr: ast::Attribute,
1687 let res = self.cfg().cfg_true(&attr);
1689 // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion,
1690 // and some tools like rustdoc and clippy rely on that. Find a way to remove them
1691 // while keeping the tools working.
1692 self.cx.expanded_inert_attrs.mark(&attr);
1693 node.visit_attrs(|attrs| attrs.insert(pos, attr));
1698 fn expand_cfg_attr(&self, node: &mut impl AstLike, attr: ast::Attribute, pos: usize) {
1699 node.visit_attrs(|attrs| {
1700 attrs.splice(pos..pos, self.cfg().expand_cfg_attr(attr, false));
1704 fn flat_map_node<Node: InvocationCollectorNode<OutputTy: Default>>(
1707 ) -> Node::OutputTy {
1709 return match self.take_first_attr(&mut node) {
1710 Some((attr, pos, derives)) => match attr.name_or_empty() {
1712 if self.expand_cfg_true(&mut node, attr, pos) {
1718 self.expand_cfg_attr(&mut node, attr, pos);
1722 Node::pre_flat_map_node_collect_attr(&self.cfg(), &attr);
1723 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1727 None if node.is_mac_call() => {
1728 let (mac, attrs, add_semicolon) = node.take_mac_call();
1729 self.check_attributes(&attrs, &mac);
1730 let mut res = self.collect_bang(mac, Node::KIND).make_ast::<Node>();
1731 Node::post_flat_map_node_collect_bang(&mut res, add_semicolon);
1735 match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| {
1736 assign_id!(this, node.id(), || node.noop_flat_map(this))
1738 Ok(output) => output,
1739 Err(returned_node) => {
1740 node = returned_node;
1749 fn visit_node<Node: InvocationCollectorNode<OutputTy = Node> + DummyAstNode>(
1754 return match self.take_first_attr(node) {
1755 Some((attr, pos, derives)) => match attr.name_or_empty() {
1757 let span = attr.span;
1758 if self.expand_cfg_true(node, attr, pos) {
1762 format!("removing {} is not supported in this position", Node::descr());
1763 self.cx.span_err(span, &msg);
1767 self.expand_cfg_attr(node, attr, pos);
1770 _ => visit_clobber(node, |node| {
1771 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1775 None if node.is_mac_call() => {
1776 visit_clobber(node, |node| {
1777 // Do not clobber unless it's actually a macro (uncommon case).
1778 let (mac, attrs, _) = node.take_mac_call();
1779 self.check_attributes(&attrs, &mac);
1780 self.collect_bang(mac, Node::KIND).make_ast::<Node>()
1784 assign_id!(self, node.id(), || node.noop_visit(self))
1791 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1792 fn flat_map_item(&mut self, node: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1793 self.flat_map_node(node)
1796 fn flat_map_trait_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1797 self.flat_map_node(AstLikeWrapper::new(node, TraitItemTag))
1800 fn flat_map_impl_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1801 self.flat_map_node(AstLikeWrapper::new(node, ImplItemTag))
1804 fn flat_map_foreign_item(
1806 node: P<ast::ForeignItem>,
1807 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1808 self.flat_map_node(node)
1811 fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1812 self.flat_map_node(node)
1815 fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
1816 self.flat_map_node(node)
1819 fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
1820 self.flat_map_node(node)
1823 fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
1824 self.flat_map_node(node)
1827 fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> {
1828 self.flat_map_node(node)
1831 fn flat_map_generic_param(
1833 node: ast::GenericParam,
1834 ) -> SmallVec<[ast::GenericParam; 1]> {
1835 self.flat_map_node(node)
1838 fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1839 self.flat_map_node(node)
1842 fn flat_map_stmt(&mut self, node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1843 // FIXME: invocations in semicolon-less expressions positions are expanded as expressions,
1844 // changing that requires some compatibility measures.
1846 // The only way that we can end up with a `MacCall` expression statement,
1847 // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the
1848 // trailing expression in a block (e.g. `fn foo() { my_macro!() }`).
1849 // Record this information, so that we can report a more specific
1850 // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed.
1851 // See #78991 for an investigation of treating macros in this position
1852 // as statements, rather than expressions, during parsing.
1853 return match &node.kind {
1854 StmtKind::Expr(expr)
1855 if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) =>
1857 self.cx.current_expansion.is_trailing_mac = true;
1858 // Don't use `assign_id` for this statement - it may get removed
1859 // entirely due to a `#[cfg]` on the contained expression
1860 let res = noop_flat_map_stmt(node, self);
1861 self.cx.current_expansion.is_trailing_mac = false;
1864 _ => noop_flat_map_stmt(node, self),
1868 self.flat_map_node(node)
1871 fn visit_crate(&mut self, node: &mut ast::Crate) {
1872 self.visit_node(node)
1875 fn visit_ty(&mut self, node: &mut P<ast::Ty>) {
1876 self.visit_node(node)
1879 fn visit_pat(&mut self, node: &mut P<ast::Pat>) {
1880 self.visit_node(node)
1883 fn visit_expr(&mut self, node: &mut P<ast::Expr>) {
1884 // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`.
1885 if let Some(attr) = node.attrs.first() {
1886 self.cfg().maybe_emit_expr_attr_err(attr);
1888 self.visit_node(node)
1891 fn filter_map_expr(&mut self, node: P<ast::Expr>) -> Option<P<ast::Expr>> {
1892 self.flat_map_node(AstLikeWrapper::new(node, OptExprTag))
1895 fn visit_block(&mut self, node: &mut P<ast::Block>) {
1896 let orig_dir_ownership = mem::replace(
1897 &mut self.cx.current_expansion.dir_ownership,
1898 DirOwnership::UnownedViaBlock,
1900 noop_visit_block(node, self);
1901 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1904 fn visit_id(&mut self, id: &mut NodeId) {
1905 // We may have already assigned a `NodeId`
1906 // by calling `assign_id`
1907 if self.monotonic && *id == ast::DUMMY_NODE_ID {
1908 *id = self.cx.resolver.next_node_id();
1913 pub struct ExpansionConfig<'feat> {
1914 pub crate_name: String,
1915 pub features: Option<&'feat Features>,
1916 pub recursion_limit: Limit,
1917 pub trace_mac: bool,
1918 pub should_test: bool, // If false, strip `#[test]` nodes
1919 pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span`
1920 pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics
1923 impl<'feat> ExpansionConfig<'feat> {
1924 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1928 recursion_limit: Limit::new(1024),
1932 proc_macro_backtrace: false,
1936 fn proc_macro_hygiene(&self) -> bool {
1937 self.features.map_or(false, |features| features.proc_macro_hygiene)