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