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