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::ExprTup(Vec::new()),
126 pub fn dummy_expr(sp: codemap::Span) -> MacResult {
127 MRExpr(MacResult::raw_dummy_expr(sp))
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
136 /// `#[deriving(...)]` is an `ItemDecorator`.
137 ItemDecorator(ItemDecorator),
139 /// A syntax extension that is attached to an item and modifies it
141 ItemModifier(ItemModifier),
143 /// A normal, function-like syntax extension.
145 /// `bytes!` is a `NormalTT`.
146 NormalTT(~MacroExpander:'static, Option<Span>),
148 /// A function-like syntax extension that has an extra ident before
151 /// `macro_rules!` is an `IdentTT`.
152 IdentTT(~IdentMacroExpander:'static, Option<Span>),
155 pub struct BlockInfo {
156 // should macros escape from this scope?
158 // what are the pending renames?
159 pending_renames: RenameList,
163 pub fn new() -> BlockInfo {
165 macros_escape: false,
166 pending_renames: Vec::new(),
171 // a list of ident->name renamings
172 pub type RenameList = Vec<(ast::Ident, Name)>;
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 {
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,
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));
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));
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));
276 pub struct MacroCrate {
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>;
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>,
296 mod_path: Vec<ast::Ident> ,
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> {
304 parse_sess: parse_sess,
307 mod_path: Vec::new(),
313 pub fn expand_expr(&mut self, mut e: @ast::Expr) -> @ast::Expr {
316 ast::ExprMac(..) => {
317 let mut expander = expand::MacroExpander {
318 extsbox: syntax_expander_table(),
321 e = expand::expand_expr(e, &mut expander);
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")
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));
347 pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
349 ExpnInfo {call_site: cs, callee: ref callee} => {
352 call_site: Span {lo: cs.lo, hi: cs.hi,
353 expn_info: self.backtrace},
354 callee: (*callee).clone()
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")
365 /// Emit `msg` attached to `sp`, and stop compilation immediately.
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);
381 /// Emit `msg` attached to `sp`, without immediately stopping
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);
390 pub fn span_warn(&self, sp: Span, msg: &str) {
391 self.print_backtrace();
392 self.parse_sess.span_diagnostic.span_warn(sp, msg);
394 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
395 self.print_backtrace();
396 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
398 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
399 self.print_backtrace();
400 self.parse_sess.span_diagnostic.span_bug(sp, msg);
402 pub fn span_note(&self, sp: Span, msg: &str) {
403 self.print_backtrace();
404 self.parse_sess.span_diagnostic.span_note(sp, msg);
406 pub fn bug(&self, msg: &str) -> ! {
407 self.print_backtrace();
408 self.parse_sess.span_diagnostic.handler().bug(msg);
410 pub fn trace_macros(&self) -> bool {
413 pub fn set_trace_macros(&mut self, x: bool) {
416 pub fn ident_of(&self, st: &str) -> ast::Ident {
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);
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)
433 _ => cx.span_err(expr.span, err_msg)
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,
445 tts: &[ast::TokenTree],
448 cx.span_err(sp, format!("{} takes no arguments", name));
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,
456 tts: &[ast::TokenTree],
460 cx.span_err(sp, format!("{} takes 1 argument.", name));
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())
467 _ => cx.span_err(sp, format!("{} requires a string.", name)),
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,
477 tts: &[ast::TokenTree]) -> Option<Vec<@ast::Expr> > {
478 let mut p = parse::new_parser_from_tts(cx.parse_sess(),
481 .map(|x| (*x).clone())
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: `,`");
489 es.push(cx.expand_expr(p.parse_expr()));
494 // in order to have some notion of scoping for macros,
495 // we want to implement the notion of a transformation
498 // This environment maps Names to SyntaxExtensions.
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....
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.
510 struct MapChainFrame {
512 map: HashMap<Name, SyntaxExtension>,
515 // Only generic to make it easy to test
516 pub struct SyntaxEnv {
517 priv chain: Vec<MapChainFrame> ,
521 pub fn new() -> SyntaxEnv {
522 let mut map = SyntaxEnv { chain: Vec::new() };
527 pub fn push_frame(&mut self) {
528 self.chain.push(MapChainFrame {
529 info: BlockInfo::new(),
534 pub fn pop_frame(&mut self) {
535 assert!(self.chain.len() > 1, "too many pops on MapChain!");
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 {
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),
558 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
559 self.find_escape_frame().map.insert(k, v);
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