base.rs 22.8 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 std::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
    pub name: String,
34
    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
              -> Box<MacResult>;
54 55
}

S
Steven Fackler 已提交
56
pub type MacroExpanderFn =
57
    fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
58
       -> Box<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
              -> Box<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
              -> Box<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
              -> Box<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>) -> Box<MacResult>;
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/// 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
    }
K
Keegan McAllister 已提交
114 115 116 117
    /// Create a pattern.
    fn make_pat(&self) -> Option<@ast::Pat> {
        None
    }
118 119 120 121 122 123 124 125 126

    /// 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)))
    }
127
}
J
John Clements 已提交
128

129 130 131 132 133
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
    e: @ast::Expr
}
impl MacExpr {
134 135
    pub fn new(e: @ast::Expr) -> Box<MacResult> {
        box MacExpr { e: e } as Box<MacResult>
136 137 138 139 140 141 142
    }
}
impl MacResult for MacExpr {
    fn make_expr(&self) -> Option<@ast::Expr> {
        Some(self.e)
    }
}
K
Keegan McAllister 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156
/// A convenience type for macros that return a single pattern.
pub struct MacPat {
    p: @ast::Pat
}
impl MacPat {
    pub fn new(p: @ast::Pat) -> Box<MacResult> {
        box MacPat { p: p } as Box<MacResult>
    }
}
impl MacResult for MacPat {
    fn make_pat(&self) -> Option<@ast::Pat> {
        Some(self.p)
    }
}
157 158 159 160 161
/// A convenience type for macros that return a single item.
pub struct MacItem {
    i: @ast::Item
}
impl MacItem {
162 163
    pub fn new(i: @ast::Item) -> Box<MacResult> {
        box MacItem { i: i } as Box<MacResult>
164 165 166 167 168 169 170 171 172 173 174 175 176 177
    }
}
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)))
    }
}
178

179 180 181 182 183
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
    expr_only: bool,
    span: Span
184
}
185 186 187 188 189 190

impl DummyResult {
    /// Create a default MacResult that can be anything.
    ///
    /// Use this as a return value after hitting any errors and
    /// calling `span_err`.
191 192
    pub fn any(sp: Span) -> Box<MacResult> {
        box DummyResult { expr_only: false, span: sp } as Box<MacResult>
193 194 195 196 197 198 199
    }

    /// 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.
200 201
    pub fn expr(sp: Span) -> Box<MacResult> {
        box DummyResult { expr_only: true, span: sp } as Box<MacResult>
202 203 204 205
    }

    /// A plain dummy expression.
    pub fn raw_expr(sp: Span) -> @ast::Expr {
206 207
        @ast::Expr {
            id: ast::DUMMY_NODE_ID,
208 209
            node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
            span: sp,
210 211
        }
    }
K
Keegan McAllister 已提交
212 213 214 215 216 217 218 219 220

    /// A plain dummy pattern.
    pub fn raw_pat(sp: Span) -> @ast::Pat {
        @ast::Pat {
            id: ast::DUMMY_NODE_ID,
            node: ast::PatWild,
            span: sp,
        }
    }
221
}
222 223 224 225

impl MacResult for DummyResult {
    fn make_expr(&self) -> Option<@ast::Expr> {
        Some(DummyResult::raw_expr(self.span))
226
    }
K
Keegan McAllister 已提交
227 228 229
    fn make_pat(&self) -> Option<@ast::Pat> {
        Some(DummyResult::raw_pat(self.span))
    }
230 231 232 233 234 235
    fn make_items(&self) -> Option<SmallVector<@ast::Item>> {
        if self.expr_only {
            None
        } else {
            Some(SmallVector::zero())
        }
236
    }
237 238 239 240
    fn make_stmt(&self) -> Option<@ast::Stmt> {
        Some(@codemap::respan(self.span,
                              ast::StmtExpr(DummyResult::raw_expr(self.span),
                                            ast::DUMMY_NODE_ID)))
241
    }
242
}
243

