1use std::any::Any;
2use std::default::Default;
3use std::iter;
4use std::path::Component::Prefix;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7use std::sync::Arc;
8
9use rustc_ast::attr::{AttributeExt, MarkedAttrs};
10use rustc_ast::token::MetaVarKind;
11use rustc_ast::tokenstream::TokenStream;
12use rustc_ast::visit::{AssocCtxt, Visitor};
13use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
14use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
15use rustc_data_structures::sync;
16use rustc_errors::{BufferedEarlyLint, DiagCtxtHandle, ErrorGuaranteed, PResult};
17use rustc_feature::Features;
18use rustc_hir as hir;
19use rustc_hir::attrs::{AttributeKind, CfgEntry, Deprecation};
20use rustc_hir::def::MacroKinds;
21use rustc_hir::limit::Limit;
22use rustc_hir::{Stability, find_attr};
23use rustc_lint_defs::RegisteredTools;
24use rustc_parse::MACRO_ARGUMENTS;
25use rustc_parse::parser::{ForceCollect, Parser};
26use rustc_session::Session;
27use rustc_session::config::CollapseMacroDebuginfo;
28use rustc_session::parse::ParseSess;
29use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
30use rustc_span::edition::Edition;
31use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
32use rustc_span::source_map::SourceMap;
33use rustc_span::{DUMMY_SP, FileName, Ident, Span, Symbol, kw, sym};
34use smallvec::{SmallVec, smallvec};
35use thin_vec::ThinVec;
36
37use crate::base::ast::MetaItemInner;
38use crate::errors;
39use crate::expand::{self, AstFragment, Invocation};
40use crate::mbe::macro_rules::ParserAnyMacro;
41use crate::module::DirOwnership;
42use crate::stats::MacroStat;
43
44#[derive(Debug, Clone)]
48pub enum Annotatable {
49 Item(Box<ast::Item>),
50 AssocItem(Box<ast::AssocItem>, AssocCtxt),
51 ForeignItem(Box<ast::ForeignItem>),
52 Stmt(Box<ast::Stmt>),
53 Expr(Box<ast::Expr>),
54 Arm(ast::Arm),
55 ExprField(ast::ExprField),
56 PatField(ast::PatField),
57 GenericParam(ast::GenericParam),
58 Param(ast::Param),
59 FieldDef(ast::FieldDef),
60 Variant(ast::Variant),
61 WherePredicate(ast::WherePredicate),
62 Crate(ast::Crate),
63}
64
65impl Annotatable {
66 pub fn span(&self) -> Span {
67 match self {
68 Annotatable::Item(item) => item.span,
69 Annotatable::AssocItem(assoc_item, _) => assoc_item.span,
70 Annotatable::ForeignItem(foreign_item) => foreign_item.span,
71 Annotatable::Stmt(stmt) => stmt.span,
72 Annotatable::Expr(expr) => expr.span,
73 Annotatable::Arm(arm) => arm.span,
74 Annotatable::ExprField(field) => field.span,
75 Annotatable::PatField(fp) => fp.pat.span,
76 Annotatable::GenericParam(gp) => gp.ident.span,
77 Annotatable::Param(p) => p.span,
78 Annotatable::FieldDef(sf) => sf.span,
79 Annotatable::Variant(v) => v.span,
80 Annotatable::WherePredicate(wp) => wp.span,
81 Annotatable::Crate(c) => c.spans.inner_span,
82 }
83 }
84
85 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
86 match self {
87 Annotatable::Item(item) => item.visit_attrs(f),
88 Annotatable::AssocItem(assoc_item, _) => assoc_item.visit_attrs(f),
89 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
90 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
91 Annotatable::Expr(expr) => expr.visit_attrs(f),
92 Annotatable::Arm(arm) => arm.visit_attrs(f),
93 Annotatable::ExprField(field) => field.visit_attrs(f),
94 Annotatable::PatField(fp) => fp.visit_attrs(f),
95 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
96 Annotatable::Param(p) => p.visit_attrs(f),
97 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
98 Annotatable::Variant(v) => v.visit_attrs(f),
99 Annotatable::WherePredicate(wp) => wp.visit_attrs(f),
100 Annotatable::Crate(c) => c.visit_attrs(f),
101 }
102 }
103
104 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) -> V::Result {
105 match self {
106 Annotatable::Item(item) => visitor.visit_item(item),
107 Annotatable::AssocItem(item, ctxt) => visitor.visit_assoc_item(item, *ctxt),
108 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
109 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
110 Annotatable::Expr(expr) => visitor.visit_expr(expr),
111 Annotatable::Arm(arm) => visitor.visit_arm(arm),
112 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
113 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
114 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
115 Annotatable::Param(p) => visitor.visit_param(p),
116 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
117 Annotatable::Variant(v) => visitor.visit_variant(v),
118 Annotatable::WherePredicate(wp) => visitor.visit_where_predicate(wp),
119 Annotatable::Crate(c) => visitor.visit_crate(c),
120 }
121 }
122
123 pub fn to_tokens(&self) -> TokenStream {
124 match self {
125 Annotatable::Item(node) => TokenStream::from_ast(node),
126 Annotatable::AssocItem(node, _) => TokenStream::from_ast(node),
127 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
128 Annotatable::Stmt(node) => {
129 assert!(!matches!(node.kind, ast::StmtKind::Empty));
130 TokenStream::from_ast(node)
131 }
132 Annotatable::Expr(node) => TokenStream::from_ast(node),
133 Annotatable::Arm(..)
134 | Annotatable::ExprField(..)
135 | Annotatable::PatField(..)
136 | Annotatable::GenericParam(..)
137 | Annotatable::Param(..)
138 | Annotatable::FieldDef(..)
139 | Annotatable::Variant(..)
140 | Annotatable::WherePredicate(..)
141 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
142 }
143 }
144
145 pub fn expect_item(self) -> Box<ast::Item> {
146 match self {
147 Annotatable::Item(i) => i,
148 _ => panic!("expected Item"),
149 }
150 }
151
152 pub fn expect_trait_item(self) -> Box<ast::AssocItem> {
153 match self {
154 Annotatable::AssocItem(i, AssocCtxt::Trait) => i,
155 _ => panic!("expected Item"),
156 }
157 }
158
159 pub fn expect_impl_item(self) -> Box<ast::AssocItem> {
160 match self {
161 Annotatable::AssocItem(i, AssocCtxt::Impl { .. }) => i,
162 _ => panic!("expected Item"),
163 }
164 }
165
166 pub fn expect_foreign_item(self) -> Box<ast::ForeignItem> {
167 match self {
168 Annotatable::ForeignItem(i) => i,
169 _ => panic!("expected foreign item"),
170 }
171 }
172
173 pub fn expect_stmt(self) -> ast::Stmt {
174 match self {
175 Annotatable::Stmt(stmt) => *stmt,
176 _ => panic!("expected statement"),
177 }
178 }
179
180 pub fn expect_expr(self) -> Box<ast::Expr> {
181 match self {
182 Annotatable::Expr(expr) => expr,
183 _ => panic!("expected expression"),
184 }
185 }
186
187 pub fn expect_arm(self) -> ast::Arm {
188 match self {
189 Annotatable::Arm(arm) => arm,
190 _ => panic!("expected match arm"),
191 }
192 }
193
194 pub fn expect_expr_field(self) -> ast::ExprField {
195 match self {
196 Annotatable::ExprField(field) => field,
197 _ => panic!("expected field"),
198 }
199 }
200
201 pub fn expect_pat_field(self) -> ast::PatField {
202 match self {
203 Annotatable::PatField(fp) => fp,
204 _ => panic!("expected field pattern"),
205 }
206 }
207
208 pub fn expect_generic_param(self) -> ast::GenericParam {
209 match self {
210 Annotatable::GenericParam(gp) => gp,
211 _ => panic!("expected generic parameter"),
212 }
213 }
214
215 pub fn expect_param(self) -> ast::Param {
216 match self {
217 Annotatable::Param(param) => param,
218 _ => panic!("expected parameter"),
219 }
220 }
221
222 pub fn expect_field_def(self) -> ast::FieldDef {
223 match self {
224 Annotatable::FieldDef(sf) => sf,
225 _ => panic!("expected struct field"),
226 }
227 }
228
229 pub fn expect_variant(self) -> ast::Variant {
230 match self {
231 Annotatable::Variant(v) => v,
232 _ => panic!("expected variant"),
233 }
234 }
235
236 pub fn expect_where_predicate(self) -> ast::WherePredicate {
237 match self {
238 Annotatable::WherePredicate(wp) => wp,
239 _ => panic!("expected where predicate"),
240 }
241 }
242
243 pub fn expect_crate(self) -> ast::Crate {
244 match self {
245 Annotatable::Crate(krate) => krate,
246 _ => panic!("expected krate"),
247 }
248 }
249}
250
251pub enum ExpandResult<T, U> {
254 Ready(T),
256 Retry(U),
258}
259
260impl<T, U> ExpandResult<T, U> {
261 pub fn map<E, F: FnOnce(T) -> E>(self, f: F) -> ExpandResult<E, U> {
262 match self {
263 ExpandResult::Ready(t) => ExpandResult::Ready(f(t)),
264 ExpandResult::Retry(u) => ExpandResult::Retry(u),
265 }
266 }
267}
268
269impl<'cx> MacroExpanderResult<'cx> {
270 pub fn from_tts(
274 cx: &'cx mut ExtCtxt<'_>,
275 tts: TokenStream,
276 site_span: Span,
277 arm_span: Span,
278 macro_ident: Ident,
279 ) -> Self {
280 let is_local = true;
282
283 let parser = ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, is_local, macro_ident);
284 ExpandResult::Ready(Box::new(parser))
285 }
286}
287
288pub trait MultiItemModifier {
289 fn expand(
291 &self,
292 ecx: &mut ExtCtxt<'_>,
293 span: Span,
294 meta_item: &ast::MetaItem,
295 item: Annotatable,
296 is_derive_const: bool,
297 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
298}
299
300impl<F> MultiItemModifier for F
301where
302 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
303{
304 fn expand(
305 &self,
306 ecx: &mut ExtCtxt<'_>,
307 span: Span,
308 meta_item: &ast::MetaItem,
309 item: Annotatable,
310 _is_derive_const: bool,
311 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
312 ExpandResult::Ready(self(ecx, span, meta_item, item))
313 }
314}
315
316pub trait BangProcMacro {
317 fn expand<'cx>(
318 &self,
319 ecx: &'cx mut ExtCtxt<'_>,
320 span: Span,
321 ts: TokenStream,
322 ) -> Result<TokenStream, ErrorGuaranteed>;
323}
324
325impl<F> BangProcMacro for F
326where
327 F: Fn(TokenStream) -> TokenStream,
328{
329 fn expand<'cx>(
330 &self,
331 _ecx: &'cx mut ExtCtxt<'_>,
332 _span: Span,
333 ts: TokenStream,
334 ) -> Result<TokenStream, ErrorGuaranteed> {
335 Ok(self(ts))
337 }
338}
339
340pub trait AttrProcMacro {
341 fn expand<'cx>(
342 &self,
343 ecx: &'cx mut ExtCtxt<'_>,
344 span: Span,
345 annotation: TokenStream,
346 annotated: TokenStream,
347 ) -> Result<TokenStream, ErrorGuaranteed>;
348}
349
350impl<F> AttrProcMacro for F
351where
352 F: Fn(TokenStream, TokenStream) -> TokenStream,
353{
354 fn expand<'cx>(
355 &self,
356 _ecx: &'cx mut ExtCtxt<'_>,
357 _span: Span,
358 annotation: TokenStream,
359 annotated: TokenStream,
360 ) -> Result<TokenStream, ErrorGuaranteed> {
361 Ok(self(annotation, annotated))
363 }
364}
365
366pub trait TTMacroExpander: Any {
368 fn expand<'cx>(
369 &self,
370 ecx: &'cx mut ExtCtxt<'_>,
371 span: Span,
372 input: TokenStream,
373 ) -> MacroExpanderResult<'cx>;
374}
375
376pub type MacroExpanderResult<'cx> = ExpandResult<Box<dyn MacResult + 'cx>, ()>;
377
378pub type MacroExpanderFn =
379 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>;
380
381impl<F: 'static> TTMacroExpander for F
382where
383 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>,
384{
385 fn expand<'cx>(
386 &self,
387 ecx: &'cx mut ExtCtxt<'_>,
388 span: Span,
389 input: TokenStream,
390 ) -> MacroExpanderResult<'cx> {
391 self(ecx, span, input)
392 }
393}
394
395pub trait GlobDelegationExpander {
396 fn expand(&self, ecx: &mut ExtCtxt<'_>) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()>;
397}
398
399macro_rules! make_stmts_default {
401 ($me:expr) => {
402 $me.make_expr().map(|e| {
403 smallvec![ast::Stmt {
404 id: ast::DUMMY_NODE_ID,
405 span: e.span,
406 kind: ast::StmtKind::Expr(e),
407 }]
408 })
409 };
410}
411
412pub trait MacResult {
415 fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
417 None
418 }
419
420 fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
422 None
423 }
424
425 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
427 None
428 }
429
430 fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
432 None
433 }
434
435 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
437 None
438 }
439
440 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
442 None
443 }
444
445 fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
447 None
448 }
449
450 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
455 make_stmts_default!(self)
456 }
457
458 fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
459 None
460 }
461
462 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
463 None
464 }
465
466 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
467 None
468 }
469
470 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
471 None
472 }
473
474 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
475 None
476 }
477
478 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
479 None
480 }
481
482 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
483 None
484 }
485
486 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
487 None
488 }
489
490 fn make_where_predicates(self: Box<Self>) -> Option<SmallVec<[ast::WherePredicate; 1]>> {
491 None
492 }
493
494 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
495 unreachable!()
497 }
498}
499
500macro_rules! make_MacEager {
501 ( $( $fld:ident: $t:ty, )* ) => {
502 #[derive(Default)]
505 pub struct MacEager {
506 $(
507 pub $fld: Option<$t>,
508 )*
509 }
510
511 impl MacEager {
512 $(
513 pub fn $fld(v: $t) -> Box<dyn MacResult> {
514 Box::new(MacEager {
515 $fld: Some(v),
516 ..Default::default()
517 })
518 }
519 )*
520 }
521 }
522}
523
524make_MacEager! {
525 expr: Box<ast::Expr>,
526 pat: Box<ast::Pat>,
527 items: SmallVec<[Box<ast::Item>; 1]>,
528 impl_items: SmallVec<[Box<ast::AssocItem>; 1]>,
529 trait_items: SmallVec<[Box<ast::AssocItem>; 1]>,
530 foreign_items: SmallVec<[Box<ast::ForeignItem>; 1]>,
531 stmts: SmallVec<[ast::Stmt; 1]>,
532 ty: Box<ast::Ty>,
533}
534
535impl MacResult for MacEager {
536 fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
537 self.expr
538 }
539
540 fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
541 self.items
542 }
543
544 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
545 self.impl_items
546 }
547
548 fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
549 self.impl_items
550 }
551
552 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
553 self.trait_items
554 }
555
556 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
557 self.foreign_items
558 }
559
560 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
561 match self.stmts.as_ref().map_or(0, |s| s.len()) {
562 0 => make_stmts_default!(self),
563 _ => self.stmts,
564 }
565 }
566
567 fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
568 if let Some(p) = self.pat {
569 return Some(p);
570 }
571 if let Some(e) = self.expr {
572 if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
573 return Some(Box::new(ast::Pat {
574 id: ast::DUMMY_NODE_ID,
575 span: e.span,
576 kind: PatKind::Expr(e),
577 tokens: None,
578 }));
579 }
580 }
581 None
582 }
583
584 fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
585 self.ty
586 }
587}
588
589#[derive(Copy, Clone)]
592pub struct DummyResult {
593 guar: Option<ErrorGuaranteed>,
594 span: Span,
595}
596
597impl DummyResult {
598 pub fn any(span: Span, guar: ErrorGuaranteed) -> Box<dyn MacResult + 'static> {
603 Box::new(DummyResult { guar: Some(guar), span })
604 }
605
606 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
608 Box::new(DummyResult { guar: None, span })
609 }
610
611 pub fn raw_expr(sp: Span, guar: Option<ErrorGuaranteed>) -> Box<ast::Expr> {
613 Box::new(ast::Expr {
614 id: ast::DUMMY_NODE_ID,
615 kind: if let Some(guar) = guar {
616 ast::ExprKind::Err(guar)
617 } else {
618 ast::ExprKind::Tup(ThinVec::new())
619 },
620 span: sp,
621 attrs: ast::AttrVec::new(),
622 tokens: None,
623 })
624 }
625}
626
627impl MacResult for DummyResult {
628 fn make_expr(self: Box<DummyResult>) -> Option<Box<ast::Expr>> {
629 Some(DummyResult::raw_expr(self.span, self.guar))
630 }
631
632 fn make_pat(self: Box<DummyResult>) -> Option<Box<ast::Pat>> {
633 Some(Box::new(ast::Pat {
634 id: ast::DUMMY_NODE_ID,
635 kind: PatKind::Wild,
636 span: self.span,
637 tokens: None,
638 }))
639 }
640
641 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
642 Some(SmallVec::new())
643 }
644
645 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
646 Some(SmallVec::new())
647 }
648
649 fn make_trait_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
650 Some(SmallVec::new())
651 }
652
653 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
654 Some(SmallVec::new())
655 }
656
657 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
658 Some(SmallVec::new())
659 }
660
661 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
662 Some(smallvec![ast::Stmt {
663 id: ast::DUMMY_NODE_ID,
664 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.guar)),
665 span: self.span,
666 }])
667 }
668
669 fn make_ty(self: Box<DummyResult>) -> Option<Box<ast::Ty>> {
670 Some(Box::new(ast::Ty {
674 id: ast::DUMMY_NODE_ID,
675 kind: ast::TyKind::Tup(ThinVec::new()),
676 span: self.span,
677 tokens: None,
678 }))
679 }
680
681 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
682 Some(SmallVec::new())
683 }
684
685 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
686 Some(SmallVec::new())
687 }
688
689 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
690 Some(SmallVec::new())
691 }
692
693 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
694 Some(SmallVec::new())
695 }
696
697 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
698 Some(SmallVec::new())
699 }
700
701 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
702 Some(SmallVec::new())
703 }
704
705 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
706 Some(SmallVec::new())
707 }
708
709 fn make_crate(self: Box<DummyResult>) -> Option<ast::Crate> {
710 Some(ast::Crate {
711 attrs: Default::default(),
712 items: Default::default(),
713 spans: Default::default(),
714 id: ast::DUMMY_NODE_ID,
715 is_placeholder: Default::default(),
716 })
717 }
718}
719
720#[derive(Clone)]
722pub enum SyntaxExtensionKind {
723 MacroRules(Arc<crate::MacroRulesMacroExpander>),
725
726 Bang(
728 Arc<dyn BangProcMacro + sync::DynSync + sync::DynSend>,
730 ),
731
732 LegacyBang(
734 Arc<dyn TTMacroExpander + sync::DynSync + sync::DynSend>,
736 ),
737
738 Attr(
740 Arc<dyn AttrProcMacro + sync::DynSync + sync::DynSend>,
744 ),
745
746 LegacyAttr(
748 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
752 ),
753
754 NonMacroAttr,
759
760 Derive(
762 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
770 ),
771
772 LegacyDerive(
774 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
777 ),
778
779 GlobDelegation(Arc<dyn GlobDelegationExpander + sync::DynSync + sync::DynSend>),
783}
784
785impl SyntaxExtensionKind {
786 pub fn as_legacy_bang(&self) -> Option<&(dyn TTMacroExpander + sync::DynSync + sync::DynSend)> {
790 match self {
791 SyntaxExtensionKind::LegacyBang(exp) => Some(exp.as_ref()),
792 SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::BANG) => {
793 Some(exp.as_ref())
794 }
795 _ => None,
796 }
797 }
798
799 pub fn as_attr(&self) -> Option<&(dyn AttrProcMacro + sync::DynSync + sync::DynSend)> {
803 match self {
804 SyntaxExtensionKind::Attr(exp) => Some(exp.as_ref()),
805 SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::ATTR) => {
806 Some(exp.as_ref())
807 }
808 _ => None,
809 }
810 }
811}
812
813pub struct SyntaxExtension {
815 pub kind: SyntaxExtensionKind,
817 pub span: Span,
819 pub allow_internal_unstable: Option<Arc<[Symbol]>>,
821 pub stability: Option<Stability>,
823 pub deprecation: Option<Deprecation>,
825 pub helper_attrs: Vec<Symbol>,
827 pub edition: Edition,
829 pub builtin_name: Option<Symbol>,
832 pub allow_internal_unsafe: bool,
834 pub local_inner_macros: bool,
836 pub collapse_debuginfo: bool,
839}
840
841impl SyntaxExtension {
842 pub fn macro_kinds(&self) -> MacroKinds {
844 match self.kind {
845 SyntaxExtensionKind::Bang(..)
846 | SyntaxExtensionKind::LegacyBang(..)
847 | SyntaxExtensionKind::GlobDelegation(..) => MacroKinds::BANG,
848 SyntaxExtensionKind::Attr(..)
849 | SyntaxExtensionKind::LegacyAttr(..)
850 | SyntaxExtensionKind::NonMacroAttr => MacroKinds::ATTR,
851 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
852 MacroKinds::DERIVE
853 }
854 SyntaxExtensionKind::MacroRules(ref m) => m.kinds(),
855 }
856 }
857
858 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
860 SyntaxExtension {
861 span: DUMMY_SP,
862 allow_internal_unstable: None,
863 stability: None,
864 deprecation: None,
865 helper_attrs: Vec::new(),
866 edition,
867 builtin_name: None,
868 kind,
869 allow_internal_unsafe: false,
870 local_inner_macros: false,
871 collapse_debuginfo: false,
872 }
873 }
874
875 fn collapse_debuginfo_by_name(
876 attr: &impl AttributeExt,
877 ) -> Result<CollapseMacroDebuginfo, Span> {
878 let list = attr.meta_item_list();
879 let Some([MetaItemInner::MetaItem(item)]) = list.as_deref() else {
880 return Err(attr.span());
881 };
882 if !item.is_word() {
883 return Err(item.span);
884 }
885
886 match item.name() {
887 Some(sym::no) => Ok(CollapseMacroDebuginfo::No),
888 Some(sym::external) => Ok(CollapseMacroDebuginfo::External),
889 Some(sym::yes) => Ok(CollapseMacroDebuginfo::Yes),
890 _ => Err(item.path.span),
891 }
892 }
893
894 fn get_collapse_debuginfo(sess: &Session, attrs: &[hir::Attribute], ext: bool) -> bool {
901 let flag = sess.opts.cg.collapse_macro_debuginfo;
902 let attr = ast::attr::find_by_name(attrs, sym::collapse_debuginfo)
903 .and_then(|attr| {
904 Self::collapse_debuginfo_by_name(attr)
905 .map_err(|span| {
906 sess.dcx().emit_err(errors::CollapseMacroDebuginfoIllegal { span })
907 })
908 .ok()
909 })
910 .unwrap_or_else(|| {
911 if find_attr!(attrs, AttributeKind::RustcBuiltinMacro { .. }) {
912 CollapseMacroDebuginfo::Yes
913 } else {
914 CollapseMacroDebuginfo::Unspecified
915 }
916 });
917 #[rustfmt::skip]
918 let collapse_table = [
919 [false, false, false, false],
920 [false, ext, ext, true],
921 [false, ext, ext, true],
922 [true, true, true, true],
923 ];
924 collapse_table[flag as usize][attr as usize]
925 }
926
927 pub fn new(
930 sess: &Session,
931 kind: SyntaxExtensionKind,
932 span: Span,
933 helper_attrs: Vec<Symbol>,
934 edition: Edition,
935 name: Symbol,
936 attrs: &[hir::Attribute],
937 is_local: bool,
938 ) -> SyntaxExtension {
939 let allow_internal_unstable =
940 find_attr!(attrs, AttributeKind::AllowInternalUnstable(i, _) => i)
941 .map(|i| i.as_slice())
942 .unwrap_or_default();
943 let allow_internal_unsafe = find_attr!(attrs, AttributeKind::AllowInternalUnsafe(_));
944
945 let local_inner_macros = ast::attr::find_by_name(attrs, sym::macro_export)
946 .and_then(|macro_export| macro_export.meta_item_list())
947 .is_some_and(|l| ast::attr::list_contains_name(&l, sym::local_inner_macros));
948 let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, !is_local);
949 tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
950
951 let (builtin_name, helper_attrs) = match find_attr!(attrs, AttributeKind::RustcBuiltinMacro { builtin_name, helper_attrs, .. } => (builtin_name, helper_attrs))
952 {
953 Some((Some(name), helper_attrs)) => {
956 (Some(*name), helper_attrs.iter().copied().collect())
957 }
958 Some((None, _)) => (Some(name), Vec::new()),
959
960 None => (None, helper_attrs),
962 };
963
964 let stability = find_attr!(attrs, AttributeKind::Stability { stability, .. } => *stability);
965
966 if let Some(sp) = find_attr!(attrs, AttributeKind::ConstStability { span, .. } => *span) {
968 sess.dcx().emit_err(errors::MacroConstStability {
969 span: sp,
970 head_span: sess.source_map().guess_head_span(span),
971 });
972 }
973 if let Some(sp) = find_attr!(attrs, AttributeKind::BodyStability{ span, .. } => *span) {
974 sess.dcx().emit_err(errors::MacroBodyStability {
975 span: sp,
976 head_span: sess.source_map().guess_head_span(span),
977 });
978 }
979
980 SyntaxExtension {
981 kind,
982 span,
983 allow_internal_unstable: (!allow_internal_unstable.is_empty())
984 .then(|| allow_internal_unstable.iter().map(|i| i.0).collect::<Vec<_>>().into()),
986 stability,
987 deprecation: find_attr!(
988 attrs,
989 AttributeKind::Deprecation { deprecation, .. } => *deprecation
990 ),
991 helper_attrs,
992 edition,
993 builtin_name,
994 allow_internal_unsafe,
995 local_inner_macros,
996 collapse_debuginfo,
997 }
998 }
999
1000 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
1002 fn expander<'cx>(
1003 cx: &'cx mut ExtCtxt<'_>,
1004 span: Span,
1005 _: TokenStream,
1006 ) -> MacroExpanderResult<'cx> {
1007 ExpandResult::Ready(DummyResult::any(
1008 span,
1009 cx.dcx().span_delayed_bug(span, "expanded a dummy bang macro"),
1010 ))
1011 }
1012 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Arc::new(expander)), edition)
1013 }
1014
1015 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
1017 fn expander(
1018 _: &mut ExtCtxt<'_>,
1019 _: Span,
1020 _: &ast::MetaItem,
1021 _: Annotatable,
1022 ) -> Vec<Annotatable> {
1023 Vec::new()
1024 }
1025 SyntaxExtension::default(SyntaxExtensionKind::Derive(Arc::new(expander)), edition)
1026 }
1027
1028 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
1029 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
1030 }
1031
1032 pub fn glob_delegation(
1033 trait_def_id: DefId,
1034 impl_def_id: LocalDefId,
1035 edition: Edition,
1036 ) -> SyntaxExtension {
1037 struct GlobDelegationExpanderImpl {
1038 trait_def_id: DefId,
1039 impl_def_id: LocalDefId,
1040 }
1041 impl GlobDelegationExpander for GlobDelegationExpanderImpl {
1042 fn expand(
1043 &self,
1044 ecx: &mut ExtCtxt<'_>,
1045 ) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()> {
1046 match ecx.resolver.glob_delegation_suffixes(self.trait_def_id, self.impl_def_id) {
1047 Ok(suffixes) => ExpandResult::Ready(suffixes),
1048 Err(Indeterminate) if ecx.force_mode => ExpandResult::Ready(Vec::new()),
1049 Err(Indeterminate) => ExpandResult::Retry(()),
1050 }
1051 }
1052 }
1053
1054 let expander = GlobDelegationExpanderImpl { trait_def_id, impl_def_id };
1055 SyntaxExtension::default(SyntaxExtensionKind::GlobDelegation(Arc::new(expander)), edition)
1056 }
1057
1058 pub fn expn_data(
1059 &self,
1060 parent: LocalExpnId,
1061 call_site: Span,
1062 descr: Symbol,
1063 kind: MacroKind,
1064 macro_def_id: Option<DefId>,
1065 parent_module: Option<DefId>,
1066 ) -> ExpnData {
1067 ExpnData::new(
1068 ExpnKind::Macro(kind, descr),
1069 parent.to_expn_id(),
1070 call_site,
1071 self.span,
1072 self.allow_internal_unstable.clone(),
1073 self.edition,
1074 macro_def_id,
1075 parent_module,
1076 self.allow_internal_unsafe,
1077 self.local_inner_macros,
1078 self.collapse_debuginfo,
1079 self.builtin_name.is_some(),
1080 )
1081 }
1082}
1083
1084pub struct Indeterminate;
1086
1087pub struct DeriveResolution {
1088 pub path: ast::Path,
1089 pub item: Annotatable,
1090 pub exts: Option<Arc<SyntaxExtension>>,
1091 pub is_const: bool,
1092}
1093
1094pub trait ResolverExpand {
1095 fn next_node_id(&mut self) -> NodeId;
1096 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
1097
1098 fn resolve_dollar_crates(&self);
1099 fn visit_ast_fragment_with_placeholders(
1100 &mut self,
1101 expn_id: LocalExpnId,
1102 fragment: &AstFragment,
1103 );
1104 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
1105
1106 fn expansion_for_ast_pass(
1107 &mut self,
1108 call_site: Span,
1109 pass: AstPass,
1110 features: &[Symbol],
1111 parent_module_id: Option<NodeId>,
1112 ) -> LocalExpnId;
1113
1114 fn resolve_imports(&mut self);
1115
1116 fn resolve_macro_invocation(
1117 &mut self,
1118 invoc: &Invocation,
1119 eager_expansion_root: LocalExpnId,
1120 force: bool,
1121 ) -> Result<Arc<SyntaxExtension>, Indeterminate>;
1122
1123 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
1124
1125 fn check_unused_macros(&mut self);
1126
1127 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
1130 fn resolve_derives(
1132 &mut self,
1133 expn_id: LocalExpnId,
1134 force: bool,
1135 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
1136 ) -> Result<(), Indeterminate>;
1137 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>>;
1140 fn cfg_accessible(
1142 &mut self,
1143 expn_id: LocalExpnId,
1144 path: &ast::Path,
1145 ) -> Result<bool, Indeterminate>;
1146 fn macro_accessible(
1147 &mut self,
1148 expn_id: LocalExpnId,
1149 path: &ast::Path,
1150 ) -> Result<bool, Indeterminate>;
1151
1152 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
1155
1156 fn declare_proc_macro(&mut self, id: NodeId);
1163
1164 fn append_stripped_cfg_item(
1165 &mut self,
1166 parent_node: NodeId,
1167 ident: Ident,
1168 cfg: CfgEntry,
1169 cfg_span: Span,
1170 );
1171
1172 fn registered_tools(&self) -> &RegisteredTools;
1174
1175 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId);
1177
1178 fn glob_delegation_suffixes(
1180 &self,
1181 trait_def_id: DefId,
1182 impl_def_id: LocalDefId,
1183 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate>;
1184
1185 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol);
1188}
1189
1190pub trait LintStoreExpand {
1191 fn pre_expansion_lint(
1192 &self,
1193 sess: &Session,
1194 features: &Features,
1195 registered_tools: &RegisteredTools,
1196 node_id: NodeId,
1197 attrs: &[Attribute],
1198 items: &[Box<Item>],
1199 name: Symbol,
1200 );
1201}
1202
1203type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
1204
1205#[derive(Debug, Clone, Default)]
1206pub struct ModuleData {
1207 pub mod_path: Vec<Ident>,
1209 pub file_path_stack: Vec<PathBuf>,
1212 pub dir_path: PathBuf,
1215}
1216
1217impl ModuleData {
1218 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
1219 ModuleData {
1220 mod_path: self.mod_path.clone(),
1221 file_path_stack: self.file_path_stack.clone(),
1222 dir_path,
1223 }
1224 }
1225}
1226
1227#[derive(Clone)]
1228pub struct ExpansionData {
1229 pub id: LocalExpnId,
1230 pub depth: usize,
1231 pub module: Rc<ModuleData>,
1232 pub dir_ownership: DirOwnership,
1233 pub lint_node_id: NodeId,
1235 pub is_trailing_mac: bool,
1236}
1237
1238pub struct ExtCtxt<'a> {
1242 pub sess: &'a Session,
1243 pub ecfg: expand::ExpansionConfig<'a>,
1244 pub num_standard_library_imports: usize,
1245 pub reduced_recursion_limit: Option<(Limit, ErrorGuaranteed)>,
1246 pub root_path: PathBuf,
1247 pub resolver: &'a mut dyn ResolverExpand,
1248 pub current_expansion: ExpansionData,
1249 pub force_mode: bool,
1252 pub expansions: FxIndexMap<Span, Vec<String>>,
1253 pub(super) lint_store: LintStoreExpandDyn<'a>,
1255 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1257 pub(super) expanded_inert_attrs: MarkedAttrs,
1261 pub macro_stats: FxHashMap<(Symbol, MacroKind), MacroStat>,
1263 pub nb_macro_errors: usize,
1264}
1265
1266impl<'a> ExtCtxt<'a> {
1267 pub fn new(
1268 sess: &'a Session,
1269 ecfg: expand::ExpansionConfig<'a>,
1270 resolver: &'a mut dyn ResolverExpand,
1271 lint_store: LintStoreExpandDyn<'a>,
1272 ) -> ExtCtxt<'a> {
1273 ExtCtxt {
1274 sess,
1275 ecfg,
1276 num_standard_library_imports: 0,
1277 reduced_recursion_limit: None,
1278 resolver,
1279 lint_store,
1280 root_path: PathBuf::new(),
1281 current_expansion: ExpansionData {
1282 id: LocalExpnId::ROOT,
1283 depth: 0,
1284 module: Default::default(),
1285 dir_ownership: DirOwnership::Owned { relative: None },
1286 lint_node_id: ast::CRATE_NODE_ID,
1287 is_trailing_mac: false,
1288 },
1289 force_mode: false,
1290 expansions: FxIndexMap::default(),
1291 expanded_inert_attrs: MarkedAttrs::new(),
1292 buffered_early_lint: vec![],
1293 macro_stats: Default::default(),
1294 nb_macro_errors: 0,
1295 }
1296 }
1297
1298 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
1299 self.sess.dcx()
1300 }
1301
1302 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1304 expand::MacroExpander::new(self, false)
1305 }
1306
1307 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1310 expand::MacroExpander::new(self, true)
1311 }
1312 pub fn new_parser_from_tts(&self, stream: TokenStream) -> Parser<'a> {
1313 Parser::new(&self.sess.psess, stream, MACRO_ARGUMENTS)
1314 }
1315 pub fn source_map(&self) -> &'a SourceMap {
1316 self.sess.psess.source_map()
1317 }
1318 pub fn psess(&self) -> &'a ParseSess {
1319 &self.sess.psess
1320 }
1321 pub fn call_site(&self) -> Span {
1322 self.current_expansion.id.expn_data().call_site
1323 }
1324
1325 pub(crate) fn expansion_descr(&self) -> String {
1327 let expn_data = self.current_expansion.id.expn_data();
1328 expn_data.kind.descr()
1329 }
1330
1331 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1334 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1335 }
1336
1337 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1340 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1341 }
1342
1343 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1346 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1347 }
1348
1349 pub fn expansion_cause(&self) -> Option<Span> {
1353 self.current_expansion.id.expansion_cause()
1354 }
1355
1356 pub fn macro_error_and_trace_macros_diag(&mut self) {
1358 self.nb_macro_errors += 1;
1359 self.trace_macros_diag();
1360 }
1361
1362 pub fn trace_macros_diag(&mut self) {
1363 for (span, notes) in self.expansions.iter() {
1364 let mut db = self.dcx().create_note(errors::TraceMacro { span: *span });
1365 for note in notes {
1366 #[allow(rustc::untranslatable_diagnostic)]
1368 db.note(note.clone());
1369 }
1370 db.emit();
1371 }
1372 self.expansions.clear();
1374 }
1375 pub fn trace_macros(&self) -> bool {
1376 self.ecfg.trace_mac
1377 }
1378 pub fn set_trace_macros(&mut self, x: bool) {
1379 self.ecfg.trace_mac = x
1380 }
1381 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1382 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1383 iter::once(Ident::new(kw::DollarCrate, def_site))
1384 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1385 .collect()
1386 }
1387 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1388 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1389 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1390 }
1391
1392 pub fn check_unused_macros(&mut self) {
1393 self.resolver.check_unused_macros();
1394 }
1395}
1396
1397pub fn resolve_path(sess: &Session, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
1401 let path = path.into();
1402
1403 if !path.is_absolute() {
1406 let callsite = span.source_callsite();
1407 let source_map = sess.source_map();
1408 let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path() else {
1409 return Err(sess.dcx().create_err(errors::ResolveRelativePath {
1410 span,
1411 path: source_map
1412 .filename_for_diagnostics(&source_map.span_to_filename(callsite))
1413 .to_string(),
1414 }));
1415 };
1416 base_path.pop();
1417 base_path.push(path);
1418 Ok(base_path)
1419 } else {
1420 match path.components().next() {
1423 Some(Prefix(prefix)) if prefix.kind().is_verbatim() => Ok(path.components().collect()),
1424 _ => Ok(path),
1425 }
1426 }
1427}
1428
1429fn pretty_printing_compatibility_hack(item: &Item, psess: &ParseSess) {
1433 if let ast::ItemKind::Enum(ident, _, enum_def) = &item.kind
1434 && ident.name == sym::ProceduralMasqueradeDummyType
1435 && let [variant] = &*enum_def.variants
1436 && variant.ident.name == sym::Input
1437 && let FileName::Real(real) = psess.source_map().span_to_filename(ident.span)
1438 && let Some(c) = real
1439 .local_path()
1440 .unwrap_or(Path::new(""))
1441 .components()
1442 .flat_map(|c| c.as_os_str().to_str())
1443 .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1444 {
1445 let crate_matches = if c.starts_with("allsorts-rental") {
1446 true
1447 } else {
1448 let mut version = c.trim_start_matches("rental-").split('.');
1449 version.next() == Some("0")
1450 && version.next() == Some("5")
1451 && version.next().and_then(|c| c.parse::<u32>().ok()).is_some_and(|v| v < 6)
1452 };
1453
1454 if crate_matches {
1455 psess.dcx().emit_fatal(errors::ProcMacroBackCompat {
1456 crate_name: "rental".to_string(),
1457 fixed_version: "0.5.6".to_string(),
1458 });
1459 }
1460 }
1461}
1462
1463pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, psess: &ParseSess) {
1464 let item = match ann {
1465 Annotatable::Item(item) => item,
1466 Annotatable::Stmt(stmt) => match &stmt.kind {
1467 ast::StmtKind::Item(item) => item,
1468 _ => return,
1469 },
1470 _ => return,
1471 };
1472 pretty_printing_compatibility_hack(item, psess)
1473}
1474
1475pub(crate) fn stream_pretty_printing_compatibility_hack(
1476 kind: MetaVarKind,
1477 stream: &TokenStream,
1478 psess: &ParseSess,
1479) {
1480 let item = match kind {
1481 MetaVarKind::Item => {
1482 let mut parser = Parser::new(psess, stream.clone(), None);
1483 parser
1485 .parse_item(ForceCollect::No)
1486 .expect("failed to reparse item")
1487 .expect("an actual item")
1488 }
1489 MetaVarKind::Stmt => {
1490 let mut parser = Parser::new(psess, stream.clone(), None);
1491 let stmt = parser
1493 .parse_stmt(ForceCollect::No)
1494 .expect("failed to reparse")
1495 .expect("an actual stmt");
1496 match &stmt.kind {
1497 ast::StmtKind::Item(item) => item.clone(),
1498 _ => return,
1499 }
1500 }
1501 _ => return,
1502 };
1503 pretty_printing_compatibility_hack(&item, psess)
1504}