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};
20 use parse::token::{InternedString, intern, str_to_ident};
21 use util::small_vector::SmallVector;
25 use std::collections::HashMap;
26 use std::gc::{Gc, GC};
29 // new-style macro! tt code:
31 // MacResult, NormalTT, IdentTT
33 // also note that ast::Mac used to have a bunch of extraneous cases and
34 // is now probably a redundant AST node, can be merged with
39 pub ext: SyntaxExtension
42 pub type ItemDecorator =
43 fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|);
45 pub type ItemModifier =
46 fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item>;
48 pub struct BasicMacroExpander {
49 pub expander: MacroExpanderFn,
50 pub span: Option<Span>
53 /// Represents a thing that maps token trees to Macro Results
54 pub trait TTMacroExpander {
58 token_tree: &[ast::TokenTree])
62 pub type MacroExpanderFn =
63 fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
66 impl TTMacroExpander for BasicMacroExpander {
70 token_tree: &[ast::TokenTree])
72 (self.expander)(ecx, span, token_tree)
76 pub struct BasicIdentMacroExpander {
77 pub expander: IdentMacroExpanderFn,
78 pub span: Option<Span>
81 pub trait IdentMacroExpander {
86 token_tree: Vec<ast::TokenTree> )
90 impl IdentMacroExpander for BasicIdentMacroExpander {
95 token_tree: Vec<ast::TokenTree> )
97 (self.expander)(cx, sp, ident, token_tree)
101 pub type IdentMacroExpanderFn =
102 fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult>;
104 /// The result of a macro expansion. The return values of the various
105 /// methods are spliced into the AST at the callsite of the macro (or
106 /// just into the compiler's internal macro table, for `make_def`).
107 pub trait MacResult {
108 /// Define a new macro.
109 // this should go away; the idea that a macro might expand into
110 // either a macro definition or an expression, depending on what
111 // the context wants, is kind of silly.
112 fn make_def(&self) -> Option<MacroDef> {
115 /// Create an expression.
116 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
119 /// Create zero or more items.
120 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
124 /// Create zero or more methods.
125 fn make_methods(&self) -> Option<SmallVector<Gc<ast::Method>>> {
129 /// Create a pattern.
130 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
134 /// Create a statement.
136 /// By default this attempts to create an expression statement,
137 /// returning None if that fails.
138 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
140 .map(|e| box(GC) codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
144 /// A convenience type for macros that return a single expression.
149 pub fn new(e: Gc<ast::Expr>) -> Box<MacResult> {
150 box MacExpr { e: e } as Box<MacResult>
153 impl MacResult for MacExpr {
154 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
158 /// A convenience type for macros that return a single pattern.
163 pub fn new(p: Gc<ast::Pat>) -> Box<MacResult> {
164 box MacPat { p: p } as Box<MacResult>
167 impl MacResult for MacPat {
168 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
172 /// A convenience type for macros that return a single item.
177 pub fn new(i: Gc<ast::Item>) -> Box<MacResult> {
178 box MacItem { i: i } as Box<MacResult>
181 impl MacResult for MacItem {
182 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
183 Some(SmallVector::one(self.i))
185 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
186 Some(box(GC) codemap::respan(
189 box(GC) codemap::respan(self.i.span, ast::DeclItem(self.i)),
190 ast::DUMMY_NODE_ID)))
194 /// Fill-in macro expansion result, to allow compilation to continue
195 /// after hitting errors.
196 pub struct DummyResult {
202 /// Create a default MacResult that can be anything.
204 /// Use this as a return value after hitting any errors and
205 /// calling `span_err`.
206 pub fn any(sp: Span) -> Box<MacResult> {
207 box DummyResult { expr_only: false, span: sp } as Box<MacResult>
210 /// Create a default MacResult that can only be an expression.
212 /// Use this for macros that must expand to an expression, so even
213 /// if an error is encountered internally, the user will receive
214 /// an error that they also used it in the wrong place.
215 pub fn expr(sp: Span) -> Box<MacResult> {
216 box DummyResult { expr_only: true, span: sp } as Box<MacResult>
219 /// A plain dummy expression.
220 pub fn raw_expr(sp: Span) -> Gc<ast::Expr> {
222 id: ast::DUMMY_NODE_ID,
223 node: ast::ExprLit(box(GC) codemap::respan(sp, ast::LitNil)),
228 /// A plain dummy pattern.
229 pub fn raw_pat(sp: Span) -> Gc<ast::Pat> {
231 id: ast::DUMMY_NODE_ID,
239 impl MacResult for DummyResult {
240 fn make_expr(&self) -> Option<Gc<ast::Expr>> {
241 Some(DummyResult::raw_expr(self.span))
243 fn make_pat(&self) -> Option<Gc<ast::Pat>> {
244 Some(DummyResult::raw_pat(self.span))
246 fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
247 // this code needs a comment... why not always just return the Some() ?
251 Some(SmallVector::zero())
254 fn make_methods(&self) -> Option<SmallVector<Gc<ast::Method>>> {
258 Some(SmallVector::zero())
261 fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
262 Some(box(GC) codemap::respan(self.span,
263 ast::StmtExpr(DummyResult::raw_expr(self.span),
264 ast::DUMMY_NODE_ID)))
268 /// An enum representing the different kinds of syntax extensions.
269 pub enum SyntaxExtension {
270 /// A syntax extension that is attached to an item and creates new items
273 /// `#[deriving(...)]` is an `ItemDecorator`.
274 ItemDecorator(ItemDecorator),
276 /// A syntax extension that is attached to an item and modifies it
278 ItemModifier(ItemModifier),
280 /// A normal, function-like syntax extension.
282 /// `bytes!` is a `NormalTT`.
283 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>),
285 /// A function-like syntax extension that has an extra ident before
288 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
290 /// An ident macro that has two properties:
291 /// - it adds a macro definition to the environment, and
292 /// - the definition it adds doesn't introduce any new
295 /// `macro_rules!` is a LetSyntaxTT
296 LetSyntaxTT(Box<IdentMacroExpander + 'static>, Option<Span>),
299 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
301 pub struct BlockInfo {
302 /// Should macros escape from this scope?
303 pub macros_escape: bool,
304 /// What are the pending renames?
305 pub pending_renames: mtwt::RenameList,
309 pub fn new() -> BlockInfo {
311 macros_escape: false,
312 pending_renames: Vec::new(),
317 /// The base map of methods for expanding syntax extension
318 /// AST nodes into full ASTs
319 fn initial_syntax_expander_table() -> SyntaxEnv {
320 // utility function to simplify creating NormalTT syntax extensions
321 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
322 NormalTT(box BasicMacroExpander {
329 let mut syntax_expanders = SyntaxEnv::new();
330 syntax_expanders.insert(intern("macro_rules"),
331 LetSyntaxTT(box BasicIdentMacroExpander {
332 expander: ext::tt::macro_rules::add_new_extension,
336 syntax_expanders.insert(intern("fmt"),
337 builtin_normal_expander(
338 ext::fmt::expand_syntax_ext));
339 syntax_expanders.insert(intern("format_args"),
340 builtin_normal_expander(
341 ext::format::expand_format_args));
342 syntax_expanders.insert(intern("format_args_method"),
343 builtin_normal_expander(
344 ext::format::expand_format_args_method));
345 syntax_expanders.insert(intern("env"),
346 builtin_normal_expander(
347 ext::env::expand_env));
348 syntax_expanders.insert(intern("option_env"),
349 builtin_normal_expander(
350 ext::env::expand_option_env));
351 syntax_expanders.insert(intern("bytes"),
352 builtin_normal_expander(
353 ext::bytes::expand_syntax_ext));
354 syntax_expanders.insert(intern("concat_idents"),
355 builtin_normal_expander(
356 ext::concat_idents::expand_syntax_ext));
357 syntax_expanders.insert(intern("concat"),
358 builtin_normal_expander(
359 ext::concat::expand_syntax_ext));
360 syntax_expanders.insert(intern("log_syntax"),
361 builtin_normal_expander(
362 ext::log_syntax::expand_syntax_ext));
363 syntax_expanders.insert(intern("deriving"),
364 ItemDecorator(ext::deriving::expand_meta_deriving));
366 // Quasi-quoting expanders
367 syntax_expanders.insert(intern("quote_tokens"),
368 builtin_normal_expander(
369 ext::quote::expand_quote_tokens));
370 syntax_expanders.insert(intern("quote_expr"),
371 builtin_normal_expander(
372 ext::quote::expand_quote_expr));
373 syntax_expanders.insert(intern("quote_ty"),
374 builtin_normal_expander(
375 ext::quote::expand_quote_ty));
376 syntax_expanders.insert(intern("quote_method"),
377 builtin_normal_expander(
378 ext::quote::expand_quote_method));
379 syntax_expanders.insert(intern("quote_item"),
380 builtin_normal_expander(
381 ext::quote::expand_quote_item));
382 syntax_expanders.insert(intern("quote_pat"),
383 builtin_normal_expander(
384 ext::quote::expand_quote_pat));
385 syntax_expanders.insert(intern("quote_stmt"),
386 builtin_normal_expander(
387 ext::quote::expand_quote_stmt));
389 syntax_expanders.insert(intern("line"),
390 builtin_normal_expander(
391 ext::source_util::expand_line));
392 syntax_expanders.insert(intern("col"),
393 builtin_normal_expander(
394 ext::source_util::expand_col));
395 syntax_expanders.insert(intern("file"),
396 builtin_normal_expander(
397 ext::source_util::expand_file));
398 syntax_expanders.insert(intern("stringify"),
399 builtin_normal_expander(
400 ext::source_util::expand_stringify));
401 syntax_expanders.insert(intern("include"),
402 builtin_normal_expander(
403 ext::source_util::expand_include));
404 syntax_expanders.insert(intern("include_str"),
405 builtin_normal_expander(
406 ext::source_util::expand_include_str));
407 syntax_expanders.insert(intern("include_bin"),
408 builtin_normal_expander(
409 ext::source_util::expand_include_bin));
410 syntax_expanders.insert(intern("module_path"),
411 builtin_normal_expander(
412 ext::source_util::expand_mod));
413 syntax_expanders.insert(intern("asm"),
414 builtin_normal_expander(
415 ext::asm::expand_asm));
416 syntax_expanders.insert(intern("cfg"),
417 builtin_normal_expander(
418 ext::cfg::expand_cfg));
419 syntax_expanders.insert(intern("trace_macros"),
420 builtin_normal_expander(
421 ext::trace_macros::expand_trace_macros));
425 /// One of these is made during expansion and incrementally updated as we go;
426 /// when a macro expansion occurs, the resulting nodes have the backtrace()
427 /// -> expn_info of their expansion context stored into their span.
428 pub struct ExtCtxt<'a> {
429 pub parse_sess: &'a parse::ParseSess,
430 pub cfg: ast::CrateConfig,
431 pub backtrace: Option<Gc<ExpnInfo>>,
432 pub ecfg: expand::ExpansionConfig,
434 pub mod_path: Vec<ast::Ident> ,
436 pub exported_macros: Vec<Gc<ast::Item>>,
438 pub syntax_env: SyntaxEnv,
441 impl<'a> ExtCtxt<'a> {
442 pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
443 ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
445 parse_sess: parse_sess,
448 mod_path: Vec::new(),
451 exported_macros: Vec::new(),
452 syntax_env: initial_syntax_expander_table(),
456 #[deprecated = "Replaced with `expander().fold_expr()`"]
457 pub fn expand_expr(&mut self, e: Gc<ast::Expr>) -> Gc<ast::Expr> {
458 self.expander().fold_expr(e)
461 /// Returns a `Folder` for deeply expanding all macros in a AST node.
462 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
463 expand::MacroExpander { cx: self }
466 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
467 -> parser::Parser<'a> {
468 parse::tts_to_parser(self.parse_sess, Vec::from_slice(tts), self.cfg())
471 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
472 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
473 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
474 pub fn call_site(&self) -> Span {
475 match self.backtrace {
476 Some(expn_info) => expn_info.call_site,
477 None => self.bug("missing top span")
480 pub fn print_backtrace(&self) { }
481 pub fn backtrace(&self) -> Option<Gc<ExpnInfo>> { self.backtrace }
482 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
483 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
484 pub fn mod_path(&self) -> Vec<ast::Ident> {
485 let mut v = Vec::new();
486 v.push(token::str_to_ident(self.ecfg.crate_name.as_slice()));
487 v.extend(self.mod_path.iter().map(|a| *a));
490 pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
492 ExpnInfo {call_site: cs, callee: ref callee} => {
494 Some(box(GC) ExpnInfo {
495 call_site: Span {lo: cs.lo, hi: cs.hi,
496 expn_info: self.backtrace.clone()},
497 callee: (*callee).clone()
502 pub fn bt_pop(&mut self) {
503 match self.backtrace {
504 Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
505 _ => self.bug("tried to pop without a push")
508 /// Emit `msg` attached to `sp`, and stop compilation immediately.
510 /// `span_err` should be strongly preferred where-ever possible:
511 /// this should *only* be used when
512 /// - continuing has a high risk of flow-on errors (e.g. errors in
513 /// declaring a macro would cause all uses of that macro to
514 /// complain about "undefined macro"), or
515 /// - there is literally nothing else that can be done (however,
516 /// in most cases one can construct a dummy expression/item to
517 /// substitute; we never hit resolve/type-checking so the dummy
518 /// value doesn't have to match anything)
519 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
520 self.print_backtrace();
521 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
524 /// Emit `msg` attached to `sp`, without immediately stopping
527 /// Compilation will be stopped in the near future (at the end of
528 /// the macro expansion phase).
529 pub fn span_err(&self, sp: Span, msg: &str) {
530 self.print_backtrace();
531 self.parse_sess.span_diagnostic.span_err(sp, msg);
533 pub fn span_warn(&self, sp: Span, msg: &str) {
534 self.print_backtrace();
535 self.parse_sess.span_diagnostic.span_warn(sp, msg);
537 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
538 self.print_backtrace();
539 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
541 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
542 self.print_backtrace();
543 self.parse_sess.span_diagnostic.span_bug(sp, msg);
545 pub fn span_note(&self, sp: Span, msg: &str) {
546 self.print_backtrace();
547 self.parse_sess.span_diagnostic.span_note(sp, msg);
549 pub fn bug(&self, msg: &str) -> ! {
550 self.print_backtrace();
551 self.parse_sess.span_diagnostic.handler().bug(msg);
553 pub fn trace_macros(&self) -> bool {
556 pub fn set_trace_macros(&mut self, x: bool) {
559 pub fn ident_of(&self, st: &str) -> ast::Ident {
562 pub fn name_of(&self, st: &str) -> ast::Name {
567 /// Extract a string literal from the macro expanded version of `expr`,
568 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
569 /// compilation on error, merely emits a non-fatal error and returns None.
570 pub fn expr_to_string(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str)
571 -> Option<(InternedString, ast::StrStyle)> {
572 // we want to be able to handle e.g. concat("foo", "bar")
573 let expr = cx.expander().fold_expr(expr);
575 ast::ExprLit(l) => match l.node {
576 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
577 _ => cx.span_err(l.span, err_msg)
579 _ => cx.span_err(expr.span, err_msg)
584 /// Non-fatally assert that `tts` is empty. Note that this function
585 /// returns even when `tts` is non-empty, macros that *need* to stop
586 /// compilation should call
587 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
588 /// done as rarely as possible).
589 pub fn check_zero_tts(cx: &ExtCtxt,
591 tts: &[ast::TokenTree],
594 cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
598 /// Extract the string literal from the first token of `tts`. If this
599 /// is not a string literal, emit an error and return None.
600 pub fn get_single_str_from_tts(cx: &ExtCtxt,
602 tts: &[ast::TokenTree],
606 cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
609 ast::TTTok(_, token::LIT_STR(ident)) => return Some(parse::str_lit(ident.as_str())),
610 ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
611 return Some(parse::raw_str_lit(ident.as_str()))
615 format!("{} requires a string.", name).as_slice())
622 /// Extract comma-separated expressions from `tts`. If there is a
623 /// parsing error, emit a non-fatal error and return None.
624 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
626 tts: &[ast::TokenTree]) -> Option<Vec<Gc<ast::Expr>>> {
627 let mut p = cx.new_parser_from_tts(tts);
628 let mut es = Vec::new();
629 while p.token != token::EOF {
630 es.push(cx.expander().fold_expr(p.parse_expr()));
631 if p.eat(&token::COMMA) {
634 if p.token != token::EOF {
635 cx.span_err(sp, "expected token: `,`");
642 /// In order to have some notion of scoping for macros,
643 /// we want to implement the notion of a transformation
646 /// This environment maps Names to SyntaxExtensions.
647 pub struct SyntaxEnv {
648 chain: Vec<MapChainFrame> ,
651 // impl question: how to implement it? Initially, the
652 // env will contain only macros, so it might be painful
653 // to add an empty frame for every context. Let's just
654 // get it working, first....
656 // NB! the mutability of the underlying maps means that
657 // if expansion is out-of-order, a deeper scope may be
658 // able to refer to a macro that was added to an enclosing
659 // scope lexically later than the deeper scope.
661 struct MapChainFrame {
663 map: HashMap<Name, Rc<SyntaxExtension>>,
667 fn new() -> SyntaxEnv {
668 let mut map = SyntaxEnv { chain: Vec::new() };
673 pub fn push_frame(&mut self) {
674 self.chain.push(MapChainFrame {
675 info: BlockInfo::new(),
680 pub fn pop_frame(&mut self) {
681 assert!(self.chain.len() > 1, "too many pops on MapChain!");
685 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
686 for (i, frame) in self.chain.mut_iter().enumerate().rev() {
687 if !frame.info.macros_escape || i == 0 {
694 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
695 for frame in self.chain.iter().rev() {
696 match frame.map.find(k) {
697 Some(v) => return Some(v.clone()),
704 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
705 self.find_escape_frame().map.insert(k, Rc::new(v));
708 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
709 let last_chain_index = self.chain.len() - 1;
710 &mut self.chain.get_mut(last_chain_index).info