244
/// An enum representing the different kinds of syntax extensions.
245
pub enum SyntaxExtension {
246 247 248 249
    /// A syntax extension that is attached to an item and creates new items
    /// based upon it.
    ///
    /// `#[deriving(...)]` is an `ItemDecorator`.
250
    ItemDecorator(ItemDecorator),
251

252 253 254
    /// A syntax extension that is attached to an item and modifies it
    /// in-place.
    ItemModifier(ItemModifier),
255

256 257 258
    /// A normal, function-like syntax extension.
    ///
    /// `bytes!` is a `NormalTT`.
259
    NormalTT(Box<MacroExpander:'static>, Option<Span>),
J
John Clements 已提交
260

261 262 263 264
    /// A function-like syntax extension that has an extra ident before
    /// the block.
    ///
    /// `macro_rules!` is an `IdentTT`.
265
    IdentTT(Box<IdentMacroExpander:'static>, Option<Span>),
266
}
267

268 269
pub type NamedSyntaxExtension = (Name, SyntaxExtension);

270 271
pub struct BlockInfo {
    // should macros escape from this scope?
272
    pub macros_escape: bool,
273
    // what are the pending renames?
274
    pub pending_renames: RenameList,
S
Steven Fackler 已提交
275 276 277 278 279 280
}

impl BlockInfo {
    pub fn new() -> BlockInfo {
        BlockInfo {
            macros_escape: false,
281
            pending_renames: Vec::new(),
S
Steven Fackler 已提交
282 283
        }
    }
J
John Clements 已提交
284
}
285

286
// a list of ident->name renamings
287
pub type RenameList = Vec<(ast::Ident, Name)>;
288

J
John Clements 已提交
289
// The base map of methods for expanding syntax extension
290
// AST nodes into full ASTs
J
John Clements 已提交
291
pub fn syntax_expander_table() -> SyntaxEnv {
J
John Clements 已提交
292
    // utility function to simplify creating NormalTT syntax extensions
S
Steven Fackler 已提交
293
    fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
294
        NormalTT(box BasicMacroExpander {
S
Steven Fackler 已提交
295 296 297 298
                expander: f,
                span: None,
            },
            None)
299
    }
K
Kiet Tran 已提交
300

301
    let mut syntax_expanders = SyntaxEnv::new();
302
    syntax_expanders.insert(intern("macro_rules"),
303
                            IdentTT(box BasicIdentMacroExpander {
S
Steven Fackler 已提交
304
                                expander: ext::tt::macro_rules::add_new_extension,
305
                                span: None,
306
                            },
S
Steven Fackler 已提交
307
                            None));
308
    syntax_expanders.insert(intern("fmt"),
S
Steven Fackler 已提交
309
                            builtin_normal_expander(
310
                                ext::fmt::expand_syntax_ext));
311
    syntax_expanders.insert(intern("format_args"),
S
Steven Fackler 已提交
312
                            builtin_normal_expander(
313 314 315 316
                                ext::format::expand_format_args));
    syntax_expanders.insert(intern("format_args_method"),
                            builtin_normal_expander(
                                ext::format::expand_format_args_method));
317
    syntax_expanders.insert(intern("env"),
S
Steven Fackler 已提交
318
                            builtin_normal_expander(
319
                                    ext::env::expand_env));
320
    syntax_expanders.insert(intern("option_env"),
S
Steven Fackler 已提交
321
                            builtin_normal_expander(
322
                                    ext::env::expand_option_env));
323
    syntax_expanders.insert(intern("bytes"),
S
Steven Fackler 已提交
324
                            builtin_normal_expander(
325
                                    ext::bytes::expand_syntax_ext));
326
    syntax_expanders.insert(intern("concat_idents"),
S
Steven Fackler 已提交
327
                            builtin_normal_expander(
328
                                    ext::concat_idents::expand_syntax_ext));
329
    syntax_expanders.insert(intern("concat"),
S
Steven Fackler 已提交
330
                            builtin_normal_expander(
331
                                    ext::concat::expand_syntax_ext));
332
    syntax_expanders.insert(intern("log_syntax"),
S
Steven Fackler 已提交
333
                            builtin_normal_expander(
334
                                    ext::log_syntax::expand_syntax_ext));
335
    syntax_expanders.insert(intern("deriving"),
S
Steven Fackler 已提交
336
                            ItemDecorator(ext::deriving::expand_meta_deriving));
337 338

    // Quasi-quoting expanders
339
    syntax_expanders.insert(intern("quote_tokens"),
S
Steven Fackler 已提交
340
                       builtin_normal_expander(
341
                            ext::quote::expand_quote_tokens));
342
    syntax_expanders.insert(intern("quote_expr"),
S
Steven Fackler 已提交
343
                       builtin_normal_expander(
344
                            ext::quote::expand_quote_expr));
345
    syntax_expanders.insert(intern("quote_ty"),
S
Steven Fackler 已提交
346
                       builtin_normal_expander(
347
                            ext::quote::expand_quote_ty));
348
    syntax_expanders.insert(intern("quote_item"),
S
Steven Fackler 已提交
349
                       builtin_normal_expander(
350
                            ext::quote::expand_quote_item));
351
    syntax_expanders.insert(intern("quote_pat"),
S
Steven Fackler 已提交
352
                       builtin_normal_expander(
353
                            ext::quote::expand_quote_pat));
354
    syntax_expanders.insert(intern("quote_stmt"),
S
Steven Fackler 已提交
355
                       builtin_normal_expander(
356
                            ext::quote::expand_quote_stmt));
357

358
    syntax_expanders.insert(intern("line"),
S
Steven Fackler 已提交
359
                            builtin_normal_expander(
360
                                    ext::source_util::expand_line));
361
    syntax_expanders.insert(intern("col"),
S
Steven Fackler 已提交
362
                            builtin_normal_expander(
363
                                    ext::source_util::expand_col));
364
    syntax_expanders.insert(intern("file"),
S
Steven Fackler 已提交
365
                            builtin_normal_expander(
366
                                    ext::source_util::expand_file));
367
    syntax_expanders.insert(intern("stringify"),
S
Steven Fackler 已提交
368
                            builtin_normal_expander(
369
                                    ext::source_util::expand_stringify));
370
    syntax_expanders.insert(intern("include"),
S
Steven Fackler 已提交
371
                            builtin_normal_expander(
372
                                    ext::source_util::expand_include));
373
    syntax_expanders.insert(intern("include_str"),
S
Steven Fackler 已提交
374
                            builtin_normal_expander(
375
                                    ext::source_util::expand_include_str));
376
    syntax_expanders.insert(intern("include_bin"),
S
Steven Fackler 已提交
377
                            builtin_normal_expander(
378
                                    ext::source_util::expand_include_bin));
379
    syntax_expanders.insert(intern("module_path"),
S
Steven Fackler 已提交
380
                            builtin_normal_expander(
381
                                    ext::source_util::expand_mod));
382
    syntax_expanders.insert(intern("asm"),
S
Steven Fackler 已提交
383
                            builtin_normal_expander(
384
                                    ext::asm::expand_asm));
385
    syntax_expanders.insert(intern("cfg"),
S
Steven Fackler 已提交
386
                            builtin_normal_expander(
387
                                    ext::cfg::expand_cfg));
388
    syntax_expanders.insert(intern("trace_macros"),
S
Steven Fackler 已提交
389
                            builtin_normal_expander(
390
                                    ext::trace_macros::expand_trace_macros));
S
Steven Fackler 已提交
391
    syntax_expanders
392
}
393 394 395 396

// 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.
397
pub struct ExtCtxt<'a> {
398 399 400
    pub parse_sess: &'a parse::ParseSess,
    pub cfg: ast::CrateConfig,
    pub backtrace: Option<@ExpnInfo>,
401
    pub ecfg: expand::ExpansionConfig,
402

403 404
    pub mod_path: Vec<ast::Ident> ,
    pub trace_mac: bool,
405
}
N
Niko Matsakis 已提交
406

