]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[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: Box<FnMut(P<ast::Item>)>);
39 }
40
41 impl<F> ItemDecorator for F
42     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, Box<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: Box<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(Show,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(ecfg: &expand::ExpansionConfig) -> SyntaxEnv {
443     // utility function to simplify creating NormalTT syntax extensions
444     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
445         NormalTT(box f, None)
446     }
447
448     let mut syntax_expanders = SyntaxEnv::new();
449     syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
450     syntax_expanders.insert(intern("format_args"),
451                             builtin_normal_expander(
452                                 ext::format::expand_format_args));
453     syntax_expanders.insert(intern("env"),
454                             builtin_normal_expander(
455                                     ext::env::expand_env));
456     syntax_expanders.insert(intern("option_env"),
457                             builtin_normal_expander(
458                                     ext::env::expand_option_env));
459     syntax_expanders.insert(intern("concat_idents"),
460                             builtin_normal_expander(
461                                     ext::concat_idents::expand_syntax_ext));
462     syntax_expanders.insert(intern("concat"),
463                             builtin_normal_expander(
464                                     ext::concat::expand_syntax_ext));
465     syntax_expanders.insert(intern("log_syntax"),
466                             builtin_normal_expander(
467                                     ext::log_syntax::expand_syntax_ext));
468     syntax_expanders.insert(intern("derive"),
469                             Decorator(box ext::deriving::expand_meta_derive));
470
471     if ecfg.enable_quotes {
472         // Quasi-quoting expanders
473         syntax_expanders.insert(intern("quote_tokens"),
474                            builtin_normal_expander(
475                                 ext::quote::expand_quote_tokens));
476         syntax_expanders.insert(intern("quote_expr"),
477                            builtin_normal_expander(
478                                 ext::quote::expand_quote_expr));
479         syntax_expanders.insert(intern("quote_ty"),
480                            builtin_normal_expander(
481                                 ext::quote::expand_quote_ty));
482         syntax_expanders.insert(intern("quote_method"),
483                            builtin_normal_expander(
484                                 ext::quote::expand_quote_method));
485         syntax_expanders.insert(intern("quote_item"),
486                            builtin_normal_expander(
487                                 ext::quote::expand_quote_item));
488         syntax_expanders.insert(intern("quote_pat"),
489                            builtin_normal_expander(
490                                 ext::quote::expand_quote_pat));
491         syntax_expanders.insert(intern("quote_arm"),
492                            builtin_normal_expander(
493                                 ext::quote::expand_quote_arm));
494         syntax_expanders.insert(intern("quote_stmt"),
495                            builtin_normal_expander(
496                                 ext::quote::expand_quote_stmt));
497     }
498
499     syntax_expanders.insert(intern("line"),
500                             builtin_normal_expander(
501                                     ext::source_util::expand_line));
502     syntax_expanders.insert(intern("column"),
503                             builtin_normal_expander(
504                                     ext::source_util::expand_column));
505     syntax_expanders.insert(intern("file"),
506                             builtin_normal_expander(
507                                     ext::source_util::expand_file));
508     syntax_expanders.insert(intern("stringify"),
509                             builtin_normal_expander(
510                                     ext::source_util::expand_stringify));
511     syntax_expanders.insert(intern("include"),
512                             builtin_normal_expander(
513                                     ext::source_util::expand_include));
514     syntax_expanders.insert(intern("include_str"),
515                             builtin_normal_expander(
516                                     ext::source_util::expand_include_str));
517     syntax_expanders.insert(intern("include_bytes"),
518                             builtin_normal_expander(
519                                     ext::source_util::expand_include_bytes));
520     syntax_expanders.insert(intern("module_path"),
521                             builtin_normal_expander(
522                                     ext::source_util::expand_mod));
523     syntax_expanders.insert(intern("asm"),
524                             builtin_normal_expander(
525                                     ext::asm::expand_asm));
526     syntax_expanders.insert(intern("cfg"),
527                             builtin_normal_expander(
528                                     ext::cfg::expand_cfg));
529     syntax_expanders.insert(intern("cfg_attr"),
530                             Modifier(box ext::cfg_attr::expand));
531     syntax_expanders.insert(intern("trace_macros"),
532                             builtin_normal_expander(
533                                     ext::trace_macros::expand_trace_macros));
534     syntax_expanders
535 }
536
537 /// One of these is made during expansion and incrementally updated as we go;
538 /// when a macro expansion occurs, the resulting nodes have the backtrace()
539 /// -> expn_info of their expansion context stored into their span.
540 pub struct ExtCtxt<'a> {
541     pub parse_sess: &'a parse::ParseSess,
542     pub cfg: ast::CrateConfig,
543     pub backtrace: ExpnId,
544     pub ecfg: expand::ExpansionConfig,
545
546     pub mod_path: Vec<ast::Ident> ,
547     pub trace_mac: bool,
548     pub exported_macros: Vec<ast::MacroDef>,
549
550     pub syntax_env: SyntaxEnv,
551     pub recursion_count: usize,
552 }
553
554 impl<'a> ExtCtxt<'a> {
555     pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
556                ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
557         let env = initial_syntax_expander_table(&ecfg);
558         ExtCtxt {
559             parse_sess: parse_sess,
560             cfg: cfg,
561             backtrace: NO_EXPANSION,
562             mod_path: Vec::new(),
563             ecfg: ecfg,
564             trace_mac: false,
565             exported_macros: Vec::new(),
566             syntax_env: env,
567             recursion_count: 0,
568         }
569     }
570
571     #[deprecated = "Replaced with `expander().fold_expr()`"]
572     pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
573         self.expander().fold_expr(e)
574     }
575
576     /// Returns a `Folder` for deeply expanding all macros in a AST node.
577     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
578         expand::MacroExpander::new(self)
579     }
580
581     pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
582         -> parser::Parser<'a> {
583         parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
584     }
585
586     pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
587     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
588     pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
589     pub fn call_site(&self) -> Span {
590         self.codemap().with_expn_info(self.backtrace, |ei| match ei {
591             Some(expn_info) => expn_info.call_site,
592             None => self.bug("missing top span")
593         })
594     }
595     pub fn print_backtrace(&self) { }
596     pub fn backtrace(&self) -> ExpnId { self.backtrace }
597     pub fn original_span(&self) -> Span {
598         let mut expn_id = self.backtrace;
599         let mut call_site = None;
600         loop {
601             match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
602                 None => break,
603                 Some(cs) => {
604                     call_site = Some(cs);
605                     expn_id = cs.expn_id;
606                 }
607             }
608         }
609         call_site.expect("missing expansion backtrace")
610     }
611     pub fn original_span_in_file(&self) -> Span {
612         let mut expn_id = self.backtrace;
613         let mut call_site = None;
614         loop {
615             let expn_info = self.codemap().with_expn_info(expn_id, |ei| {
616                 ei.map(|ei| (ei.call_site, ei.callee.name == "include"))
617             });
618             match expn_info {
619                 None => break,
620                 Some((cs, is_include)) => {
621                     if is_include {
622                         // Don't recurse into file using "include!".
623                         break;
624                     }
625                     call_site = Some(cs);
626                     expn_id = cs.expn_id;
627                 }
628             }
629         }
630         call_site.expect("missing expansion backtrace")
631     }
632
633     pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
634     pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
635     pub fn mod_path(&self) -> Vec<ast::Ident> {
636         let mut v = Vec::new();
637         v.push(token::str_to_ident(&self.ecfg.crate_name[]));
638         v.extend(self.mod_path.iter().map(|a| *a));
639         return v;
640     }
641     pub fn bt_push(&mut self, ei: ExpnInfo) {
642         self.recursion_count += 1;
643         if self.recursion_count > self.ecfg.recursion_limit {
644             self.span_fatal(ei.call_site,
645                             &format!("recursion limit reached while expanding the macro `{}`",
646                                     ei.callee.name)[]);
647         }
648
649         let mut call_site = ei.call_site;
650         call_site.expn_id = self.backtrace;
651         self.backtrace = self.codemap().record_expansion(ExpnInfo {
652             call_site: call_site,
653             callee: ei.callee
654         });
655     }
656     pub fn bt_pop(&mut self) {
657         match self.backtrace {
658             NO_EXPANSION => self.bug("tried to pop without a push"),
659             expn_id => {
660                 self.recursion_count -= 1;
661                 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
662                     expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
663                 });
664             }
665         }
666     }
667
668     pub fn insert_macro(&mut self, def: ast::MacroDef) {
669         if def.export {
670             self.exported_macros.push(def.clone());
671         }
672         if def.use_locally {
673             let ext = macro_rules::compile(self, &def);
674             self.syntax_env.insert(def.ident.name, ext);
675         }
676     }
677
678     /// Emit `msg` attached to `sp`, and stop compilation immediately.
679     ///
680     /// `span_err` should be strongly preferred where-ever possible:
681     /// this should *only* be used when
682     /// - continuing has a high risk of flow-on errors (e.g. errors in
683     ///   declaring a macro would cause all uses of that macro to
684     ///   complain about "undefined macro"), or
685     /// - there is literally nothing else that can be done (however,
686     ///   in most cases one can construct a dummy expression/item to
687     ///   substitute; we never hit resolve/type-checking so the dummy
688     ///   value doesn't have to match anything)
689     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
690         self.print_backtrace();
691         self.parse_sess.span_diagnostic.span_fatal(sp, msg);
692     }
693
694     /// Emit `msg` attached to `sp`, without immediately stopping
695     /// compilation.
696     ///
697     /// Compilation will be stopped in the near future (at the end of
698     /// the macro expansion phase).
699     pub fn span_err(&self, sp: Span, msg: &str) {
700         self.print_backtrace();
701         self.parse_sess.span_diagnostic.span_err(sp, msg);
702     }
703     pub fn span_warn(&self, sp: Span, msg: &str) {
704         self.print_backtrace();
705         self.parse_sess.span_diagnostic.span_warn(sp, msg);
706     }
707     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
708         self.print_backtrace();
709         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
710     }
711     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
712         self.print_backtrace();
713         self.parse_sess.span_diagnostic.span_bug(sp, msg);
714     }
715     pub fn span_note(&self, sp: Span, msg: &str) {
716         self.print_backtrace();
717         self.parse_sess.span_diagnostic.span_note(sp, msg);
718     }
719     pub fn span_help(&self, sp: Span, msg: &str) {
720         self.print_backtrace();
721         self.parse_sess.span_diagnostic.span_help(sp, msg);
722     }
723     pub fn bug(&self, msg: &str) -> ! {
724         self.print_backtrace();
725         self.parse_sess.span_diagnostic.handler().bug(msg);
726     }
727     pub fn trace_macros(&self) -> bool {
728         self.trace_mac
729     }
730     pub fn set_trace_macros(&mut self, x: bool) {
731         self.trace_mac = x
732     }
733     pub fn ident_of(&self, st: &str) -> ast::Ident {
734         str_to_ident(st)
735     }
736     pub fn name_of(&self, st: &str) -> ast::Name {
737         token::intern(st)
738     }
739 }
740
741 /// Extract a string literal from the macro expanded version of `expr`,
742 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
743 /// compilation on error, merely emits a non-fatal error and returns None.
744 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
745                       -> Option<(InternedString, ast::StrStyle)> {
746     // we want to be able to handle e.g. concat("foo", "bar")
747     let expr = cx.expander().fold_expr(expr);
748     match expr.node {
749         ast::ExprLit(ref l) => match l.node {
750             ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
751             _ => cx.span_err(l.span, err_msg)
752         },
753         _ => cx.span_err(expr.span, err_msg)
754     }
755     None
756 }
757
758 /// Non-fatally assert that `tts` is empty. Note that this function
759 /// returns even when `tts` is non-empty, macros that *need* to stop
760 /// compilation should call
761 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
762 /// done as rarely as possible).
763 pub fn check_zero_tts(cx: &ExtCtxt,
764                       sp: Span,
765                       tts: &[ast::TokenTree],
766                       name: &str) {
767     if tts.len() != 0 {
768         cx.span_err(sp, &format!("{} takes no arguments", name)[]);
769     }
770 }
771
772 /// Extract the string literal from the first token of `tts`. If this
773 /// is not a string literal, emit an error and return None.
774 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
775                                sp: Span,
776                                tts: &[ast::TokenTree],
777                                name: &str)
778                                -> Option<String> {
779     let mut p = cx.new_parser_from_tts(tts);
780     if p.token == token::Eof {
781         cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
782         return None
783     }
784     let ret = cx.expander().fold_expr(p.parse_expr());
785     if p.token != token::Eof {
786         cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
787     }
788     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
789         s.get().to_string()
790     })
791 }
792
793 /// Extract comma-separated expressions from `tts`. If there is a
794 /// parsing error, emit a non-fatal error and return None.
795 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
796                           sp: Span,
797                           tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
798     let mut p = cx.new_parser_from_tts(tts);
799     let mut es = Vec::new();
800     while p.token != token::Eof {
801         es.push(cx.expander().fold_expr(p.parse_expr()));
802         if p.eat(&token::Comma) {
803             continue;
804         }
805         if p.token != token::Eof {
806             cx.span_err(sp, "expected token: `,`");
807             return None;
808         }
809     }
810     Some(es)
811 }
812
813 /// In order to have some notion of scoping for macros,
814 /// we want to implement the notion of a transformation
815 /// environment.
816 ///
817 /// This environment maps Names to SyntaxExtensions.
818 pub struct SyntaxEnv {
819     chain: Vec<MapChainFrame> ,
820 }
821
822 // impl question: how to implement it? Initially, the
823 // env will contain only macros, so it might be painful
824 // to add an empty frame for every context. Let's just
825 // get it working, first....
826
827 // NB! the mutability of the underlying maps means that
828 // if expansion is out-of-order, a deeper scope may be
829 // able to refer to a macro that was added to an enclosing
830 // scope lexically later than the deeper scope.
831
832 struct MapChainFrame {
833     info: BlockInfo,
834     map: HashMap<Name, Rc<SyntaxExtension>>,
835 }
836
837 impl SyntaxEnv {
838     fn new() -> SyntaxEnv {
839         let mut map = SyntaxEnv { chain: Vec::new() };
840         map.push_frame();
841         map
842     }
843
844     pub fn push_frame(&mut self) {
845         self.chain.push(MapChainFrame {
846             info: BlockInfo::new(),
847             map: HashMap::new(),
848         });
849     }
850
851     pub fn pop_frame(&mut self) {
852         assert!(self.chain.len() > 1, "too many pops on MapChain!");
853         self.chain.pop();
854     }
855
856     fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
857         for (i, frame) in self.chain.iter_mut().enumerate().rev() {
858             if !frame.info.macros_escape || i == 0 {
859                 return frame
860             }
861         }
862         unreachable!()
863     }
864
865     pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
866         for frame in self.chain.iter().rev() {
867             match frame.map.get(k) {
868                 Some(v) => return Some(v.clone()),
869                 None => {}
870             }
871         }
872         None
873     }
874
875     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
876         self.find_escape_frame().map.insert(k, Rc::new(v));
877     }
878
879     pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
880         let last_chain_index = self.chain.len() - 1;
881         &mut self.chain[last_chain_index].info
882     }
883 }