base.rs 25.5 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};
21
use ptr::P;
S
Steven Fackler 已提交
22
use util::small_vector::SmallVector;
23
use ext::mtwt;
24
use fold::Folder;
25

26
use std::collections::HashMap;
27
use std::gc::{Gc, GC};
28
use std::rc::Rc;
29

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

38
pub struct MacroDef {
39
    pub name: String,
40
    pub ext: SyntaxExtension
41
}
42

43 44 45 46
pub trait ItemDecorator {
    fn expand(&self,
              ecx: &mut ExtCtxt,
              sp: Span,
47 48 49
              meta_item: &ast::MetaItem,
              item: &ast::Item,
              push: |P<ast::Item>|);
50 51
}

52
impl ItemDecorator for fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, |P<ast::Item>|) {
53 54 55
    fn expand(&self,
              ecx: &mut ExtCtxt,
              sp: Span,
56 57 58
              meta_item: &ast::MetaItem,
              item: &ast::Item,
              push: |P<ast::Item>|) {
59 60 61
        (*self)(ecx, sp, meta_item, item, push)
    }
}
62

63 64 65 66
pub trait ItemModifier {
    fn expand(&self,
              ecx: &mut ExtCtxt,
              span: Span,
67 68 69
              meta_item: &ast::MetaItem,
              item: P<ast::Item>)
              -> P<ast::Item>;
70 71
}

72
impl ItemModifier for fn(&mut ExtCtxt, Span, &ast::MetaItem, P<ast::Item>) -> P<ast::Item> {
73 74 75
    fn expand(&self,
              ecx: &mut ExtCtxt,
              span: Span,
76 77 78
              meta_item: &ast::MetaItem,
              item: P<ast::Item>)
              -> P<ast::Item> {
79 80 81
        (*self)(ecx, span, meta_item, item)
    }
}
82

83 84
/// Represents a thing that maps token trees to Macro Results
pub trait TTMacroExpander {
85 86 87 88 89
    fn expand<'cx>(&self,
                   ecx: &'cx mut ExtCtxt,
                   span: Span,
                   token_tree: &[ast::TokenTree])
                   -> Box<MacResult+'cx>;
90 91
}

S
Steven Fackler 已提交
92
pub type MacroExpanderFn =
93
    fn<'cx>(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
94

95
impl TTMacroExpander for MacroExpanderFn {
96 97 98 99 100
    fn expand<'cx>(&self,
                   ecx: &'cx mut ExtCtxt,
                   span: Span,
                   token_tree: &[ast::TokenTree])
                   -> Box<MacResult+'cx> {
101
        (*self)(ecx, span, token_tree)
102 103
    }
}
J
John Clements 已提交
104

S
Steven Fackler 已提交
105
pub trait IdentMacroExpander {
106 107 108 109 110 111
    fn expand<'cx>(&self,
                   cx: &'cx mut ExtCtxt,
                   sp: Span,
                   ident: ast::Ident,
                   token_tree: Vec<ast::TokenTree> )
                   -> Box<MacResult+'cx>;
112 113
}

114 115 116 117
pub type IdentMacroExpanderFn =
    fn<'cx>(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;

impl IdentMacroExpander for IdentMacroExpanderFn {
118 119 120 121 122 123
    fn expand<'cx>(&self,
                   cx: &'cx mut ExtCtxt,
                   sp: Span,
                   ident: ast::Ident,
                   token_tree: Vec<ast::TokenTree> )
                   -> Box<MacResult+'cx> {
124
        (*self)(cx, sp, ident, token_tree)
125 126 127
    }
}

128 129 130 131
/// 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 {
132
    /// Attempt to define a new macro.
133 134 135
    // this should go away; the idea that a macro might expand into
    // either a macro definition or an expression, depending on what
    // the context wants, is kind of silly.
136
    fn make_def(&mut self) -> Option<MacroDef> {
137 138 139
        None
    }
    /// Create an expression.
