From 8fd7790eb51b546b18cbe209f910c396917bd88e Mon Sep 17 00:00:00 2001 From: Giga Bowser <45986823+Giga-Bowser@users.noreply.github.com> Date: Sat, 23 Nov 2024 12:41:48 -0500 Subject: [PATCH] minor: Add `token_tree` constructor to `SyntaxFactory` --- .../src/ast/syntax_factory/constructors.rs | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/syntax/src/ast/syntax_factory/constructors.rs b/crates/syntax/src/ast/syntax_factory/constructors.rs index 944724ff05..54f17bd721 100644 --- a/crates/syntax/src/ast/syntax_factory/constructors.rs +++ b/crates/syntax/src/ast/syntax_factory/constructors.rs @@ -4,7 +4,7 @@ use itertools::Itertools; use crate::{ ast::{self, make, HasName, HasTypeBounds}, syntax_editor::SyntaxMappingBuilder, - AstNode, SyntaxKind, SyntaxToken, + AstNode, NodeOrToken, SyntaxKind, SyntaxNode, SyntaxToken, }; use super::SyntaxFactory; @@ -169,6 +169,32 @@ impl SyntaxFactory { ast } + pub fn token_tree( + &self, + delimiter: SyntaxKind, + tt: Vec>, + ) -> ast::TokenTree { + let tt: Vec<_> = tt.into_iter().collect(); + let input: Vec<_> = tt.iter().cloned().filter_map(only_nodes).collect(); + + let ast = make::token_tree(delimiter, tt).clone_for_update(); + + if let Some(mut mapping) = self.mappings() { + let mut builder = SyntaxMappingBuilder::new(ast.syntax().clone()); + builder.map_children( + input.into_iter(), + ast.token_trees_and_tokens().filter_map(only_nodes), + ); + builder.finish(&mut mapping); + } + + return ast; + + fn only_nodes(element: NodeOrToken) -> Option { + element.as_node().map(|it| it.syntax().clone()) + } + } + pub fn token(&self, kind: SyntaxKind) -> SyntaxToken { make::token(kind) }