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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::collections::HashMap;
use inlinable_string::InlinableString;

use crate::input::{Show, Input, Debugger, ParserInfo};
use crate::macros::is_parse_debug;

type Index = usize;

struct Tree<T> {
    // All of the nodes in the tree live in this vector.
    nodes: Vec<T>,
    // Maps from an index (`parent`) index `nodes` to a set of indexes in
    // `nodes` corresponding to the children of `key`.
    children: HashMap<Index, Vec<Index>>,
    // This "tree" keeps track of which parent children are currently being
    // pushed to. A `push` adds to this stack while a `pop` removes from this
    // stack. If the stack is empty, the root is being pushed to.
    stack: Vec<Index>
}

impl<T> Tree<T> {
    fn new() -> Tree<T> {
        Tree {
            nodes: vec![],
            children: HashMap::new(),
            stack: Vec::with_capacity(8)
        }
    }

    fn push(&mut self, node: T) -> Index {
        // Add the node to the tree and get its index.
        self.nodes.push(node);
        let index = self.nodes.len() - 1;

        // If the stack indicates we have a parent, add to its children.
        if !self.stack.is_empty() {
            let parent = self.stack[self.stack.len() - 1];
            self.children.entry(parent).or_insert(vec![]).push(index);
        }

        // Make this the new parent.
        self.stack.push(index);
        index
    }

    fn pop_level(&mut self) -> Option<Index> {
        self.stack.pop()
    }

    fn clear(&mut self) {
        *self = Self::new();
    }

    fn get(&self, index: Index) -> &T {
        &self.nodes[index]
    }

    fn get_mut(&mut self, index: Index) -> &mut T {
        &mut self.nodes[index]
    }

    fn get_children(&self, index: Index) -> &[Index] {
        match self.children.get(&index) {
            Some(children) => &children[..],
            None => &[]
        }
    }
}

impl Tree<Info> {
    fn debug_print(&self, sibling_map: &mut Vec<bool>, node: Index) {
        let parent_count = sibling_map.len();
        for (i, &has_siblings) in sibling_map.iter().enumerate() {
            if i < parent_count - 1 {
                match has_siblings {
                    true => print!(" │   "),
                    false => print!("     ")
                }
            } else {
                match has_siblings {
                    true => print!(" ├── "),
                    false => print!(" └── ")
                }
            }
        }

        let info = self.get(node);
        let success = match info.success {
            Some(true) => " ✓",
            Some(false) => " ✗",
            None => ""
        };

        #[cfg(feature = "color")]
        use yansi::{Style, Paint, Color::*};

        #[cfg(feature = "color")]
        let style = match info.success {
            Some(true) => Green.into(),
            Some(false) => Red.into(),
            None => Style::default(),
        };

        #[cfg(feature = "color")]
        println!("{}{} ({})", info.parser.name.paint(style), success.paint(style), info.context);

        #[cfg(not(feature = "color"))]
        println!("{}{} ({})", info.parser.name, success, info.context);

        let children = self.get_children(node);
        let num_children = children.len();
        for (i, &child) in children.iter().enumerate() {
            let have_siblings = i != (num_children - 1);
            sibling_map.push(have_siblings);
            self.debug_print(sibling_map, child);
            sibling_map.pop();
        }
    }
}

struct Info {
    parser: ParserInfo,
    context: InlinableString,
    success: Option<bool>,
}

impl Info {
    fn new(parser: ParserInfo) -> Self {
        Info { parser, context: iformat!(), success: None }
    }
}

pub struct TreeDebugger {
    tree: Tree<Info>,
}

impl TreeDebugger {
    pub fn new() -> Self {
        Self { tree: Tree::new() }
    }
}

impl<I: Input> Debugger<I> for TreeDebugger {
    fn on_entry(&mut self, p: &ParserInfo) {
        if !((p.raw && is_parse_debug!("full")) || (!p.raw && is_parse_debug!())) {
            return;
        }

        self.tree.push(Info::new(*p));
    }

    fn on_exit(&mut self, p: &ParserInfo, ok: bool, ctxt: I::Context) {
        if !((p.raw && is_parse_debug!("full")) || (!p.raw && is_parse_debug!())) {
            return;
        }

        let index = self.tree.pop_level();
        if let Some(last_node) = index {
            let last = self.tree.get_mut(last_node);
            last.success = Some(ok);
            last.context = iformat!("{}", &ctxt as &dyn Show);
        }

        // We've reached the end. Print the whole thing and clear the tree.
        if let Some(0) = index {
            self.tree.debug_print(&mut vec![], 0);
            self.tree.clear();
        }
    }
}