]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Rollup merge of #41015 - arielb1:new-block-stack, r=alexcrichton
[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::{MultiDecorator, MultiModifier, NormalTT, IdentTT};
12
13 use ast::{self, Attribute, Name, PatKind, MetaItem};
14 use attr::HasAttrs;
15 use codemap::{self, CodeMap, Spanned, respan};
16 use syntax_pos::{Span, DUMMY_SP};
17 use errors::DiagnosticBuilder;
18 use ext::expand::{self, Expansion, Invocation};
19 use ext::hygiene::{Mark, SyntaxContext};
20 use fold::{self, Folder};
21 use parse::{self, parser, DirectoryOwnership};
22 use parse::token;
23 use ptr::P;
24 use symbol::Symbol;
25 use util::small_vector::SmallVector;
26
27 use std::path::PathBuf;
28 use std::rc::Rc;
29 use std::default::Default;
30 use tokenstream::{self, TokenStream};
31
32
33 #[derive(Debug,Clone)]
34 pub enum Annotatable {
35     Item(P<ast::Item>),
36     TraitItem(P<ast::TraitItem>),
37     ImplItem(P<ast::ImplItem>),
38 }
39
40 impl HasAttrs for Annotatable {
41     fn attrs(&self) -> &[Attribute] {
42         match *self {
43             Annotatable::Item(ref item) => &item.attrs,
44             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
45             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
46         }
47     }
48
49     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
50         match self {
51             Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
52             Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
53             Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
54         }
55     }
56 }
57
58 impl Annotatable {
59     pub fn span(&self) -> Span {
60         match *self {
61             Annotatable::Item(ref item) => item.span,
62             Annotatable::TraitItem(ref trait_item) => trait_item.span,
63             Annotatable::ImplItem(ref impl_item) => impl_item.span,
64         }
65     }
66
67     pub fn expect_item(self) -> P<ast::Item> {
68         match self {
69             Annotatable::Item(i) => i,
70             _ => panic!("expected Item")
71         }
72     }
73
74     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
75         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
76               G: FnMut(Annotatable) -> Annotatable
77     {
78         match self {
79             Annotatable::Item(i) => Annotatable::Item(f(i)),
80             _ => or(self)
81         }
82     }
83
84     pub fn expect_trait_item(self) -> ast::TraitItem {
85         match self {
86             Annotatable::TraitItem(i) => i.unwrap(),
87             _ => panic!("expected Item")
88         }
89     }
90
91     pub fn expect_impl_item(self) -> ast::ImplItem {
92         match self {
93             Annotatable::ImplItem(i) => i.unwrap(),
94             _ => panic!("expected Item")
95         }
96     }
97 }
98
99 // A more flexible ItemDecorator.
100 pub trait MultiItemDecorator {
101     fn expand(&self,
102               ecx: &mut ExtCtxt,
103               sp: Span,
104               meta_item: &ast::MetaItem,
105               item: &Annotatable,
106               push: &mut FnMut(Annotatable));
107 }
108
109 impl<F> MultiItemDecorator for F
110     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
111 {
112     fn expand(&self,
113               ecx: &mut ExtCtxt,
114               sp: Span,
115               meta_item: &ast::MetaItem,
116               item: &Annotatable,
117               push: &mut FnMut(Annotatable)) {
118         (*self)(ecx, sp, meta_item, item, push)
119     }
120 }
121
122 // `meta_item` is the annotation, and `item` is the item being modified.
123 // FIXME Decorators should follow the same pattern too.
124 pub trait MultiItemModifier {
125     fn expand(&self,
126               ecx: &mut ExtCtxt,
127               span: Span,
128               meta_item: &ast::MetaItem,
129               item: Annotatable)
130               -> Vec<Annotatable>;
131 }
132
133 impl<F, T> MultiItemModifier for F
134     where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
135           T: Into<Vec<Annotatable>>,
136 {
137     fn expand(&self,
138               ecx: &mut ExtCtxt,
139               span: Span,
140               meta_item: &ast::MetaItem,
141               item: Annotatable)
142               -> Vec<Annotatable> {
143         (*self)(ecx, span, meta_item, item).into()
144     }
145 }
146
147 impl Into<Vec<Annotatable>> for Annotatable {
148     fn into(self) -> Vec<Annotatable> {
149         vec![self]
150     }
151 }
152
153 pub trait ProcMacro {
154     fn expand<'cx>(&self,
155                    ecx: &'cx mut ExtCtxt,
156                    span: Span,
157                    ts: TokenStream)
158                    -> TokenStream;
159 }
160
161 impl<F> ProcMacro for F
162     where F: Fn(TokenStream) -> TokenStream
163 {
164     fn expand<'cx>(&self,
165                    _ecx: &'cx mut ExtCtxt,
166                    _span: Span,
167                    ts: TokenStream)
168                    -> TokenStream {
169         // FIXME setup implicit context in TLS before calling self.
170         (*self)(ts)
171     }
172 }
173
174 pub trait AttrProcMacro {
175     fn expand<'cx>(&self,
176                    ecx: &'cx mut ExtCtxt,
177                    span: Span,
178                    annotation: TokenStream,
179                    annotated: TokenStream)
180                    -> TokenStream;
181 }
182
183 impl<F> AttrProcMacro for F
184     where F: Fn(TokenStream, TokenStream) -> TokenStream
185 {
186     fn expand<'cx>(&self,
187                    _ecx: &'cx mut ExtCtxt,
188                    _span: Span,
189                    annotation: TokenStream,
190                    annotated: TokenStream)
191                    -> TokenStream {
192         // FIXME setup implicit context in TLS before calling self.
193         (*self)(annotation, annotated)
194     }
195 }
196
197 /// Represents a thing that maps token trees to Macro Results
198 pub trait TTMacroExpander {
199     fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
200                    -> Box<MacResult+'cx>;
201 }
202
203 pub type MacroExpanderFn =
204     for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
205                 -> Box<MacResult+'cx>;
206
207 impl<F> TTMacroExpander for F
208     where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree]) -> Box<MacResult+'cx>
209 {
210     fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
211                    -> Box<MacResult+'cx> {
212         struct AvoidInterpolatedIdents;
213
214         impl Folder for AvoidInterpolatedIdents {
215             fn fold_tt(&mut self, tt: tokenstream::TokenTree) -> tokenstream::TokenTree {
216                 if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt {
217                     if let token::NtIdent(ident) = **nt {
218                         return tokenstream::TokenTree::Token(ident.span, token::Ident(ident.node));
219                     }
220                 }
221                 fold::noop_fold_tt(tt, self)
222             }
223
224             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
225                 fold::noop_fold_mac(mac, self)
226             }
227         }
228
229         let input: Vec<_> =
230             input.trees().map(|tt| AvoidInterpolatedIdents.fold_tt(tt)).collect();
231         (*self)(ecx, span, &input)
232     }
233 }
234
235 pub trait IdentMacroExpander {
236     fn expand<'cx>(&self,
237                    cx: &'cx mut ExtCtxt,
238                    sp: Span,
239                    ident: ast::Ident,
240                    token_tree: Vec<tokenstream::TokenTree>)
241                    -> Box<MacResult+'cx>;
242 }
243
244 pub type IdentMacroExpanderFn =
245     for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
246                 -> Box<MacResult+'cx>;
247
248 impl<F> IdentMacroExpander for F
249     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
250                           Vec<tokenstream::TokenTree>) -> Box<MacResult+'cx>
251 {
252     fn expand<'cx>(&self,
253                    cx: &'cx mut ExtCtxt,
254                    sp: Span,
255                    ident: ast::Ident,
256                    token_tree: Vec<tokenstream::TokenTree>)
257                    -> Box<MacResult+'cx>
258     {
259         (*self)(cx, sp, ident, token_tree)
260     }
261 }
262
263 // Use a macro because forwarding to a simple function has type system issues
264 macro_rules! make_stmts_default {
265     ($me:expr) => {
266         $me.make_expr().map(|e| SmallVector::one(ast::Stmt {
267             id: ast::DUMMY_NODE_ID,
268             span: e.span,
269             node: ast::StmtKind::Expr(e),
270         }))
271     }
272 }
273
274 /// The result of a macro expansion. The return values of the various
275 /// methods are spliced into the AST at the callsite of the macro.
276 pub trait MacResult {
277     /// Create an expression.
278     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
279         None
280     }
281     /// Create zero or more items.
282     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
283         None
284     }
285
286     /// Create zero or more impl items.
287     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
288         None
289     }
290
291     /// Create zero or more trait items.
292     fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
293         None
294     }
295
296     /// Create a pattern.
297     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
298         None
299     }
300
301     /// Create zero or more statements.
302     ///
303     /// By default this attempts to create an expression statement,
304     /// returning None if that fails.
305     fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
306         make_stmts_default!(self)
307     }
308
309     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
310         None
311     }
312 }
313
314 macro_rules! make_MacEager {
315     ( $( $fld:ident: $t:ty, )* ) => {
316         /// `MacResult` implementation for the common case where you've already
317         /// built each form of AST that you might return.
318         #[derive(Default)]
319         pub struct MacEager {
320             $(
321                 pub $fld: Option<$t>,
322             )*
323         }
324
325         impl MacEager {
326             $(
327                 pub fn $fld(v: $t) -> Box<MacResult> {
328                     Box::new(MacEager {
329                         $fld: Some(v),
330                         ..Default::default()
331                     })
332                 }
333             )*
334         }
335     }
336 }
337
338 make_MacEager! {
339     expr: P<ast::Expr>,
340     pat: P<ast::Pat>,
341     items: SmallVector<P<ast::Item>>,
342     impl_items: SmallVector<ast::ImplItem>,
343     trait_items: SmallVector<ast::TraitItem>,
344     stmts: SmallVector<ast::Stmt>,
345     ty: P<ast::Ty>,
346 }
347
348 impl MacResult for MacEager {
349     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
350         self.expr
351     }
352
353     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
354         self.items
355     }
356
357     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
358         self.impl_items
359     }
360
361     fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
362         self.trait_items
363     }
364
365     fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
366         match self.stmts.as_ref().map_or(0, |s| s.len()) {
367             0 => make_stmts_default!(self),
368             _ => self.stmts,
369         }
370     }
371
372     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
373         if let Some(p) = self.pat {
374             return Some(p);
375         }
376         if let Some(e) = self.expr {
377             if let ast::ExprKind::Lit(_) = e.node {
378                 return Some(P(ast::Pat {
379                     id: ast::DUMMY_NODE_ID,
380                     span: e.span,
381                     node: PatKind::Lit(e),
382                 }));
383             }
384         }
385         None
386     }
387
388     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
389         self.ty
390     }
391 }
392
393 /// Fill-in macro expansion result, to allow compilation to continue
394 /// after hitting errors.
395 #[derive(Copy, Clone)]
396 pub struct DummyResult {
397     expr_only: bool,
398     span: Span
399 }
400
401 impl DummyResult {
402     /// Create a default MacResult that can be anything.
403     ///
404     /// Use this as a return value after hitting any errors and
405     /// calling `span_err`.
406     pub fn any(sp: Span) -> Box<MacResult+'static> {
407         Box::new(DummyResult { expr_only: false, span: sp })
408     }
409
410     /// Create a default MacResult that can only be an expression.
411     ///
412     /// Use this for macros that must expand to an expression, so even
413     /// if an error is encountered internally, the user will receive
414     /// an error that they also used it in the wrong place.
415     pub fn expr(sp: Span) -> Box<MacResult+'static> {
416         Box::new(DummyResult { expr_only: true, span: sp })
417     }
418
419     /// A plain dummy expression.
420     pub fn raw_expr(sp: Span) -> P<ast::Expr> {
421         P(ast::Expr {
422             id: ast::DUMMY_NODE_ID,
423             node: ast::ExprKind::Lit(P(codemap::respan(sp, ast::LitKind::Bool(false)))),
424             span: sp,
425             attrs: ast::ThinVec::new(),
426         })
427     }
428
429     /// A plain dummy pattern.
430     pub fn raw_pat(sp: Span) -> ast::Pat {
431         ast::Pat {
432             id: ast::DUMMY_NODE_ID,
433             node: PatKind::Wild,
434             span: sp,
435         }
436     }
437
438     pub fn raw_ty(sp: Span) -> P<ast::Ty> {
439         P(ast::Ty {
440             id: ast::DUMMY_NODE_ID,
441             node: ast::TyKind::Infer,
442             span: sp
443         })
444     }
445 }
446
447 impl MacResult for DummyResult {
448     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
449         Some(DummyResult::raw_expr(self.span))
450     }
451
452     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
453         Some(P(DummyResult::raw_pat(self.span)))
454     }
455
456     fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
457         // this code needs a comment... why not always just return the Some() ?
458         if self.expr_only {
459             None
460         } else {
461             Some(SmallVector::new())
462         }
463     }
464
465     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<ast::ImplItem>> {
466         if self.expr_only {
467             None
468         } else {
469             Some(SmallVector::new())
470         }
471     }
472
473     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVector<ast::TraitItem>> {
474         if self.expr_only {
475             None
476         } else {
477             Some(SmallVector::new())
478         }
479     }
480
481     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<ast::Stmt>> {
482         Some(SmallVector::one(ast::Stmt {
483             id: ast::DUMMY_NODE_ID,
484             node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
485             span: self.span,
486         }))
487     }
488
489     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
490         Some(DummyResult::raw_ty(self.span))
491     }
492 }
493
494 pub type BuiltinDeriveFn =
495     for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut FnMut(Annotatable));
496
497 /// Represents different kinds of macro invocations that can be resolved.
498 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
499 pub enum MacroKind {
500     /// A bang macro - foo!()
501     Bang,
502     /// An attribute macro - #[foo]
503     Attr,
504     /// A derive attribute macro - #[derive(Foo)]
505     Derive,
506 }
507
508 /// An enum representing the different kinds of syntax extensions.
509 pub enum SyntaxExtension {
510     /// A syntax extension that is attached to an item and creates new items
511     /// based upon it.
512     ///
513     /// `#[derive(...)]` is a `MultiItemDecorator`.
514     ///
515     /// Prefer ProcMacro or MultiModifier since they are more flexible.
516     MultiDecorator(Box<MultiItemDecorator>),
517
518     /// A syntax extension that is attached to an item and modifies it
519     /// in-place. Also allows decoration, i.e., creating new items.
520     MultiModifier(Box<MultiItemModifier>),
521
522     /// A function-like procedural macro. TokenStream -> TokenStream.
523     ProcMacro(Box<ProcMacro>),
524
525     /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
526     /// The first TokenSteam is the attribute, the second is the annotated item.
527     /// Allows modification of the input items and adding new items, similar to
528     /// MultiModifier, but uses TokenStreams, rather than AST nodes.
529     AttrProcMacro(Box<AttrProcMacro>),
530
531     /// A normal, function-like syntax extension.
532     ///
533     /// `bytes!` is a `NormalTT`.
534     ///
535     /// The `bool` dictates whether the contents of the macro can
536     /// directly use `#[unstable]` things (true == yes).
537     NormalTT(Box<TTMacroExpander>, Option<Span>, bool),
538
539     /// A function-like syntax extension that has an extra ident before
540     /// the block.
541     ///
542     IdentTT(Box<IdentMacroExpander>, Option<Span>, bool),
543
544     /// An attribute-like procedural macro. TokenStream -> TokenStream.
545     /// The input is the annotated item.
546     /// Allows generating code to implement a Trait for a given struct
547     /// or enum item.
548     ProcMacroDerive(Box<MultiItemModifier>, Vec<Symbol> /* inert attribute names */),
549
550     /// An attribute-like procedural macro that derives a builtin trait.
551     BuiltinDerive(BuiltinDeriveFn),
552 }
553
554 impl SyntaxExtension {
555     /// Return which kind of macro calls this syntax extension.
556     pub fn kind(&self) -> MacroKind {
557         match *self {
558             SyntaxExtension::NormalTT(..) |
559             SyntaxExtension::IdentTT(..) |
560             SyntaxExtension::ProcMacro(..) =>
561                 MacroKind::Bang,
562             SyntaxExtension::MultiDecorator(..) |
563             SyntaxExtension::MultiModifier(..) |
564             SyntaxExtension::AttrProcMacro(..) =>
565                 MacroKind::Attr,
566             SyntaxExtension::ProcMacroDerive(..) |
567             SyntaxExtension::BuiltinDerive(..) =>
568                 MacroKind::Derive,
569         }
570     }
571 }
572
573 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
574
575 pub trait Resolver {
576     fn next_node_id(&mut self) -> ast::NodeId;
577     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
578     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
579     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool;
580
581     fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]);
582     fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>);
583
584     fn resolve_imports(&mut self);
585     // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
586     fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute>;
587     fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
588                      -> Result<Option<Rc<SyntaxExtension>>, Determinacy>;
589     fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
590                      -> Result<Rc<SyntaxExtension>, Determinacy>;
591 }
592
593 #[derive(Copy, Clone, Debug)]
594 pub enum Determinacy {
595     Determined,
596     Undetermined,
597 }
598
599 pub struct DummyResolver;
600
601 impl Resolver for DummyResolver {
602     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
603     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
604     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
605     fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false }
606
607     fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion, _derives: &[Mark]) {}
608     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Rc<SyntaxExtension>) {}
609
610     fn resolve_imports(&mut self) {}
611     fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>) -> Option<Attribute> { None }
612     fn resolve_invoc(&mut self, _invoc: &mut Invocation, _scope: Mark, _force: bool)
613                      -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
614         Err(Determinacy::Determined)
615     }
616     fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _kind: MacroKind,
617                      _force: bool) -> Result<Rc<SyntaxExtension>, Determinacy> {
618         Err(Determinacy::Determined)
619     }
620 }
621
622 #[derive(Clone)]
623 pub struct ModuleData {
624     pub mod_path: Vec<ast::Ident>,
625     pub directory: PathBuf,
626 }
627
628 #[derive(Clone)]
629 pub struct ExpansionData {
630     pub mark: Mark,
631     pub depth: usize,
632     pub module: Rc<ModuleData>,
633     pub directory_ownership: DirectoryOwnership,
634 }
635
636 /// One of these is made during expansion and incrementally updated as we go;
637 /// when a macro expansion occurs, the resulting nodes have the backtrace()
638 /// -> expn_info of their expansion context stored into their span.
639 pub struct ExtCtxt<'a> {
640     pub parse_sess: &'a parse::ParseSess,
641     pub ecfg: expand::ExpansionConfig<'a>,
642     pub crate_root: Option<&'static str>,
643     pub resolver: &'a mut Resolver,
644     pub resolve_err_count: usize,
645     pub current_expansion: ExpansionData,
646 }
647
648 impl<'a> ExtCtxt<'a> {
649     pub fn new(parse_sess: &'a parse::ParseSess,
650                ecfg: expand::ExpansionConfig<'a>,
651                resolver: &'a mut Resolver)
652                -> ExtCtxt<'a> {
653         ExtCtxt {
654             parse_sess: parse_sess,
655             ecfg: ecfg,
656             crate_root: None,
657             resolver: resolver,
658             resolve_err_count: 0,
659             current_expansion: ExpansionData {
660                 mark: Mark::root(),
661                 depth: 0,
662                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
663                 directory_ownership: DirectoryOwnership::Owned,
664             },
665         }
666     }
667
668     /// Returns a `Folder` for deeply expanding all macros in an AST node.
669     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
670         expand::MacroExpander::new(self, false)
671     }
672
673     /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
674     /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
675     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
676         expand::MacroExpander::new(self, true)
677     }
678
679     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
680         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
681     }
682     pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
683     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
684     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
685     pub fn call_site(&self) -> Span {
686         match self.current_expansion.mark.expn_info() {
687             Some(expn_info) => expn_info.call_site,
688             None => DUMMY_SP,
689         }
690     }
691     pub fn backtrace(&self) -> SyntaxContext {
692         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
693     }
694
695     /// Returns span for the macro which originally caused the current expansion to happen.
696     ///
697     /// Stops backtracing at include! boundary.
698     pub fn expansion_cause(&self) -> Span {
699         let mut ctxt = self.backtrace();
700         let mut last_macro = None;
701         loop {
702             if ctxt.outer().expn_info().map_or(None, |info| {
703                 if info.callee.name() == "include" {
704                     // Stop going up the backtrace once include! is encountered
705                     return None;
706                 }
707                 ctxt = info.call_site.ctxt;
708                 last_macro = Some(info.call_site);
709                 return Some(());
710             }).is_none() {
711                 break
712             }
713         }
714         last_macro.expect("missing expansion backtrace")
715     }
716
717     pub fn struct_span_warn(&self,
718                             sp: Span,
719                             msg: &str)
720                             -> DiagnosticBuilder<'a> {
721         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
722     }
723     pub fn struct_span_err(&self,
724                            sp: Span,
725                            msg: &str)
726                            -> DiagnosticBuilder<'a> {
727         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
728     }
729     pub fn struct_span_fatal(&self,
730                              sp: Span,
731                              msg: &str)
732                              -> DiagnosticBuilder<'a> {
733         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
734     }
735
736     /// Emit `msg` attached to `sp`, and stop compilation immediately.
737     ///
738     /// `span_err` should be strongly preferred where-ever possible:
739     /// this should *only* be used when
740     /// - continuing has a high risk of flow-on errors (e.g. errors in
741     ///   declaring a macro would cause all uses of that macro to
742     ///   complain about "undefined macro"), or
743     /// - there is literally nothing else that can be done (however,
744     ///   in most cases one can construct a dummy expression/item to
745     ///   substitute; we never hit resolve/type-checking so the dummy
746     ///   value doesn't have to match anything)
747     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
748         panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
749     }
750
751     /// Emit `msg` attached to `sp`, without immediately stopping
752     /// compilation.
753     ///
754     /// Compilation will be stopped in the near future (at the end of
755     /// the macro expansion phase).
756     pub fn span_err(&self, sp: Span, msg: &str) {
757         self.parse_sess.span_diagnostic.span_err(sp, msg);
758     }
759     pub fn span_warn(&self, sp: Span, msg: &str) {
760         self.parse_sess.span_diagnostic.span_warn(sp, msg);
761     }
762     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
763         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
764     }
765     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
766         self.parse_sess.span_diagnostic.span_bug(sp, msg);
767     }
768     pub fn bug(&self, msg: &str) -> ! {
769         self.parse_sess.span_diagnostic.bug(msg);
770     }
771     pub fn trace_macros(&self) -> bool {
772         self.ecfg.trace_mac
773     }
774     pub fn set_trace_macros(&mut self, x: bool) {
775         self.ecfg.trace_mac = x
776     }
777     pub fn ident_of(&self, st: &str) -> ast::Ident {
778         ast::Ident::from_str(st)
779     }
780     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
781         let mut v = Vec::new();
782         if let Some(s) = self.crate_root {
783             v.push(self.ident_of(s));
784         }
785         v.extend(components.iter().map(|s| self.ident_of(s)));
786         return v
787     }
788     pub fn name_of(&self, st: &str) -> ast::Name {
789         Symbol::intern(st)
790     }
791 }
792
793 /// Extract a string literal from the macro expanded version of `expr`,
794 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
795 /// compilation on error, merely emits a non-fatal error and returns None.
796 pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
797                               -> Option<Spanned<(Symbol, ast::StrStyle)>> {
798     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
799     let expr = expr.map(|mut expr| {
800         expr.span.ctxt = expr.span.ctxt.apply_mark(cx.current_expansion.mark);
801         expr
802     });
803
804     // we want to be able to handle e.g. concat("foo", "bar")
805     let expr = cx.expander().fold_expr(expr);
806     match expr.node {
807         ast::ExprKind::Lit(ref l) => match l.node {
808             ast::LitKind::Str(s, style) => return Some(respan(expr.span, (s, style))),
809             _ => cx.span_err(l.span, err_msg)
810         },
811         _ => cx.span_err(expr.span, err_msg)
812     }
813     None
814 }
815
816 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
817                       -> Option<(Symbol, ast::StrStyle)> {
818     expr_to_spanned_string(cx, expr, err_msg).map(|s| s.node)
819 }
820
821 /// Non-fatally assert that `tts` is empty. Note that this function
822 /// returns even when `tts` is non-empty, macros that *need* to stop
823 /// compilation should call
824 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
825 /// done as rarely as possible).
826 pub fn check_zero_tts(cx: &ExtCtxt,
827                       sp: Span,
828                       tts: &[tokenstream::TokenTree],
829                       name: &str) {
830     if !tts.is_empty() {
831         cx.span_err(sp, &format!("{} takes no arguments", name));
832     }
833 }
834
835 /// Extract the string literal from the first token of `tts`. If this
836 /// is not a string literal, emit an error and return None.
837 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
838                                sp: Span,
839                                tts: &[tokenstream::TokenTree],
840                                name: &str)
841                                -> Option<String> {
842     let mut p = cx.new_parser_from_tts(tts);
843     if p.token == token::Eof {
844         cx.span_err(sp, &format!("{} takes 1 argument", name));
845         return None
846     }
847     let ret = panictry!(p.parse_expr());
848     if p.token != token::Eof {
849         cx.span_err(sp, &format!("{} takes 1 argument", name));
850     }
851     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
852         s.to_string()
853     })
854 }
855
856 /// Extract comma-separated expressions from `tts`. If there is a
857 /// parsing error, emit a non-fatal error and return None.
858 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
859                           sp: Span,
860                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
861     let mut p = cx.new_parser_from_tts(tts);
862     let mut es = Vec::new();
863     while p.token != token::Eof {
864         es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
865         if p.eat(&token::Comma) {
866             continue;
867         }
868         if p.token != token::Eof {
869             cx.span_err(sp, "expected token: `,`");
870             return None;
871         }
872     }
873     Some(es)
874 }
875
876 pub struct ChangeSpan {
877     pub span: Span
878 }
879
880 impl Folder for ChangeSpan {
881     fn new_span(&mut self, _sp: Span) -> Span {
882         self.span
883     }
884
885     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
886         fold::noop_fold_mac(mac, self)
887     }
888 }