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.
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.
13 use ext::base::ExtCtxt;
15 use ext::build::AstBuilder;
20 /// Quasiquoting works via token trees.
22 /// This is registered as a set of expression syntax extension called quote!
23 /// that lifts its argument token-tree to an AST representing the
24 /// construction of the same token tree, with token::SubstNt interpreted
25 /// as antiquotes (splices).
30 use ext::base::ExtCtxt;
31 use parse::{self, token, classify};
35 use ast::{TokenTree, Expr};
37 pub use parse::new_parser_from_tts;
38 pub use codemap::{BytePos, Span, dummy_spanned, DUMMY_SP};
41 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree>;
44 impl ToTokens for TokenTree {
45 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
50 impl<T: ToTokens> ToTokens for Vec<T> {
51 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
52 self.iter().flat_map(|t| t.to_tokens(cx)).collect()
56 impl<T: ToTokens> ToTokens for Spanned<T> {
57 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
58 // FIXME: use the span?
59 self.node.to_tokens(cx)
63 impl<T: ToTokens> ToTokens for Option<T> {
64 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
66 &Some(ref t) => t.to_tokens(cx),
72 impl ToTokens for ast::Ident {
73 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
74 vec![ast::TtToken(DUMMY_SP, token::Ident(*self, token::Plain))]
78 impl ToTokens for ast::Path {
79 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
80 vec![ast::TtToken(DUMMY_SP, token::Interpolated(token::NtPath(Box::new(self.clone()))))]
84 impl ToTokens for ast::Ty {
85 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
86 vec![ast::TtToken(self.span, token::Interpolated(token::NtTy(P(self.clone()))))]
90 impl ToTokens for ast::Block {
91 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
92 vec![ast::TtToken(self.span, token::Interpolated(token::NtBlock(P(self.clone()))))]
96 impl ToTokens for ast::Generics {
97 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
98 vec![ast::TtToken(DUMMY_SP, token::Interpolated(token::NtGenerics(self.clone())))]
102 impl ToTokens for ast::WhereClause {
103 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
104 vec![ast::TtToken(DUMMY_SP, token::Interpolated(token::NtWhereClause(self.clone())))]
108 impl ToTokens for P<ast::Item> {
109 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
110 vec![ast::TtToken(self.span, token::Interpolated(token::NtItem(self.clone())))]
114 impl ToTokens for P<ast::ImplItem> {
115 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
116 vec![ast::TtToken(self.span, token::Interpolated(token::NtImplItem(self.clone())))]
120 impl ToTokens for P<ast::TraitItem> {
121 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
122 vec![ast::TtToken(self.span, token::Interpolated(token::NtTraitItem(self.clone())))]
126 impl ToTokens for P<ast::Stmt> {
127 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
129 ast::TtToken(self.span, token::Interpolated(token::NtStmt(self.clone())))
132 // Some statements require a trailing semicolon.
133 if classify::stmt_ends_with_semi(&self.node) {
134 tts.push(ast::TtToken(self.span, token::Semi));
141 impl ToTokens for P<ast::Expr> {
142 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
143 vec![ast::TtToken(self.span, token::Interpolated(token::NtExpr(self.clone())))]
147 impl ToTokens for P<ast::Pat> {
148 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
149 vec![ast::TtToken(self.span, token::Interpolated(token::NtPat(self.clone())))]
153 impl ToTokens for ast::Arm {
154 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
155 vec![ast::TtToken(DUMMY_SP, token::Interpolated(token::NtArm(self.clone())))]
159 macro_rules! impl_to_tokens_slice {
160 ($t: ty, $sep: expr) => {
161 impl ToTokens for [$t] {
162 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
164 for (i, x) in self.iter().enumerate() {
168 v.extend(x.to_tokens(cx));
176 impl_to_tokens_slice! { ast::Ty, [ast::TtToken(DUMMY_SP, token::Comma)] }
177 impl_to_tokens_slice! { P<ast::Item>, [] }
179 impl ToTokens for P<ast::MetaItem> {
180 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
181 vec![ast::TtToken(DUMMY_SP, token::Interpolated(token::NtMeta(self.clone())))]
185 impl ToTokens for ast::Attribute {
186 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
188 // FIXME: The spans could be better
189 r.push(ast::TtToken(self.span, token::Pound));
190 if self.node.style == ast::AttrInner {
191 r.push(ast::TtToken(self.span, token::Not));
193 r.push(ast::TtDelimited(self.span, Rc::new(ast::Delimited {
194 delim: token::Bracket,
195 open_span: self.span,
196 tts: self.node.value.to_tokens(cx),
197 close_span: self.span,
203 impl ToTokens for str {
204 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
205 let lit = ast::LitStr(
206 token::intern_and_get_ident(self), ast::CookedStr);
207 dummy_spanned(lit).to_tokens(cx)
211 impl ToTokens for () {
212 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
213 vec![ast::TtDelimited(DUMMY_SP, Rc::new(ast::Delimited {
217 close_span: DUMMY_SP,
222 impl ToTokens for ast::Lit {
223 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
224 // FIXME: This is wrong
226 id: ast::DUMMY_NODE_ID,
227 node: ast::ExprLit(P(self.clone())),
233 impl ToTokens for bool {
234 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
235 dummy_spanned(ast::LitBool(*self)).to_tokens(cx)
239 impl ToTokens for char {
240 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
241 dummy_spanned(ast::LitChar(*self)).to_tokens(cx)
245 macro_rules! impl_to_tokens_int {
246 (signed, $t:ty, $tag:expr) => (
247 impl ToTokens for $t {
248 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
249 let lit = ast::LitInt(*self as u64, ast::SignedIntLit($tag,
250 ast::Sign::new(*self)));
251 dummy_spanned(lit).to_tokens(cx)
255 (unsigned, $t:ty, $tag:expr) => (
256 impl ToTokens for $t {
257 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
258 let lit = ast::LitInt(*self as u64, ast::UnsignedIntLit($tag));
259 dummy_spanned(lit).to_tokens(cx)
265 impl_to_tokens_int! { signed, isize, ast::TyIs }
266 impl_to_tokens_int! { signed, i8, ast::TyI8 }
267 impl_to_tokens_int! { signed, i16, ast::TyI16 }
268 impl_to_tokens_int! { signed, i32, ast::TyI32 }
269 impl_to_tokens_int! { signed, i64, ast::TyI64 }
271 impl_to_tokens_int! { unsigned, usize, ast::TyUs }
272 impl_to_tokens_int! { unsigned, u8, ast::TyU8 }
273 impl_to_tokens_int! { unsigned, u16, ast::TyU16 }
274 impl_to_tokens_int! { unsigned, u32, ast::TyU32 }
275 impl_to_tokens_int! { unsigned, u64, ast::TyU64 }
277 pub trait ExtParseUtils {
278 fn parse_item(&self, s: String) -> P<ast::Item>;
279 fn parse_expr(&self, s: String) -> P<ast::Expr>;
280 fn parse_stmt(&self, s: String) -> P<ast::Stmt>;
281 fn parse_tts(&self, s: String) -> Vec<ast::TokenTree>;
284 impl<'a> ExtParseUtils for ExtCtxt<'a> {
286 fn parse_item(&self, s: String) -> P<ast::Item> {
287 parse::parse_item_from_source_str(
288 "<quote expansion>".to_string(),
291 self.parse_sess()).expect("parse error")
294 fn parse_stmt(&self, s: String) -> P<ast::Stmt> {
295 parse::parse_stmt_from_source_str("<quote expansion>".to_string(),
298 self.parse_sess()).expect("parse error")
301 fn parse_expr(&self, s: String) -> P<ast::Expr> {
302 parse::parse_expr_from_source_str("<quote expansion>".to_string(),
308 fn parse_tts(&self, s: String) -> Vec<ast::TokenTree> {
309 parse::parse_tts_from_source_str("<quote expansion>".to_string(),
317 pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt,
319 tts: &[ast::TokenTree])
320 -> Box<base::MacResult+'cx> {
321 let (cx_expr, expr) = expand_tts(cx, sp, tts);
322 let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]);
323 base::MacEager::expr(expanded)
326 pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt,
328 tts: &[ast::TokenTree])
329 -> Box<base::MacResult+'cx> {
330 let expanded = expand_parse_call(cx, sp, "parse_expr", vec!(), tts);
331 base::MacEager::expr(expanded)
334 pub fn expand_quote_item<'cx>(cx: &mut ExtCtxt,
336 tts: &[ast::TokenTree])
337 -> Box<base::MacResult+'cx> {
338 let expanded = expand_parse_call(cx, sp, "parse_item", vec!(), tts);
339 base::MacEager::expr(expanded)
342 pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt,
344 tts: &[ast::TokenTree])
345 -> Box<base::MacResult+'cx> {
346 let expanded = expand_parse_call(cx, sp, "parse_pat", vec!(), tts);
347 base::MacEager::expr(expanded)
350 pub fn expand_quote_arm(cx: &mut ExtCtxt,
352 tts: &[ast::TokenTree])
353 -> Box<base::MacResult+'static> {
354 let expanded = expand_parse_call(cx, sp, "parse_arm", vec!(), tts);
355 base::MacEager::expr(expanded)
358 pub fn expand_quote_ty(cx: &mut ExtCtxt,
360 tts: &[ast::TokenTree])
361 -> Box<base::MacResult+'static> {
362 let expanded = expand_parse_call(cx, sp, "parse_ty", vec!(), tts);
363 base::MacEager::expr(expanded)
366 pub fn expand_quote_stmt(cx: &mut ExtCtxt,
368 tts: &[ast::TokenTree])
369 -> Box<base::MacResult+'static> {
370 let expanded = expand_parse_call(cx, sp, "parse_stmt", vec!(), tts);
371 base::MacEager::expr(expanded)
374 pub fn expand_quote_attr(cx: &mut ExtCtxt,
376 tts: &[ast::TokenTree])
377 -> Box<base::MacResult+'static> {
378 let expanded = expand_parse_call(cx, sp, "parse_attribute",
379 vec!(cx.expr_bool(sp, true)), tts);
381 base::MacEager::expr(expanded)
384 pub fn expand_quote_matcher(cx: &mut ExtCtxt,
386 tts: &[ast::TokenTree])
387 -> Box<base::MacResult+'static> {
388 let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
389 let mut vector = mk_stmts_let(cx, sp);
390 vector.extend(statements_mk_tts(cx, &tts[..], true));
391 let block = cx.expr_block(
394 Some(cx.expr_ident(sp, id_ext("tt")))));
396 let expanded = expand_wrapper(cx, sp, cx_expr, block, &[&["syntax", "ext", "quote", "rt"]]);
397 base::MacEager::expr(expanded)
400 fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> {
401 strs.iter().map(|str| str_to_ident(&(*str))).collect()
404 fn id_ext(str: &str) -> ast::Ident {
408 // Lift an ident to the expr that evaluates to that ident.
409 fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
410 let e_str = cx.expr_str(sp, ident.name.as_str());
411 cx.expr_method_call(sp,
412 cx.expr_ident(sp, id_ext("ext_cx")),
417 // Lift a name to the expr that evaluates to that name
418 fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
419 let e_str = cx.expr_str(sp, ident.name.as_str());
420 cx.expr_method_call(sp,
421 cx.expr_ident(sp, id_ext("ext_cx")),
426 fn mk_ast_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
427 let idents = vec!(id_ext("syntax"), id_ext("ast"), id_ext(name));
428 cx.expr_path(cx.path_global(sp, idents))
431 fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
432 let idents = vec!(id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name));
433 cx.expr_path(cx.path_global(sp, idents))
436 fn mk_binop(cx: &ExtCtxt, sp: Span, bop: token::BinOpToken) -> P<ast::Expr> {
437 let name = match bop {
438 token::Plus => "Plus",
439 token::Minus => "Minus",
440 token::Star => "Star",
441 token::Slash => "Slash",
442 token::Percent => "Percent",
443 token::Caret => "Caret",
449 mk_token_path(cx, sp, name)
452 fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> {
453 let name = match delim {
454 token::Paren => "Paren",
455 token::Bracket => "Bracket",
456 token::Brace => "Brace",
458 mk_token_path(cx, sp, name)
461 #[allow(non_upper_case_globals)]
462 fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
463 macro_rules! mk_lit {
464 ($name: expr, $suffix: expr, $($args: expr),*) => {{
465 let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]);
466 let suffix = match $suffix {
467 Some(name) => cx.expr_some(sp, mk_name(cx, sp, ast::Ident::new(name))),
468 None => cx.expr_none(sp)
470 cx.expr_call(sp, mk_token_path(cx, sp, "Literal"), vec![inner, suffix])
474 token::BinOp(binop) => {
475 return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec!(mk_binop(cx, sp, binop)));
477 token::BinOpEq(binop) => {
478 return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"),
479 vec!(mk_binop(cx, sp, binop)));
482 token::OpenDelim(delim) => {
483 return cx.expr_call(sp, mk_token_path(cx, sp, "OpenDelim"),
484 vec![mk_delim(cx, sp, delim)]);
486 token::CloseDelim(delim) => {
487 return cx.expr_call(sp, mk_token_path(cx, sp, "CloseDelim"),
488 vec![mk_delim(cx, sp, delim)]);
491 token::Literal(token::Byte(i), suf) => {
492 let e_byte = mk_name(cx, sp, i.ident());
493 return mk_lit!("Byte", suf, e_byte);
496 token::Literal(token::Char(i), suf) => {
497 let e_char = mk_name(cx, sp, i.ident());
498 return mk_lit!("Char", suf, e_char);
501 token::Literal(token::Integer(i), suf) => {
502 let e_int = mk_name(cx, sp, i.ident());
503 return mk_lit!("Integer", suf, e_int);
506 token::Literal(token::Float(fident), suf) => {
507 let e_fident = mk_name(cx, sp, fident.ident());
508 return mk_lit!("Float", suf, e_fident);
511 token::Literal(token::Str_(ident), suf) => {
512 return mk_lit!("Str_", suf, mk_name(cx, sp, ident.ident()))
515 token::Literal(token::StrRaw(ident, n), suf) => {
516 return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_usize(sp, n))
519 token::Ident(ident, style) => {
520 return cx.expr_call(sp,
521 mk_token_path(cx, sp, "Ident"),
522 vec![mk_ident(cx, sp, ident),
524 ModName => mk_token_path(cx, sp, "ModName"),
525 Plain => mk_token_path(cx, sp, "Plain"),
529 token::Lifetime(ident) => {
530 return cx.expr_call(sp,
531 mk_token_path(cx, sp, "Lifetime"),
532 vec!(mk_ident(cx, sp, ident)));
535 token::DocComment(ident) => {
536 return cx.expr_call(sp,
537 mk_token_path(cx, sp, "DocComment"),
538 vec!(mk_name(cx, sp, ident.ident())));
541 token::MatchNt(name, kind, namep, kindp) => {
542 return cx.expr_call(sp,
543 mk_token_path(cx, sp, "MatchNt"),
544 vec!(mk_ident(cx, sp, name),
545 mk_ident(cx, sp, kind),
547 ModName => mk_token_path(cx, sp, "ModName"),
548 Plain => mk_token_path(cx, sp, "Plain"),
551 ModName => mk_token_path(cx, sp, "ModName"),
552 Plain => mk_token_path(cx, sp, "Plain"),
556 token::Interpolated(_) => panic!("quote! with interpolated token"),
561 let name = match *tok {
565 token::EqEq => "EqEq",
569 token::AndAnd => "AndAnd",
570 token::OrOr => "OrOr",
572 token::Tilde => "Tilde",
575 token::DotDot => "DotDot",
576 token::Comma => "Comma",
577 token::Semi => "Semi",
578 token::Colon => "Colon",
579 token::ModSep => "ModSep",
580 token::RArrow => "RArrow",
581 token::LArrow => "LArrow",
582 token::FatArrow => "FatArrow",
583 token::Pound => "Pound",
584 token::Dollar => "Dollar",
585 token::Question => "Question",
586 token::Underscore => "Underscore",
588 _ => panic!("unhandled token in quote!"),
590 mk_token_path(cx, sp, name)
593 fn statements_mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree, matcher: bool) -> Vec<P<ast::Stmt>> {
595 ast::TtToken(sp, SubstNt(ident, _)) => {
596 // tt.extend($ident.to_tokens(ext_cx))
599 cx.expr_method_call(sp,
600 cx.expr_ident(sp, ident),
602 vec!(cx.expr_ident(sp, id_ext("ext_cx"))));
604 cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]);
607 cx.expr_method_call(sp,
608 cx.expr_ident(sp, id_ext("tt")),
612 vec!(cx.stmt_expr(e_push))
614 ref tt @ ast::TtToken(_, MatchNt(..)) if !matcher => {
615 let mut seq = vec![];
616 for i in 0..tt.len() {
617 seq.push(tt.get_tt(i));
619 statements_mk_tts(cx, &seq[..], matcher)
621 ast::TtToken(sp, ref tok) => {
622 let e_sp = cx.expr_ident(sp, id_ext("_sp"));
623 let e_tok = cx.expr_call(sp,
624 mk_ast_path(cx, sp, "TtToken"),
625 vec!(e_sp, expr_mk_token(cx, sp, tok)));
627 cx.expr_method_call(sp,
628 cx.expr_ident(sp, id_ext("tt")),
631 vec!(cx.stmt_expr(e_push))
633 ast::TtDelimited(_, ref delimed) => {
634 statements_mk_tt(cx, &delimed.open_tt(), matcher).into_iter()
635 .chain(delimed.tts.iter()
636 .flat_map(|tt| statements_mk_tt(cx, tt, matcher)))
637 .chain(statements_mk_tt(cx, &delimed.close_tt(), matcher))
640 ast::TtSequence(sp, ref seq) => {
642 panic!("TtSequence in quote!");
645 let e_sp = cx.expr_ident(sp, id_ext("_sp"));
647 let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
648 let mut tts_stmts = vec![stmt_let_tt];
649 tts_stmts.extend(statements_mk_tts(cx, &seq.tts[..], matcher));
650 let e_tts = cx.expr_block(cx.block(sp, tts_stmts,
651 Some(cx.expr_ident(sp, id_ext("tt")))));
652 let e_separator = match seq.separator {
653 Some(ref sep) => cx.expr_some(sp, expr_mk_token(cx, sp, sep)),
654 None => cx.expr_none(sp),
656 let e_op = match seq.op {
657 ast::ZeroOrMore => mk_ast_path(cx, sp, "ZeroOrMore"),
658 ast::OneOrMore => mk_ast_path(cx, sp, "OneOrMore"),
660 let fields = vec![cx.field_imm(sp, id_ext("tts"), e_tts),
661 cx.field_imm(sp, id_ext("separator"), e_separator),
662 cx.field_imm(sp, id_ext("op"), e_op),
663 cx.field_imm(sp, id_ext("num_captures"),
664 cx.expr_usize(sp, seq.num_captures))];
665 let seq_path = vec![id_ext("syntax"), id_ext("ast"), id_ext("SequenceRepetition")];
666 let e_seq_struct = cx.expr_struct(sp, cx.path_global(sp, seq_path), fields);
667 let e_rc_new = cx.expr_call_global(sp, vec![id_ext("std"),
672 let e_tok = cx.expr_call(sp,
673 mk_ast_path(cx, sp, "TtSequence"),
674 vec!(e_sp, e_rc_new));
676 cx.expr_method_call(sp,
677 cx.expr_ident(sp, id_ext("tt")),
680 vec!(cx.stmt_expr(e_push))
685 fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[ast::TokenTree])
686 -> (P<ast::Expr>, Vec<ast::TokenTree>) {
687 // NB: It appears that the main parser loses its mind if we consider
688 // $foo as a SubstNt during the main parse, so we have to re-parse
689 // under quote_depth > 0. This is silly and should go away; the _guess_ is
690 // it has to do with transition away from supporting old-style macros, so
691 // try removing it when enough of them are gone.
693 let mut p = cx.new_parser_from_tts(tts);
696 let cx_expr = p.parse_expr();
697 if !panictry!(p.eat(&token::Comma)) {
698 panic!(p.fatal("expected token `,`"));
701 let tts = panictry!(p.parse_all_token_trees());
707 fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<P<ast::Stmt>> {
708 // We also bind a single value, sp, to ext_cx.call_site()
710 // This causes every span in a token-tree quote to be attributed to the
711 // call site of the extension using the quote. We can't really do much
712 // better since the source of the quote may well be in a library that
713 // was not even parsed by this compilation run, that the user has no
714 // source code for (eg. in libsyntax, which they're just _using_).
716 // The old quasiquoter had an elaborate mechanism for denoting input
717 // file locations from which quotes originated; unfortunately this
718 // relied on feeding the source string of the quote back into the
719 // compiler (which we don't really want to do) and, in any case, only
720 // pushed the problem a very small step further back: an error
721 // resulting from a parse of the resulting quote is still attributed to
722 // the site the string literal occurred, which was in a source file
723 // _other_ than the one the user has control over. For example, an
724 // error in a quote from the protocol compiler, invoked in user code
725 // using macro_rules! for example, will be attributed to the macro_rules.rs
726 // file in libsyntax, which the user might not even have source to (unless
727 // they happen to have a compiler on hand). Over all, the phase distinction
728 // just makes quotes "hard to attribute". Possibly this could be fixed
729 // by recreating some of the original qq machinery in the tt regime
730 // (pushing fake FileMaps onto the parser to account for original sites
731 // of quotes, for example) but at this point it seems not likely to be
734 let e_sp = cx.expr_method_call(sp,
735 cx.expr_ident(sp, id_ext("ext_cx")),
739 let stmt_let_sp = cx.stmt_let(sp, false,
743 let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
745 vec!(stmt_let_sp, stmt_let_tt)
748 fn statements_mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], matcher: bool) -> Vec<P<ast::Stmt>> {
749 let mut ss = Vec::new();
751 ss.extend(statements_mk_tt(cx, tt, matcher));
756 fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
757 -> (P<ast::Expr>, P<ast::Expr>) {
758 let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
760 let mut vector = mk_stmts_let(cx, sp);
761 vector.extend(statements_mk_tts(cx, &tts[..], false));
762 let block = cx.expr_block(
765 Some(cx.expr_ident(sp, id_ext("tt")))));
770 fn expand_wrapper(cx: &ExtCtxt,
772 cx_expr: P<ast::Expr>,
774 imports: &[&[&str]]) -> P<ast::Expr> {
775 // Explicitly borrow to avoid moving from the invoker (#16992)
776 let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
777 let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
779 let stmts = imports.iter().map(|path| {
780 // make item: `use ...;`
781 let path = path.iter().map(|s| s.to_string()).collect();
782 cx.stmt_item(sp, cx.item_use_glob(sp, ast::Inherited, ids_ext(path)))
783 }).chain(Some(stmt_let_ext_cx)).collect();
785 cx.expr_block(cx.block_all(sp, stmts, Some(expr)))
788 fn expand_parse_call(cx: &ExtCtxt,
791 arg_exprs: Vec<P<ast::Expr>> ,
792 tts: &[ast::TokenTree]) -> P<ast::Expr> {
793 let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
795 let cfg_call = || cx.expr_method_call(
796 sp, cx.expr_ident(sp, id_ext("ext_cx")),
797 id_ext("cfg"), Vec::new());
799 let parse_sess_call = || cx.expr_method_call(
800 sp, cx.expr_ident(sp, id_ext("ext_cx")),
801 id_ext("parse_sess"), Vec::new());
803 let new_parser_call =
805 cx.expr_ident(sp, id_ext("new_parser_from_tts")),
806 vec!(parse_sess_call(), cfg_call(), tts_expr));
808 let expr = cx.expr_method_call(sp, new_parser_call, id_ext(parse_method),
811 if parse_method == "parse_attribute" {
812 expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"],
813 &["syntax", "parse", "attr"]])
815 expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]])