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, AstNodeWrapper, AttrStyle, AttrVec, ExprKind, ForeignItemKind};
15 use rustc_ast::{HasAttrs, HasNodeId};
16 use rustc_ast::{Inline, ItemKind, MacArgs, 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>,
344 impl InvocationKind {
345 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
346 // HACK: For unnamed fields placeholders should have the same visibility as the actual
347 // fields because for tuple structs/variants resolve determines visibilities of their
348 // constructor using these field visibilities before attributes on them are expanded.
349 // The assumption is that the attribute expansion cannot change field visibilities,
350 // and it holds because only inert attributes are supported in this position.
352 InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
353 | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
354 if field.ident.is_none() =>
356 Some(field.vis.clone())
364 pub fn span(&self) -> Span {
366 InvocationKind::Bang { span, .. } => *span,
367 InvocationKind::Attr { attr, .. } => attr.span,
368 InvocationKind::Derive { path, .. } => path.span,
373 pub struct MacroExpander<'a, 'b> {
374 pub cx: &'a mut ExtCtxt<'b>,
375 monotonic: bool, // cf. `cx.monotonic_expander()`
378 impl<'a, 'b> MacroExpander<'a, 'b> {
379 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
380 MacroExpander { cx, monotonic }
383 pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate {
384 let file_path = match self.cx.source_map().span_to_filename(krate.spans.inner_span) {
385 FileName::Real(name) => name
387 .expect("attempting to resolve a file path in an external file"),
388 other => PathBuf::from(other.prefer_local().to_string()),
390 let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
391 self.cx.root_path = dir_path.clone();
392 self.cx.current_expansion.module = Rc::new(ModuleData {
393 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
394 file_path_stack: vec![file_path],
397 let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate();
398 assert_eq!(krate.id, ast::CRATE_NODE_ID);
399 self.cx.trace_macros_diag();
403 // Recursively expand all macro invocations in this AST fragment.
404 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
405 let orig_expansion_data = self.cx.current_expansion.clone();
406 let orig_force_mode = self.cx.force_mode;
408 // Collect all macro invocations and replace them with placeholders.
409 let (mut fragment_with_placeholders, mut invocations) =
410 self.collect_invocations(input_fragment, &[]);
412 // Optimization: if we resolve all imports now,
413 // we'll be able to immediately resolve most of imported macros.
414 self.resolve_imports();
416 // Resolve paths in all invocations and produce output expanded fragments for them, but
417 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
418 // The output fragments also go through expansion recursively until no invocations are left.
419 // Unresolved macros produce dummy outputs as a recovery measure.
420 invocations.reverse();
421 let mut expanded_fragments = Vec::new();
422 let mut undetermined_invocations = Vec::new();
423 let (mut progress, mut force) = (false, !self.monotonic);
425 let Some((invoc, ext)) = invocations.pop() else {
426 self.resolve_imports();
427 if undetermined_invocations.is_empty() {
430 invocations = mem::take(&mut undetermined_invocations);
431 force = !mem::replace(&mut progress, false);
432 if force && self.monotonic {
433 self.cx.sess.delay_span_bug(
434 invocations.last().unwrap().0.span(),
435 "expansion entered force mode without producing any errors",
441 let ext = match ext {
444 let eager_expansion_root = if self.monotonic {
445 invoc.expansion_data.id
447 orig_expansion_data.id
449 match self.cx.resolver.resolve_macro_invocation(
451 eager_expansion_root,
455 Err(Indeterminate) => {
456 // Cannot resolve, will retry this invocation later.
457 undetermined_invocations.push((invoc, None));
464 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
465 let depth = depth - orig_expansion_data.depth;
466 self.cx.current_expansion = invoc.expansion_data.clone();
467 self.cx.force_mode = force;
469 let fragment_kind = invoc.fragment_kind;
470 let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) {
471 ExpandResult::Ready(fragment) => {
472 let mut derive_invocations = Vec::new();
473 let derive_placeholders = self
476 .take_derive_resolutions(expn_id)
478 derive_invocations.reserve(derives.len());
481 .map(|(path, item, _exts)| {
482 // FIXME: Consider using the derive resolutions (`_exts`)
483 // instead of enqueuing the derives to be resolved again later.
484 let expn_id = LocalExpnId::fresh_empty();
485 derive_invocations.push((
487 kind: InvocationKind::Derive { path, item },
489 expansion_data: ExpansionData {
491 ..self.cx.current_expansion.clone()
496 NodeId::placeholder_from_expn_id(expn_id)
500 .unwrap_or_default();
502 let (fragment, collected_invocations) =
503 self.collect_invocations(fragment, &derive_placeholders);
504 // We choose to expand any derive invocations associated with this macro invocation
505 // *before* any macro invocations collected from the output fragment
506 derive_invocations.extend(collected_invocations);
507 (fragment, derive_invocations)
509 ExpandResult::Retry(invoc) => {
513 "expansion entered force mode but is still stuck",
516 // Cannot expand, will retry this invocation later.
517 undetermined_invocations.push((invoc, Some(ext)));
524 if expanded_fragments.len() < depth {
525 expanded_fragments.push(Vec::new());
527 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
528 invocations.extend(new_invocations.into_iter().rev());
531 self.cx.current_expansion = orig_expansion_data;
532 self.cx.force_mode = orig_force_mode;
534 // Finally incorporate all the expanded macros into the input AST fragment.
535 let mut placeholder_expander = PlaceholderExpander::default();
536 while let Some(expanded_fragments) = expanded_fragments.pop() {
537 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
539 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
542 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
543 fragment_with_placeholders
546 fn resolve_imports(&mut self) {
548 self.cx.resolver.resolve_imports();
552 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
553 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
554 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
555 /// prepares data for resolving paths of macro invocations.
556 fn collect_invocations(
558 mut fragment: AstFragment,
559 extra_placeholders: &[NodeId],
560 ) -> (AstFragment, Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>) {
561 // Resolve `$crate`s in the fragment for pretty-printing.
562 self.cx.resolver.resolve_dollar_crates();
564 let mut invocations = {
565 let mut collector = InvocationCollector {
566 // Non-derive macro invocations cannot see the results of cfg expansion - they
567 // will either be removed along with the item, or invoked before the cfg/cfg_attr
568 // attribute is expanded. Therefore, we don't need to configure the tokens
569 // Derive macros *can* see the results of cfg-expansion - they are handled
570 // specially in `fully_expand_fragment`
572 invocations: Vec::new(),
573 monotonic: self.monotonic,
575 fragment.mut_visit_with(&mut collector);
576 fragment.add_placeholders(extra_placeholders);
577 collector.invocations
583 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
585 if self.cx.sess.opts.unstable_opts.incremental_relative_spans {
586 for (invoc, _) in invocations.iter_mut() {
587 let expn_id = invoc.expansion_data.id;
588 let parent_def = self.cx.resolver.invocation_parent(expn_id);
589 let span = match &mut invoc.kind {
590 InvocationKind::Bang { ref mut span, .. } => span,
591 InvocationKind::Attr { attr, .. } => &mut attr.span,
592 InvocationKind::Derive { path, .. } => &mut path.span,
594 *span = span.with_parent(Some(parent_def));
599 (fragment, invocations)
602 fn error_recursion_limit_reached(&mut self) {
603 let expn_data = self.cx.current_expansion.id.expn_data();
604 let suggested_limit = match self.cx.ecfg.recursion_limit {
605 Limit(0) => Limit(2),
611 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
614 "consider increasing the recursion limit by adding a \
615 `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
616 suggested_limit, self.cx.ecfg.crate_name,
619 self.cx.trace_macros_diag();
622 /// A macro's expansion does not fit in this fragment kind.
623 /// For example, a non-type macro in a type position.
624 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
626 "non-{kind} macro in {kind} position: {path}",
628 path = pprust::path_to_string(&mac.path),
630 self.cx.span_err(span, &msg);
631 self.cx.trace_macros_diag();
637 ext: &SyntaxExtensionKind,
638 ) -> ExpandResult<AstFragment, Invocation> {
639 let recursion_limit =
640 self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
641 if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
642 if self.cx.reduced_recursion_limit.is_none() {
643 self.error_recursion_limit_reached();
646 // Reduce the recursion limit by half each time it triggers.
647 self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
649 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
652 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
653 ExpandResult::Ready(match invoc.kind {
654 InvocationKind::Bang { mac, .. } => match ext {
655 SyntaxExtensionKind::Bang(expander) => {
656 let Ok(tok_result) = expander.expand(self.cx, span, mac.args.inner_tokens()) else {
657 return ExpandResult::Ready(fragment_kind.dummy(span));
659 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
661 SyntaxExtensionKind::LegacyBang(expander) => {
662 let prev = self.cx.current_expansion.prior_type_ascription;
663 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
664 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
665 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
668 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
669 fragment_kind.dummy(span)
671 self.cx.current_expansion.prior_type_ascription = prev;
676 InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
677 SyntaxExtensionKind::Attr(expander) => {
678 self.gate_proc_macro_input(&item);
679 self.gate_proc_macro_attr_item(span, &item);
680 let tokens = match &item {
681 // FIXME: Collect tokens and use them instead of generating
682 // fake ones. These are unstable, so it needs to be
683 // fixed prior to stabilization
684 // Fake tokens when we are invoking an inner attribute, and
685 // we are invoking it on an out-of-line module or crate.
686 Annotatable::Crate(krate) => rustc_parse::fake_token_stream_for_crate(
687 &self.cx.sess.parse_sess,
690 Annotatable::Item(item_inner)
691 if matches!(attr.style, AttrStyle::Inner)
696 ModKind::Unloaded | ModKind::Loaded(_, Inline::No, _),
700 rustc_parse::fake_token_stream_for_item(
701 &self.cx.sess.parse_sess,
705 _ => item.to_tokens(),
707 let attr_item = attr.unwrap_normal_item();
708 if let MacArgs::Eq(..) = attr_item.args {
709 self.cx.span_err(span, "key-value macro attributes are not supported");
711 let inner_tokens = attr_item.args.inner_tokens();
712 let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) else {
713 return ExpandResult::Ready(fragment_kind.dummy(span));
715 self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
717 SyntaxExtensionKind::LegacyAttr(expander) => {
718 match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) {
720 let items = match expander.expand(self.cx, span, &meta, item) {
721 ExpandResult::Ready(items) => items,
722 ExpandResult::Retry(item) => {
723 // Reassemble the original invocation for retrying.
724 return ExpandResult::Retry(Invocation {
725 kind: InvocationKind::Attr { attr, pos, item, derives },
730 if fragment_kind == AstFragmentKind::Expr && items.is_empty() {
732 "removing an expression is not supported in this position";
733 self.cx.span_err(span, msg);
734 fragment_kind.dummy(span)
736 fragment_kind.expect_from_annotatables(items)
741 fragment_kind.dummy(span)
745 SyntaxExtensionKind::NonMacroAttr => {
746 self.cx.expanded_inert_attrs.mark(&attr);
747 item.visit_attrs(|attrs| attrs.insert(pos, attr));
748 fragment_kind.expect_from_annotatables(iter::once(item))
752 InvocationKind::Derive { path, item } => match ext {
753 SyntaxExtensionKind::Derive(expander)
754 | SyntaxExtensionKind::LegacyDerive(expander) => {
755 if let SyntaxExtensionKind::Derive(..) = ext {
756 self.gate_proc_macro_input(&item);
758 let meta = ast::MetaItem { kind: MetaItemKind::Word, span, path };
759 let items = match expander.expand(self.cx, span, &meta, item) {
760 ExpandResult::Ready(items) => items,
761 ExpandResult::Retry(item) => {
762 // Reassemble the original invocation for retrying.
763 return ExpandResult::Retry(Invocation {
764 kind: InvocationKind::Derive { path: meta.path, item },
769 fragment_kind.expect_from_annotatables(items)
776 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
777 let kind = match item {
779 | Annotatable::TraitItem(_)
780 | Annotatable::ImplItem(_)
781 | Annotatable::ForeignItem(_)
782 | Annotatable::Crate(..) => return,
783 Annotatable::Stmt(stmt) => {
784 // Attributes are stable on item statements,
785 // but unstable on all other kinds of statements
791 Annotatable::Expr(_) => "expressions",
793 | Annotatable::ExprField(..)
794 | Annotatable::PatField(..)
795 | Annotatable::GenericParam(..)
796 | Annotatable::Param(..)
797 | Annotatable::FieldDef(..)
798 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
800 if self.cx.ecfg.proc_macro_hygiene() {
804 &self.cx.sess.parse_sess,
805 sym::proc_macro_hygiene,
807 &format!("custom attributes cannot be applied to {}", kind),
812 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
813 struct GateProcMacroInput<'a> {
814 parse_sess: &'a ParseSess,
817 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
818 fn visit_item(&mut self, item: &'ast ast::Item) {
820 ItemKind::Mod(_, mod_kind)
821 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
825 sym::proc_macro_hygiene,
827 "non-inline modules in proc macro input are unstable",
834 visit::walk_item(self, item);
838 if !self.cx.ecfg.proc_macro_hygiene() {
840 .visit_with(&mut GateProcMacroInput { parse_sess: &self.cx.sess.parse_sess });
844 fn parse_ast_fragment(
847 kind: AstFragmentKind,
851 let mut parser = self.cx.new_parser_from_tts(toks);
852 match parse_ast_fragment(&mut parser, kind) {
854 ensure_complete_parse(&mut parser, path, kind.name(), span);
858 if err.span.is_dummy() {
861 annotate_err_with_kind(&mut err, kind, span);
863 self.cx.trace_macros_diag();
870 pub fn parse_ast_fragment<'a>(
871 this: &mut Parser<'a>,
872 kind: AstFragmentKind,
873 ) -> PResult<'a, AstFragment> {
875 AstFragmentKind::Items => {
876 let mut items = SmallVec::new();
877 while let Some(item) = this.parse_item(ForceCollect::No)? {
880 AstFragment::Items(items)
882 AstFragmentKind::TraitItems => {
883 let mut items = SmallVec::new();
884 while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
887 AstFragment::TraitItems(items)
889 AstFragmentKind::ImplItems => {
890 let mut items = SmallVec::new();
891 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
894 AstFragment::ImplItems(items)
896 AstFragmentKind::ForeignItems => {
897 let mut items = SmallVec::new();
898 while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
901 AstFragment::ForeignItems(items)
903 AstFragmentKind::Stmts => {
904 let mut stmts = SmallVec::new();
905 // Won't make progress on a `}`.
906 while this.token != token::Eof && this.token != token::CloseDelim(Delimiter::Brace) {
907 if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
911 AstFragment::Stmts(stmts)
913 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
914 AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(this.parse_expr()?),
915 AstFragmentKind::OptExpr => {
916 if this.token != token::Eof {
917 AstFragment::OptExpr(Some(this.parse_expr()?))
919 AstFragment::OptExpr(None)
922 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
923 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat_allow_top_alt(
927 CommaRecoveryMode::LikelyTuple,
929 AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?),
930 AstFragmentKind::Arms
931 | AstFragmentKind::ExprFields
932 | AstFragmentKind::PatFields
933 | AstFragmentKind::GenericParams
934 | AstFragmentKind::Params
935 | AstFragmentKind::FieldDefs
936 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
940 pub fn ensure_complete_parse<'a>(
941 this: &mut Parser<'a>,
942 macro_path: &ast::Path,
946 if this.token != token::Eof {
947 let token = pprust::token_to_string(&this.token);
948 let msg = format!("macro expansion ignores token `{}` and any following", token);
949 // Avoid emitting backtrace info twice.
950 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
951 let mut err = this.struct_span_err(def_site_span, &msg);
952 err.span_label(span, "caused by the macro expansion here");
954 "the usage of `{}!` is likely invalid in {} context",
955 pprust::path_to_string(macro_path),
960 let semi_span = this.sess.source_map().next_point(span);
961 match this.sess.source_map().span_to_snippet(semi_span) {
962 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
965 "you might be missing a semicolon here",
967 Applicability::MaybeIncorrect,
976 /// Wraps a call to `noop_visit_*` / `noop_flat_map_*`
977 /// for an AST node that supports attributes
978 /// (see the `Annotatable` enum)
979 /// This method assigns a `NodeId`, and sets that `NodeId`
980 /// as our current 'lint node id'. If a macro call is found
981 /// inside this AST node, we will use this AST node's `NodeId`
982 /// to emit lints associated with that macro (allowing
983 /// `#[allow]` / `#[deny]` to be applied close to
984 /// the macro invocation).
986 /// Do *not* call this for a macro AST node
987 /// (e.g. `ExprKind::MacCall`) - we cannot emit lints
988 /// at these AST nodes, since they are removed and
989 /// replaced with the result of macro expansion.
991 /// All other `NodeId`s are assigned by `visit_id`.
992 /// * `self` is the 'self' parameter for the current method,
993 /// * `id` is a mutable reference to the `NodeId` field
994 /// of the current AST node.
995 /// * `closure` is a closure that executes the
996 /// `noop_visit_*` / `noop_flat_map_*` method
997 /// for the current AST node.
998 macro_rules! assign_id {
999 ($self:ident, $id:expr, $closure:expr) => {{
1000 let old_id = $self.cx.current_expansion.lint_node_id;
1001 if $self.monotonic {
1002 debug_assert_eq!(*$id, ast::DUMMY_NODE_ID);
1003 let new_id = $self.cx.resolver.next_node_id();
1005 $self.cx.current_expansion.lint_node_id = new_id;
1007 let ret = ($closure)();
1008 $self.cx.current_expansion.lint_node_id = old_id;
1018 /// A trait implemented for all `AstFragment` nodes and providing all pieces
1019 /// of functionality used by `InvocationCollector`.
1020 trait InvocationCollectorNode: HasAttrs + HasNodeId + Sized {
1021 type OutputTy = SmallVec<[Self; 1]>;
1022 type AttrsTy: Deref<Target = [ast::Attribute]> = ast::AttrVec;
1023 const KIND: AstFragmentKind;
1024 fn to_annotatable(self) -> Annotatable;
1025 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy;
1026 fn descr() -> &'static str {
1029 fn noop_flat_map<V: MutVisitor>(self, _visitor: &mut V) -> Self::OutputTy {
1032 fn noop_visit<V: MutVisitor>(&mut self, _visitor: &mut V) {
1035 fn is_mac_call(&self) -> bool {
1038 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1041 fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {}
1042 fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) {
1044 fn wrap_flat_map_node_noop_flat_map(
1046 collector: &mut InvocationCollector<'_, '_>,
1047 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1048 ) -> Result<Self::OutputTy, Self> {
1049 Ok(noop_flat_map(node, collector))
1053 impl InvocationCollectorNode for P<ast::Item> {
1054 const KIND: AstFragmentKind = AstFragmentKind::Items;
1055 fn to_annotatable(self) -> Annotatable {
1056 Annotatable::Item(self)
1058 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1059 fragment.make_items()
1061 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1062 noop_flat_map_item(self, visitor)
1064 fn is_mac_call(&self) -> bool {
1065 matches!(self.kind, ItemKind::MacCall(..))
1067 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1068 let node = self.into_inner();
1070 ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1071 _ => unreachable!(),
1074 fn wrap_flat_map_node_noop_flat_map(
1076 collector: &mut InvocationCollector<'_, '_>,
1077 noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1078 ) -> Result<Self::OutputTy, Self> {
1079 if !matches!(node.kind, ItemKind::Mod(..)) {
1080 return Ok(noop_flat_map(node, collector));
1083 // Work around borrow checker not seeing through `P`'s deref.
1084 let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs));
1085 let ItemKind::Mod(_, mod_kind) = &mut node.kind else {
1089 let ecx = &mut collector.cx;
1090 let (file_path, dir_path, dir_ownership) = match mod_kind {
1091 ModKind::Loaded(_, inline, _) => {
1092 // Inline `mod foo { ... }`, but we still need to push directories.
1093 let (dir_path, dir_ownership) = mod_dir_path(
1097 &ecx.current_expansion.module,
1098 ecx.current_expansion.dir_ownership,
1102 (None, dir_path, dir_ownership)
1104 ModKind::Unloaded => {
1105 // We have an outline `mod foo;` so we need to parse the file.
1106 let old_attrs_len = attrs.len();
1107 let ParsedExternalMod { items, spans, file_path, dir_path, dir_ownership } =
1112 &ecx.current_expansion.module,
1113 ecx.current_expansion.dir_ownership,
1117 if let Some(lint_store) = ecx.lint_store {
1118 lint_store.pre_expansion_lint(
1120 ecx.resolver.registered_tools(),
1121 ecx.current_expansion.lint_node_id,
1124 ident.name.as_str(),
1128 *mod_kind = ModKind::Loaded(items, Inline::No, spans);
1130 if node.attrs.len() > old_attrs_len {
1131 // If we loaded an out-of-line module and added some inner attributes,
1132 // then we need to re-configure it and re-collect attributes for
1133 // resolution and expansion.
1136 (Some(file_path), dir_path, dir_ownership)
1140 // Set the module info before we flat map.
1141 let mut module = ecx.current_expansion.module.with_dir_path(dir_path);
1142 module.mod_path.push(ident);
1143 if let Some(file_path) = file_path {
1144 module.file_path_stack.push(file_path);
1147 let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module));
1148 let orig_dir_ownership =
1149 mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership);
1151 let res = Ok(noop_flat_map(node, collector));
1153 collector.cx.current_expansion.dir_ownership = orig_dir_ownership;
1154 collector.cx.current_expansion.module = orig_module;
1159 struct TraitItemTag;
1160 impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, TraitItemTag> {
1161 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1162 const KIND: AstFragmentKind = AstFragmentKind::TraitItems;
1163 fn to_annotatable(self) -> Annotatable {
1164 Annotatable::TraitItem(self.wrapped)
1166 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1167 fragment.make_trait_items()
1169 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1170 noop_flat_map_assoc_item(self.wrapped, visitor)
1172 fn is_mac_call(&self) -> bool {
1173 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1175 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1176 let item = self.wrapped.into_inner();
1178 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1179 _ => unreachable!(),
1185 impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, ImplItemTag> {
1186 type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1187 const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
1188 fn to_annotatable(self) -> Annotatable {
1189 Annotatable::ImplItem(self.wrapped)
1191 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1192 fragment.make_impl_items()
1194 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1195 noop_flat_map_assoc_item(self.wrapped, visitor)
1197 fn is_mac_call(&self) -> bool {
1198 matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1200 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1201 let item = self.wrapped.into_inner();
1203 AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1204 _ => unreachable!(),
1209 impl InvocationCollectorNode for P<ast::ForeignItem> {
1210 const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
1211 fn to_annotatable(self) -> Annotatable {
1212 Annotatable::ForeignItem(self)
1214 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1215 fragment.make_foreign_items()
1217 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1218 noop_flat_map_foreign_item(self, visitor)
1220 fn is_mac_call(&self) -> bool {
1221 matches!(self.kind, ForeignItemKind::MacCall(..))
1223 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1224 let node = self.into_inner();
1226 ForeignItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1227 _ => unreachable!(),
1232 impl InvocationCollectorNode for ast::Variant {
1233 const KIND: AstFragmentKind = AstFragmentKind::Variants;
1234 fn to_annotatable(self) -> Annotatable {
1235 Annotatable::Variant(self)
1237 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1238 fragment.make_variants()
1240 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1241 noop_flat_map_variant(self, visitor)
1245 impl InvocationCollectorNode for ast::FieldDef {
1246 const KIND: AstFragmentKind = AstFragmentKind::FieldDefs;
1247 fn to_annotatable(self) -> Annotatable {
1248 Annotatable::FieldDef(self)
1250 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1251 fragment.make_field_defs()
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 noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1267 noop_flat_map_pat_field(self, visitor)
1271 impl InvocationCollectorNode for ast::ExprField {
1272 const KIND: AstFragmentKind = AstFragmentKind::ExprFields;
1273 fn to_annotatable(self) -> Annotatable {
1274 Annotatable::ExprField(self)
1276 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1277 fragment.make_expr_fields()
1279 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1280 noop_flat_map_expr_field(self, visitor)
1284 impl InvocationCollectorNode for ast::Param {
1285 const KIND: AstFragmentKind = AstFragmentKind::Params;
1286 fn to_annotatable(self) -> Annotatable {
1287 Annotatable::Param(self)
1289 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1290 fragment.make_params()
1292 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1293 noop_flat_map_param(self, visitor)
1297 impl InvocationCollectorNode for ast::GenericParam {
1298 const KIND: AstFragmentKind = AstFragmentKind::GenericParams;
1299 fn to_annotatable(self) -> Annotatable {
1300 Annotatable::GenericParam(self)
1302 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1303 fragment.make_generic_params()
1305 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1306 noop_flat_map_generic_param(self, visitor)
1310 impl InvocationCollectorNode for ast::Arm {
1311 const KIND: AstFragmentKind = AstFragmentKind::Arms;
1312 fn to_annotatable(self) -> Annotatable {
1313 Annotatable::Arm(self)
1315 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1316 fragment.make_arms()
1318 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1319 noop_flat_map_arm(self, visitor)
1323 impl InvocationCollectorNode for ast::Stmt {
1324 type AttrsTy = ast::AttrVec;
1325 const KIND: AstFragmentKind = AstFragmentKind::Stmts;
1326 fn to_annotatable(self) -> Annotatable {
1327 Annotatable::Stmt(P(self))
1329 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1330 fragment.make_stmts()
1332 fn noop_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1333 noop_flat_map_stmt(self, visitor)
1335 fn is_mac_call(&self) -> bool {
1337 StmtKind::MacCall(..) => true,
1338 StmtKind::Item(item) => matches!(item.kind, ItemKind::MacCall(..)),
1339 StmtKind::Semi(expr) => matches!(expr.kind, ExprKind::MacCall(..)),
1340 StmtKind::Expr(..) => unreachable!(),
1341 StmtKind::Local(..) | StmtKind::Empty => false,
1344 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1345 // We pull macro invocations (both attributes and fn-like macro calls) out of their
1346 // `StmtKind`s and treat them as statement macro invocations, not as items or expressions.
1347 let (add_semicolon, mac, attrs) = match self.kind {
1348 StmtKind::MacCall(mac) => {
1349 let ast::MacCallStmt { mac, style, attrs, .. } = mac.into_inner();
1350 (style == MacStmtStyle::Semicolon, mac, attrs)
1352 StmtKind::Item(item) => match item.into_inner() {
1353 ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => {
1354 (mac.args.need_semicolon(), mac, attrs)
1356 _ => unreachable!(),
1358 StmtKind::Semi(expr) => match expr.into_inner() {
1359 ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => {
1360 (mac.args.need_semicolon(), mac, attrs)
1362 _ => unreachable!(),
1364 _ => unreachable!(),
1366 (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No })
1368 fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) {
1369 // If this is a macro invocation with a semicolon, then apply that
1370 // semicolon to the final statement produced by expansion.
1371 if matches!(add_semicolon, AddSemicolon::Yes) {
1372 if let Some(stmt) = stmts.pop() {
1373 stmts.push(stmt.add_trailing_semicolon());
1379 impl InvocationCollectorNode for ast::Crate {
1380 type OutputTy = ast::Crate;
1381 const KIND: AstFragmentKind = AstFragmentKind::Crate;
1382 fn to_annotatable(self) -> Annotatable {
1383 Annotatable::Crate(self)
1385 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1386 fragment.make_crate()
1388 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1389 noop_visit_crate(self, visitor)
1393 impl InvocationCollectorNode for P<ast::Ty> {
1394 type OutputTy = P<ast::Ty>;
1395 const KIND: AstFragmentKind = AstFragmentKind::Ty;
1396 fn to_annotatable(self) -> Annotatable {
1399 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1402 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1403 noop_visit_ty(self, visitor)
1405 fn is_mac_call(&self) -> bool {
1406 matches!(self.kind, ast::TyKind::MacCall(..))
1408 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1409 let node = self.into_inner();
1411 TyKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1412 _ => unreachable!(),
1417 impl InvocationCollectorNode for P<ast::Pat> {
1418 type OutputTy = P<ast::Pat>;
1419 const KIND: AstFragmentKind = AstFragmentKind::Pat;
1420 fn to_annotatable(self) -> Annotatable {
1423 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1426 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1427 noop_visit_pat(self, visitor)
1429 fn is_mac_call(&self) -> bool {
1430 matches!(self.kind, PatKind::MacCall(..))
1432 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1433 let node = self.into_inner();
1435 PatKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1436 _ => unreachable!(),
1441 impl InvocationCollectorNode for P<ast::Expr> {
1442 type OutputTy = P<ast::Expr>;
1443 type AttrsTy = ast::AttrVec;
1444 const KIND: AstFragmentKind = AstFragmentKind::Expr;
1445 fn to_annotatable(self) -> Annotatable {
1446 Annotatable::Expr(self)
1448 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1449 fragment.make_expr()
1451 fn descr() -> &'static str {
1454 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1455 noop_visit_expr(self, visitor)
1457 fn is_mac_call(&self) -> bool {
1458 matches!(self.kind, ExprKind::MacCall(..))
1460 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1461 let node = self.into_inner();
1463 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1464 _ => unreachable!(),
1470 impl InvocationCollectorNode for AstNodeWrapper<P<ast::Expr>, OptExprTag> {
1471 type OutputTy = Option<P<ast::Expr>>;
1472 type AttrsTy = ast::AttrVec;
1473 const KIND: AstFragmentKind = AstFragmentKind::OptExpr;
1474 fn to_annotatable(self) -> Annotatable {
1475 Annotatable::Expr(self.wrapped)
1477 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1478 fragment.make_opt_expr()
1480 fn noop_flat_map<V: MutVisitor>(mut self, visitor: &mut V) -> Self::OutputTy {
1481 noop_visit_expr(&mut self.wrapped, visitor);
1484 fn is_mac_call(&self) -> bool {
1485 matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1487 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1488 let node = self.wrapped.into_inner();
1490 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1491 _ => unreachable!(),
1494 fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) {
1495 cfg.maybe_emit_expr_attr_err(&attr);
1499 /// This struct is a hack to workaround unstable of `stmt_expr_attributes`.
1500 /// It can be removed once that feature is stabilized.
1501 struct MethodReceiverTag;
1502 impl DummyAstNode for MethodReceiverTag {
1503 fn dummy() -> MethodReceiverTag {
1507 impl InvocationCollectorNode for AstNodeWrapper<P<ast::Expr>, MethodReceiverTag> {
1508 type OutputTy = Self;
1509 type AttrsTy = ast::AttrVec;
1510 const KIND: AstFragmentKind = AstFragmentKind::MethodReceiverExpr;
1511 fn descr() -> &'static str {
1514 fn to_annotatable(self) -> Annotatable {
1515 Annotatable::Expr(self.wrapped)
1517 fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1518 AstNodeWrapper::new(fragment.make_method_receiver_expr(), MethodReceiverTag)
1520 fn noop_visit<V: MutVisitor>(&mut self, visitor: &mut V) {
1521 noop_visit_expr(&mut self.wrapped, visitor)
1523 fn is_mac_call(&self) -> bool {
1524 matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1526 fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1527 let node = self.wrapped.into_inner();
1529 ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1530 _ => unreachable!(),
1535 struct InvocationCollector<'a, 'b> {
1536 cx: &'a mut ExtCtxt<'b>,
1537 invocations: Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>,
1541 impl<'a, 'b> InvocationCollector<'a, 'b> {
1542 fn cfg(&self) -> StripUnconfigured<'_> {
1544 sess: &self.cx.sess,
1545 features: self.cx.ecfg.features,
1546 config_tokens: false,
1547 lint_node_id: self.cx.current_expansion.lint_node_id,
1551 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1552 let expn_id = LocalExpnId::fresh_empty();
1553 let vis = kind.placeholder_visibility();
1554 self.invocations.push((
1558 expansion_data: ExpansionData {
1560 depth: self.cx.current_expansion.depth + 1,
1561 ..self.cx.current_expansion.clone()
1566 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1569 fn collect_bang(&mut self, mac: P<ast::MacCall>, kind: AstFragmentKind) -> AstFragment {
1570 // cache the macro call span so that it can be
1571 // easily adjusted for incremental compilation
1572 let span = mac.span();
1573 self.collect(kind, InvocationKind::Bang { mac, span })
1578 (attr, pos, derives): (ast::Attribute, usize, Vec<ast::Path>),
1580 kind: AstFragmentKind,
1582 self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
1585 /// If `item` is an attribute invocation, remove the attribute and return it together with
1586 /// its position and derives following it. We have to collect the derives in order to resolve
1587 /// legacy derive helpers (helpers written before derives that introduce them).
1590 item: &mut impl HasAttrs,
1591 ) -> Option<(ast::Attribute, usize, Vec<ast::Path>)> {
1592 let mut attr = None;
1594 let mut cfg_pos = None;
1595 let mut attr_pos = None;
1596 for (pos, attr) in item.attrs().iter().enumerate() {
1597 if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) {
1598 let name = attr.ident().map(|ident| ident.name);
1599 if name == Some(sym::cfg) || name == Some(sym::cfg_attr) {
1600 cfg_pos = Some(pos); // a cfg attr found, no need to search anymore
1602 } else if attr_pos.is_none()
1603 && !name.map_or(false, rustc_feature::is_builtin_attr_name)
1605 attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr
1610 item.visit_attrs(|attrs| {
1611 attr = Some(match (cfg_pos, attr_pos) {
1612 (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()),
1614 let attr = attrs.remove(pos);
1615 let following_derives = attrs[pos..]
1617 .filter(|a| a.has_name(sym::derive))
1618 .flat_map(|a| a.meta_item_list().unwrap_or_default())
1619 .filter_map(|nested_meta| match nested_meta {
1620 NestedMetaItem::MetaItem(ast::MetaItem {
1621 kind: MetaItemKind::Word,
1629 (attr, pos, following_derives)
1638 // Detect use of feature-gated or invalid attributes on macro invocations
1639 // since they will not be detected after macro expansion.
1640 fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
1641 let features = self.cx.ecfg.features.unwrap();
1642 let mut attrs = attrs.iter().peekable();
1643 let mut span: Option<Span> = None;
1644 while let Some(attr) = attrs.next() {
1645 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
1646 validate_attr::check_meta(&self.cx.sess.parse_sess, attr);
1648 let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
1649 span = Some(current_span);
1651 if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
1655 if attr.is_doc_comment() {
1656 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1657 &UNUSED_DOC_COMMENTS,
1659 self.cx.current_expansion.lint_node_id,
1660 "unused doc comment",
1661 BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1663 } else if rustc_attr::is_builtin_attr(attr) {
1664 let attr_name = attr.ident().unwrap().name;
1665 // `#[cfg]` and `#[cfg_attr]` are special - they are
1666 // eagerly evaluated.
1667 if attr_name != sym::cfg && attr_name != sym::cfg_attr {
1668 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1671 self.cx.current_expansion.lint_node_id,
1672 &format!("unused attribute `{}`", attr_name),
1673 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
1675 macro_name: pprust::path_to_string(&call.path),
1676 invoc_span: call.path.span,
1686 node: &mut impl HasAttrs,
1687 attr: ast::Attribute,
1690 let res = self.cfg().cfg_true(&attr);
1692 // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion,
1693 // and some tools like rustdoc and clippy rely on that. Find a way to remove them
1694 // while keeping the tools working.
1695 self.cx.expanded_inert_attrs.mark(&attr);
1696 node.visit_attrs(|attrs| attrs.insert(pos, attr));
1701 fn expand_cfg_attr(&self, node: &mut impl HasAttrs, attr: ast::Attribute, pos: usize) {
1702 node.visit_attrs(|attrs| {
1703 // Repeated `insert` calls is inefficient, but the number of
1704 // insertions is almost always 0 or 1 in practice.
1705 for cfg in self.cfg().expand_cfg_attr(attr, false).into_iter().rev() {
1706 attrs.insert(pos, cfg)
1711 fn flat_map_node<Node: InvocationCollectorNode<OutputTy: Default>>(
1714 ) -> Node::OutputTy {
1716 return match self.take_first_attr(&mut node) {
1717 Some((attr, pos, derives)) => match attr.name_or_empty() {
1719 if self.expand_cfg_true(&mut node, attr, pos) {
1725 self.expand_cfg_attr(&mut node, attr, pos);
1729 Node::pre_flat_map_node_collect_attr(&self.cfg(), &attr);
1730 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1734 None if node.is_mac_call() => {
1735 let (mac, attrs, add_semicolon) = node.take_mac_call();
1736 self.check_attributes(&attrs, &mac);
1737 let mut res = self.collect_bang(mac, Node::KIND).make_ast::<Node>();
1738 Node::post_flat_map_node_collect_bang(&mut res, add_semicolon);
1742 match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| {
1743 assign_id!(this, node.node_id_mut(), || node.noop_flat_map(this))
1745 Ok(output) => output,
1746 Err(returned_node) => {
1747 node = returned_node;
1756 fn visit_node<Node: InvocationCollectorNode<OutputTy = Node> + DummyAstNode>(
1761 return match self.take_first_attr(node) {
1762 Some((attr, pos, derives)) => match attr.name_or_empty() {
1764 let span = attr.span;
1765 if self.expand_cfg_true(node, attr, pos) {
1769 format!("removing {} is not supported in this position", Node::descr());
1770 self.cx.span_err(span, &msg);
1774 self.expand_cfg_attr(node, attr, pos);
1777 _ => visit_clobber(node, |node| {
1778 self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
1782 None if node.is_mac_call() => {
1783 visit_clobber(node, |node| {
1784 // Do not clobber unless it's actually a macro (uncommon case).
1785 let (mac, attrs, _) = node.take_mac_call();
1786 self.check_attributes(&attrs, &mac);
1787 self.collect_bang(mac, Node::KIND).make_ast::<Node>()
1791 assign_id!(self, node.node_id_mut(), || node.noop_visit(self))
1798 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1799 fn flat_map_item(&mut self, node: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1800 self.flat_map_node(node)
1803 fn flat_map_trait_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1804 self.flat_map_node(AstNodeWrapper::new(node, TraitItemTag))
1807 fn flat_map_impl_item(&mut self, node: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1808 self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag))
1811 fn flat_map_foreign_item(
1813 node: P<ast::ForeignItem>,
1814 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1815 self.flat_map_node(node)
1818 fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1819 self.flat_map_node(node)
1822 fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
1823 self.flat_map_node(node)
1826 fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
1827 self.flat_map_node(node)
1830 fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
1831 self.flat_map_node(node)
1834 fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> {
1835 self.flat_map_node(node)
1838 fn flat_map_generic_param(
1840 node: ast::GenericParam,
1841 ) -> SmallVec<[ast::GenericParam; 1]> {
1842 self.flat_map_node(node)
1845 fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1846 self.flat_map_node(node)
1849 fn flat_map_stmt(&mut self, node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1850 // FIXME: invocations in semicolon-less expressions positions are expanded as expressions,
1851 // changing that requires some compatibility measures.
1853 // The only way that we can end up with a `MacCall` expression statement,
1854 // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the
1855 // trailing expression in a block (e.g. `fn foo() { my_macro!() }`).
1856 // Record this information, so that we can report a more specific
1857 // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed.
1858 // See #78991 for an investigation of treating macros in this position
1859 // as statements, rather than expressions, during parsing.
1860 return match &node.kind {
1861 StmtKind::Expr(expr)
1862 if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) =>
1864 self.cx.current_expansion.is_trailing_mac = true;
1865 // Don't use `assign_id` for this statement - it may get removed
1866 // entirely due to a `#[cfg]` on the contained expression
1867 let res = noop_flat_map_stmt(node, self);
1868 self.cx.current_expansion.is_trailing_mac = false;
1871 _ => noop_flat_map_stmt(node, self),
1875 self.flat_map_node(node)
1878 fn visit_crate(&mut self, node: &mut ast::Crate) {
1879 self.visit_node(node)
1882 fn visit_ty(&mut self, node: &mut P<ast::Ty>) {
1883 self.visit_node(node)
1886 fn visit_pat(&mut self, node: &mut P<ast::Pat>) {
1887 self.visit_node(node)
1890 fn visit_expr(&mut self, node: &mut P<ast::Expr>) {
1891 // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`.
1892 if let Some(attr) = node.attrs.first() {
1893 self.cfg().maybe_emit_expr_attr_err(attr);
1895 self.visit_node(node)
1898 fn visit_method_receiver_expr(&mut self, node: &mut P<ast::Expr>) {
1899 visit_clobber(node, |node| {
1900 let mut wrapper = AstNodeWrapper::new(node, MethodReceiverTag);
1901 self.visit_node(&mut wrapper);
1906 fn filter_map_expr(&mut self, node: P<ast::Expr>) -> Option<P<ast::Expr>> {
1907 self.flat_map_node(AstNodeWrapper::new(node, OptExprTag))
1910 fn visit_block(&mut self, node: &mut P<ast::Block>) {
1911 let orig_dir_ownership = mem::replace(
1912 &mut self.cx.current_expansion.dir_ownership,
1913 DirOwnership::UnownedViaBlock,
1915 noop_visit_block(node, self);
1916 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1919 fn visit_id(&mut self, id: &mut NodeId) {
1920 // We may have already assigned a `NodeId`
1921 // by calling `assign_id`
1922 if self.monotonic && *id == ast::DUMMY_NODE_ID {
1923 *id = self.cx.resolver.next_node_id();
1928 pub struct ExpansionConfig<'feat> {
1929 pub crate_name: String,
1930 pub features: Option<&'feat Features>,
1931 pub recursion_limit: Limit,
1932 pub trace_mac: bool,
1933 pub should_test: bool, // If false, strip `#[test]` nodes
1934 pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span`
1935 pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics
1938 impl<'feat> ExpansionConfig<'feat> {
1939 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1943 recursion_limit: Limit::new(1024),
1947 proc_macro_backtrace: false,
1951 fn proc_macro_hygiene(&self) -> bool {
1952 self.features.map_or(false, |features| features.proc_macro_hygiene)