]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
b898696d349754784e724638498dc3d5c7206283
[rust.git] / src / libsyntax / ext / base.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::SyntaxExtension::*;
12
13 use ast::{self, Attribute, Name, PatKind, MetaItem};
14 use attr::HasAttrs;
15 use source_map::{self, SourceMap, Spanned, respan};
16 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
17 use edition::Edition;
18 use errors::{DiagnosticBuilder, DiagnosticId};
19 use ext::expand::{self, AstFragment, Invocation};
20 use ext::hygiene::{self, Mark, SyntaxContext, Transparency};
21 use fold::{self, Folder};
22 use parse::{self, parser, DirectoryOwnership};
23 use parse::token;
24 use ptr::P;
25 use smallvec::SmallVec;
26 use symbol::{keywords, Ident, Symbol};
27 use ThinVec;
28
29 use rustc_data_structures::fx::FxHashMap;
30 use std::iter;
31 use std::path::PathBuf;
32 use std::rc::Rc;
33 use rustc_data_structures::sync::{self, Lrc};
34 use std::default::Default;
35 use tokenstream::{self, TokenStream};
36
37
38 #[derive(Debug,Clone)]
39 pub enum Annotatable {
40     Item(P<ast::Item>),
41     TraitItem(P<ast::TraitItem>),
42     ImplItem(P<ast::ImplItem>),
43     ForeignItem(P<ast::ForeignItem>),
44     Stmt(P<ast::Stmt>),
45     Expr(P<ast::Expr>),
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         }
58     }
59
60     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
61         match self {
62             Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
63             Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
64             Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
65             Annotatable::ForeignItem(foreign_item) =>
66                 Annotatable::ForeignItem(foreign_item.map_attrs(f)),
67             Annotatable::Stmt(stmt) => Annotatable::Stmt(stmt.map_attrs(f)),
68             Annotatable::Expr(expr) => Annotatable::Expr(expr.map_attrs(f)),
69         }
70     }
71 }
72
73 impl Annotatable {
74     pub fn span(&self) -> Span {
75         match *self {
76             Annotatable::Item(ref item) => item.span,
77             Annotatable::TraitItem(ref trait_item) => trait_item.span,
78             Annotatable::ImplItem(ref impl_item) => impl_item.span,
79             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
80             Annotatable::Stmt(ref stmt) => stmt.span,
81             Annotatable::Expr(ref expr) => expr.span,
82         }
83     }
84
85     pub fn expect_item(self) -> P<ast::Item> {
86         match self {
87             Annotatable::Item(i) => i,
88             _ => panic!("expected Item")
89         }
90     }
91
92     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
93         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
94               G: FnMut(Annotatable) -> Annotatable
95     {
96         match self {
97             Annotatable::Item(i) => Annotatable::Item(f(i)),
98             _ => or(self)
99         }
100     }
101
102     pub fn expect_trait_item(self) -> ast::TraitItem {
103         match self {
104             Annotatable::TraitItem(i) => i.into_inner(),
105             _ => panic!("expected Item")
106         }
107     }
108
109     pub fn expect_impl_item(self) -> ast::ImplItem {
110         match self {
111             Annotatable::ImplItem(i) => i.into_inner(),
112             _ => panic!("expected Item")
113         }
114     }
115
116     pub fn expect_foreign_item(self) -> ast::ForeignItem {
117         match self {
118             Annotatable::ForeignItem(i) => i.into_inner(),
119             _ => panic!("expected foreign item")
120         }
121     }
122
123     pub fn expect_stmt(self) -> ast::Stmt {
124         match self {
125             Annotatable::Stmt(stmt) => stmt.into_inner(),
126             _ => panic!("expected statement"),
127         }
128     }
129
130     pub fn expect_expr(self) -> P<ast::Expr> {
131         match self {
132             Annotatable::Expr(expr) => expr,
133             _ => panic!("expected expression"),
134         }
135     }
136
137     pub fn derive_allowed(&self) -> bool {
138         match *self {
139             Annotatable::Item(ref item) => match item.node {
140                 ast::ItemKind::Struct(..) |
141                 ast::ItemKind::Enum(..) |
142                 ast::ItemKind::Union(..) => true,
143                 _ => false,
144             },
145             _ => false,
146         }
147     }
148 }
149
150 // A more flexible ItemDecorator.
151 pub trait MultiItemDecorator {
152     fn expand(&self,
153               ecx: &mut ExtCtxt,
154               sp: Span,
155               meta_item: &ast::MetaItem,
156               item: &Annotatable,
157               push: &mut dyn FnMut(Annotatable));
158 }
159
160 impl<F> MultiItemDecorator for F
161     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
162 {
163     fn expand(&self,
164               ecx: &mut ExtCtxt,
165               sp: Span,
166               meta_item: &ast::MetaItem,
167               item: &Annotatable,
168               push: &mut dyn FnMut(Annotatable)) {
169         (*self)(ecx, sp, meta_item, item, push)
170     }
171 }
172
173 // `meta_item` is the annotation, and `item` is the item being modified.
174 // FIXME Decorators should follow the same pattern too.
175 pub trait MultiItemModifier {
176     fn expand(&self,
177               ecx: &mut ExtCtxt,
178               span: Span,
179               meta_item: &ast::MetaItem,
180               item: Annotatable)
181               -> Vec<Annotatable>;
182 }
183
184 impl<F, T> MultiItemModifier for F
185     where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
186           T: Into<Vec<Annotatable>>,
187 {
188     fn expand(&self,
189               ecx: &mut ExtCtxt,
190               span: Span,
191               meta_item: &ast::MetaItem,
192               item: Annotatable)
193               -> Vec<Annotatable> {
194         (*self)(ecx, span, meta_item, item).into()
195     }
196 }
197
198 impl Into<Vec<Annotatable>> for Annotatable {
199     fn into(self) -> Vec<Annotatable> {
200         vec![self]
201     }
202 }
203
204 pub trait ProcMacro {
205     fn expand<'cx>(&self,
206                    ecx: &'cx mut ExtCtxt,
207                    span: Span,
208                    ts: TokenStream)
209                    -> TokenStream;
210 }
211
212 impl<F> ProcMacro for F
213     where F: Fn(TokenStream) -> TokenStream
214 {
215     fn expand<'cx>(&self,
216                    _ecx: &'cx mut ExtCtxt,
217                    _span: Span,
218                    ts: TokenStream)
219                    -> TokenStream {
220         // FIXME setup implicit context in TLS before calling self.
221         (*self)(ts)
222     }
223 }
224
225 pub trait AttrProcMacro {
226     fn expand<'cx>(&self,
227                    ecx: &'cx mut ExtCtxt,
228                    span: Span,
229                    annotation: TokenStream,
230                    annotated: TokenStream)
231                    -> TokenStream;
232 }
233
234 impl<F> AttrProcMacro for F
235     where F: Fn(TokenStream, TokenStream) -> TokenStream
236 {
237     fn expand<'cx>(&self,
238                    _ecx: &'cx mut ExtCtxt,
239                    _span: Span,
240                    annotation: TokenStream,
241                    annotated: TokenStream)
242                    -> TokenStream {
243         // FIXME setup implicit context in TLS before calling self.
244         (*self)(annotation, annotated)
245     }
246 }
247
248 /// Represents a thing that maps token trees to Macro Results
249 pub trait TTMacroExpander {
250     fn expand<'cx>(
251         &self,
252         ecx: &'cx mut ExtCtxt,
253         span: Span,
254         input: TokenStream,
255         def_span: Option<Span>,
256     ) -> Box<dyn MacResult+'cx>;
257 }
258
259 pub type MacroExpanderFn =
260     for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
261                 -> Box<dyn MacResult+'cx>;
262
263 impl<F> TTMacroExpander for F
264     where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
265     -> Box<dyn MacResult+'cx>
266 {
267     fn expand<'cx>(
268         &self,
269         ecx: &'cx mut ExtCtxt,
270         span: Span,
271         input: TokenStream,
272         _def_span: Option<Span>,
273     ) -> Box<dyn MacResult+'cx> {
274         struct AvoidInterpolatedIdents;
275
276         impl Folder for AvoidInterpolatedIdents {
277             fn fold_tt(&mut self, tt: tokenstream::TokenTree) -> tokenstream::TokenTree {
278                 if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt {
279                     if let token::NtIdent(ident, is_raw) = nt.0 {
280                         return tokenstream::TokenTree::Token(ident.span,
281                                                              token::Ident(ident, is_raw));
282                     }
283                 }
284                 fold::noop_fold_tt(tt, self)
285             }
286
287             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
288                 fold::noop_fold_mac(mac, self)
289             }
290         }
291
292         let input: Vec<_> =
293             input.trees().map(|tt| AvoidInterpolatedIdents.fold_tt(tt)).collect();
294         (*self)(ecx, span, &input)
295     }
296 }
297
298 pub trait IdentMacroExpander {
299     fn expand<'cx>(&self,
300                    cx: &'cx mut ExtCtxt,
301                    sp: Span,
302                    ident: ast::Ident,
303                    token_tree: Vec<tokenstream::TokenTree>)
304                    -> Box<dyn MacResult+'cx>;
305 }
306
307 pub type IdentMacroExpanderFn =
308     for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
309                 -> Box<dyn MacResult+'cx>;
310
311 impl<F> IdentMacroExpander for F
312     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
313                           Vec<tokenstream::TokenTree>) -> Box<dyn MacResult+'cx>
314 {
315     fn expand<'cx>(&self,
316                    cx: &'cx mut ExtCtxt,
317                    sp: Span,
318                    ident: ast::Ident,
319                    token_tree: Vec<tokenstream::TokenTree>)
320                    -> Box<dyn MacResult+'cx>
321     {
322         (*self)(cx, sp, ident, token_tree)
323     }
324 }
325
326 // Use a macro because forwarding to a simple function has type system issues
327 macro_rules! make_stmts_default {
328     ($me:expr) => {
329         $me.make_expr().map(|e| smallvec![ast::Stmt {
330             id: ast::DUMMY_NODE_ID,
331             span: e.span,
332             node: ast::StmtKind::Expr(e),
333         }])
334     }
335 }
336
337 /// The result of a macro expansion. The return values of the various
338 /// methods are spliced into the AST at the callsite of the macro.
339 pub trait MacResult {
340     /// Create an expression.
341     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
342         None
343     }
344     /// Create zero or more items.
345     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
346         None
347     }
348
349     /// Create zero or more impl items.
350     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
351         None
352     }
353
354     /// Create zero or more trait items.
355     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
356         None
357     }
358
359     /// Create zero or more items in an `extern {}` block
360     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
361
362     /// Create a pattern.
363     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
364         None
365     }
366
367     /// Create zero or more statements.
368     ///
369     /// By default this attempts to create an expression statement,
370     /// returning None if that fails.
371     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
372         make_stmts_default!(self)
373     }
374
375     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
376         None
377     }
378 }
379
380 macro_rules! make_MacEager {
381     ( $( $fld:ident: $t:ty, )* ) => {
382         /// `MacResult` implementation for the common case where you've already
383         /// built each form of AST that you might return.
384         #[derive(Default)]
385         pub struct MacEager {
386             $(
387                 pub $fld: Option<$t>,
388             )*
389         }
390
391         impl MacEager {
392             $(
393                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
394                     Box::new(MacEager {
395                         $fld: Some(v),
396                         ..Default::default()
397                     })
398                 }
399             )*
400         }
401     }
402 }
403
404 make_MacEager! {
405     expr: P<ast::Expr>,
406     pat: P<ast::Pat>,
407     items: SmallVec<[P<ast::Item>; 1]>,
408     impl_items: SmallVec<[ast::ImplItem; 1]>,
409     trait_items: SmallVec<[ast::TraitItem; 1]>,
410     foreign_items: SmallVec<[ast::ForeignItem; 1]>,
411     stmts: SmallVec<[ast::Stmt; 1]>,
412     ty: P<ast::Ty>,
413 }
414
415 impl MacResult for MacEager {
416     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
417         self.expr
418     }
419
420     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
421         self.items
422     }
423
424     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
425         self.impl_items
426     }
427
428     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
429         self.trait_items
430     }
431
432     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
433         self.foreign_items
434     }
435
436     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
437         match self.stmts.as_ref().map_or(0, |s| s.len()) {
438             0 => make_stmts_default!(self),
439             _ => self.stmts,
440         }
441     }
442
443     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
444         if let Some(p) = self.pat {
445             return Some(p);
446         }
447         if let Some(e) = self.expr {
448             if let ast::ExprKind::Lit(_) = e.node {
449                 return Some(P(ast::Pat {
450                     id: ast::DUMMY_NODE_ID,
451                     span: e.span,
452                     node: PatKind::Lit(e),
453                 }));
454             }
455         }
456         None
457     }
458
459     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
460         self.ty
461     }
462 }
463
464 /// Fill-in macro expansion result, to allow compilation to continue
465 /// after hitting errors.
466 #[derive(Copy, Clone)]
467 pub struct DummyResult {
468     expr_only: bool,
469     span: Span
470 }
471
472 impl DummyResult {
473     /// Create a default MacResult that can be anything.
474     ///
475     /// Use this as a return value after hitting any errors and
476     /// calling `span_err`.
477     pub fn any(sp: Span) -> Box<dyn MacResult+'static> {
478         Box::new(DummyResult { expr_only: false, span: sp })
479     }
480
481     /// Create a default MacResult that can only be an expression.
482     ///
483     /// Use this for macros that must expand to an expression, so even
484     /// if an error is encountered internally, the user will receive
485     /// an error that they also used it in the wrong place.
486     pub fn expr(sp: Span) -> Box<dyn MacResult+'static> {
487         Box::new(DummyResult { expr_only: true, span: sp })
488     }
489
490     /// A plain dummy expression.
491     pub fn raw_expr(sp: Span) -> P<ast::Expr> {
492         P(ast::Expr {
493             id: ast::DUMMY_NODE_ID,
494             node: ast::ExprKind::Lit(source_map::respan(sp, ast::LitKind::Bool(false))),
495             span: sp,
496             attrs: ThinVec::new(),
497         })
498     }
499
500     /// A plain dummy pattern.
501     pub fn raw_pat(sp: Span) -> ast::Pat {
502         ast::Pat {
503             id: ast::DUMMY_NODE_ID,
504             node: PatKind::Wild,
505             span: sp,
506         }
507     }
508
509     pub fn raw_ty(sp: Span) -> P<ast::Ty> {
510         P(ast::Ty {
511             id: ast::DUMMY_NODE_ID,
512             node: ast::TyKind::Infer,
513             span: sp
514         })
515     }
516 }
517
518 impl MacResult for DummyResult {
519     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
520         Some(DummyResult::raw_expr(self.span))
521     }
522
523     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
524         Some(P(DummyResult::raw_pat(self.span)))
525     }
526
527     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
528         // this code needs a comment... why not always just return the Some() ?
529         if self.expr_only {
530             None
531         } else {
532             Some(SmallVec::new())
533         }
534     }
535
536     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
537         if self.expr_only {
538             None
539         } else {
540             Some(SmallVec::new())
541         }
542     }
543
544     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
545         if self.expr_only {
546             None
547         } else {
548             Some(SmallVec::new())
549         }
550     }
551
552     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
553         if self.expr_only {
554             None
555         } else {
556             Some(SmallVec::new())
557         }
558     }
559
560     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
561         Some(smallvec![ast::Stmt {
562             id: ast::DUMMY_NODE_ID,
563             node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
564             span: self.span,
565         }])
566     }
567
568     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
569         Some(DummyResult::raw_ty(self.span))
570     }
571 }
572
573 pub type BuiltinDeriveFn =
574     for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable));
575
576 /// Represents different kinds of macro invocations that can be resolved.
577 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
578 pub enum MacroKind {
579     /// A bang macro - foo!()
580     Bang,
581     /// An attribute macro - #[foo]
582     Attr,
583     /// A derive attribute macro - #[derive(Foo)]
584     Derive,
585     /// A view of a procedural macro from the same crate that defines it.
586     ProcMacroStub,
587 }
588
589 impl MacroKind {
590     pub fn descr(self) -> &'static str {
591         match self {
592             MacroKind::Bang => "macro",
593             MacroKind::Attr => "attribute macro",
594             MacroKind::Derive => "derive macro",
595             MacroKind::ProcMacroStub => "crate-local procedural macro",
596         }
597     }
598
599     pub fn article(self) -> &'static str {
600         match self {
601             MacroKind::Attr => "an",
602             _ => "a",
603         }
604     }
605 }
606
607 /// An enum representing the different kinds of syntax extensions.
608 pub enum SyntaxExtension {
609     /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
610     NonMacroAttr { mark_used: bool },
611
612     /// A syntax extension that is attached to an item and creates new items
613     /// based upon it.
614     ///
615     /// `#[derive(...)]` is a `MultiItemDecorator`.
616     ///
617     /// Prefer ProcMacro or MultiModifier since they are more flexible.
618     MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
619
620     /// A syntax extension that is attached to an item and modifies it
621     /// in-place. Also allows decoration, i.e., creating new items.
622     MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
623
624     /// A function-like procedural macro. TokenStream -> TokenStream.
625     ProcMacro {
626         expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
627         allow_internal_unstable: bool,
628         edition: Edition,
629     },
630
631     /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
632     /// The first TokenSteam is the attribute, the second is the annotated item.
633     /// Allows modification of the input items and adding new items, similar to
634     /// MultiModifier, but uses TokenStreams, rather than AST nodes.
635     AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
636
637     /// A normal, function-like syntax extension.
638     ///
639     /// `bytes!` is a `NormalTT`.
640     NormalTT {
641         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
642         def_info: Option<(ast::NodeId, Span)>,
643         /// Whether the contents of the macro can
644         /// directly use `#[unstable]` things (true == yes).
645         allow_internal_unstable: bool,
646         /// Whether the contents of the macro can use `unsafe`
647         /// without triggering the `unsafe_code` lint.
648         allow_internal_unsafe: bool,
649         /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
650         /// for a given macro.
651         local_inner_macros: bool,
652         /// The macro's feature name if it is unstable, and the stability feature
653         unstable_feature: Option<(Symbol, u32)>,
654         /// Edition of the crate in which the macro is defined
655         edition: Edition,
656     },
657
658     /// A function-like syntax extension that has an extra ident before
659     /// the block.
660     ///
661     IdentTT(Box<dyn IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
662
663     /// An attribute-like procedural macro. TokenStream -> TokenStream.
664     /// The input is the annotated item.
665     /// Allows generating code to implement a Trait for a given struct
666     /// or enum item.
667     ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
668                     Vec<Symbol> /* inert attribute names */, Edition),
669
670     /// An attribute-like procedural macro that derives a builtin trait.
671     BuiltinDerive(BuiltinDeriveFn),
672
673     /// A declarative macro, e.g. `macro m() {}`.
674     DeclMacro {
675         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
676         def_info: Option<(ast::NodeId, Span)>,
677         is_transparent: bool,
678         edition: Edition,
679     }
680 }
681
682 impl SyntaxExtension {
683     /// Return which kind of macro calls this syntax extension.
684     pub fn kind(&self) -> MacroKind {
685         match *self {
686             SyntaxExtension::DeclMacro { .. } |
687             SyntaxExtension::NormalTT { .. } |
688             SyntaxExtension::IdentTT(..) |
689             SyntaxExtension::ProcMacro { .. } =>
690                 MacroKind::Bang,
691             SyntaxExtension::NonMacroAttr { .. } |
692             SyntaxExtension::MultiDecorator(..) |
693             SyntaxExtension::MultiModifier(..) |
694             SyntaxExtension::AttrProcMacro(..) =>
695                 MacroKind::Attr,
696             SyntaxExtension::ProcMacroDerive(..) |
697             SyntaxExtension::BuiltinDerive(..) =>
698                 MacroKind::Derive,
699         }
700     }
701
702     pub fn default_transparency(&self) -> Transparency {
703         match *self {
704             SyntaxExtension::ProcMacro { .. } |
705             SyntaxExtension::AttrProcMacro(..) |
706             SyntaxExtension::ProcMacroDerive(..) |
707             SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
708             SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
709             _ => Transparency::SemiTransparent,
710         }
711     }
712
713     pub fn edition(&self) -> Edition {
714         match *self {
715             SyntaxExtension::NormalTT { edition, .. } |
716             SyntaxExtension::DeclMacro { edition, .. } |
717             SyntaxExtension::ProcMacro { edition, .. } |
718             SyntaxExtension::AttrProcMacro(.., edition) |
719             SyntaxExtension::ProcMacroDerive(.., edition) => edition,
720             // Unstable legacy stuff
721             SyntaxExtension::NonMacroAttr { .. } |
722             SyntaxExtension::IdentTT(..) |
723             SyntaxExtension::MultiDecorator(..) |
724             SyntaxExtension::MultiModifier(..) |
725             SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(),
726         }
727     }
728 }
729
730 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
731
732 pub trait Resolver {
733     fn next_node_id(&mut self) -> ast::NodeId;
734     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
735     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
736
737     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
738                                             derives: &[Mark]);
739     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
740
741     fn resolve_imports(&mut self);
742
743     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
744                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
745     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
746                           derives_in_scope: Vec<ast::Path>, force: bool)
747                           -> Result<Lrc<SyntaxExtension>, Determinacy>;
748
749     fn check_unused_macros(&self);
750 }
751
752 #[derive(Copy, Clone, PartialEq, Debug)]
753 pub enum Determinacy {
754     Determined,
755     Undetermined,
756 }
757
758 impl Determinacy {
759     pub fn determined(determined: bool) -> Determinacy {
760         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
761     }
762 }
763
764 pub struct DummyResolver;
765
766 impl Resolver for DummyResolver {
767     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
768     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
769     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
770
771     fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
772                                             _derives: &[Mark]) {}
773     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
774
775     fn resolve_imports(&mut self) {}
776     fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
777                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
778         Err(Determinacy::Determined)
779     }
780     fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
781                           _derives_in_scope: Vec<ast::Path>, _force: bool)
782                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
783         Err(Determinacy::Determined)
784     }
785     fn check_unused_macros(&self) {}
786 }
787
788 #[derive(Clone)]
789 pub struct ModuleData {
790     pub mod_path: Vec<ast::Ident>,
791     pub directory: PathBuf,
792 }
793
794 #[derive(Clone)]
795 pub struct ExpansionData {
796     pub mark: Mark,
797     pub depth: usize,
798     pub module: Rc<ModuleData>,
799     pub directory_ownership: DirectoryOwnership,
800     pub crate_span: Option<Span>,
801 }
802
803 /// One of these is made during expansion and incrementally updated as we go;
804 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
805 /// -> expn_info` of their expansion context stored into their span.
806 pub struct ExtCtxt<'a> {
807     pub parse_sess: &'a parse::ParseSess,
808     pub ecfg: expand::ExpansionConfig<'a>,
809     pub root_path: PathBuf,
810     pub resolver: &'a mut dyn Resolver,
811     pub resolve_err_count: usize,
812     pub current_expansion: ExpansionData,
813     pub expansions: FxHashMap<Span, Vec<String>>,
814 }
815
816 impl<'a> ExtCtxt<'a> {
817     pub fn new(parse_sess: &'a parse::ParseSess,
818                ecfg: expand::ExpansionConfig<'a>,
819                resolver: &'a mut dyn Resolver)
820                -> ExtCtxt<'a> {
821         ExtCtxt {
822             parse_sess,
823             ecfg,
824             root_path: PathBuf::new(),
825             resolver,
826             resolve_err_count: 0,
827             current_expansion: ExpansionData {
828                 mark: Mark::root(),
829                 depth: 0,
830                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
831                 directory_ownership: DirectoryOwnership::Owned { relative: None },
832                 crate_span: None,
833             },
834             expansions: FxHashMap::default(),
835         }
836     }
837
838     /// Returns a `Folder` for deeply expanding all macros in an AST node.
839     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
840         expand::MacroExpander::new(self, false)
841     }
842
843     /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
844     /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
845     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
846         expand::MacroExpander::new(self, true)
847     }
848
849     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
850         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
851     }
852     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
853     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
854     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
855     pub fn call_site(&self) -> Span {
856         match self.current_expansion.mark.expn_info() {
857             Some(expn_info) => expn_info.call_site,
858             None => DUMMY_SP,
859         }
860     }
861     pub fn backtrace(&self) -> SyntaxContext {
862         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
863     }
864
865     /// Returns span for the macro which originally caused the current expansion to happen.
866     ///
867     /// Stops backtracing at include! boundary.
868     pub fn expansion_cause(&self) -> Option<Span> {
869         let mut ctxt = self.backtrace();
870         let mut last_macro = None;
871         loop {
872             if ctxt.outer().expn_info().map_or(None, |info| {
873                 if info.format.name() == "include" {
874                     // Stop going up the backtrace once include! is encountered
875                     return None;
876                 }
877                 ctxt = info.call_site.ctxt();
878                 last_macro = Some(info.call_site);
879                 Some(())
880             }).is_none() {
881                 break
882             }
883         }
884         last_macro
885     }
886
887     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
888                                                 sp: S,
889                                                 msg: &str)
890                                                 -> DiagnosticBuilder<'a> {
891         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
892     }
893     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
894                                                sp: S,
895                                                msg: &str)
896                                                -> DiagnosticBuilder<'a> {
897         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
898     }
899     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
900                                                  sp: S,
901                                                  msg: &str)
902                                                  -> DiagnosticBuilder<'a> {
903         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
904     }
905
906     /// Emit `msg` attached to `sp`, and stop compilation immediately.
907     ///
908     /// `span_err` should be strongly preferred where-ever possible:
909     /// this should *only* be used when:
910     ///
911     /// - continuing has a high risk of flow-on errors (e.g. errors in
912     ///   declaring a macro would cause all uses of that macro to
913     ///   complain about "undefined macro"), or
914     /// - there is literally nothing else that can be done (however,
915     ///   in most cases one can construct a dummy expression/item to
916     ///   substitute; we never hit resolve/type-checking so the dummy
917     ///   value doesn't have to match anything)
918     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
919         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
920     }
921
922     /// Emit `msg` attached to `sp`, without immediately stopping
923     /// compilation.
924     ///
925     /// Compilation will be stopped in the near future (at the end of
926     /// the macro expansion phase).
927     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
928         self.parse_sess.span_diagnostic.span_err(sp, msg);
929     }
930     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
931         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
932     }
933     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
934                         -> DiagnosticBuilder<'a> {
935         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
936     }
937     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
938         self.parse_sess.span_diagnostic.span_warn(sp, msg);
939     }
940     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
941         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
942     }
943     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
944         self.parse_sess.span_diagnostic.span_bug(sp, msg);
945     }
946     pub fn trace_macros_diag(&mut self) {
947         for (sp, notes) in self.expansions.iter() {
948             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
949             for note in notes {
950                 db.note(note);
951             }
952             db.emit();
953         }
954         // Fixme: does this result in errors?
955         self.expansions.clear();
956     }
957     pub fn bug(&self, msg: &str) -> ! {
958         self.parse_sess.span_diagnostic.bug(msg);
959     }
960     pub fn trace_macros(&self) -> bool {
961         self.ecfg.trace_mac
962     }
963     pub fn set_trace_macros(&mut self, x: bool) {
964         self.ecfg.trace_mac = x
965     }
966     pub fn ident_of(&self, st: &str) -> ast::Ident {
967         ast::Ident::from_str(st)
968     }
969     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
970         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
971         iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
972             .chain(components.iter().map(|s| self.ident_of(s)))
973             .collect()
974     }
975     pub fn name_of(&self, st: &str) -> ast::Name {
976         Symbol::intern(st)
977     }
978
979     pub fn check_unused_macros(&self) {
980         self.resolver.check_unused_macros();
981     }
982 }
983
984 /// Extract a string literal from the macro expanded version of `expr`,
985 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
986 /// compilation on error, merely emits a non-fatal error and returns None.
987 pub fn expr_to_spanned_string<'a>(
988     cx: &'a mut ExtCtxt,
989     expr: P<ast::Expr>,
990     err_msg: &str,
991 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
992     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
993     let expr = expr.map(|mut expr| {
994         expr.span = expr.span.apply_mark(cx.current_expansion.mark);
995         expr
996     });
997
998     // we want to be able to handle e.g. `concat!("foo", "bar")`
999     let expr = cx.expander().fold_expr(expr);
1000     Err(match expr.node {
1001         ast::ExprKind::Lit(ref l) => match l.node {
1002             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
1003             _ => cx.struct_span_err(l.span, err_msg)
1004         },
1005         _ => cx.struct_span_err(expr.span, err_msg)
1006     })
1007 }
1008
1009 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
1010                       -> Option<(Symbol, ast::StrStyle)> {
1011     expr_to_spanned_string(cx, expr, err_msg)
1012         .map_err(|mut err| err.emit())
1013         .ok()
1014         .map(|s| s.node)
1015 }
1016
1017 /// Non-fatally assert that `tts` is empty. Note that this function
1018 /// returns even when `tts` is non-empty, macros that *need* to stop
1019 /// compilation should call
1020 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1021 /// done as rarely as possible).
1022 pub fn check_zero_tts(cx: &ExtCtxt,
1023                       sp: Span,
1024                       tts: &[tokenstream::TokenTree],
1025                       name: &str) {
1026     if !tts.is_empty() {
1027         cx.span_err(sp, &format!("{} takes no arguments", name));
1028     }
1029 }
1030
1031 /// Interpreting `tts` as a comma-separated sequence of expressions,
1032 /// expect exactly one string literal, or emit an error and return None.
1033 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1034                                sp: Span,
1035                                tts: &[tokenstream::TokenTree],
1036                                name: &str)
1037                                -> Option<String> {
1038     let mut p = cx.new_parser_from_tts(tts);
1039     if p.token == token::Eof {
1040         cx.span_err(sp, &format!("{} takes 1 argument", name));
1041         return None
1042     }
1043     let ret = panictry!(p.parse_expr());
1044     let _ = p.eat(&token::Comma);
1045
1046     if p.token != token::Eof {
1047         cx.span_err(sp, &format!("{} takes 1 argument", name));
1048     }
1049     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1050         s.to_string()
1051     })
1052 }
1053
1054 /// Extract comma-separated expressions from `tts`. If there is a
1055 /// parsing error, emit a non-fatal error and return None.
1056 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1057                           sp: Span,
1058                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1059     let mut p = cx.new_parser_from_tts(tts);
1060     let mut es = Vec::new();
1061     while p.token != token::Eof {
1062         es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1063         if p.eat(&token::Comma) {
1064             continue;
1065         }
1066         if p.token != token::Eof {
1067             cx.span_err(sp, "expected token: `,`");
1068             return None;
1069         }
1070     }
1071     Some(es)
1072 }