base.rs 22.0 KB
Newer Older
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

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;
A
Alex Crichton 已提交
18
use parse::token;
P
Patrick Walton 已提交
19
use parse::token::{InternedString, intern, str_to_ident};
S
Steven Fackler 已提交
20
use util::small_vector::SmallVector;
21

22
use collections::HashMap;
23

24 25
// new-style macro! tt code:
//
26
//    MacResult, NormalTT, IdentTT
27
//
28
// also note that ast::Mac used to have a bunch of extraneous cases and
29
// is now probably a redundant AST node, can be merged with
30
// ast::MacInvocTT.
31

32
pub struct MacroDef {
33 34
    pub name: ~str,
    pub ext: SyntaxExtension
35
}
36

37
pub type ItemDecorator =
S
Steven Fackler 已提交
38
    fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item, |@ast::Item|);
39

40 41 42
pub type ItemModifier =
    fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item) -> @ast::Item;

S
Steven Fackler 已提交
43
pub struct BasicMacroExpander {
44 45
    pub expander: MacroExpanderFn,
    pub span: Option<Span>
46 47
}

S
Steven Fackler 已提交
48
pub trait MacroExpander {
49
    fn expand(&self,
S
Steven Fackler 已提交
50
              ecx: &mut ExtCtxt,
51
              span: Span,
S
Steven Fackler 已提交
52
              token_tree: &[ast::TokenTree])
53
              -> ~MacResult;
54 55
}

S
Steven Fackler 已提交
56
pub type MacroExpanderFn =
57
    fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
58
       -> ~MacResult;
59

S
Steven Fackler 已提交
60
impl MacroExpander for BasicMacroExpander {
61
    fn expand(&self,
S
Steven Fackler 已提交
62
              ecx: &mut ExtCtxt,
63
              span: Span,
S
Steven Fackler 已提交
64
              token_tree: &[ast::TokenTree])
65
              -> ~MacResult {
S
Steven Fackler 已提交
66
        (self.expander)(ecx, span, token_tree)
67 68
    }
}
J
John Clements 已提交
69

S
Steven Fackler 已提交
70
pub struct BasicIdentMacroExpander {
71 72
    pub expander: IdentMacroExpanderFn,
    pub span: Option<Span>
73 74
}

S
Steven Fackler 已提交
75
pub trait IdentMacroExpander {
76
    fn expand(&self,
S
Steven Fackler 已提交
77
              cx: &mut ExtCtxt,
78 79
              sp: Span,
              ident: ast::Ident,
80
              token_tree: Vec<ast::TokenTree> )
81
              -> ~MacResult;
82 83
}

S
Steven Fackler 已提交
84
impl IdentMacroExpander for BasicIdentMacroExpander {
85
    fn expand(&self,
S
Steven Fackler 已提交
86
              cx: &mut ExtCtxt,
87 88
              sp: Span,
              ident: ast::Ident,
89
              token_tree: Vec<ast::TokenTree> )
90
              -> ~MacResult {
S
Steven Fackler 已提交
91
        (self.expander)(cx, sp, ident, token_tree)
92 93 94
    }
}

S
Steven Fackler 已提交
95
pub type IdentMacroExpanderFn =
96
    fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> ~MacResult;
97

98
pub type MacroCrateRegistrationFun =
S
Steven Fackler 已提交
99
    fn(|ast::Name, SyntaxExtension|);
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
/// The result of a macro expansion. The return values of the various
/// methods are spliced into the AST at the callsite of the macro (or
/// just into the compiler's internal macro table, for `make_def`).
pub trait MacResult {
    /// Define a new macro.
    fn make_def(&self) -> Option<MacroDef> {
        None
    }
    /// Create an expression.
    fn make_expr(&self) -> Option<@ast::Expr> {
        None
    }
    /// Create zero or more items.
    fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
        None
    }

    /// Create a statement.
    ///
    /// By default this attempts to create an expression statement,
    /// returning None if that fails.
    fn make_stmt(&self) -> Option<@ast::Stmt> {
        self.make_expr()
            .map(|e| @codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
    }
126
}
J
John Clements 已提交
127

