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.
11 use ast::{self, Arg, Arm, Block, Expr, Item, Pat, Stmt, Ty};
14 use ext::base::ExtCtxt;
16 use ext::build::AstBuilder;
17 use parse::parser::{Parser, PathStyle};
20 use tokenstream::{TokenStream, TokenTree};
22 /// Quasiquoting works via token trees.
24 /// This is registered as a set of expression syntax extension called quote!
25 /// that lifts its argument token-tree to an AST representing the
26 /// construction of the same token tree, with `token::SubstNt` interpreted
27 /// as antiquotes (splices).
32 use ext::base::ExtCtxt;
33 use parse::{self, classify};
34 use parse::token::{self, Token};
38 use tokenstream::{self, TokenTree, TokenStream};
40 pub use parse::new_parser_from_tts;
41 pub use syntax_pos::{BytePos, Span, DUMMY_SP, FileName};
42 pub use codemap::{dummy_spanned};
45 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree>;
48 impl ToTokens for TokenTree {
49 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
54 impl<T: ToTokens> ToTokens for Vec<T> {
55 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
56 self.iter().flat_map(|t| t.to_tokens(cx)).collect()
60 impl<T: ToTokens> ToTokens for Spanned<T> {
61 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
62 // FIXME: use the span?
63 self.node.to_tokens(cx)
67 impl<T: ToTokens> ToTokens for Option<T> {
68 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
70 Some(ref t) => t.to_tokens(cx),
76 impl ToTokens for ast::Ident {
77 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
78 vec![TokenTree::Token(DUMMY_SP, token::Ident(*self))]
82 impl ToTokens for ast::Path {
83 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
84 let nt = token::NtPath(self.clone());
85 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
89 impl ToTokens for ast::Ty {
90 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
91 let nt = token::NtTy(P(self.clone()));
92 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
96 impl ToTokens for ast::Block {
97 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
98 let nt = token::NtBlock(P(self.clone()));
99 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
103 impl ToTokens for ast::Generics {
104 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
105 let nt = token::NtGenerics(self.clone());
106 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
110 impl ToTokens for ast::WhereClause {
111 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
112 let nt = token::NtWhereClause(self.clone());
113 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
117 impl ToTokens for P<ast::Item> {
118 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
119 let nt = token::NtItem(self.clone());
120 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
124 impl ToTokens for ast::ImplItem {
125 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
126 let nt = token::NtImplItem(self.clone());
127 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
131 impl ToTokens for P<ast::ImplItem> {
132 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
133 let nt = token::NtImplItem((**self).clone());
134 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
138 impl ToTokens for ast::TraitItem {
139 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
140 let nt = token::NtTraitItem(self.clone());
141 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
145 impl ToTokens for ast::Stmt {
146 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
147 let nt = token::NtStmt(self.clone());
148 let mut tts = vec![TokenTree::Token(self.span, Token::interpolated(nt))];
150 // Some statements require a trailing semicolon.
151 if classify::stmt_ends_with_semi(&self.node) {
152 tts.push(TokenTree::Token(self.span, token::Semi));
159 impl ToTokens for P<ast::Expr> {
160 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
161 let nt = token::NtExpr(self.clone());
162 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
166 impl ToTokens for P<ast::Pat> {
167 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
168 let nt = token::NtPat(self.clone());
169 vec![TokenTree::Token(self.span, Token::interpolated(nt))]
173 impl ToTokens for ast::Arm {
174 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
175 let nt = token::NtArm(self.clone());
176 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
180 impl ToTokens for ast::Arg {
181 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
182 let nt = token::NtArg(self.clone());
183 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
187 impl ToTokens for P<ast::Block> {
188 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
189 let nt = token::NtBlock(self.clone());
190 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
194 impl ToTokens for ast::Lifetime {
195 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
196 vec![TokenTree::Token(DUMMY_SP, token::Lifetime(self.ident))]
200 macro_rules! impl_to_tokens_slice {
201 ($t: ty, $sep: expr) => {
202 impl ToTokens for [$t] {
203 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
205 for (i, x) in self.iter().enumerate() {
207 v.extend_from_slice(&$sep);
209 v.extend(x.to_tokens(cx));
217 impl_to_tokens_slice! { ast::Ty, [TokenTree::Token(DUMMY_SP, token::Comma)] }
218 impl_to_tokens_slice! { P<ast::Item>, [] }
219 impl_to_tokens_slice! { ast::Arg, [TokenTree::Token(DUMMY_SP, token::Comma)] }
221 impl ToTokens for ast::MetaItem {
222 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
223 let nt = token::NtMeta(self.clone());
224 vec![TokenTree::Token(DUMMY_SP, Token::interpolated(nt))]
228 impl ToTokens for ast::Attribute {
229 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
231 // FIXME: The spans could be better
232 r.push(TokenTree::Token(self.span, token::Pound));
233 if self.style == ast::AttrStyle::Inner {
234 r.push(TokenTree::Token(self.span, token::Not));
236 let mut inner = Vec::new();
237 for (i, segment) in self.path.segments.iter().enumerate() {
239 inner.push(TokenTree::Token(self.span, token::Colon).into());
241 inner.push(TokenTree::Token(self.span, token::Ident(segment.identifier)).into());
243 inner.push(self.tokens.clone());
245 r.push(TokenTree::Delimited(self.span, tokenstream::Delimited {
246 delim: token::Bracket, tts: TokenStream::concat(inner).into()
252 impl ToTokens for str {
253 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
254 let lit = ast::LitKind::Str(Symbol::intern(self), ast::StrStyle::Cooked);
255 dummy_spanned(lit).to_tokens(cx)
259 impl ToTokens for () {
260 fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
261 vec![TokenTree::Delimited(DUMMY_SP, tokenstream::Delimited {
263 tts: TokenStream::empty().into(),
268 impl ToTokens for ast::Lit {
269 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
270 // FIXME: This is wrong
272 id: ast::DUMMY_NODE_ID,
273 node: ast::ExprKind::Lit(P(self.clone())),
275 attrs: ast::ThinVec::new(),
280 impl ToTokens for bool {
281 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
282 dummy_spanned(ast::LitKind::Bool(*self)).to_tokens(cx)
286 impl ToTokens for char {
287 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
288 dummy_spanned(ast::LitKind::Char(*self)).to_tokens(cx)
292 macro_rules! impl_to_tokens_int {
293 (signed, $t:ty, $tag:expr) => (
294 impl ToTokens for $t {
295 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
296 let val = if *self < 0 {
301 let lit = ast::LitKind::Int(val as u128, ast::LitIntType::Signed($tag));
302 let lit = P(ast::Expr {
303 id: ast::DUMMY_NODE_ID,
304 node: ast::ExprKind::Lit(P(dummy_spanned(lit))),
306 attrs: ast::ThinVec::new(),
309 return lit.to_tokens(cx);
312 id: ast::DUMMY_NODE_ID,
313 node: ast::ExprKind::Unary(ast::UnOp::Neg, lit),
315 attrs: ast::ThinVec::new(),
320 (unsigned, $t:ty, $tag:expr) => (
321 impl ToTokens for $t {
322 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
323 let lit = ast::LitKind::Int(*self as u128, ast::LitIntType::Unsigned($tag));
324 dummy_spanned(lit).to_tokens(cx)
330 impl_to_tokens_int! { signed, isize, ast::IntTy::Isize }
331 impl_to_tokens_int! { signed, i8, ast::IntTy::I8 }
332 impl_to_tokens_int! { signed, i16, ast::IntTy::I16 }
333 impl_to_tokens_int! { signed, i32, ast::IntTy::I32 }
334 impl_to_tokens_int! { signed, i64, ast::IntTy::I64 }
336 impl_to_tokens_int! { unsigned, usize, ast::UintTy::Usize }
337 impl_to_tokens_int! { unsigned, u8, ast::UintTy::U8 }
338 impl_to_tokens_int! { unsigned, u16, ast::UintTy::U16 }
339 impl_to_tokens_int! { unsigned, u32, ast::UintTy::U32 }
340 impl_to_tokens_int! { unsigned, u64, ast::UintTy::U64 }
342 pub trait ExtParseUtils {
343 fn parse_item(&self, s: String) -> P<ast::Item>;
344 fn parse_expr(&self, s: String) -> P<ast::Expr>;
345 fn parse_stmt(&self, s: String) -> ast::Stmt;
346 fn parse_tts(&self, s: String) -> Vec<TokenTree>;
349 impl<'a> ExtParseUtils for ExtCtxt<'a> {
350 fn parse_item(&self, s: String) -> P<ast::Item> {
351 panictry!(parse::parse_item_from_source_str(
352 FileName::QuoteExpansion,
354 self.parse_sess())).expect("parse error")
357 fn parse_stmt(&self, s: String) -> ast::Stmt {
358 panictry!(parse::parse_stmt_from_source_str(
359 FileName::QuoteExpansion,
361 self.parse_sess())).expect("parse error")
364 fn parse_expr(&self, s: String) -> P<ast::Expr> {
365 panictry!(parse::parse_expr_from_source_str(
366 FileName::QuoteExpansion,
371 fn parse_tts(&self, s: String) -> Vec<TokenTree> {
372 let source_name = FileName::QuoteExpansion;
373 parse::parse_stream_from_source_str(source_name, s, self.parse_sess(), None)
374 .into_trees().collect()
379 // Replaces `Token::OpenDelim .. Token::CloseDelim` with `TokenTree::Delimited(..)`.
380 pub fn unflatten(tts: Vec<TokenTree>) -> Vec<TokenTree> {
381 use tokenstream::Delimited;
383 let mut results = Vec::new();
384 let mut result = Vec::new();
387 TokenTree::Token(_, token::OpenDelim(..)) => {
388 results.push(::std::mem::replace(&mut result, Vec::new()));
390 TokenTree::Token(span, token::CloseDelim(delim)) => {
391 let tree = TokenTree::Delimited(span, Delimited {
393 tts: result.into_iter().map(TokenStream::from).collect::<TokenStream>().into(),
395 result = results.pop().unwrap();
398 tree => result.push(tree),
404 // These panicking parsing functions are used by the quote_*!() syntax extensions,
405 // but shouldn't be used otherwise.
406 pub fn parse_expr_panic(parser: &mut Parser) -> P<Expr> {
407 panictry!(parser.parse_expr())
410 pub fn parse_item_panic(parser: &mut Parser) -> Option<P<Item>> {
411 panictry!(parser.parse_item())
414 pub fn parse_pat_panic(parser: &mut Parser) -> P<Pat> {
415 panictry!(parser.parse_pat())
418 pub fn parse_arm_panic(parser: &mut Parser) -> Arm {
419 panictry!(parser.parse_arm())
422 pub fn parse_ty_panic(parser: &mut Parser) -> P<Ty> {
423 panictry!(parser.parse_ty())
426 pub fn parse_stmt_panic(parser: &mut Parser) -> Option<Stmt> {
427 panictry!(parser.parse_stmt())
430 pub fn parse_attribute_panic(parser: &mut Parser, permit_inner: bool) -> ast::Attribute {
431 panictry!(parser.parse_attribute(permit_inner))
434 pub fn parse_arg_panic(parser: &mut Parser) -> Arg {
435 panictry!(parser.parse_arg())
438 pub fn parse_block_panic(parser: &mut Parser) -> P<Block> {
439 panictry!(parser.parse_block())
442 pub fn parse_meta_item_panic(parser: &mut Parser) -> ast::MetaItem {
443 panictry!(parser.parse_meta_item())
446 pub fn parse_path_panic(parser: &mut Parser, mode: PathStyle) -> ast::Path {
447 panictry!(parser.parse_path(mode))
450 pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt,
453 -> Box<base::MacResult+'cx> {
454 let (cx_expr, expr) = expand_tts(cx, sp, tts);
455 let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]);
456 base::MacEager::expr(expanded)
459 pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt,
462 -> Box<base::MacResult+'cx> {
463 let expanded = expand_parse_call(cx, sp, "parse_expr_panic", vec![], tts);
464 base::MacEager::expr(expanded)
467 pub fn expand_quote_item<'cx>(cx: &'cx mut ExtCtxt,
470 -> Box<base::MacResult+'cx> {
471 let expanded = expand_parse_call(cx, sp, "parse_item_panic", vec![], tts);
472 base::MacEager::expr(expanded)
475 pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt,
478 -> Box<base::MacResult+'cx> {
479 let expanded = expand_parse_call(cx, sp, "parse_pat_panic", vec![], tts);
480 base::MacEager::expr(expanded)
483 pub fn expand_quote_arm(cx: &mut ExtCtxt,
486 -> Box<base::MacResult+'static> {
487 let expanded = expand_parse_call(cx, sp, "parse_arm_panic", vec![], tts);
488 base::MacEager::expr(expanded)
491 pub fn expand_quote_ty(cx: &mut ExtCtxt,
494 -> Box<base::MacResult+'static> {
495 let expanded = expand_parse_call(cx, sp, "parse_ty_panic", vec![], tts);
496 base::MacEager::expr(expanded)
499 pub fn expand_quote_stmt(cx: &mut ExtCtxt,
502 -> Box<base::MacResult+'static> {
503 let expanded = expand_parse_call(cx, sp, "parse_stmt_panic", vec![], tts);
504 base::MacEager::expr(expanded)
507 pub fn expand_quote_attr(cx: &mut ExtCtxt,
510 -> Box<base::MacResult+'static> {
511 let expanded = expand_parse_call(cx, sp, "parse_attribute_panic",
512 vec![cx.expr_bool(sp, true)], tts);
514 base::MacEager::expr(expanded)
517 pub fn expand_quote_arg(cx: &mut ExtCtxt,
520 -> Box<base::MacResult+'static> {
521 let expanded = expand_parse_call(cx, sp, "parse_arg_panic", vec![], tts);
522 base::MacEager::expr(expanded)
525 pub fn expand_quote_block(cx: &mut ExtCtxt,
528 -> Box<base::MacResult+'static> {
529 let expanded = expand_parse_call(cx, sp, "parse_block_panic", vec![], tts);
530 base::MacEager::expr(expanded)
533 pub fn expand_quote_meta_item(cx: &mut ExtCtxt,
536 -> Box<base::MacResult+'static> {
537 let expanded = expand_parse_call(cx, sp, "parse_meta_item_panic", vec![], tts);
538 base::MacEager::expr(expanded)
541 pub fn expand_quote_path(cx: &mut ExtCtxt,
544 -> Box<base::MacResult+'static> {
545 let mode = mk_parser_path(cx, sp, &["PathStyle", "Type"]);
546 let expanded = expand_parse_call(cx, sp, "parse_path_panic", vec![mode], tts);
547 base::MacEager::expr(expanded)
550 fn ids_ext(strs: Vec<String>) -> Vec<ast::Ident> {
551 strs.iter().map(|s| ast::Ident::from_str(s)).collect()
554 fn id_ext(s: &str) -> ast::Ident {
555 ast::Ident::from_str(s)
558 // Lift an ident to the expr that evaluates to that ident.
559 fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
560 let e_str = cx.expr_str(sp, ident.name);
561 cx.expr_method_call(sp,
562 cx.expr_ident(sp, id_ext("ext_cx")),
567 // Lift a name to the expr that evaluates to that name
568 fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
569 let e_str = cx.expr_str(sp, ident.name);
570 cx.expr_method_call(sp,
571 cx.expr_ident(sp, id_ext("ext_cx")),
576 fn mk_tt_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
577 let idents = vec![id_ext("syntax"), id_ext("tokenstream"), id_ext("TokenTree"), id_ext(name)];
578 cx.expr_path(cx.path_global(sp, idents))
581 fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
582 let idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name)];
583 cx.expr_path(cx.path_global(sp, idents))
586 fn mk_parser_path(cx: &ExtCtxt, sp: Span, names: &[&str]) -> P<ast::Expr> {
587 let mut idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("parser")];
588 idents.extend(names.iter().cloned().map(id_ext));
589 cx.expr_path(cx.path_global(sp, idents))
592 fn mk_binop(cx: &ExtCtxt, sp: Span, bop: token::BinOpToken) -> P<ast::Expr> {
593 let name = match bop {
594 token::Plus => "Plus",
595 token::Minus => "Minus",
596 token::Star => "Star",
597 token::Slash => "Slash",
598 token::Percent => "Percent",
599 token::Caret => "Caret",
605 mk_token_path(cx, sp, name)
608 fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> {
609 let name = match delim {
610 token::Paren => "Paren",
611 token::Bracket => "Bracket",
612 token::Brace => "Brace",
613 token::NoDelim => "NoDelim",
615 mk_token_path(cx, sp, name)
618 #[allow(non_upper_case_globals)]
619 fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
620 macro_rules! mk_lit {
621 ($name: expr, $suffix: expr, $content: expr $(, $count: expr)*) => {{
622 let name = mk_name(cx, sp, ast::Ident::with_empty_ctxt($content));
623 let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![
624 name $(, cx.expr_usize(sp, $count))*
626 let suffix = match $suffix {
627 Some(name) => cx.expr_some(sp, mk_name(cx, sp, ast::Ident::with_empty_ctxt(name))),
628 None => cx.expr_none(sp)
630 cx.expr_call(sp, mk_token_path(cx, sp, "Literal"), vec![inner, suffix])
634 let name = match *tok {
635 token::BinOp(binop) => {
636 return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec![mk_binop(cx, sp, binop)]);
638 token::BinOpEq(binop) => {
639 return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"),
640 vec![mk_binop(cx, sp, binop)]);
643 token::OpenDelim(delim) => {
644 return cx.expr_call(sp, mk_token_path(cx, sp, "OpenDelim"),
645 vec![mk_delim(cx, sp, delim)]);
647 token::CloseDelim(delim) => {
648 return cx.expr_call(sp, mk_token_path(cx, sp, "CloseDelim"),
649 vec![mk_delim(cx, sp, delim)]);
652 token::Literal(token::Byte(i), suf) => return mk_lit!("Byte", suf, i),
653 token::Literal(token::Char(i), suf) => return mk_lit!("Char", suf, i),
654 token::Literal(token::Integer(i), suf) => return mk_lit!("Integer", suf, i),
655 token::Literal(token::Float(i), suf) => return mk_lit!("Float", suf, i),
656 token::Literal(token::Str_(i), suf) => return mk_lit!("Str_", suf, i),
657 token::Literal(token::StrRaw(i, n), suf) => return mk_lit!("StrRaw", suf, i, n),
658 token::Literal(token::ByteStr(i), suf) => return mk_lit!("ByteStr", suf, i),
659 token::Literal(token::ByteStrRaw(i, n), suf) => return mk_lit!("ByteStrRaw", suf, i, n),
661 token::Ident(ident) => {
662 return cx.expr_call(sp,
663 mk_token_path(cx, sp, "Ident"),
664 vec![mk_ident(cx, sp, ident)]);
667 token::Lifetime(ident) => {
668 return cx.expr_call(sp,
669 mk_token_path(cx, sp, "Lifetime"),
670 vec![mk_ident(cx, sp, ident)]);
673 token::DocComment(ident) => {
674 return cx.expr_call(sp,
675 mk_token_path(cx, sp, "DocComment"),
676 vec![mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident))]);
679 token::Interpolated(_) => {
680 cx.span_err(sp, "quote! with interpolated token");
688 token::EqEq => "EqEq",
692 token::AndAnd => "AndAnd",
693 token::OrOr => "OrOr",
695 token::Tilde => "Tilde",
698 token::DotDot => "DotDot",
699 token::DotEq => "DotEq",
700 token::DotDotDot => "DotDotDot",
701 token::DotDotEq => "DotDotEq",
702 token::Comma => "Comma",
703 token::Semi => "Semi",
704 token::Colon => "Colon",
705 token::ModSep => "ModSep",
706 token::RArrow => "RArrow",
707 token::LArrow => "LArrow",
708 token::FatArrow => "FatArrow",
709 token::Pound => "Pound",
710 token::Dollar => "Dollar",
711 token::Question => "Question",
714 token::Whitespace | token::Comment | token::Shebang(_) => {
715 panic!("unhandled token in quote!");
718 mk_token_path(cx, sp, name)
721 fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, quoted: bool) -> Vec<ast::Stmt> {
723 TokenTree::Token(sp, token::Ident(ident)) if quoted => {
724 // tt.extend($ident.to_tokens(ext_cx))
727 cx.expr_method_call(sp,
728 cx.expr_ident(sp, ident),
730 vec![cx.expr_ident(sp, id_ext("ext_cx"))]);
732 cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]);
735 cx.expr_method_call(sp,
736 cx.expr_ident(sp, id_ext("tt")),
740 vec![cx.stmt_expr(e_push)]
742 TokenTree::Token(sp, ref tok) => {
743 let e_sp = cx.expr_ident(sp, id_ext("_sp"));
744 let e_tok = cx.expr_call(sp,
745 mk_tt_path(cx, sp, "Token"),
746 vec![e_sp, expr_mk_token(cx, sp, tok)]);
748 cx.expr_method_call(sp,
749 cx.expr_ident(sp, id_ext("tt")),
752 vec![cx.stmt_expr(e_push)]
754 TokenTree::Delimited(span, ref delimed) => {
755 let mut stmts = statements_mk_tt(cx, &delimed.open_tt(span), false);
756 stmts.extend(statements_mk_tts(cx, delimed.stream()));
757 stmts.extend(statements_mk_tt(cx, &delimed.close_tt(span), false));
763 fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[TokenTree])
764 -> (P<ast::Expr>, Vec<TokenTree>) {
765 let mut p = cx.new_parser_from_tts(tts);
767 let cx_expr = panictry!(p.parse_expr());
768 if !p.eat(&token::Comma) {
769 let _ = p.diagnostic().fatal("expected token `,`");
772 let tts = panictry!(p.parse_all_token_trees());
778 fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<ast::Stmt> {
779 // We also bind a single value, sp, to ext_cx.call_site()
781 // This causes every span in a token-tree quote to be attributed to the
782 // call site of the extension using the quote. We can't really do much
783 // better since the source of the quote may well be in a library that
784 // was not even parsed by this compilation run, that the user has no
785 // source code for (eg. in libsyntax, which they're just _using_).
787 // The old quasiquoter had an elaborate mechanism for denoting input
788 // file locations from which quotes originated; unfortunately this
789 // relied on feeding the source string of the quote back into the
790 // compiler (which we don't really want to do) and, in any case, only
791 // pushed the problem a very small step further back: an error
792 // resulting from a parse of the resulting quote is still attributed to
793 // the site the string literal occurred, which was in a source file
794 // _other_ than the one the user has control over. For example, an
795 // error in a quote from the protocol compiler, invoked in user code
796 // using macro_rules! for example, will be attributed to the macro_rules.rs
797 // file in libsyntax, which the user might not even have source to (unless
798 // they happen to have a compiler on hand). Over all, the phase distinction
799 // just makes quotes "hard to attribute". Possibly this could be fixed
800 // by recreating some of the original qq machinery in the tt regime
801 // (pushing fake FileMaps onto the parser to account for original sites
802 // of quotes, for example) but at this point it seems not likely to be
805 let e_sp = cx.expr_method_call(sp,
806 cx.expr_ident(sp, id_ext("ext_cx")),
810 let stmt_let_sp = cx.stmt_let(sp, false,
814 let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
816 vec![stmt_let_sp, stmt_let_tt]
819 fn statements_mk_tts(cx: &ExtCtxt, tts: TokenStream) -> Vec<ast::Stmt> {
820 let mut ss = Vec::new();
821 let mut quoted = false;
822 for tt in tts.into_trees() {
824 TokenTree::Token(_, token::Dollar) if !quoted => true,
826 ss.extend(statements_mk_tt(cx, &tt, quoted));
834 fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[TokenTree]) -> (P<ast::Expr>, P<ast::Expr>) {
835 let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
837 let mut vector = mk_stmts_let(cx, sp);
838 vector.extend(statements_mk_tts(cx, tts.iter().cloned().collect()));
839 vector.push(cx.stmt_expr(cx.expr_ident(sp, id_ext("tt"))));
840 let block = cx.expr_block(cx.block(sp, vector));
841 let unflatten = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext("unflatten")];
843 (cx_expr, cx.expr_call_global(sp, unflatten, vec![block]))
846 fn expand_wrapper(cx: &ExtCtxt,
848 cx_expr: P<ast::Expr>,
850 imports: &[&[&str]]) -> P<ast::Expr> {
851 // Explicitly borrow to avoid moving from the invoker (#16992)
852 let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
853 let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
855 let mut stmts = imports.iter().map(|path| {
856 // make item: `use ...;`
857 let path = path.iter().map(|s| s.to_string()).collect();
858 let use_item = cx.item_use_glob(
860 respan(sp.shrink_to_lo(), ast::VisibilityKind::Inherited),
863 cx.stmt_item(sp, use_item)
864 }).chain(Some(stmt_let_ext_cx)).collect::<Vec<_>>();
865 stmts.push(cx.stmt_expr(expr));
867 cx.expr_block(cx.block(sp, stmts))
870 fn expand_parse_call(cx: &ExtCtxt,
873 arg_exprs: Vec<P<ast::Expr>> ,
874 tts: &[TokenTree]) -> P<ast::Expr> {
875 let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
877 let parse_sess_call = || cx.expr_method_call(
878 sp, cx.expr_ident(sp, id_ext("ext_cx")),
879 id_ext("parse_sess"), Vec::new());
881 let new_parser_call =
883 cx.expr_ident(sp, id_ext("new_parser_from_tts")),
884 vec![parse_sess_call(), tts_expr]);
886 let path = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext(parse_method)];
887 let mut args = vec![cx.expr_mut_addr_of(sp, new_parser_call)];
888 args.extend(arg_exprs);
889 let expr = cx.expr_call_global(sp, path, args);
891 if parse_method == "parse_attribute" {
892 expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"],
893 &["syntax", "parse", "attr"]])
895 expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]])