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