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