]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Auto merge of #28957 - GuillaumeGomez:patch-5, r=Manishearth
[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;
14 use ast::Name;
15 use codemap;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
17 use ext;
18 use ext::expand;
19 use ext::tt::macro_rules;
20 use feature_gate::GatedCfg;
21 use parse;
22 use parse::parser;
23 use parse::token;
24 use parse::token::{InternedString, intern, str_to_ident};
25 use ptr::P;
26 use util::small_vector::SmallVector;
27 use ext::mtwt;
28 use fold::Folder;
29
30 use std::collections::HashMap;
31 use std::rc::Rc;
32 use std::default::Default;
33
34
35 #[derive(Debug,Clone)]
36 pub enum Annotatable {
37     Item(P<ast::Item>),
38     TraitItem(P<ast::TraitItem>),
39     ImplItem(P<ast::ImplItem>),
40 }
41
42 impl Annotatable {
43     pub fn attrs(&self) -> &[ast::Attribute] {
44         match *self {
45             Annotatable::Item(ref i) => &i.attrs,
46             Annotatable::TraitItem(ref ti) => &ti.attrs,
47             Annotatable::ImplItem(ref ii) => &ii.attrs,
48         }
49     }
50
51     pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
52         match self {
53             Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
54                 attrs: attrs,
55                 ..i
56             })),
57             Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
58                 ast::TraitItem { attrs: attrs, ..ti }
59             })),
60             Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
61                 ast::ImplItem { attrs: attrs, ..ii }
62             })),
63         }
64     }
65
66     pub fn expect_item(self) -> P<ast::Item> {
67         match self {
68             Annotatable::Item(i) => i,
69             _ => panic!("expected Item")
70         }
71     }
72
73     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
74         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
75               G: FnMut(Annotatable) -> Annotatable
76     {
77         match self {
78             Annotatable::Item(i) => Annotatable::Item(f(i)),
79             _ => or(self)
80         }
81     }
82
83     pub fn expect_trait_item(self) -> P<ast::TraitItem> {
84         match self {
85             Annotatable::TraitItem(i) => i,
86             _ => panic!("expected Item")
87         }
88     }
89
90     pub fn expect_impl_item(self) -> P<ast::ImplItem> {
91         match self {
92             Annotatable::ImplItem(i) => i,
93             _ => panic!("expected Item")
94         }
95     }
96 }
97
98 // A more flexible ItemDecorator.
99 pub trait MultiItemDecorator {
100     fn expand(&self,
101               ecx: &mut ExtCtxt,
102               sp: Span,
103               meta_item: &ast::MetaItem,
104               item: &Annotatable,
105               push: &mut FnMut(Annotatable));
106 }
107
108 impl<F> MultiItemDecorator for F
109     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
110 {
111     fn expand(&self,
112               ecx: &mut ExtCtxt,
113               sp: Span,
114               meta_item: &ast::MetaItem,
115               item: &Annotatable,
116               push: &mut FnMut(Annotatable)) {
117         (*self)(ecx, sp, meta_item, item, push)
118     }
119 }
120
121 // A more flexible ItemModifier (ItemModifier should go away, eventually, FIXME).
122 // meta_item is the annotation, item is the item being modified, parent_item
123 // is the impl or trait item is declared in if item is part of such a thing.
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               -> Annotatable;
132 }
133
134 impl<F> MultiItemModifier for F
135     where F: Fn(&mut ExtCtxt,
136                 Span,
137                 &ast::MetaItem,
138                 Annotatable) -> Annotatable
139 {
140     fn expand(&self,
141               ecx: &mut ExtCtxt,
142               span: Span,
143               meta_item: &ast::MetaItem,
144               item: Annotatable)
145               -> Annotatable {
146         (*self)(ecx, span, meta_item, item)
147     }
148 }
149
150 /// Represents a thing that maps token trees to Macro Results
151 pub trait TTMacroExpander {
152     fn expand<'cx>(&self,
153                    ecx: &'cx mut ExtCtxt,
154                    span: Span,
155                    token_tree: &[ast::TokenTree])
156                    -> Box<MacResult+'cx>;
157 }
158
159 pub type MacroExpanderFn =
160     for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
161
162 impl<F> TTMacroExpander for F
163     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
164 {
165     fn expand<'cx>(&self,
166                    ecx: &'cx mut ExtCtxt,
167                    span: Span,
168                    token_tree: &[ast::TokenTree])
169                    -> Box<MacResult+'cx> {
170         (*self)(ecx, span, token_tree)
171     }
172 }
173
174 pub trait IdentMacroExpander {
175     fn expand<'cx>(&self,
176                    cx: &'cx mut ExtCtxt,
177                    sp: Span,
178                    ident: ast::Ident,
179                    token_tree: Vec<ast::TokenTree> )
180                    -> Box<MacResult+'cx>;
181 }
182
183 pub type IdentMacroExpanderFn =
184     for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
185
186 impl<F> IdentMacroExpander for F
187     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
188                           Vec<ast::TokenTree>) -> Box<MacResult+'cx>
189 {
190     fn expand<'cx>(&self,
191                    cx: &'cx mut ExtCtxt,
192                    sp: Span,
193                    ident: ast::Ident,
194                    token_tree: Vec<ast::TokenTree> )
195                    -> Box<MacResult+'cx>
196     {
197         (*self)(cx, sp, ident, token_tree)
198     }
199 }
200
201 // Use a macro because forwarding to a simple function has type system issues
202 macro_rules! make_stmts_default {
203     ($me:expr) => {
204         $me.make_expr().map(|e| {
205             SmallVector::one(P(codemap::respan(
206                 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
207         })
208     }
209 }
210
211 /// The result of a macro expansion. The return values of the various
212 /// methods are spliced into the AST at the callsite of the macro.
213 pub trait MacResult {
214     /// Create an expression.
215     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
216         None
217     }
218     /// Create zero or more items.
219     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
220         None
221     }
222
223     /// Create zero or more impl items.
224     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
225         None
226     }
227
228     /// Create a pattern.
229     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
230         None
231     }
232
233     /// Create zero or more statements.
234     ///
235     /// By default this attempts to create an expression statement,
236     /// returning None if that fails.
237     fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
238         make_stmts_default!(self)
239     }
240
241     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
242         None
243     }
244 }
245
246 macro_rules! make_MacEager {
247     ( $( $fld:ident: $t:ty, )* ) => {
248         /// `MacResult` implementation for the common case where you've already
249         /// built each form of AST that you might return.
250         #[derive(Default)]
251         pub struct MacEager {
252             $(
253                 pub $fld: Option<$t>,
254             )*
255         }
256
257         impl MacEager {
258             $(
259                 pub fn $fld(v: $t) -> Box<MacResult> {
260                     Box::new(MacEager {
261                         $fld: Some(v),
262                         ..Default::default()
263                     })
264                 }
265             )*
266         }
267     }
268 }
269
270 make_MacEager! {
271     expr: P<ast::Expr>,
272     pat: P<ast::Pat>,
273     items: SmallVector<P<ast::Item>>,
274     impl_items: SmallVector<P<ast::ImplItem>>,
275     stmts: SmallVector<P<ast::Stmt>>,
276     ty: P<ast::Ty>,
277 }
278
279 impl MacResult for MacEager {
280     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
281         self.expr
282     }
283
284     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
285         self.items
286     }
287
288     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
289         self.impl_items
290     }
291
292     fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
293         match self.stmts.as_ref().map_or(0, |s| s.len()) {
294             0 => make_stmts_default!(self),
295             _ => self.stmts,
296         }
297     }
298
299     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
300         if let Some(p) = self.pat {
301             return Some(p);
302         }
303         if let Some(e) = self.expr {
304             if let ast::ExprLit(_) = e.node {
305                 return Some(P(ast::Pat {
306                     id: ast::DUMMY_NODE_ID,
307                     span: e.span,
308                     node: ast::PatLit(e),
309                 }));
310             }
311         }
312         None
313     }
314
315     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
316         self.ty
317     }
318 }
319
320 /// Fill-in macro expansion result, to allow compilation to continue
321 /// after hitting errors.
322 #[derive(Copy, Clone)]
323 pub struct DummyResult {
324     expr_only: bool,
325     span: Span
326 }
327
328 impl DummyResult {
329     /// Create a default MacResult that can be anything.
330     ///
331     /// Use this as a return value after hitting any errors and
332     /// calling `span_err`.
333     pub fn any(sp: Span) -> Box<MacResult+'static> {
334         Box::new(DummyResult { expr_only: false, span: sp })
335     }
336
337     /// Create a default MacResult that can only be an expression.
338     ///
339     /// Use this for macros that must expand to an expression, so even
340     /// if an error is encountered internally, the user will receive
341     /// an error that they also used it in the wrong place.
342     pub fn expr(sp: Span) -> Box<MacResult+'static> {
343         Box::new(DummyResult { expr_only: true, span: sp })
344     }
345
346     /// A plain dummy expression.
347     pub fn raw_expr(sp: Span) -> P<ast::Expr> {
348         P(ast::Expr {
349             id: ast::DUMMY_NODE_ID,
350             node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
351             span: sp,
352         })
353     }
354
355     /// A plain dummy pattern.
356     pub fn raw_pat(sp: Span) -> ast::Pat {
357         ast::Pat {
358             id: ast::DUMMY_NODE_ID,
359             node: ast::PatWild(ast::PatWildSingle),
360             span: sp,
361         }
362     }
363
364     pub fn raw_ty(sp: Span) -> P<ast::Ty> {
365         P(ast::Ty {
366             id: ast::DUMMY_NODE_ID,
367             node: ast::TyInfer,
368             span: sp
369         })
370     }
371 }
372
373 impl MacResult for DummyResult {
374     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
375         Some(DummyResult::raw_expr(self.span))
376     }
377
378     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
379         Some(P(DummyResult::raw_pat(self.span)))
380     }
381
382     fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
383         // this code needs a comment... why not always just return the Some() ?
384         if self.expr_only {
385             None
386         } else {
387             Some(SmallVector::zero())
388         }
389     }
390
391     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
392         if self.expr_only {
393             None
394         } else {
395             Some(SmallVector::zero())
396         }
397     }
398
399     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Stmt>>> {
400         Some(SmallVector::one(P(
401             codemap::respan(self.span,
402                             ast::StmtExpr(DummyResult::raw_expr(self.span),
403                                           ast::DUMMY_NODE_ID)))))
404     }
405 }
406
407 /// An enum representing the different kinds of syntax extensions.
408 pub enum SyntaxExtension {
409     /// A syntax extension that is attached to an item and creates new items
410     /// based upon it.
411     ///
412     /// `#[derive(...)]` is a `MultiItemDecorator`.
413     MultiDecorator(Box<MultiItemDecorator + 'static>),
414
415     /// A syntax extension that is attached to an item and modifies it
416     /// in-place. More flexible version than Modifier.
417     MultiModifier(Box<MultiItemModifier + 'static>),
418
419     /// A normal, function-like syntax extension.
420     ///
421     /// `bytes!` is a `NormalTT`.
422     ///
423     /// The `bool` dictates whether the contents of the macro can
424     /// directly use `#[unstable]` things (true == yes).
425     NormalTT(Box<TTMacroExpander + 'static>, Option<Span>, bool),
426
427     /// A function-like syntax extension that has an extra ident before
428     /// the block.
429     ///
430     IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
431
432     /// Represents `macro_rules!` itself.
433     MacroRulesTT,
434 }
435
436 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
437
438 pub struct BlockInfo {
439     /// Should macros escape from this scope?
440     pub macros_escape: bool,
441     /// What are the pending renames?
442     pub pending_renames: mtwt::RenameList,
443 }
444
445 impl BlockInfo {
446     pub fn new() -> BlockInfo {
447         BlockInfo {
448             macros_escape: false,
449             pending_renames: Vec::new(),
450         }
451     }
452 }
453
454 /// The base map of methods for expanding syntax extension
455 /// AST nodes into full ASTs
456 fn initial_syntax_expander_table<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
457                                         -> SyntaxEnv {
458     // utility function to simplify creating NormalTT syntax extensions
459     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
460         NormalTT(Box::new(f), None, false)
461     }
462
463     let mut syntax_expanders = SyntaxEnv::new();
464     syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
465     syntax_expanders.insert(intern("format_args"),
466                             // format_args uses `unstable` things internally.
467                             NormalTT(Box::new(ext::format::expand_format_args), None, true));
468     syntax_expanders.insert(intern("env"),
469                             builtin_normal_expander(
470                                     ext::env::expand_env));
471     syntax_expanders.insert(intern("option_env"),
472                             builtin_normal_expander(
473                                     ext::env::expand_option_env));
474     syntax_expanders.insert(intern("concat_idents"),
475                             builtin_normal_expander(
476                                     ext::concat_idents::expand_syntax_ext));
477     syntax_expanders.insert(intern("concat"),
478                             builtin_normal_expander(
479                                     ext::concat::expand_syntax_ext));
480     syntax_expanders.insert(intern("log_syntax"),
481                             builtin_normal_expander(
482                                     ext::log_syntax::expand_syntax_ext));
483
484     ext::deriving::register_all(&mut syntax_expanders);
485
486     if ecfg.enable_quotes() {
487         // Quasi-quoting expanders
488         syntax_expanders.insert(intern("quote_tokens"),
489                            builtin_normal_expander(
490                                 ext::quote::expand_quote_tokens));
491         syntax_expanders.insert(intern("quote_expr"),
492                            builtin_normal_expander(
493                                 ext::quote::expand_quote_expr));
494         syntax_expanders.insert(intern("quote_ty"),
495                            builtin_normal_expander(
496                                 ext::quote::expand_quote_ty));
497         syntax_expanders.insert(intern("quote_item"),
498                            builtin_normal_expander(
499                                 ext::quote::expand_quote_item));
500         syntax_expanders.insert(intern("quote_pat"),
501                            builtin_normal_expander(
502                                 ext::quote::expand_quote_pat));
503         syntax_expanders.insert(intern("quote_arm"),
504                            builtin_normal_expander(
505                                 ext::quote::expand_quote_arm));
506         syntax_expanders.insert(intern("quote_stmt"),
507                            builtin_normal_expander(
508                                 ext::quote::expand_quote_stmt));
509         syntax_expanders.insert(intern("quote_matcher"),
510                            builtin_normal_expander(
511                                 ext::quote::expand_quote_matcher));
512         syntax_expanders.insert(intern("quote_attr"),
513                            builtin_normal_expander(
514                                 ext::quote::expand_quote_attr));
515     }
516
517     syntax_expanders.insert(intern("line"),
518                             builtin_normal_expander(
519                                     ext::source_util::expand_line));
520     syntax_expanders.insert(intern("column"),
521                             builtin_normal_expander(
522                                     ext::source_util::expand_column));
523     syntax_expanders.insert(intern("file"),
524                             builtin_normal_expander(
525                                     ext::source_util::expand_file));
526     syntax_expanders.insert(intern("stringify"),
527                             builtin_normal_expander(
528                                     ext::source_util::expand_stringify));
529     syntax_expanders.insert(intern("include"),
530                             builtin_normal_expander(
531                                     ext::source_util::expand_include));
532     syntax_expanders.insert(intern("include_str"),
533                             builtin_normal_expander(
534                                     ext::source_util::expand_include_str));
535     syntax_expanders.insert(intern("include_bytes"),
536                             builtin_normal_expander(
537                                     ext::source_util::expand_include_bytes));
538     syntax_expanders.insert(intern("module_path"),
539                             builtin_normal_expander(
540                                     ext::source_util::expand_mod));
541     syntax_expanders.insert(intern("asm"),
542                             builtin_normal_expander(
543                                     ext::asm::expand_asm));
544     syntax_expanders.insert(intern("cfg"),
545                             builtin_normal_expander(
546                                     ext::cfg::expand_cfg));
547     syntax_expanders.insert(intern("trace_macros"),
548                             builtin_normal_expander(
549                                     ext::trace_macros::expand_trace_macros));
550     syntax_expanders
551 }
552
553 /// One of these is made during expansion and incrementally updated as we go;
554 /// when a macro expansion occurs, the resulting nodes have the backtrace()
555 /// -> expn_info of their expansion context stored into their span.
556 pub struct ExtCtxt<'a> {
557     pub parse_sess: &'a parse::ParseSess,
558     pub cfg: ast::CrateConfig,
559     pub backtrace: ExpnId,
560     pub ecfg: expand::ExpansionConfig<'a>,
561     pub crate_root: Option<&'static str>,
562     pub feature_gated_cfgs: &'a mut Vec<GatedCfg>,
563
564     pub mod_path: Vec<ast::Ident> ,
565     pub exported_macros: Vec<ast::MacroDef>,
566
567     pub syntax_env: SyntaxEnv,
568     pub recursion_count: usize,
569 }
570
571 impl<'a> ExtCtxt<'a> {
572     pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
573                ecfg: expand::ExpansionConfig<'a>,
574                feature_gated_cfgs: &'a mut Vec<GatedCfg>) -> ExtCtxt<'a> {
575         let env = initial_syntax_expander_table(&ecfg);
576         ExtCtxt {
577             parse_sess: parse_sess,
578             cfg: cfg,
579             backtrace: NO_EXPANSION,
580             mod_path: Vec::new(),
581             ecfg: ecfg,
582             crate_root: None,
583             feature_gated_cfgs: feature_gated_cfgs,
584             exported_macros: Vec::new(),
585             syntax_env: env,
586             recursion_count: 0,
587         }
588     }
589
590     #[unstable(feature = "rustc_private")]
591     #[deprecated(since = "1.0.0",
592                  reason = "Replaced with `expander().fold_expr()`")]
593     pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
594         self.expander().fold_expr(e)
595     }
596
597     /// Returns a `Folder` for deeply expanding all macros in an AST node.
598     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
599         expand::MacroExpander::new(self)
600     }
601
602     pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
603         -> parser::Parser<'a> {
604         parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
605     }
606
607     pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
608     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
609     pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
610     pub fn call_site(&self) -> Span {
611         self.codemap().with_expn_info(self.backtrace, |ei| match ei {
612             Some(expn_info) => expn_info.call_site,
613             None => self.bug("missing top span")
614         })
615     }
616     pub fn backtrace(&self) -> ExpnId { self.backtrace }
617
618     /// Original span that caused the current exapnsion to happen.
619     pub fn original_span(&self) -> Span {
620         let mut expn_id = self.backtrace;
621         let mut call_site = None;
622         loop {
623             match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
624                 None => break,
625                 Some(cs) => {
626                     call_site = Some(cs);
627                     expn_id = cs.expn_id;
628                 }
629             }
630         }
631         call_site.expect("missing expansion backtrace")
632     }
633
634     /// Returns span for the macro which originally caused the current expansion to happen.
635     ///
636     /// Stops backtracing at include! boundary.
637     pub fn expansion_cause(&self) -> Span {
638         let mut expn_id = self.backtrace;
639         let mut last_macro = None;
640         loop {
641             if self.codemap().with_expn_info(expn_id, |info| {
642                 info.map_or(None, |i| {
643                     if i.callee.name().as_str() == "include" {
644                         // Stop going up the backtrace once include! is encountered
645                         return None;
646                     }
647                     expn_id = i.call_site.expn_id;
648                     last_macro = Some(i.call_site);
649                     return Some(());
650                 })
651             }).is_none() {
652                 break
653             }
654         }
655         last_macro.expect("missing expansion backtrace")
656     }
657
658     pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
659     pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
660     pub fn mod_path(&self) -> Vec<ast::Ident> {
661         let mut v = Vec::new();
662         v.push(token::str_to_ident(&self.ecfg.crate_name));
663         v.extend(self.mod_path.iter().cloned());
664         return v;
665     }
666     pub fn bt_push(&mut self, ei: ExpnInfo) {
667         self.recursion_count += 1;
668         if self.recursion_count > self.ecfg.recursion_limit {
669             panic!(self.span_fatal(ei.call_site,
670                             &format!("recursion limit reached while expanding the macro `{}`",
671                                     ei.callee.name())));
672         }
673
674         let mut call_site = ei.call_site;
675         call_site.expn_id = self.backtrace;
676         self.backtrace = self.codemap().record_expansion(ExpnInfo {
677             call_site: call_site,
678             callee: ei.callee
679         });
680     }
681     pub fn bt_pop(&mut self) {
682         match self.backtrace {
683             NO_EXPANSION => self.bug("tried to pop without a push"),
684             expn_id => {
685                 self.recursion_count -= 1;
686                 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
687                     expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
688                 });
689             }
690         }
691     }
692
693     pub fn insert_macro(&mut self, def: ast::MacroDef) {
694         if def.export {
695             self.exported_macros.push(def.clone());
696         }
697         if def.use_locally {
698             let ext = macro_rules::compile(self, &def);
699             self.syntax_env.insert(def.ident.name, ext);
700         }
701     }
702
703     /// Emit `msg` attached to `sp`, and stop compilation immediately.
704     ///
705     /// `span_err` should be strongly preferred where-ever possible:
706     /// this should *only* be used when
707     /// - continuing has a high risk of flow-on errors (e.g. errors in
708     ///   declaring a macro would cause all uses of that macro to
709     ///   complain about "undefined macro"), or
710     /// - there is literally nothing else that can be done (however,
711     ///   in most cases one can construct a dummy expression/item to
712     ///   substitute; we never hit resolve/type-checking so the dummy
713     ///   value doesn't have to match anything)
714     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
715         panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
716     }
717
718     /// Emit `msg` attached to `sp`, without immediately stopping
719     /// compilation.
720     ///
721     /// Compilation will be stopped in the near future (at the end of
722     /// the macro expansion phase).
723     pub fn span_err(&self, sp: Span, msg: &str) {
724         self.parse_sess.span_diagnostic.span_err(sp, msg);
725     }
726     pub fn span_warn(&self, sp: Span, msg: &str) {
727         self.parse_sess.span_diagnostic.span_warn(sp, msg);
728     }
729     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
730         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
731     }
732     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
733         self.parse_sess.span_diagnostic.span_bug(sp, msg);
734     }
735     pub fn span_note(&self, sp: Span, msg: &str) {
736         self.parse_sess.span_diagnostic.span_note(sp, msg);
737     }
738     pub fn span_help(&self, sp: Span, msg: &str) {
739         self.parse_sess.span_diagnostic.span_help(sp, msg);
740     }
741     pub fn fileline_help(&self, sp: Span, msg: &str) {
742         self.parse_sess.span_diagnostic.fileline_help(sp, msg);
743     }
744     pub fn bug(&self, msg: &str) -> ! {
745         self.parse_sess.span_diagnostic.handler().bug(msg);
746     }
747     pub fn trace_macros(&self) -> bool {
748         self.ecfg.trace_mac
749     }
750     pub fn set_trace_macros(&mut self, x: bool) {
751         self.ecfg.trace_mac = x
752     }
753     pub fn ident_of(&self, st: &str) -> ast::Ident {
754         str_to_ident(st)
755     }
756     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
757         let mut v = Vec::new();
758         if let Some(s) = self.crate_root {
759             v.push(self.ident_of(s));
760         }
761         v.extend(components.iter().map(|s| self.ident_of(s)));
762         return v
763     }
764     pub fn name_of(&self, st: &str) -> ast::Name {
765         token::intern(st)
766     }
767 }
768
769 /// Extract a string literal from the macro expanded version of `expr`,
770 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
771 /// compilation on error, merely emits a non-fatal error and returns None.
772 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
773                       -> Option<(InternedString, ast::StrStyle)> {
774     // we want to be able to handle e.g. concat("foo", "bar")
775     let expr = cx.expander().fold_expr(expr);
776     match expr.node {
777         ast::ExprLit(ref l) => match l.node {
778             ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
779             _ => cx.span_err(l.span, err_msg)
780         },
781         _ => cx.span_err(expr.span, err_msg)
782     }
783     None
784 }
785
786 /// Non-fatally assert that `tts` is empty. Note that this function
787 /// returns even when `tts` is non-empty, macros that *need* to stop
788 /// compilation should call
789 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
790 /// done as rarely as possible).
791 pub fn check_zero_tts(cx: &ExtCtxt,
792                       sp: Span,
793                       tts: &[ast::TokenTree],
794                       name: &str) {
795     if !tts.is_empty() {
796         cx.span_err(sp, &format!("{} takes no arguments", name));
797     }
798 }
799
800 /// Extract the string literal from the first token of `tts`. If this
801 /// is not a string literal, emit an error and return None.
802 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
803                                sp: Span,
804                                tts: &[ast::TokenTree],
805                                name: &str)
806                                -> Option<String> {
807     let mut p = cx.new_parser_from_tts(tts);
808     if p.token == token::Eof {
809         cx.span_err(sp, &format!("{} takes 1 argument", name));
810         return None
811     }
812     let ret = cx.expander().fold_expr(p.parse_expr());
813     if p.token != token::Eof {
814         cx.span_err(sp, &format!("{} takes 1 argument", name));
815     }
816     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
817         s.to_string()
818     })
819 }
820
821 /// Extract comma-separated expressions from `tts`. If there is a
822 /// parsing error, emit a non-fatal error and return None.
823 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
824                           sp: Span,
825                           tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
826     let mut p = cx.new_parser_from_tts(tts);
827     let mut es = Vec::new();
828     while p.token != token::Eof {
829         es.push(cx.expander().fold_expr(p.parse_expr()));
830         if panictry!(p.eat(&token::Comma)){
831             continue;
832         }
833         if p.token != token::Eof {
834             cx.span_err(sp, "expected token: `,`");
835             return None;
836         }
837     }
838     Some(es)
839 }
840
841 /// In order to have some notion of scoping for macros,
842 /// we want to implement the notion of a transformation
843 /// environment.
844 ///
845 /// This environment maps Names to SyntaxExtensions.
846 pub struct SyntaxEnv {
847     chain: Vec<MapChainFrame> ,
848 }
849
850 // impl question: how to implement it? Initially, the
851 // env will contain only macros, so it might be painful
852 // to add an empty frame for every context. Let's just
853 // get it working, first....
854
855 // NB! the mutability of the underlying maps means that
856 // if expansion is out-of-order, a deeper scope may be
857 // able to refer to a macro that was added to an enclosing
858 // scope lexically later than the deeper scope.
859
860 struct MapChainFrame {
861     info: BlockInfo,
862     map: HashMap<Name, Rc<SyntaxExtension>>,
863 }
864
865 impl SyntaxEnv {
866     fn new() -> SyntaxEnv {
867         let mut map = SyntaxEnv { chain: Vec::new() };
868         map.push_frame();
869         map
870     }
871
872     pub fn push_frame(&mut self) {
873         self.chain.push(MapChainFrame {
874             info: BlockInfo::new(),
875             map: HashMap::new(),
876         });
877     }
878
879     pub fn pop_frame(&mut self) {
880         assert!(self.chain.len() > 1, "too many pops on MapChain!");
881         self.chain.pop();
882     }
883
884     fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
885         for (i, frame) in self.chain.iter_mut().enumerate().rev() {
886             if !frame.info.macros_escape || i == 0 {
887                 return frame
888             }
889         }
890         unreachable!()
891     }
892
893     pub fn find(&self, k: Name) -> Option<Rc<SyntaxExtension>> {
894         for frame in self.chain.iter().rev() {
895             match frame.map.get(&k) {
896                 Some(v) => return Some(v.clone()),
897                 None => {}
898             }
899         }
900         None
901     }
902
903     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
904         self.find_escape_frame().map.insert(k, Rc::new(v));
905     }
906
907     pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
908         let last_chain_index = self.chain.len() - 1;
909         &mut self.chain[last_chain_index].info
910     }
911 }