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 node to a `TokenTree` (what macro
18 pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> (tt::Subtree, TokenMap) {
19 let global_offset = node.text_range().start();
20 let mut c = Convertor::new(node, global_offset);
21 let subtree = convert_tokens(&mut c);
22 c.id_alloc.map.shrink_to_fit();
23 (subtree, c.id_alloc.map)
26 // The following items are what `rustc` macro can be parsed into :
27 // link: https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/libsyntax/ext/expand.rs#L141
28 // * Expr(P<ast::Expr>) -> token_tree_to_expr
29 // * Pat(P<ast::Pat>) -> token_tree_to_pat
30 // * Ty(P<ast::Ty>) -> token_tree_to_ty
31 // * Stmts(SmallVec<[ast::Stmt; 1]>) -> token_tree_to_stmts
32 // * Items(SmallVec<[P<ast::Item>; 1]>) -> token_tree_to_items
34 // * TraitItems(SmallVec<[ast::TraitItem; 1]>)
35 // * AssocItems(SmallVec<[ast::AssocItem; 1]>)
36 // * ForeignItems(SmallVec<[ast::ForeignItem; 1]>
38 pub fn token_tree_to_syntax_node(
40 fragment_kind: FragmentKind,
41 ) -> Result<(Parse<SyntaxNode>, TokenMap), ExpandError> {
42 let buffer = match tt {
43 tt::Subtree { delimiter: None, token_trees } => {
44 TokenBuffer::from_tokens(token_trees.as_slice())
46 _ => TokenBuffer::from_subtree(tt),
48 let mut token_source = SubtreeTokenSource::new(&buffer);
49 let mut tree_sink = TtTreeSink::new(buffer.begin());
50 parser::parse_fragment(&mut token_source, &mut tree_sink, fragment_kind);
51 if tree_sink.roots.len() != 1 {
52 return Err(ExpandError::ConversionError);
54 //FIXME: would be cool to report errors
55 let (parse, range_map) = tree_sink.finish();
56 Ok((parse, range_map))
59 /// Convert a string to a `TokenTree`
60 pub fn parse_to_token_tree(text: &str) -> Option<(tt::Subtree, TokenMap)> {
61 let (tokens, errors) = tokenize(text);
62 if !errors.is_empty() {
66 let mut conv = RawConvertor {
68 offset: TextSize::default(),
70 id_alloc: TokenIdAlloc {
71 map: Default::default(),
72 global_offset: TextSize::default(),
77 let subtree = convert_tokens(&mut conv);
78 Some((subtree, conv.id_alloc.map))
81 /// Split token tree with seperate expr: $($e:expr)SEP*
82 pub fn parse_exprs_with_sep(tt: &tt::Subtree, sep: char) -> Vec<tt::Subtree> {
83 if tt.token_trees.is_empty() {
87 let mut iter = TtIter::new(tt);
88 let mut res = Vec::new();
90 while iter.peek_n(0).is_some() {
91 let expanded = iter.expect_fragment(FragmentKind::Expr);
92 if expanded.err.is_some() {
96 res.push(match expanded.value {
98 Some(tt @ tt::TokenTree::Leaf(_)) => {
99 tt::Subtree { delimiter: None, token_trees: vec![tt] }
101 Some(tt::TokenTree::Subtree(tt)) => tt,
104 let mut fork = iter.clone();
105 if fork.expect_char(sep).is_err() {
111 if iter.peek_n(0).is_some() {
112 res.push(tt::Subtree { delimiter: None, token_trees: iter.into_iter().cloned().collect() });
118 fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
120 subtree: tt::Subtree,
122 open_range: TextRange,
125 let entry = StackEntry {
126 subtree: tt::Subtree { delimiter: None, ..Default::default() },
127 // never used (delimiter is `None`)
129 open_range: TextRange::empty(TextSize::of('.')),
131 let mut stack = vec![entry];
134 let entry = stack.last_mut().unwrap();
135 let result = &mut entry.subtree.token_trees;
136 let (token, range) = match conv.bump() {
141 let k: SyntaxKind = token.kind();
143 if let Some(tokens) = conv.convert_doc_comment(&token) {
144 result.extend(tokens);
149 result.push(if k.is_punct() && k != UNDERSCORE {
150 assert_eq!(range.len(), TextSize::of('.'));
152 if let Some(delim) = entry.subtree.delimiter {
153 let expected = match delim.kind {
154 tt::DelimiterKind::Parenthesis => T![')'],
155 tt::DelimiterKind::Brace => T!['}'],
156 tt::DelimiterKind::Bracket => T![']'],
160 let entry = stack.pop().unwrap();
161 conv.id_alloc().close_delim(entry.idx, Some(range));
162 stack.last_mut().unwrap().subtree.token_trees.push(entry.subtree.into());
167 let delim = match k {
168 T!['('] => Some(tt::DelimiterKind::Parenthesis),
169 T!['{'] => Some(tt::DelimiterKind::Brace),
170 T!['['] => Some(tt::DelimiterKind::Bracket),
174 if let Some(kind) = delim {
175 let mut subtree = tt::Subtree::default();
176 let (id, idx) = conv.id_alloc().open_delim(range);
177 subtree.delimiter = Some(tt::Delimiter { id, kind });
178 stack.push(StackEntry { subtree, idx, open_range: range });
181 let spacing = match conv.peek() {
183 if next.kind().is_trivia()
184 || next.kind() == T!['[']
185 || next.kind() == T!['{']
186 || next.kind() == T!['('] =>
190 Some(next) if next.kind().is_punct() && next.kind() != UNDERSCORE => {
193 _ => tt::Spacing::Alone,
195 let char = match token.to_char() {
198 panic!("Token from lexer must be single char: token = {:#?}", token);
201 tt::Leaf::from(tt::Punct { char, spacing, id: conv.id_alloc().alloc(range) }).into()
204 macro_rules! make_leaf {
206 tt::$i { id: conv.id_alloc().alloc(range), text: token.to_text() }.into()
209 let leaf: tt::Leaf = match k {
210 T![true] | T![false] => make_leaf!(Ident),
211 IDENT => make_leaf!(Ident),
212 UNDERSCORE => make_leaf!(Ident),
213 k if k.is_keyword() => make_leaf!(Ident),
214 k if k.is_literal() => make_leaf!(Literal),
216 let char_unit = TextSize::of('\'');
217 let r = TextRange::at(range.start(), char_unit);
218 let apostrophe = tt::Leaf::from(tt::Punct {
220 spacing: tt::Spacing::Joint,
221 id: conv.id_alloc().alloc(r),
223 result.push(apostrophe.into());
225 let r = TextRange::at(range.start() + char_unit, range.len() - char_unit);
226 let ident = tt::Leaf::from(tt::Ident {
227 text: SmolStr::new(&token.to_text()[1..]),
228 id: conv.id_alloc().alloc(r),
230 result.push(ident.into());
240 // If we get here, we've consumed all input tokens.
241 // We might have more than one subtree in the stack, if the delimiters are improperly balanced.
242 // Merge them so we're left with one.
243 while stack.len() > 1 {
244 let entry = stack.pop().unwrap();
245 let parent = stack.last_mut().unwrap();
247 conv.id_alloc().close_delim(entry.idx, None);
248 let leaf: tt::Leaf = tt::Punct {
249 id: conv.id_alloc().alloc(entry.open_range),
250 char: match entry.subtree.delimiter.unwrap().kind {
251 tt::DelimiterKind::Parenthesis => '(',
252 tt::DelimiterKind::Brace => '{',
253 tt::DelimiterKind::Bracket => '[',
255 spacing: tt::Spacing::Alone,
258 parent.subtree.token_trees.push(leaf.into());
259 parent.subtree.token_trees.extend(entry.subtree.token_trees);
262 let subtree = stack.pop().unwrap().subtree;
263 if subtree.token_trees.len() == 1 {
264 if let tt::TokenTree::Subtree(first) = &subtree.token_trees[0] {
265 return first.clone();
271 /// Returns the textual content of a doc comment block as a quoted string
272 /// That is, strips leading `///` (or `/**`, etc)
273 /// and strips the ending `*/`
274 /// And then quote the string, which is needed to convert to `tt::Literal`
275 fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
276 let prefix_len = comment.prefix().len();
277 let mut text = &comment.text()[prefix_len..];
279 // Remove ending "*/"
280 if comment.kind().shape == ast::CommentShape::Block {
281 text = &text[0..text.len() - 2];
285 // Note that `tt::Literal` expect an escaped string
286 let text = format!("\"{}\"", text.escape_debug());
290 fn convert_doc_comment(token: &syntax::SyntaxToken) -> Option<Vec<tt::TokenTree>> {
291 let comment = ast::Comment::cast(token.clone())?;
292 let doc = comment.kind().doc?;
294 // Make `doc="\" Comments\""
295 let meta_tkns = vec![mk_ident("doc"), mk_punct('='), mk_doc_literal(&comment)];
298 let mut token_trees = vec![mk_punct('#')];
299 if let ast::CommentPlacement::Inner = doc {
300 token_trees.push(mk_punct('!'));
302 token_trees.push(tt::TokenTree::from(tt::Subtree {
303 delimiter: Some(tt::Delimiter {
304 kind: tt::DelimiterKind::Bracket,
305 id: tt::TokenId::unspecified(),
307 token_trees: meta_tkns,
310 return Some(token_trees);
313 fn mk_ident(s: &str) -> tt::TokenTree {
314 tt::TokenTree::from(tt::Leaf::from(tt::Ident {
316 id: tt::TokenId::unspecified(),
320 fn mk_punct(c: char) -> tt::TokenTree {
321 tt::TokenTree::from(tt::Leaf::from(tt::Punct {
323 spacing: tt::Spacing::Alone,
324 id: tt::TokenId::unspecified(),
328 fn mk_doc_literal(comment: &ast::Comment) -> tt::TokenTree {
329 let lit = tt::Literal { text: doc_comment_text(comment), id: tt::TokenId::unspecified() };
331 tt::TokenTree::from(tt::Leaf::from(lit))
335 struct TokenIdAlloc {
337 global_offset: TextSize,
342 fn alloc(&mut self, absolute_range: TextRange) -> tt::TokenId {
343 let relative_range = absolute_range - self.global_offset;
344 let token_id = tt::TokenId(self.next_id);
346 self.map.insert(token_id, relative_range);
350 fn open_delim(&mut self, open_abs_range: TextRange) -> (tt::TokenId, usize) {
351 let token_id = tt::TokenId(self.next_id);
353 let idx = self.map.insert_delim(
355 open_abs_range - self.global_offset,
356 open_abs_range - self.global_offset,
361 fn close_delim(&mut self, idx: usize, close_abs_range: Option<TextRange>) {
362 match close_abs_range {
364 self.map.remove_delim(idx);
367 self.map.update_close_delim(idx, close - self.global_offset);
373 /// A Raw Token (straightly from lexer) convertor
374 struct RawConvertor<'a> {
377 id_alloc: TokenIdAlloc,
378 inner: std::slice::Iter<'a, RawToken>,
381 trait SrcToken: std::fmt::Debug {
382 fn kind(&self) -> SyntaxKind;
384 fn to_char(&self) -> Option<char>;
386 fn to_text(&self) -> SmolStr;
389 trait TokenConvertor {
390 type Token: SrcToken;
392 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>>;
394 fn bump(&mut self) -> Option<(Self::Token, TextRange)>;
396 fn peek(&self) -> Option<Self::Token>;
398 fn id_alloc(&mut self) -> &mut TokenIdAlloc;
401 impl<'a> SrcToken for (&'a RawToken, &'a str) {
402 fn kind(&self) -> SyntaxKind {
406 fn to_char(&self) -> Option<char> {
407 self.1.chars().next()
410 fn to_text(&self) -> SmolStr {
415 impl RawConvertor<'_> {}
417 impl<'a> TokenConvertor for RawConvertor<'a> {
418 type Token = (&'a RawToken, &'a str);
420 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>> {
421 convert_doc_comment(&doc_comment(token.1))
424 fn bump(&mut self) -> Option<(Self::Token, TextRange)> {
425 let token = self.inner.next()?;
426 let range = TextRange::at(self.offset, token.len);
427 self.offset += token.len;
429 Some(((token, &self.text[range]), range))
432 fn peek(&self) -> Option<Self::Token> {
433 let token = self.inner.as_slice().get(0);
436 let range = TextRange::at(self.offset, it.len);
437 (it, &self.text[range])
441 fn id_alloc(&mut self) -> &mut TokenIdAlloc {
447 id_alloc: TokenIdAlloc,
448 current: Option<SyntaxToken>,
450 punct_offset: Option<(SyntaxToken, TextSize)>,
454 fn new(node: &SyntaxNode, global_offset: TextSize) -> Convertor {
456 id_alloc: { TokenIdAlloc { map: TokenMap::default(), global_offset, next_id: 0 } },
457 current: node.first_token(),
458 range: node.text_range(),
466 Ordinary(SyntaxToken),
467 Punch(SyntaxToken, TextSize),
471 fn token(&self) -> &SyntaxToken {
473 SynToken::Ordinary(it) => it,
474 SynToken::Punch(it, _) => it,
479 impl SrcToken for SynToken {
480 fn kind(&self) -> SyntaxKind {
483 fn to_char(&self) -> Option<char> {
485 SynToken::Ordinary(_) => None,
486 SynToken::Punch(it, i) => it.text().chars().nth((*i).into()),
489 fn to_text(&self) -> SmolStr {
490 self.token().text().into()
494 impl TokenConvertor for Convertor {
495 type Token = SynToken;
496 fn convert_doc_comment(&self, token: &Self::Token) -> Option<Vec<tt::TokenTree>> {
497 convert_doc_comment(token.token())
500 fn bump(&mut self) -> Option<(Self::Token, TextRange)> {
501 if let Some((punct, offset)) = self.punct_offset.clone() {
502 if usize::from(offset) + 1 < punct.text().len() {
503 let offset = offset + TextSize::of('.');
504 let range = punct.text_range();
505 self.punct_offset = Some((punct.clone(), offset));
506 let range = TextRange::at(range.start() + offset, TextSize::of('.'));
507 return Some((SynToken::Punch(punct, offset), range));
511 let curr = self.current.clone()?;
512 if !&self.range.contains_range(curr.text_range()) {
515 self.current = curr.next_token();
517 let token = if curr.kind().is_punct() {
518 let range = curr.text_range();
519 let range = TextRange::at(range.start(), TextSize::of('.'));
520 self.punct_offset = Some((curr.clone(), 0.into()));
521 (SynToken::Punch(curr, 0.into()), range)
523 self.punct_offset = None;
524 let range = curr.text_range();
525 (SynToken::Ordinary(curr), range)
531 fn peek(&self) -> Option<Self::Token> {
532 if let Some((punct, mut offset)) = self.punct_offset.clone() {
533 offset += TextSize::of('.');
534 if usize::from(offset) < punct.text().len() {
535 return Some(SynToken::Punch(punct, offset));
539 let curr = self.current.clone()?;
540 if !self.range.contains_range(curr.text_range()) {
544 let token = if curr.kind().is_punct() {
545 SynToken::Punch(curr, 0.into())
547 SynToken::Ordinary(curr)
552 fn id_alloc(&mut self) -> &mut TokenIdAlloc {
557 struct TtTreeSink<'a> {
560 open_delims: FxHashMap<tt::TokenId, TextSize>,
562 inner: SyntaxTreeBuilder,
566 // Use for detect ill-form tree which is not single root
567 roots: smallvec::SmallVec<[usize; 1]>,
570 impl<'a> TtTreeSink<'a> {
571 fn new(cursor: Cursor<'a>) -> Self {
575 open_delims: FxHashMap::default(),
577 inner: SyntaxTreeBuilder::default(),
578 roots: smallvec::SmallVec::new(),
579 token_map: TokenMap::default(),
583 fn finish(mut self) -> (Parse<SyntaxNode>, TokenMap) {
584 self.token_map.shrink_to_fit();
585 (self.inner.finish(), self.token_map)
589 fn delim_to_str(d: Option<tt::DelimiterKind>, closing: bool) -> &'static str {
590 let texts = match d {
591 Some(tt::DelimiterKind::Parenthesis) => "()",
592 Some(tt::DelimiterKind::Brace) => "{}",
593 Some(tt::DelimiterKind::Bracket) => "[]",
597 let idx = closing as usize;
598 &texts[idx..texts.len() - (1 - idx)]
601 impl<'a> TreeSink for TtTreeSink<'a> {
602 fn token(&mut self, kind: SyntaxKind, mut n_tokens: u8) {
603 if kind == L_DOLLAR || kind == R_DOLLAR {
604 self.cursor = self.cursor.bump_subtree();
607 if kind == LIFETIME_IDENT {
611 let mut last = self.cursor;
612 for _ in 0..n_tokens {
613 let tmp_str: SmolStr;
614 if self.cursor.eof() {
618 let text: &str = match self.cursor.token_tree() {
619 Some(tt::buffer::TokenTreeRef::Leaf(leaf, _)) => {
620 // Mark the range if needed
621 let (text, id) = match leaf {
622 tt::Leaf::Ident(ident) => (&ident.text, ident.id),
623 tt::Leaf::Punct(punct) => {
624 assert!(punct.char.is_ascii());
625 let char = &(punct.char as u8);
626 tmp_str = SmolStr::new_inline(
627 std::str::from_utf8(std::slice::from_ref(char)).unwrap(),
631 tt::Leaf::Literal(lit) => (&lit.text, lit.id),
633 let range = TextRange::at(self.text_pos, TextSize::of(text.as_str()));
634 self.token_map.insert(id, range);
635 self.cursor = self.cursor.bump();
638 Some(tt::buffer::TokenTreeRef::Subtree(subtree, _)) => {
639 self.cursor = self.cursor.subtree().unwrap();
640 if let Some(id) = subtree.delimiter.map(|it| it.id) {
641 self.open_delims.insert(id, self.text_pos);
643 delim_to_str(subtree.delimiter_kind(), false)
646 if let Some(parent) = self.cursor.end() {
647 self.cursor = self.cursor.bump();
648 if let Some(id) = parent.delimiter.map(|it| it.id) {
649 if let Some(open_delim) = self.open_delims.get(&id) {
650 let open_range = TextRange::at(*open_delim, TextSize::of('('));
651 let close_range = TextRange::at(self.text_pos, TextSize::of('('));
652 self.token_map.insert_delim(id, open_range, close_range);
655 delim_to_str(parent.delimiter_kind(), true)
662 self.text_pos += TextSize::of(text);
665 self.inner.token(kind, self.buf.as_str());
667 // Add whitespace between adjoint puncts
668 let next = last.bump();
670 Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(curr), _)),
671 Some(tt::buffer::TokenTreeRef::Leaf(tt::Leaf::Punct(_), _)),
672 ) = (last.token_tree(), next.token_tree())
674 // Note: We always assume the semi-colon would be the last token in
675 // other parts of RA such that we don't add whitespace here.
676 if curr.spacing == tt::Spacing::Alone && curr.char != ';' {
677 self.inner.token(WHITESPACE, " ");
678 self.text_pos += TextSize::of(' ');
683 fn start_node(&mut self, kind: SyntaxKind) {
684 self.inner.start_node(kind);
686 match self.roots.last_mut() {
687 None | Some(0) => self.roots.push(1),
688 Some(ref mut n) => **n += 1,
692 fn finish_node(&mut self) {
693 self.inner.finish_node();
694 *self.roots.last_mut().unwrap() -= 1;
697 fn error(&mut self, error: ParseError) {
698 self.inner.error(error, self.text_pos)
705 use crate::tests::parse_macro;
706 use parser::TokenSource;
708 algo::{insert_children, InsertPosition},
711 use test_utils::assert_eq_text;
714 fn convert_tt_token_source() {
715 let expansion = parse_macro(
717 macro_rules! literals {
729 .expand_tt("literals!(foo);");
730 let tts = &[expansion.into()];
731 let buffer = tt::buffer::TokenBuffer::from_tokens(tts);
732 let mut tt_src = SubtreeTokenSource::new(&buffer);
733 let mut tokens = vec![];
734 while tt_src.current().kind != EOF {
735 tokens.push((tt_src.current().kind, tt_src.text()));
740 // [let] [a] [=] ['c'] [;]
741 assert_eq!(tokens[2 + 3].1, "'c'");
742 assert_eq!(tokens[2 + 3].0, CHAR);
743 // [let] [c] [=] [1000] [;]
744 assert_eq!(tokens[2 + 5 + 3].1, "1000");
745 assert_eq!(tokens[2 + 5 + 3].0, INT_NUMBER);
746 // [let] [f] [=] [12E+99_f64] [;]
747 assert_eq!(tokens[2 + 10 + 3].1, "12E+99_f64");
748 assert_eq!(tokens[2 + 10 + 3].0, FLOAT_NUMBER);
750 // [let] [s] [=] ["rust1"] [;]
751 assert_eq!(tokens[2 + 15 + 3].1, "\"rust1\"");
752 assert_eq!(tokens[2 + 15 + 3].0, STRING);
756 fn stmts_token_trees_to_expr_is_err() {
757 let expansion = parse_macro(
769 .expand_tt("stmts!();");
770 assert!(token_tree_to_syntax_node(&expansion, FragmentKind::Expr).is_err());
774 fn test_token_tree_last_child_is_white_space() {
775 let source_file = ast::SourceFile::parse("f!({} );").ok().unwrap();
776 let macro_call = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
777 let token_tree = macro_call.token_tree().unwrap();
779 // Token Tree now is :
789 token_tree.syntax().descendants_with_tokens().find(|it| it.kind() == T!['}']).unwrap();
790 let space = token_tree
792 .descendants_with_tokens()
793 .find(|it| it.kind() == SyntaxKind::WHITESPACE)
796 // reorder th white space, such that the white is inside the inner token-tree.
797 let token_tree = insert_children(
798 &rbrace.parent().unwrap(),
799 InsertPosition::Last,
800 std::iter::once(space),
803 // Token Tree now is :
808 let token_tree = ast::TokenTree::cast(token_tree).unwrap();
809 let tt = syntax_node_to_token_tree(token_tree.syntax()).0;
811 assert_eq!(tt.delimiter_kind(), Some(tt::DelimiterKind::Brace));
815 fn test_token_tree_multi_char_punct() {
816 let source_file = ast::SourceFile::parse("struct Foo { a: x::Y }").ok().unwrap();
817 let struct_def = source_file.syntax().descendants().find_map(ast::Struct::cast).unwrap();
818 let tt = syntax_node_to_token_tree(struct_def.syntax()).0;
819 token_tree_to_syntax_node(&tt, FragmentKind::Item).unwrap();
823 fn test_missing_closing_delim() {
824 let source_file = ast::SourceFile::parse("m!(x").tree();
825 let node = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
826 let tt = syntax_node_to_token_tree(node.syntax()).0.to_string();
827 assert_eq_text!(&*tt, "( x");