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