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