From d417fc9ae19c36b5d741bf6ce78aa9ac5bc29fe5 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Tue, 7 Dec 2021 23:08:06 -0800 Subject: [PATCH] Print string contents of tree-sitter leaf nodes --- src/main.rs | 2 +- src/tree_sitter_parser.rs | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 20dd136c7..4d18e5ad0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -189,7 +189,7 @@ fn main() { let bytes = read_or_die(&path); let src = String::from_utf8_lossy(&bytes).to_string(); let (tree, _) = tsp::parse_to_tree(&src, &ts_lang); - tsp::print_tree(&tree); + tsp::print_tree(&src, &tree); } None => { println!("No tree-sitter parser for extension: {:?}", extension); diff --git a/src/tree_sitter_parser.rs b/src/tree_sitter_parser.rs index 3b871a7ee..d363cfaed 100644 --- a/src/tree_sitter_parser.rs +++ b/src/tree_sitter_parser.rs @@ -320,18 +320,25 @@ pub fn parse_to_tree(src: &str, config: &TreeSitterConfig) -> (tree_sitter::Tree (tree, node_keyword_ids) } -pub fn print_tree(tree: &tree_sitter::Tree) { +pub fn print_tree(src: &str, tree: &tree_sitter::Tree) { let mut cursor = tree.walk(); - print_cursor(&mut cursor, 0); + print_cursor(src, &mut cursor, 0); } -fn print_cursor(cursor: &mut TreeCursor, depth: usize) { +fn print_cursor(src: &str, cursor: &mut TreeCursor, depth: usize) { loop { let node = cursor.node(); - println!("{}{:#?}", " ".repeat(depth), node); + node.end_position(); + + if node.child_count() == 0 { + let node_src = &src[node.start_byte()..node.end_byte()]; + println!("{}{:#?} {:?}", " ".repeat(depth), node, node_src); + } else { + println!("{}{:#?}", " ".repeat(depth), node); + } if cursor.goto_first_child() { - print_cursor(cursor, depth + 1); + print_cursor(src, cursor, depth + 1); cursor.goto_parent(); }