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

23
use std::collections::HashMap;
24
use std::gc::{Gc, GC};
25

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

34
pub struct MacroDef {
35
    pub name: String,
36
    pub ext: SyntaxExtension
37
}
38

39
pub type ItemDecorator =
40
    fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|);
41

42
pub type ItemModifier =
43
    fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item>;
44

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

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

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

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

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

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

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

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

100 101 102 103 104 105 106 107 108
/// 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.
109
    fn make_expr(&self) -> Option<Gc<ast::Expr>> {
110 111 112
        None
    }
    /// Create zero or more items.
113
    fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
114 115
        None
    }
K
Keegan McAllister 已提交
116
    /// Create a pattern.
117
    fn make_pat(&self) -> Option<Gc<ast::Pat>> {
K
Keegan McAllister 已提交
118 119
        None
    }
120 121 122 123 124

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

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

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

impl DummyResult {
    /// Create a default MacResult that can be anything.
    ///
    /// Use this as a return value after hitting any errors and
    /// calling `span_err`.
193 194
    pub fn any(sp: Span) -> Box<MacResult> {
        box DummyResult { expr_only: false, span: sp } as Box<MacResult>
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
200
    /// if an error is encountered internally, the user will receive
201
    /// an error that they also used it in the wrong place.
202 203
    pub fn expr(sp: Span) -> Box<MacResult> {
        box DummyResult { expr_only: true, span: sp } as Box<MacResult>
204 205 206
    }

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

    /// A plain dummy pattern.
216 217
    pub fn raw_pat(sp: Span) -> Gc<ast::Pat> {
        box(GC) ast::Pat {
K
Keegan McAllister 已提交
218 219 220 221 222
            id: ast::DUMMY_NODE_ID,
            node: ast::PatWild,
            span: sp,
        }
    }
223
}
224 225

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

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

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

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

263 264 265 266
    /// A function-like syntax extension that has an extra ident before
    /// the block.
    ///
    /// `macro_rules!` is an `IdentTT`.
A
Alex Crichton 已提交
267
    IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
268
}
269

270 271
pub type NamedSyntaxExtension = (Name, SyntaxExtension);

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

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

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

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

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

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

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

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

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

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

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

437 438 439 440 441
    pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
        -> parser::Parser<'a> {
        parse::tts_to_parser(self.parse_sess, Vec::from_slice(tts), self.cfg())
    }

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

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

535 536 537
/// 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.
538
pub fn expr_to_str(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str)
539
                   -> Option<(InternedString, ast::StrStyle)> {
540 541
    // we want to be able to handle e.g. concat("foo", "bar")
    let expr = cx.expand_expr(expr);
542
    match expr.node {
543
        ast::ExprLit(l) => match l.node {
P
Patrick Walton 已提交
544
            ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
545
            _ => cx.span_err(l.span, err_msg)
546
        },
547
        _ => cx.span_err(expr.span, err_msg)
548
    }
549
    None
550 551
}

552 553 554 555 556
/// 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).
557 558 559
pub fn check_zero_tts(cx: &ExtCtxt,
                      sp: Span,
                      tts: &[ast::TokenTree],
560
                      name: &str) {
561
    if tts.len() != 0 {
562
        cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
563
    }
564 565
}

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

590 591
/// Extract comma-separated expressions from `tts`. If there is a
/// parsing error, emit a non-fatal error and return None.
592
pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
593
                          sp: Span,
594
                          tts: &[ast::TokenTree]) -> Option<Vec<Gc<ast::Expr>>> {
595
    let mut p = cx.new_parser_from_tts(tts);
596
    let mut es = Vec::new();
597
    while p.token != token::EOF {
598 599 600 601 602
        es.push(cx.expand_expr(p.parse_expr()));
        if p.eat(&token::COMMA) {
            continue;
        }
        if p.token != token::EOF {
603 604
            cx.span_err(sp, "expected token: `,`");
            return None;
605
        }
606
    }
607
    Some(es)
608 609
}

J
John Clements 已提交
610 611 612 613
// in order to have some notion of scoping for macros,
// we want to implement the notion of a transformation
// environment.

S
Steven Fackler 已提交
614
// This environment maps Names to SyntaxExtensions.
J
John Clements 已提交
615 616 617 618 619 620 621 622 623 624 625

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

626
struct MapChainFrame {
S
Steven Fackler 已提交
627
    info: BlockInfo,
628 629 630
    map: HashMap<Name, SyntaxExtension>,
}

S
Steven Fackler 已提交
631
// Only generic to make it easy to test
632
pub struct SyntaxEnv {
633
    chain: Vec<MapChainFrame> ,
S
Steven Fackler 已提交
634
}
J
John Clements 已提交
635

636 637
impl SyntaxEnv {
    pub fn new() -> SyntaxEnv {
638
        let mut map = SyntaxEnv { chain: Vec::new() };
S
Steven Fackler 已提交
639 640
        map.push_frame();
        map
J
John Clements 已提交
641 642
    }

S
Steven Fackler 已提交
643 644 645 646 647
    pub fn push_frame(&mut self) {
        self.chain.push(MapChainFrame {
            info: BlockInfo::new(),
            map: HashMap::new(),
        });
J
John Clements 已提交
648 649
    }

S
Steven Fackler 已提交
650 651 652
    pub fn pop_frame(&mut self) {
        assert!(self.chain.len() > 1, "too many pops on MapChain!");
        self.chain.pop();
653 654
    }

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

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

674
    pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
S
Steven Fackler 已提交
675
        self.find_escape_frame().map.insert(k, v);
J
John Clements 已提交
676 677
    }

678
    pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
679 680
        let last_chain_index = self.chain.len() - 1;
        &mut self.chain.get_mut(last_chain_index).info
J
John Clements 已提交
681 682
    }
}