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