128 129 130 131 132 133
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
    e: @ast::Expr
}
impl MacExpr {
    pub fn new(e: @ast::Expr) -> ~MacResult {
134
        box MacExpr { e: e } as ~MacResult
135 136 137 138 139 140 141 142 143 144 145 146 147
    }
}
impl MacResult for MacExpr {
    fn make_expr(&self) -> Option<@ast::Expr> {
        Some(self.e)
    }
}
/// A convenience type for macros that return a single item.
pub struct MacItem {
    i: @ast::Item
}
impl MacItem {
    pub fn new(i: @ast::Item) -> ~MacResult {
148
        box MacItem { i: i } as ~MacResult
149 150 151 152 153 154 155 156 157 158 159 160 161 162
    }
}
impl MacResult for MacItem {
    fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
        Some(SmallVector::one(self.i))
    }
    fn make_stmt(&self) -> Option<@ast::Stmt> {
        Some(@codemap::respan(
            self.i.span,
            ast::StmtDecl(
                @codemap::respan(self.i.span, ast::DeclItem(self.i)),
                ast::DUMMY_NODE_ID)))
    }
}
163

164 165 166 167 168
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
    expr_only: bool,
    span: Span
169
}
170 171 172 173 174 175 176

impl DummyResult {
    /// Create a default MacResult that can be anything.
    ///
    /// Use this as a return value after hitting any errors and
    /// calling `span_err`.
    pub fn any(sp: Span) -> ~MacResult {
177
        box DummyResult { expr_only: false, span: sp } as ~MacResult
178 179 180 181 182 183 184 185
    }

    /// Create a default MacResult that can only be an expression.
    ///
    /// Use this for macros that must expand to an expression, so even
    /// if an error is encountered internally, the user will recieve
    /// an error that they also used it in the wrong place.
    pub fn expr(sp: Span) -> ~MacResult {
186
        box DummyResult { expr_only: true, span: sp } as ~MacResult
187 188 189 190
    }

    /// A plain dummy expression.
    pub fn raw_expr(sp: Span) -> @ast::Expr {
191 192
        @ast::Expr {
            id: ast::DUMMY_NODE_ID,
193 194
            node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
            span: sp,
195 196
        }
    }
197
}
198 199 200 201

impl MacResult for DummyResult {
    fn make_expr(&self) -> Option<@ast::Expr> {
        Some(DummyResult::raw_expr(self.span))
202
    }
203 204 205 206 207 208
    fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
        if self.expr_only {
            None
        } else {
            Some(SmallVector::zero())
        }
209
    }
210 211 212 213
    fn make_stmt(&self) -> Option<@ast::Stmt> {
        Some(@codemap::respan(self.span,
                              ast::StmtExpr(DummyResult::raw_expr(self.span),
                                            ast::DUMMY_NODE_ID)))
214
    }
215
}
216

