aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: f99d31b3661ae9a3019f9a9d03bfb8e5a94ee273 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use std::{collections::BTreeSet, fmt::Write};
use {SyntaxError, SyntaxNode, SyntaxNodeRef};

/// Parse a file and create a string representation of the resulting parse tree.
pub fn dump_tree(syntax: &SyntaxNode) -> String {
    let syntax = syntax.as_ref();
    let mut errors: BTreeSet<_> = syntax.root.errors.iter().cloned().collect();
    let mut result = String::new();
    go(syntax, &mut result, 0, &mut errors);
    return result;

    fn go(
        node: SyntaxNodeRef,
        buff: &mut String,
        level: usize,
        errors: &mut BTreeSet<SyntaxError>,
    ) {
        buff.push_str(&String::from("  ").repeat(level));
        writeln!(buff, "{:?}", node).unwrap();
        let my_errors: Vec<_> = errors
            .iter()
            .filter(|e| e.offset == node.range().start())
            .cloned()
            .collect();
        for err in my_errors {
            errors.remove(&err);
            buff.push_str(&String::from("  ").repeat(level));
            writeln!(buff, "err: `{}`", err.message).unwrap();
        }

        for child in node.children() {
            go(child, buff, level + 1, errors)
        }

        let my_errors: Vec<_> = errors
            .iter()
            .filter(|e| e.offset == node.range().end())
            .cloned()
            .collect();
        for err in my_errors {
            errors.remove(&err);
            buff.push_str(&String::from("  ").repeat(level));
            writeln!(buff, "err: `{}`", err.message).unwrap();
        }
    }
}