use std::iter;
use bit_vec;
use bit_vec::BitVec;
use crate::prelude::*;
pub struct SymbolBitSet {
bit_vec: BitVec,
}
pub struct Iter<'a> {
iter: iter::Enumerate<bit_vec::Iter<'a>>,
}
impl SymbolBitSet {
pub fn new<'a, G>(grammar: &'a G, elem: bool) -> Self
where
G: RuleContainer + Default,
&'a G: RuleContainerRef<'a, Target = G>,
{
SymbolBitSet {
bit_vec: BitVec::from_elem(grammar.num_syms(), elem),
}
}
pub fn terminal_set<'a, G>(grammar: &'a G) -> Self
where
G: RuleContainer + Default,
&'a G: RuleContainerRef<'a, Target = G>,
{
let mut set = SymbolBitSet::new(grammar, true);
for rule in grammar.rules() {
set.set(rule.lhs(), false);
}
set
}
pub fn terminal_or_nulling_set<'a, G>(grammar: &'a G) -> Self
where
G: RuleContainer + Default,
&'a G: RuleContainerRef<'a, Target = G>,
{
let mut set = SymbolBitSet::new(grammar, true);
for rule in grammar.rules() {
set.set(rule.lhs(), false);
}
for rule in grammar.rules() {
if rule.rhs().is_empty() {
set.set(rule.lhs(), true);
}
}
set
}
pub fn set(&mut self, sym: Symbol, value: bool) {
self.bit_vec.set(sym.into(), value);
}
pub fn has_sym(&self, sym: Symbol) -> bool {
self.bit_vec[sym.into()]
}
pub fn into_bit_vec(self) -> BitVec {
self.bit_vec
}
pub fn iter(&self) -> Iter {
Iter {
iter: self.bit_vec.iter().enumerate(),
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = Symbol;
fn next(&mut self) -> Option<Self::Item> {
for (id, is_present) in &mut self.iter {
if is_present {
return Some(Symbol::from(id));
}
}
None
}
}