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