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