217
/// An enum representing the different kinds of syntax extensions.
218
pub enum SyntaxExtension {
219 220 221 222
    /// A syntax extension that is attached to an item and creates new items
    /// based upon it.
    ///
    /// `#[deriving(...)]` is an `ItemDecorator`.
223
    ItemDecorator(ItemDecorator),
224

225 226 227
    /// A syntax extension that is attached to an item and modifies it
    /// in-place.
    ItemModifier(ItemModifier),
228

229 230 231 232
    /// A normal, function-like syntax extension.
    ///
    /// `bytes!` is a `NormalTT`.
    NormalTT(~MacroExpander:'static, Option<Span>),
J
John Clements 已提交
233

234 235 236 237
    /// A function-like syntax extension that has an extra ident before
    /// the block.
    ///
    /// `macro_rules!` is an `IdentTT`.
S
Steven Fackler 已提交
238
    IdentTT(~IdentMacroExpander:'static, Option<Span>),
239
}
240

241 242
pub struct BlockInfo {
    // should macros escape from this scope?
243
    pub macros_escape: bool,
244
    // what are the pending renames?
245
    pub pending_renames: RenameList,
S
Steven Fackler 已提交
246 247 248 249 250 251
}

impl BlockInfo {
    pub fn new() -> BlockInfo {
        BlockInfo {
            macros_escape: false,
252
            pending_renames: Vec::new(),
S
Steven Fackler 已提交
253 254
        }
    }
J
John Clements 已提交
255
}
256

257
// a list of ident->name renamings
258
pub type RenameList = Vec<(ast::Ident, Name)>;
259

J
John Clements 已提交
260
// The base map of methods for expanding syntax extension
261
// AST nodes into full ASTs
J
John Clements 已提交
262
pub fn syntax_expander_table() -> SyntaxEnv {
J
John Clements 已提交
263
    // utility function to simplify creating NormalTT syntax extensions
S
Steven Fackler 已提交
264
    fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
265
        NormalTT(box BasicMacroExpander {
S
Steven Fackler 已提交
266 267 268 269
                expander: f,
                span: None,
            },
            None)
270
    }
K
Kiet Tran 已提交
271

272
    let mut syntax_expanders = SyntaxEnv::new();
273
    syntax_expanders.insert(intern("macro_rules"),
274
                            IdentTT(box BasicIdentMacroExpander {
S
Steven Fackler 已提交
275
                                expander: ext::tt::macro_rules::add_new_extension,
276
                                span: None,
277
                            },
S
Steven Fackler 已提交
278
                            None));
279
    syntax_expanders.insert(intern("fmt"),
S
Steven Fackler 已提交
280
                            builtin_normal_expander(
281
                                ext::fmt::expand_syntax_ext));
282
    syntax_expanders.insert(intern("format_args"),
S
Steven Fackler 已提交
283
                            builtin_normal_expander(
284
                                ext::format::expand_args));
285
    syntax_expanders.insert(intern("env"),
S
Steven Fackler 已提交
286
                            builtin_normal_expander(
287
                                    ext::env::expand_env));
288
    syntax_expanders.insert(intern("option_env"),
S
Steven Fackler 已提交
289
                            builtin_normal_expander(
290
                                    ext::env::expand_option_env));
291
    syntax_expanders.insert(intern("bytes"),
S
Steven Fackler 已提交
292
                            builtin_normal_expander(
293
                                    ext::bytes::expand_syntax_ext));
294
    syntax_expanders.insert(intern("concat_idents"),
S
Steven Fackler 已提交
295
                            builtin_normal_expander(
296
                                    ext::concat_idents::expand_syntax_ext));
297
    syntax_expanders.insert(intern("concat"),
S
Steven Fackler 已提交
298
                            builtin_normal_expander(
299
                                    ext::concat::expand_syntax_ext));
300
    syntax_expanders.insert(intern("log_syntax"),
S
Steven Fackler 已提交
301
                            builtin_normal_expander(
302
                                    ext::log_syntax::expand_syntax_ext));
303
    syntax_expanders.insert(intern("deriving"),
S
Steven Fackler 已提交
304
                            ItemDecorator(ext::deriving::expand_meta_deriving));
305 306

    // Quasi-quoting expanders
307
    syntax_expanders.insert(intern("quote_tokens"),
S
Steven Fackler 已提交
308
                       builtin_normal_expander(
309
                            ext::quote::expand_quote_tokens));
310
    syntax_expanders.insert(intern("quote_expr"),
S
Steven Fackler 已提交
311
                       builtin_normal_expander(
312
                            ext::quote::expand_quote_expr));
313
    syntax_expanders.insert(intern("quote_ty"),
S
Steven Fackler 已提交
314
                       builtin_normal_expander(
315
                            ext::quote::expand_quote_ty));
316
    syntax_expanders.insert(intern("quote_item"),
S
Steven Fackler 已提交
317
                       builtin_normal_expander(
318
                            ext::quote::expand_quote_item));
319
    syntax_expanders.insert(intern("quote_pat"),
S
Steven Fackler 已提交
320
                       builtin_normal_expander(
321
                            ext::quote::expand_quote_pat));
322
    syntax_expanders.insert(intern("quote_stmt"),
S
Steven Fackler 已提交
323
                       builtin_normal_expander(
324
                            ext::quote::expand_quote_stmt));
325

326
    syntax_expanders.insert(intern("line"),
S
Steven Fackler 已提交
327
                            builtin_normal_expander(
328
                                    ext::source_util::expand_line));
329
    syntax_expanders.insert(intern("col"),
S
Steven Fackler 已提交
330
                            builtin_normal_expander(
331
                                    ext::source_util::expand_col));
332
    syntax_expanders.insert(intern("file"),
S
Steven Fackler 已提交
333
                            builtin_normal_expander(
334
                                    ext::source_util::expand_file));
335
    syntax_expanders.insert(intern("stringify"),
S
Steven Fackler 已提交
336
                            builtin_normal_expander(
337
                                    ext::source_util::expand_stringify));
338
    syntax_expanders.insert(intern("include"),
S
Steven Fackler 已提交
339
                            builtin_normal_expander(
340
                                    ext::source_util::expand_include));
341
    syntax_expanders.insert(intern("include_str"),
S
Steven Fackler 已提交
342
                            builtin_normal_expander(
343
                                    ext::source_util::expand_include_str));
344
    syntax_expanders.insert(intern("include_bin"),
S
Steven Fackler 已提交
345
                            builtin_normal_expander(
346
                                    ext::source_util::expand_include_bin));
347
    syntax_expanders.insert(intern("module_path"),
S
Steven Fackler 已提交
348
                            builtin_normal_expander(
349
                                    ext::source_util::expand_mod));
350
    syntax_expanders.insert(intern("asm"),
S
Steven Fackler 已提交
351
                            builtin_normal_expander(
352
                                    ext::asm::expand_asm));
353
    syntax_expanders.insert(intern("cfg"),
S
Steven Fackler 已提交
354
                            builtin_normal_expander(
355
                                    ext::cfg::expand_cfg));
356
    syntax_expanders.insert(intern("trace_macros"),
S
Steven Fackler 已提交
357
                            builtin_normal_expander(
358
                                    ext::trace_macros::expand_trace_macros));
S
Steven Fackler 已提交
359
    syntax_expanders
360
}
361

362
pub struct MacroCrate {
363
    pub lib: Option<Path>,
364 365
    pub macros: Vec<~str>,
    pub registrar_symbol: Option<~str>,
366 367 368
}

pub trait CrateLoader {
369
    fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate;
370 371
}

372 373 374
// One of these is made during expansion and incrementally updated as we go;
// when a macro expansion occurs, the resulting nodes have the backtrace()
// -> expn_info of their expansion context stored into their span.
375
pub struct ExtCtxt<'a> {
376 377 378 379
    pub parse_sess: &'a parse::ParseSess,
    pub cfg: ast::CrateConfig,
    pub backtrace: Option<@ExpnInfo>,
    pub ecfg: expand::ExpansionConfig<'a>,
380

381 382
    pub mod_path: Vec<ast::Ident> ,
    pub trace_mac: bool,
383
}
N
Niko Matsakis 已提交
384

