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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
use std::marker::PhantomData;
use num_traits::{AsPrimitive, PrimInt, Unsigned};
use vob::Vob;
use super::YaccGrammar;
use crate::{RIdx, Symbol, TIdx};
/// `Firsts` stores all the first sets for a given grammar. For example, given this code and
/// grammar:
/// ```text
/// let grm = YaccGrammar::new(YaccKind::Original(YaccOriginalActionKind::GenericParseTree), "
/// S: A 'b';
/// A: 'a'
/// | ;").unwrap();
/// let firsts = Firsts::new(&grm);
/// ```
/// then the following assertions (and only the following assertions) about the firsts set are
/// correct:
/// ```text
/// assert!(firsts.is_set(grm.rule_idx("S").unwrap(), grm.token_idx("a").unwrap()));
/// assert!(firsts.is_set(grm.rule_idx("S").unwrap(), grm.token_idx("b").unwrap()));
/// assert!(firsts.is_set(grm.rule_idx("A").unwrap(), grm.token_idx("a").unwrap()));
/// assert!(firsts.is_epsilon_set(grm.rule_idx("A").unwrap()));
/// ```
#[derive(Debug)]
pub struct YaccFirsts<StorageT> {
firsts: Vec<Vob>,
epsilons: Vob,
phantom: PhantomData<StorageT>,
}
impl<StorageT: 'static + PrimInt + Unsigned> YaccFirsts<StorageT>
where
usize: AsPrimitive<StorageT>,
{
/// Generates and returns the firsts set for the given grammar.
pub fn new(grm: &YaccGrammar<StorageT>) -> Self {
let mut firsts = YaccFirsts {
firsts: vec![
Vob::from_elem(false, usize::from(grm.tokens_len()));
usize::from(grm.rules_len())
],
epsilons: Vob::from_elem(false, usize::from(grm.rules_len())),
phantom: PhantomData,
};
// Loop looking for changes to the firsts set, until we reach a fixed point. In essence, we
// look at each rule E, and see if any of the rules at the start of its productions
// have new elements in since we last looked. If they do, we'll have to do another round.
loop {
let mut changed = false;
for ridx in grm.iter_rules() {
// For each rule E
for &pidx in grm.rule_to_prods(ridx).iter() {
// ...and each production A
let prod = grm.prod(pidx);
if prod.is_empty() {
// if it's an empty production, ensure this rule's epsilon bit is
// set.
if !firsts.is_epsilon_set(ridx) {
firsts.epsilons.set(usize::from(ridx), true);
changed = true;
}
continue;
}
for (sidx, sym) in prod.iter().enumerate() {
match *sym {
Symbol::Token(s_tidx) => {
// if symbol is a token, add to FIRSTS
if !firsts.set(ridx, s_tidx) {
changed = true;
}
break;
}
Symbol::Rule(s_ridx) => {
// if we're dealing with another rule, union its FIRSTs
// together with the current rules FIRSTs. Note this is
// (intentionally) a no-op if the two tokens are one and the
// same.
for tidx in grm.iter_tidxs() {
if firsts.is_set(s_ridx, tidx) && !firsts.set(ridx, tidx) {
changed = true;
}
}
// If the epsilon bit in the rule being referenced is set,
// and if its the last symbol in the production, then add epsilon
// to FIRSTs.
if firsts.is_epsilon_set(s_ridx) && sidx == prod.len() - 1 {
// Only add epsilon if the symbol is the last in the production
if !firsts.epsilons[usize::from(ridx)] {
firsts.epsilons.set(usize::from(ridx), true);
changed = true;
}
}
// If FIRST(X) of production R : X Y2 Y3 doesn't contain epsilon,
// then don't try and calculate the FIRSTS of Y2 or Y3 (i.e. stop
// now).
if !firsts.is_epsilon_set(s_ridx) {
break;
}
}
}
}
}
}
if !changed {
return firsts;
}
}
}
/// Return all the firsts for rule `ridx`.
pub fn firsts(&self, ridx: RIdx<StorageT>) -> &Vob {
&self.firsts[usize::from(ridx)]
}
/// Returns true if the token `tidx` is in the first set for rule `ridx`.
pub fn is_set(&self, ridx: RIdx<StorageT>, tidx: TIdx<StorageT>) -> bool {
self.firsts[usize::from(ridx)][usize::from(tidx)]
}
/// Returns true if the rule `ridx` has epsilon in its first set.
pub fn is_epsilon_set(&self, ridx: RIdx<StorageT>) -> bool {
self.epsilons[usize::from(ridx)]
}
/// Ensures that the firsts bit for token `tidx` rule `ridx` is set. Returns true if
/// it was already set, or false otherwise.
pub fn set(&mut self, ridx: RIdx<StorageT>, tidx: TIdx<StorageT>) -> bool {
let r = &mut self.firsts[usize::from(ridx)];
if r[usize::from(tidx)] {
true
} else {
r.set(usize::from(tidx), true);
false
}
}
}
#[cfg(test)]
mod test {
use super::{
super::{YaccGrammar, YaccKind, YaccOriginalActionKind},
YaccFirsts,
};
use num_traits::{AsPrimitive, PrimInt, Unsigned};
fn has<StorageT: 'static + PrimInt + Unsigned>(
grm: &YaccGrammar<StorageT>,
firsts: &YaccFirsts<StorageT>,
rn: &str,
should_be: Vec<&str>,
) where
usize: AsPrimitive<StorageT>,
{
let ridx = grm.rule_idx(rn).unwrap();
for tidx in grm.iter_tidxs() {
let n = grm.token_name(tidx).unwrap_or("<no name>");
match should_be.iter().position(|&x| x == n) {
Some(_) => {
if !firsts.is_set(ridx, tidx) {
panic!("{} is not set in {}", n, rn);
}
}
None => {
if firsts.is_set(ridx, tidx) {
panic!("{} is incorrectly set in {}", n, rn);
}
}
}
}
if should_be.iter().any(|x| x == &"") {
assert!(firsts.is_epsilon_set(ridx));
}
}
#[test]
fn test_first() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start C
%token c d
%%
C: 'c';
D: 'd';
E: D | C;
F: E;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "^", vec!["c"]);
has(&grm, &firsts, "D", vec!["d"]);
has(&grm, &firsts, "E", vec!["d", "c"]);
has(&grm, &firsts, "F", vec!["d", "c"]);
}
#[test]
fn test_first_no_subsequent_rules() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start C
%token c d
%%
C: 'c';
D: 'd';
E: D C;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "E", vec!["d"]);
}
#[test]
fn test_first_epsilon() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start A
%token a b c
%%
A: B 'a';
B: 'b' | ;
C: 'c' | ;
D: C;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "A", vec!["b", "a"]);
has(&grm, &firsts, "C", vec!["c", ""]);
has(&grm, &firsts, "D", vec!["c", ""]);
}
#[test]
fn test_last_epsilon() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start A
%token b c
%%
A: B C;
B: 'b' | ;
C: B 'c' B;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "A", vec!["b", "c"]);
has(&grm, &firsts, "B", vec!["b", ""]);
has(&grm, &firsts, "C", vec!["b", "c"]);
}
#[test]
fn test_first_no_multiples() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start A
%token b c
%%
A: B 'b';
B: 'b' | ;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "A", vec!["b"]);
}
fn eco_grammar() -> YaccGrammar {
YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start S
%token a b c d f
%%
S: S 'b' | 'b' A 'a' | 'a';
A: 'a' S 'c' | 'a' | 'a' S 'b';
B: A S;
C: D A;
D: 'd' | ;
F: C D 'f';
",
)
.unwrap()
}
#[test]
fn test_first_from_eco() {
let grm = eco_grammar();
let firsts = grm.firsts();
has(&grm, &firsts, "S", vec!["a", "b"]);
has(&grm, &firsts, "A", vec!["a"]);
has(&grm, &firsts, "B", vec!["a"]);
has(&grm, &firsts, "D", vec!["d", ""]);
has(&grm, &firsts, "C", vec!["d", "a"]);
has(&grm, &firsts, "F", vec!["d", "a"]);
}
#[test]
fn test_first_from_eco_bug() {
let grm = YaccGrammar::new(
YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
"
%start E
%token a b c d e f
%%
E : T | E 'b' T;
T : P | T 'e' P;
P : 'a';
C: C 'c' | ;
D: D 'd' | F;
F: 'f' | ;
G: C D;
",
)
.unwrap();
let firsts = grm.firsts();
has(&grm, &firsts, "E", vec!["a"]);
has(&grm, &firsts, "T", vec!["a"]);
has(&grm, &firsts, "P", vec!["a"]);
has(&grm, &firsts, "C", vec!["c", ""]);
has(&grm, &firsts, "D", vec!["f", "d", ""]);
has(&grm, &firsts, "G", vec!["c", "d", "f", ""]);
}
}