Skip to main content

dump_ast/
dump_ast.rs

1use tree_sitter::Parser;
2use tsift_graph::lang::Lang;
3
4fn dump(lang_name: &str, lang: Lang, source: &str, _depth: usize) {
5    let mut parser = Parser::new();
6    parser.set_language(&lang.tree_sitter_language()).unwrap();
7    let tree = parser.parse(source.as_bytes(), None).unwrap();
8    println!("=== {} ===", lang_name);
9    println!("Source:\n{}\n", source);
10    fn walk(node: tree_sitter::Node, source: &str, indent: usize) {
11        let text = &source[node.byte_range()];
12        let short = if text.len() > 60 { &text[..60] } else { text };
13        let short = short.replace('\n', "\\n");
14        println!(
15            "{}{} [{}-{}] {:?}",
16            "  ".repeat(indent),
17            node.kind(),
18            node.start_position().row,
19            node.end_position().row,
20            short
21        );
22        let mut cursor = node.walk();
23        if cursor.goto_first_child() {
24            loop {
25                walk(cursor.node(), source, indent + 1);
26                if !cursor.goto_next_sibling() {
27                    break;
28                }
29            }
30        }
31    }
32    walk(tree.root_node(), source, 0);
33    println!();
34}
35
36fn main() {
37    #[cfg(feature = "lang-zig")]
38    dump(
39        "Zig",
40        Lang::Zig,
41        r#"
42const std = @import("std");
43pub fn main() !void {}
44const Point = struct { x: i32, y: i32 };
45const Color = enum { red, green, blue };
46const Result = union(enum) { ok: i32, err: []const u8 };
47"#
48        .trim(),
49        4,
50    );
51
52    #[cfg(feature = "lang-bash")]
53    dump(
54        "Bash",
55        Lang::Bash,
56        r#"
57#!/bin/bash
58hello() { echo hi; }
59function world { echo world; }
60alias ll='ls -la'
61alias grep='grep --color=auto'
62"#
63        .trim(),
64        4,
65    );
66
67    #[cfg(feature = "lang-markdown")]
68    dump(
69        "Markdown",
70        Lang::Markdown,
71        r#"
72# Title
73
74## Section
75
76```rust
77fn main() {}
78```
79
80```python
81def hello():
82    pass
83```
84
85### Subsection
86"#
87        .trim(),
88        4,
89    );
90}