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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use crate::collections::Collection;
use crate::grammar::repr::*;
use crate::lr1::core::*;
use crate::lr1::tls::Lr1Tls;
use bit_set::{self, BitSet};
use std::fmt::{Debug, Error, Formatter};
use std::hash::Hash;

pub trait Lookahead: Clone + Debug + Eq + Ord + Hash + Collection<Item = Self> {
    fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error>;

    fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>>;
}

#[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Nil;

impl Collection for Nil {
    type Item = Nil;

    fn push(&mut self, _: Nil) -> bool {
        false
    }
}

impl Lookahead for Nil {
    fn fmt_as_item_suffix(&self, _fmt: &mut Formatter) -> Result<(), Error> {
        Ok(())
    }

    fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> {
        let index = this_state.index;

        let mut conflicts = vec![];

        for (terminal, &next_state) in &this_state.shifts {
            conflicts.extend(
                this_state
                    .reductions
                    .iter()
                    .map(|&(_, production)| Conflict {
                        state: index,
                        lookahead: Nil,
                        production,
                        action: Action::Shift(terminal.clone(), next_state),
                    }),
            );
        }

        if this_state.reductions.len() > 1 {
            for &(_, production) in &this_state.reductions[1..] {
                let other_production = this_state.reductions[0].1;
                conflicts.push(Conflict {
                    state: index,
                    lookahead: Nil,
                    production,
                    action: Action::Reduce(other_production),
                });
            }
        }

        conflicts
    }
}

/// I have semi-arbitrarily decided to use the term "token" to mean
/// either one of the terminals of our language, or else the
/// pseudo-symbol EOF that represents "end of input".
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Token {
    Eof,
    Error,
    Terminal(TerminalString),
}

impl Lookahead for TokenSet {
    fn fmt_as_item_suffix(&self, fmt: &mut Formatter) -> Result<(), Error> {
        write!(fmt, " {:?}", self)
    }

    fn conflicts<'grammar>(this_state: &State<'grammar, Self>) -> Vec<Conflict<'grammar, Self>> {
        let mut conflicts = vec![];

        for (terminal, &next_state) in &this_state.shifts {
            let token = Token::Terminal(terminal.clone());
            let inconsistent =
                this_state
                    .reductions
                    .iter()
                    .filter_map(|&(ref reduce_tokens, production)| {
                        if reduce_tokens.contains(&token) {
                            Some(production)
                        } else {
                            None
                        }
                    });
            let set = TokenSet::from(token.clone());
            for production in inconsistent {
                conflicts.push(Conflict {
                    state: this_state.index,
                    lookahead: set.clone(),
                    production,
                    action: Action::Shift(terminal.clone(), next_state),
                });
            }
        }

        let len = this_state.reductions.len();
        for i in 0..len {
            for j in i + 1..len {
                let &(ref i_tokens, i_production) = &this_state.reductions[i];
                let &(ref j_tokens, j_production) = &this_state.reductions[j];

                if i_tokens.is_disjoint(j_tokens) {
                    continue;
                }

                conflicts.push(Conflict {
                    state: this_state.index,
                    lookahead: i_tokens.intersection(j_tokens),
                    production: i_production,
                    action: Action::Reduce(j_production),
                });
            }
        }

        conflicts
    }
}

impl Token {
    #[deprecated(since = "1.0.0", note = "use `Eof` instead")]
    pub const EOF: Self = Self::Eof;

    pub fn unwrap_terminal(&self) -> &TerminalString {
        match *self {
            Token::Terminal(ref t) => t,
            Token::Eof | Token::Error => {
                panic!("`unwrap_terminal()` invoked but with EOF or Error")
            }
        }
    }
}

#[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct TokenSet {
    bit_set: BitSet<u32>,
}

fn with<OP, RET>(op: OP) -> RET
where
    OP: FnOnce(&TerminalSet) -> RET,
{
    Lr1Tls::with(op)
}

impl TokenSet {
    pub fn new() -> Self {
        with(|terminals| TokenSet {
            bit_set: BitSet::with_capacity(terminals.all.len() + 2),
        })
    }

