]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
Get rid of structural records in libsyntax and the last bit in librustc.
[rust.git] / src / libsyntax / ext / expand.rs
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.
4 //
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.
10
11 use core::prelude::*;
12
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};
15 use ast;
16 use attr;
17 use codemap::{span, CallInfo, ExpandedFrom, NameAndSpan};
18 use ext::base::*;
19 use fold::*;
20 use parse::{parser, parse_expr_from_source_str, new_parser_from_tts};
21
22 use core::option;
23 use core::vec;
24 use std::oldmap::HashMap;
25
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))
29                 -> (expr_, span) {
30     return match e {
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) => {
34
35             match (*mac).node {
36
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) {
45                   None => {
46                     cx.span_fatal(pth.span,
47                                   fmt!("macro undefined: '%s'", *extname))
48                   }
49                   Some(NormalTT(SyntaxExpanderTT{expander: exp,
50                                                  span: exp_sp})) => {
51                     cx.bt_push(ExpandedFrom(CallInfo{
52                         call_site: s,
53                         callee: NameAndSpan {
54                             name: *extname, span: exp_sp
55                         }
56                     }));
57
58                     let expanded = match exp(cx, (*mac).span, (*tts)) {
59                       MRExpr(e) => e,
60                       MRAny(expr_maker,_,_) => expr_maker(),
61                       _ => cx.span_fatal(
62                           pth.span, fmt!("non-expr macro in expr pos: %s",
63                                          *extname))
64                     };
65
66                     //keep going, outside-in
67                     let fully_expanded = fld.fold_expr(expanded).node;
68                     cx.bt_pop();
69
70                     (fully_expanded, s)
71                   }
72                   _ => {
73                     cx.span_fatal(pth.span,
74                                   fmt!("'%s' is not a tt-style macro",
75                                        *extname))
76                   }
77
78                 }
79               }
80             }
81           }
82           _ => orig(e, s, fld)
83         };
84 }
85
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.
92 //
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)
98                      -> ast::_mod {
99     // Fold the contents first:
100     let module_ = orig(module_, fld);
101
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);
108
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,
116                           span: None
117                       }
118                   }));
119                   let r = dec_fn(cx, attr.span, attr.node.value, items);
120                   cx.bt_pop();
121                   r
122               }
123             }
124         }
125     };
126
127     ast::_mod { items: new_items, ..module_ }
128 }
129
130
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,
138       _ => false
139     };
140     let maybe_it = match it.node {
141       ast::item_mac(*) => expand_item_mac(exts, cx, it, fld),
142       _ => Some(it)
143     };
144
145     match maybe_it {
146       Some(it) => {
147         if is_mod { cx.mod_push(it.ident); }
148         let ret_val = orig(it, fld);
149         if is_mod { cx.mod_pop(); }
150         return ret_val;
151       }
152       None => return None
153     }
154 }
155
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> {
161
162     let (pth, tts) = match it.node {
163         item_mac(codemap::spanned { node: mac_invoc_tt(pth, ref tts), _}) => {
164             (pth, (*tts))
165         }
166         _ => cx.span_bug(it.span, ~"invalid item macro invocation")
167     };
168
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)),
173
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)));
180             }
181             cx.bt_push(ExpandedFrom(CallInfo {
182                 call_site: it.span,
183                 callee: NameAndSpan {
184                     name: *extname,
185                     span: (*expand).span
186                 }
187             }));
188             ((*expand).expander)(cx, it.span, tts)
189         }
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",
194                                    *extname));
195             }
196             cx.bt_push(ExpandedFrom(CallInfo {
197                 call_site: it.span,
198                 callee: NameAndSpan {
199                     name: *extname,
200                     span: (*expand).span
201                 }
202             }));
203             ((*expand).expander)(cx, it.span, it.ident, tts)
204         }
205         _ => cx.span_fatal(
206             it.span, fmt!("%s! is not legal in item position", *extname))
207     };
208
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: "
213                                     + *extname),
214         MRAny(_, item_maker, _) =>
215             option::chain(item_maker(), |i| {fld.fold_item(i)}),
216         MRDef(ref mdef) => {
217             exts.insert(@/*bad*/ copy mdef.name, (*mdef).ext);
218             None
219         }
220     };
221     cx.bt_pop();
222     return maybe_it;
223 }
224
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))
228                 -> (stmt_, span) {
229
230     let (mac, pth, tts, semi) = match s {
231         stmt_mac(ref mac, semi) => {
232             match (*mac).node {
233                 mac_invoc_tt(pth, ref tts) => ((*mac), pth, (*tts), semi)
234             }
235         }
236         _ => return orig(s, sp, fld)
237     };
238
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) {
242         None =>
243             cx.span_fatal(pth.span, fmt!("macro undefined: '%s'", *extname)),
244
245         Some(NormalTT(
246             SyntaxExpanderTT{expander: exp, span: exp_sp})) => {
247             cx.bt_push(ExpandedFrom(CallInfo {
248                 call_site: sp,
249                 callee: NameAndSpan { name: *extname, span: exp_sp }
250             }));
251             let expanded = match exp(cx, mac.span, tts) {
252                 MRExpr(e) =>
253                     @codemap::spanned { node: stmt_expr(e, cx.next_id()),
254                                     span: e.span},
255                 MRAny(_,_,stmt_mkr) => stmt_mkr(),
256                 _ => cx.span_fatal(
257                     pth.span,
258                     fmt!("non-stmt macro in stmt pos: %s", *extname))
259             };
260
261             //keep going, outside-in
262             let fully_expanded = fld.fold_stmt(expanded).node;
263             cx.bt_pop();
264
265             (fully_expanded, sp)
266         }
267
268         _ => {
269             cx.span_fatal(pth.span,
270                           fmt!("'%s' is not a tt-style macro", *extname))
271         }
272     };
273
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 */
277     }, sp)
278
279 }
280
281
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()};
285 }
286
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.
291
292 pub fn core_macros() -> ~str {
293     return
294 ~"{
295     macro_rules! ignore (($($x:tt)*) => (()))
296
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),+ )) ))
305
306     macro_rules! fail(
307         ($msg: expr) => (
308             ::core::sys::begin_unwind($msg, file!().to_owned(), line!())
309         );
310         () => (
311             fail!(~\"explicit failure\")
312         )
313     )
314
315     macro_rules! fail_unless(
316         ($cond:expr) => {
317             if !$cond {
318                 fail!(~\"assertion failed: \" + stringify!($cond))
319             }
320         }
321     )
322
323     macro_rules! condition (
324
325         { $c:ident: $in:ty -> $out:ty; } => {
326
327             mod $c {
328                 fn key(_x: @::core::condition::Handler<$in,$out>) { }
329
330                 pub const cond : ::core::condition::Condition<$in,$out> =
331                     ::core::condition::Condition {
332                     name: stringify!($c),
333                     key: key
334                 };
335             }
336         }
337     )
338
339 }";
340 }
341
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),
353         .. *afp};
354     let f = make_fold(f_pre);
355     let cm = parse_expr_from_source_str(~"<core-macros>",
356                                         @core_macros(),
357                                         cfg,
358                                         parse_sess);
359
360     // This is run for its side-effects on the expander env,
361     // as it registers all the core macros as expanders.
362     f.fold_expr(cm);
363
364     let res = @f.fold_crate(*c);
365     return res;
366 }
367 // Local Variables:
368 // mode: rust
369 // fill-column: 78;
370 // indent-tabs-mode: nil
371 // c-basic-offset: 4
372 // buffer-file-coding-system: utf-8-unix
373 // End: