1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use codemap::{CodeMap, Span, ExpnInfo};
19 use parse::token::{InternedString, intern, str_to_ident};
20 use util::small_vector::SmallVector;
22 use std::collections::HashMap;
23 use std::gc::{Gc, GC};
25 // new-style macro! tt code:
27 // MacResult, NormalTT, IdentTT
29 // also note that ast::Mac used to have a bunch of extraneous cases and
30 // is now probably a redundant AST node, can be merged with
35 pub ext: SyntaxExtension
38 pub type ItemDecorator =
39 fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|);
41 pub type ItemModifier =
42 fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item>;
44 pub struct BasicMacroExpander {
45 pub expander: MacroExpanderFn,
46 pub span: Option<Span>
49 pub trait MacroExpander {
53 token_tree: &[ast::TokenTree])
57 pub type MacroExpanderFn =
58 fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
61 impl MacroExpander for BasicMacroExpander {
65 token_tree: &[ast::TokenTree])
67 (self.expander)(ecx, span, token_tree)
71 pub struct BasicIdentMacroExpander {
72 pub expander: IdentMacroExpanderFn,
73 pub span: Option<Span>
76 pub trait IdentMacroExpander {
81 token_tree: Vec<ast::TokenTree> )
85 impl IdentMacroExpander for BasicIdentMacroExpander {
90 token_tree: Vec<ast::TokenTree> )
92 (self.expander)(cx, sp, ident, token_tree)
96 pub type IdentMacroExpanderFn =
97 fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult>;
99 /// The result of a macro expansion. The return values of the various
100 /// methods are spliced into the AST at the callsite of the macro (or
101 /// just into the compiler's internal macro table, for `make_def`).
102 pub trait MacResult {
103 /// Define a new macro.
104 fn make_def(&self) -> Option<MacroDef> {
107 /// Create an expression.
108 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
111 /// Create zero or more items.
112 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
115 /// Create a pattern.
116 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
120 /// Create a statement.
122 /// By default this attempts to create an expression statement,
123 /// returning None if that fails.
124 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
126 .map(|e| box(GC) codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
130 /// A convenience type for macros that return a single expression.
135 pub fn new(e: Gc<ast::Expr>) -> Box<MacResult> {
136 box MacExpr { e: e } as Box<MacResult>
139 impl MacResult for MacExpr {
140 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
144 /// A convenience type for macros that return a single pattern.
149 pub fn new(p: Gc<ast::Pat>) -> Box<MacResult> {
150 box MacPat { p: p } as Box<MacResult>
153 impl MacResult for MacPat {
154 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
158 /// A convenience type for macros that return a single item.
163 pub fn new(i: Gc<ast::Item>) -> Box<MacResult> {
164 box MacItem { i: i } as Box<MacResult>
167 impl MacResult for MacItem {
168 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
169 Some(SmallVector::one(self.i))
171 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
172 Some(box(GC) codemap::respan(
175 box(GC) codemap::respan(self.i.span, ast::DeclItem(self.i)),
176 ast::DUMMY_NODE_ID)))
180 /// Fill-in macro expansion result, to allow compilation to continue
181 /// after hitting errors.
182 pub struct DummyResult {
188 /// Create a default MacResult that can be anything.
190 /// Use this as a return value after hitting any errors and
191 /// calling `span_err`.
192 pub fn any(sp: Span) -> Box<MacResult> {
193 box DummyResult { expr_only: false, span: sp } as Box<MacResult>
196 /// Create a default MacResult that can only be an expression.
198 /// Use this for macros that must expand to an expression, so even
199 /// if an error is encountered internally, the user will receive
200 /// an error that they also used it in the wrong place.
201 pub fn expr(sp: Span) -> Box<MacResult> {
202 box DummyResult { expr_only: true, span: sp } as Box<MacResult>
205 /// A plain dummy expression.
206 pub fn raw_expr(sp: Span) -> Gc<ast::Expr> {
208 id: ast::DUMMY_NODE_ID,
209 node: ast::ExprLit(box(GC) codemap::respan(sp, ast::LitNil)),
214 /// A plain dummy pattern.
215 pub fn raw_pat(sp: Span) -> Gc<ast::Pat> {
217 id: ast::DUMMY_NODE_ID,
224 impl MacResult for DummyResult {
225 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
226 Some(DummyResult::raw_expr(self.span))
228 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
229 Some(DummyResult::raw_pat(self.span))
231 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
235 Some(SmallVector::zero())
238 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
239 Some(box(GC) codemap::respan(self.span,
240 ast::StmtExpr(DummyResult::raw_expr(self.span),
241 ast::DUMMY_NODE_ID)))
245 /// An enum representing the different kinds of syntax extensions.
246 pub enum SyntaxExtension {
247 /// A syntax extension that is attached to an item and creates new items
250 /// `#[deriving(...)]` is an `ItemDecorator`.
251 ItemDecorator(ItemDecorator),
253 /// A syntax extension that is attached to an item and modifies it
255 ItemModifier(ItemModifier),
257 /// A normal, function-like syntax extension.
259 /// `bytes!` is a `NormalTT`.
260 NormalTT(Box<MacroExpander + 'static>, Option<Span>),
262 /// A function-like syntax extension that has an extra ident before
265 /// `macro_rules!` is an `IdentTT`.
266 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
269 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
271 pub struct BlockInfo {
272 // should macros escape from this scope?
273 pub macros_escape: bool,
274 // what are the pending renames?
275 pub pending_renames: RenameList,
279 pub fn new() -> BlockInfo {
281 macros_escape: false,
282 pending_renames: Vec::new(),
287 // a list of ident->name renamings
288 pub type RenameList = Vec<(ast::Ident, Name)>;
290 // The base map of methods for expanding syntax extension
291 // AST nodes into full ASTs
292 pub fn syntax_expander_table() -> SyntaxEnv {
293 // utility function to simplify creating NormalTT syntax extensions
294 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
295 NormalTT(box BasicMacroExpander {
302 let mut syntax_expanders = SyntaxEnv::new();
303 syntax_expanders.insert(intern("macro_rules"),
304 IdentTT(box BasicIdentMacroExpander {
305 expander: ext::tt::macro_rules::add_new_extension,
309 syntax_expanders.insert(intern("fmt"),
310 builtin_normal_expander(
311 ext::fmt::expand_syntax_ext));
312 syntax_expanders.insert(intern("format_args"),
313 builtin_normal_expander(
314 ext::format::expand_format_args));
315 syntax_expanders.insert(intern("format_args_method"),
316 builtin_normal_expander(
317 ext::format::expand_format_args_method));
318 syntax_expanders.insert(intern("env"),
319 builtin_normal_expander(
320 ext::env::expand_env));
321 syntax_expanders.insert(intern("option_env"),
322 builtin_normal_expander(
323 ext::env::expand_option_env));
324 syntax_expanders.insert(intern("bytes"),
325 builtin_normal_expander(
326 ext::bytes::expand_syntax_ext));
327 syntax_expanders.insert(intern("concat_idents"),
328 builtin_normal_expander(
329 ext::concat_idents::expand_syntax_ext));
330 syntax_expanders.insert(intern("concat"),
331 builtin_normal_expander(
332 ext::concat::expand_syntax_ext));
333 syntax_expanders.insert(intern("log_syntax"),
334 builtin_normal_expander(
335 ext::log_syntax::expand_syntax_ext));
336 syntax_expanders.insert(intern("deriving"),
337 ItemDecorator(ext::deriving::expand_meta_deriving));
339 // Quasi-quoting expanders
340 syntax_expanders.insert(intern("quote_tokens"),
341 builtin_normal_expander(
342 ext::quote::expand_quote_tokens));
343 syntax_expanders.insert(intern("quote_expr"),
344 builtin_normal_expander(
345 ext::quote::expand_quote_expr));
346 syntax_expanders.insert(intern("quote_ty"),
347 builtin_normal_expander(
348 ext::quote::expand_quote_ty));
349 syntax_expanders.insert(intern("quote_item"),
350 builtin_normal_expander(
351 ext::quote::expand_quote_item));
352 syntax_expanders.insert(intern("quote_pat"),
353 builtin_normal_expander(
354 ext::quote::expand_quote_pat));
355 syntax_expanders.insert(intern("quote_stmt"),
356 builtin_normal_expander(
357 ext::quote::expand_quote_stmt));
359 syntax_expanders.insert(intern("line"),
360 builtin_normal_expander(
361 ext::source_util::expand_line));
362 syntax_expanders.insert(intern("col"),
363 builtin_normal_expander(
364 ext::source_util::expand_col));
365 syntax_expanders.insert(intern("file"),
366 builtin_normal_expander(
367 ext::source_util::expand_file));
368 syntax_expanders.insert(intern("stringify"),
369 builtin_normal_expander(
370 ext::source_util::expand_stringify));
371 syntax_expanders.insert(intern("include"),
372 builtin_normal_expander(
373 ext::source_util::expand_include));
374 syntax_expanders.insert(intern("include_str"),
375 builtin_normal_expander(
376 ext::source_util::expand_include_str));
377 syntax_expanders.insert(intern("include_bin"),
378 builtin_normal_expander(
379 ext::source_util::expand_include_bin));
380 syntax_expanders.insert(intern("module_path"),
381 builtin_normal_expander(
382 ext::source_util::expand_mod));
383 syntax_expanders.insert(intern("asm"),
384 builtin_normal_expander(
385 ext::asm::expand_asm));
386 syntax_expanders.insert(intern("cfg"),
387 builtin_normal_expander(
388 ext::cfg::expand_cfg));
389 syntax_expanders.insert(intern("trace_macros"),
390 builtin_normal_expander(
391 ext::trace_macros::expand_trace_macros));
395 // One of these is made during expansion and incrementally updated as we go;
396 // when a macro expansion occurs, the resulting nodes have the backtrace()
397 // -> expn_info of their expansion context stored into their span.
398 pub struct ExtCtxt<'a> {
399 pub parse_sess: &'a parse::ParseSess,
400 pub cfg: ast::CrateConfig,
401 pub backtrace: Option<Gc<ExpnInfo>>,
402 pub ecfg: expand::ExpansionConfig,
404 pub mod_path: Vec<ast::Ident> ,
408 impl<'a> ExtCtxt<'a> {
409 pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
410 ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
412 parse_sess: parse_sess,
415 mod_path: Vec::new(),
421 pub fn expand_expr(&mut self, mut e: Gc<ast::Expr>) -> Gc<ast::Expr> {
424 ast::ExprMac(..) => {
425 let mut expander = expand::MacroExpander {
426 extsbox: syntax_expander_table(),
429 e = expand::expand_expr(e, &mut expander);
436 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
437 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
438 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
439 pub fn call_site(&self) -> Span {
440 match self.backtrace {
441 Some(expn_info) => expn_info.call_site,
442 None => self.bug("missing top span")
445 pub fn print_backtrace(&self) { }
446 pub fn backtrace(&self) -> Option<Gc<ExpnInfo>> { self.backtrace }
447 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
448 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
449 pub fn mod_path(&self) -> Vec<ast::Ident> {
450 let mut v = Vec::new();
451 v.push(token::str_to_ident(self.ecfg.crate_id.name.as_slice()));
452 v.extend(self.mod_path.iter().map(|a| *a));
455 pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
457 ExpnInfo {call_site: cs, callee: ref callee} => {
459 Some(box(GC) ExpnInfo {
460 call_site: Span {lo: cs.lo, hi: cs.hi,
461 expn_info: self.backtrace.clone()},
462 callee: (*callee).clone()
467 pub fn bt_pop(&mut self) {
468 match self.backtrace {
469 Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
470 _ => self.bug("tried to pop without a push")
473 /// Emit `msg` attached to `sp`, and stop compilation immediately.
475 /// `span_err` should be strongly prefered where-ever possible:
476 /// this should *only* be used when
477 /// - continuing has a high risk of flow-on errors (e.g. errors in
478 /// declaring a macro would cause all uses of that macro to
479 /// complain about "undefined macro"), or
480 /// - there is literally nothing else that can be done (however,
481 /// in most cases one can construct a dummy expression/item to
482 /// substitute; we never hit resolve/type-checking so the dummy
483 /// value doesn't have to match anything)
484 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
485 self.print_backtrace();
486 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
489 /// Emit `msg` attached to `sp`, without immediately stopping
492 /// Compilation will be stopped in the near future (at the end of
493 /// the macro expansion phase).
494 pub fn span_err(&self, sp: Span, msg: &str) {
495 self.print_backtrace();
496 self.parse_sess.span_diagnostic.span_err(sp, msg);
498 pub fn span_warn(&self, sp: Span, msg: &str) {
499 self.print_backtrace();
500 self.parse_sess.span_diagnostic.span_warn(sp, msg);
502 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
503 self.print_backtrace();
504 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
506 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
507 self.print_backtrace();
508 self.parse_sess.span_diagnostic.span_bug(sp, msg);
510 pub fn span_note(&self, sp: Span, msg: &str) {
511 self.print_backtrace();
512 self.parse_sess.span_diagnostic.span_note(sp, msg);
514 pub fn bug(&self, msg: &str) -> ! {
515 self.print_backtrace();
516 self.parse_sess.span_diagnostic.handler().bug(msg);
518 pub fn trace_macros(&self) -> bool {
521 pub fn set_trace_macros(&mut self, x: bool) {
524 pub fn ident_of(&self, st: &str) -> ast::Ident {
529 /// Extract a string literal from the macro expanded version of `expr`,
530 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
531 /// compilation on error, merely emits a non-fatal error and returns None.
532 pub fn expr_to_str(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str)
533 -> Option<(InternedString, ast::StrStyle)> {
534 // we want to be able to handle e.g. concat("foo", "bar")
535 let expr = cx.expand_expr(expr);
537 ast::ExprLit(l) => match l.node {
538 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
539 _ => cx.span_err(l.span, err_msg)
541 _ => cx.span_err(expr.span, err_msg)
546 /// Non-fatally assert that `tts` is empty. Note that this function
547 /// returns even when `tts` is non-empty, macros that *need* to stop
548 /// compilation should call
549 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
550 /// done as rarely as possible).
551 pub fn check_zero_tts(cx: &ExtCtxt,
553 tts: &[ast::TokenTree],
556 cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
560 /// Extract the string literal from the first token of `tts`. If this
561 /// is not a string literal, emit an error and return None.
562 pub fn get_single_str_from_tts(cx: &ExtCtxt,
564 tts: &[ast::TokenTree],
568 cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
571 ast::TTTok(_, token::LIT_STR(ident))
572 | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
573 return Some(token::get_ident(ident).get().to_string())
577 format!("{} requires a string.", name).as_slice())
584 /// Extract comma-separated expressions from `tts`. If there is a
585 /// parsing error, emit a non-fatal error and return None.
586 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
588 tts: &[ast::TokenTree]) -> Option<Vec<Gc<ast::Expr>>> {
589 let mut p = parse::new_parser_from_tts(cx.parse_sess(),
592 .map(|x| (*x).clone())
594 let mut es = Vec::new();
595 while p.token != token::EOF {
596 if es.len() != 0 && !p.eat(&token::COMMA) {
597 cx.span_err(sp, "expected token: `,`");
600 es.push(cx.expand_expr(p.parse_expr()));
605 // in order to have some notion of scoping for macros,
606 // we want to implement the notion of a transformation
609 // This environment maps Names to SyntaxExtensions.
611 //impl question: how to implement it? Initially, the
612 // env will contain only macros, so it might be painful
613 // to add an empty frame for every context. Let's just
614 // get it working, first....
616 // NB! the mutability of the underlying maps means that
617 // if expansion is out-of-order, a deeper scope may be
618 // able to refer to a macro that was added to an enclosing
619 // scope lexically later than the deeper scope.
621 struct MapChainFrame {
623 map: HashMap<Name, SyntaxExtension>,
626 // Only generic to make it easy to test
627 pub struct SyntaxEnv {
628 chain: Vec<MapChainFrame> ,
632 pub fn new() -> SyntaxEnv {
633 let mut map = SyntaxEnv { chain: Vec::new() };
638 pub fn push_frame(&mut self) {
639 self.chain.push(MapChainFrame {
640 info: BlockInfo::new(),
645 pub fn pop_frame(&mut self) {
646 assert!(self.chain.len() > 1, "too many pops on MapChain!");
650 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
651 for (i, frame) in self.chain.mut_iter().enumerate().rev() {
652 if !frame.info.macros_escape || i == 0 {
659 pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
660 for frame in self.chain.iter().rev() {
661 match frame.map.find(k) {
662 Some(v) => return Some(v),
669 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
670 self.find_escape_frame().map.insert(k, v);
673 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
674 let last_chain_index = self.chain.len() - 1;
675 &mut self.chain.get_mut(last_chain_index).info