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.
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 collections::HashMap;
24 // new-style macro! tt code:
26 // MacResult, NormalTT, IdentTT
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
37 pub type ItemDecorator =
38 fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item, |@ast::Item|);
40 pub type ItemModifier =
41 fn(&mut ExtCtxt, Span, @ast::MetaItem, @ast::Item) -> @ast::Item;
43 pub struct BasicMacroExpander {
44 expander: MacroExpanderFn,
48 pub trait MacroExpander {
52 token_tree: &[ast::TokenTree])
56 pub type MacroExpanderFn =
57 fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
60 impl MacroExpander for BasicMacroExpander {
64 token_tree: &[ast::TokenTree])
66 (self.expander)(ecx, span, token_tree)
70 pub struct BasicIdentMacroExpander {
71 expander: IdentMacroExpanderFn,
75 pub trait IdentMacroExpander {
80 token_tree: Vec<ast::TokenTree> )
84 impl IdentMacroExpander for BasicIdentMacroExpander {
89 token_tree: Vec<ast::TokenTree> )
91 (self.expander)(cx, sp, ident, token_tree)
95 pub type IdentMacroExpanderFn =
96 fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree> ) -> MacResult;
98 pub type MacroCrateRegistrationFun =
99 fn(|ast::Name, SyntaxExtension|);
102 fn make_expr(&self) -> @ast::Expr;
103 fn make_items(&self) -> SmallVector<@ast::Item>;
104 fn make_stmt(&self) -> @ast::Stmt;
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 {
121 id: ast::DUMMY_NODE_ID,
122 node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)),
126 pub fn dummy_expr(sp: codemap::Span) -> MacResult {
127 MRExpr(MacResult::raw_dummy_expr(sp))
129 pub fn dummy_any(sp: codemap::Span) -> MacResult {
130 MRAny(~DummyMacResult { sp: sp })
133 struct DummyMacResult {
136 impl AnyMacro for DummyMacResult {
137 fn make_expr(&self) -> @ast::Expr {
138 MacResult::raw_dummy_expr(self.sp)
140 fn make_items(&self) -> SmallVector<@ast::Item> {
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))
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
154 /// `#[deriving(...)]` is an `ItemDecorator`.
155 ItemDecorator(ItemDecorator),
157 /// A syntax extension that is attached to an item and modifies it
159 ItemModifier(ItemModifier),
161 /// A normal, function-like syntax extension.
163 /// `bytes!` is a `NormalTT`.
164 NormalTT(~MacroExpander:'static, Option<Span>),
166 /// A function-like syntax extension that has an extra ident before
169 /// `macro_rules!` is an `IdentTT`.
170 IdentTT(~IdentMacroExpander:'static, Option<Span>),
173 pub struct BlockInfo {
174 // should macros escape from this scope?
176 // what are the pending renames?
177 pending_renames: RenameList,
181 pub fn new() -> BlockInfo {
183 macros_escape: false,
184 pending_renames: Vec::new(),
189 // a list of ident->name renamings
190 pub type RenameList = Vec<(ast::Ident, Name)>;
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 {
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,
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));
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));
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));
294 pub struct MacroCrate {
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>;
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>,
314 mod_path: Vec<ast::Ident> ,
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> {
322 parse_sess: parse_sess,
325 mod_path: Vec::new(),
331 pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
334 ast::ExprMac(..) => {
335 let mut expander = expand::MacroExpander {
336 extsbox: syntax_expander_table(),
339 e = expand::expand_expr(e, &mut expander);
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")
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));
365 pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
367 ExpnInfo {call_site: cs, callee: ref callee} => {
370 call_site: Span {lo: cs.lo, hi: cs.hi,
371 expn_info: self.backtrace},
372 callee: (*callee).clone()
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")
383 /// Emit `msg` attached to `sp`, and stop compilation immediately.
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);
399 /// Emit `msg` attached to `sp`, without immediately stopping
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);
408 pub fn span_warn(&self, sp: Span, msg: &str) {
409 self.print_backtrace();
410 self.parse_sess.span_diagnostic.span_warn(sp, msg);
412 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
413 self.print_backtrace();
414 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
416 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
417 self.print_backtrace();
418 self.parse_sess.span_diagnostic.span_bug(sp, msg);
420 pub fn span_note(&self, sp: Span, msg: &str) {
421 self.print_backtrace();
422 self.parse_sess.span_diagnostic.span_note(sp, msg);
424 pub fn bug(&self, msg: &str) -> ! {
425 self.print_backtrace();
426 self.parse_sess.span_diagnostic.handler().bug(msg);
428 pub fn trace_macros(&self) -> bool {
431 pub fn set_trace_macros(&mut self, x: bool) {
434 pub fn ident_of(&self, st: &str) -> ast::Ident {
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);
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)
451 _ => cx.span_err(expr.span, err_msg)
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,
463 tts: &[ast::TokenTree],
466 cx.span_err(sp, format!("{} takes no arguments", name));
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,
474 tts: &[ast::TokenTree],
478 cx.span_err(sp, format!("{} takes 1 argument.", name));
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())
485 _ => cx.span_err(sp, format!("{} requires a string.", name)),
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,
495 tts: &[ast::TokenTree]) -> Option<Vec<@ast::Expr> > {
496 let mut p = parse::new_parser_from_tts(cx.parse_sess(),
499 .map(|x| (*x).clone())
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: `,`");
507 es.push(cx.expand_expr(p.parse_expr()));
512 // in order to have some notion of scoping for macros,
513 // we want to implement the notion of a transformation
516 // This environment maps Names to SyntaxExtensions.
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....
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.
528 struct MapChainFrame {
530 map: HashMap<Name, SyntaxExtension>,
533 // Only generic to make it easy to test
534 pub struct SyntaxEnv {
535 priv chain: Vec<MapChainFrame> ,
539 pub fn new() -> SyntaxEnv {
540 let mut map = SyntaxEnv { chain: Vec::new() };
545 pub fn push_frame(&mut self) {
546 self.chain.push(MapChainFrame {
547 info: BlockInfo::new(),
552 pub fn pop_frame(&mut self) {
553 assert!(self.chain.len() > 1, "too many pops on MapChain!");
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 {
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),
576 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
577 self.find_escape_frame().map.insert(k, v);
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