2 use crate::config::StripUnconfigured;
3 use crate::hygiene::SyntaxContext;
4 use crate::mbe::diagnostics::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, AstNodeWrapper, AttrArgs, AttrStyle, AttrVec, ExprKind};
15 use rustc_ast::{ForeignItemKind, HasAttrs, HasNodeId};
16 use rustc_ast::{Inline, ItemKind, MacStmtStyle, MetaItemKind, ModKind};
17 use rustc_ast::{NestedMetaItem, NodeId, PatKind, StmtKind, TyKind};
18 use rustc_ast_pretty::pprust;
19 use rustc_data_structures::map_in_place::MapInPlace;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_errors::{Applicability, PResult};
22 use rustc_feature::Features;
23 use rustc_parse::parser::{
24 AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma,
26 use rustc_parse::validate_attr;
27 use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS};
28 use rustc_session::lint::BuiltinLintDiagnostics;
29 use rustc_session::parse::{feature_err, ParseSess};
30 use rustc_session::Limit;
31 use rustc_span::symbol::{sym, Ident};
32 use rustc_span::{FileName, LocalExpnId, Span};
34 use smallvec::SmallVec;
36 use std::path::PathBuf;
40 macro_rules! ast_fragments {
42 $($Kind:ident($AstTy:ty) {
44 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
45 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*);)?
49 /// A fragment of AST that can be produced by a single macro expansion.
50 /// Can also serve as an input and intermediate result for macro expansion operations.
51 pub enum AstFragment {
52 OptExpr(Option<P<ast::Expr>>),
53 MethodReceiverExpr(P<ast::Expr>),
57 /// "Discriminant" of an AST fragment.
58 #[derive(Copy, Clone, PartialEq, Eq)]
59 pub enum AstFragmentKind {
65 impl AstFragmentKind {
66 pub fn name(self) -> &'static str {
68 AstFragmentKind::OptExpr => "expression",
69 AstFragmentKind::MethodReceiverExpr => "expression",
70 $(AstFragmentKind::$Kind => $kind_name,)*
74 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
76 AstFragmentKind::OptExpr =>
77 result.make_expr().map(Some).map(AstFragment::OptExpr),
78 AstFragmentKind::MethodReceiverExpr =>
79 result.make_expr().map(AstFragment::MethodReceiverExpr),
80 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
86 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
87 if placeholders.is_empty() {
91 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
92 ${ignore(flat_map_ast_elt)}
93 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
95 _ => panic!("unexpected AST fragment kind")
99 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
101 AstFragment::OptExpr(expr) => expr,
102 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
106 pub fn make_method_receiver_expr(self) -> P<ast::Expr> {
108 AstFragment::MethodReceiverExpr(expr) => expr,
109 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
113 $(pub fn $make_ast(self) -> $AstTy {
115 AstFragment::$Kind(ast) => ast,
116 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
120 fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
121 T::fragment_to_output(self)
124 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
126 AstFragment::OptExpr(opt_expr) => {
127 visit_clobber(opt_expr, |opt_expr| {
128 if let Some(expr) = opt_expr {
129 vis.filter_map_expr(expr)
135 AstFragment::MethodReceiverExpr(expr) => vis.visit_method_receiver_expr(expr),
136 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
137 $($(AstFragment::$Kind(ast) =>
138 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
142 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
144 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
145 AstFragment::OptExpr(None) => {}
146 AstFragment::MethodReceiverExpr(ref expr) => visitor.visit_method_receiver_expr(expr),
147 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
148 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
149 visitor.$visit_ast_elt(ast_elt, $($args)*);
155 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
156 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
158 Some(self.make(AstFragmentKind::$Kind).$make_ast())
165 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
166 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
167 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
168 Stmts(SmallVec<[ast::Stmt; 1]>) {
169 "statement"; many fn flat_map_stmt; fn visit_stmt(); fn make_stmts;
171 Items(SmallVec<[P<ast::Item>; 1]>) {
172 "item"; many fn flat_map_item; fn visit_item(); fn make_items;
174 TraitItems(SmallVec<[P<ast::AssocItem>; 1]>) {
176 many fn flat_map_trait_item;
177 fn visit_assoc_item(AssocCtxt::Trait);
180 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
182 many fn flat_map_impl_item;
183 fn visit_assoc_item(AssocCtxt::Impl);
186 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
188 many fn flat_map_foreign_item;
189 fn visit_foreign_item();
190 fn make_foreign_items;
192 Arms(SmallVec<[ast::Arm; 1]>) {
193 "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms;
195 ExprFields(SmallVec<[ast::ExprField; 1]>) {
196 "field expression"; many fn flat_map_expr_field; fn visit_expr_field(); fn make_expr_fields;
198 PatFields(SmallVec<[ast::PatField; 1]>) {
200 many fn flat_map_pat_field;
201 fn visit_pat_field();
204 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
206 many fn flat_map_generic_param;
207 fn visit_generic_param();
208 fn make_generic_params;
210 Params(SmallVec<[ast::Param; 1]>) {
211 "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params;
213 FieldDefs(SmallVec<[ast::FieldDef; 1]>) {
215 many fn flat_map_field_def;
216 fn visit_field_def();
219 Variants(SmallVec<[ast::Variant; 1]>) {
220 "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants;
222 Crate(ast::Crate) { "crate"; one fn visit_crate; fn visit_crate; fn make_crate; }
225 pub enum SupportsMacroExpansion {
227 Yes { supports_inner_attrs: bool },
230 impl AstFragmentKind {
231 pub(crate) fn dummy(self, span: Span) -> AstFragment {
232 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
235 pub fn supports_macro_expansion(self) -> SupportsMacroExpansion {
237 AstFragmentKind::OptExpr
238 | AstFragmentKind::Expr
239 | AstFragmentKind::MethodReceiverExpr
240 | AstFragmentKind::Stmts
241 | AstFragmentKind::Ty
242 | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false },
243 AstFragmentKind::Items
244 | AstFragmentKind::TraitItems
245 | AstFragmentKind::ImplItems
246 | AstFragmentKind::ForeignItems
247 | AstFragmentKind::Crate => SupportsMacroExpansion::Yes { supports_inner_attrs: true },
248 AstFragmentKind::Arms
249 | AstFragmentKind::ExprFields
250 | AstFragmentKind::PatFields
251 | AstFragmentKind::GenericParams
252 | AstFragmentKind::Params
253 | AstFragmentKind::FieldDefs
254 | AstFragmentKind::Variants => SupportsMacroExpansion::No,
258 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
262 let mut items = items.into_iter();
264 AstFragmentKind::Arms => {
265 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
267 AstFragmentKind::ExprFields => {
268 AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect())
270 AstFragmentKind::PatFields => {
271 AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect())
273 AstFragmentKind::GenericParams => {
274 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
276 AstFragmentKind::Params => {
277 AstFragment::Params(items.map(Annotatable::expect_param).collect())
279 AstFragmentKind::FieldDefs => {
280 AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect())
282 AstFragmentKind::Variants => {
283 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
285 AstFragmentKind::Items => {
286 AstFragment::Items(items.map(Annotatable::expect_item).collect())
288 AstFragmentKind::ImplItems => {
289 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
291 AstFragmentKind::TraitItems => {
292 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
294 AstFragmentKind::ForeignItems => {
295 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
297 AstFragmentKind::Stmts => {
298 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
300 AstFragmentKind::Expr => AstFragment::Expr(
301 items.next().expect("expected exactly one expression").expect_expr(),
303 AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(
304 items.next().expect("expected exactly one expression").expect_expr(),
306 AstFragmentKind::OptExpr => {
307 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
309 AstFragmentKind::Crate => {
310 AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate())
312 AstFragmentKind::Pat | AstFragmentKind::Ty => {
313 panic!("patterns and types aren't annotatable")
319 pub struct Invocation {
320 pub kind: InvocationKind,
321 pub fragment_kind: AstFragmentKind,
322 pub expansion_data: ExpansionData,
325 pub enum InvocationKind {
327 mac: P<ast::MacCall>,
331 attr: ast::Attribute,
332 // Re-insertion position for inert attributes.
335 // Required for resolving derive helper attributes.
336 derives: Vec<ast::Path>,
345 impl InvocationKind {
346 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
347 // HACK: For unnamed fields placeholders should have the same visibility as the actual
348 // fields because for tuple structs/variants resolve determines visibilities of their
349 // constructor using these field visibilities before attributes on them are expanded.
350 // The assumption is that the attribute expansion cannot change field visibilities,
351 // and it holds because only inert attributes are supported in this position.
353 InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
354 | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
355 if field.ident.is_none() =>
357 Some(field.vis.clone())
365 pub fn span(&self) -> Span {
367 InvocationKind::Bang { span, .. } => *span,
368 InvocationKind::Attr { attr, .. } => attr.span,
369 InvocationKind::Derive { path, .. } => path.span,
374 pub struct MacroExpander<'a, 'b> {
375 pub cx: &'a mut ExtCtxt<'b>,
376 monotonic: bool, // cf. `cx.monotonic_expander()`
379 impl<'a, 'b> MacroExpander<'a, 'b> {
380 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
381 MacroExpander { cx, monotonic }
384 pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate {
385 let file_path = match self.cx.source_map().span_to_filename(krate.spans.inner_span) {
386 FileName::Real(name) => name
388 .expect("attempting to resolve a file path in an external file"),
389 other => PathBuf::from(other.prefer_local().to_string()),
391 let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
392 self.cx.root_path = dir_path.clone();
393 self.cx.current_expansion.module = Rc::new(ModuleData {
394 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
395 file_path_stack: vec![file_path],
398 let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate();
399 assert_eq!(krate.id, ast::CRATE_NODE_ID);
400 self.cx.trace_macros_diag();
404 /// Recursively expand all macro invocations in this AST fragment.
405 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
406 let orig_expansion_data = self.cx.current_expansion.clone();
407 let orig_force_mode = self.cx.force_mode;
409 // Collect all macro invocations and replace them with placeholders.
410 let (mut fragment_with_placeholders, mut invocations) =
411 self.collect_invocations(input_fragment, &[]);
413 // Optimization: if we resolve all imports now,
414 // we'll be able to immediately resolve most of imported macros.
415 self.resolve_imports();
417 // Resolve paths in all invocations and produce output expanded fragments for them, but
418 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
419 // The output fragments also go through expansion recursively until no invocations are left.
420 // Unresolved macros produce dummy outputs as a recovery measure.
421 invocations.reverse();
422 let mut expanded_fragments = Vec::new();
423 let mut undetermined_invocations = Vec::new();
424 let (mut progress, mut force) = (false, !self.monotonic);
426 let Some((invoc, ext)) = invocations.pop() else {
427 self.resolve_imports();
428 if undetermined_invocations.is_empty() {
431 invocations = mem::take(&mut undetermined_invocations);
432 force = !mem::replace(&mut progress, false);
433 if force && self.monotonic {
434 self.cx.sess.delay_span_bug(
435 invocations.last().unwrap().0.span(),
436 "expansion entered force mode without producing any errors",
442 let ext = match ext {
445 let eager_expansion_root = if self.monotonic {
446 invoc.expansion_data.id
448 orig_expansion_data.id
450 match self.cx.resolver.resolve_macro_invocation(
452 eager_expansion_root,
456 Err(Indeterminate) => {
457 // Cannot resolve, will retry this invocation later.
458 undetermined_invocations.push((invoc, None));
465 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
466 let depth = depth - orig_expansion_data.depth;
467 self.cx.current_expansion = invoc.expansion_data.clone();
468 self.cx.force_mode = force;
470 let fragment_kind = invoc.fragment_kind;
471 let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) {
472 ExpandResult::Ready(fragment) => {
473 let mut derive_invocations = Vec::new();
474 let derive_placeholders = self
477 .take_derive_resolutions(expn_id)
479 derive_invocations.reserve(derives.len());
482 .map(|(path, item, _exts, is_const)| {
483 // FIXME: Consider using the derive resolutions (`_exts`)
484 // instead of enqueuing the derives to be resolved again later.
485 let expn_id = LocalExpnId::fresh_empty();
486 derive_invocations.push((
488 kind: InvocationKind::Derive { path, item, is_const },
490 expansion_data: ExpansionData {
492 ..self.cx.current_expansion.clone()
497 NodeId::placeholder_from_expn_id(expn_id)
501 .unwrap_or_default();
503 let (fragment, collected_invocations) =
504 self.collect_invocations(fragment, &derive_placeholders);
505 // We choose to expand any derive invocations associated with this macro invocation
506 // *before* any macro invocations collected from the output fragment
507 derive_invocations.extend(collected_invocations);
508 (fragment, derive_invocations)
510 ExpandResult::Retry(invoc) => {
514 "expansion entered force mode but is still stuck",
517 // Cannot expand, will retry this invocation later.
518 undetermined_invocations.push((invoc, Some(ext)));
525 if expanded_fragments.len() < depth {
526 expanded_fragments.push(Vec::new());
528 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
529 invocations.extend(new_invocations.into_iter().rev());
532 self.cx.current_expansion = orig_expansion_data;
533 self.cx.force_mode = orig_force_mode;
535 // Finally incorporate all the expanded macros into the input AST fragment.
536 let mut placeholder_expander = PlaceholderExpander::default();
537 while let Some(expanded_fragments) = expanded_fragments.pop() {
538 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
540 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
543 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
544 fragment_with_placeholders
547 fn resolve_imports(&mut self) {
549 self.cx.resolver.resolve_imports();
553 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
554 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
555 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
556 /// prepares data for resolving paths of macro invocations.
557 fn collect_invocations(
559 mut fragment: AstFragment,
560 extra_placeholders: &[NodeId],
561 ) -> (AstFragment, Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>) {
562 // Resolve `$crate`s in the fragment for pretty-printing.
563 self.cx.resolver.resolve_dollar_crates();
565 let mut invocations = {
566 let mut collector = InvocationCollector {
567 // Non-derive macro invocations cannot see the results of cfg expansion - they
568 // will either be removed along with the item, or invoked before the cfg/cfg_attr
569 // attribute is expanded. Therefore, we don't need to configure the tokens
570 // Derive macros *can* see the results of cfg-expansion - they are handled
571 // specially in `fully_expand_fragment`
573 invocations: Vec::new(),
574 monotonic: self.monotonic,
576 fragment.mut_visit_with(&mut collector);
577 fragment.add_placeholders(extra_placeholders);
578 collector.invocations
584 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
586 if self.cx.sess.opts.unstable_opts.incremental_relative_spans {
587 for (invoc, _) in invocations.iter_mut() {
588 let expn_id = invoc.expansion_data.id;
589 let parent_def = self.cx.resolver.invocation_parent(expn_id);
590 let span = match &mut invoc.kind {
591 InvocationKind::Bang { ref mut span, .. } => span,
592 InvocationKind::Attr { attr, .. } => &mut attr.span,
593 InvocationKind::Derive { path, .. } => &mut path.span,
595 *span = span.with_parent(Some(parent_def));
600 (fragment, invocations)
603 fn error_recursion_limit_reached(&mut self) {
604 let expn_data = self.cx.current_expansion.id.expn_data();
605 let suggested_limit = match self.cx.ecfg.recursion_limit {
606 Limit(0) => Limit(2),
612 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
615 "consider increasing the recursion limit by adding a \
616 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
617 suggested_limit, self.cx.ecfg.crate_name,
620 self.cx.trace_macros_diag();
623 /// A macro's expansion does not fit in this fragment kind.
624 /// For example, a non-type macro in a type position.
625 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
627 "non-{kind} macro in {kind} position: {path}",
629 path = pprust::path_to_string(&mac.path),
631 self.cx.span_err(span, &msg);
632 self.cx.trace_macros_diag();
638 ext: &SyntaxExtensionKind,
639 ) -> ExpandResult<AstFragment, Invocation> {
640 let recursion_limit =
641 self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
642 if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
643 if self.cx.reduced_recursion_limit.is_none() {
644 self.error_recursion_limit_reached();
647 // Reduce the recursion limit by half each time it triggers.
648 self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
650 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
653 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
654 ExpandResult::Ready(match invoc.kind {
655 InvocationKind::Bang { mac, .. } => match ext {
656 SyntaxExtensionKind::Bang(expander) => {
657 let Ok(tok_result) = expander.expand(self.cx, span, mac.args.tokens.clone()) else {
658 return ExpandResult::Ready(fragment_kind.dummy(span));
660 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
662 SyntaxExtensionKind::LegacyBang(expander) => {
663 let prev = self.cx.current_expansion.prior_type_ascription;
664 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
665 let tok_result = expander.expand(self.cx, span, mac.args.tokens.clone());
666 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
669 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
670 fragment_kind.dummy(span)
672 self.cx.current_expansion.prior_type_ascription = prev;
677 InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
678 SyntaxExtensionKind::Attr(expander) => {
679 self.gate_proc_macro_input(&item);
680 self.gate_proc_macro_attr_item(span, &item);
681 let tokens = match &item {
682 // FIXME: Collect tokens and use them instead of generating
683 // fake ones. These are unstable, so it needs to be
684 // fixed prior to stabilization
685 // Fake tokens when we are invoking an inner attribute, and
686 // we are invoking it on an out-of-line module or crate.
687 Annotatable::Crate(krate) => rustc_parse::fake_token_stream_for_crate(
688 &self.cx.sess.parse_sess,
691 Annotatable::Item(item_inner)
692 if matches!(attr.style, AttrStyle::Inner)
697 ModKind::Unloaded | ModKind::Loaded(_, Inline::No, _),
701 rustc_parse::fake_token_stream_for_item(
702 &self.cx.sess.parse_sess,
706 _ => item.to_tokens(),
708 let attr_item = attr.unwrap_normal_item();
709 if let AttrArgs::Eq(..) = attr_item.args {
710 self.cx.span_err(span, "key-value macro attributes are not supported");
712 let inner_tokens = attr_item.args.inner_tokens();
713 let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) else {
714 return ExpandResult::Ready(fragment_kind.dummy(span));
716 self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
718 SyntaxExtensionKind::LegacyAttr(expander) => {
719 match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) {
721 let items = match expander.expand(self.cx, span, &meta, item, false) {
722 ExpandResult::Ready(items) => items,
723 ExpandResult::Retry(item) => {
724 // Reassemble the original invocation for retrying.
725 return ExpandResult::Retry(Invocation {
726 kind: InvocationKind::Attr { attr, pos, item, derives },
731 if fragment_kind == AstFragmentKind::Expr && items.is_empty() {
733 "removing an expression is not supported in this position";
734 self.cx.span_err(span, msg);
735 fragment_kind.dummy(span)
737 fragment_kind.expect_from_annotatables(items)
742 fragment_kind.dummy(span)
746 SyntaxExtensionKind::NonMacroAttr => {
747 self.cx.expanded_inert_attrs.mark(&attr);
748 item.visit_attrs(|attrs| attrs.insert(pos, attr));
749 fragment_kind.expect_from_annotatables(iter::once(item))
753 InvocationKind::Derive { path, item, is_const } => match ext {
754 SyntaxExtensionKind::Derive(expander)
755 | SyntaxExtensionKind::LegacyDerive(expander) => {
756 if let SyntaxExtensionKind::Derive(..) = ext {
757 self.gate_proc_macro_input(&item);
759 let meta = ast::MetaItem { kind: MetaItemKind::Word, span, path };
760 let items = match expander.expand(self.cx, span, &meta, item, is_const) {
761 ExpandResult::Ready(items) => items,
762 ExpandResult::Retry(item) => {
763 // Reassemble the original invocation for retrying.
764 return ExpandResult::Retry(Invocation {
765 kind: InvocationKind::Derive { path: meta.path, item, is_const },
770 fragment_kind.expect_from_annotatables(items)
777 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
778 let kind = match item {
780 | Annotatable::TraitItem(_)
781 | Annotatable::ImplItem(_)
782 | Annotatable::ForeignItem(_)
783 | Annotatable::Crate(..) => return,
784 Annotatable::Stmt(stmt) => {
785 // Attributes are stable on item statements,
786 // but unstable on all other kinds of statements
792 Annotatable::Expr(_) => "expressions",
794 | Annotatable::ExprField(..)
795 | Annotatable::PatField(..)
796 | Annotatable::GenericParam(..)
797 | Annotatable::Param(..)
798 | Annotatable::FieldDef(..)
799 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
801 if self.cx.ecfg.proc_macro_hygiene() {
805 &self.cx.sess.parse_sess,
806 sym::proc_macro_hygiene,
808 &format!("custom attributes cannot be applied to {}", kind),
813 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
814 struct GateProcMacroInput<'a> {
815 parse_sess: &'a ParseSess,
818 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
819 fn visit_item(&mut self, item: &'ast ast::Item) {
821 ItemKind::Mod(_, mod_kind)
822 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
826 sym::proc_macro_hygiene,
828 "non-inline modules in proc macro input are unstable",
835 visit::walk_item(self, item);
839 if !self.cx.ecfg.proc_macro_hygiene() {
841 .visit_with(&mut GateProcMacroInput { parse_sess: &self.cx.sess.parse_sess });
845 fn parse_ast_fragment(
848 kind: AstFragmentKind,
852 let mut parser = self.cx.new_parser_from_tts(toks);
853 match parse_ast_fragment(&mut parser, kind) {
855 ensure_complete_parse(&mut parser, path, kind.name(), span);
859 if err.span.is_dummy() {
862 annotate_err_with_kind(&mut err, kind, span);
864 self.cx.trace_macros_diag();
871 pub fn parse_ast_fragment<'a>(
872 this: &mut Parser<'a>,
873 kind: AstFragmentKind,
874 ) -> PResult<'a, AstFragment> {
876 AstFragmentKind::Items => {
877 let mut items = SmallVec::new();
878 while let Some(item) = this.parse_item(ForceCollect::No)? {
881 AstFragment::Items(items)
883 AstFragmentKind::TraitItems => {
884 let mut items = SmallVec::new();
885 while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
888 AstFragment::TraitItems(items)
890 AstFragmentKind::ImplItems => {
891 let mut items = SmallVec::new();
892 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
895 AstFragment::ImplItems(items)
897 AstFragmentKind::ForeignItems => {
898 let mut items = SmallVec::new();
899 while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
902 AstFragment::ForeignItems(items)
904 AstFragmentKind::Stmts => {
905 let mut stmts = SmallVec::new();
906 // Won't make progress on a `}`.
907 while this.token != token::Eof && this.token != token::CloseDelim(Delimiter::Brace) {
908 if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
912 AstFragment::Stmts(stmts)
914 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
915 AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(this.parse_expr()?),
916 AstFragmentKind::OptExpr => {
917 if this.token != token::Eof {
918 AstFragment::OptExpr(Some(this.parse_expr()?))
920 AstFragment::OptExpr(None)
923 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
924 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat_allow_top_alt(
928 CommaRecoveryMode::LikelyTuple,
930 AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?),
931 AstFragmentKind::Arms
932 | AstFragmentKind::ExprFields
933 | AstFragmentKind::PatFields
934 | AstFragmentKind::GenericParams
935 | AstFragmentKind::Params
936 | AstFragmentKind::FieldDefs
937 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
941 pub fn ensure_complete_parse<'a>(
942 this: &mut Parser<'a>,
943 macro_path: &ast::Path,
947 if this.token != token::Eof {
948 let token = pprust::token_to_string(&this.token);
949 let msg = format!("macro expansion ignores token `{}` and any following", token);
950 // Avoid emitting backtrace info twice.
951 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
952 let mut err = this.struct_span_err(def_site_span, &msg);
953 err.span_label(span, "caused by the macro expansion here");
955 "the usage of `{}!` is likely invalid in {} context",
956 pprust::path_to_string(macro_path),
961 let semi_span = this.sess.source_map().next_point(span);
962 match this.sess.source_map().span_to_snippet(semi_span) {
963 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
966 "you might be missing a semicolon here",
968 Applicability::MaybeIncorrect,
977 /// Wraps a call to `noop_visit_*` / `noop_flat_map_*`
978 /// for an AST node that supports attributes
979 /// (see the `Annotatable` enum)
980 /// This method assigns a `NodeId`, and sets that `NodeId`
981 /// as our current 'lint node id'. If a macro call is found
982 /// inside this AST node, we will use this AST node's `NodeId`
983 /// to emit lints associated with that macro (allowing
984 /// `#[allow]` / `#[deny]` to be applied close to
985 /// the macro invocation).
987 /// Do *not* call this for a macro AST node
988 /// (e.g. `ExprKind::MacCall`) - we cannot emit lints
989 /// at these AST nodes, since they are removed and
990 /// replaced with the result of macro expansion.
992 /// All other `NodeId`s are assigned by `visit_id`.
993 /// * `self` is the 'self' parameter for the current method,
994 /// * `id` is a mutable reference to the `NodeId` field
995 /// of the current AST node.
996 /// * `closure` is a closure that executes the
997 /// `noop_visit_*` / `noop_flat_map_*` method
998 /// for the current AST node.
999 macro_rules! assign_id {
1000 ($self:ident, $id:expr, $closure:expr) => {{
1001 let old_id = $self.cx.current_expansion.lint_node_id;
1002 if $self.monotonic {
1003 debug_assert_eq!(*$id, ast::DUMMY_NODE_ID);
1004 let new_id = $self.cx.resolver.next_node_id();
1006 $self.cx.current_expansion.lint_node_id = new_id;
1008 let ret = ($closure)();
1009 $self.cx.current_expansion.lint_node_id = old_id;
1019 /// A trait implemented for all `AstFragment` nodes and providing all pieces
1020 /// of functionality used by `InvocationCollector`.
1021 trait InvocationCollectorNode: HasAttrs + HasNodeId + Sized {
1022 type OutputTy = SmallVec<[Self; 1]>;
1023 type AttrsTy: Deref<Target = [ast::Attribute]> = ast::AttrVec;
1024 const KIND: AstFragmentKind;
1025 fn to_annotatable(self) -> Annotatable;
1026 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy;
1027 fn descr() -> &'static str {
1030 fn noop_flat_map<V: MutVisitor>(self, _visitor: &mut V) -> Self::OutputTy {
1033 fn noop_visit<V: MutVisitor>(&mut self, _visitor: &mut V) {
1036 fn is_mac_call(&self) -> bool {
1039 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1042 fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {}
1043 fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) {
1045 fn wrap_flat_map_node_noop_flat_map(
1047 collector: &mut InvocationCollector<'_, '_>,
1048 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1049 ) -> Result<Self::OutputTy, Self> {
1050 Ok(noop_flat_map(node, collector))
1054 impl InvocationCollectorNode for P<ast::Item> {
1055 const KIND: AstFragmentKind = AstFragmentKind::Items;
1056 fn to_annotatable(self) -> Annotatable {
1057 Annotatable::Item(self)
1059 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1060 fragment.make_items()
1062 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1063 noop_flat_map_item(self, visitor)
1065 fn is_mac_call(&self) -> bool {
1066 matches!(self.kind, ItemKind::MacCall(..))
1068 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1069 let node = self.into_inner();
1071 ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1072 _ => unreachable!(),
1075 fn wrap_flat_map_node_noop_flat_map(
1077 collector: &mut InvocationCollector<'_, '_>,
1078 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1079 ) -> Result<Self::OutputTy, Self> {
1080 if !matches!(node.kind, ItemKind::Mod(..)) {
1081 return Ok(noop_flat_map(node, collector));
1084 // Work around borrow checker not seeing through `P`'s deref.
1085 let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs));
1086 let ItemKind::Mod(_, mod_kind) = &mut node.kind else {
1090 let ecx = &mut collector.cx;
1091 let (file_path, dir_path, dir_ownership) = match mod_kind {
1092 ModKind::Loaded(_, inline, _) => {
1093 // Inline `mod foo { ... }`, but we still need to push directories.
1094 let (dir_path, dir_ownership) = mod_dir_path(
1098 &ecx.current_expansion.module,
1099 ecx.current_expansion.dir_ownership,
1103 (None, dir_path, dir_ownership)
1105 ModKind::Unloaded => {
1106 // We have an outline `mod foo;` so we need to parse the file.
1107 let old_attrs_len = attrs.len();
1108 let ParsedExternalMod { items, spans, file_path, dir_path, dir_ownership } =
1113 &ecx.current_expansion.module,
1114 ecx.current_expansion.dir_ownership,
1118 if let Some(lint_store) = ecx.lint_store {
1119 lint_store.pre_expansion_lint(
1121 ecx.resolver.registered_tools(),
1122 ecx.current_expansion.lint_node_id,
1125 ident.name.as_str(),
1129 *mod_kind = ModKind::Loaded(items, Inline::No, spans);
1131 if node.attrs.len() > old_attrs_len {
1132 // If we loaded an out-of-line module and added some inner attributes,
1133 // then we need to re-configure it and re-collect attributes for
1134 // resolution and expansion.
1137 (Some(file_path), dir_path, dir_ownership)
1141 // Set the module info before we flat map.
1142 let mut module = ecx.current_expansion.module.with_dir_path(dir_path);
1143 module.mod_path.push(ident);
1144 if let Some(file_path) = file_path {
1145 module.file_path_stack.push(file_path);
1148 let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module));
1149 let orig_dir_ownership =
1150 mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership);
1152 let res = Ok(noop_flat_map(node, collector));
1154 collector.cx.current_expansion.dir_ownership = orig_dir_ownership;
1155 collector.cx.current_expansion.module = orig_module;
1160 struct TraitItemTag;
1161 impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, TraitItemTag> {
1162 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1163 const KIND: AstFragmentKind = AstFragmentKind::TraitItems;
1164 fn to_annotatable(self) -> Annotatable {
1165 Annotatable::TraitItem(self.wrapped)
1167 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1168 fragment.make_trait_items()
1170 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1171 noop_flat_map_assoc_item(self.wrapped, visitor)
1173 fn is_mac_call(&self) -> bool {
1174 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1176 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1177 let item = self.wrapped.into_inner();
1179 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1180 _ => unreachable!(),
1186 impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, ImplItemTag> {
1187 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1188 const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
1189 fn to_annotatable(self) -> Annotatable {
1190 Annotatable::ImplItem(self.wrapped)
1192 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1193 fragment.make_impl_items()
1195 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1196 noop_flat_map_assoc_item(self.wrapped, visitor)
1198 fn is_mac_call(&self) -> bool {
1199 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1201 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1202 let item = self.wrapped.into_inner();
1204 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1205 _ => unreachable!(),
1210 impl InvocationCollectorNode for P<ast::ForeignItem> {
1211 const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
1212 fn to_annotatable(self) -> Annotatable {
1213 Annotatable::ForeignItem(self)
1215 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1216 fragment.make_foreign_items()
1218 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1219 noop_flat_map_foreign_item(self, visitor)
1221 fn is_mac_call(&self) -> bool {
1222 matches!(self.kind, ForeignItemKind::MacCall(..))
1224 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1225 let node = self.into_inner();
1227 ForeignItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1228 _ => unreachable!(),
1233 impl InvocationCollectorNode for ast::Variant {
1234 const KIND: AstFragmentKind = AstFragmentKind::Variants;
1235 fn to_annotatable(self) -> Annotatable {
1236 Annotatable::Variant(self)
1238 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1239 fragment.make_variants()
1241 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1242 noop_flat_map_variant(self, visitor)
1246 impl InvocationCollectorNode for ast::FieldDef {
1247 const KIND: AstFragmentKind = AstFragmentKind::FieldDefs;
1248 fn to_annotatable(self) -> Annotatable {
1249 Annotatable::FieldDef(self)
1251 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1252 fragment.make_field_defs()
1254 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1255 noop_flat_map_field_def(self, visitor)
1259 impl InvocationCollectorNode for ast::PatField {
1260 const KIND: AstFragmentKind = AstFragmentKind::PatFields;
1261 fn to_annotatable(self) -> Annotatable {
1262 Annotatable::PatField(self)
1264 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1265 fragment.make_pat_fields()
1267 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1268 noop_flat_map_pat_field(self, visitor)
1272 impl InvocationCollectorNode for ast::ExprField {
1273 const KIND: AstFragmentKind = AstFragmentKind::ExprFields;
1274 fn to_annotatable(self) -> Annotatable {
1275 Annotatable::ExprField(self)
1277 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1278 fragment.make_expr_fields()
1280 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1281 noop_flat_map_expr_field(self, visitor)
1285 impl InvocationCollectorNode for ast::Param {
1286 const KIND: AstFragmentKind = AstFragmentKind::Params;
1287 fn to_annotatable(self) -> Annotatable {
1288 Annotatable::Param(self)
1290 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1291 fragment.make_params()
1293 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1294 noop_flat_map_param(self, visitor)
1298 impl InvocationCollectorNode for ast::GenericParam {
1299 const KIND: AstFragmentKind = AstFragmentKind::GenericParams;
1300 fn to_annotatable(self) -> Annotatable {
1301 Annotatable::GenericParam(self)
1303 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1304 fragment.make_generic_params()
1306 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1307 noop_flat_map_generic_param(self, visitor)
1311 impl InvocationCollectorNode for ast::Arm {
1312 const KIND: AstFragmentKind = AstFragmentKind::Arms;
1313 fn to_annotatable(self) -> Annotatable {
1314 Annotatable::Arm(self)
1316 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1317 fragment.make_arms()
1319 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1320 noop_flat_map_arm(self, visitor)
1324 impl InvocationCollectorNode for ast::Stmt {
1325 type AttrsTy = ast::AttrVec;
1326 const KIND: AstFragmentKind = AstFragmentKind::Stmts;
1327 fn to_annotatable(self) -> Annotatable {
1328 Annotatable::Stmt(P(self))
1330 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1331 fragment.make_stmts()
1333 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1334 noop_flat_map_stmt(self, visitor)
1336 fn is_mac_call(&self) -> bool {
1338 StmtKind::MacCall(..) => true,
1339 StmtKind::Item(item) => matches!(item.kind, ItemKind::MacCall(..)),
1340 StmtKind::Semi(expr) => matches!(expr.kind, ExprKind::MacCall(..)),
1341 StmtKind::Expr(..) => unreachable!(),
1342 StmtKind::Local(..) | StmtKind::Empty => false,
1345 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1346 // We pull macro invocations (both attributes and fn-like macro calls) out of their
1347 // `StmtKind`s and treat them as statement macro invocations, not as items or expressions.
1348 let (add_semicolon, mac, attrs) = match self.kind {
1349 StmtKind::MacCall(mac) => {
1350 let ast::MacCallStmt { mac, style, attrs, .. } = mac.into_inner();
1351 (style == MacStmtStyle::Semicolon, mac, attrs)
1353 StmtKind::Item(item) => match item.into_inner() {
1354 ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => {
1355 (mac.args.need_semicolon(), mac, attrs)
1357 _ => unreachable!(),
1359 StmtKind::Semi(expr) => match expr.into_inner() {
1360 ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => {
1361 (mac.args.need_semicolon(), mac, attrs)
1363 _ => unreachable!(),
1365 _ => unreachable!(),
1367 (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No })
1369 fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) {
1370 // If this is a macro invocation with a semicolon, then apply that
1371 // semicolon to the final statement produced by expansion.
1372 if matches!(add_semicolon, AddSemicolon::Yes) {
1373 if let Some(stmt) = stmts.pop() {
1374 stmts.push(stmt.add_trailing_semicolon());
1380 impl InvocationCollectorNode for ast::Crate {
1381 type OutputTy = ast::Crate;
1382 const KIND: AstFragmentKind = AstFragmentKind::Crate;
1383 fn to_annotatable(self) -> Annotatable {
1384 Annotatable::Crate(self)
1386 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1387 fragment.make_crate()
1389 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1390 noop_visit_crate(self, visitor)
1394 impl InvocationCollectorNode for P<ast::Ty> {
1395 type OutputTy = P<ast::Ty>;
1396 const KIND: AstFragmentKind = AstFragmentKind::Ty;
1397 fn to_annotatable(self) -> Annotatable {
1400 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1403 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1404 noop_visit_ty(self, visitor)
1406 fn is_mac_call(&self) -> bool {
1407 matches!(self.kind, ast::TyKind::MacCall(..))
1409 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1410 let node = self.into_inner();
1412 TyKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1413 _ => unreachable!(),
1418 impl InvocationCollectorNode for P<ast::Pat> {
1419 type OutputTy = P<ast::Pat>;
1420 const KIND: AstFragmentKind = AstFragmentKind::Pat;
1421 fn to_annotatable(self) -> Annotatable {
1424 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1427 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1428 noop_visit_pat(self, visitor)
1430 fn is_mac_call(&self) -> bool {
1431 matches!(self.kind, PatKind::MacCall(..))
1433 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1434 let node = self.into_inner();
1436 PatKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1437 _ => unreachable!(),
1442 impl InvocationCollectorNode for P<ast::Expr> {
1443 type OutputTy = P<ast::Expr>;
1444 type AttrsTy = ast::AttrVec;
1445 const KIND: AstFragmentKind = AstFragmentKind::Expr;
1446 fn to_annotatable(self) -> Annotatable {
1447 Annotatable::Expr(self)
1449 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1450 fragment.make_expr()
1452 fn descr() -> &'static str {
1455 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1456 noop_visit_expr(self, visitor)
1458 fn is_mac_call(&self) -> bool {
1459 matches!(self.kind, ExprKind::MacCall(..))
1461 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1462 let node = self.into_inner();
1464 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1465 _ => unreachable!(),
1471 impl InvocationCollectorNode for AstNodeWrapper<P<ast::Expr>, OptExprTag> {
1472 type OutputTy = Option<P<ast::Expr>>;
1473 type AttrsTy = ast::AttrVec;
1474 const KIND: AstFragmentKind = AstFragmentKind::OptExpr;
1475 fn to_annotatable(self) -> Annotatable {
1476 Annotatable::Expr(self.wrapped)
1478 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1479 fragment.make_opt_expr()
1481 fn noop_flat_map<V: MutVisitor>(mut self, visitor: &mut V) -> Self::OutputTy {
1482 noop_visit_expr(&mut self.wrapped, visitor);
1485 fn is_mac_call(&self) -> bool {
1486 matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1488 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1489 let node = self.wrapped.into_inner();
1491 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1492 _ => unreachable!(),
1495 fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) {
1496 cfg.maybe_emit_expr_attr_err(&attr);
1500 /// This struct is a hack to workaround unstable of `stmt_expr_attributes`.
1501 /// It can be removed once that feature is stabilized.
1502 struct MethodReceiverTag;
1503 impl DummyAstNode for MethodReceiverTag {
1504 fn dummy() -> MethodReceiverTag {
1508 impl InvocationCollectorNode for AstNodeWrapper<P<ast::Expr>, MethodReceiverTag> {
1509 type OutputTy = Self;
1510 type AttrsTy = ast::AttrVec;
1511 const KIND: AstFragmentKind = AstFragmentKind::MethodReceiverExpr;
1512 fn descr() -> &'static str {
1515 fn to_annotatable(self) -> Annotatable {
1516 Annotatable::Expr(self.wrapped)
1518 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1519 AstNodeWrapper::new(fragment.make_method_receiver_expr(), MethodReceiverTag)
1521 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1522 noop_visit_expr(&mut self.wrapped, visitor)
1524 fn is_mac_call(&self) -> bool {
1525 matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1527 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1528 let node = self.wrapped.into_inner();
1530 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1531 _ => unreachable!(),
1536 struct InvocationCollector<'a, 'b> {
1537 cx: &'a mut ExtCtxt<'b>,
1538 invocations: Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>,
1542 impl<'a, 'b> InvocationCollector<'a, 'b> {
1543 fn cfg(&self) -> StripUnconfigured<'_> {
1545 sess: &self.cx.sess,
1546 features: self.cx.ecfg.features,
1547 config_tokens: false,
1548 lint_node_id: self.cx.current_expansion.lint_node_id,
1552 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1553 let expn_id = LocalExpnId::fresh_empty();
1554 let vis = kind.placeholder_visibility();
1555 self.invocations.push((
1559 expansion_data: ExpansionData {
1561 depth: self.cx.current_expansion.depth + 1,
1562 ..self.cx.current_expansion.clone()
1567 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1570 fn collect_bang(&mut self, mac: P<ast::MacCall>, kind: AstFragmentKind) -> AstFragment {
1571 // cache the macro call span so that it can be
1572 // easily adjusted for incremental compilation
1573 let span = mac.span();
1574 self.collect(kind, InvocationKind::Bang { mac, span })
1579 (attr, pos, derives): (ast::Attribute, usize, Vec<ast::Path>),
1581 kind: AstFragmentKind,
1583 self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
1586 /// If `item` is an attribute invocation, remove the attribute and return it together with
1587 /// its position and derives following it. We have to collect the derives in order to resolve
1588 /// legacy derive helpers (helpers written before derives that introduce them).
1591 item: &mut impl HasAttrs,
1592 ) -> Option<(ast::Attribute, usize, Vec<ast::Path>)> {
1593 let mut attr = None;
1595 let mut cfg_pos = None;
1596 let mut attr_pos = None;
1597 for (pos, attr) in item.attrs().iter().enumerate() {
1598 if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) {
1599 let name = attr.ident().map(|ident| ident.name);
1600 if name == Some(sym::cfg) || name == Some(sym::cfg_attr) {
1601 cfg_pos = Some(pos); // a cfg attr found, no need to search anymore
1603 } else if attr_pos.is_none()
1604 && !name.map_or(false, rustc_feature::is_builtin_attr_name)
1606 attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr
1611 item.visit_attrs(|attrs| {
1612 attr = Some(match (cfg_pos, attr_pos) {
1613 (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()),
1615 let attr = attrs.remove(pos);
1616 let following_derives = attrs[pos..]
1618 .filter(|a| a.has_name(sym::derive))
1619 .flat_map(|a| a.meta_item_list().unwrap_or_default())
1620 .filter_map(|nested_meta| match nested_meta {
1621 NestedMetaItem::MetaItem(ast::MetaItem {
1622 kind: MetaItemKind::Word,
1630 (attr, pos, following_derives)
1639 // Detect use of feature-gated or invalid attributes on macro invocations
1640 // since they will not be detected after macro expansion.
1641 fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
1642 let features = self.cx.ecfg.features.unwrap();
1643 let mut attrs = attrs.iter().peekable();
1644 let mut span: Option<Span> = None;
1645 while let Some(attr) = attrs.next() {
1646 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
1647 validate_attr::check_attr(&self.cx.sess.parse_sess, attr);
1649 let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
1650 span = Some(current_span);
1652 if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
1656 if attr.is_doc_comment() {
1657 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1658 &UNUSED_DOC_COMMENTS,
1660 self.cx.current_expansion.lint_node_id,
1661 "unused doc comment",
1662 BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1664 } else if rustc_attr::is_builtin_attr(attr) {
1665 let attr_name = attr.ident().unwrap().name;
1666 // `#[cfg]` and `#[cfg_attr]` are special - they are
1667 // eagerly evaluated.
1668 if attr_name != sym::cfg && attr_name != sym::cfg_attr {
1669 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1672 self.cx.current_expansion.lint_node_id,
1673 &format!("unused attribute `{}`", attr_name),
1674 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
1676 macro_name: pprust::path_to_string(&call.path),
1677 invoc_span: call.path.span,
1687 node: &mut impl HasAttrs,
1688 attr: ast::Attribute,
1691 let res = self.cfg().cfg_true(&attr);
1693 // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion,
1694 // and some tools like rustdoc and clippy rely on that. Find a way to remove them
1695 // while keeping the tools working.
1696 self.cx.expanded_inert_attrs.mark(&attr);
1697 node.visit_attrs(|attrs| attrs.insert(pos, attr));
1702 fn expand_cfg_attr(&self, node: &mut impl HasAttrs, attr: ast::Attribute, pos: usize) {
1703 node.visit_attrs(|attrs| {
1704 // Repeated `insert` calls is inefficient, but the number of
1705 // insertions is almost always 0 or 1 in practice.
1706 for cfg in self.cfg().expand_cfg_attr(attr, false).into_iter().rev() {
1707 attrs.insert(pos, cfg)
1712 fn flat_map_node<Node: InvocationCollectorNode<OutputTy: Default>>(
1715 ) -> Node::OutputTy {
1717 return match self.take_first_attr(&mut node) {
1718 Some((attr, pos, derives)) => match attr.name_or_empty() {
1720 if self.expand_cfg_true(&mut node, attr, pos) {
1726 self.expand_cfg_attr(&mut node, attr, pos);
1730 Node::pre_flat_map_node_collect_attr(&self.cfg(), &attr);
1731 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1735 None if node.is_mac_call() => {
1736 let (mac, attrs, add_semicolon) = node.take_mac_call();
1737 self.check_attributes(&attrs, &mac);
1738 let mut res = self.collect_bang(mac, Node::KIND).make_ast::<Node>();
1739 Node::post_flat_map_node_collect_bang(&mut res, add_semicolon);
1743 match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| {
1744 assign_id!(this, node.node_id_mut(), || node.noop_flat_map(this))
1746 Ok(output) => output,
1747 Err(returned_node) => {
1748 node = returned_node;
1757 fn visit_node<Node: InvocationCollectorNode<OutputTy = Node> + DummyAstNode>(
1762 return match self.take_first_attr(node) {
1763 Some((attr, pos, derives)) => match attr.name_or_empty() {
1765 let span = attr.span;
1766 if self.expand_cfg_true(node, attr, pos) {
1770 format!("removing {} is not supported in this position", Node::descr());
1771 self.cx.span_err(span, &msg);
1775 self.expand_cfg_attr(node, attr, pos);
1778 _ => visit_clobber(node, |node| {
1779 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1783 None if node.is_mac_call() => {
1784 visit_clobber(node, |node| {
1785 // Do not clobber unless it's actually a macro (uncommon case).
1786 let (mac, attrs, _) = node.take_mac_call();
1787 self.check_attributes(&attrs, &mac);
1788 self.collect_bang(mac, Node::KIND).make_ast::<Node>()
1792 assign_id!(self, node.node_id_mut(), || node.noop_visit(self))
1799 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1800 fn flat_map_item(&mut self, node: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1801 self.flat_map_node(node)
1804 fn flat_map_trait_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1805 self.flat_map_node(AstNodeWrapper::new(node, TraitItemTag))
1808 fn flat_map_impl_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1809 self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag))
1812 fn flat_map_foreign_item(
1814 node: P<ast::ForeignItem>,
1815 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1816 self.flat_map_node(node)
1819 fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1820 self.flat_map_node(node)
1823 fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
1824 self.flat_map_node(node)
1827 fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
1828 self.flat_map_node(node)
1831 fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
1832 self.flat_map_node(node)
1835 fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> {
1836 self.flat_map_node(node)
1839 fn flat_map_generic_param(
1841 node: ast::GenericParam,
1842 ) -> SmallVec<[ast::GenericParam; 1]> {
1843 self.flat_map_node(node)
1846 fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1847 self.flat_map_node(node)
1850 fn flat_map_stmt(&mut self, node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1851 // FIXME: invocations in semicolon-less expressions positions are expanded as expressions,
1852 // changing that requires some compatibility measures.
1854 // The only way that we can end up with a `MacCall` expression statement,
1855 // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the
1856 // trailing expression in a block (e.g. `fn foo() { my_macro!() }`).
1857 // Record this information, so that we can report a more specific
1858 // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed.
1859 // See #78991 for an investigation of treating macros in this position
1860 // as statements, rather than expressions, during parsing.
1861 return match &node.kind {
1862 StmtKind::Expr(expr)
1863 if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) =>
1865 self.cx.current_expansion.is_trailing_mac = true;
1866 // Don't use `assign_id` for this statement - it may get removed
1867 // entirely due to a `#[cfg]` on the contained expression
1868 let res = noop_flat_map_stmt(node, self);
1869 self.cx.current_expansion.is_trailing_mac = false;
1872 _ => noop_flat_map_stmt(node, self),
1876 self.flat_map_node(node)
1879 fn visit_crate(&mut self, node: &mut ast::Crate) {
1880 self.visit_node(node)
1883 fn visit_ty(&mut self, node: &mut P<ast::Ty>) {
1884 self.visit_node(node)
1887 fn visit_pat(&mut self, node: &mut P<ast::Pat>) {
1888 self.visit_node(node)
1891 fn visit_expr(&mut self, node: &mut P<ast::Expr>) {
1892 // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`.
1893 if let Some(attr) = node.attrs.first() {
1894 self.cfg().maybe_emit_expr_attr_err(attr);
1896 self.visit_node(node)
1899 fn visit_method_receiver_expr(&mut self, node: &mut P<ast::Expr>) {
1900 visit_clobber(node, |node| {
1901 let mut wrapper = AstNodeWrapper::new(node, MethodReceiverTag);
1902 self.visit_node(&mut wrapper);
1907 fn filter_map_expr(&mut self, node: P<ast::Expr>) -> Option<P<ast::Expr>> {
1908 self.flat_map_node(AstNodeWrapper::new(node, OptExprTag))
1911 fn visit_block(&mut self, node: &mut P<ast::Block>) {
1912 let orig_dir_ownership = mem::replace(
1913 &mut self.cx.current_expansion.dir_ownership,
1914 DirOwnership::UnownedViaBlock,
1916 noop_visit_block(node, self);
1917 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1920 fn visit_id(&mut self, id: &mut NodeId) {
1921 // We may have already assigned a `NodeId`
1922 // by calling `assign_id`
1923 if self.monotonic && *id == ast::DUMMY_NODE_ID {
1924 *id = self.cx.resolver.next_node_id();
1929 pub struct ExpansionConfig<'feat> {
1930 pub crate_name: String,
1931 pub features: Option<&'feat Features>,
1932 pub recursion_limit: Limit,
1933 pub trace_mac: bool,
1934 /// If false, strip `#[test]` nodes
1935 pub should_test: bool,
1936 /// If true, use verbose debugging for `proc_macro::Span`
1937 pub span_debug: bool,
1938 /// If true, show backtraces for proc-macro panics
1939 pub proc_macro_backtrace: bool,
1942 impl<'feat> ExpansionConfig<'feat> {
1943 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1947 recursion_limit: Limit::new(1024),
1951 proc_macro_backtrace: false,
1955 fn proc_macro_hygiene(&self) -> bool {
1956 self.features.map_or(false, |features| features.proc_macro_hygiene)