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