407
impl<'a> ExtCtxt<'a> {
E
Eduard Burtescu 已提交
408
    pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
409
                   ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
S
Steven Fackler 已提交
410
        ExtCtxt {
411 412
            parse_sess: parse_sess,
            cfg: cfg,
S
Steven Fackler 已提交
413
            backtrace: None,
414
            mod_path: Vec::new(),
415
            ecfg: ecfg,
S
Steven Fackler 已提交
416
            trace_mac: false
417 418 419
        }
    }

S
Steven Fackler 已提交
420
    pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
421 422
        loop {
            match e.node {
A
Alex Crichton 已提交
423
                ast::ExprMac(..) => {
S
Steven Fackler 已提交
424
                    let mut expander = expand::MacroExpander {
S
Steven Fackler 已提交
425
                        extsbox: syntax_expander_table(),
426 427
                        cx: self,
                    };
S
Steven Fackler 已提交
428
                    e = expand::expand_expr(e, &mut expander);
429 430 431 432 433 434
                }
                _ => return e
            }
        }
    }

E
Eduard Burtescu 已提交
435
    pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
E
Eduard Burtescu 已提交
436
    pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
437
    pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
438
    pub fn call_site(&self) -> Span {
S
Steven Fackler 已提交
439
        match self.backtrace {
440
            Some(expn_info) => expn_info.call_site,
441
            None => self.bug("missing top span")
442
        }
443
    }
