]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw
[rust.git] / src / libsyntax / ext / base.rs
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.
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 ast;
12 use ast::Name;
13 use codemap;
14 use codemap::{CodeMap, Span, ExpnInfo};
15 use ext;
16 use ext::expand;
17 use parse;
18 use parse::token;
19 use parse::token::{InternedString, intern, str_to_ident};
20 use util::small_vector::SmallVector;
21
22 use collections::HashMap;
23
24 // new-style macro! tt code:
25 //
26 //    MacResult, NormalTT, IdentTT
27 //
28 // also note that ast::Mac used to have a bunch of extraneous cases and
29 // is now probably a redundant AST node, can be merged with
30 // ast::MacInvocTT.
31
32 pub struct MacroDef {
33     name: ~str,
34     ext: SyntaxExtension
35 }
36
37 pub type ItemDecorator =
38     fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item, |@ast::Item|);
39
40 pub type ItemModifier =
41     fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item) -> @ast::Item;
42
43 pub struct BasicMacroExpander {
44     expander: MacroExpanderFn,
45     span: Option<Span>
46 }
47
48 pub trait MacroExpander {
49     fn expand(&self,
50               ecx: &mut ExtCtxt,
51               span: Span,
52               token_tree: &[ast::TokenTree])
53               -> MacResult;
54 }
55
56 pub type MacroExpanderFn =
57     fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
58        -> MacResult;
59
60 impl MacroExpander for BasicMacroExpander {
61     fn expand(&self,
62               ecx: &mut ExtCtxt,
63               span: Span,
64               token_tree: &[ast::TokenTree])
65               -> MacResult {
66         (self.expander)(ecx, span, token_tree)
67     }
68 }
69
70 pub struct BasicIdentMacroExpander {
71     expander: IdentMacroExpanderFn,
72     span: Option<Span>
73 }
74
75 pub trait IdentMacroExpander {
76     fn expand(&self,
77               cx: &mut ExtCtxt,
78               sp: Span,
79               ident: ast::Ident,
80               token_tree: Vec<ast::TokenTree> )
81               -> MacResult;
82 }
83
84 impl IdentMacroExpander for BasicIdentMacroExpander {
85     fn expand(&self,
86               cx: &mut ExtCtxt,
87               sp: Span,
88               ident: ast::Ident,
89               token_tree: Vec<ast::TokenTree> )
90               -> MacResult {
91         (self.expander)(cx, sp, ident, token_tree)
92     }
93 }
94
95 pub type IdentMacroExpanderFn =
96     fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> MacResult;
97
98 pub type MacroCrateRegistrationFun =
99     fn(|ast::Name, SyntaxExtension|);
100
101 pub trait AnyMacro {
102     fn make_expr(&self) -> @ast::Expr;
103     fn make_items(&self) -> SmallVector<@ast::Item>;
104     fn make_stmt(&self) -> @ast::Stmt;
105 }
106
107
108 pub enum MacResult {
109     MRExpr(@ast::Expr),
110     MRItem(@ast::Item),
111     MRAny(~AnyMacro:),
112     MRDef(MacroDef),
113 }
114 impl MacResult {
115     /// Create an empty expression MacResult; useful for satisfying
116     /// type signatures after emitting a non-fatal error (which stop
117     /// compilation well before the validity (or otherwise)) of the
118     /// expression are checked.
119     pub fn raw_dummy_expr(sp: codemap::Span) -> @ast::Expr {
120         @ast::Expr {
121             id: ast::DUMMY_NODE_ID,
122             node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
123             span: sp,
124         }
125     }
126     pub fn dummy_expr(sp: codemap::Span) -> MacResult {
127         MRExpr(MacResult::raw_dummy_expr(sp))
128     }
129     pub fn dummy_any(sp: codemap::Span) -> MacResult {
130         MRAny(~DummyMacResult { sp: sp })
131     }
132 }
133 struct DummyMacResult {
134     sp: codemap::Span
135 }
136 impl AnyMacro for DummyMacResult {
137     fn make_expr(&self) -> @ast::Expr {
138         MacResult::raw_dummy_expr(self.sp)
139     }
140     fn make_items(&self) -> SmallVector<@ast::Item> {
141         SmallVector::zero()
142     }
143     fn make_stmt(&self) -> @ast::Stmt {
144         @codemap::respan(self.sp,
145                          ast::StmtExpr(MacResult::raw_dummy_expr(self.sp), ast::DUMMY_NODE_ID))
146     }
147 }
148
149 /// An enum representing the different kinds of syntax extensions.
150 pub enum SyntaxExtension {
151     /// A syntax extension that is attached to an item and creates new items
152     /// based upon it.
153     ///
154     /// `#[deriving(...)]` is an `ItemDecorator`.
155     ItemDecorator(ItemDecorator),
156
157     /// A syntax extension that is attached to an item and modifies it
158     /// in-place.
159     ItemModifier(ItemModifier),
160
161     /// A normal, function-like syntax extension.
162     ///
163     /// `bytes!` is a `NormalTT`.
164     NormalTT(~MacroExpander:'static, Option<Span>),
165
166     /// A function-like syntax extension that has an extra ident before
167     /// the block.
168     ///
169     /// `macro_rules!` is an `IdentTT`.
170     IdentTT(~IdentMacroExpander:'static, Option<Span>),
171 }
172
173 pub struct BlockInfo {
174     // should macros escape from this scope?
175     macros_escape: bool,
176     // what are the pending renames?
177     pending_renames: RenameList,
178 }
179
180 impl BlockInfo {
181     pub fn new() -> BlockInfo {
182         BlockInfo {
183             macros_escape: false,
184             pending_renames: Vec::new(),
185         }
186     }
187 }
188
189 // a list of ident->name renamings
190 pub type RenameList = Vec<(ast::Ident, Name)>;
191
192 // The base map of methods for expanding syntax extension
193 // AST nodes into full ASTs
194 pub fn syntax_expander_table() -> SyntaxEnv {
195     // utility function to simplify creating NormalTT syntax extensions
196     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
197         NormalTT(~BasicMacroExpander {
198                 expander: f,
199                 span: None,
200             },
201             None)
202     }
203
204     let mut syntax_expanders = SyntaxEnv::new();
205     syntax_expanders.insert(intern(&"macro_rules"),
206                             IdentTT(~BasicIdentMacroExpander {
207                                 expander: ext::tt::macro_rules::add_new_extension,
208                                 span: None,
209                             },
210                             None));
211     syntax_expanders.insert(intern(&"fmt"),
212                             builtin_normal_expander(
213                                 ext::fmt::expand_syntax_ext));
214     syntax_expanders.insert(intern(&"format_args"),
215                             builtin_normal_expander(
216                                 ext::format::expand_args));
217     syntax_expanders.insert(intern(&"env"),
218                             builtin_normal_expander(
219                                     ext::env::expand_env));
220     syntax_expanders.insert(intern(&"option_env"),
221                             builtin_normal_expander(
222                                     ext::env::expand_option_env));
223     syntax_expanders.insert(intern("bytes"),
224                             builtin_normal_expander(
225                                     ext::bytes::expand_syntax_ext));
226     syntax_expanders.insert(intern("concat_idents"),
227                             builtin_normal_expander(
228                                     ext::concat_idents::expand_syntax_ext));
229     syntax_expanders.insert(intern("concat"),
230                             builtin_normal_expander(
231                                     ext::concat::expand_syntax_ext));
232     syntax_expanders.insert(intern(&"log_syntax"),
233                             builtin_normal_expander(
234                                     ext::log_syntax::expand_syntax_ext));
235     syntax_expanders.insert(intern(&"deriving"),
236                             ItemDecorator(ext::deriving::expand_meta_deriving));
237
238     // Quasi-quoting expanders
239     syntax_expanders.insert(intern(&"quote_tokens"),
240                        builtin_normal_expander(
241                             ext::quote::expand_quote_tokens));
242     syntax_expanders.insert(intern(&"quote_expr"),
243                        builtin_normal_expander(
244                             ext::quote::expand_quote_expr));
245     syntax_expanders.insert(intern(&"quote_ty"),
246                        builtin_normal_expander(
247                             ext::quote::expand_quote_ty));
248     syntax_expanders.insert(intern(&"quote_item"),
249                        builtin_normal_expander(
250                             ext::quote::expand_quote_item));
251     syntax_expanders.insert(intern(&"quote_pat"),
252                        builtin_normal_expander(
253                             ext::quote::expand_quote_pat));
254     syntax_expanders.insert(intern(&"quote_stmt"),
255                        builtin_normal_expander(
256                             ext::quote::expand_quote_stmt));
257
258     syntax_expanders.insert(intern(&"line"),
259                             builtin_normal_expander(
260                                     ext::source_util::expand_line));
261     syntax_expanders.insert(intern(&"col"),
262                             builtin_normal_expander(
263                                     ext::source_util::expand_col));
264     syntax_expanders.insert(intern(&"file"),
265                             builtin_normal_expander(
266                                     ext::source_util::expand_file));
267     syntax_expanders.insert(intern(&"stringify"),
268                             builtin_normal_expander(
269                                     ext::source_util::expand_stringify));
270     syntax_expanders.insert(intern(&"include"),
271                             builtin_normal_expander(
272                                     ext::source_util::expand_include));
273     syntax_expanders.insert(intern(&"include_str"),
274                             builtin_normal_expander(
275                                     ext::source_util::expand_include_str));
276     syntax_expanders.insert(intern(&"include_bin"),
277                             builtin_normal_expander(
278                                     ext::source_util::expand_include_bin));
279     syntax_expanders.insert(intern(&"module_path"),
280                             builtin_normal_expander(
281                                     ext::source_util::expand_mod));
282     syntax_expanders.insert(intern(&"asm"),
283                             builtin_normal_expander(
284                                     ext::asm::expand_asm));
285     syntax_expanders.insert(intern(&"cfg"),
286                             builtin_normal_expander(
287                                     ext::cfg::expand_cfg));
288     syntax_expanders.insert(intern(&"trace_macros"),
289                             builtin_normal_expander(
290                                     ext::trace_macros::expand_trace_macros));
291     syntax_expanders
292 }
293
294 pub struct MacroCrate {
295     lib: Option<Path>,
296     cnum: ast::CrateNum,
297 }
298
299 pub trait CrateLoader {
300     fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate;
301     fn get_exported_macros(&mut self, crate_num: ast::CrateNum) -> Vec<~str> ;
302     fn get_registrar_symbol(&mut self, crate_num: ast::CrateNum) -> Option<~str>;
303 }
304
305 // One of these is made during expansion and incrementally updated as we go;
306 // when a macro expansion occurs, the resulting nodes have the backtrace()
307 // -> expn_info of their expansion context stored into their span.
308 pub struct ExtCtxt<'a> {
309     parse_sess: &'a parse::ParseSess,
310     cfg: ast::CrateConfig,
311     backtrace: Option<@ExpnInfo>,
312     ecfg: expand::ExpansionConfig<'a>,
313
314     mod_path: Vec<ast::Ident> ,
315     trace_mac: bool
316 }
317
318 impl<'a> ExtCtxt<'a> {
319     pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
320                    ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
321         ExtCtxt {
322             parse_sess: parse_sess,
323             cfg: cfg,
324             backtrace: None,
325             mod_path: Vec::new(),
326             ecfg: ecfg,
327             trace_mac: false
328         }
329     }
330
331     pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
332         loop {
333             match e.node {
334                 ast::ExprMac(..) => {
335                     let mut expander = expand::MacroExpander {
336                         extsbox: syntax_expander_table(),
337                         cx: self,
338                     };
339                     e = expand::expand_expr(e, &mut expander);
340                 }
341                 _ => return e
342             }
343         }
344     }
345
346     pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
347     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
348     pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
349     pub fn call_site(&self) -> Span {
350         match self.backtrace {
351             Some(expn_info) => expn_info.call_site,
352             None => self.bug("missing top span")
353         }
354     }
355     pub fn print_backtrace(&self) { }
356     pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
357     pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
358     pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
359     pub fn mod_path(&self) -> Vec<ast::Ident> {
360         let mut v = Vec::new();
361         v.push(token::str_to_ident(self.ecfg.crate_id.name));
362         v.extend(&mut self.mod_path.iter().map(|a| *a));
363         return v;
364     }
365     pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
366         match ei {
367             ExpnInfo {call_site: cs, callee: ref callee} => {
368                 self.backtrace =
369                     Some(@ExpnInfo {
370                         call_site: Span {lo: cs.lo, hi: cs.hi,
371                                          expn_info: self.backtrace},
372                         callee: (*callee).clone()
373                     });
374             }
375         }
376     }
377     pub fn bt_pop(&mut self) {
378         match self.backtrace {
379             Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
380             _ => self.bug("tried to pop without a push")
381         }
382     }
383     /// Emit `msg` attached to `sp`, and stop compilation immediately.
384     ///
385     /// `span_err` should be strongly prefered where-ever possible:
386     /// this should *only* be used when
387     /// - continuing has a high risk of flow-on errors (e.g. errors in
388     ///   declaring a macro would cause all uses of that macro to
389     ///   complain about "undefined macro"), or
390     /// - there is literally nothing else that can be done (however,
391     ///   in most cases one can construct a dummy expression/item to
392     ///   substitute; we never hit resolve/type-checking so the dummy
393     ///   value doesn't have to match anything)
394     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
395         self.print_backtrace();
396         self.parse_sess.span_diagnostic.span_fatal(sp, msg);
397     }
398
399     /// Emit `msg` attached to `sp`, without immediately stopping
400     /// compilation.
401     ///
402     /// Compilation will be stopped in the near future (at the end of
403     /// the macro expansion phase).
404     pub fn span_err(&self, sp: Span, msg: &str) {
405         self.print_backtrace();
406         self.parse_sess.span_diagnostic.span_err(sp, msg);
407     }
408     pub fn span_warn(&self, sp: Span, msg: &str) {
409         self.print_backtrace();
410         self.parse_sess.span_diagnostic.span_warn(sp, msg);
411     }
412     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
413         self.print_backtrace();
414         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
415     }
416     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
417         self.print_backtrace();
418         self.parse_sess.span_diagnostic.span_bug(sp, msg);
419     }
420     pub fn span_note(&self, sp: Span, msg: &str) {
421         self.print_backtrace();
422         self.parse_sess.span_diagnostic.span_note(sp, msg);
423     }
424     pub fn bug(&self, msg: &str) -> ! {
425         self.print_backtrace();
426         self.parse_sess.span_diagnostic.handler().bug(msg);
427     }
428     pub fn trace_macros(&self) -> bool {
429         self.trace_mac
430     }
431     pub fn set_trace_macros(&mut self, x: bool) {
432         self.trace_mac = x
433     }
434     pub fn ident_of(&self, st: &str) -> ast::Ident {
435         str_to_ident(st)
436     }
437 }
438
439 /// Extract a string literal from the macro expanded version of `expr`,
440 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
441 /// compilation on error, merely emits a non-fatal error and returns None.
442 pub fn expr_to_str(cx: &mut ExtCtxt, expr: @ast::Expr, err_msg: &str)
443                    -> Option<(InternedString, ast::StrStyle)> {
444     // we want to be able to handle e.g. concat("foo", "bar")
445     let expr = cx.expand_expr(expr);
446     match expr.node {
447         ast::ExprLit(l) => match l.node {
448             ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
449             _ => cx.span_err(l.span, err_msg)
450         },
451         _ => cx.span_err(expr.span, err_msg)
452     }
453     None
454 }
455
456 /// Non-fatally assert that `tts` is empty. Note that this function
457 /// returns even when `tts` is non-empty, macros that *need* to stop
458 /// compilation should call
459 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
460 /// done as rarely as possible).
461 pub fn check_zero_tts(cx: &ExtCtxt,
462                       sp: Span,
463                       tts: &[ast::TokenTree],
464                       name: &str) {
465     if tts.len() != 0 {
466         cx.span_err(sp, format!("{} takes no arguments", name));
467     }
468 }
469
470 /// Extract the string literal from the first token of `tts`. If this
471 /// is not a string literal, emit an error and return None.
472 pub fn get_single_str_from_tts(cx: &ExtCtxt,
473                                sp: Span,
474                                tts: &[ast::TokenTree],
475                                name: &str)
476                                -> Option<~str> {
477     if tts.len() != 1 {
478         cx.span_err(sp, format!("{} takes 1 argument.", name));
479     } else {
480         match tts[0] {
481             ast::TTTok(_, token::LIT_STR(ident))
482             | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
483                 return Some(token::get_ident(ident).get().to_str())
484             }
485             _ => cx.span_err(sp, format!("{} requires a string.", name)),
486         }
487     }
488     None
489 }
490
491 /// Extract comma-separated expressions from `tts`. If there is a
492 /// parsing error, emit a non-fatal error and return None.
493 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
494                           sp: Span,
495                           tts: &[ast::TokenTree]) -> Option<Vec<@ast::Expr> > {
496     let mut p = parse::new_parser_from_tts(cx.parse_sess(),
497                                            cx.cfg(),
498                                            tts.iter()
499                                               .map(|x| (*x).clone())
500                                               .collect());
501     let mut es = Vec::new();
502     while p.token != token::EOF {
503         if es.len() != 0 && !p.eat(&token::COMMA) {
504             cx.span_err(sp, "expected token: `,`");
505             return None;
506         }
507         es.push(cx.expand_expr(p.parse_expr()));
508     }
509     Some(es)
510 }
511
512 // in order to have some notion of scoping for macros,
513 // we want to implement the notion of a transformation
514 // environment.
515
516 // This environment maps Names to SyntaxExtensions.
517
518 //impl question: how to implement it? Initially, the
519 // env will contain only macros, so it might be painful
520 // to add an empty frame for every context. Let's just
521 // get it working, first....
522
523 // NB! the mutability of the underlying maps means that
524 // if expansion is out-of-order, a deeper scope may be
525 // able to refer to a macro that was added to an enclosing
526 // scope lexically later than the deeper scope.
527
528 struct MapChainFrame {
529     info: BlockInfo,
530     map: HashMap<Name, SyntaxExtension>,
531 }
532
533 // Only generic to make it easy to test
534 pub struct SyntaxEnv {
535     priv chain: Vec<MapChainFrame> ,
536 }
537
538 impl SyntaxEnv {
539     pub fn new() -> SyntaxEnv {
540         let mut map = SyntaxEnv { chain: Vec::new() };
541         map.push_frame();
542         map
543     }
544
545     pub fn push_frame(&mut self) {
546         self.chain.push(MapChainFrame {
547             info: BlockInfo::new(),
548             map: HashMap::new(),
549         });
550     }
551
552     pub fn pop_frame(&mut self) {
553         assert!(self.chain.len() > 1, "too many pops on MapChain!");
554         self.chain.pop();
555     }
556
557     fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
558         for (i, frame) in self.chain.mut_iter().enumerate().rev() {
559             if !frame.info.macros_escape || i == 0 {
560                 return frame
561             }
562         }
563         unreachable!()
564     }
565
566     pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
567         for frame in self.chain.iter().rev() {
568             match frame.map.find(k) {
569                 Some(v) => return Some(v),
570                 None => {}
571             }
572         }
573         None
574     }
575
576     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
577         self.find_escape_frame().map.insert(k, v);
578     }
579
580     pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
581         let last_chain_index = self.chain.len() - 1;
582         &mut self.chain.get_mut(last_chain_index).info
583     }
584 }