140
    fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
141 142 143
        None
    }
    /// Create zero or more items.
144
    fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
145 146
        None
    }
147 148

    /// Create zero or more methods.
149
    fn make_methods(self: Box<Self>) -> Option<SmallVector<P<ast::Method>>> {
150 151 152
        None
    }

K
Keegan McAllister 已提交
153
    /// Create a pattern.
154
    fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
K
Keegan McAllister 已提交
155 156
        None
    }
157 158 159 160 161

    /// Create a statement.
    ///
    /// By default this attempts to create an expression statement,
    /// returning None if that fails.
162
    fn make_stmt(self: Box<Self>) -> Option<P<ast::Stmt>> {
163
        self.make_expr()
164
            .map(|e| P(codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
165
    }
166
}
J
John Clements 已提交
167

168 169
/// A convenience type for macros that return a single expression.
pub struct MacExpr {
170
    e: P<ast::Expr>
171 172
}
impl MacExpr {
173
    pub fn new(e: P<ast::Expr>) -> Box<MacResult+'static> {
174
        box MacExpr { e: e } as Box<MacResult+'static>
175 176 177
    }
}
impl MacResult for MacExpr {
178
    fn make_expr(self: Box<MacExpr>) -> Option<P<ast::Expr>> {
179 180
        Some(self.e)
    }
181
    fn make_pat(self: Box<MacExpr>) -> Option<P<ast::Pat>> {
182
        match self.e.node {
183
            ast::ExprLit(_) => Some(P(ast::Pat {
184
                id: ast::DUMMY_NODE_ID,
185 186 187
                span: self.e.span,
                node: ast::PatLit(self.e)
            })),
188 189 190
            _ => None
        }
    }
191
}
K
Keegan McAllister 已提交
192 193
/// A convenience type for macros that return a single pattern.
pub struct MacPat {
194
    p: P<ast::Pat>
K
Keegan McAllister 已提交
195 196
}
impl MacPat {
197
    pub fn new(p: P<ast::Pat>) -> Box<MacResult+'static> {
198
        box MacPat { p: p } as Box<MacResult+'static>
K
Keegan McAllister 已提交
199 200 201
    }
}
impl MacResult for MacPat {
202
    fn make_pat(self: Box<MacPat>) -> Option<P<ast::Pat>> {
K
Keegan McAllister 已提交
203 204 205
        Some(self.p)
    }
}
206 207
/// A convenience type for macros that return a single item.
pub struct MacItem {
208
    i: P<ast::Item>
209 210
}
impl MacItem {
211
    pub fn new(i: P<ast::Item>) -> Box<MacResult+'static> {
212
        box MacItem { i: i } as Box<MacResult+'static>
213 214 215
    }
}
impl MacResult for MacItem {
216
    fn make_items(self: Box<MacItem>) -> Option<SmallVector<P<ast::Item>>> {
217 218
        Some(SmallVector::one(self.i))
    }
219 220
    fn make_stmt(self: Box<MacItem>) -> Option<P<ast::Stmt>> {
        Some(P(codemap::respan(
221 222
            self.i.span,
            ast::StmtDecl(
223 224
                P(codemap::respan(self.i.span, ast::DeclItem(self.i))),
                ast::DUMMY_NODE_ID))))
225 226
    }
}
227

228 229 230 231 232
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
pub struct DummyResult {
    expr_only: bool,
    span: Span
233
}
234 235 236 237 238 239

impl DummyResult {
    /// Create a default MacResult that can be anything.
    ///
    /// Use this as a return value after hitting any errors and
    /// calling `span_err`.
240 241
    pub fn any(sp: Span) -> Box<MacResult+'static> {
        box DummyResult { expr_only: false, span: sp } as Box<MacResult+'static>
242 243 244 245 246
    }

    /// Create a default MacResult that can only be an expression.
    ///
    /// Use this for macros that must expand to an expression, so even
247
    /// if an error is encountered internally, the user will receive
248
    /// an error that they also used it in the wrong place.
249 250
    pub fn expr(sp: Span) -> Box<MacResult+'static> {
        box DummyResult { expr_only: true, span: sp } as Box<MacResult+'static>
251 252 253
    }

    /// A plain dummy expression.
254 255
    pub fn raw_expr(sp: Span) -> P<ast::Expr> {
        P(ast::Expr {
256
            id: ast::DUMMY_NODE_ID,
257
            node: ast::ExprLit(P(codemap::respan(sp, ast::LitNil))),
258
            span: sp,
259
        })
260
    }
K
Keegan McAllister 已提交
261 262

    /// A plain dummy pattern.
263 264
    pub fn raw_pat(sp: Span) -> ast::Pat {
        ast::Pat {
K
Keegan McAllister 已提交
265
            id: ast::DUMMY_NODE_ID,
266
            node: ast::PatWild(ast::PatWildSingle),
K
Keegan McAllister 已提交
267 268 269
            span: sp,
        }
    }
270

271
}
272 273

impl MacResult for DummyResult {
274
    fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
275
        Some(DummyResult::raw_expr(self.span))
276
    }
277 278
    fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
        Some(P(DummyResult::raw_pat(self.span)))
K
Keegan McAllister 已提交
279
    }
280
    fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
281 282 283 284 285 286 287
        // this code needs a comment... why not always just return the Some() ?
        if self.expr_only {
            None
        } else {
            Some(SmallVector::zero())
        }
    }
288
    fn make_methods(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Method>>> {
289 290 291 292 293
        if self.expr_only {
            None
        } else {
            Some(SmallVector::zero())
        }
294
    }
295 296 297 298
    fn make_stmt(self: Box<DummyResult>) -> Option<P<ast::Stmt>> {
        Some(P(codemap::respan(self.span,
                               ast::StmtExpr(DummyResult::raw_expr(self.span),
                                             ast::DUMMY_NODE_ID))))
299
    }
300
}
301

