]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/ext/base.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libsyntax / ext / base.rs
1 // Copyright 2015 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 pub use self::SyntaxExtension::*;
12
13 use ast;
14 use ast::Name;
15 use codemap;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION, CompilerExpansion};
17 use ext;
18 use ext::expand;
19 use ext::tt::macro_rules;
20 use parse;
21 use parse::parser;
22 use parse::token;
23 use parse::token::{InternedString, intern, str_to_ident};
24 use ptr::P;
25 use util::small_vector::SmallVector;
26 use ext::mtwt;
27 use fold::Folder;
28
29 use std::collections::HashMap;
30 use std::rc::Rc;
31 use std::default::Default;
32
33 #[unstable(feature = "rustc_private")]
34 #[deprecated(since = "1.0.0", reason = "replaced by MultiItemDecorator")]
35 pub trait ItemDecorator {
36 fn expand(&self,
37 ecx: &mut ExtCtxt,
38 sp: Span,
39 meta_item: &ast::MetaItem,
40 item: &ast::Item,
41 push: &mut FnMut(P<ast::Item>));
42 }
43
44 #[allow(deprecated)]
45 #[unstable(feature = "rustc_private")]
46 #[deprecated(since = "1.0.0", reason = "replaced by MultiItemDecorator")]
47 impl<F> ItemDecorator for F
48 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, &mut FnMut(P<ast::Item>))
49 {
50 fn expand(&self,
51 ecx: &mut ExtCtxt,
52 sp: Span,
53 meta_item: &ast::MetaItem,
54 item: &ast::Item,
55 push: &mut FnMut(P<ast::Item>)) {
56 (*self)(ecx, sp, meta_item, item, push)
57 }
58 }
59
60 #[unstable(feature = "rustc_private")]
61 #[deprecated(since = "1.0.0", reason = "replaced by MultiItemModifier")]
62 pub trait ItemModifier {
63 fn expand(&self,
64 ecx: &mut ExtCtxt,
65 span: Span,
66 meta_item: &ast::MetaItem,
67 item: P<ast::Item>)
68 -> P<ast::Item>;
69 }
70
71 #[allow(deprecated)]
72 #[unstable(feature = "rustc_private")]
73 #[deprecated(since = "1.0.0", reason = "replaced by MultiItemModifier")]
74 impl<F> ItemModifier for F
75 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, P<ast::Item>) -> P<ast::Item>
76 {
77
78 fn expand(&self,
79 ecx: &mut ExtCtxt,
80 span: Span,
81 meta_item: &ast::MetaItem,
82 item: P<ast::Item>)
83 -> P<ast::Item> {
84 (*self)(ecx, span, meta_item, item)
85 }
86 }
87
88 #[derive(Debug,Clone)]
89 pub enum Annotatable {
90 Item(P<ast::Item>),
91 TraitItem(P<ast::TraitItem>),
92 ImplItem(P<ast::ImplItem>),
93 }
94
95 impl Annotatable {
96 pub fn attrs(&self) -> &[ast::Attribute] {
97 match *self {
98 Annotatable::Item(ref i) => &i.attrs,
99 Annotatable::TraitItem(ref ti) => &ti.attrs,
100 Annotatable::ImplItem(ref ii) => &ii.attrs,
101 }
102 }
103
104 pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
105 match self {
106 Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
107 attrs: attrs,
108 ..i
109 })),
110 Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
111 ast::TraitItem { attrs: attrs, ..ti }
112 })),
113 Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
114 ast::ImplItem { attrs: attrs, ..ii }
115 })),
116 }
117 }
118
119 pub fn expect_item(self) -> P<ast::Item> {
120 match self {
121 Annotatable::Item(i) => i,
122 _ => panic!("expected Item")
123 }
124 }
125
126 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
127 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
128 G: FnMut(Annotatable) -> Annotatable
129 {
130 match self {
131 Annotatable::Item(i) => Annotatable::Item(f(i)),
132 _ => or(self)
133 }
134 }
135
136 pub fn expect_trait_item(self) -> P<ast::TraitItem> {
137 match self {
138 Annotatable::TraitItem(i) => i,
139 _ => panic!("expected Item")
140 }
141 }
142
143 pub fn expect_impl_item(self) -> P<ast::ImplItem> {
144 match self {
145 Annotatable::ImplItem(i) => i,
146 _ => panic!("expected Item")
147 }
148 }
149 }
150
151 // A more flexible ItemDecorator.
152 pub trait MultiItemDecorator {
153 fn expand(&self,
154 ecx: &mut ExtCtxt,
155 sp: Span,
156 meta_item: &ast::MetaItem,
157 item: &Annotatable,
158 push: &mut FnMut(Annotatable));
159 }
160
161 impl<F> MultiItemDecorator for F
162 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
163 {
164 fn expand(&self,
165 ecx: &mut ExtCtxt,
166 sp: Span,
167 meta_item: &ast::MetaItem,
168 item: &Annotatable,
169 push: &mut FnMut(Annotatable)) {
170 (*self)(ecx, sp, meta_item, item, push)
171 }
172 }
173
174 // A more flexible ItemModifier (ItemModifier should go away, eventually, FIXME).
175 // meta_item is the annotation, item is the item being modified, parent_item
176 // is the impl or trait item is declared in if item is part of such a thing.
177 // FIXME Decorators should follow the same pattern too.
178 pub trait MultiItemModifier {
179 fn expand(&self,
180 ecx: &mut ExtCtxt,
181 span: Span,
182 meta_item: &ast::MetaItem,
183 item: Annotatable)
184 -> Annotatable;
185 }
186
187 impl<F> MultiItemModifier for F
188 where F: Fn(&mut ExtCtxt,
189 Span,
190 &ast::MetaItem,
191 Annotatable) -> Annotatable
192 {
193 fn expand(&self,
194 ecx: &mut ExtCtxt,
195 span: Span,
196 meta_item: &ast::MetaItem,
197 item: Annotatable)
198 -> Annotatable {
199 (*self)(ecx, span, meta_item, item)
200 }
201 }
202
203 /// Represents a thing that maps token trees to Macro Results
204 pub trait TTMacroExpander {
205 fn expand<'cx>(&self,
206 ecx: &'cx mut ExtCtxt,
207 span: Span,
208 token_tree: &[ast::TokenTree])
209 -> Box<MacResult+'cx>;
210 }
211
212 pub type MacroExpanderFn =
213 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
214
215 impl<F> TTMacroExpander for F
216 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
217 {
218 fn expand<'cx>(&self,
219 ecx: &'cx mut ExtCtxt,
220 span: Span,
221 token_tree: &[ast::TokenTree])
222 -> Box<MacResult+'cx> {
223 (*self)(ecx, span, token_tree)
224 }
225 }
226
227 pub trait IdentMacroExpander {
228 fn expand<'cx>(&self,
229 cx: &'cx mut ExtCtxt,
230 sp: Span,
231 ident: ast::Ident,
232 token_tree: Vec<ast::TokenTree> )
233 -> Box<MacResult+'cx>;
234 }
235
236 pub type IdentMacroExpanderFn =
237 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
238
239 impl<F> IdentMacroExpander for F
240 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
241 Vec<ast::TokenTree>) -> Box<MacResult+'cx>
242 {
243 fn expand<'cx>(&self,
244 cx: &'cx mut ExtCtxt,
245 sp: Span,
246 ident: ast::Ident,
247 token_tree: Vec<ast::TokenTree> )
248 -> Box<MacResult+'cx>
249 {
250 (*self)(cx, sp, ident, token_tree)
251 }
252 }
253
254 // Use a macro because forwarding to a simple function has type system issues
255 macro_rules! make_stmts_default {
256 ($me:expr) => {
257 $me.make_expr().map(|e| {
258 SmallVector::one(P(codemap::respan(
259 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
260 })
261 }
262 }
263
264 /// The result of a macro expansion. The return values of the various
265 /// methods are spliced into the AST at the callsite of the macro.
266 pub trait MacResult {
267 /// Create an expression.
268 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
269 None
270 }
271 /// Create zero or more items.
272 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
273 None
274 }
275
276 /// Create zero or more impl items.
277 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
278 None
279 }
280
281 /// Create a pattern.
282 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
283 None
284 }
285
286 /// Create zero or more statements.
287 ///
288 /// By default this attempts to create an expression statement,
289 /// returning None if that fails.
290 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
291 make_stmts_default!(self)
292 }
293 }
294
295 macro_rules! make_MacEager {
296 ( $( $fld:ident: $t:ty, )* ) => {
297 /// `MacResult` implementation for the common case where you've already
298 /// built each form of AST that you might return.
299 #[derive(Default)]
300 pub struct MacEager {
301 $(
302 pub $fld: Option<$t>,
303 )*
304 }
305
306 impl MacEager {
307 $(
308 pub fn $fld(v: $t) -> Box<MacResult> {
309 Box::new(MacEager {
310 $fld: Some(v),
311 ..Default::default()
312 })
313 }
314 )*
315 }
316 }
317 }
318
319 make_MacEager! {
320 expr: P<ast::Expr>,
321 pat: P<ast::Pat>,
322 items: SmallVector<P<ast::Item>>,
323 impl_items: SmallVector<P<ast::ImplItem>>,
324 stmts: SmallVector<P<ast::Stmt>>,
325 }
326
327 impl MacResult for MacEager {
328 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
329 self.expr
330 }
331
332 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
333 self.items
334 }
335
336 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
337 self.impl_items
338 }
339
340 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
341 match self.stmts.as_ref().map_or(0, |s| s.len()) {
342 0 => make_stmts_default!(self),
343 _ => self.stmts,
344 }
345 }
346
347 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
348 if let Some(p) = self.pat {
349 return Some(p);
350 }
351 if let Some(e) = self.expr {
352 if let ast::ExprLit(_) = e.node {
353 return Some(P(ast::Pat {
354 id: ast::DUMMY_NODE_ID,
355 span: e.span,
356 node: ast::PatLit(e),
357 }));
358 }
359 }
360 None
361 }
362 }
363
364 /// Fill-in macro expansion result, to allow compilation to continue
365 /// after hitting errors.
366 #[derive(Copy, Clone)]
367 pub struct DummyResult {
368 expr_only: bool,
369 span: Span
370 }
371
372 impl DummyResult {
373 /// Create a default MacResult that can be anything.
374 ///
375 /// Use this as a return value after hitting any errors and
376 /// calling `span_err`.
377 pub fn any(sp: Span) -> Box<MacResult+'static> {
378 Box::new(DummyResult { expr_only: false, span: sp })
379 }
380
381 /// Create a default MacResult that can only be an expression.
382 ///
383 /// Use this for macros that must expand to an expression, so even
384 /// if an error is encountered internally, the user will receive
385 /// an error that they also used it in the wrong place.
386 pub fn expr(sp: Span) -> Box<MacResult+'static> {
387 Box::new(DummyResult { expr_only: true, span: sp })
388 }
389
390 /// A plain dummy expression.
391 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
392 P(ast::Expr {
393 id: ast::DUMMY_NODE_ID,
394 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
395 span: sp,
396 })
397 }
398
399 /// A plain dummy pattern.
400 pub fn raw_pat(sp: Span) -> ast::Pat {
401 ast::Pat {
402 id: ast::DUMMY_NODE_ID,
403 node: ast::PatWild(ast::PatWildSingle),
404 span: sp,
405 }
406 }
407
408 }
409
410 impl MacResult for DummyResult {
411 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
412 Some(DummyResult::raw_expr(self.span))
413 }
414 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
415 Some(P(DummyResult::raw_pat(self.span)))
416 }
417 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
418 // this code needs a comment... why not always just return the Some() ?
419 if self.expr_only {
420 None
421 } else {
422 Some(SmallVector::zero())
423 }
424 }
425 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
426 if self.expr_only {
427 None
428 } else {
429 Some(SmallVector::zero())
430 }
431 }
432 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Stmt>>> {
433 Some(SmallVector::one(P(
434 codemap::respan(self.span,
435 ast::StmtExpr(DummyResult::raw_expr(self.span),
436 ast::DUMMY_NODE_ID)))))
437 }
438 }
439
440 /// An enum representing the different kinds of syntax extensions.
441 pub enum SyntaxExtension {
442 /// A syntax extension that is attached to an item and creates new items
443 /// based upon it.
444 #[unstable(feature = "rustc_private")]
445 #[deprecated(since = "1.0.0", reason = "replaced by MultiDecorator")]
446 #[allow(deprecated)]
447 Decorator(Box<ItemDecorator + 'static>),
448
449 /// A syntax extension that is attached to an item and creates new items
450 /// based upon it.
451 ///
452 /// `#[derive(...)]` is a `MultiItemDecorator`.
453 MultiDecorator(Box<MultiItemDecorator + 'static>),
454
455 /// A syntax extension that is attached to an item and modifies it
456 /// in-place.
457 #[unstable(feature = "rustc_private")]
458 #[deprecated(since = "1.0.0", reason = "replaced by MultiModifier")]
459 #[allow(deprecated)]
460 Modifier(Box<ItemModifier + 'static>),
461
462 /// A syntax extension that is attached to an item and modifies it
463 /// in-place. More flexible version than Modifier.
464 MultiModifier(Box<MultiItemModifier + 'static>),
465
466 /// A normal, function-like syntax extension.
467 ///
468 /// `bytes!` is a `NormalTT`.
469 ///
470 /// The `bool` dictates whether the contents of the macro can
471 /// directly use `#[unstable]` things (true == yes).
472 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>, bool),
473
474 /// A function-like syntax extension that has an extra ident before
475 /// the block.
476 ///
477 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
478
479 /// Represents `macro_rules!` itself.
480 MacroRulesTT,
481 }
482
483 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
484
485 pub struct BlockInfo {
486 /// Should macros escape from this scope?
487 pub macros_escape: bool,
488 /// What are the pending renames?
489 pub pending_renames: mtwt::RenameList,
490 }
491
492 impl BlockInfo {
493 pub fn new() -> BlockInfo {
494 BlockInfo {
495 macros_escape: false,
496 pending_renames: Vec::new(),
497 }
498 }
499 }
500
501 /// The base map of methods for expanding syntax extension
502 /// AST nodes into full ASTs
503 fn initial_syntax_expander_table<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
504 -> SyntaxEnv {
505 // utility function to simplify creating NormalTT syntax extensions
506 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
507 NormalTT(Box::new(f), None, false)
508 }
509
510 let mut syntax_expanders = SyntaxEnv::new();
511 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
512 syntax_expanders.insert(intern("format_args"),
513 // format_args uses `unstable` things internally.
514 NormalTT(Box::new(ext::format::expand_format_args), None, true));
515 syntax_expanders.insert(intern("env"),
516 builtin_normal_expander(
517 ext::env::expand_env));
518 syntax_expanders.insert(intern("option_env"),
519 builtin_normal_expander(
520 ext::env::expand_option_env));
521 syntax_expanders.insert(intern("concat_idents"),
522 builtin_normal_expander(
523 ext::concat_idents::expand_syntax_ext));
524 syntax_expanders.insert(intern("concat"),
525 builtin_normal_expander(
526 ext::concat::expand_syntax_ext));
527 syntax_expanders.insert(intern("log_syntax"),
528 builtin_normal_expander(
529 ext::log_syntax::expand_syntax_ext));
530
531 ext::deriving::register_all(&mut syntax_expanders);
532
533 if ecfg.enable_quotes() {
534 // Quasi-quoting expanders
535 syntax_expanders.insert(intern("quote_tokens"),
536 builtin_normal_expander(
537 ext::quote::expand_quote_tokens));
538 syntax_expanders.insert(intern("quote_expr"),
539 builtin_normal_expander(
540 ext::quote::expand_quote_expr));
541 syntax_expanders.insert(intern("quote_ty"),
542 builtin_normal_expander(
543 ext::quote::expand_quote_ty));
544 syntax_expanders.insert(intern("quote_item"),
545 builtin_normal_expander(
546 ext::quote::expand_quote_item));
547 syntax_expanders.insert(intern("quote_pat"),
548 builtin_normal_expander(
549 ext::quote::expand_quote_pat));
550 syntax_expanders.insert(intern("quote_arm"),
551 builtin_normal_expander(
552 ext::quote::expand_quote_arm));
553 syntax_expanders.insert(intern("quote_stmt"),
554 builtin_normal_expander(
555 ext::quote::expand_quote_stmt));
556 syntax_expanders.insert(intern("quote_matcher"),
557 builtin_normal_expander(
558 ext::quote::expand_quote_matcher));
559 syntax_expanders.insert(intern("quote_attr"),
560 builtin_normal_expander(
561 ext::quote::expand_quote_attr));
562 }
563
564 syntax_expanders.insert(intern("line"),
565 builtin_normal_expander(
566 ext::source_util::expand_line));
567 syntax_expanders.insert(intern("column"),
568 builtin_normal_expander(
569 ext::source_util::expand_column));
570 syntax_expanders.insert(intern("file"),
571 builtin_normal_expander(
572 ext::source_util::expand_file));
573 syntax_expanders.insert(intern("stringify"),
574 builtin_normal_expander(
575 ext::source_util::expand_stringify));
576 syntax_expanders.insert(intern("include"),
577 builtin_normal_expander(
578 ext::source_util::expand_include));
579 syntax_expanders.insert(intern("include_str"),
580 builtin_normal_expander(
581 ext::source_util::expand_include_str));
582 syntax_expanders.insert(intern("include_bytes"),
583 builtin_normal_expander(
584 ext::source_util::expand_include_bytes));
585 syntax_expanders.insert(intern("module_path"),
586 builtin_normal_expander(
587 ext::source_util::expand_mod));
588 syntax_expanders.insert(intern("asm"),
589 builtin_normal_expander(
590 ext::asm::expand_asm));
591 syntax_expanders.insert(intern("cfg"),
592 builtin_normal_expander(
593 ext::cfg::expand_cfg));
594 syntax_expanders.insert(intern("push_unsafe"),
595 builtin_normal_expander(
596 ext::pushpop_safe::expand_push_unsafe));
597 syntax_expanders.insert(intern("pop_unsafe"),
598 builtin_normal_expander(
599 ext::pushpop_safe::expand_pop_unsafe));
600 syntax_expanders.insert(intern("trace_macros"),
601 builtin_normal_expander(
602 ext::trace_macros::expand_trace_macros));
603 syntax_expanders
604 }
605
606 /// One of these is made during expansion and incrementally updated as we go;
607 /// when a macro expansion occurs, the resulting nodes have the backtrace()
608 /// -> expn_info of their expansion context stored into their span.
609 pub struct ExtCtxt<'a> {
610 pub parse_sess: &'a parse::ParseSess,
611 pub cfg: ast::CrateConfig,
612 pub backtrace: ExpnId,
613 pub ecfg: expand::ExpansionConfig<'a>,
614 pub use_std: bool,
615
616 pub mod_path: Vec<ast::Ident> ,
617 pub exported_macros: Vec<ast::MacroDef>,
618
619 pub syntax_env: SyntaxEnv,
620 pub recursion_count: usize,
621 }
622
623 impl<'a> ExtCtxt<'a> {
624 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
625 ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
626 let env = initial_syntax_expander_table(&ecfg);
627 ExtCtxt {
628 parse_sess: parse_sess,
629 cfg: cfg,
630 backtrace: NO_EXPANSION,
631 mod_path: Vec::new(),
632 ecfg: ecfg,
633 use_std: true,
634 exported_macros: Vec::new(),
635 syntax_env: env,
636 recursion_count: 0,
637 }
638 }
639
640 #[unstable(feature = "rustc_private")]
641 #[deprecated(since = "1.0.0",
642 reason = "Replaced with `expander().fold_expr()`")]
643 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
644 self.expander().fold_expr(e)
645 }
646
647 /// Returns a `Folder` for deeply expanding all macros in a AST node.
648 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
649 expand::MacroExpander::new(self)
650 }
651
652 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
653 -> parser::Parser<'a> {
654 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
655 }
656
657 pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
658 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
659 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
660 pub fn call_site(&self) -> Span {
661 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
662 Some(expn_info) => expn_info.call_site,
663 None => self.bug("missing top span")
664 })
665 }
666 pub fn backtrace(&self) -> ExpnId { self.backtrace }
667
668 /// Original span that caused the current exapnsion to happen.
669 pub fn original_span(&self) -> Span {
670 let mut expn_id = self.backtrace;
671 let mut call_site = None;
672 loop {
673 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
674 None => break,
675 Some(cs) => {
676 call_site = Some(cs);
677 expn_id = cs.expn_id;
678 }
679 }
680 }
681 call_site.expect("missing expansion backtrace")
682 }
683
684 /// Returns span for the macro which originally caused the current expansion to happen.
685 ///
686 /// Stops backtracing at include! boundary.
687 pub fn expansion_cause(&self) -> Span {
688 let mut expn_id = self.backtrace;
689 let mut last_macro = None;
690 loop {
691 if self.codemap().with_expn_info(expn_id, |info| {
692 info.map_or(None, |i| {
693 if i.callee.name == "include" {
694 // Stop going up the backtrace once include! is encountered
695 return None;
696 }
697 expn_id = i.call_site.expn_id;
698 if i.callee.format != CompilerExpansion {
699 last_macro = Some(i.call_site)
700 }
701 return Some(());
702 })
703 }).is_none() {
704 break
705 }
706 }
707 last_macro.expect("missing expansion backtrace")
708 }
709
710 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
711 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
712 pub fn mod_path(&self) -> Vec<ast::Ident> {
713 let mut v = Vec::new();
714 v.push(token::str_to_ident(&self.ecfg.crate_name));
715 v.extend(self.mod_path.iter().cloned());
716 return v;
717 }
718 pub fn bt_push(&mut self, ei: ExpnInfo) {
719 self.recursion_count += 1;
720 if self.recursion_count > self.ecfg.recursion_limit {
721 panic!(self.span_fatal(ei.call_site,
722 &format!("recursion limit reached while expanding the macro `{}`",
723 ei.callee.name)));
724 }
725
726 let mut call_site = ei.call_site;
727 call_site.expn_id = self.backtrace;
728 self.backtrace = self.codemap().record_expansion(ExpnInfo {
729 call_site: call_site,
730 callee: ei.callee
731 });
732 }
733 pub fn bt_pop(&mut self) {
734 match self.backtrace {
735 NO_EXPANSION => self.bug("tried to pop without a push"),
736 expn_id => {
737 self.recursion_count -= 1;
738 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
739 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
740 });
741 }
742 }
743 }
744
745 pub fn insert_macro(&mut self, def: ast::MacroDef) {
746 if def.export {
747 self.exported_macros.push(def.clone());
748 }
749 if def.use_locally {
750 let ext = macro_rules::compile(self, &def);
751 self.syntax_env.insert(def.ident.name, ext);
752 }
753 }
754
755 /// Emit `msg` attached to `sp`, and stop compilation immediately.
756 ///
757 /// `span_err` should be strongly preferred where-ever possible:
758 /// this should *only* be used when
759 /// - continuing has a high risk of flow-on errors (e.g. errors in
760 /// declaring a macro would cause all uses of that macro to
761 /// complain about "undefined macro"), or
762 /// - there is literally nothing else that can be done (however,
763 /// in most cases one can construct a dummy expression/item to
764 /// substitute; we never hit resolve/type-checking so the dummy
765 /// value doesn't have to match anything)
766 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
767 panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
768 }
769
770 /// Emit `msg` attached to `sp`, without immediately stopping
771 /// compilation.
772 ///
773 /// Compilation will be stopped in the near future (at the end of
774 /// the macro expansion phase).
775 pub fn span_err(&self, sp: Span, msg: &str) {
776 self.parse_sess.span_diagnostic.span_err(sp, msg);
777 }
778 pub fn span_warn(&self, sp: Span, msg: &str) {
779 self.parse_sess.span_diagnostic.span_warn(sp, msg);
780 }
781 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
782 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
783 }
784 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
785 self.parse_sess.span_diagnostic.span_bug(sp, msg);
786 }
787 pub fn span_note(&self, sp: Span, msg: &str) {
788 self.parse_sess.span_diagnostic.span_note(sp, msg);
789 }
790 pub fn span_help(&self, sp: Span, msg: &str) {
791 self.parse_sess.span_diagnostic.span_help(sp, msg);
792 }
793 pub fn fileline_help(&self, sp: Span, msg: &str) {
794 self.parse_sess.span_diagnostic.fileline_help(sp, msg);
795 }
796 pub fn bug(&self, msg: &str) -> ! {
797 self.parse_sess.span_diagnostic.handler().bug(msg);
798 }
799 pub fn trace_macros(&self) -> bool {
800 self.ecfg.trace_mac
801 }
802 pub fn set_trace_macros(&mut self, x: bool) {
803 self.ecfg.trace_mac = x
804 }
805 pub fn ident_of(&self, st: &str) -> ast::Ident {
806 str_to_ident(st)
807 }
808 pub fn ident_of_std(&self, st: &str) -> ast::Ident {
809 self.ident_of(if self.use_std { "std" } else { st })
810 }
811 pub fn name_of(&self, st: &str) -> ast::Name {
812 token::intern(st)
813 }
814 }
815
816 /// Extract a string literal from the macro expanded version of `expr`,
817 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
818 /// compilation on error, merely emits a non-fatal error and returns None.
819 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
820 -> Option<(InternedString, ast::StrStyle)> {
821 // we want to be able to handle e.g. concat("foo", "bar")
822 let expr = cx.expander().fold_expr(expr);
823 match expr.node {
824 ast::ExprLit(ref l) => match l.node {
825 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
826 _ => cx.span_err(l.span, err_msg)
827 },
828 _ => cx.span_err(expr.span, err_msg)
829 }
830 None
831 }
832
833 /// Non-fatally assert that `tts` is empty. Note that this function
834 /// returns even when `tts` is non-empty, macros that *need* to stop
835 /// compilation should call
836 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
837 /// done as rarely as possible).
838 pub fn check_zero_tts(cx: &ExtCtxt,
839 sp: Span,
840 tts: &[ast::TokenTree],
841 name: &str) {
842 if !tts.is_empty() {
843 cx.span_err(sp, &format!("{} takes no arguments", name));
844 }
845 }
846
847 /// Extract the string literal from the first token of `tts`. If this
848 /// is not a string literal, emit an error and return None.
849 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
850 sp: Span,
851 tts: &[ast::TokenTree],
852 name: &str)
853 -> Option<String> {
854 let mut p = cx.new_parser_from_tts(tts);
855 if p.token == token::Eof {
856 cx.span_err(sp, &format!("{} takes 1 argument", name));
857 return None
858 }
859 let ret = cx.expander().fold_expr(p.parse_expr());
860 if p.token != token::Eof {
861 cx.span_err(sp, &format!("{} takes 1 argument", name));
862 }
863 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
864 s.to_string()
865 })
866 }
867
868 /// Extract comma-separated expressions from `tts`. If there is a
869 /// parsing error, emit a non-fatal error and return None.
870 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
871 sp: Span,
872 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
873 let mut p = cx.new_parser_from_tts(tts);
874 let mut es = Vec::new();
875 while p.token != token::Eof {
876 es.push(cx.expander().fold_expr(p.parse_expr()));
877 if panictry!(p.eat(&token::Comma)){
878 continue;
879 }
880 if p.token != token::Eof {
881 cx.span_err(sp, "expected token: `,`");
882 return None;
883 }
884 }
885 Some(es)
886 }
887
888 /// In order to have some notion of scoping for macros,
889 /// we want to implement the notion of a transformation
890 /// environment.
891 ///
892 /// This environment maps Names to SyntaxExtensions.
893 pub struct SyntaxEnv {
894 chain: Vec<MapChainFrame> ,
895 }
896
897 // impl question: how to implement it? Initially, the
898 // env will contain only macros, so it might be painful
899 // to add an empty frame for every context. Let's just
900 // get it working, first....
901
902 // NB! the mutability of the underlying maps means that
903 // if expansion is out-of-order, a deeper scope may be
904 // able to refer to a macro that was added to an enclosing
905 // scope lexically later than the deeper scope.
906
907 struct MapChainFrame {
908 info: BlockInfo,
909 map: HashMap<Name, Rc<SyntaxExtension>>,
910 }
911
912 impl SyntaxEnv {
913 fn new() -> SyntaxEnv {
914 let mut map = SyntaxEnv { chain: Vec::new() };
915 map.push_frame();
916 map
917 }
918
919 pub fn push_frame(&mut self) {
920 self.chain.push(MapChainFrame {
921 info: BlockInfo::new(),
922 map: HashMap::new(),
923 });
924 }
925
926 pub fn pop_frame(&mut self) {
927 assert!(self.chain.len() > 1, "too many pops on MapChain!");
928 self.chain.pop();
929 }
930
931 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
932 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
933 if !frame.info.macros_escape || i == 0 {
934 return frame
935 }
936 }
937 unreachable!()
938 }
939
940 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
941 for frame in self.chain.iter().rev() {
942 match frame.map.get(k) {
943 Some(v) => return Some(v.clone()),
944 None => {}
945 }
946 }
947 None
948 }
949
950 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
951 self.find_escape_frame().map.insert(k, Rc::new(v));
952 }
953
954 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
955 let last_chain_index = self.chain.len() - 1;
956 &mut self.chain[last_chain_index].info
957 }
958 }