1 //! Conversions between [`SyntaxNode`] and [`tt::TokenTree`].
3 use parser::{FragmentKind, ParseError, TreeSink};
4 use rustc_hash::FxHashMap;
6 ast::{self, make::tokens::doc_comment},
7 tokenize, AstToken, Parse, SmolStr, SyntaxKind,
9 SyntaxNode, SyntaxToken, SyntaxTreeBuilder, TextRange, TextSize, Token as RawToken, T,
11 use tt::buffer::{Cursor, TokenBuffer};
13 use crate::{subtree_source::SubtreeTokenSource, tt_iter::TtIter};
14 use crate::{ExpandError, TokenMap};
16 /// Convert the syntax tree (what user has written) to a `TokenTree` (what macro
18 pub fn ast_to_token_tree(ast: &impl ast::AstNode) -> (tt::Subtree, TokenMap) {
19 syntax_node_to_token_tree(ast.syntax())
22 /// Convert the syntax node to a `TokenTree` (what macro
24 pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> (tt::Subtree, TokenMap) {
25 let global_offset = node.text_range().start();
26 let mut c = Convertor::new(node, global_offset);
27 let subtree = convert_tokens(&mut c);
28 c.id_alloc.map.shrink_to_fit();
29 (subtree, c.id_alloc.map)
32 // The following items are what `rustc` macro can be parsed into :
33 // link: https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/libsyntax/ext/expand.rs#L141
34 // * Expr(P<ast::Expr>) -> token_tree_to_expr
35 // * Pat(P<ast::Pat>) -> token_tree_to_pat
36 // * Ty(P<ast::Ty>) -> token_tree_to_ty
37 // * Stmts(SmallVec<[ast::Stmt; 1]>) -> token_tree_to_stmts
38 // * Items(SmallVec<[P<ast::Item>; 1]>) -> token_tree_to_items
40 // * TraitItems(SmallVec<[ast::TraitItem; 1]>)
41 // * AssocItems(SmallVec<[ast::AssocItem; 1]>)
42 // * ForeignItems(SmallVec<[ast::ForeignItem; 1]>
44 pub fn token_tree_to_syntax_node(
46 fragment_kind: FragmentKind,
47 ) -> Result<(Parse<SyntaxNode>, TokenMap), ExpandError> {
48 let buffer = match tt {
49 tt::Subtree { delimiter: None, token_trees } => {
50 TokenBuffer::from_tokens(token_trees.as_slice())
52 _ => TokenBuffer::from_subtree(tt),
54 let mut token_source = SubtreeTokenSource::new(&buffer);
55 let mut tree_sink = TtTreeSink::new(buffer.begin());
56 parser::parse_fragment(&mut token_source, &mut tree_sink, fragment_kind);
57 if tree_sink.roots.len() != 1 {
58 return Err(ExpandError::ConversionError);
60 //FIXME: would be cool to report errors
61 let (parse, range_map) = tree_sink.finish();
62 Ok((parse, range_map))
65 /// Convert a string to a `TokenTree`
66 pub fn parse_to_token_tree(text: &str) -> Option<(tt::Subtree, TokenMap)> {
67 let (tokens, errors) = tokenize(text);
68 if !errors.is_empty() {
72 let mut conv = RawConvertor {
74 offset: TextSize::default(),
76 id_alloc: TokenIdAlloc {
77 map: Default::default(),
78 global_offset: TextSize::default(),
83 let subtree = convert_tokens(&mut conv);
84 Some((subtree, conv.id_alloc.map))
87 /// Split token tree with seperate expr: $($e:expr)SEP*
88 pub fn parse_exprs_with_sep(tt: &tt::Subtree, sep: char) -> Vec<tt::Subtree> {
89 if tt.token_trees.is_empty() {
93 let mut iter = TtIter::new(tt);
94 let mut res = Vec::new();
96 while iter.peek_n(0).is_some() {
97 let expanded = iter.expect_fragment(FragmentKind::Expr);
98 if expanded.err.is_some() {
102 res.push(match expanded.value {
104 Some(tt @ tt::TokenTree::Leaf(_)) => {
105 tt::Subtree { delimiter: None, token_trees: vec![tt] }
107 Some(tt::TokenTree::Subtree(tt)) => tt,
110 let mut fork = iter.clone();
111 if fork.expect_char(sep).is_err() {
117 if iter.peek_n(0).is_some() {
118 res.push(tt::Subtree { delimiter: None, token_trees: iter.into_iter().cloned().collect() });
124 fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
126 subtree: tt::Subtree,
128 open_range: TextRange,
131 let entry = StackEntry {
132 subtree: tt::Subtree { delimiter: None, ..Default::default() },
133 // never used (delimiter is `None`)
135 open_range: TextRange::empty(TextSize::of('.')),
137 let mut stack = vec![entry];
140 let entry = stack.last_mut().unwrap();
141 let result = &mut entry.subtree.token_trees;
142 let (token, range) = match conv.bump() {
147 let k: SyntaxKind = token.kind();
149 if let Some(tokens) = conv.convert_doc_comment(&token) {
150 result.extend(tokens);
155 result.push(if k.is_punct() && k != UNDERSCORE {
156 assert_eq!(range.len(), TextSize::of('.'));
158 if let Some(delim) = entry.subtree.delimiter {
159 let expected = match delim.kind {
160 tt::DelimiterKind::Parenthesis => T![')'],
161 tt::DelimiterKind::Brace => T!['}'],
162 tt::DelimiterKind::Bracket => T![']'],
166 let entry = stack.pop().unwrap();
167 conv.id_alloc().close_delim(entry.idx, Some(range));
168 stack.last_mut().unwrap().subtree.token_trees.push(entry.subtree.into());
173 let delim = match k {
174 T!['('] => Some(tt::DelimiterKind::Parenthesis),
175 T!['{'] => Some(tt::DelimiterKind::Brace),
176 T!['['] => Some(tt::DelimiterKind::Bracket),
180 if let Some(kind) = delim {
181 let mut subtree = tt::Subtree::default();
182 let (id, idx) = conv.id_alloc().open_delim(range);
183 subtree.delimiter = Some(tt::Delimiter { id, kind });
184 stack.push(StackEntry { subtree, idx, open_range: range });
187 let spacing = match conv.peek() {
189 if next.kind().is_trivia()
190 || next.kind() == T!['[']
191 || next.kind() == T!['{']
192 || next.kind() == T!['('] =>
196 Some(next) if next.kind().is_punct() && next.kind() != UNDERSCORE => {
199 _ => tt::Spacing::Alone,
201 let char = match token.to_char() {
204 panic!("Token from lexer must be single char: token = {:#?}", token);
207 tt::Leaf::from(tt::Punct { char, spacing, id: conv.id_alloc().alloc(range) }).into()
210 macro_rules! make_leaf {
212 tt::$i { id: conv.id_alloc().alloc(range), text: token.to_text() }.into()
215 let leaf: tt::Leaf = match k {
216 T![true] | T![false] => make_leaf!(Ident),
217 IDENT => make_leaf!(Ident),
218 UNDERSCORE => make_leaf!(Ident),
219 k if k.is_keyword() => make_leaf!(Ident),
220 k if k.is_literal() => make_leaf!(Literal),
222 let char_unit = TextSize::of('\'');
223 let r = TextRange::at(range.start(), char_unit);
224 let apostrophe = tt::Leaf::from(tt::Punct {
226 spacing: tt::Spacing::Joint,
227 id: conv.id_alloc().alloc(r),
229 result.push(apostrophe.into());
231 let r = TextRange::at(range.start() + char_unit, range.len() - char_unit);
232 let ident = tt::Leaf::from(tt::Ident {
233 text: SmolStr::new(&token.to_text()[1..]),
234 id: conv.id_alloc().alloc(r),
236 result.push(ident.into());
246 // If we get here, we've consumed all input tokens.
247 // We might have more than one subtree in the stack, if the delimiters are improperly balanced.
248 // Merge them so we're left with one.
249 while stack.len() > 1 {
250 let entry = stack.pop().unwrap();
251 let parent = stack.last_mut().unwrap();
253 conv.id_alloc().close_delim(entry.idx, None);
254 let leaf: tt::Leaf = tt::Punct {
255 id: conv.id_alloc().alloc(entry.open_range),
256 char: match entry.subtree.delimiter.unwrap().kind {
257 tt::DelimiterKind::Parenthesis => '(',
258 tt::DelimiterKind::Brace => '{',
259 tt::DelimiterKind::Bracket => '[',
261 spacing: tt::Spacing::Alone,
264 parent.subtree.token_trees.push(leaf.into());
265 parent.subtree.token_trees.extend(entry.subtree.token_trees);
268 let subtree = stack.pop().unwrap().subtree;
269 if subtree.token_trees.len() == 1 {
270 if let tt::TokenTree::Subtree(first) = &subtree.token_trees[0] {
271 return first.clone();
277 /// Returns the textual content of a doc comment block as a quoted string
278 /// That is, strips leading `///` (or `/**`, etc)
279 /// and strips the ending `*/`
280 /// And then quote the string, which is needed to convert to `tt::Literal`
281 fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
282 let prefix_len = comment.prefix().len();
283 let mut text = &comment.text()[prefix_len..];
285 // Remove ending "*/"
286 if comment.kind().shape == ast::CommentShape::Block {
287 text = &text[0..text.len() - 2];
291 // Note that `tt::Literal` expect an escaped string
292 let text = format!("\"{}\"", text.escape_debug());
296 fn convert_doc_comment(token: &syntax::SyntaxToken) -> Option<Vec<tt::TokenTree>> {
297 let comment = ast::Comment::cast(token.clone())?;
298 let doc = comment.kind().doc?;
300 // Make `doc="\" Comments\""
301 let meta_tkns = vec![mk_ident("doc"), mk_punct('='), mk_doc_literal(&comment)];
304 let mut token_trees = vec![mk_punct('#')];
305 if let ast::CommentPlacement::Inner = doc {
306 token_trees.push(mk_punct('!'));
308 token_trees.push(tt::TokenTree::from(tt::Subtree {
309 delimiter: Some(tt::Delimiter {
310 kind: tt::DelimiterKind::Bracket,
311 id: tt::TokenId::unspecified(),
313 token_trees: meta_tkns,
316 return Some(token_trees);
319 fn mk_ident(s: &str) -> tt::TokenTree {
320 tt::TokenTree::from(tt::Leaf::from(tt::Ident {
322 id: tt::TokenId::unspecified(),
326 fn mk_punct(c: char) -> tt::TokenTree {
327 tt::TokenTree::from(tt::Leaf::from(tt::Punct {
329 spacing: tt::Spacing::Alone,
330 id: tt::TokenId::unspecified(),
334 fn mk_doc_literal(comment: &ast::Comment) -> tt::TokenTree {
335 let lit = tt::Literal { text: doc_comment_text(comment), id: tt::TokenId::unspecified() };
337 tt::TokenTree::from(tt::Leaf::from(lit))
341 struct TokenIdAlloc {
343 global_offset: TextSize,
348 fn alloc(&mut self, absolute_range: TextRange) -> tt::TokenId {
349 let relative_range = absolute_range - self.global_offset;
350 let token_id = tt::TokenId(self.next_id);
352 self.map.insert(token_id, relative_range);
356 fn open_delim(&mut self, open_abs_range: TextRange) -> (tt::TokenId, usize) {
357 let token_id = tt::TokenId(self.next_id);
359 let idx = self.map.insert_delim(
361 open_abs_range - self.global_offset,
362 open_abs_range - self.global_offset,
367 fn close_delim(&mut self, idx: usize, close_abs_range: Option<TextRange>) {
368 match close_abs_range {
370 self.map.remove_delim(idx);
373 self.map.update_close_delim(idx, close - self.global_offset);
379 /// A Raw Token (straightly from lexer) convertor
380 struct RawConvertor<'a> {
383 id_alloc: TokenIdAlloc,
384 inner: std::slice::Iter<'a, RawToken>,
387 trait SrcToken: std::fmt::Debug {
388 fn kind(&self) -> SyntaxKind;
390 fn to_char(&self) -> Option<char>;
392 fn to_text(&self) -> SmolStr;
395 trait TokenConvertor {
396 type Token: SrcToken;
398 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>>;
400 fn bump(&mut self) -> Option<(Self::Token, TextRange)>;
402 fn peek(&self) -> Option<Self::Token>;
404 fn id_alloc(&mut self) -> &mut TokenIdAlloc;
407 impl<'a> SrcToken for (&'a RawToken, &'a str) {
408 fn kind(&self) -> SyntaxKind {
412 fn to_char(&self) -> Option<char> {
413 self.1.chars().next()
416 fn to_text(&self) -> SmolStr {
421 impl RawConvertor<'_> {}
423 impl<'a> TokenConvertor for RawConvertor<'a> {
424 type Token = (&'a RawToken, &'a str);
426 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>> {
427 convert_doc_comment(&doc_comment(token.1))
430 fn bump(&mut self) -> Option<(Self::Token, TextRange)> {
431 let token = self.inner.next()?;
432 let range = TextRange::at(self.offset, token.len);
433 self.offset += token.len;
435 Some(((token, &self.text[range]), range))
438 fn peek(&self) -> Option<Self::Token> {
439 let token = self.inner.as_slice().get(0);
442 let range = TextRange::at(self.offset, it.len);
443 (it, &self.text[range])
447 fn id_alloc(&mut self) -> &mut TokenIdAlloc {
453 id_alloc: TokenIdAlloc,
454 current: Option<SyntaxToken>,
456 punct_offset: Option<(SyntaxToken, TextSize)>,
460 fn new(node: &SyntaxNode, global_offset: TextSize) -> Convertor {
462 id_alloc: { TokenIdAlloc { map: TokenMap::default(), global_offset, next_id: 0 } },
463 current: node.first_token(),
464 range: node.text_range(),
472 Ordinary(SyntaxToken),
473 Punch(SyntaxToken, TextSize),
477 fn token(&self) -> &SyntaxToken {
479 SynToken::Ordinary(it) => it,
480 SynToken::Punch(it, _) => it,
485 impl SrcToken for SynToken {
486 fn kind(&self) -> SyntaxKind {
489 fn to_char(&self) -> Option<char> {
491 SynToken::Ordinary(_) => None,
492 SynToken::Punch(it, i) => it.text().chars().nth((*i).into()),
495 fn to_text(&self) -> SmolStr {
496 self.token().text().into()
500 impl TokenConvertor for Convertor {
501 type Token = SynToken;
502 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>> {
503 convert_doc_comment(token.token())
506 fn bump(&mut self) -> Option<(Self::Token, TextRange)> {
507 if let Some((punct, offset)) = self.punct_offset.clone() {
508 if usize::from(offset) + 1 < punct.text().len() {
509 let offset = offset + TextSize::of('.');
510 let range = punct.text_range();
511 self.punct_offset = Some((punct.clone(), offset));
512 let range = TextRange::at(range.start() + offset, TextSize::of('.'));
513 return Some((SynToken::Punch(punct, offset), range));
517 let curr = self.current.clone()?;
518 if !&self.range.contains_range(curr.text_range()) {
521 self.current = curr.next_token();
523 let token = if curr.kind().is_punct() {
524 let range = curr.text_range();
525 let range = TextRange::at(range.start(), TextSize::of('.'));
526 self.punct_offset = Some((curr.clone(), 0.into()));
527 (SynToken::Punch(curr, 0.into()), range)
529 self.punct_offset = None;
530 let range = curr.text_range();
531 (SynToken::Ordinary(curr), range)
537 fn peek(&self) -> Option<Self::Token> {
538 if let Some((punct, mut offset)) = self.punct_offset.clone() {
539 offset += TextSize::of('.');
540 if usize::from(offset) < punct.text().len() {
541 return Some(SynToken::Punch(punct, offset));
545 let curr = self.current.clone()?;
546 if !self.range.contains_range(curr.text_range()) {
550 let token = if curr.kind().is_punct() {
551 SynToken::Punch(curr, 0.into())
553 SynToken::Ordinary(curr)
558 fn id_alloc(&mut self) -> &mut TokenIdAlloc {
563 struct TtTreeSink<'a> {
566 open_delims: FxHashMap<tt::TokenId, TextSize>,
568 inner: SyntaxTreeBuilder,
572 // Use for detect ill-form tree which is not single root
573 roots: smallvec::SmallVec<[usize; 1]>,
576 impl<'a> TtTreeSink<'a> {
577 fn new(cursor: Cursor<'a>) -> Self {
581 open_delims: FxHashMap::default(),
583 inner: SyntaxTreeBuilder::default(),
584 roots: smallvec::SmallVec::new(),
585 token_map: TokenMap::default(),
589 fn finish(mut self) -> (Parse<SyntaxNode>, TokenMap) {
590 self.token_map.shrink_to_fit();
591 (self.inner.finish(), self.token_map)
595 fn delim_to_str(d: Option<tt::DelimiterKind>, closing: bool) -> &'static str {
596 let texts = match d {
597 Some(tt::DelimiterKind::Parenthesis) => "()",
598 Some(tt::DelimiterKind::Brace) => "{}",
599 Some(tt::DelimiterKind::Bracket) => "[]",
603 let idx = closing as usize;
604 &texts[idx..texts.len() - (1 - idx)]
607 impl<'a> TreeSink for TtTreeSink<'a> {
608 fn token(&mut self, kind: SyntaxKind, mut n_tokens: u8) {
609 if kind == L_DOLLAR || kind == R_DOLLAR {
610 self.cursor = self.cursor.bump_subtree();
613 if kind == LIFETIME_IDENT {
617 let mut last = self.cursor;
618 for _ in 0..n_tokens {
619 let tmp_str: SmolStr;
620 if self.cursor.eof() {
624 let text: &str = match self.cursor.token_tree() {
625 Some(tt::buffer::TokenTreeRef::Leaf(leaf, _)) => {
626 // Mark the range if needed
627 let (text, id) = match leaf {
628 tt::Leaf::Ident(ident) => (&ident.text, ident.id),
629 tt::Leaf::Punct(punct) => {
630 assert!(punct.char.is_ascii());
631 let char = &(punct.char as u8);
632 tmp_str = SmolStr::new_inline(
633 std::str::from_utf8(std::slice::from_ref(char)).unwrap(),
637 tt::Leaf::Literal(lit) => (&lit.text, lit.id),
639 let range = TextRange::at(self.text_pos, TextSize::of(text.as_str()));
640 self.token_map.insert(id, range);
641 self.cursor = self.cursor.bump();
644 Some(tt::buffer::TokenTreeRef::Subtree(subtree, _)) => {
645 self.cursor = self.cursor.subtree().unwrap();
646 if let Some(id) = subtree.delimiter.map(|it| it.id) {
647 self.open_delims.insert(id, self.text_pos);
649 delim_to_str(subtree.delimiter_kind(), false)
652 if let Some(parent) = self.cursor.end() {
653 self.cursor = self.cursor.bump();
654 if let Some(id) = parent.delimiter.map(|it| it.id) {
655 if let Some(open_delim) = self.open_delims.get(&id) {
656 let open_range = TextRange::at(*open_delim, TextSize::of('('));
657 let close_range = TextRange::at(self.text_pos, TextSize::of('('));
658 self.token_map.insert_delim(id, open_range, close_range);
661 delim_to_str(parent.delimiter_kind(), true)
668 self.text_pos += TextSize::of(text);
671 self.inner.token(kind, self.buf.as_str());
673 // Add whitespace between adjoint puncts
674 let next = last.bump();
676 Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(curr), _)),
677 Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(_), _)),
678 ) = (last.token_tree(), next.token_tree())
680 // Note: We always assume the semi-colon would be the last token in
681 // other parts of RA such that we don't add whitespace here.
682 if curr.spacing == tt::Spacing::Alone && curr.char != ';' {
683 self.inner.token(WHITESPACE, " ");
684 self.text_pos += TextSize::of(' ');
689 fn start_node(&mut self, kind: SyntaxKind) {
690 self.inner.start_node(kind);
692 match self.roots.last_mut() {
693 None | Some(0) => self.roots.push(1),
694 Some(ref mut n) => **n += 1,
698 fn finish_node(&mut self) {
699 self.inner.finish_node();
700 *self.roots.last_mut().unwrap() -= 1;
703 fn error(&mut self, error: ParseError) {
704 self.inner.error(error, self.text_pos)
711 use crate::tests::parse_macro;
712 use parser::TokenSource;
714 algo::{insert_children, InsertPosition},
717 use test_utils::assert_eq_text;
720 fn convert_tt_token_source() {
721 let expansion = parse_macro(
723 macro_rules! literals {
735 .expand_tt("literals!(foo);");
736 let tts = &[expansion.into()];
737 let buffer = tt::buffer::TokenBuffer::from_tokens(tts);
738 let mut tt_src = SubtreeTokenSource::new(&buffer);
739 let mut tokens = vec![];
740 while tt_src.current().kind != EOF {
741 tokens.push((tt_src.current().kind, tt_src.text()));
746 // [let] [a] [=] ['c'] [;]
747 assert_eq!(tokens[2 + 3].1, "'c'");
748 assert_eq!(tokens[2 + 3].0, CHAR);
749 // [let] [c] [=] [1000] [;]
750 assert_eq!(tokens[2 + 5 + 3].1, "1000");
751 assert_eq!(tokens[2 + 5 + 3].0, INT_NUMBER);
752 // [let] [f] [=] [12E+99_f64] [;]
753 assert_eq!(tokens[2 + 10 + 3].1, "12E+99_f64");
754 assert_eq!(tokens[2 + 10 + 3].0, FLOAT_NUMBER);
756 // [let] [s] [=] ["rust1"] [;]
757 assert_eq!(tokens[2 + 15 + 3].1, "\"rust1\"");
758 assert_eq!(tokens[2 + 15 + 3].0, STRING);
762 fn stmts_token_trees_to_expr_is_err() {
763 let expansion = parse_macro(
775 .expand_tt("stmts!();");
776 assert!(token_tree_to_syntax_node(&expansion, FragmentKind::Expr).is_err());
780 fn test_token_tree_last_child_is_white_space() {
781 let source_file = ast::SourceFile::parse("f!({} );").ok().unwrap();
782 let macro_call = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
783 let token_tree = macro_call.token_tree().unwrap();
785 // Token Tree now is :
795 token_tree.syntax().descendants_with_tokens().find(|it| it.kind() == T!['}']).unwrap();
796 let space = token_tree
798 .descendants_with_tokens()
799 .find(|it| it.kind() == SyntaxKind::WHITESPACE)
802 // reorder th white space, such that the white is inside the inner token-tree.
803 let token_tree = insert_children(
804 &rbrace.parent().unwrap(),
805 InsertPosition::Last,
806 std::iter::once(space),
809 // Token Tree now is :
814 let token_tree = ast::TokenTree::cast(token_tree).unwrap();
815 let tt = ast_to_token_tree(&token_tree).0;
817 assert_eq!(tt.delimiter_kind(), Some(tt::DelimiterKind::Brace));
821 fn test_token_tree_multi_char_punct() {
822 let source_file = ast::SourceFile::parse("struct Foo { a: x::Y }").ok().unwrap();
823 let struct_def = source_file.syntax().descendants().find_map(ast::Struct::cast).unwrap();
824 let tt = ast_to_token_tree(&struct_def).0;
825 token_tree_to_syntax_node(&tt, FragmentKind::Item).unwrap();
829 fn test_missing_closing_delim() {
830 let source_file = ast::SourceFile::parse("m!(x").tree();
831 let node = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
832 let tt = ast_to_token_tree(&node).0.to_string();
833 assert_eq_text!(&*tt, "( x");