302
/// An enum representing the different kinds of syntax extensions.
303
pub enum SyntaxExtension {
304 305 306 307
    /// A syntax extension that is attached to an item and creates new items
    /// based upon it.
    ///
    /// `#[deriving(...)]` is an `ItemDecorator`.
308
    ItemDecorator(Box<ItemDecorator + 'static>),
309

310 311
    /// A syntax extension that is attached to an item and modifies it
    /// in-place.
312
    ItemModifier(Box<ItemModifier + 'static>),
313

314 315 316
    /// A normal, function-like syntax extension.
    ///
    /// `bytes!` is a `NormalTT`.
317
    NormalTT(Box<TTMacroExpander + 'static>, Option<Span>),
J
John Clements 已提交
318

319 320 321
    /// A function-like syntax extension that has an extra ident before
    /// the block.
    ///
A
Alex Crichton 已提交
322
    IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
J
John Clements 已提交
323 324 325 326 327 328 329 330

    /// An ident macro that has two properties:
    /// - it adds a macro definition to the environment, and
    /// - the definition it adds doesn't introduce any new
    ///   identifiers.
    ///
    /// `macro_rules!` is a LetSyntaxTT
    LetSyntaxTT(Box<IdentMacroExpander + 'static>, Option<Span>),
331
}
332

333 334
pub type NamedSyntaxExtension = (Name, SyntaxExtension);

335
pub struct BlockInfo {
336
    /// Should macros escape from this scope?
337
    pub macros_escape: bool,
338
    /// What are the pending renames?
339
    pub pending_renames: mtwt::RenameList,
S
Steven Fackler 已提交
340 341 342 343 344 345
}

impl BlockInfo {
    pub fn new() -> BlockInfo {
        BlockInfo {
            macros_escape: false,
346
            pending_renames: Vec::new(),
S
Steven Fackler 已提交
347 348
        }
    }
J
John Clements 已提交
349
}
350

351 352
/// The base map of methods for expanding syntax extension
/// AST nodes into full ASTs
353
fn initial_syntax_expander_table() -> SyntaxEnv {
J
John Clements 已提交
354
    // utility function to simplify creating NormalTT syntax extensions
S
Steven Fackler 已提交
355
    fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
356
        NormalTT(box f, None)
357
    }
K
Kiet Tran 已提交
358

359
    let mut syntax_expanders = SyntaxEnv::new();
360
    syntax_expanders.insert(intern("macro_rules"),
361
                            LetSyntaxTT(box ext::tt::macro_rules::add_new_extension, None));
362
    syntax_expanders.insert(intern("fmt"),
S
Steven Fackler 已提交
363
                            builtin_normal_expander(
364
                                ext::fmt::expand_syntax_ext));
365
    syntax_expanders.insert(intern("format_args"),
S
Steven Fackler 已提交
366
                            builtin_normal_expander(
367 368 369 370
                                ext::format::expand_format_args));
    syntax_expanders.insert(intern("format_args_method"),
                            builtin_normal_expander(
                                ext::format::expand_format_args_method));
371
    syntax_expanders.insert(intern("env"),
S
Steven Fackler 已提交
372
                            builtin_normal_expander(
373
                                    ext::env::expand_env));
374
    syntax_expanders.insert(intern("option_env"),
S
Steven Fackler 已提交
375
                            builtin_normal_expander(
376
                                    ext::env::expand_option_env));
377
    syntax_expanders.insert(intern("bytes"),
S
Steven Fackler 已提交
378
                            builtin_normal_expander(
379
                                    ext::bytes::expand_syntax_ext));
380
    syntax_expanders.insert(intern("concat_idents"),
S
Steven Fackler 已提交
381
                            builtin_normal_expander(
382
                                    ext::concat_idents::expand_syntax_ext));
383
    syntax_expanders.insert(intern("concat"),
S
Steven Fackler 已提交
384
                            builtin_normal_expander(
385
                                    ext::concat::expand_syntax_ext));
386
    syntax_expanders.insert(intern("log_syntax"),
S
Steven Fackler 已提交
387
                            builtin_normal_expander(
388
                                    ext::log_syntax::expand_syntax_ext));
389
    syntax_expanders.insert(intern("deriving"),
390
                            ItemDecorator(box ext::deriving::expand_meta_deriving));
391 392

    // Quasi-quoting expanders
393
    syntax_expanders.insert(intern("quote_tokens"),
S
Steven Fackler 已提交
394
                       builtin_normal_expander(
395
                            ext::quote::expand_quote_tokens));
396
    syntax_expanders.insert(intern("quote_expr"),
S
Steven Fackler 已提交
397
                       builtin_normal_expander(
398
                            ext::quote::expand_quote_expr));
399
    syntax_expanders.insert(intern("quote_ty"),
S
Steven Fackler 已提交
400
                       builtin_normal_expander(
401
                            ext::quote::expand_quote_ty));
B
Ben Gamari 已提交
402 403 404
    syntax_expanders.insert(intern("quote_method"),
                       builtin_normal_expander(
                            ext::quote::expand_quote_method));
405
    syntax_expanders.insert(intern("quote_item"),
S
Steven Fackler 已提交
406
                       builtin_normal_expander(
407
                            ext::quote::expand_quote_item));
408
    syntax_expanders.insert(intern("quote_pat"),
S
Steven Fackler 已提交
409
                       builtin_normal_expander(
410
                            ext::quote::expand_quote_pat));
411 412 413
    syntax_expanders.insert(intern("quote_arm"),
                       builtin_normal_expander(
                            ext::quote::expand_quote_arm));
414
    syntax_expanders.insert(intern("quote_stmt"),
S
Steven Fackler 已提交
415
                       builtin_normal_expander(
416
                            ext::quote::expand_quote_stmt));
417

418
    syntax_expanders.insert(intern("line"),
S
Steven Fackler 已提交
419
                            builtin_normal_expander(
420
                                    ext::source_util::expand_line));
421
    syntax_expanders.insert(intern("col"),
S
Steven Fackler 已提交
422
                            builtin_normal_expander(
423
                                    ext::source_util::expand_col));
424
    syntax_expanders.insert(intern("file"),
S
Steven Fackler 已提交
425
                            builtin_normal_expander(
426
                                    ext::source_util::expand_file));
427
    syntax_expanders.insert(intern("stringify"),
S
Steven Fackler 已提交
428
                            builtin_normal_expander(
429
                                    ext::source_util::expand_stringify));
430
    syntax_expanders.insert(intern("include"),
S
Steven Fackler 已提交
431
                            builtin_normal_expander(
432
                                    ext::source_util::expand_include));
433
    syntax_expanders.insert(intern("include_str"),
S
Steven Fackler 已提交
434
                            builtin_normal_expander(
435
                                    ext::source_util::expand_include_str));
436
    syntax_expanders.insert(intern("include_bin"),
S
Steven Fackler 已提交
437
                            builtin_normal_expander(
438
                                    ext::source_util::expand_include_bin));
439
    syntax_expanders.insert(intern("module_path"),
S
Steven Fackler 已提交
440
                            builtin_normal_expander(
441
                                    ext::source_util::expand_mod));
442
    syntax_expanders.insert(intern("asm"),
S
Steven Fackler 已提交
443
                            builtin_normal_expander(
444
                                    ext::asm::expand_asm));
445
    syntax_expanders.insert(intern("cfg"),
S
Steven Fackler 已提交
446
                            builtin_normal_expander(
447
                                    ext::cfg::expand_cfg));
448
    syntax_expanders.insert(intern("trace_macros"),
S
Steven Fackler 已提交
449
                            builtin_normal_expander(
450
                                    ext::trace_macros::expand_trace_macros));
S
Steven Fackler 已提交
451
    syntax_expanders
452
}
453

454 455 456
/// 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.
457
pub struct ExtCtxt<'a> {
458 459
    pub parse_sess: &'a parse::ParseSess,
    pub cfg: ast::CrateConfig,
460
    pub backtrace: Option<Gc<ExpnInfo>>,
461
    pub ecfg: expand::ExpansionConfig,
462

463 464
    pub mod_path: Vec<ast::Ident> ,
    pub trace_mac: bool,
465
    pub exported_macros: Vec<P<ast::Item>>,
466

467
    pub syntax_env: SyntaxEnv,
468
}
N
Niko Matsakis 已提交
469

470
impl<'a> ExtCtxt<'a> {
E
Eduard Burtescu 已提交
471
    pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
472
                   ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
S
Steven Fackler 已提交
473
        ExtCtxt {
474 475
            parse_sess: parse_sess,
            cfg: cfg,
S
Steven Fackler 已提交
476
            backtrace: None,
477
            mod_path: Vec::new(),
478
            ecfg: ecfg,
479 480
            trace_mac: false,
            exported_macros: Vec::new(),
481
            syntax_env: initial_syntax_expander_table(),
482 483 484
        }
    }

485
    #[deprecated = "Replaced with `expander().fold_expr()`"]
486
    pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
487 488 489 490 491 492
        self.expander().fold_expr(e)
    }

