Debian Codegraph @

Xtree-house/highlighter/src/pretty_print.rs

raw symbols SCIP
1 use std::fmt;
2
3 use tree_sitter::{SyntaxTreeNode, TreeCursor};
4
5 pub fn pretty_print_tree<W: fmt::Write>(fmt: &mut W, node: SyntaxTreeNode) -> fmt::Result {
6 if node.child_count() == 0 {
7 if node_is_visible(&node) {
8 write!(fmt, "({})", node.kind())
9 } else {
10 write!(fmt, "\"{}\"", node.kind())
11 }
12 } else {
13 pretty_print_tree_impl(fmt, &mut node.walk(), 0)
14 }
15 }
16
17 fn pretty_print_tree_impl<W: fmt::Write>(
18 fmt: &mut W,
19 cursor: &mut TreeCursor,
20 depth: usize,
21 ) -> fmt::Result {
22 let node = cursor.node();
23 let visible = node_is_visible(&node);
24
25 if visible {
26 let indentation_columns = depth * 2;
27 write!(fmt, "{:indentation_columns$}", "")?;
28
29 if let Some(field_name) = cursor.field_name() {
30 write!(fmt, "{}: ", field_name)?;
31 }
32
33 write!(fmt, "({}", node.kind())?;
34 }
35
36 // Handle children.
37 if cursor.goto_first_child() {
38 loop {
39 if node_is_visible(&cursor.node()) {
40 fmt.write_char('\n')?;
41 }
42
43 pretty_print_tree_impl(fmt, cursor, depth + 1)?;
44
45 if !cursor.goto_next_sibling() {
46 break;
47 }
48 }
49
50 let moved = cursor.goto_parent();
51 // The parent of the first child must exist, and must be `node`.
52 debug_assert!(moved);
53 debug_assert!(cursor.node() == node);
54 }
55
56 if visible {
57 fmt.write_char(')')?;
58 }
59
60 Ok(())
61 }
62
63 fn node_is_visible(node: &SyntaxTreeNode) -> bool {
64 node.is_missing() || (node.is_named() && node.language().node_kind_is_visible(node.kind_id()))
65 }