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