    /// Returns a `Folder` for deeply expanding all macros in a AST node.
    pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
        expand::MacroExpander { cx: self }
493 494
    }

495 496 497 498 499
    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 已提交
500
    pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
E
Eduard Burtescu 已提交
501
    pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
502
    pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
503
    pub fn call_site(&self) -> Span {
S
Steven Fackler 已提交
504
        match self.backtrace {
505
            Some(expn_info) => expn_info.call_site,
506
            None => self.bug("missing top span")
507
        }
508
    }
509
    pub fn print_backtrace(&self) { }
510
    pub fn backtrace(&self) -> Option<Gc<ExpnInfo>> { self.backtrace }
S
Steven Fackler 已提交
511
    pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
512
    pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
513 514
    pub fn mod_path(&self) -> Vec<ast::Ident> {
        let mut v = Vec::new();
515
        v.push(token::str_to_ident(self.ecfg.crate_name.as_slice()));
516
        v.extend(self.mod_path.iter().map(|a| *a));
517 518
        return v;
    }
S
Steven Fackler 已提交
519
    pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
520
        match ei {
521
            ExpnInfo {call_site: cs, callee: ref callee} => {
S
Steven Fackler 已提交
522
                self.backtrace =
523
                    Some(box(GC) ExpnInfo {
524
                        call_site: Span {lo: cs.lo, hi: cs.hi,
525
                                         expn_info: self.backtrace.clone()},
526 527
                        callee: (*callee).clone()
                    });
K
Kevin Atkinson 已提交
528
            }
529
        }
