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