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