]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/base.rs
Auto merge of #83806 - JohnTitor:issue-51446, r=estebank
[rust.git] / compiler / rustc_expand / src / base.rs
1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirOwnership;
3
4 use rustc_ast::ptr::P;
5 use rustc_ast::token::{self, Nonterminal};
6 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, LazyTokenStream, TokenStream};
7 use rustc_ast::visit::{AssocCtxt, Visitor};
8 use rustc_ast::{self as ast, AstLike, Attribute, Item, NodeId, PatKind};
9 use rustc_attr::{self as attr, Deprecation, Stability};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::sync::{self, Lrc};
12 use rustc_errors::{DiagnosticBuilder, ErrorReported};
13 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
14 use rustc_lint_defs::BuiltinLintDiagnostics;
15 use rustc_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS};
16 use rustc_session::{parse::ParseSess, Limit, Session};
17 use rustc_span::def_id::DefId;
18 use rustc_span::edition::Edition;
19 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
20 use rustc_span::source_map::SourceMap;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
23 use smallvec::{smallvec, SmallVec};
24
25 use std::default::Default;
26 use std::iter;
27 use std::path::PathBuf;
28 use std::rc::Rc;
29
30 crate use rustc_span::hygiene::MacroKind;
31
32 #[derive(Debug, Clone)]
33 pub enum Annotatable {
34     Item(P<ast::Item>),
35     TraitItem(P<ast::AssocItem>),
36     ImplItem(P<ast::AssocItem>),
37     ForeignItem(P<ast::ForeignItem>),
38     Stmt(P<ast::Stmt>),
39     Expr(P<ast::Expr>),
40     Arm(ast::Arm),
41     ExprField(ast::ExprField),
42     PatField(ast::PatField),
43     GenericParam(ast::GenericParam),
44     Param(ast::Param),
45     FieldDef(ast::FieldDef),
46     Variant(ast::Variant),
47 }
48
49 impl AstLike for Annotatable {
50     fn attrs(&self) -> &[Attribute] {
51         match *self {
52             Annotatable::Item(ref item) => &item.attrs,
53             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
54             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
55             Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
56             Annotatable::Stmt(ref stmt) => stmt.attrs(),
57             Annotatable::Expr(ref expr) => &expr.attrs,
58             Annotatable::Arm(ref arm) => &arm.attrs,
59             Annotatable::ExprField(ref field) => &field.attrs,
60             Annotatable::PatField(ref fp) => &fp.attrs,
61             Annotatable::GenericParam(ref gp) => &gp.attrs,
62             Annotatable::Param(ref p) => &p.attrs,
63             Annotatable::FieldDef(ref sf) => &sf.attrs,
64             Annotatable::Variant(ref v) => &v.attrs(),
65         }
66     }
67
68     fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
69         match self {
70             Annotatable::Item(item) => item.visit_attrs(f),
71             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
72             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
73             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
74             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
75             Annotatable::Expr(expr) => expr.visit_attrs(f),
76             Annotatable::Arm(arm) => arm.visit_attrs(f),
77             Annotatable::ExprField(field) => field.visit_attrs(f),
78             Annotatable::PatField(fp) => fp.visit_attrs(f),
79             Annotatable::GenericParam(gp) => gp.visit_attrs(f),
80             Annotatable::Param(p) => p.visit_attrs(f),
81             Annotatable::FieldDef(sf) => sf.visit_attrs(f),
82             Annotatable::Variant(v) => v.visit_attrs(f),
83         }
84     }
85
86     fn tokens_mut(&mut self) -> Option<&mut Option<LazyTokenStream>> {
87         match self {
88             Annotatable::Item(item) => item.tokens_mut(),
89             Annotatable::TraitItem(trait_item) => trait_item.tokens_mut(),
90             Annotatable::ImplItem(impl_item) => impl_item.tokens_mut(),
91             Annotatable::ForeignItem(foreign_item) => foreign_item.tokens_mut(),
92             Annotatable::Stmt(stmt) => stmt.tokens_mut(),
93             Annotatable::Expr(expr) => expr.tokens_mut(),
94             Annotatable::Arm(arm) => arm.tokens_mut(),
95             Annotatable::ExprField(field) => field.tokens_mut(),
96             Annotatable::PatField(fp) => fp.tokens_mut(),
97             Annotatable::GenericParam(gp) => gp.tokens_mut(),
98             Annotatable::Param(p) => p.tokens_mut(),
99             Annotatable::FieldDef(sf) => sf.tokens_mut(),
100             Annotatable::Variant(v) => v.tokens_mut(),
101         }
102     }
103 }
104
105 impl Annotatable {
106     pub fn span(&self) -> Span {
107         match *self {
108             Annotatable::Item(ref item) => item.span,
109             Annotatable::TraitItem(ref trait_item) => trait_item.span,
110             Annotatable::ImplItem(ref impl_item) => impl_item.span,
111             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
112             Annotatable::Stmt(ref stmt) => stmt.span,
113             Annotatable::Expr(ref expr) => expr.span,
114             Annotatable::Arm(ref arm) => arm.span,
115             Annotatable::ExprField(ref field) => field.span,
116             Annotatable::PatField(ref fp) => fp.pat.span,
117             Annotatable::GenericParam(ref gp) => gp.ident.span,
118             Annotatable::Param(ref p) => p.span,
119             Annotatable::FieldDef(ref sf) => sf.span,
120             Annotatable::Variant(ref v) => v.span,
121         }
122     }
123
124     pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
125         match self {
126             Annotatable::Item(item) => visitor.visit_item(item),
127             Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
128             Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
129             Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
130             Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
131             Annotatable::Expr(expr) => visitor.visit_expr(expr),
132             Annotatable::Arm(arm) => visitor.visit_arm(arm),
133             Annotatable::ExprField(field) => visitor.visit_expr_field(field),
134             Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
135             Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
136             Annotatable::Param(p) => visitor.visit_param(p),
137             Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
138             Annotatable::Variant(v) => visitor.visit_variant(v),
139         }
140     }
141
142     crate fn into_nonterminal(self) -> Nonterminal {
143         match self {
144             Annotatable::Item(item) => token::NtItem(item),
145             Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
146                 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
147             }
148             Annotatable::ForeignItem(item) => {
149                 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
150             }
151             Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
152             Annotatable::Expr(expr) => token::NtExpr(expr),
153             Annotatable::Arm(..)
154             | Annotatable::ExprField(..)
155             | Annotatable::PatField(..)
156             | Annotatable::GenericParam(..)
157             | Annotatable::Param(..)
158             | Annotatable::FieldDef(..)
159             | Annotatable::Variant(..) => panic!("unexpected annotatable"),
160         }
161     }
162
163     crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
164         // Tokens of an attribute target may be invalidated by some outer `#[derive]` performing
165         // "full configuration" (attributes following derives on the same item should be the most
166         // common case), that's why synthesizing tokens is allowed.
167         nt_to_tokenstream(&self.into_nonterminal(), sess, CanSynthesizeMissingTokens::Yes)
168     }
169
170     pub fn expect_item(self) -> P<ast::Item> {
171         match self {
172             Annotatable::Item(i) => i,
173             _ => panic!("expected Item"),
174         }
175     }
176
177     pub fn expect_trait_item(self) -> P<ast::AssocItem> {
178         match self {
179             Annotatable::TraitItem(i) => i,
180             _ => panic!("expected Item"),
181         }
182     }
183
184     pub fn expect_impl_item(self) -> P<ast::AssocItem> {
185         match self {
186             Annotatable::ImplItem(i) => i,
187             _ => panic!("expected Item"),
188         }
189     }
190
191     pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
192         match self {
193             Annotatable::ForeignItem(i) => i,
194             _ => panic!("expected foreign item"),
195         }
196     }
197
198     pub fn expect_stmt(self) -> ast::Stmt {
199         match self {
200             Annotatable::Stmt(stmt) => stmt.into_inner(),
201             _ => panic!("expected statement"),
202         }
203     }
204
205     pub fn expect_expr(self) -> P<ast::Expr> {
206         match self {
207             Annotatable::Expr(expr) => expr,
208             _ => panic!("expected expression"),
209         }
210     }
211
212     pub fn expect_arm(self) -> ast::Arm {
213         match self {
214             Annotatable::Arm(arm) => arm,
215             _ => panic!("expected match arm"),
216         }
217     }
218
219     pub fn expect_expr_field(self) -> ast::ExprField {
220         match self {
221             Annotatable::ExprField(field) => field,
222             _ => panic!("expected field"),
223         }
224     }
225
226     pub fn expect_pat_field(self) -> ast::PatField {
227         match self {
228             Annotatable::PatField(fp) => fp,
229             _ => panic!("expected field pattern"),
230         }
231     }
232
233     pub fn expect_generic_param(self) -> ast::GenericParam {
234         match self {
235             Annotatable::GenericParam(gp) => gp,
236             _ => panic!("expected generic parameter"),
237         }
238     }
239
240     pub fn expect_param(self) -> ast::Param {
241         match self {
242             Annotatable::Param(param) => param,
243             _ => panic!("expected parameter"),
244         }
245     }
246
247     pub fn expect_field_def(self) -> ast::FieldDef {
248         match self {
249             Annotatable::FieldDef(sf) => sf,
250             _ => panic!("expected struct field"),
251         }
252     }
253
254     pub fn expect_variant(self) -> ast::Variant {
255         match self {
256             Annotatable::Variant(v) => v,
257             _ => panic!("expected variant"),
258         }
259     }
260 }
261
262 /// Result of an expansion that may need to be retried.
263 /// Consider using this for non-`MultiItemModifier` expanders as well.
264 pub enum ExpandResult<T, U> {
265     /// Expansion produced a result (possibly dummy).
266     Ready(T),
267     /// Expansion could not produce a result and needs to be retried.
268     Retry(U),
269 }
270
271 // `meta_item` is the attribute, and `item` is the item being modified.
272 pub trait MultiItemModifier {
273     fn expand(
274         &self,
275         ecx: &mut ExtCtxt<'_>,
276         span: Span,
277         meta_item: &ast::MetaItem,
278         item: Annotatable,
279     ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
280 }
281
282 impl<F> MultiItemModifier for F
283 where
284     F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
285 {
286     fn expand(
287         &self,
288         ecx: &mut ExtCtxt<'_>,
289         span: Span,
290         meta_item: &ast::MetaItem,
291         item: Annotatable,
292     ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
293         ExpandResult::Ready(self(ecx, span, meta_item, item))
294     }
295 }
296
297 pub trait ProcMacro {
298     fn expand<'cx>(
299         &self,
300         ecx: &'cx mut ExtCtxt<'_>,
301         span: Span,
302         ts: TokenStream,
303     ) -> Result<TokenStream, ErrorReported>;
304 }
305
306 impl<F> ProcMacro for F
307 where
308     F: Fn(TokenStream) -> TokenStream,
309 {
310     fn expand<'cx>(
311         &self,
312         _ecx: &'cx mut ExtCtxt<'_>,
313         _span: Span,
314         ts: TokenStream,
315     ) -> Result<TokenStream, ErrorReported> {
316         // FIXME setup implicit context in TLS before calling self.
317         Ok(self(ts))
318     }
319 }
320
321 pub trait AttrProcMacro {
322     fn expand<'cx>(
323         &self,
324         ecx: &'cx mut ExtCtxt<'_>,
325         span: Span,
326         annotation: TokenStream,
327         annotated: TokenStream,
328     ) -> Result<TokenStream, ErrorReported>;
329 }
330
331 impl<F> AttrProcMacro for F
332 where
333     F: Fn(TokenStream, TokenStream) -> TokenStream,
334 {
335     fn expand<'cx>(
336         &self,
337         _ecx: &'cx mut ExtCtxt<'_>,
338         _span: Span,
339         annotation: TokenStream,
340         annotated: TokenStream,
341     ) -> Result<TokenStream, ErrorReported> {
342         // FIXME setup implicit context in TLS before calling self.
343         Ok(self(annotation, annotated))
344     }
345 }
346
347 /// Represents a thing that maps token trees to Macro Results
348 pub trait TTMacroExpander {
349     fn expand<'cx>(
350         &self,
351         ecx: &'cx mut ExtCtxt<'_>,
352         span: Span,
353         input: TokenStream,
354     ) -> Box<dyn MacResult + 'cx>;
355 }
356
357 pub type MacroExpanderFn =
358     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
359
360 impl<F> TTMacroExpander for F
361 where
362     F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
363 {
364     fn expand<'cx>(
365         &self,
366         ecx: &'cx mut ExtCtxt<'_>,
367         span: Span,
368         input: TokenStream,
369     ) -> Box<dyn MacResult + 'cx> {
370         self(ecx, span, input)
371     }
372 }
373
374 // Use a macro because forwarding to a simple function has type system issues
375 macro_rules! make_stmts_default {
376     ($me:expr) => {
377         $me.make_expr().map(|e| {
378             smallvec![ast::Stmt {
379                 id: ast::DUMMY_NODE_ID,
380                 span: e.span,
381                 kind: ast::StmtKind::Expr(e),
382             }]
383         })
384     };
385 }
386
387 /// The result of a macro expansion. The return values of the various
388 /// methods are spliced into the AST at the callsite of the macro.
389 pub trait MacResult {
390     /// Creates an expression.
391     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
392         None
393     }
394     /// Creates zero or more items.
395     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
396         None
397     }
398
399     /// Creates zero or more impl items.
400     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
401         None
402     }
403
404     /// Creates zero or more trait items.
405     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
406         None
407     }
408
409     /// Creates zero or more items in an `extern {}` block
410     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
411         None
412     }
413
414     /// Creates a pattern.
415     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
416         None
417     }
418
419     /// Creates zero or more statements.
420     ///
421     /// By default this attempts to create an expression statement,
422     /// returning None if that fails.
423     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
424         make_stmts_default!(self)
425     }
426
427     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
428         None
429     }
430
431     fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
432         None
433     }
434
435     fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
436         None
437     }
438
439     fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
440         None
441     }
442
443     fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
444         None
445     }
446
447     fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
448         None
449     }
450
451     fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
452         None
453     }
454
455     fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
456         None
457     }
458 }
459
460 macro_rules! make_MacEager {
461     ( $( $fld:ident: $t:ty, )* ) => {
462         /// `MacResult` implementation for the common case where you've already
463         /// built each form of AST that you might return.
464         #[derive(Default)]
465         pub struct MacEager {
466             $(
467                 pub $fld: Option<$t>,
468             )*
469         }
470
471         impl MacEager {
472             $(
473                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
474                     Box::new(MacEager {
475                         $fld: Some(v),
476                         ..Default::default()
477                     })
478                 }
479             )*
480         }
481     }
482 }
483
484 make_MacEager! {
485     expr: P<ast::Expr>,
486     pat: P<ast::Pat>,
487     items: SmallVec<[P<ast::Item>; 1]>,
488     impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
489     trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
490     foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
491     stmts: SmallVec<[ast::Stmt; 1]>,
492     ty: P<ast::Ty>,
493 }
494
495 impl MacResult for MacEager {
496     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
497         self.expr
498     }
499
500     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
501         self.items
502     }
503
504     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
505         self.impl_items
506     }
507
508     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
509         self.trait_items
510     }
511
512     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
513         self.foreign_items
514     }
515
516     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
517         match self.stmts.as_ref().map_or(0, |s| s.len()) {
518             0 => make_stmts_default!(self),
519             _ => self.stmts,
520         }
521     }
522
523     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
524         if let Some(p) = self.pat {
525             return Some(p);
526         }
527         if let Some(e) = self.expr {
528             if let ast::ExprKind::Lit(_) = e.kind {
529                 return Some(P(ast::Pat {
530                     id: ast::DUMMY_NODE_ID,
531                     span: e.span,
532                     kind: PatKind::Lit(e),
533                     tokens: None,
534                 }));
535             }
536         }
537         None
538     }
539
540     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
541         self.ty
542     }
543 }
544
545 /// Fill-in macro expansion result, to allow compilation to continue
546 /// after hitting errors.
547 #[derive(Copy, Clone)]
548 pub struct DummyResult {
549     is_error: bool,
550     span: Span,
551 }
552
553 impl DummyResult {
554     /// Creates a default MacResult that can be anything.
555     ///
556     /// Use this as a return value after hitting any errors and
557     /// calling `span_err`.
558     pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
559         Box::new(DummyResult { is_error: true, span })
560     }
561
562     /// Same as `any`, but must be a valid fragment, not error.
563     pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
564         Box::new(DummyResult { is_error: false, span })
565     }
566
567     /// A plain dummy expression.
568     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
569         P(ast::Expr {
570             id: ast::DUMMY_NODE_ID,
571             kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
572             span: sp,
573             attrs: ast::AttrVec::new(),
574             tokens: None,
575         })
576     }
577
578     /// A plain dummy pattern.
579     pub fn raw_pat(sp: Span) -> ast::Pat {
580         ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
581     }
582
583     /// A plain dummy type.
584     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
585         P(ast::Ty {
586             id: ast::DUMMY_NODE_ID,
587             kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
588             span: sp,
589             tokens: None,
590         })
591     }
592 }
593
594 impl MacResult for DummyResult {
595     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
596         Some(DummyResult::raw_expr(self.span, self.is_error))
597     }
598
599     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
600         Some(P(DummyResult::raw_pat(self.span)))
601     }
602
603     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
604         Some(SmallVec::new())
605     }
606
607     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
608         Some(SmallVec::new())
609     }
610
611     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
612         Some(SmallVec::new())
613     }
614
615     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
616         Some(SmallVec::new())
617     }
618
619     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
620         Some(smallvec![ast::Stmt {
621             id: ast::DUMMY_NODE_ID,
622             kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
623             span: self.span,
624         }])
625     }
626
627     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
628         Some(DummyResult::raw_ty(self.span, self.is_error))
629     }
630
631     fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
632         Some(SmallVec::new())
633     }
634
635     fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
636         Some(SmallVec::new())
637     }
638
639     fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
640         Some(SmallVec::new())
641     }
642
643     fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
644         Some(SmallVec::new())
645     }
646
647     fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
648         Some(SmallVec::new())
649     }
650
651     fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
652         Some(SmallVec::new())
653     }
654
655     fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
656         Some(SmallVec::new())
657     }
658 }
659
660 /// A syntax extension kind.
661 pub enum SyntaxExtensionKind {
662     /// A token-based function-like macro.
663     Bang(
664         /// An expander with signature TokenStream -> TokenStream.
665         Box<dyn ProcMacro + sync::Sync + sync::Send>,
666     ),
667
668     /// An AST-based function-like macro.
669     LegacyBang(
670         /// An expander with signature TokenStream -> AST.
671         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
672     ),
673
674     /// A token-based attribute macro.
675     Attr(
676         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
677         /// The first TokenSteam is the attribute itself, the second is the annotated item.
678         /// The produced TokenSteam replaces the input TokenSteam.
679         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
680     ),
681
682     /// An AST-based attribute macro.
683     LegacyAttr(
684         /// An expander with signature (AST, AST) -> AST.
685         /// The first AST fragment is the attribute itself, the second is the annotated item.
686         /// The produced AST fragment replaces the input AST fragment.
687         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
688     ),
689
690     /// A trivial attribute "macro" that does nothing,
691     /// only keeps the attribute and marks it as inert,
692     /// thus making it ineligible for further expansion.
693     NonMacroAttr {
694         /// Suppresses the `unused_attributes` lint for this attribute.
695         mark_used: bool,
696     },
697
698     /// A token-based derive macro.
699     Derive(
700         /// An expander with signature TokenStream -> TokenStream (not yet).
701         /// The produced TokenSteam is appended to the input TokenSteam.
702         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
703     ),
704
705     /// An AST-based derive macro.
706     LegacyDerive(
707         /// An expander with signature AST -> AST.
708         /// The produced AST fragment is appended to the input AST fragment.
709         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
710     ),
711 }
712
713 /// A struct representing a macro definition in "lowered" form ready for expansion.
714 pub struct SyntaxExtension {
715     /// A syntax extension kind.
716     pub kind: SyntaxExtensionKind,
717     /// Span of the macro definition.
718     pub span: Span,
719     /// List of unstable features that are treated as stable inside this macro.
720     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
721     /// Suppresses the `unsafe_code` lint for code produced by this macro.
722     pub allow_internal_unsafe: bool,
723     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
724     pub local_inner_macros: bool,
725     /// The macro's stability info.
726     pub stability: Option<Stability>,
727     /// The macro's deprecation info.
728     pub deprecation: Option<Deprecation>,
729     /// Names of helper attributes registered by this macro.
730     pub helper_attrs: Vec<Symbol>,
731     /// Edition of the crate in which this macro is defined.
732     pub edition: Edition,
733     /// Built-in macros have a couple of special properties like availability
734     /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
735     pub builtin_name: Option<Symbol>,
736 }
737
738 impl SyntaxExtension {
739     /// Returns which kind of macro calls this syntax extension.
740     pub fn macro_kind(&self) -> MacroKind {
741         match self.kind {
742             SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
743             SyntaxExtensionKind::Attr(..)
744             | SyntaxExtensionKind::LegacyAttr(..)
745             | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
746             SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
747                 MacroKind::Derive
748             }
749         }
750     }
751
752     /// Constructs a syntax extension with default properties.
753     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
754         SyntaxExtension {
755             span: DUMMY_SP,
756             allow_internal_unstable: None,
757             allow_internal_unsafe: false,
758             local_inner_macros: false,
759             stability: None,
760             deprecation: None,
761             helper_attrs: Vec::new(),
762             edition,
763             builtin_name: None,
764             kind,
765         }
766     }
767
768     /// Constructs a syntax extension with the given properties
769     /// and other properties converted from attributes.
770     pub fn new(
771         sess: &Session,
772         kind: SyntaxExtensionKind,
773         span: Span,
774         helper_attrs: Vec<Symbol>,
775         edition: Edition,
776         name: Symbol,
777         attrs: &[ast::Attribute],
778     ) -> SyntaxExtension {
779         let allow_internal_unstable =
780             attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
781
782         let mut local_inner_macros = false;
783         if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
784             if let Some(l) = macro_export.meta_item_list() {
785                 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
786             }
787         }
788
789         let builtin_name = sess
790             .find_by_name(attrs, sym::rustc_builtin_macro)
791             .map(|a| a.value_str().unwrap_or(name));
792         let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
793         if let Some((_, sp)) = const_stability {
794             sess.parse_sess
795                 .span_diagnostic
796                 .struct_span_err(sp, "macros cannot have const stability attributes")
797                 .span_label(sp, "invalid const stability attribute")
798                 .span_label(
799                     sess.source_map().guess_head_span(span),
800                     "const stability attribute affects this macro",
801                 )
802                 .emit();
803         }
804
805         SyntaxExtension {
806             kind,
807             span,
808             allow_internal_unstable: (!allow_internal_unstable.is_empty())
809                 .then(|| allow_internal_unstable.into()),
810             allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
811             local_inner_macros,
812             stability: stability.map(|(s, _)| s),
813             deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
814             helper_attrs,
815             edition,
816             builtin_name,
817         }
818     }
819
820     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
821         fn expander<'cx>(
822             _: &'cx mut ExtCtxt<'_>,
823             span: Span,
824             _: TokenStream,
825         ) -> Box<dyn MacResult + 'cx> {
826             DummyResult::any(span)
827         }
828         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
829     }
830
831     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
832         fn expander(
833             _: &mut ExtCtxt<'_>,
834             _: Span,
835             _: &ast::MetaItem,
836             _: Annotatable,
837         ) -> Vec<Annotatable> {
838             Vec::new()
839         }
840         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
841     }
842
843     pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
844         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
845     }
846
847     pub fn expn_data(
848         &self,
849         parent: ExpnId,
850         call_site: Span,
851         descr: Symbol,
852         macro_def_id: Option<DefId>,
853     ) -> ExpnData {
854         ExpnData::new(
855             ExpnKind::Macro(self.macro_kind(), descr),
856             parent,
857             call_site,
858             self.span,
859             self.allow_internal_unstable.clone(),
860             self.allow_internal_unsafe,
861             self.local_inner_macros,
862             self.edition,
863             macro_def_id,
864         )
865     }
866 }
867
868 /// Error type that denotes indeterminacy.
869 pub struct Indeterminate;
870
871 pub type DeriveResolutions = Vec<(ast::Path, Option<Lrc<SyntaxExtension>>)>;
872
873 pub trait ResolverExpand {
874     fn next_node_id(&mut self) -> NodeId;
875
876     fn resolve_dollar_crates(&mut self);
877     fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
878     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
879
880     fn expansion_for_ast_pass(
881         &mut self,
882         call_site: Span,
883         pass: AstPass,
884         features: &[Symbol],
885         parent_module_id: Option<NodeId>,
886     ) -> ExpnId;
887
888     fn resolve_imports(&mut self);
889
890     fn resolve_macro_invocation(
891         &mut self,
892         invoc: &Invocation,
893         eager_expansion_root: ExpnId,
894         force: bool,
895     ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
896
897     fn check_unused_macros(&mut self);
898
899     /// Some parent node that is close enough to the given macro call.
900     fn lint_node_id(&self, expn_id: ExpnId) -> NodeId;
901
902     // Resolver interfaces for specific built-in macros.
903     /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
904     fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
905     /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
906     fn resolve_derives(
907         &mut self,
908         expn_id: ExpnId,
909         force: bool,
910         derive_paths: &dyn Fn() -> DeriveResolutions,
911     ) -> Result<(), Indeterminate>;
912     /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
913     /// back from resolver.
914     fn take_derive_resolutions(&mut self, expn_id: ExpnId) -> Option<DeriveResolutions>;
915     /// Path resolution logic for `#[cfg_accessible(path)]`.
916     fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;
917 }
918
919 #[derive(Clone, Default)]
920 pub struct ModuleData {
921     /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
922     pub mod_path: Vec<Ident>,
923     /// Stack of paths to files loaded by out-of-line module items,
924     /// used to detect and report recursive module inclusions.
925     pub file_path_stack: Vec<PathBuf>,
926     /// Directory to search child module files in,
927     /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
928     pub dir_path: PathBuf,
929 }
930
931 impl ModuleData {
932     pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
933         ModuleData {
934             mod_path: self.mod_path.clone(),
935             file_path_stack: self.file_path_stack.clone(),
936             dir_path,
937         }
938     }
939 }
940
941 #[derive(Clone)]
942 pub struct ExpansionData {
943     pub id: ExpnId,
944     pub depth: usize,
945     pub module: Rc<ModuleData>,
946     pub dir_ownership: DirOwnership,
947     pub prior_type_ascription: Option<(Span, bool)>,
948 }
949
950 type OnExternModLoaded<'a> =
951     Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
952
953 /// One of these is made during expansion and incrementally updated as we go;
954 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
955 /// -> expn_data` of their expansion context stored into their span.
956 pub struct ExtCtxt<'a> {
957     pub sess: &'a Session,
958     pub ecfg: expand::ExpansionConfig<'a>,
959     pub reduced_recursion_limit: Option<Limit>,
960     pub root_path: PathBuf,
961     pub resolver: &'a mut dyn ResolverExpand,
962     pub current_expansion: ExpansionData,
963     /// Error recovery mode entered when expansion is stuck
964     /// (or during eager expansion, but that's a hack).
965     pub force_mode: bool,
966     pub expansions: FxHashMap<Span, Vec<String>>,
967     /// Called directly after having parsed an external `mod foo;` in expansion.
968     ///
969     /// `Ident` is the module name.
970     pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
971 }
972
973 impl<'a> ExtCtxt<'a> {
974     pub fn new(
975         sess: &'a Session,
976         ecfg: expand::ExpansionConfig<'a>,
977         resolver: &'a mut dyn ResolverExpand,
978         extern_mod_loaded: OnExternModLoaded<'a>,
979     ) -> ExtCtxt<'a> {
980         ExtCtxt {
981             sess,
982             ecfg,
983             reduced_recursion_limit: None,
984             resolver,
985             extern_mod_loaded,
986             root_path: PathBuf::new(),
987             current_expansion: ExpansionData {
988                 id: ExpnId::root(),
989                 depth: 0,
990                 module: Default::default(),
991                 dir_ownership: DirOwnership::Owned { relative: None },
992                 prior_type_ascription: None,
993             },
994             force_mode: false,
995             expansions: FxHashMap::default(),
996         }
997     }
998
999     /// Returns a `Folder` for deeply expanding all macros in an AST node.
1000     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1001         expand::MacroExpander::new(self, false)
1002     }
1003
1004     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1005     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1006     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1007         expand::MacroExpander::new(self, true)
1008     }
1009     pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1010         rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1011     }
1012     pub fn source_map(&self) -> &'a SourceMap {
1013         self.sess.parse_sess.source_map()
1014     }
1015     pub fn parse_sess(&self) -> &'a ParseSess {
1016         &self.sess.parse_sess
1017     }
1018     pub fn call_site(&self) -> Span {
1019         self.current_expansion.id.expn_data().call_site
1020     }
1021
1022     /// Equivalent of `Span::def_site` from the proc macro API,
1023     /// except that the location is taken from the span passed as an argument.
1024     pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1025         span.with_def_site_ctxt(self.current_expansion.id)
1026     }
1027
1028     /// Equivalent of `Span::call_site` from the proc macro API,
1029     /// except that the location is taken from the span passed as an argument.
1030     pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1031         span.with_call_site_ctxt(self.current_expansion.id)
1032     }
1033
1034     /// Equivalent of `Span::mixed_site` from the proc macro API,
1035     /// except that the location is taken from the span passed as an argument.
1036     pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1037         span.with_mixed_site_ctxt(self.current_expansion.id)
1038     }
1039
1040     /// Returns span for the macro which originally caused the current expansion to happen.
1041     ///
1042     /// Stops backtracing at include! boundary.
1043     pub fn expansion_cause(&self) -> Option<Span> {
1044         self.current_expansion.id.expansion_cause()
1045     }
1046
1047     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1048         self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1049     }
1050
1051     /// Emit `msg` attached to `sp`, without immediately stopping
1052     /// compilation.
1053     ///
1054     /// Compilation will be stopped in the near future (at the end of
1055     /// the macro expansion phase).
1056     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1057         self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1058     }
1059     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1060         self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1061     }
1062     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1063         self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1064     }
1065     pub fn trace_macros_diag(&mut self) {
1066         for (sp, notes) in self.expansions.iter() {
1067             let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1068             for note in notes {
1069                 db.note(note);
1070             }
1071             db.emit();
1072         }
1073         // Fixme: does this result in errors?
1074         self.expansions.clear();
1075     }
1076     pub fn bug(&self, msg: &str) -> ! {
1077         self.sess.parse_sess.span_diagnostic.bug(msg);
1078     }
1079     pub fn trace_macros(&self) -> bool {
1080         self.ecfg.trace_mac
1081     }
1082     pub fn set_trace_macros(&mut self, x: bool) {
1083         self.ecfg.trace_mac = x
1084     }
1085     pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1086         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1087         iter::once(Ident::new(kw::DollarCrate, def_site))
1088             .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1089             .collect()
1090     }
1091     pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1092         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1093         components.iter().map(|&s| Ident::new(s, def_site)).collect()
1094     }
1095
1096     pub fn check_unused_macros(&mut self) {
1097         self.resolver.check_unused_macros();
1098     }
1099
1100     /// Resolves a path mentioned inside Rust code.
1101     ///
1102     /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1103     ///
1104     /// Returns an absolute path to the file that `path` refers to.
1105     pub fn resolve_path(
1106         &self,
1107         path: impl Into<PathBuf>,
1108         span: Span,
1109     ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1110         let path = path.into();
1111
1112         // Relative paths are resolved relative to the file in which they are found
1113         // after macro expansion (that is, they are unhygienic).
1114         if !path.is_absolute() {
1115             let callsite = span.source_callsite();
1116             let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1117                 FileName::Real(name) => name.into_local_path(),
1118                 FileName::DocTest(path, _) => path,
1119                 other => {
1120                     return Err(self.struct_span_err(
1121                         span,
1122                         &format!("cannot resolve relative path in non-file source `{}`", other),
1123                     ));
1124                 }
1125             };
1126             result.pop();
1127             result.push(path);
1128             Ok(result)
1129         } else {
1130             Ok(path)
1131         }
1132     }
1133 }
1134
1135 /// Extracts a string literal from the macro expanded version of `expr`,
1136 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1137 /// compilation on error, merely emits a non-fatal error and returns `None`.
1138 pub fn expr_to_spanned_string<'a>(
1139     cx: &'a mut ExtCtxt<'_>,
1140     expr: P<ast::Expr>,
1141     err_msg: &str,
1142 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1143     // Perform eager expansion on the expression.
1144     // We want to be able to handle e.g., `concat!("foo", "bar")`.
1145     let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1146
1147     Err(match expr.kind {
1148         ast::ExprKind::Lit(ref l) => match l.kind {
1149             ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1150             ast::LitKind::Err(_) => None,
1151             _ => Some(cx.struct_span_err(l.span, err_msg)),
1152         },
1153         ast::ExprKind::Err => None,
1154         _ => Some(cx.struct_span_err(expr.span, err_msg)),
1155     })
1156 }
1157
1158 pub fn expr_to_string(
1159     cx: &mut ExtCtxt<'_>,
1160     expr: P<ast::Expr>,
1161     err_msg: &str,
1162 ) -> Option<(Symbol, ast::StrStyle)> {
1163     expr_to_spanned_string(cx, expr, err_msg)
1164         .map_err(|err| {
1165             err.map(|mut err| {
1166                 err.emit();
1167             })
1168         })
1169         .ok()
1170         .map(|(symbol, style, _)| (symbol, style))
1171 }
1172
1173 /// Non-fatally assert that `tts` is empty. Note that this function
1174 /// returns even when `tts` is non-empty, macros that *need* to stop
1175 /// compilation should call
1176 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1177 /// done as rarely as possible).
1178 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1179     if !tts.is_empty() {
1180         cx.span_err(sp, &format!("{} takes no arguments", name));
1181     }
1182 }
1183
1184 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1185 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1186     match p.parse_expr() {
1187         Ok(e) => return Some(e),
1188         Err(mut err) => err.emit(),
1189     }
1190     while p.token != token::Eof {
1191         p.bump();
1192     }
1193     None
1194 }
1195
1196 /// Interpreting `tts` as a comma-separated sequence of expressions,
1197 /// expect exactly one string literal, or emit an error and return `None`.
1198 pub fn get_single_str_from_tts(
1199     cx: &mut ExtCtxt<'_>,
1200     sp: Span,
1201     tts: TokenStream,
1202     name: &str,
1203 ) -> Option<String> {
1204     let mut p = cx.new_parser_from_tts(tts);
1205     if p.token == token::Eof {
1206         cx.span_err(sp, &format!("{} takes 1 argument", name));
1207         return None;
1208     }
1209     let ret = parse_expr(&mut p)?;
1210     let _ = p.eat(&token::Comma);
1211
1212     if p.token != token::Eof {
1213         cx.span_err(sp, &format!("{} takes 1 argument", name));
1214     }
1215     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1216 }
1217
1218 /// Extracts comma-separated expressions from `tts`.
1219 /// On error, emit it, and return `None`.
1220 pub fn get_exprs_from_tts(
1221     cx: &mut ExtCtxt<'_>,
1222     sp: Span,
1223     tts: TokenStream,
1224 ) -> Option<Vec<P<ast::Expr>>> {
1225     let mut p = cx.new_parser_from_tts(tts);
1226     let mut es = Vec::new();
1227     while p.token != token::Eof {
1228         let expr = parse_expr(&mut p)?;
1229
1230         // Perform eager expansion on the expression.
1231         // We want to be able to handle e.g., `concat!("foo", "bar")`.
1232         let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1233
1234         es.push(expr);
1235         if p.eat(&token::Comma) {
1236             continue;
1237         }
1238         if p.token != token::Eof {
1239             cx.span_err(sp, "expected token: `,`");
1240             return None;
1241         }
1242     }
1243     Some(es)
1244 }
1245
1246 /// This nonterminal looks like some specific enums from
1247 /// `proc-macro-hack` and `procedural-masquerade` crates.
1248 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1249 /// asserts in old versions of those crates and their wide use in the ecosystem.
1250 /// See issue #73345 for more details.
1251 /// FIXME(#73933): Remove this eventually.
1252 pub(crate) fn pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1253     let item = match nt {
1254         Nonterminal::NtItem(item) => item,
1255         Nonterminal::NtStmt(stmt) => match &stmt.kind {
1256             ast::StmtKind::Item(item) => item,
1257             _ => return false,
1258         },
1259         _ => return false,
1260     };
1261
1262     let name = item.ident.name;
1263     if name == sym::ProceduralMasqueradeDummyType {
1264         if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1265             if let [variant] = &*enum_def.variants {
1266                 if variant.ident.name == sym::Input {
1267                     sess.buffer_lint_with_diagnostic(
1268                         &PROC_MACRO_BACK_COMPAT,
1269                         item.ident.span,
1270                         ast::CRATE_NODE_ID,
1271                         "using `procedural-masquerade` crate",
1272                         BuiltinLintDiagnostics::ProcMacroBackCompat(
1273                         "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1274                         Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())
1275                     );
1276                     return true;
1277                 }
1278             }
1279         }
1280     }
1281     false
1282 }