Write a printing tree walker for displaying tree-sitter results

ida_star
Wilfred Hughes 2021-08-28 11:39:40 +07:00
parent 2eb2f8b67d
commit 52f019c9ba
2 changed files with 22 additions and 1 deletions

@ -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);

@ -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<Syntax<'a>>,