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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
//! The Lr grammar class.

#![allow(missing_docs)]

use std::collections::{BTreeMap, VecDeque};
use std::rc::Rc;

use crate::history::RootHistoryNode;
use crate::prelude::*;
use crate::symbol::SymbolBitSet;

type Dot = u32;
type RuleId = u32;
type SetId = u32;

/// A container of LR(0) items.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Lr0Items {
    pub map: BTreeMap<RuleId, Lr0Item>,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Lr0Item {
    pub rhs: Vec<Symbol>,
    pub dot: Dot,
}

/// A builder for an LR(0) item closure.
pub struct Lr0ClosureBuilder<'a, G> {
    grammar: &'a mut G,
    queue: VecDeque<Lr0Item>,
    terminal_set: SymbolBitSet,
}

/// Builder of LR(0) Finite State Machine.
pub struct Lr0FsmBuilder<'a, G> {
    closure: Lr0ClosureBuilder<'a, G>,
    sets_queue: VecDeque<Rc<Lr0Items>>,
    cached_sets: BTreeMap<Rc<Lr0Items>, u32>,
}

/// An LR(0) node.
#[derive(Debug, Eq, PartialEq)]
pub struct Lr0Node {
    /// List of LR(0) items.
    pub items: Rc<Lr0Items>,
    /// List of transitions through terminals.
    pub link: BTreeMap<Symbol, SetId>,
}

impl Lr0Items {
    fn new() -> Self {
        Lr0Items {
            map: BTreeMap::new(),
        }
    }
}

impl<'a, G> Lr0ClosureBuilder<'a, G>
where
    G: RuleContainer + Default,
    for<'b> &'b G: RuleContainerRef<'b, Target = G>,
{
    /// Creates a builder for an LR(0) item closure.
    pub fn new(grammar: &'a mut G) -> Self {
        Lr0ClosureBuilder {
            queue: VecDeque::new(),
            terminal_set: SymbolBitSet::terminal_set(&grammar),
            grammar,
        }
    }

    /// We compute the closure for LR(0) items.
    pub fn closure(&mut self, items: &mut Lr0Items) {
        self.queue.clear();
        self.queue.extend(items.map.values().cloned());

        while let Some(item) = self.queue.pop_front() {
            if let Some(nonterminal_postdot) = self.nonterminal_postdot(&item) {
                for (rule_idx, rule) in self.grammar.rules().enumerate() {
                    if rule.lhs() == nonterminal_postdot {
                        let new_item = Lr0Item {
                            rhs: rule.rhs().to_vec(),
                            dot: 0,
                        };
                        if items
                            .map
                            .insert(rule_idx as RuleId, new_item.clone())
                            .is_none()
                        {
                            self.queue.push_back(new_item);
                        }
                    }
                }
            }
        }
    }

    /// Advances the items by a symbol.
    pub fn advance(&mut self, items: &Lr0Items, sym: Symbol) -> Option<Lr0Items> {
        let mut new_items = Lr0Items::new();
        for (&rule_id, item) in items.map.iter() {
            if let Some(postdot) = self.postdot(item) {
                if postdot == sym {
                    new_items.map.insert(
                        rule_id,
                        Lr0Item {
                            rhs: item.rhs.clone(),
                            dot: item.dot + 1,
                        },
                    );
                }
            }
        }
        if new_items.map.is_empty() {
            None
        } else {
            self.closure(&mut new_items);
            Some(new_items)
        }
    }

    fn postdot(&self, item: &Lr0Item) -> Option<Symbol> {
        item.rhs.get(item.dot as usize).cloned()
    }

    fn nonterminal_postdot(&self, item: &Lr0Item) -> Option<Symbol> {
        match item.rhs.get(item.dot as usize) {
            Some(&postdot) => {
                if !self.terminal_set.has_sym(postdot) {
                    Some(postdot)
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl<'a, G> Lr0FsmBuilder<'a, G>
where
    G: RuleContainer + Default,
    for<'b> &'b G: RuleContainerRef<'b, Target = G>,
{
    /// Creates a new LR(0) Finite State Machine builder.
    pub fn new(grammar: &'a mut G) -> Self {
        Lr0FsmBuilder {
            closure: Lr0ClosureBuilder::new(grammar),
            sets_queue: VecDeque::new(),
            cached_sets: BTreeMap::new(),
        }
    }

    /// Construct an LR(0) Finite State Machine.
    pub fn make_lr0_fsm(&mut self, start_sym: Symbol) -> Vec<Lr0Node> {
        self.cached_sets.clear();
        self.sets_queue.clear();

        let initial_item_set = self.initial_item_set(start_sym);
        self.introduce_set(initial_item_set, 0);
        let mut result = vec![];
        while let Some(items) = self.sets_queue.pop_front() {
            let mut link = BTreeMap::new();
            let terminals: Vec<Symbol> = self.closure.terminal_set.iter().collect();
            for terminal in terminals {
                if let Some(advanced_set) = self.closure.advance(&items, terminal) {
                    let id = self.id_of(Rc::new(advanced_set));
                    link.insert(terminal, id);
                }
            }
            result.push(Lr0Node { items, link })
        }
        result
    }

    fn initial_item_set(&mut self, start_sym: Symbol) -> Rc<Lr0Items> {
        let (_new_start, new_start_rule_id) = self.augment_grammar(start_sym);
        let initial_item = Lr0Item {
            rhs: vec![start_sym],
            dot: 0,
        };
        let mut initial_item_set = Lr0Items::new();
        initial_item_set.map.insert(new_start_rule_id, initial_item);
        self.closure.closure(&mut initial_item_set);
        Rc::new(initial_item_set)
    }

    fn augment_grammar(&mut self, start_sym: Symbol) -> (Symbol, RuleId) {
        let new_start = self.closure.grammar.sym();
        let rule_id = self.closure.grammar.rules().count() as RuleId;
        let history_id = self
            .closure
            .grammar
            .add_history_node(RootHistoryNode::NoOp.into());
        self.closure
            .grammar
            .rule(new_start)
            .rhs_with_history(&[start_sym], history_id);
        (new_start, rule_id)
    }

    fn id_of(&mut self, items: Rc<Lr0Items>) -> SetId {
        match self.cached_sets.get(&items) {
            None => {
                let id = self.cached_sets.len() as SetId;
                self.introduce_set(items, id);
                id
            }
            Some(&id) => id,
        }
    }

    fn introduce_set(&mut self, items: Rc<Lr0Items>, id: SetId) {
        self.cached_sets.insert(items.clone(), id);
        self.sets_queue.push_back(items);
    }
}