1 // Copyright 2012-2013 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.
14 use codemap::{CodeMap, Span, ExpnInfo};
19 use parse::token::{InternedString, intern, str_to_ident};
20 use util::small_vector::SmallVector;
22 use std::hashmap::HashMap;
23 use std::unstable::dynamic_lib::DynamicLibrary;
25 // new-style macro! tt code:
27 // MacResult, NormalTT, IdentTT
29 // also note that ast::Mac used to have a bunch of extraneous cases and
30 // is now probably a redundant AST node, can be merged with
38 pub type ItemDecorator =
39 fn(&ExtCtxt, Span, @ast::MetaItem, ~[@ast::Item]) -> ~[@ast::Item];
41 pub struct BasicMacroExpander {
42 expander: MacroExpanderFn,
46 pub trait MacroExpander {
50 token_tree: &[ast::TokenTree])
54 pub type MacroExpanderFn =
55 fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
58 impl MacroExpander for BasicMacroExpander {
62 token_tree: &[ast::TokenTree])
64 (self.expander)(ecx, span, token_tree)
68 pub struct BasicIdentMacroExpander {
69 expander: IdentMacroExpanderFn,
73 pub trait IdentMacroExpander {
78 token_tree: ~[ast::TokenTree])
82 impl IdentMacroExpander for BasicIdentMacroExpander {
87 token_tree: ~[ast::TokenTree])
89 (self.expander)(cx, sp, ident, token_tree)
93 pub type IdentMacroExpanderFn =
94 fn(&mut ExtCtxt, Span, ast::Ident, ~[ast::TokenTree]) -> MacResult;
96 pub type MacroCrateRegistrationFun =
97 fn(|ast::Name, SyntaxExtension|);
100 fn make_expr(&self) -> @ast::Expr;
101 fn make_items(&self) -> SmallVector<@ast::Item>;
102 fn make_stmt(&self) -> @ast::Stmt;
112 /// Create an empty expression MacResult; useful for satisfying
113 /// type signatures after emitting a non-fatal error (which stop
114 /// compilation well before the validity (or otherwise)) of the
115 /// expression are checked.
116 pub fn dummy_expr() -> MacResult {
118 id: ast::DUMMY_NODE_ID, node: ast::ExprLogLevel, span: codemap::DUMMY_SP
123 pub enum SyntaxExtension {
124 // #[deriving] and such
125 ItemDecorator(ItemDecorator),
127 // Token-tree expanders
128 NormalTT(~MacroExpander:'static, Option<Span>),
130 // An IdentTT is a macro that has an
131 // identifier in between the name of the
132 // macro and the argument. Currently,
133 // the only examples of this is
136 // perhaps macro_rules! will lose its odd special identifier argument,
137 // and this can go away also
138 IdentTT(~IdentMacroExpander:'static, Option<Span>),
141 pub struct BlockInfo {
142 // should macros escape from this scope?
143 macros_escape : bool,
144 // what are the pending renames?
145 pending_renames : RenameList,
146 // references for crates loaded in this scope
147 macro_crates: ~[DynamicLibrary],
151 pub fn new() -> BlockInfo {
153 macros_escape: false,
154 pending_renames: ~[],
160 // a list of ident->name renamings
161 pub type RenameList = ~[(ast::Ident,Name)];
163 // The base map of methods for expanding syntax extension
164 // AST nodes into full ASTs
165 pub fn syntax_expander_table() -> SyntaxEnv {
166 // utility function to simplify creating NormalTT syntax extensions
167 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
168 NormalTT(~BasicMacroExpander {
175 let mut syntax_expanders = SyntaxEnv::new();
176 syntax_expanders.insert(intern(&"macro_rules"),
177 IdentTT(~BasicIdentMacroExpander {
178 expander: ext::tt::macro_rules::add_new_extension,
182 syntax_expanders.insert(intern(&"fmt"),
183 builtin_normal_expander(
184 ext::fmt::expand_syntax_ext));
185 syntax_expanders.insert(intern(&"format_args"),
186 builtin_normal_expander(
187 ext::format::expand_args));
188 syntax_expanders.insert(intern(&"env"),
189 builtin_normal_expander(
190 ext::env::expand_env));
191 syntax_expanders.insert(intern(&"option_env"),
192 builtin_normal_expander(
193 ext::env::expand_option_env));
194 syntax_expanders.insert(intern("bytes"),
195 builtin_normal_expander(
196 ext::bytes::expand_syntax_ext));
197 syntax_expanders.insert(intern("concat_idents"),
198 builtin_normal_expander(
199 ext::concat_idents::expand_syntax_ext));
200 syntax_expanders.insert(intern("concat"),
201 builtin_normal_expander(
202 ext::concat::expand_syntax_ext));
203 syntax_expanders.insert(intern(&"log_syntax"),
204 builtin_normal_expander(
205 ext::log_syntax::expand_syntax_ext));
206 syntax_expanders.insert(intern(&"deriving"),
207 ItemDecorator(ext::deriving::expand_meta_deriving));
209 // Quasi-quoting expanders
210 syntax_expanders.insert(intern(&"quote_tokens"),
211 builtin_normal_expander(
212 ext::quote::expand_quote_tokens));
213 syntax_expanders.insert(intern(&"quote_expr"),
214 builtin_normal_expander(
215 ext::quote::expand_quote_expr));
216 syntax_expanders.insert(intern(&"quote_ty"),
217 builtin_normal_expander(
218 ext::quote::expand_quote_ty));
219 syntax_expanders.insert(intern(&"quote_item"),
220 builtin_normal_expander(
221 ext::quote::expand_quote_item));
222 syntax_expanders.insert(intern(&"quote_pat"),
223 builtin_normal_expander(
224 ext::quote::expand_quote_pat));
225 syntax_expanders.insert(intern(&"quote_stmt"),
226 builtin_normal_expander(
227 ext::quote::expand_quote_stmt));
229 syntax_expanders.insert(intern(&"line"),
230 builtin_normal_expander(
231 ext::source_util::expand_line));
232 syntax_expanders.insert(intern(&"col"),
233 builtin_normal_expander(
234 ext::source_util::expand_col));
235 syntax_expanders.insert(intern(&"file"),
236 builtin_normal_expander(
237 ext::source_util::expand_file));
238 syntax_expanders.insert(intern(&"stringify"),
239 builtin_normal_expander(
240 ext::source_util::expand_stringify));
241 syntax_expanders.insert(intern(&"include"),
242 builtin_normal_expander(
243 ext::source_util::expand_include));
244 syntax_expanders.insert(intern(&"include_str"),
245 builtin_normal_expander(
246 ext::source_util::expand_include_str));
247 syntax_expanders.insert(intern(&"include_bin"),
248 builtin_normal_expander(
249 ext::source_util::expand_include_bin));
250 syntax_expanders.insert(intern(&"module_path"),
251 builtin_normal_expander(
252 ext::source_util::expand_mod));
253 syntax_expanders.insert(intern(&"asm"),
254 builtin_normal_expander(
255 ext::asm::expand_asm));
256 syntax_expanders.insert(intern(&"cfg"),
257 builtin_normal_expander(
258 ext::cfg::expand_cfg));
259 syntax_expanders.insert(intern(&"trace_macros"),
260 builtin_normal_expander(
261 ext::trace_macros::expand_trace_macros));
265 pub struct MacroCrate {
270 pub trait CrateLoader {
271 fn load_crate(&mut self, crate: &ast::ViewItem) -> MacroCrate;
272 fn get_exported_macros(&mut self, crate_num: ast::CrateNum) -> ~[~str];
273 fn get_registrar_symbol(&mut self, crate_num: ast::CrateNum) -> Option<~str>;
276 // One of these is made during expansion and incrementally updated as we go;
277 // when a macro expansion occurs, the resulting nodes have the backtrace()
278 // -> expn_info of their expansion context stored into their span.
279 pub struct ExtCtxt<'a> {
280 parse_sess: @parse::ParseSess,
281 cfg: ast::CrateConfig,
282 backtrace: Option<@ExpnInfo>,
283 loader: &'a mut CrateLoader,
285 mod_path: ~[ast::Ident],
289 impl<'a> ExtCtxt<'a> {
290 pub fn new<'a>(parse_sess: @parse::ParseSess, cfg: ast::CrateConfig,
291 loader: &'a mut CrateLoader) -> ExtCtxt<'a> {
293 parse_sess: parse_sess,
302 pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
305 ast::ExprMac(..) => {
306 let mut expander = expand::MacroExpander {
307 extsbox: syntax_expander_table(),
310 e = expand::expand_expr(e, &mut expander);
317 pub fn codemap(&self) -> @CodeMap { self.parse_sess.cm }
318 pub fn parse_sess(&self) -> @parse::ParseSess { self.parse_sess }
319 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
320 pub fn call_site(&self) -> Span {
321 match self.backtrace {
322 Some(expn_info) => expn_info.call_site,
323 None => self.bug("missing top span")
326 pub fn print_backtrace(&self) { }
327 pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace }
328 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
329 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
330 pub fn mod_path(&self) -> ~[ast::Ident] { self.mod_path.clone() }
331 pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
333 ExpnInfo {call_site: cs, callee: ref callee} => {
336 call_site: Span {lo: cs.lo, hi: cs.hi,
337 expn_info: self.backtrace},
342 pub fn bt_pop(&mut self) {
343 match self.backtrace {
344 Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
345 _ => self.bug("tried to pop without a push")
348 /// Emit `msg` attached to `sp`, and stop compilation immediately.
350 /// `span_err` should be strongly prefered where-ever possible:
351 /// this should *only* be used when
352 /// - continuing has a high risk of flow-on errors (e.g. errors in
353 /// declaring a macro would cause all uses of that macro to
354 /// complain about "undefined macro"), or
355 /// - there is literally nothing else that can be done (however,
356 /// in most cases one can construct a dummy expression/item to
357 /// substitute; we never hit resolve/type-checking so the dummy
358 /// value doesn't have to match anything)
359 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
360 self.print_backtrace();
361 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
364 /// Emit `msg` attached to `sp`, without immediately stopping
367 /// Compilation will be stopped in the near future (at the end of
368 /// the macro expansion phase).
369 pub fn span_err(&self, sp: Span, msg: &str) {
370 self.print_backtrace();
371 self.parse_sess.span_diagnostic.span_err(sp, msg);
373 pub fn span_warn(&self, sp: Span, msg: &str) {
374 self.print_backtrace();
375 self.parse_sess.span_diagnostic.span_warn(sp, msg);
377 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
378 self.print_backtrace();
379 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
381 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
382 self.print_backtrace();
383 self.parse_sess.span_diagnostic.span_bug(sp, msg);
385 pub fn span_note(&self, sp: Span, msg: &str) {
386 self.print_backtrace();
387 self.parse_sess.span_diagnostic.span_note(sp, msg);
389 pub fn bug(&self, msg: &str) -> ! {
390 self.print_backtrace();
391 self.parse_sess.span_diagnostic.handler().bug(msg);
393 pub fn trace_macros(&self) -> bool {
396 pub fn set_trace_macros(&mut self, x: bool) {
399 pub fn ident_of(&self, st: &str) -> ast::Ident {
404 /// Extract a string literal from `expr`, emitting `err_msg` if `expr`
405 /// is not a string literal. This does not stop compilation on error,
406 /// merely emits a non-fatal error and returns None.
407 pub fn expr_to_str(cx: &ExtCtxt, expr: @ast::Expr, err_msg: &str)
408 -> Option<(InternedString, ast::StrStyle)> {
410 ast::ExprLit(l) => match l.node {
411 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
412 _ => cx.span_err(l.span, err_msg)
414 _ => cx.span_err(expr.span, err_msg)
419 /// Non-fatally assert that `tts` is empty. Note that this function
420 /// returns even when `tts` is non-empty, macros that *need* to stop
421 /// compilation should call
422 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
423 /// done as rarely as possible).
424 pub fn check_zero_tts(cx: &ExtCtxt,
426 tts: &[ast::TokenTree],
429 cx.span_err(sp, format!("{} takes no arguments", name));
433 /// Extract the string literal from the first token of `tts`. If this
434 /// is not a string literal, emit an error and return None.
435 pub fn get_single_str_from_tts(cx: &ExtCtxt,
437 tts: &[ast::TokenTree],
441 cx.span_err(sp, format!("{} takes 1 argument.", name));
444 ast::TTTok(_, token::LIT_STR(ident))
445 | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
446 let interned_str = token::get_ident(ident.name);
447 return Some(interned_str.get().to_str())
449 _ => cx.span_err(sp, format!("{} requires a string.", name)),
455 /// Extract comma-separated expressions from `tts`. If there is a
456 /// parsing error, emit a non-fatal error and return None.
457 pub fn get_exprs_from_tts(cx: &ExtCtxt,
459 tts: &[ast::TokenTree]) -> Option<~[@ast::Expr]> {
460 let mut p = parse::new_parser_from_tts(cx.parse_sess(),
464 while p.token != token::EOF {
465 if es.len() != 0 && !p.eat(&token::COMMA) {
466 cx.span_err(sp, "expected token: `,`");
469 es.push(p.parse_expr());
474 // in order to have some notion of scoping for macros,
475 // we want to implement the notion of a transformation
478 // This environment maps Names to SyntaxExtensions.
480 // Actually, the following implementation is parameterized
481 // by both key and value types.
483 //impl question: how to implement it? Initially, the
484 // env will contain only macros, so it might be painful
485 // to add an empty frame for every context. Let's just
486 // get it working, first....
488 // NB! the mutability of the underlying maps means that
489 // if expansion is out-of-order, a deeper scope may be
490 // able to refer to a macro that was added to an enclosing
491 // scope lexically later than the deeper scope.
493 struct MapChainFrame {
495 map: HashMap<Name, SyntaxExtension>,
499 impl Drop for MapChainFrame {
501 // make sure that syntax extension dtors run before we drop the libs
506 // Only generic to make it easy to test
507 pub struct SyntaxEnv {
508 priv chain: ~[MapChainFrame],
512 pub fn new() -> SyntaxEnv {
513 let mut map = SyntaxEnv { chain: ~[] };
518 pub fn push_frame(&mut self) {
519 self.chain.push(MapChainFrame {
520 info: BlockInfo::new(),
525 pub fn pop_frame(&mut self) {
526 assert!(self.chain.len() > 1, "too many pops on MapChain!");
530 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
531 for (i, frame) in self.chain.mut_iter().enumerate().rev() {
532 if !frame.info.macros_escape || i == 0 {
539 pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
540 for frame in self.chain.iter().rev() {
541 match frame.map.find(k) {
542 Some(v) => return Some(v),
549 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
550 self.find_escape_frame().map.insert(k, v);
553 pub fn insert_macro_crate(&mut self, lib: DynamicLibrary) {
554 self.find_escape_frame().info.macro_crates.push(lib);
557 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
558 &mut self.chain[self.chain.len()-1].info