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