    /// A TokenSet containing all possible terminals + EOF.
    pub fn all() -> Self {
        let mut s = TokenSet::new();
        with(|terminals| {
            for i in 0..terminals.all.len() {
                s.bit_set.insert(i);
            }
            s.insert_eof();
        });
        s
    }

    pub fn eof() -> Self {
        let mut set = TokenSet::new();
        set.insert_eof();
        set
    }

    fn eof_bit(&self) -> usize {
        with(|terminals| terminals.all.len())
    }

    fn bit(&self, lookahead: &Token) -> usize {
        with(|t| self.bit_with(lookahead, t))
    }

    fn bit_with(&self, lookahead: &Token, terminals: &TerminalSet) -> usize {
        match *lookahead {
            Token::Eof => terminals.all.len(),
            Token::Error => terminals.all.len() + 1,
            Token::Terminal(ref t) => terminals.bits[t],
        }
    }

    pub fn reserve(&mut self, len: usize) {
        self.bit_set.reserve_len(len)
    }

    pub fn len(&self) -> usize {
        self.bit_set.len()
    }

    pub fn insert(&mut self, lookahead: Token) -> bool {
        let bit = self.bit(&lookahead);
        self.bit_set.insert(bit)
    }

    pub fn insert_with(&mut self, lookahead: Token, terminals: &TerminalSet) -> bool {
        let bit = self.bit_with(&lookahead, terminals);
        self.bit_set.insert(bit)
    }

    pub fn insert_eof(&mut self) -> bool {
        let bit = self.eof_bit();
        self.bit_set.insert(bit)
    }

    pub fn union_with(&mut self, set: &TokenSet) -> bool {
        let len = self.len();
        self.bit_set.union_with(&set.bit_set);
        self.len() != len
    }

    pub fn intersection(&self, set: &TokenSet) -> TokenSet {
        let mut bit_set = self.bit_set.clone();
        bit_set.intersect_with(&set.bit_set);
        TokenSet { bit_set }
    }

    pub fn contains(&self, token: &Token) -> bool {
        self.bit_set.contains(self.bit(token))
    }

    pub fn contains_eof(&self) -> bool {
        self.bit_set.contains(self.eof_bit())
    }

    /// If this set contains EOF, removes it from the set and returns
    /// true. Otherwise, returns false.
    pub fn take_eof(&mut self) -> bool {
        let eof_bit = self.eof_bit();
        let contains_eof = self.bit_set.contains(eof_bit);
        self.bit_set.remove(eof_bit);
        contains_eof
    }

    pub fn is_disjoint(&self, other: &TokenSet) -> bool {
        self.bit_set.is_disjoint(&other.bit_set)
    }

    pub fn is_intersecting(&self, other: &TokenSet) -> bool {
        !self.is_disjoint(other)
    }

    pub fn iter(&self) -> TokenSetIter<'_> {
        TokenSetIter {
            bit_set: self.bit_set.iter(),
        }
    }
}

pub struct TokenSetIter<'iter> {
    bit_set: bit_set::Iter<'iter, u32>,
}

impl<'iter> Iterator for TokenSetIter<'iter> {
    type Item = Token;

    fn next(&mut self) -> Option<Token> {
        self.bit_set.next().map(|bit| {
            with(|terminals| {
                if bit == terminals.all.len() + 1 {
                    Token::Error
                } else if bit == terminals.all.len() {
                    Token::Eof
                } else {
                    Token::Terminal(terminals.all[bit].clone())
                }
            })
        })
    }
}

impl Debug for TokenSet {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        let terminals: Vec<_> = self.iter().collect();
        Debug::fmt(&terminals, fmt)
    }
}

impl<'iter> IntoIterator for &'iter TokenSet {
    type IntoIter = TokenSetIter<'iter>;
    type Item = Token;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl Collection for TokenSet {
    type Item = TokenSet;

    fn push(&mut self, item: TokenSet) -> bool {
        self.union_with(&item)
    }
}

impl From<Token> for TokenSet {
    fn from(token: Token) -> Self {
        let mut set = TokenSet::new();
        set.insert(token);
        set
    }
}