444
    pub fn print_backtrace(&self) { }
S
Steven Fackler 已提交
445 446
    pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
    pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
447
    pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
448 449
    pub fn mod_path(&self) -> Vec<ast::Ident> {
        let mut v = Vec::new();
450
        v.push(token::str_to_ident(self.ecfg.crate_id.name.as_slice()));
451
        v.extend(self.mod_path.iter().map(|a| *a));
452 453
        return v;
    }
S
Steven Fackler 已提交
454
    pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
455
        match ei {
456
            ExpnInfo {call_site: cs, callee: ref callee} => {
S
Steven Fackler 已提交
457
                self.backtrace =
458
                    Some(@ExpnInfo {
459
                        call_site: Span {lo: cs.lo, hi: cs.hi,
S
Steven Fackler 已提交
460
                                         expn_info: self.backtrace},
461 462
                        callee: (*callee).clone()
                    });
K
Kevin Atkinson 已提交
463
            }
464
        }
465
    }
S
Steven Fackler 已提交
466 467
    pub fn bt_pop(&mut self) {
        match self.backtrace {
468
            Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
469
            _ => self.bug("tried to pop without a push")
470 471
        }
    }
472 473 474 475 476 477 478 479 480 481 482
    /// 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)
483
    pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
484 485 486
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_fatal(sp, msg);
    }
487 488 489 490 491 492

    /// 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).
493
    pub fn span_err(&self, sp: Span, msg: &str) {
494 495 496
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_err(sp, msg);
    }
497
    pub fn span_warn(&self, sp: Span, msg: &str) {
498 499 500
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_warn(sp, msg);
    }
501
    pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
502 503 504
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
    }
505
    pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
506 507 508
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_bug(sp, msg);
    }
S
Steven Fackler 已提交
509 510 511 512
    pub fn span_note(&self, sp: Span, msg: &str) {
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_note(sp, msg);
    }
513
    pub fn bug(&self, msg: &str) -> ! {
514 515 516
        self.print_backtrace();
        self.parse_sess.span_diagnostic.handler().bug(msg);
    }
517
    pub fn trace_macros(&self) -> bool {
S
Steven Fackler 已提交
518
        self.trace_mac
519
    }
S
Steven Fackler 已提交
520 521
    pub fn set_trace_macros(&mut self, x: bool) {
        self.trace_mac = x
522
    }
523
    pub fn ident_of(&self, st: &str) -> ast::Ident {
524
        str_to_ident(st)
525 526 527
    }
}

528 529 530 531
/// 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)
532
                   -> Option<(InternedString, ast::StrStyle)> {
533 534
    // we want to be able to handle e.g. concat("foo", "bar")
    let expr = cx.expand_expr(expr);
535
    match expr.node {
536
        ast::ExprLit(l) => match l.node {
P
Patrick Walton 已提交
537
            ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
538
            _ => cx.span_err(l.span, err_msg)
539
        },
540
        _ => cx.span_err(expr.span, err_msg)
541
    }
542
    None
543 544
}

545 546 547 548 549
/// 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).
550 551 552
pub fn check_zero_tts(cx: &ExtCtxt,
                      sp: Span,
                      tts: &[ast::TokenTree],
553
                      name: &str) {
554
    if tts.len() != 0 {
555
        cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
556
    }
557 558
}

