fork of https://github.com/tree-sitter/tree-sitter-graph

Add `join` function

Changed files
+74
src
tests
+1
CHANGELOG.md
··· 15 15 - Function `eq` to compare two values for equality. 16 16 - Function `format` to format strings. 17 17 - Function `concat` to concatenate lists. 18 + - Function `join` to join a list of values using an optional separator. 18 19 19 20 #### Removed 20 21
+26
src/functions.rs
··· 133 133 // list functions 134 134 functions.add(Identifier::from("concat"), stdlib::list::Concat); 135 135 functions.add(Identifier::from("is-empty"), stdlib::list::IsEmpty); 136 + functions.add(Identifier::from("join"), stdlib::list::Join); 136 137 functions.add(Identifier::from("length"), stdlib::list::Length); 137 138 functions 138 139 } ··· 612 613 ) -> Result<Value, ExecutionError> { 613 614 let list = parameters.param()?.into_list()?; 614 615 Ok(list.is_empty().into()) 616 + } 617 + } 618 + 619 + /// The implementation of the standard [`join`][`crate::reference::functions#join`] function. 620 + pub struct Join; 621 + 622 + impl Function for Join { 623 + fn call( 624 + &self, 625 + _graph: &mut Graph, 626 + _source: &str, 627 + parameters: &mut dyn Parameters, 628 + ) -> Result<Value, ExecutionError> { 629 + let list = parameters.param()?.into_list()?; 630 + let sep = match parameters.param() { 631 + Ok(sep) => sep.into_string()?, 632 + Err(_) => "".to_string(), 633 + }; 634 + parameters.finish()?; 635 + let result = list 636 + .into_iter() 637 + .map(|x| format!("{}", x)) 638 + .collect::<Vec<_>>() 639 + .join(&sep); 640 + Ok(result.into()) 615 641 } 616 642 } 617 643
+11
src/reference/functions.rs
··· 118 118 //! - Input parameters: a list value 119 119 //! - Output value: a boolean indicating whether the list is empty or not 120 120 //! 121 + //! ## `join` 122 + //! 123 + //! Join a list of values using the given separator 124 + //! 125 + //! - Input parameters: 126 + //! - `list`: A list of values 127 + //! - `sep`: An optional separator string 128 + //! - Output value: 129 + //! - A string consisting of the formatted values from the list separated by 130 + //! the separator string 131 + //! 121 132 //! ## `length` 122 133 //! 123 134 //! Determine the length of a list.
+36
tests/it/functions.rs
··· 196 196 "#}, 197 197 ); 198 198 } 199 + 200 + #[test] 201 + fn can_join_list_with_separator() { 202 + check_execution( 203 + "pass", 204 + indoc! {r#" 205 + (module) @root 206 + { 207 + node n 208 + attr (n) str = (join [1, 2, 3] ".") 209 + } 210 + "#}, 211 + indoc! {r#" 212 + node 0 213 + str: "1.2.3" 214 + "#}, 215 + ); 216 + } 217 + 218 + #[test] 219 + fn can_join_list_without_separator() { 220 + check_execution( 221 + "pass", 222 + indoc! {r#" 223 + (module) @root 224 + { 225 + node n 226 + attr (n) str = (join [1, 2, 3]) 227 + } 228 + "#}, 229 + indoc! {r#" 230 + node 0 231 + str: "123" 232 + "#}, 233 + ); 234 + }