530
    }
S
Steven Fackler 已提交
531 532
    pub fn bt_pop(&mut self) {
        match self.backtrace {
533
            Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
534
            _ => self.bug("tried to pop without a push")
535 536
        }
    }
537 538
    /// Emit `msg` attached to `sp`, and stop compilation immediately.
    ///
J
Joseph Crail 已提交
539
    /// `span_err` should be strongly preferred where-ever possible:
540 541 542 543 544 545 546 547
    /// 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)
548
    pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
549 550 551
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_fatal(sp, msg);
    }
552 553 554 555 556 557

    /// 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).
558
    pub fn span_err(&self, sp: Span, msg: &str) {
559 560 561
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_err(sp, msg);
    }
562
    pub fn span_warn(&self, sp: Span, msg: &str) {
563 564 565
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_warn(sp, msg);
    }
566
    pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
567 568 569
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
    }
570
    pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
571 572 573
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_bug(sp, msg);
    }
S
Steven Fackler 已提交
574 575 576 577
    pub fn span_note(&self, sp: Span, msg: &str) {
        self.print_backtrace();
        self.parse_sess.span_diagnostic.span_note(sp, msg);
    }
578
    pub fn bug(&self, msg: &str) -> ! {
579 580 581
        self.print_backtrace();
        self.parse_sess.span_diagnostic.handler().bug(msg);
    }
582
    pub fn trace_macros(&self) -> bool {
S
Steven Fackler 已提交
583
        self.trace_mac
584
    }
S
Steven Fackler 已提交
585 586
    pub fn set_trace_macros(&mut self, x: bool) {
        self.trace_mac = x
587
    }
588
    pub fn ident_of(&self, st: &str) -> ast::Ident {
589
        str_to_ident(st)
590
    }
C
Corey Richardson 已提交
591 592 593
    pub fn name_of(&self, st: &str) -> ast::Name {
        token::intern(st)
    }
594 595
}

596 597 598
/// 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.
599 600
pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
                      -> Option<(InternedString, ast::StrStyle)> {
601
    // we want to be able to handle e.g. concat("foo", "bar")
602
    let expr = cx.expander().fold_expr(expr);
603
    match expr.node {
604
        ast::ExprLit(ref l) => match l.node {
P
Patrick Walton 已提交
605
            ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
606
            _ => cx.span_err(l.span, err_msg)
607
        },
608
        _ => cx.span_err(expr.span, err_msg)
609
    }
610
    None
611 612
}

613 614 615 616 617
/// 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).
618 619 620
pub fn check_zero_tts(cx: &ExtCtxt,
                      sp: Span,
                      tts: &[ast::TokenTree],
621
                      name: &str) {
622
    if tts.len() != 0 {
623
        cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
624
    }
625 626
}

