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