]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Merge remote-tracking branch 'origin/master' into gen
[rust.git] / src / libsyntax / ext / base.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::SyntaxExtension::*;
12
13 use ast::{self, Attribute, Name, PatKind, MetaItem};
14 use attr::HasAttrs;
15 use 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.0 {
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(..) |
582             SyntaxExtension::ProcMacro(..) |
583             SyntaxExtension::AttrProcMacro(..) |
584             SyntaxExtension::ProcMacroDerive(..) => true,
585             _ => false,
586         }
587     }
588 }
589
590 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
591
592 pub trait Resolver {
593     fn next_node_id(&mut self) -> ast::NodeId;
594     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
595     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
596     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool;
597
598     fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]);
599     fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>);
600
601     fn resolve_imports(&mut self);
602     // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
603     fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute>;
604     fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
605                      -> Result<Option<Rc<SyntaxExtension>>, Determinacy>;
606     fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
607                      -> Result<Rc<SyntaxExtension>, Determinacy>;
608     fn check_unused_macros(&self);
609 }
610
611 #[derive(Copy, Clone, Debug, PartialEq)]
612 pub enum Determinacy {
613     Determined,
614     Undetermined,
615 }
616
617 pub struct DummyResolver;
618
619 impl Resolver for DummyResolver {
620     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
621     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
622     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
623     fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false }
624
625     fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion, _derives: &[Mark]) {}
626     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Rc<SyntaxExtension>) {}
627
628     fn resolve_imports(&mut self) {}
629     fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>) -> Option<Attribute> { None }
630     fn resolve_invoc(&mut self, _invoc: &mut Invocation, _scope: Mark, _force: bool)
631                      -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
632         Err(Determinacy::Determined)
633     }
634     fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _kind: MacroKind,
635                      _force: bool) -> Result<Rc<SyntaxExtension>, Determinacy> {
636         Err(Determinacy::Determined)
637     }
638     fn check_unused_macros(&self) {}
639 }
640
641 #[derive(Clone)]
642 pub struct ModuleData {
643     pub mod_path: Vec<ast::Ident>,
644     pub directory: PathBuf,
645 }
646
647 #[derive(Clone)]
648 pub struct ExpansionData {
649     pub mark: Mark,
650     pub depth: usize,
651     pub module: Rc<ModuleData>,
652     pub directory_ownership: DirectoryOwnership,
653 }
654
655 /// One of these is made during expansion and incrementally updated as we go;
656 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
657 /// -> expn_info` of their expansion context stored into their span.
658 pub struct ExtCtxt<'a> {
659     pub parse_sess: &'a parse::ParseSess,
660     pub ecfg: expand::ExpansionConfig<'a>,
661     pub crate_root: Option<&'static str>,
662     pub resolver: &'a mut Resolver,
663     pub resolve_err_count: usize,
664     pub current_expansion: ExpansionData,
665     pub expansions: HashMap<Span, Vec<String>>,
666 }
667
668 impl<'a> ExtCtxt<'a> {
669     pub fn new(parse_sess: &'a parse::ParseSess,
670                ecfg: expand::ExpansionConfig<'a>,
671                resolver: &'a mut Resolver)
672                -> ExtCtxt<'a> {
673         ExtCtxt {
674             parse_sess: parse_sess,
675             ecfg: ecfg,
676             crate_root: None,
677             resolver: resolver,
678             resolve_err_count: 0,
679             current_expansion: ExpansionData {
680                 mark: Mark::root(),
681                 depth: 0,
682                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
683                 directory_ownership: DirectoryOwnership::Owned,
684             },
685             expansions: HashMap::new(),
686         }
687     }
688
689     /// Returns a `Folder` for deeply expanding all macros in an AST node.
690     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
691         expand::MacroExpander::new(self, false)
692     }
693
694     /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
695     /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
696     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
697         expand::MacroExpander::new(self, true)
698     }
699
700     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
701         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
702     }
703     pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
704     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
705     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
706     pub fn call_site(&self) -> Span {
707         match self.current_expansion.mark.expn_info() {
708             Some(expn_info) => expn_info.call_site,
709             None => DUMMY_SP,
710         }
711     }
712     pub fn backtrace(&self) -> SyntaxContext {
713         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
714     }
715
716     /// Returns span for the macro which originally caused the current expansion to happen.
717     ///
718     /// Stops backtracing at include! boundary.
719     pub fn expansion_cause(&self) -> Option<Span> {
720         let mut ctxt = self.backtrace();
721         let mut last_macro = None;
722         loop {
723             if ctxt.outer().expn_info().map_or(None, |info| {
724                 if info.callee.name() == "include" {
725                     // Stop going up the backtrace once include! is encountered
726                     return None;
727                 }
728                 ctxt = info.call_site.ctxt;
729                 last_macro = Some(info.call_site);
730                 Some(())
731             }).is_none() {
732                 break
733             }
734         }
735         last_macro
736     }
737
738     pub fn struct_span_warn(&self,
739                             sp: Span,
740                             msg: &str)
741                             -> DiagnosticBuilder<'a> {
742         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
743     }
744     pub fn struct_span_err(&self,
745                            sp: Span,
746                            msg: &str)
747                            -> DiagnosticBuilder<'a> {
748         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
749     }
750     pub fn struct_span_fatal(&self,
751                              sp: Span,
752                              msg: &str)
753                              -> DiagnosticBuilder<'a> {
754         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
755     }
756
757     /// Emit `msg` attached to `sp`, and stop compilation immediately.
758     ///
759     /// `span_err` should be strongly preferred where-ever possible:
760     /// this should *only* be used when
761     /// - continuing has a high risk of flow-on errors (e.g. errors in
762     ///   declaring a macro would cause all uses of that macro to
763     ///   complain about "undefined macro"), or
764     /// - there is literally nothing else that can be done (however,
765     ///   in most cases one can construct a dummy expression/item to
766     ///   substitute; we never hit resolve/type-checking so the dummy
767     ///   value doesn't have to match anything)
768     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
769         panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
770     }
771
772     /// Emit `msg` attached to `sp`, without immediately stopping
773     /// compilation.
774     ///
775     /// Compilation will be stopped in the near future (at the end of
776     /// the macro expansion phase).
777     pub fn span_err(&self, sp: Span, msg: &str) {
778         self.parse_sess.span_diagnostic.span_err(sp, msg);
779     }
780     pub fn span_warn(&self, sp: Span, msg: &str) {
781         self.parse_sess.span_diagnostic.span_warn(sp, msg);
782     }
783     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
784         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
785     }
786     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
787         self.parse_sess.span_diagnostic.span_bug(sp, msg);
788     }
789     pub fn trace_macros_diag(&self) {
790         for (sp, notes) in self.expansions.iter() {
791             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
792             for note in notes {
793                 db.note(note);
794             }
795             db.emit();
796         }
797     }
798     pub fn bug(&self, msg: &str) -> ! {
799         self.parse_sess.span_diagnostic.bug(msg);
800     }
801     pub fn trace_macros(&self) -> bool {
802         self.ecfg.trace_mac
803     }
804     pub fn set_trace_macros(&mut self, x: bool) {
805         self.ecfg.trace_mac = x
806     }
807     pub fn ident_of(&self, st: &str) -> ast::Ident {
808         ast::Ident::from_str(st)
809     }
810     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
811         let mut v = Vec::new();
812         if let Some(s) = self.crate_root {
813             v.push(self.ident_of(s));
814         }
815         v.extend(components.iter().map(|s| self.ident_of(s)));
816         v
817     }
818     pub fn name_of(&self, st: &str) -> ast::Name {
819         Symbol::intern(st)
820     }
821
822     pub fn check_unused_macros(&self) {
823         self.resolver.check_unused_macros();
824     }
825 }
826
827 /// Extract a string literal from the macro expanded version of `expr`,
828 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
829 /// compilation on error, merely emits a non-fatal error and returns None.
830 pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
831                               -> Option<Spanned<(Symbol, ast::StrStyle)>> {
832     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
833     let expr = expr.map(|mut expr| {
834         expr.span.ctxt = expr.span.ctxt.apply_mark(cx.current_expansion.mark);
835         expr
836     });
837
838     // we want to be able to handle e.g. concat("foo", "bar")
839     let expr = cx.expander().fold_expr(expr);
840     match expr.node {
841         ast::ExprKind::Lit(ref l) => match l.node {
842             ast::LitKind::Str(s, style) => return Some(respan(expr.span, (s, style))),
843             _ => cx.span_err(l.span, err_msg)
844         },
845         _ => cx.span_err(expr.span, err_msg)
846     }
847     None
848 }
849
850 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
851                       -> Option<(Symbol, ast::StrStyle)> {
852     expr_to_spanned_string(cx, expr, err_msg).map(|s| s.node)
853 }
854
855 /// Non-fatally assert that `tts` is empty. Note that this function
856 /// returns even when `tts` is non-empty, macros that *need* to stop
857 /// compilation should call
858 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
859 /// done as rarely as possible).
860 pub fn check_zero_tts(cx: &ExtCtxt,
861                       sp: Span,
862                       tts: &[tokenstream::TokenTree],
863                       name: &str) {
864     if !tts.is_empty() {
865         cx.span_err(sp, &format!("{} takes no arguments", name));
866     }
867 }
868
869 /// Extract the string literal from the first token of `tts`. If this
870 /// is not a string literal, emit an error and return None.
871 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
872                                sp: Span,
873                                tts: &[tokenstream::TokenTree],
874                                name: &str)
875                                -> Option<String> {
876     let mut p = cx.new_parser_from_tts(tts);
877     if p.token == token::Eof {
878         cx.span_err(sp, &format!("{} takes 1 argument", name));
879         return None
880     }
881     let ret = panictry!(p.parse_expr());
882     if p.token != token::Eof {
883         cx.span_err(sp, &format!("{} takes 1 argument", name));
884     }
885     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
886         s.to_string()
887     })
888 }
889
890 /// Extract comma-separated expressions from `tts`. If there is a
891 /// parsing error, emit a non-fatal error and return None.
892 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
893                           sp: Span,
894                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
895     let mut p = cx.new_parser_from_tts(tts);
896     let mut es = Vec::new();
897     while p.token != token::Eof {
898         es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
899         if p.eat(&token::Comma) {
900             continue;
901         }
902         if p.token != token::Eof {
903             cx.span_err(sp, "expected token: `,`");
904             return None;
905         }
906     }
907     Some(es)
908 }