From 52f019c9ba5b080b0a3da1fcf5c0512cc9971e41 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Sat, 28 Aug 2021 11:39:40 -0700 Subject: [PATCH] Write a printing tree walker for displaying tree-sitter results --- src/main.rs | 2 +- src/tree_sitter_parser.rs | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 39c6052b7..4611559a3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -147,7 +147,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); - println!("{:#?}", tree.root_node()); + tsp::print_tree(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 c6ecd8778..7606e60bc 100644 --- a/src/tree_sitter_parser.rs +++ b/src/tree_sitter_parser.rs @@ -112,6 +112,27 @@ pub fn parse_to_tree(src: &str, config: &TreeSitterConfig) -> tree_sitter::Tree parser.parse(src, None).unwrap() } +pub fn print_tree(tree: tree_sitter::Tree) { + let mut cursor = tree.walk(); + print_cursor(&mut cursor, 0); +} + +fn print_cursor(cursor: &mut TreeCursor, depth: usize) { + loop { + let node = cursor.node(); + println!("{}{:#?}", " ".repeat(depth), node); + + if cursor.goto_first_child() { + print_cursor(cursor, depth + 1); + cursor.goto_parent(); + } + + if !cursor.goto_next_sibling() { + break; + } + } +} + /// Parse `src` with tree-sitter and convert to difftastic Syntax. pub fn parse<'a>( arena: &'a Arena>,