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