385
impl<'a> ExtCtxt<'a> {
E
Eduard Burtescu 已提交
386
    pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
387
                   ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
S
Steven Fackler 已提交
388
        ExtCtxt {
389 390
            parse_sess: parse_sess,
            cfg: cfg,
S
Steven Fackler 已提交
391
            backtrace: None,
392
            mod_path: Vec::new(),
393
            ecfg: ecfg,
S
Steven Fackler 已提交
394
            trace_mac: false
395 396 397
        }
    }

S
Steven Fackler 已提交
398
    pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
399 400
        loop {
            match e.node {
A
Alex Crichton 已提交
401
                ast::ExprMac(..) => {
S
Steven Fackler 已提交
402
                    let mut expander = expand::MacroExpander {
S
Steven Fackler 已提交
403
                        extsbox: syntax_expander_table(),
404 405
                        cx: self,
                    };
S
Steven Fackler 已提交
406
                    e = expand::expand_expr(e, &mut expander);
407 408 409 410 411 412
                }
                _ => return e
            }
        }
    }

E
Eduard Burtescu 已提交
413
    pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
E
Eduard Burtescu 已提交
414
    pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
415
    pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
416
    pub fn call_site(&self) -> Span {
S
Steven Fackler 已提交
417
        match self.backtrace {
418
            Some(expn_info) => expn_info.call_site,
419
            None => self.bug("missing top span")
420
        }
421
    }
422
    pub fn print_backtrace(&self) { }
S
Steven Fackler 已提交
423 424
    pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
    pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
425
    pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
426 427 428
    pub fn mod_path(&self) -> Vec<ast::Ident> {
        let mut v = Vec::new();
        v.push(token::str_to_ident(self.ecfg.crate_id.name));
429
        v.extend(self.mod_path.iter().map(|a| *a));
430 431
        return v;
    }
S
Steven Fackler 已提交
432
    pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
