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