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