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.
11 pub use self::SyntaxExtension::*;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
22 use parse::token::{InternedString, intern, str_to_ident};
24 use util::small_vector::SmallVector;
28 use std::collections::HashMap;
31 // new-style macro! tt code:
33 // MacResult, NormalTT, IdentTT
35 // also note that ast::Mac used to have a bunch of extraneous cases and
36 // is now probably a redundant AST node, can be merged with
41 pub ext: SyntaxExtension
44 pub trait ItemDecorator {
48 meta_item: &ast::MetaItem,
50 push: |P<ast::Item>|);
53 impl ItemDecorator for fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, |P<ast::Item>|) {
57 meta_item: &ast::MetaItem,
59 push: |P<ast::Item>|) {
60 (*self)(ecx, sp, meta_item, item, push)
64 pub trait ItemModifier {
68 meta_item: &ast::MetaItem,
73 impl ItemModifier for fn(&mut ExtCtxt, Span, &ast::MetaItem, P<ast::Item>) -> P<ast::Item> {
77 meta_item: &ast::MetaItem,
80 (*self)(ecx, span, meta_item, item)
84 /// Represents a thing that maps token trees to Macro Results
85 pub trait TTMacroExpander {
87 ecx: &'cx mut ExtCtxt,
89 token_tree: &[ast::TokenTree])
90 -> Box<MacResult+'cx>;
93 pub type MacroExpanderFn =
94 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
96 impl TTMacroExpander for MacroExpanderFn {
98 ecx: &'cx mut ExtCtxt,
100 token_tree: &[ast::TokenTree])
101 -> Box<MacResult+'cx> {
102 (*self)(ecx, span, token_tree)
106 pub trait IdentMacroExpander {
107 fn expand<'cx>(&self,
108 cx: &'cx mut ExtCtxt,
111 token_tree: Vec<ast::TokenTree> )
112 -> Box<MacResult+'cx>;
115 pub type IdentMacroExpanderFn =
116 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
118 impl IdentMacroExpander for IdentMacroExpanderFn {
119 fn expand<'cx>(&self,
120 cx: &'cx mut ExtCtxt,
123 token_tree: Vec<ast::TokenTree> )
124 -> Box<MacResult+'cx> {
125 (*self)(cx, sp, ident, token_tree)
129 /// The result of a macro expansion. The return values of the various
130 /// methods are spliced into the AST at the callsite of the macro (or
131 /// just into the compiler's internal macro table, for `make_def`).
132 pub trait MacResult {
133 /// Attempt to define a new macro.
134 // this should go away; the idea that a macro might expand into
135 // either a macro definition or an expression, depending on what
136 // the context wants, is kind of silly.
137 fn make_def(&mut self) -> Option<MacroDef> {
140 /// Create an expression.
141 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
144 /// Create zero or more items.
145 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
149 /// Create zero or more methods.
150 fn make_methods(self: Box<Self>) -> Option<SmallVector<P<ast::Method>>> {
154 /// Create a pattern.
155 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
159 /// Create a statement.
161 /// By default this attempts to create an expression statement,
162 /// returning None if that fails.
163 fn make_stmt(self: Box<Self>) -> Option<P<ast::Stmt>> {
165 .map(|e| P(codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
169 /// A convenience type for macros that return a single expression.
174 pub fn new(e: P<ast::Expr>) -> Box<MacResult+'static> {
175 box MacExpr { e: e } as Box<MacResult+'static>
178 impl MacResult for MacExpr {
179 fn make_expr(self: Box<MacExpr>) -> Option<P<ast::Expr>> {
182 fn make_pat(self: Box<MacExpr>) -> Option<P<ast::Pat>> {
184 ast::ExprLit(_) => Some(P(ast::Pat {
185 id: ast::DUMMY_NODE_ID,
187 node: ast::PatLit(self.e)
193 /// A convenience type for macros that return a single pattern.
198 pub fn new(p: P<ast::Pat>) -> Box<MacResult+'static> {
199 box MacPat { p: p } as Box<MacResult+'static>
202 impl MacResult for MacPat {
203 fn make_pat(self: Box<MacPat>) -> Option<P<ast::Pat>> {
207 /// A type for macros that return multiple items.
208 pub struct MacItems {
209 items: SmallVector<P<ast::Item>>
213 pub fn new<I: Iterator<P<ast::Item>>>(it: I) -> Box<MacResult+'static> {
214 box MacItems { items: it.collect() } as Box<MacResult+'static>
218 impl MacResult for MacItems {
219 fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
224 /// Fill-in macro expansion result, to allow compilation to continue
225 /// after hitting errors.
226 pub struct DummyResult {
232 /// Create a default MacResult that can be anything.
234 /// Use this as a return value after hitting any errors and
235 /// calling `span_err`.
236 pub fn any(sp: Span) -> Box<MacResult+'static> {
237 box DummyResult { expr_only: false, span: sp } as Box<MacResult+'static>
240 /// Create a default MacResult that can only be an expression.
242 /// Use this for macros that must expand to an expression, so even
243 /// if an error is encountered internally, the user will receive
244 /// an error that they also used it in the wrong place.
245 pub fn expr(sp: Span) -> Box<MacResult+'static> {
246 box DummyResult { expr_only: true, span: sp } as Box<MacResult+'static>
249 /// A plain dummy expression.
250 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
252 id: ast::DUMMY_NODE_ID,
253 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
258 /// A plain dummy pattern.
259 pub fn raw_pat(sp: Span) -> ast::Pat {
261 id: ast::DUMMY_NODE_ID,
262 node: ast::PatWild(ast::PatWildSingle),
269 impl MacResult for DummyResult {
270 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
271 Some(DummyResult::raw_expr(self.span))
273 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
274 Some(P(DummyResult::raw_pat(self.span)))
276 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
277 // this code needs a comment... why not always just return the Some() ?
281 Some(SmallVector::zero())
284 fn make_methods(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Method>>> {
288 Some(SmallVector::zero())
291 fn make_stmt(self: Box<DummyResult>) -> Option<P<ast::Stmt>> {
292 Some(P(codemap::respan(self.span,
293 ast::StmtExpr(DummyResult::raw_expr(self.span),
294 ast::DUMMY_NODE_ID))))
298 /// An enum representing the different kinds of syntax extensions.
299 pub enum SyntaxExtension {
300 /// A syntax extension that is attached to an item and creates new items
303 /// `#[deriving(...)]` is an `ItemDecorator`.
304 Decorator(Box<ItemDecorator + 'static>),
306 /// A syntax extension that is attached to an item and modifies it
308 Modifier(Box<ItemModifier + 'static>),
310 /// A normal, function-like syntax extension.
312 /// `bytes!` is a `NormalTT`.
313 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>),
315 /// A function-like syntax extension that has an extra ident before
318 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
320 /// An ident macro that has two properties:
321 /// - it adds a macro definition to the environment, and
322 /// - the definition it adds doesn't introduce any new
325 /// `macro_rules!` is a LetSyntaxTT
326 LetSyntaxTT(Box<IdentMacroExpander + 'static>, Option<Span>),
329 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
331 pub struct BlockInfo {
332 /// Should macros escape from this scope?
333 pub macros_escape: bool,
334 /// What are the pending renames?
335 pub pending_renames: mtwt::RenameList,
339 pub fn new() -> BlockInfo {
341 macros_escape: false,
342 pending_renames: Vec::new(),
347 /// The base map of methods for expanding syntax extension
348 /// AST nodes into full ASTs
349 fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv {
350 // utility function to simplify creating NormalTT syntax extensions
351 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
352 NormalTT(box f, None)
355 let mut syntax_expanders = SyntaxEnv::new();
356 syntax_expanders.insert(intern("macro_rules"),
357 LetSyntaxTT(box ext::tt::macro_rules::add_new_extension, None));
358 syntax_expanders.insert(intern("fmt"),
359 builtin_normal_expander(
360 ext::fmt::expand_syntax_ext));
361 syntax_expanders.insert(intern("format_args"),
362 builtin_normal_expander(
363 ext::format::expand_format_args));
364 syntax_expanders.insert(intern("env"),
365 builtin_normal_expander(
366 ext::env::expand_env));
367 syntax_expanders.insert(intern("option_env"),
368 builtin_normal_expander(
369 ext::env::expand_option_env));
370 syntax_expanders.insert(intern("bytes"),
371 builtin_normal_expander(
372 ext::bytes::expand_syntax_ext));
373 syntax_expanders.insert(intern("concat_idents"),
374 builtin_normal_expander(
375 ext::concat_idents::expand_syntax_ext));
376 syntax_expanders.insert(intern("concat"),
377 builtin_normal_expander(
378 ext::concat::expand_syntax_ext));
379 syntax_expanders.insert(intern("log_syntax"),
380 builtin_normal_expander(
381 ext::log_syntax::expand_syntax_ext));
382 syntax_expanders.insert(intern("deriving"),
383 Decorator(box ext::deriving::expand_meta_deriving));
385 if ecfg.enable_quotes {
386 // Quasi-quoting expanders
387 syntax_expanders.insert(intern("quote_tokens"),
388 builtin_normal_expander(
389 ext::quote::expand_quote_tokens));
390 syntax_expanders.insert(intern("quote_expr"),
391 builtin_normal_expander(
392 ext::quote::expand_quote_expr));
393 syntax_expanders.insert(intern("quote_ty"),
394 builtin_normal_expander(
395 ext::quote::expand_quote_ty));
396 syntax_expanders.insert(intern("quote_method"),
397 builtin_normal_expander(
398 ext::quote::expand_quote_method));
399 syntax_expanders.insert(intern("quote_item"),
400 builtin_normal_expander(
401 ext::quote::expand_quote_item));
402 syntax_expanders.insert(intern("quote_pat"),
403 builtin_normal_expander(
404 ext::quote::expand_quote_pat));
405 syntax_expanders.insert(intern("quote_arm"),
406 builtin_normal_expander(
407 ext::quote::expand_quote_arm));
408 syntax_expanders.insert(intern("quote_stmt"),
409 builtin_normal_expander(
410 ext::quote::expand_quote_stmt));
413 syntax_expanders.insert(intern("line"),
414 builtin_normal_expander(
415 ext::source_util::expand_line));
416 syntax_expanders.insert(intern("column"),
417 builtin_normal_expander(
418 ext::source_util::expand_column));
419 syntax_expanders.insert(intern("file"),
420 builtin_normal_expander(
421 ext::source_util::expand_file));
422 syntax_expanders.insert(intern("stringify"),
423 builtin_normal_expander(
424 ext::source_util::expand_stringify));
425 syntax_expanders.insert(intern("include"),
426 builtin_normal_expander(
427 ext::source_util::expand_include));
428 syntax_expanders.insert(intern("include_str"),
429 builtin_normal_expander(
430 ext::source_util::expand_include_str));
431 syntax_expanders.insert(intern("include_bin"),
432 builtin_normal_expander(
433 ext::source_util::expand_include_bin));
434 syntax_expanders.insert(intern("module_path"),
435 builtin_normal_expander(
436 ext::source_util::expand_mod));
437 syntax_expanders.insert(intern("asm"),
438 builtin_normal_expander(
439 ext::asm::expand_asm));
440 syntax_expanders.insert(intern("cfg"),
441 builtin_normal_expander(
442 ext::cfg::expand_cfg));
443 syntax_expanders.insert(intern("cfg_attr"),
444 Modifier(box ext::cfg_attr::expand));
445 syntax_expanders.insert(intern("trace_macros"),
446 builtin_normal_expander(
447 ext::trace_macros::expand_trace_macros));
451 /// One of these is made during expansion and incrementally updated as we go;
452 /// when a macro expansion occurs, the resulting nodes have the backtrace()
453 /// -> expn_info of their expansion context stored into their span.
454 pub struct ExtCtxt<'a> {
455 pub parse_sess: &'a parse::ParseSess,
456 pub cfg: ast::CrateConfig,
457 pub backtrace: ExpnId,
458 pub ecfg: expand::ExpansionConfig,
460 pub mod_path: Vec<ast::Ident> ,
462 pub exported_macros: Vec<P<ast::Item>>,
464 pub syntax_env: SyntaxEnv,
465 pub recursion_count: uint,
468 impl<'a> ExtCtxt<'a> {
469 pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
470 ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
471 let env = initial_syntax_expander_table(&ecfg);
473 parse_sess: parse_sess,
475 backtrace: NO_EXPANSION,
476 mod_path: Vec::new(),
479 exported_macros: Vec::new(),
485 #[deprecated = "Replaced with `expander().fold_expr()`"]
486 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
487 self.expander().fold_expr(e)
490 /// Returns a `Folder` for deeply expanding all macros in a AST node.
491 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
492 expand::MacroExpander { cx: self }
495 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
496 -> parser::Parser<'a> {
497 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
500 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
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 {
504 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
505 Some(expn_info) => expn_info.call_site,
506 None => self.bug("missing top span")
509 pub fn print_backtrace(&self) { }
510 pub fn backtrace(&self) -> ExpnId { self.backtrace }
511 pub fn original_span(&self) -> Span {
512 let mut expn_id = self.backtrace;
513 let mut call_site = None;
515 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
518 call_site = Some(cs);
519 expn_id = cs.expn_id;
523 call_site.expect("missing expansion backtrace")
525 pub fn original_span_in_file(&self) -> Span {
526 let mut expn_id = self.backtrace;
527 let mut call_site = None;
529 let expn_info = self.codemap().with_expn_info(expn_id, |ei| {
530 ei.map(|ei| (ei.call_site, ei.callee.name.as_slice() == "include"))
534 Some((cs, is_include)) => {
536 // Don't recurse into file using "include!".
539 call_site = Some(cs);
540 expn_id = cs.expn_id;
544 call_site.expect("missing expansion backtrace")
547 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
548 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
549 pub fn mod_path(&self) -> Vec<ast::Ident> {
550 let mut v = Vec::new();
551 v.push(token::str_to_ident(self.ecfg.crate_name.as_slice()));
552 v.extend(self.mod_path.iter().map(|a| *a));
555 pub fn bt_push(&mut self, ei: ExpnInfo) {
556 self.recursion_count += 1;
557 if self.recursion_count > self.ecfg.recursion_limit {
558 self.span_fatal(ei.call_site,
559 format!("recursion limit reached while expanding the macro `{}`",
560 ei.callee.name).as_slice());
563 let mut call_site = ei.call_site;
564 call_site.expn_id = self.backtrace;
565 self.backtrace = self.codemap().record_expansion(ExpnInfo {
566 call_site: call_site,
570 pub fn bt_pop(&mut self) {
571 match self.backtrace {
572 NO_EXPANSION => self.bug("tried to pop without a push"),
574 self.recursion_count -= 1;
575 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
576 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
581 /// Emit `msg` attached to `sp`, and stop compilation immediately.
583 /// `span_err` should be strongly preferred where-ever possible:
584 /// this should *only* be used when
585 /// - continuing has a high risk of flow-on errors (e.g. errors in
586 /// declaring a macro would cause all uses of that macro to
587 /// complain about "undefined macro"), or
588 /// - there is literally nothing else that can be done (however,
589 /// in most cases one can construct a dummy expression/item to
590 /// substitute; we never hit resolve/type-checking so the dummy
591 /// value doesn't have to match anything)
592 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
593 self.print_backtrace();
594 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
597 /// Emit `msg` attached to `sp`, without immediately stopping
600 /// Compilation will be stopped in the near future (at the end of
601 /// the macro expansion phase).
602 pub fn span_err(&self, sp: Span, msg: &str) {
603 self.print_backtrace();
604 self.parse_sess.span_diagnostic.span_err(sp, msg);
606 pub fn span_warn(&self, sp: Span, msg: &str) {
607 self.print_backtrace();
608 self.parse_sess.span_diagnostic.span_warn(sp, msg);
610 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
611 self.print_backtrace();
612 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
614 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
615 self.print_backtrace();
616 self.parse_sess.span_diagnostic.span_bug(sp, msg);
618 pub fn span_note(&self, sp: Span, msg: &str) {
619 self.print_backtrace();
620 self.parse_sess.span_diagnostic.span_note(sp, msg);
622 pub fn span_help(&self, sp: Span, msg: &str) {
623 self.print_backtrace();
624 self.parse_sess.span_diagnostic.span_help(sp, msg);
626 pub fn bug(&self, msg: &str) -> ! {
627 self.print_backtrace();
628 self.parse_sess.span_diagnostic.handler().bug(msg);
630 pub fn trace_macros(&self) -> bool {
633 pub fn set_trace_macros(&mut self, x: bool) {
636 pub fn ident_of(&self, st: &str) -> ast::Ident {
639 pub fn name_of(&self, st: &str) -> ast::Name {
644 /// Extract a string literal from the macro expanded version of `expr`,
645 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
646 /// compilation on error, merely emits a non-fatal error and returns None.
647 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
648 -> Option<(InternedString, ast::StrStyle)> {
649 // we want to be able to handle e.g. concat("foo", "bar")
650 let expr = cx.expander().fold_expr(expr);
652 ast::ExprLit(ref l) => match l.node {
653 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
654 _ => cx.span_err(l.span, err_msg)
656 _ => cx.span_err(expr.span, err_msg)
661 /// Non-fatally assert that `tts` is empty. Note that this function
662 /// returns even when `tts` is non-empty, macros that *need* to stop
663 /// compilation should call
664 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
665 /// done as rarely as possible).
666 pub fn check_zero_tts(cx: &ExtCtxt,
668 tts: &[ast::TokenTree],
671 cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
675 /// Extract the string literal from the first token of `tts`. If this
676 /// is not a string literal, emit an error and return None.
677 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
679 tts: &[ast::TokenTree],
682 let mut p = cx.new_parser_from_tts(tts);
683 if p.token == token::Eof {
684 cx.span_err(sp, format!("{} takes 1 argument", name).as_slice());
687 let ret = cx.expander().fold_expr(p.parse_expr());
688 if p.token != token::Eof {
689 cx.span_err(sp, format!("{} takes 1 argument", name).as_slice());
691 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
696 /// Extract comma-separated expressions from `tts`. If there is a
697 /// parsing error, emit a non-fatal error and return None.
698 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
700 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
701 let mut p = cx.new_parser_from_tts(tts);
702 let mut es = Vec::new();
703 while p.token != token::Eof {
704 es.push(cx.expander().fold_expr(p.parse_expr()));
705 if p.eat(&token::Comma) {
708 if p.token != token::Eof {
709 cx.span_err(sp, "expected token: `,`");
716 /// In order to have some notion of scoping for macros,
717 /// we want to implement the notion of a transformation
720 /// This environment maps Names to SyntaxExtensions.
721 pub struct SyntaxEnv {
722 chain: Vec<MapChainFrame> ,
725 // impl question: how to implement it? Initially, the
726 // env will contain only macros, so it might be painful
727 // to add an empty frame for every context. Let's just
728 // get it working, first....
730 // NB! the mutability of the underlying maps means that
731 // if expansion is out-of-order, a deeper scope may be
732 // able to refer to a macro that was added to an enclosing
733 // scope lexically later than the deeper scope.
735 struct MapChainFrame {
737 map: HashMap<Name, Rc<SyntaxExtension>>,
741 fn new() -> SyntaxEnv {
742 let mut map = SyntaxEnv { chain: Vec::new() };
747 pub fn push_frame(&mut self) {
748 self.chain.push(MapChainFrame {
749 info: BlockInfo::new(),
754 pub fn pop_frame(&mut self) {
755 assert!(self.chain.len() > 1, "too many pops on MapChain!");
759 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
760 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
761 if !frame.info.macros_escape || i == 0 {
768 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
769 for frame in self.chain.iter().rev() {
770 match frame.map.get(k) {
771 Some(v) => return Some(v.clone()),
778 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
779 self.find_escape_frame().map.insert(k, Rc::new(v));
782 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
783 let last_chain_index = self.chain.len() - 1;
784 &mut self.chain[last_chain_index].info