]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/base.rs
Auto merge of #87712 - est31:line-column-1-based, r=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::{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};
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     /// Creates zero or more items.
358     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
359         None
360     }
361
362     /// Creates zero or more impl items.
363     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
364         None
365     }
366
367     /// Creates zero or more trait items.
368     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
369         None
370     }
371
372     /// Creates zero or more items in an `extern {}` block
373     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
374         None
375     }
376
377     /// Creates a pattern.
378     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
379         None
380     }
381
382     /// Creates zero or more statements.
383     ///
384     /// By default this attempts to create an expression statement,
385     /// returning None if that fails.
386     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
387         make_stmts_default!(self)
388     }
389
390     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
391         None
392     }
393
394     fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
395         None
396     }
397
398     fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
399         None
400     }
401
402     fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
403         None
404     }
405
406     fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
407         None
408     }
409
410     fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
411         None
412     }
413
414     fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
415         None
416     }
417
418     fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
419         None
420     }
421 }
422
423 macro_rules! make_MacEager {
424     ( $( $fld:ident: $t:ty, )* ) => {
425         /// `MacResult` implementation for the common case where you've already
426         /// built each form of AST that you might return.
427         #[derive(Default)]
428         pub struct MacEager {
429             $(
430                 pub $fld: Option<$t>,
431             )*
432         }
433
434         impl MacEager {
435             $(
436                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
437                     Box::new(MacEager {
438                         $fld: Some(v),
439                         ..Default::default()
440                     })
441                 }
442             )*
443         }
444     }
445 }
446
447 make_MacEager! {
448     expr: P<ast::Expr>,
449     pat: P<ast::Pat>,
450     items: SmallVec<[P<ast::Item>; 1]>,
451     impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
452     trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
453     foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
454     stmts: SmallVec<[ast::Stmt; 1]>,
455     ty: P<ast::Ty>,
456 }
457
458 impl MacResult for MacEager {
459     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
460         self.expr
461     }
462
463     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
464         self.items
465     }
466
467     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
468         self.impl_items
469     }
470
471     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
472         self.trait_items
473     }
474
475     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
476         self.foreign_items
477     }
478
479     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
480         match self.stmts.as_ref().map_or(0, |s| s.len()) {
481             0 => make_stmts_default!(self),
482             _ => self.stmts,
483         }
484     }
485
486     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
487         if let Some(p) = self.pat {
488             return Some(p);
489         }
490         if let Some(e) = self.expr {
491             if let ast::ExprKind::Lit(_) = e.kind {
492                 return Some(P(ast::Pat {
493                     id: ast::DUMMY_NODE_ID,
494                     span: e.span,
495                     kind: PatKind::Lit(e),
496                     tokens: None,
497                 }));
498             }
499         }
500         None
501     }
502
503     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
504         self.ty
505     }
506 }
507
508 /// Fill-in macro expansion result, to allow compilation to continue
509 /// after hitting errors.
510 #[derive(Copy, Clone)]
511 pub struct DummyResult {
512     is_error: bool,
513     span: Span,
514 }
515
516 impl DummyResult {
517     /// Creates a default MacResult that can be anything.
518     ///
519     /// Use this as a return value after hitting any errors and
520     /// calling `span_err`.
521     pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
522         Box::new(DummyResult { is_error: true, span })
523     }
524
525     /// Same as `any`, but must be a valid fragment, not error.
526     pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
527         Box::new(DummyResult { is_error: false, span })
528     }
529
530     /// A plain dummy expression.
531     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
532         P(ast::Expr {
533             id: ast::DUMMY_NODE_ID,
534             kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
535             span: sp,
536             attrs: ast::AttrVec::new(),
537             tokens: None,
538         })
539     }
540
541     /// A plain dummy pattern.
542     pub fn raw_pat(sp: Span) -> ast::Pat {
543         ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
544     }
545
546     /// A plain dummy type.
547     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
548         P(ast::Ty {
549             id: ast::DUMMY_NODE_ID,
550             kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
551             span: sp,
552             tokens: None,
553         })
554     }
555 }
556
557 impl MacResult for DummyResult {
558     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
559         Some(DummyResult::raw_expr(self.span, self.is_error))
560     }
561
562     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
563         Some(P(DummyResult::raw_pat(self.span)))
564     }
565
566     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
567         Some(SmallVec::new())
568     }
569
570     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
571         Some(SmallVec::new())
572     }
573
574     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
575         Some(SmallVec::new())
576     }
577
578     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
579         Some(SmallVec::new())
580     }
581
582     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
583         Some(smallvec![ast::Stmt {
584             id: ast::DUMMY_NODE_ID,
585             kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
586             span: self.span,
587         }])
588     }
589
590     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
591         Some(DummyResult::raw_ty(self.span, self.is_error))
592     }
593
594     fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
595         Some(SmallVec::new())
596     }
597
598     fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
599         Some(SmallVec::new())
600     }
601
602     fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
603         Some(SmallVec::new())
604     }
605
606     fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
607         Some(SmallVec::new())
608     }
609
610     fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
611         Some(SmallVec::new())
612     }
613
614     fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
615         Some(SmallVec::new())
616     }
617
618     fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
619         Some(SmallVec::new())
620     }
621 }
622
623 /// A syntax extension kind.
624 pub enum SyntaxExtensionKind {
625     /// A token-based function-like macro.
626     Bang(
627         /// An expander with signature TokenStream -> TokenStream.
628         Box<dyn ProcMacro + sync::Sync + sync::Send>,
629     ),
630
631     /// An AST-based function-like macro.
632     LegacyBang(
633         /// An expander with signature TokenStream -> AST.
634         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
635     ),
636
637     /// A token-based attribute macro.
638     Attr(
639         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
640         /// The first TokenSteam is the attribute itself, the second is the annotated item.
641         /// The produced TokenSteam replaces the input TokenSteam.
642         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
643     ),
644
645     /// An AST-based attribute macro.
646     LegacyAttr(
647         /// An expander with signature (AST, AST) -> AST.
648         /// The first AST fragment is the attribute itself, the second is the annotated item.
649         /// The produced AST fragment replaces the input AST fragment.
650         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
651     ),
652
653     /// A trivial attribute "macro" that does nothing,
654     /// only keeps the attribute and marks it as inert,
655     /// thus making it ineligible for further expansion.
656     NonMacroAttr {
657         /// Suppresses the `unused_attributes` lint for this attribute.
658         mark_used: bool,
659     },
660
661     /// A token-based derive macro.
662     Derive(
663         /// An expander with signature TokenStream -> TokenStream (not yet).
664         /// The produced TokenSteam is appended to the input TokenSteam.
665         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
666     ),
667
668     /// An AST-based derive macro.
669     LegacyDerive(
670         /// An expander with signature AST -> AST.
671         /// The produced AST fragment is appended to the input AST fragment.
672         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
673     ),
674 }
675
676 /// A struct representing a macro definition in "lowered" form ready for expansion.
677 pub struct SyntaxExtension {
678     /// A syntax extension kind.
679     pub kind: SyntaxExtensionKind,
680     /// Span of the macro definition.
681     pub span: Span,
682     /// List of unstable features that are treated as stable inside this macro.
683     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
684     /// Suppresses the `unsafe_code` lint for code produced by this macro.
685     pub allow_internal_unsafe: bool,
686     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
687     pub local_inner_macros: bool,
688     /// The macro's stability info.
689     pub stability: Option<Stability>,
690     /// The macro's deprecation info.
691     pub deprecation: Option<Deprecation>,
692     /// Names of helper attributes registered by this macro.
693     pub helper_attrs: Vec<Symbol>,
694     /// Edition of the crate in which this macro is defined.
695     pub edition: Edition,
696     /// Built-in macros have a couple of special properties like availability
697     /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
698     pub builtin_name: Option<Symbol>,
699 }
700
701 impl SyntaxExtension {
702     /// Returns which kind of macro calls this syntax extension.
703     pub fn macro_kind(&self) -> MacroKind {
704         match self.kind {
705             SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
706             SyntaxExtensionKind::Attr(..)
707             | SyntaxExtensionKind::LegacyAttr(..)
708             | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
709             SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
710                 MacroKind::Derive
711             }
712         }
713     }
714
715     /// Constructs a syntax extension with default properties.
716     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
717         SyntaxExtension {
718             span: DUMMY_SP,
719             allow_internal_unstable: None,
720             allow_internal_unsafe: false,
721             local_inner_macros: false,
722             stability: None,
723             deprecation: None,
724             helper_attrs: Vec::new(),
725             edition,
726             builtin_name: None,
727             kind,
728         }
729     }
730
731     /// Constructs a syntax extension with the given properties
732     /// and other properties converted from attributes.
733     pub fn new(
734         sess: &Session,
735         kind: SyntaxExtensionKind,
736         span: Span,
737         helper_attrs: Vec<Symbol>,
738         edition: Edition,
739         name: Symbol,
740         attrs: &[ast::Attribute],
741     ) -> SyntaxExtension {
742         let allow_internal_unstable =
743             attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
744
745         let mut local_inner_macros = false;
746         if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
747             if let Some(l) = macro_export.meta_item_list() {
748                 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
749             }
750         }
751
752         let (builtin_name, helper_attrs) = sess
753             .find_by_name(attrs, sym::rustc_builtin_macro)
754             .map(|attr| {
755                 // Override `helper_attrs` passed above if it's a built-in macro,
756                 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
757                 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
758                     || (Some(name), Vec::new()),
759                     |(name, helper_attrs)| (Some(name), helper_attrs),
760                 )
761             })
762             .unwrap_or_else(|| (None, helper_attrs));
763         let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
764         if let Some((_, sp)) = const_stability {
765             sess.parse_sess
766                 .span_diagnostic
767                 .struct_span_err(sp, "macros cannot have const stability attributes")
768                 .span_label(sp, "invalid const stability attribute")
769                 .span_label(
770                     sess.source_map().guess_head_span(span),
771                     "const stability attribute affects this macro",
772                 )
773                 .emit();
774         }
775
776         SyntaxExtension {
777             kind,
778             span,
779             allow_internal_unstable: (!allow_internal_unstable.is_empty())
780                 .then(|| allow_internal_unstable.into()),
781             allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
782             local_inner_macros,
783             stability: stability.map(|(s, _)| s),
784             deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
785             helper_attrs,
786             edition,
787             builtin_name,
788         }
789     }
790
791     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
792         fn expander<'cx>(
793             _: &'cx mut ExtCtxt<'_>,
794             span: Span,
795             _: TokenStream,
796         ) -> Box<dyn MacResult + 'cx> {
797             DummyResult::any(span)
798         }
799         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
800     }
801
802     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
803         fn expander(
804             _: &mut ExtCtxt<'_>,
805             _: Span,
806             _: &ast::MetaItem,
807             _: Annotatable,
808         ) -> Vec<Annotatable> {
809             Vec::new()
810         }
811         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
812     }
813
814     pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
815         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
816     }
817
818     pub fn expn_data(
819         &self,
820         parent: LocalExpnId,
821         call_site: Span,
822         descr: Symbol,
823         macro_def_id: Option<DefId>,
824         parent_module: Option<DefId>,
825     ) -> ExpnData {
826         ExpnData::new(
827             ExpnKind::Macro(self.macro_kind(), descr),
828             parent.to_expn_id(),
829             call_site,
830             self.span,
831             self.allow_internal_unstable.clone(),
832             self.allow_internal_unsafe,
833             self.local_inner_macros,
834             self.edition,
835             macro_def_id,
836             parent_module,
837         )
838     }
839 }
840
841 /// Error type that denotes indeterminacy.
842 pub struct Indeterminate;
843
844 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
845
846 pub trait ResolverExpand {
847     fn next_node_id(&mut self) -> NodeId;
848
849     fn resolve_dollar_crates(&mut self);
850     fn visit_ast_fragment_with_placeholders(
851         &mut self,
852         expn_id: LocalExpnId,
853         fragment: &AstFragment,
854     );
855     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
856
857     fn expansion_for_ast_pass(
858         &mut self,
859         call_site: Span,
860         pass: AstPass,
861         features: &[Symbol],
862         parent_module_id: Option<NodeId>,
863     ) -> LocalExpnId;
864
865     fn resolve_imports(&mut self);
866
867     fn resolve_macro_invocation(
868         &mut self,
869         invoc: &Invocation,
870         eager_expansion_root: LocalExpnId,
871         force: bool,
872     ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
873
874     fn check_unused_macros(&mut self);
875
876     // Resolver interfaces for specific built-in macros.
877     /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
878     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
879     /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
880     fn resolve_derives(
881         &mut self,
882         expn_id: LocalExpnId,
883         force: bool,
884         derive_paths: &dyn Fn() -> DeriveResolutions,
885     ) -> Result<(), Indeterminate>;
886     /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
887     /// back from resolver.
888     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
889     /// Path resolution logic for `#[cfg_accessible(path)]`.
890     fn cfg_accessible(
891         &mut self,
892         expn_id: LocalExpnId,
893         path: &ast::Path,
894     ) -> Result<bool, Indeterminate>;
895
896     /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
897     /// No caching is performed.
898     fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
899 }
900
901 #[derive(Clone, Default)]
902 pub struct ModuleData {
903     /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
904     pub mod_path: Vec<Ident>,
905     /// Stack of paths to files loaded by out-of-line module items,
906     /// used to detect and report recursive module inclusions.
907     pub file_path_stack: Vec<PathBuf>,
908     /// Directory to search child module files in,
909     /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
910     pub dir_path: PathBuf,
911 }
912
913 impl ModuleData {
914     pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
915         ModuleData {
916             mod_path: self.mod_path.clone(),
917             file_path_stack: self.file_path_stack.clone(),
918             dir_path,
919         }
920     }
921 }
922
923 #[derive(Clone)]
924 pub struct ExpansionData {
925     pub id: LocalExpnId,
926     pub depth: usize,
927     pub module: Rc<ModuleData>,
928     pub dir_ownership: DirOwnership,
929     pub prior_type_ascription: Option<(Span, bool)>,
930     /// Some parent node that is close to this macro call
931     pub lint_node_id: NodeId,
932     pub is_trailing_mac: bool,
933 }
934
935 type OnExternModLoaded<'a> =
936     Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
937
938 /// One of these is made during expansion and incrementally updated as we go;
939 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
940 /// -> expn_data` of their expansion context stored into their span.
941 pub struct ExtCtxt<'a> {
942     pub sess: &'a Session,
943     pub ecfg: expand::ExpansionConfig<'a>,
944     pub reduced_recursion_limit: Option<Limit>,
945     pub root_path: PathBuf,
946     pub resolver: &'a mut dyn ResolverExpand,
947     pub current_expansion: ExpansionData,
948     /// Error recovery mode entered when expansion is stuck
949     /// (or during eager expansion, but that's a hack).
950     pub force_mode: bool,
951     pub expansions: FxHashMap<Span, Vec<String>>,
952     /// Called directly after having parsed an external `mod foo;` in expansion.
953     ///
954     /// `Ident` is the module name.
955     pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
956     /// When we 'expand' an inert attribute, we leave it
957     /// in the AST, but insert it here so that we know
958     /// not to expand it again.
959     pub(super) expanded_inert_attrs: MarkedAttrs,
960 }
961
962 impl<'a> ExtCtxt<'a> {
963     pub fn new(
964         sess: &'a Session,
965         ecfg: expand::ExpansionConfig<'a>,
966         resolver: &'a mut dyn ResolverExpand,
967         extern_mod_loaded: OnExternModLoaded<'a>,
968     ) -> ExtCtxt<'a> {
969         ExtCtxt {
970             sess,
971             ecfg,
972             reduced_recursion_limit: None,
973             resolver,
974             extern_mod_loaded,
975             root_path: PathBuf::new(),
976             current_expansion: ExpansionData {
977                 id: LocalExpnId::ROOT,
978                 depth: 0,
979                 module: Default::default(),
980                 dir_ownership: DirOwnership::Owned { relative: None },
981                 prior_type_ascription: None,
982                 lint_node_id: ast::CRATE_NODE_ID,
983                 is_trailing_mac: false,
984             },
985             force_mode: false,
986             expansions: FxHashMap::default(),
987             expanded_inert_attrs: MarkedAttrs::new(),
988         }
989     }
990
991     /// Returns a `Folder` for deeply expanding all macros in an AST node.
992     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
993         expand::MacroExpander::new(self, false)
994     }
995
996     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
997     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
998     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
999         expand::MacroExpander::new(self, true)
1000     }
1001     pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1002         rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1003     }
1004     pub fn source_map(&self) -> &'a SourceMap {
1005         self.sess.parse_sess.source_map()
1006     }
1007     pub fn parse_sess(&self) -> &'a ParseSess {
1008         &self.sess.parse_sess
1009     }
1010     pub fn call_site(&self) -> Span {
1011         self.current_expansion.id.expn_data().call_site
1012     }
1013
1014     /// Equivalent of `Span::def_site` from the proc macro API,
1015     /// except that the location is taken from the span passed as an argument.
1016     pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1017         span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1018     }
1019
1020     /// Equivalent of `Span::call_site` from the proc macro API,
1021     /// except that the location is taken from the span passed as an argument.
1022     pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1023         span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1024     }
1025
1026     /// Equivalent of `Span::mixed_site` from the proc macro API,
1027     /// except that the location is taken from the span passed as an argument.
1028     pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1029         span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1030     }
1031
1032     /// Returns span for the macro which originally caused the current expansion to happen.
1033     ///
1034     /// Stops backtracing at include! boundary.
1035     pub fn expansion_cause(&self) -> Option<Span> {
1036         self.current_expansion.id.expansion_cause()
1037     }
1038
1039     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1040         self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1041     }
1042
1043     /// Emit `msg` attached to `sp`, without immediately stopping
1044     /// compilation.
1045     ///
1046     /// Compilation will be stopped in the near future (at the end of
1047     /// the macro expansion phase).
1048     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1049         self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1050     }
1051     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1052         self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1053     }
1054     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1055         self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1056     }
1057     pub fn trace_macros_diag(&mut self) {
1058         for (sp, notes) in self.expansions.iter() {
1059             let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1060             for note in notes {
1061                 db.note(note);
1062             }
1063             db.emit();
1064         }
1065         // Fixme: does this result in errors?
1066         self.expansions.clear();
1067     }
1068     pub fn bug(&self, msg: &str) -> ! {
1069         self.sess.parse_sess.span_diagnostic.bug(msg);
1070     }
1071     pub fn trace_macros(&self) -> bool {
1072         self.ecfg.trace_mac
1073     }
1074     pub fn set_trace_macros(&mut self, x: bool) {
1075         self.ecfg.trace_mac = x
1076     }
1077     pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1078         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1079         iter::once(Ident::new(kw::DollarCrate, def_site))
1080             .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1081             .collect()
1082     }
1083     pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1084         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1085         components.iter().map(|&s| Ident::new(s, def_site)).collect()
1086     }
1087
1088     pub fn check_unused_macros(&mut self) {
1089         self.resolver.check_unused_macros();
1090     }
1091
1092     /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1093     ///
1094     /// This unifies the logic used for resolving `include_X!`.
1095     ///
1096     /// FIXME: move this to `rustc_builtin_macros` and make it private.
1097     pub fn resolve_path(
1098         &self,
1099         path: impl Into<PathBuf>,
1100         span: Span,
1101     ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1102         let path = path.into();
1103
1104         // Relative paths are resolved relative to the file in which they are found
1105         // after macro expansion (that is, they are unhygienic).
1106         if !path.is_absolute() {
1107             let callsite = span.source_callsite();
1108             let mut result = match self.source_map().span_to_filename(callsite) {
1109                 FileName::Real(name) => name
1110                     .into_local_path()
1111                     .expect("attempting to resolve a file path in an external file"),
1112                 FileName::DocTest(path, _) => path,
1113                 other => {
1114                     return Err(self.struct_span_err(
1115                         span,
1116                         &format!(
1117                             "cannot resolve relative path in non-file source `{}`",
1118                             other.prefer_local()
1119                         ),
1120                     ));
1121                 }
1122             };
1123             result.pop();
1124             result.push(path);
1125             Ok(result)
1126         } else {
1127             Ok(path)
1128         }
1129     }
1130 }
1131
1132 /// Extracts a string literal from the macro expanded version of `expr`,
1133 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1134 /// compilation on error, merely emits a non-fatal error and returns `None`.
1135 pub fn expr_to_spanned_string<'a>(
1136     cx: &'a mut ExtCtxt<'_>,
1137     expr: P<ast::Expr>,
1138     err_msg: &str,
1139 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1140     // Perform eager expansion on the expression.
1141     // We want to be able to handle e.g., `concat!("foo", "bar")`.
1142     let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1143
1144     Err(match expr.kind {
1145         ast::ExprKind::Lit(ref l) => match l.kind {
1146             ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1147             ast::LitKind::Err(_) => None,
1148             _ => Some(cx.struct_span_err(l.span, err_msg)),
1149         },
1150         ast::ExprKind::Err => None,
1151         _ => Some(cx.struct_span_err(expr.span, err_msg)),
1152     })
1153 }
1154
1155 pub fn expr_to_string(
1156     cx: &mut ExtCtxt<'_>,
1157     expr: P<ast::Expr>,
1158     err_msg: &str,
1159 ) -> Option<(Symbol, ast::StrStyle)> {
1160     expr_to_spanned_string(cx, expr, err_msg)
1161         .map_err(|err| {
1162             err.map(|mut err| {
1163                 err.emit();
1164             })
1165         })
1166         .ok()
1167         .map(|(symbol, style, _)| (symbol, style))
1168 }
1169
1170 /// Non-fatally assert that `tts` is empty. Note that this function
1171 /// returns even when `tts` is non-empty, macros that *need* to stop
1172 /// compilation should call
1173 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1174 /// done as rarely as possible).
1175 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1176     if !tts.is_empty() {
1177         cx.span_err(sp, &format!("{} takes no arguments", name));
1178     }
1179 }
1180
1181 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1182 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1183     match p.parse_expr() {
1184         Ok(e) => return Some(e),
1185         Err(mut err) => err.emit(),
1186     }
1187     while p.token != token::Eof {
1188         p.bump();
1189     }
1190     None
1191 }
1192
1193 /// Interpreting `tts` as a comma-separated sequence of expressions,
1194 /// expect exactly one string literal, or emit an error and return `None`.
1195 pub fn get_single_str_from_tts(
1196     cx: &mut ExtCtxt<'_>,
1197     sp: Span,
1198     tts: TokenStream,
1199     name: &str,
1200 ) -> Option<String> {
1201     let mut p = cx.new_parser_from_tts(tts);
1202     if p.token == token::Eof {
1203         cx.span_err(sp, &format!("{} takes 1 argument", name));
1204         return None;
1205     }
1206     let ret = parse_expr(&mut p)?;
1207     let _ = p.eat(&token::Comma);
1208
1209     if p.token != token::Eof {
1210         cx.span_err(sp, &format!("{} takes 1 argument", name));
1211     }
1212     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1213 }
1214
1215 /// Extracts comma-separated expressions from `tts`.
1216 /// On error, emit it, and return `None`.
1217 pub fn get_exprs_from_tts(
1218     cx: &mut ExtCtxt<'_>,
1219     sp: Span,
1220     tts: TokenStream,
1221 ) -> Option<Vec<P<ast::Expr>>> {
1222     let mut p = cx.new_parser_from_tts(tts);
1223     let mut es = Vec::new();
1224     while p.token != token::Eof {
1225         let expr = parse_expr(&mut p)?;
1226
1227         // Perform eager expansion on the expression.
1228         // We want to be able to handle e.g., `concat!("foo", "bar")`.
1229         let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1230
1231         es.push(expr);
1232         if p.eat(&token::Comma) {
1233             continue;
1234         }
1235         if p.token != token::Eof {
1236             cx.span_err(sp, "expected token: `,`");
1237             return None;
1238         }
1239     }
1240     Some(es)
1241 }
1242
1243 pub fn parse_macro_name_and_helper_attrs(
1244     diag: &rustc_errors::Handler,
1245     attr: &Attribute,
1246     descr: &str,
1247 ) -> Option<(Symbol, Vec<Symbol>)> {
1248     // Once we've located the `#[proc_macro_derive]` attribute, verify
1249     // that it's of the form `#[proc_macro_derive(Foo)]` or
1250     // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1251     let list = match attr.meta_item_list() {
1252         Some(list) => list,
1253         None => return None,
1254     };
1255     if list.len() != 1 && list.len() != 2 {
1256         diag.span_err(attr.span, "attribute must have either one or two arguments");
1257         return None;
1258     }
1259     let trait_attr = match list[0].meta_item() {
1260         Some(meta_item) => meta_item,
1261         _ => {
1262             diag.span_err(list[0].span(), "not a meta item");
1263             return None;
1264         }
1265     };
1266     let trait_ident = match trait_attr.ident() {
1267         Some(trait_ident) if trait_attr.is_word() => trait_ident,
1268         _ => {
1269             diag.span_err(trait_attr.span, "must only be one word");
1270             return None;
1271         }
1272     };
1273
1274     if !trait_ident.name.can_be_raw() {
1275         diag.span_err(
1276             trait_attr.span,
1277             &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1278         );
1279     }
1280
1281     let attributes_attr = list.get(1);
1282     let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1283         if !attr.has_name(sym::attributes) {
1284             diag.span_err(attr.span(), "second argument must be `attributes`")
1285         }
1286         attr.meta_item_list()
1287             .unwrap_or_else(|| {
1288                 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1289                 &[]
1290             })
1291             .iter()
1292             .filter_map(|attr| {
1293                 let attr = match attr.meta_item() {
1294                     Some(meta_item) => meta_item,
1295                     _ => {
1296                         diag.span_err(attr.span(), "not a meta item");
1297                         return None;
1298                     }
1299                 };
1300
1301                 let ident = match attr.ident() {
1302                     Some(ident) if attr.is_word() => ident,
1303                     _ => {
1304                         diag.span_err(attr.span, "must only be one word");
1305                         return None;
1306                     }
1307                 };
1308                 if !ident.name.can_be_raw() {
1309                     diag.span_err(
1310                         attr.span,
1311                         &format!("`{}` cannot be a name of derive helper attribute", ident),
1312                     );
1313                 }
1314
1315                 Some(ident.name)
1316             })
1317             .collect()
1318     } else {
1319         Vec::new()
1320     };
1321
1322     Some((trait_ident.name, proc_attrs))
1323 }
1324
1325 /// This nonterminal looks like some specific enums from
1326 /// `proc-macro-hack` and `procedural-masquerade` crates.
1327 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1328 /// asserts in old versions of those crates and their wide use in the ecosystem.
1329 /// See issue #73345 for more details.
1330 /// FIXME(#73933): Remove this eventually.
1331 pub(crate) fn pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1332     let item = match nt {
1333         Nonterminal::NtItem(item) => item,
1334         Nonterminal::NtStmt(stmt) => match &stmt.kind {
1335             ast::StmtKind::Item(item) => item,
1336             _ => return false,
1337         },
1338         _ => return false,
1339     };
1340
1341     let name = item.ident.name;
1342     if name == sym::ProceduralMasqueradeDummyType {
1343         if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1344             if let [variant] = &*enum_def.variants {
1345                 if variant.ident.name == sym::Input {
1346                     sess.buffer_lint_with_diagnostic(
1347                         &PROC_MACRO_BACK_COMPAT,
1348                         item.ident.span,
1349                         ast::CRATE_NODE_ID,
1350                         "using `procedural-masquerade` crate",
1351                         BuiltinLintDiagnostics::ProcMacroBackCompat(
1352                         "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1353                         Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())
1354                     );
1355                     return true;
1356                 }
1357             }
1358         }
1359     }
1360     false
1361 }