627 628
/// 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 已提交
629
pub fn get_single_str_from_tts(cx: &ExtCtxt,
630
                               sp: Span,
631
                               tts: &[ast::TokenTree],
632
                               name: &str)
633
                               -> Option<String> {
634
    if tts.len() != 1 {
635
        cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
636 637
    } else {
        match tts[0] {
638 639 640
            ast::TTTok(_, token::LIT_STR(ident)) => return Some(parse::str_lit(ident.as_str())),
            ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
                return Some(parse::raw_str_lit(ident.as_str()))
641
            }
642 643 644 645
            _ => {
                cx.span_err(sp,
                            format!("{} requires a string.", name).as_slice())
            }
646
        }
647
    }
648
    None
649
}
650

651 652
/// Extract comma-separated expressions from `tts`. If there is a
/// parsing error, emit a non-fatal error and return None.
653
pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
654
                          sp: Span,
655
                          tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
656
    let mut p = cx.new_parser_from_tts(tts);
657
    let mut es = Vec::new();
658
    while p.token != token::EOF {
659
        es.push(cx.expander().fold_expr(p.parse_expr()));
660 661 662 663
        if p.eat(&token::COMMA) {
            continue;
        }
        if p.token != token::EOF {
664 665
            cx.span_err(sp, "expected token: `,`");
            return None;
666
        }
667
    }
668
    Some(es)
669 670
}

671 672 673
/// In order to have some notion of scoping for macros,
/// we want to implement the notion of a transformation
/// environment.
674
///
675
/// This environment maps Names to SyntaxExtensions.
676 677 678
pub struct SyntaxEnv {
    chain: Vec<MapChainFrame> ,
}
J
John Clements 已提交
679

680
// impl question: how to implement it? Initially, the
J
John Clements 已提交
681 682 683 684 685 686 687 688 689
// 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.

690
struct MapChainFrame {
S
Steven Fackler 已提交
691
    info: BlockInfo,
692
    map: HashMap<Name, Rc<SyntaxExtension>>,
S
Steven Fackler 已提交
693
}
J
John Clements 已提交
694

695
impl SyntaxEnv {
696
    fn new() -> SyntaxEnv {
697
        let mut map = SyntaxEnv { chain: Vec::new() };
S
Steven Fackler 已提交
698 699
        map.push_frame();
        map
J
John Clements 已提交
700 701
    }

S
Steven Fackler 已提交
702 703 704 705 706
    pub fn push_frame(&mut self) {
        self.chain.push(MapChainFrame {
            info: BlockInfo::new(),
            map: HashMap::new(),
        });
J
John Clements 已提交
707 708
    }

S
Steven Fackler 已提交
709 710 711
    pub fn pop_frame(&mut self) {
        assert!(self.chain.len() > 1, "too many pops on MapChain!");
        self.chain.pop();
712 713
    }

714
    fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
A
Aaron Turon 已提交
715
        for (i, frame) in self.chain.iter_mut().enumerate().rev() {
S
Steven Fackler 已提交
716 717 718
            if !frame.info.macros_escape || i == 0 {
                return frame
            }
J
John Clements 已提交
719
        }
S
Steven Fackler 已提交
720
        unreachable!()
J
John Clements 已提交
721 722
    }

723
    pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
S
Sean Chalmers 已提交
724
        for frame in self.chain.iter().rev() {
S
Steven Fackler 已提交
725
            match frame.map.find(k) {
726
                Some(v) => return Some(v.clone()),
S
Steven Fackler 已提交
727
                None => {}
J
John Clements 已提交
728 729
            }
        }
S
Steven Fackler 已提交
730
        None
J
John Clements 已提交
731 732
    }

733
    pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
734
        self.find_escape_frame().map.insert(k, Rc::new(v));
J
John Clements 已提交
735 736
    }

737
    pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
738 739
        let last_chain_index = self.chain.len() - 1;
        &mut self.chain.get_mut(last_chain_index).info
J
John Clements 已提交
740 741
    }
}