433
        match ei {
434
            ExpnInfo {call_site: cs, callee: ref callee} => {
S
Steven Fackler 已提交
435
                self.backtrace =
436
                    Some(@ExpnInfo {
437
                        call_site: Span {lo: cs.lo, hi: cs.hi,
S
Steven Fackler 已提交
438
                                         expn_info: self.backtrace},
439 440
                        callee: (*callee).clone()
                    });
K
Kevin Atkinson 已提交
441
            }
442
        }
443
    }
S
Steven Fackler 已提交
444 445
    pub fn bt_pop(&mut self) {
        match self.backtrace {
446
            Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
447
            _ => self.bug("tried to pop without a push")
448 449
        }
    }
450 451 452 453 454 455 456 457 458 459 460
    /// Emit `msg` attached to `sp`, and stop compilation immediately.
    ///
    /// `span_err` should be strongly prefered where-ever possible:
    /// this should *only* be used when
    /// - continuing has a high risk of flow-on errors (e.g. errors in
    ///   declaring a macro would cause all uses of that macro to
    ///   complain about "undefined macro"), or
    /// - there is literally nothing else that can be done (however,
    ///   in most cases one can construct a dummy expression/item to
    ///   substitute; we never hit resolve/type-checking so the dummy
    ///   value doesn't have to match anything)
461
    pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
462 463 464
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_fatal(sp, msg);
    }
465 466 467 468 469 470

    /// Emit `msg` attached to `sp`, without immediately stopping
    /// compilation.
    ///
    /// Compilation will be stopped in the near future (at the end of
    /// the macro expansion phase).
471
    pub fn span_err(&self, sp: Span, msg: &str) {
472 473 474
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_err(sp, msg);
    }
475
    pub fn span_warn(&self, sp: Span, msg: &str) {
476 477 478
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_warn(sp, msg);
    }
479
    pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
480 481 482
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
    }
483
    pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
484 485 486
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_bug(sp, msg);
    }
S
Steven Fackler 已提交
487 488 489 490
    pub fn span_note(&self, sp: Span, msg: &str) {
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_note(sp, msg);
    }
491
    pub fn bug(&self, msg: &str) -> ! {
492 493 494
        self.print_backtrace();
        self.parse_sess.span_diagnostic.handler().bug(msg);
    }
495
    pub fn trace_macros(&self) -> bool {
S
Steven Fackler 已提交
496
        self.trace_mac
497
    }
S
Steven Fackler 已提交
498 499
    pub fn set_trace_macros(&mut self, x: bool) {
        self.trace_mac = x
500
    }
501
    pub fn ident_of(&self, st: &str) -> ast::Ident {
502
        str_to_ident(st)
503 504 505
    }
}

506 507 508 509
/// Extract a string literal from the macro expanded version of `expr`,
/// emitting `err_msg` if `expr` is not a string literal. This does not stop
/// compilation on error, merely emits a non-fatal error and returns None.
pub fn expr_to_str(cx: &mut ExtCtxt, expr: @ast::Expr, err_msg: &str)
510
                   -> Option<(InternedString, ast::StrStyle)> {
511 512
    // we want to be able to handle e.g. concat("foo", "bar")
    let expr = cx.expand_expr(expr);
513
    match expr.node {
514
        ast::ExprLit(l) => match l.node {
P
Patrick Walton 已提交
515
            ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
516
            _ => cx.span_err(l.span, err_msg)
517
        },
518
        _ => cx.span_err(expr.span, err_msg)
519
    }
520
    None
521 522
}

523 524 525 526 527
/// Non-fatally assert that `tts` is empty. Note that this function
/// returns even when `tts` is non-empty, macros that *need* to stop
/// compilation should call
/// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
/// done as rarely as possible).
528 529 530
pub fn check_zero_tts(cx: &ExtCtxt,
                      sp: Span,
                      tts: &[ast::TokenTree],
531
                      name: &str) {
532
    if tts.len() != 0 {
533
        cx.span_err(sp, format!("{} takes no arguments", name));
534
    }
535 536
}

537 538
/// Extract the string literal from the first token of `tts`. If this
/// is not a string literal, emit an error and return None.
S
Steven Fackler 已提交
539
pub fn get_single_str_from_tts(cx: &ExtCtxt,
540
                               sp: Span,
541
                               tts: &[ast::TokenTree],
542
                               name: &str)