559 560
/// 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 已提交
561
pub fn get_single_str_from_tts(cx: &ExtCtxt,
562
                               sp: Span,
563
                               tts: &[ast::TokenTree],
564
                               name: &str)
565
                               -> Option<String> {
566
    if tts.len() != 1 {
567
        cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
568 569 570
    } else {
        match tts[0] {
            ast::TTTok(_, token::LIT_STR(ident))
571
            | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
572
                return Some(token::get_ident(ident).get().to_string())
573
            }
574 575 576 577
            _ => {
                cx.span_err(sp,
                            format!("{} requires a string.", name).as_slice())
            }
578
        }
579
    }
580
    None
581
}
582

583 584
/// Extract comma-separated expressions from `tts`. If there is a
/// parsing error, emit a non-fatal error and return None.
585
pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
586
                          sp: Span,
587
                          tts: &[ast::TokenTree]) -> Option<Vec<@ast::Expr> > {
588 589
    let mut p = parse::new_parser_from_tts(cx.parse_sess(),
                                           cx.cfg(),
590 591 592
                                           tts.iter()
                                              .map(|x| (*x).clone())
                                              .collect());
593
    let mut es = Vec::new();
594
    while p.token != token::EOF {
595
        if es.len() != 0 && !p.eat(&token::COMMA) {
596 597
            cx.span_err(sp, "expected token: `,`");
            return None;
598
        }
599
        es.push(cx.expand_expr(p.parse_expr()));
600
    }
601
    Some(es)
602 603
}

J
John Clements 已提交
604 605 606 607
// in order to have some notion of scoping for macros,
// we want to implement the notion of a transformation
// environment.

S
Steven Fackler 已提交
608
// This environment maps Names to SyntaxExtensions.
J
John Clements 已提交
609 610 611 612 613 614 615 616 617 618 619

//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.

620
struct MapChainFrame {
S
Steven Fackler 已提交
621
    info: BlockInfo,
622 623 624
    map: HashMap<Name, SyntaxExtension>,
}

S
Steven Fackler 已提交
625
// Only generic to make it easy to test
626
pub struct SyntaxEnv {
627
    chain: Vec<MapChainFrame> ,
S
Steven Fackler 已提交
628
}
J
John Clements 已提交
629

630 631
impl SyntaxEnv {
    pub fn new() -> SyntaxEnv {
632
        let mut map = SyntaxEnv { chain: Vec::new() };
S
Steven Fackler 已提交
633 634
        map.push_frame();
        map
J
John Clements 已提交
635 636
    }

S
Steven Fackler 已提交
637 638 639 640 641
    pub fn push_frame(&mut self) {
        self.chain.push(MapChainFrame {
            info: BlockInfo::new(),
            map: HashMap::new(),
        });
J
John Clements 已提交
642 643
    }

S
Steven Fackler 已提交
644 645 646
    pub fn pop_frame(&mut self) {
        assert!(self.chain.len() > 1, "too many pops on MapChain!");
        self.chain.pop();
647 648
    }

649
    fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
S
Sean Chalmers 已提交
650
        for (i, frame) in self.chain.mut_iter().enumerate().rev() {
S
Steven Fackler 已提交
651 652 653
            if !frame.info.macros_escape || i == 0 {
                return frame
            }
J
John Clements 已提交
654
        }
S
Steven Fackler 已提交
655
        unreachable!()
J
John Clements 已提交
656 657
    }

658
    pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
S
Sean Chalmers 已提交
659
        for frame in self.chain.iter().rev() {
S
Steven Fackler 已提交
660 661 662
            match frame.map.find(k) {
                Some(v) => return Some(v),
                None => {}
J
John Clements 已提交
663 664
            }
        }
S
Steven Fackler 已提交
665
        None
J
John Clements 已提交
666 667
    }

668
    pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
S
Steven Fackler 已提交
669
        self.find_escape_frame().map.insert(k, v);
J
John Clements 已提交
670 671
    }

672
    pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
673 674
        let last_chain_index = self.chain.len() - 1;
        &mut self.chain.get_mut(last_chain_index).info
J
John Clements 已提交
675 676
    }
}