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};
19 use ext::tt::macro_rules;
23 use parse::token::{InternedString, intern, str_to_ident};
25 use util::small_vector::SmallVector;
29 use std::collections::HashMap;
32 pub trait ItemDecorator {
36 meta_item: &ast::MetaItem,
38 push: Box<FnMut(P<ast::Item>)>);
41 impl<F> ItemDecorator for F
42 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, Box<FnMut(P<ast::Item>)>)
47 meta_item: &ast::MetaItem,
49 push: Box<FnMut(P<ast::Item>)>) {
50 (*self)(ecx, sp, meta_item, item, push)
54 pub trait ItemModifier {
58 meta_item: &ast::MetaItem,
63 impl<F> ItemModifier for F
64 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, P<ast::Item>) -> P<ast::Item>
69 meta_item: &ast::MetaItem,
72 (*self)(ecx, span, meta_item, item)
76 /// Represents a thing that maps token trees to Macro Results
77 pub trait TTMacroExpander {
79 ecx: &'cx mut ExtCtxt,
81 token_tree: &[ast::TokenTree])
82 -> Box<MacResult+'cx>;
85 pub type MacroExpanderFn =
86 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
88 impl<F> TTMacroExpander for F
89 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
92 ecx: &'cx mut ExtCtxt,
94 token_tree: &[ast::TokenTree])
95 -> Box<MacResult+'cx> {
96 (*self)(ecx, span, token_tree)
100 pub trait IdentMacroExpander {
101 fn expand<'cx>(&self,
102 cx: &'cx mut ExtCtxt,
105 token_tree: Vec<ast::TokenTree> )
106 -> Box<MacResult+'cx>;
109 pub type IdentMacroExpanderFn =
110 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
112 impl<F> IdentMacroExpander for F
113 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
114 Vec<ast::TokenTree>) -> Box<MacResult+'cx>
116 fn expand<'cx>(&self,
117 cx: &'cx mut ExtCtxt,
120 token_tree: Vec<ast::TokenTree> )
121 -> Box<MacResult+'cx>
123 (*self)(cx, sp, ident, token_tree)
127 /// The result of a macro expansion. The return values of the various
128 /// methods are spliced into the AST at the callsite of the macro (or
129 /// just into the compiler's internal macro table, for `make_def`).
130 pub trait MacResult {
131 /// Create an expression.
132 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
135 /// Create zero or more items.
136 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
140 /// Create zero or more methods.
141 fn make_methods(self: Box<Self>) -> Option<SmallVector<P<ast::Method>>> {
145 /// Create a pattern.
146 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
150 /// Create a statement.
152 /// By default this attempts to create an expression statement,
153 /// returning None if that fails.
154 fn make_stmt(self: Box<Self>) -> Option<P<ast::Stmt>> {
156 .map(|e| P(codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
160 /// A convenience type for macros that return a single expression.
165 pub fn new(e: P<ast::Expr>) -> Box<MacResult+'static> {
166 box MacExpr { e: e } as Box<MacResult+'static>
169 impl MacResult for MacExpr {
170 fn make_expr(self: Box<MacExpr>) -> Option<P<ast::Expr>> {
173 fn make_pat(self: Box<MacExpr>) -> Option<P<ast::Pat>> {
175 ast::ExprLit(_) => Some(P(ast::Pat {
176 id: ast::DUMMY_NODE_ID,
178 node: ast::PatLit(self.e)
184 /// A convenience type for macros that return a single pattern.
189 pub fn new(p: P<ast::Pat>) -> Box<MacResult+'static> {
190 box MacPat { p: p } as Box<MacResult+'static>
193 impl MacResult for MacPat {
194 fn make_pat(self: Box<MacPat>) -> Option<P<ast::Pat>> {
198 /// A type for macros that return multiple items.
199 pub struct MacItems {
200 items: SmallVector<P<ast::Item>>
204 pub fn new<I: Iterator<Item=P<ast::Item>>>(it: I) -> Box<MacResult+'static> {
205 box MacItems { items: it.collect() } as Box<MacResult+'static>
209 impl MacResult for MacItems {
210 fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
215 /// Fill-in macro expansion result, to allow compilation to continue
216 /// after hitting errors.
218 pub struct DummyResult {
224 /// Create a default MacResult that can be anything.
226 /// Use this as a return value after hitting any errors and
227 /// calling `span_err`.
228 pub fn any(sp: Span) -> Box<MacResult+'static> {
229 box DummyResult { expr_only: false, span: sp } as Box<MacResult+'static>
232 /// Create a default MacResult that can only be an expression.
234 /// Use this for macros that must expand to an expression, so even
235 /// if an error is encountered internally, the user will receive
236 /// an error that they also used it in the wrong place.
237 pub fn expr(sp: Span) -> Box<MacResult+'static> {
238 box DummyResult { expr_only: true, span: sp } as Box<MacResult+'static>
241 /// A plain dummy expression.
242 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
244 id: ast::DUMMY_NODE_ID,
245 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
250 /// A plain dummy pattern.
251 pub fn raw_pat(sp: Span) -> ast::Pat {
253 id: ast::DUMMY_NODE_ID,
254 node: ast::PatWild(ast::PatWildSingle),
261 impl MacResult for DummyResult {
262 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
263 Some(DummyResult::raw_expr(self.span))
265 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
266 Some(P(DummyResult::raw_pat(self.span)))
268 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
269 // this code needs a comment... why not always just return the Some() ?
273 Some(SmallVector::zero())
276 fn make_methods(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Method>>> {
280 Some(SmallVector::zero())
283 fn make_stmt(self: Box<DummyResult>) -> Option<P<ast::Stmt>> {
284 Some(P(codemap::respan(self.span,
285 ast::StmtExpr(DummyResult::raw_expr(self.span),
286 ast::DUMMY_NODE_ID))))
290 /// An enum representing the different kinds of syntax extensions.
291 pub enum SyntaxExtension {
292 /// A syntax extension that is attached to an item and creates new items
295 /// `#[derive(...)]` is an `ItemDecorator`.
296 Decorator(Box<ItemDecorator + 'static>),
298 /// A syntax extension that is attached to an item and modifies it
300 Modifier(Box<ItemModifier + 'static>),
302 /// A normal, function-like syntax extension.
304 /// `bytes!` is a `NormalTT`.
305 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>),
307 /// A function-like syntax extension that has an extra ident before
310 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
312 /// Represents `macro_rules!` itself.
316 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
318 pub struct BlockInfo {
319 /// Should macros escape from this scope?
320 pub macros_escape: bool,
321 /// What are the pending renames?
322 pub pending_renames: mtwt::RenameList,
326 pub fn new() -> BlockInfo {
328 macros_escape: false,
329 pending_renames: Vec::new(),
334 /// The base map of methods for expanding syntax extension
335 /// AST nodes into full ASTs
336 fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv {
337 // utility function to simplify creating NormalTT syntax extensions
338 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
339 NormalTT(box f, None)
342 let mut syntax_expanders = SyntaxEnv::new();
343 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
344 syntax_expanders.insert(intern("fmt"),
345 builtin_normal_expander(
346 ext::fmt::expand_syntax_ext));
347 syntax_expanders.insert(intern("format_args"),
348 builtin_normal_expander(
349 ext::format::expand_format_args));
350 syntax_expanders.insert(intern("env"),
351 builtin_normal_expander(
352 ext::env::expand_env));
353 syntax_expanders.insert(intern("option_env"),
354 builtin_normal_expander(
355 ext::env::expand_option_env));
356 syntax_expanders.insert(intern("bytes"),
357 builtin_normal_expander(
358 ext::bytes::expand_syntax_ext));
359 syntax_expanders.insert(intern("concat_idents"),
360 builtin_normal_expander(
361 ext::concat_idents::expand_syntax_ext));
362 syntax_expanders.insert(intern("concat"),
363 builtin_normal_expander(
364 ext::concat::expand_syntax_ext));
365 syntax_expanders.insert(intern("log_syntax"),
366 builtin_normal_expander(
367 ext::log_syntax::expand_syntax_ext));
368 syntax_expanders.insert(intern("derive"),
369 Decorator(box ext::deriving::expand_meta_derive));
370 syntax_expanders.insert(intern("deriving"),
371 Decorator(box ext::deriving::expand_meta_deriving));
373 if ecfg.enable_quotes {
374 // Quasi-quoting expanders
375 syntax_expanders.insert(intern("quote_tokens"),
376 builtin_normal_expander(
377 ext::quote::expand_quote_tokens));
378 syntax_expanders.insert(intern("quote_expr"),
379 builtin_normal_expander(
380 ext::quote::expand_quote_expr));
381 syntax_expanders.insert(intern("quote_ty"),
382 builtin_normal_expander(
383 ext::quote::expand_quote_ty));
384 syntax_expanders.insert(intern("quote_method"),
385 builtin_normal_expander(
386 ext::quote::expand_quote_method));
387 syntax_expanders.insert(intern("quote_item"),
388 builtin_normal_expander(
389 ext::quote::expand_quote_item));
390 syntax_expanders.insert(intern("quote_pat"),
391 builtin_normal_expander(
392 ext::quote::expand_quote_pat));
393 syntax_expanders.insert(intern("quote_arm"),
394 builtin_normal_expander(
395 ext::quote::expand_quote_arm));
396 syntax_expanders.insert(intern("quote_stmt"),
397 builtin_normal_expander(
398 ext::quote::expand_quote_stmt));
401 syntax_expanders.insert(intern("line"),
402 builtin_normal_expander(
403 ext::source_util::expand_line));
404 syntax_expanders.insert(intern("column"),
405 builtin_normal_expander(
406 ext::source_util::expand_column));
407 syntax_expanders.insert(intern("file"),
408 builtin_normal_expander(
409 ext::source_util::expand_file));
410 syntax_expanders.insert(intern("stringify"),
411 builtin_normal_expander(
412 ext::source_util::expand_stringify));
413 syntax_expanders.insert(intern("include"),
414 builtin_normal_expander(
415 ext::source_util::expand_include));
416 syntax_expanders.insert(intern("include_str"),
417 builtin_normal_expander(
418 ext::source_util::expand_include_str));
419 syntax_expanders.insert(intern("include_bin"),
420 builtin_normal_expander(
421 ext::source_util::expand_include_bin));
422 syntax_expanders.insert(intern("include_bytes"),
423 builtin_normal_expander(
424 ext::source_util::expand_include_bytes));
425 syntax_expanders.insert(intern("module_path"),
426 builtin_normal_expander(
427 ext::source_util::expand_mod));
428 syntax_expanders.insert(intern("asm"),
429 builtin_normal_expander(
430 ext::asm::expand_asm));
431 syntax_expanders.insert(intern("cfg"),
432 builtin_normal_expander(
433 ext::cfg::expand_cfg));
434 syntax_expanders.insert(intern("cfg_attr"),
435 Modifier(box ext::cfg_attr::expand));
436 syntax_expanders.insert(intern("trace_macros"),
437 builtin_normal_expander(
438 ext::trace_macros::expand_trace_macros));
442 /// One of these is made during expansion and incrementally updated as we go;
443 /// when a macro expansion occurs, the resulting nodes have the backtrace()
444 /// -> expn_info of their expansion context stored into their span.
445 pub struct ExtCtxt<'a> {
446 pub parse_sess: &'a parse::ParseSess,
447 pub cfg: ast::CrateConfig,
448 pub backtrace: ExpnId,
449 pub ecfg: expand::ExpansionConfig,
451 pub mod_path: Vec<ast::Ident> ,
453 pub exported_macros: Vec<ast::MacroDef>,
455 pub syntax_env: SyntaxEnv,
456 pub recursion_count: uint,
459 impl<'a> ExtCtxt<'a> {
460 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
461 ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
462 let env = initial_syntax_expander_table(&ecfg);
464 parse_sess: parse_sess,
466 backtrace: NO_EXPANSION,
467 mod_path: Vec::new(),
470 exported_macros: Vec::new(),
476 #[deprecated = "Replaced with `expander().fold_expr()`"]
477 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
478 self.expander().fold_expr(e)
481 /// Returns a `Folder` for deeply expanding all macros in a AST node.
482 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
483 expand::MacroExpander::new(self)
486 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
487 -> parser::Parser<'a> {
488 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
491 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
492 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
493 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
494 pub fn call_site(&self) -> Span {
495 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
496 Some(expn_info) => expn_info.call_site,
497 None => self.bug("missing top span")
500 pub fn print_backtrace(&self) { }
501 pub fn backtrace(&self) -> ExpnId { self.backtrace }
502 pub fn original_span(&self) -> Span {
503 let mut expn_id = self.backtrace;
504 let mut call_site = None;
506 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
509 call_site = Some(cs);
510 expn_id = cs.expn_id;
514 call_site.expect("missing expansion backtrace")
516 pub fn original_span_in_file(&self) -> Span {
517 let mut expn_id = self.backtrace;
518 let mut call_site = None;
520 let expn_info = self.codemap().with_expn_info(expn_id, |ei| {
521 ei.map(|ei| (ei.call_site, ei.callee.name == "include"))
525 Some((cs, is_include)) => {
527 // Don't recurse into file using "include!".
530 call_site = Some(cs);
531 expn_id = cs.expn_id;
535 call_site.expect("missing expansion backtrace")
538 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
539 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
540 pub fn mod_path(&self) -> Vec<ast::Ident> {
541 let mut v = Vec::new();
542 v.push(token::str_to_ident(self.ecfg.crate_name[]));
543 v.extend(self.mod_path.iter().map(|a| *a));
546 pub fn bt_push(&mut self, ei: ExpnInfo) {
547 self.recursion_count += 1;
548 if self.recursion_count > self.ecfg.recursion_limit {
549 self.span_fatal(ei.call_site,
550 format!("recursion limit reached while expanding the macro `{}`",
554 let mut call_site = ei.call_site;
555 call_site.expn_id = self.backtrace;
556 self.backtrace = self.codemap().record_expansion(ExpnInfo {
557 call_site: call_site,
561 pub fn bt_pop(&mut self) {
562 match self.backtrace {
563 NO_EXPANSION => self.bug("tried to pop without a push"),
565 self.recursion_count -= 1;
566 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
567 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
573 pub fn insert_macro(&mut self, def: ast::MacroDef) {
575 self.exported_macros.push(def.clone());
578 let ext = macro_rules::compile(self, &def);
579 self.syntax_env.insert(def.ident.name, ext);
583 /// Emit `msg` attached to `sp`, and stop compilation immediately.
585 /// `span_err` should be strongly preferred where-ever possible:
586 /// this should *only* be used when
587 /// - continuing has a high risk of flow-on errors (e.g. errors in
588 /// declaring a macro would cause all uses of that macro to
589 /// complain about "undefined macro"), or
590 /// - there is literally nothing else that can be done (however,
591 /// in most cases one can construct a dummy expression/item to
592 /// substitute; we never hit resolve/type-checking so the dummy
593 /// value doesn't have to match anything)
594 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
595 self.print_backtrace();
596 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
599 /// Emit `msg` attached to `sp`, without immediately stopping
602 /// Compilation will be stopped in the near future (at the end of
603 /// the macro expansion phase).
604 pub fn span_err(&self, sp: Span, msg: &str) {
605 self.print_backtrace();
606 self.parse_sess.span_diagnostic.span_err(sp, msg);
608 pub fn span_warn(&self, sp: Span, msg: &str) {
609 self.print_backtrace();
610 self.parse_sess.span_diagnostic.span_warn(sp, msg);
612 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
613 self.print_backtrace();
614 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
616 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
617 self.print_backtrace();
618 self.parse_sess.span_diagnostic.span_bug(sp, msg);
620 pub fn span_note(&self, sp: Span, msg: &str) {
621 self.print_backtrace();
622 self.parse_sess.span_diagnostic.span_note(sp, msg);
624 pub fn span_help(&self, sp: Span, msg: &str) {
625 self.print_backtrace();
626 self.parse_sess.span_diagnostic.span_help(sp, msg);
628 pub fn bug(&self, msg: &str) -> ! {
629 self.print_backtrace();
630 self.parse_sess.span_diagnostic.handler().bug(msg);
632 pub fn trace_macros(&self) -> bool {
635 pub fn set_trace_macros(&mut self, x: bool) {
638 pub fn ident_of(&self, st: &str) -> ast::Ident {
641 pub fn name_of(&self, st: &str) -> ast::Name {
646 /// Extract a string literal from the macro expanded version of `expr`,
647 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
648 /// compilation on error, merely emits a non-fatal error and returns None.
649 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
650 -> Option<(InternedString, ast::StrStyle)> {
651 // we want to be able to handle e.g. concat("foo", "bar")
652 let expr = cx.expander().fold_expr(expr);
654 ast::ExprLit(ref l) => match l.node {
655 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
656 _ => cx.span_err(l.span, err_msg)
658 _ => cx.span_err(expr.span, err_msg)
663 /// Non-fatally assert that `tts` is empty. Note that this function
664 /// returns even when `tts` is non-empty, macros that *need* to stop
665 /// compilation should call
666 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
667 /// done as rarely as possible).
668 pub fn check_zero_tts(cx: &ExtCtxt,
670 tts: &[ast::TokenTree],
673 cx.span_err(sp, format!("{} takes no arguments", name)[]);
677 /// Extract the string literal from the first token of `tts`. If this
678 /// is not a string literal, emit an error and return None.
679 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
681 tts: &[ast::TokenTree],
684 let mut p = cx.new_parser_from_tts(tts);
685 if p.token == token::Eof {
686 cx.span_err(sp, format!("{} takes 1 argument", name)[]);
689 let ret = cx.expander().fold_expr(p.parse_expr());
690 if p.token != token::Eof {
691 cx.span_err(sp, format!("{} takes 1 argument", name)[]);
693 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
698 /// Extract comma-separated expressions from `tts`. If there is a
699 /// parsing error, emit a non-fatal error and return None.
700 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
702 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
703 let mut p = cx.new_parser_from_tts(tts);
704 let mut es = Vec::new();
705 while p.token != token::Eof {
706 es.push(cx.expander().fold_expr(p.parse_expr()));
707 if p.eat(&token::Comma) {
710 if p.token != token::Eof {
711 cx.span_err(sp, "expected token: `,`");
718 /// In order to have some notion of scoping for macros,
719 /// we want to implement the notion of a transformation
722 /// This environment maps Names to SyntaxExtensions.
723 pub struct SyntaxEnv {
724 chain: Vec<MapChainFrame> ,
727 // impl question: how to implement it? Initially, the
728 // env will contain only macros, so it might be painful
729 // to add an empty frame for every context. Let's just
730 // get it working, first....
732 // NB! the mutability of the underlying maps means that
733 // if expansion is out-of-order, a deeper scope may be
734 // able to refer to a macro that was added to an enclosing
735 // scope lexically later than the deeper scope.
737 struct MapChainFrame {
739 map: HashMap<Name, Rc<SyntaxExtension>>,
743 fn new() -> SyntaxEnv {
744 let mut map = SyntaxEnv { chain: Vec::new() };
749 pub fn push_frame(&mut self) {
750 self.chain.push(MapChainFrame {
751 info: BlockInfo::new(),
756 pub fn pop_frame(&mut self) {
757 assert!(self.chain.len() > 1, "too many pops on MapChain!");
761 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
762 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
763 if !frame.info.macros_escape || i == 0 {
770 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
771 for frame in self.chain.iter().rev() {
772 match frame.map.get(k) {
773 Some(v) => return Some(v.clone()),
780 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
781 self.find_escape_frame().map.insert(k, Rc::new(v));
784 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
785 let last_chain_index = self.chain.len() - 1;
786 &mut self.chain[last_chain_index].info