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
171
172
173
use std::cmp;
use std::collections;
use std::ops;
use std::rc;

use grammar;

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RawNode {
    pub span: ops::Range<usize>,
    pub name: rc::Rc<str>,
    pub non_terminals: Vec<Node>,
}

impl RawNode {
    pub fn dump(&self, indent: usize) {
        println!(
            "{:indent$}{} @ {:?}",
            "",
            self.name,
            self.span,
            indent = indent
        );
        for each in self.non_terminals.iter() {
            each.dump(indent + 4);
        }
    }
}

impl PartialOrd for RawNode {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawNode {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        cmp::Ordering::Equal
            .then(self.span.start.cmp(&other.span.start))
            .then(self.span.end.cmp(&other.span.end))
            .then(self.name.cmp(&other.name))
            .then(self.non_terminals.cmp(&other.non_terminals))
    }
}

/// A reference-counted [`RawNode`]
///
/// [`RawNode`]: struct.RawNode.html
pub type Node = rc::Rc<RawNode>;

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct PartialNode {
    /// We know the contents of this node within this span.
    known_span: ops::Range<usize>,
    /// The completed symbols of this node, in reverse order.
    reversed_non_terminals: Vec<Node>,
}

impl PartialNode {
    fn step_back(
        mut self,
        symbol: &grammar::Symbol,
        builder: &Builder,
    ) -> collections::BTreeSet<PartialNode> {
        let mut res = collections::BTreeSet::new();

        if self.known_span.start == 0 {
            // Stepping this back any further won't produce a sensible result.
            return res;
        }

        match symbol {
            grammar::Symbol::Terminal(_) => {
                self.known_span.start -= 1;
                res.insert(self);
            }

            grammar::Symbol::NonTerminal(name) => {
                for each in builder.get(..self.known_span.start, name.clone()) {
                    let mut new_partial = self.clone();
                    new_partial.known_span.start = each.span.start;
                    new_partial.reversed_non_terminals.push(each.clone());

                    res.insert(new_partial);
                }
            }
        }

        res
    }
}

impl PartialOrd for PartialNode {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for PartialNode {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        cmp::Ordering::Equal
            .then(self.known_span.start.cmp(&other.known_span.start))
            .then(self.known_span.end.cmp(&other.known_span.end))
            .then(
                self.reversed_non_terminals
                    .cmp(&other.reversed_non_terminals),
            )
    }
}

#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Builder(
    collections::BTreeMap<(usize, rc::Rc<str>), collections::BTreeSet<Node>>,
);

impl Builder {
    pub fn new() -> Builder {
        Default::default()
    }

    pub fn rule_completed<'a>(
        &mut self,
        span: ops::Range<usize>,
        name: rc::Rc<str>,
        symbols: &'a [grammar::Symbol],
    ) {
        let mut partials = collections::BTreeSet::new();
        partials.insert(PartialNode {
            known_span: span.end..span.end,
            reversed_non_terminals: vec![],
        });

        for symbol in symbols.iter().rev() {
            partials = partials
                .into_iter()
                .flat_map(|each| each.step_back(symbol, self))
                .collect();
        }

        let newly_completed_nodes = partials
            .into_iter()
            .filter(|each| each.known_span == span)
            .map(|each| {
                let mut non_terminals = each.reversed_non_terminals;
                non_terminals.reverse();

                rc::Rc::new(RawNode {
                    span: each.known_span,
                    name: name.clone(),
                    non_terminals: non_terminals,
                })
            }).collect::<Vec<_>>();

        // TODO: If newly_completed_nodes contains more than one item,
        // we should choose one to avoid an ambiguous parse tree.

        let node_set = self.0.entry((span.end, name)).or_default();
        for each in newly_completed_nodes {
            node_set.insert(each);
        }
    }

    pub fn get(
        &self,
        end_by: ops::RangeTo<usize>,
        named: rc::Rc<str>,
    ) -> collections::BTreeSet<Node> {
        self.0
            .get(&(end_by.end, named))
            .cloned()
            .unwrap_or_default()
    }
}