543
                               -> Option<~str> {
544
    if tts.len() != 1 {
545 546 547 548
        cx.span_err(sp, format!("{} takes 1 argument.", name));
    } else {
        match tts[0] {
            ast::TTTok(_, token::LIT_STR(ident))
549
            | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
550
                return Some(token::get_ident(ident).get().to_str())
551
            }
552 553
            _ => cx.span_err(sp, format!("{} requires a string.", name)),
        }
554
    }
555
    None
556
}
557

558 559
/// Extract comma-separated expressions from `tts`. If there is a
/// parsing error, emit a non-fatal error and return None.
560
pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
561
                          sp: Span,
562
                          tts: &[ast::TokenTree]) -> Option<Vec<@ast::Expr> > {
563 564
    let mut p = parse::new_parser_from_tts(cx.parse_sess(),
                                           cx.cfg(),
565 566 567
                                           tts.iter()
                                              .map(|x| (*x).clone())
                                              .collect());
568
    let mut es = Vec::new();
569
    while p.token != token::EOF {
570
        if es.len() != 0 && !p.eat(&token::COMMA) {
571 572
            cx.span_err(sp, "expected token: `,`");
            return None;
573
        }
574
        es.push(cx.expand_expr(p.parse_expr()));
575
    }
576
    Some(es)
577 578
}

J
John Clements 已提交
579 580 581 582
// in order to have some notion of scoping for macros,
// we want to implement the notion of a transformation
// environment.

S
Steven Fackler 已提交
583
// This environment maps Names to SyntaxExtensions.
J
John Clements 已提交
584 585 586 587 588 589 590 591 592 593 594

//impl question: how to implement it? Initially, the
// env will contain only macros, so it might be painful
// to add an empty frame for every context. Let's just
// get it working, first....

// NB! the mutability of the underlying maps means that
// if expansion is out-of-order, a deeper scope may be
// able to refer to a macro that was added to an enclosing
// scope lexically later than the deeper scope.

595
struct MapChainFrame {
S
Steven Fackler 已提交
596
    info: BlockInfo,
597 598 599
    map: HashMap<Name, SyntaxExtension>,
}

S
Steven Fackler 已提交
600
// Only generic to make it easy to test
601
pub struct SyntaxEnv {
602
    chain: Vec<MapChainFrame> ,
S
Steven Fackler 已提交
603
}
J
John Clements 已提交
604

605 606
impl SyntaxEnv {
    pub fn new() -> SyntaxEnv {
607
        let mut map = SyntaxEnv { chain: Vec::new() };
S
Steven Fackler 已提交
608 609
        map.push_frame();
        map
J
John Clements 已提交
610 611
    }

S
Steven Fackler 已提交
612 613 614 615 616
    pub fn push_frame(&mut self) {
        self.chain.push(MapChainFrame {
            info: BlockInfo::new(),
            map: HashMap::new(),
        });
J
John Clements 已提交
617 618
    }

S
Steven Fackler 已提交
619 620 621
    pub fn pop_frame(&mut self) {
        assert!(self.chain.len() > 1, "too many pops on MapChain!");
        self.chain.pop();
622 623
    }

624
    fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
S
Sean Chalmers 已提交
625
        for (i, frame) in self.chain.mut_iter().enumerate().rev() {
S
Steven Fackler 已提交
626 627 628
            if !frame.info.macros_escape || i == 0 {
                return frame
            }
J
John Clements 已提交
629
        }
S
Steven Fackler 已提交
630
        unreachable!()
J
John Clements 已提交
631 632
    }

633
    pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
S
Sean Chalmers 已提交
634
        for frame in self.chain.iter().rev() {
S
Steven Fackler 已提交
635 636 637
            match frame.map.find(k) {
                Some(v) => return Some(v),
                None => {}
J
John Clements 已提交
638 639
            }
        }
S
Steven Fackler 已提交
640
        None
J
John Clements 已提交
641 642
    }

643
    pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
S
Steven Fackler 已提交
644
        self.find_escape_frame().map.insert(k, v);
J
John Clements 已提交
645 646
    }

647
    pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
648 649
        let last_chain_index = self.chain.len() - 1;
        &mut self.chain.get_mut(last_chain_index).info
J
John Clements 已提交
650 651
    }
}