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