1 // Copyright 2012 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.
13 use ast::{crate, expr_, expr_mac, mac_invoc_tt};
14 use ast::{tt_delim, tt_tok, item_mac, stmt_, stmt_mac, stmt_expr, stmt_semi};
17 use codemap::{span, CallInfo, ExpandedFrom, NameAndSpan};
20 use parse::{parser, parse_expr_from_source_str, new_parser_from_tts};
24 use std::oldmap::HashMap;
26 pub fn expand_expr(exts: SyntaxExtensions, cx: ext_ctxt,
27 e: expr_, s: span, fld: ast_fold,
28 orig: fn@(expr_, span, ast_fold) -> (expr_, span))
31 // expr_mac should really be expr_ext or something; it's the
32 // entry-point for all syntax extensions.
33 expr_mac(ref mac) => {
37 // Token-tree macros, these will be the only case when we're
38 // finished transitioning.
39 mac_invoc_tt(pth, ref tts) => {
40 assert (vec::len(pth.idents) == 1u);
41 /* using idents and token::special_idents would make the
42 the macro names be hygienic */
43 let extname = cx.parse_sess().interner.get(pth.idents[0]);
44 match exts.find(&extname) {
46 cx.span_fatal(pth.span,
47 fmt!("macro undefined: '%s'", *extname))
49 Some(NormalTT(SyntaxExpanderTT{expander: exp,
51 cx.bt_push(ExpandedFrom(CallInfo{
54 name: *extname, span: exp_sp
58 let expanded = match exp(cx, (*mac).span, (*tts)) {
60 MRAny(expr_maker,_,_) => expr_maker(),
62 pth.span, fmt!("non-expr macro in expr pos: %s",
66 //keep going, outside-in
67 let fully_expanded = fld.fold_expr(expanded).node;
73 cx.span_fatal(pth.span,
74 fmt!("'%s' is not a tt-style macro",
86 // This is a secondary mechanism for invoking syntax extensions on items:
87 // "decorator" attributes, such as #[auto_encode]. These are invoked by an
88 // attribute prefixing an item, and are interpreted by feeding the item
89 // through the named attribute _as a syntax extension_ and splicing in the
90 // resulting item vec into place in favour of the decorator. Note that
91 // these do _not_ work for macro extensions, just ItemDecorator ones.
93 // NB: there is some redundancy between this and expand_item, below, and
94 // they might benefit from some amount of semantic and language-UI merger.
95 pub fn expand_mod_items(exts: SyntaxExtensions, cx: ext_ctxt,
96 module_: ast::_mod, fld: ast_fold,
97 orig: fn@(ast::_mod, ast_fold) -> ast::_mod)
99 // Fold the contents first:
100 let module_ = orig(module_, fld);
102 // For each item, look through the attributes. If any of them are
103 // decorated with "item decorators", then use that function to transform
104 // the item into a new set of items.
105 let new_items = do vec::flat_map(module_.items) |item| {
106 do vec::foldr(item.attrs, ~[*item]) |attr, items| {
107 let mname = attr::get_attr_name(attr);
109 match exts.find(&mname) {
110 None | Some(NormalTT(_)) | Some(ItemTT(*)) => items,
111 Some(ItemDecorator(dec_fn)) => {
112 cx.bt_push(ExpandedFrom(CallInfo {
113 call_site: attr.span,
114 callee: NameAndSpan {
115 name: /*bad*/ copy *mname,
119 let r = dec_fn(cx, attr.span, attr.node.value, items);
127 ast::_mod { items: new_items, ..module_ }
131 // When we enter a module, record it, for the sake of `module!`
132 pub fn expand_item(exts: SyntaxExtensions,
133 cx: ext_ctxt, &&it: @ast::item, fld: ast_fold,
134 orig: fn@(&&v: @ast::item, ast_fold) -> Option<@ast::item>)
135 -> Option<@ast::item> {
136 let is_mod = match it.node {
137 ast::item_mod(_) | ast::item_foreign_mod(_) => true,
140 let maybe_it = match it.node {
141 ast::item_mac(*) => expand_item_mac(exts, cx, it, fld),
147 if is_mod { cx.mod_push(it.ident); }
148 let ret_val = orig(it, fld);
149 if is_mod { cx.mod_pop(); }
156 // Support for item-position macro invocations, exactly the same
157 // logic as for expression-position macro invocations.
158 pub fn expand_item_mac(exts: SyntaxExtensions,
159 cx: ext_ctxt, &&it: @ast::item,
160 fld: ast_fold) -> Option<@ast::item> {
162 let (pth, tts) = match it.node {
163 item_mac(codemap::spanned { node: mac_invoc_tt(pth, ref tts), _}) => {
166 _ => cx.span_bug(it.span, ~"invalid item macro invocation")
169 let extname = cx.parse_sess().interner.get(pth.idents[0]);
170 let expanded = match exts.find(&extname) {
171 None => cx.span_fatal(pth.span,
172 fmt!("macro undefined: '%s!'", *extname)),
174 Some(NormalTT(ref expand)) => {
175 if it.ident != parse::token::special_idents::invalid {
176 cx.span_fatal(pth.span,
177 fmt!("macro %s! expects no ident argument, \
178 given '%s'", *extname,
179 *cx.parse_sess().interner.get(it.ident)));
181 cx.bt_push(ExpandedFrom(CallInfo {
183 callee: NameAndSpan {
188 ((*expand).expander)(cx, it.span, tts)
190 Some(ItemTT(ref expand)) => {
191 if it.ident == parse::token::special_idents::invalid {
192 cx.span_fatal(pth.span,
193 fmt!("macro %s! expects an ident argument",
196 cx.bt_push(ExpandedFrom(CallInfo {
198 callee: NameAndSpan {
203 ((*expand).expander)(cx, it.span, it.ident, tts)
206 it.span, fmt!("%s! is not legal in item position", *extname))
209 let maybe_it = match expanded {
210 MRItem(it) => fld.fold_item(it),
211 MRExpr(_) => cx.span_fatal(pth.span,
212 ~"expr macro in item position: "
214 MRAny(_, item_maker, _) =>
215 option::chain(item_maker(), |i| {fld.fold_item(i)}),
217 exts.insert(@/*bad*/ copy mdef.name, (*mdef).ext);
225 pub fn expand_stmt(exts: SyntaxExtensions, cx: ext_ctxt,
226 && s: stmt_, sp: span, fld: ast_fold,
227 orig: fn@(&&s: stmt_, span, ast_fold) -> (stmt_, span))
230 let (mac, pth, tts, semi) = match s {
231 stmt_mac(ref mac, semi) => {
233 mac_invoc_tt(pth, ref tts) => ((*mac), pth, (*tts), semi)
236 _ => return orig(s, sp, fld)
239 assert(vec::len(pth.idents) == 1u);
240 let extname = cx.parse_sess().interner.get(pth.idents[0]);
241 let (fully_expanded, sp) = match exts.find(&extname) {
243 cx.span_fatal(pth.span, fmt!("macro undefined: '%s'", *extname)),
246 SyntaxExpanderTT{expander: exp, span: exp_sp})) => {
247 cx.bt_push(ExpandedFrom(CallInfo {
249 callee: NameAndSpan { name: *extname, span: exp_sp }
251 let expanded = match exp(cx, mac.span, tts) {
253 @codemap::spanned { node: stmt_expr(e, cx.next_id()),
255 MRAny(_,_,stmt_mkr) => stmt_mkr(),
258 fmt!("non-stmt macro in stmt pos: %s", *extname))
261 //keep going, outside-in
262 let fully_expanded = fld.fold_stmt(expanded).node;
269 cx.span_fatal(pth.span,
270 fmt!("'%s' is not a tt-style macro", *extname))
274 return (match fully_expanded {
275 stmt_expr(e, stmt_id) if semi => stmt_semi(e, stmt_id),
276 _ => { fully_expanded } /* might already have a semi */
282 pub fn new_span(cx: ext_ctxt, sp: span) -> span {
283 /* this discards information in the case of macro-defining macros */
284 return span {lo: sp.lo, hi: sp.hi, expn_info: cx.backtrace()};
287 // FIXME (#2247): this is a terrible kludge to inject some macros into
288 // the default compilation environment. When the macro-definition system
289 // is substantially more mature, these should move from here, into a
290 // compiled part of libcore at very least.
292 pub fn core_macros() -> ~str {
295 macro_rules! ignore (($($x:tt)*) => (()))
297 macro_rules! error ( ($( $arg:expr ),+) => (
298 log(::core::error, fmt!( $($arg),+ )) ))
299 macro_rules! warn ( ($( $arg:expr ),+) => (
300 log(::core::warn, fmt!( $($arg),+ )) ))
301 macro_rules! info ( ($( $arg:expr ),+) => (
302 log(::core::info, fmt!( $($arg),+ )) ))
303 macro_rules! debug ( ($( $arg:expr ),+) => (
304 log(::core::debug, fmt!( $($arg),+ )) ))
308 ::core::sys::begin_unwind($msg, file!().to_owned(), line!())
311 fail!(~\"explicit failure\")
315 macro_rules! fail_unless(
318 fail!(~\"assertion failed: \" + stringify!($cond))
323 macro_rules! condition (
325 { $c:ident: $in:ty -> $out:ty; } => {
328 fn key(_x: @::core::condition::Handler<$in,$out>) { }
330 pub const cond : ::core::condition::Condition<$in,$out> =
331 ::core::condition::Condition {
332 name: stringify!($c),
342 pub fn expand_crate(parse_sess: @mut parse::ParseSess,
343 cfg: ast::crate_cfg, c: @crate) -> @crate {
344 let exts = syntax_expander_table();
345 let afp = default_ast_fold();
346 let cx: ext_ctxt = mk_ctxt(parse_sess, cfg);
347 let f_pre = @AstFoldFns {
348 fold_expr: |a,b,c| expand_expr(exts, cx, a, b, c, afp.fold_expr),
349 fold_mod: |a,b| expand_mod_items(exts, cx, a, b, afp.fold_mod),
350 fold_item: |a,b| expand_item(exts, cx, a, b, afp.fold_item),
351 fold_stmt: |a,b,c| expand_stmt(exts, cx, a, b, c, afp.fold_stmt),
352 new_span: |a| new_span(cx, a),
354 let f = make_fold(f_pre);
355 let cm = parse_expr_from_source_str(~"<core-macros>",
360 // This is run for its side-effects on the expander env,
361 // as it registers all the core macros as expanders.
364 let res = @f.fold_crate(*c);
370 // indent-tabs-mode: nil
372 // buffer-file-coding-system: utf-8-unix