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
use crate::{Pr, Symbol, Terminal};
use std::cell::RefCell;
use std::fmt::{Display, Error, Formatter};

///
/// Type of the RHS of a Production type
///
#[derive(Debug, Clone, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SymbolString(pub Vec<Symbol>);

///
/// Internal state type that controls the search of k-complete substrings.
///
#[derive(Debug, Clone)]
enum State {
    Initial,
    NtFound(usize, usize),
    KComplete(usize, usize),
}

impl SymbolString {
    ///
    /// Construction from a given production
    ///
    pub fn from_production(pr: &Pr) -> Self {
        Self(pr.get_r().clone())
    }

    ///
    /// Construction from a given symbol string
    ///
    pub fn from_slice(symbols: &[Symbol]) -> Self {
        Self(symbols.to_vec())
    }

    ///
    /// Find a k-complete sub-symbol-string within this symbol-string.
    ///
    /// k-complete means here that for a given non-terminal nt there exists a
    /// sequence of terminals with length k <<OR>> a sequence of terminals with
    /// 0 <= length < k followed by an END symbol that is directly following it.
    ///
    pub fn is_k_complete_for_nt_at(
        &self,
        nt: &str,
        k: usize,
        start: usize,
    ) -> Option<(usize, usize)> {
        let state = RefCell::new(State::Initial);
        self.0.iter().enumerate().skip(start).for_each(|(idx, sy)| {
            let old_state = state.borrow().clone();
            let mut new_state = state.borrow_mut();
            match (old_state, sy) {
                (State::Initial, Symbol::N(n)) if n == nt => *new_state = State::NtFound(idx, 0),
                (State::Initial, _) => (),
                (State::NtFound(nt_idx, len), Symbol::T(Terminal::Trm(_))) if len + 1 < k => {
                    *new_state = State::NtFound(nt_idx, len + 1)
                }
                (State::NtFound(nt_idx, len), Symbol::T(Terminal::Trm(_))) => {
                    *new_state = State::KComplete(nt_idx, len + 1)
                }
                (State::NtFound(nt_idx, len), Symbol::T(Terminal::End)) => {
                    *new_state = State::KComplete(nt_idx, len + 1)
                }
                (State::NtFound(_, _), Symbol::N(n)) if n == nt => {
                    *new_state = State::NtFound(idx, 0)
                }
                (State::NtFound(_, _), Symbol::N(_)) => *new_state = State::Initial,
                (State::NtFound(_, _), Symbol::T(Terminal::Eps)) => {
                    panic!("Not allowed symbol type for symbol string: Epsilon")
                }
                (State::KComplete(_, _), _) => (),
            }
        });
        if let State::KComplete(start_idx, len) = state.into_inner() {
            Some((start_idx, len))
        } else {
            None
        }
    }

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

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn first_len(&self) -> usize {
        self.0
            .iter()
            .take_while(|s| {
                matches!(s, Symbol::T(Terminal::Trm(_))) || matches!(s, Symbol::T(Terminal::End))
            })
            .count()
    }

    pub fn is_k_derivable(&self, k: usize) -> bool {
        // Necessary
        self.first_len() < k &&
        // Possible
        self.0.iter().any(|s| matches!(s, Symbol::N(_)))
    }

    pub fn static_first_len(symbols: &[Symbol]) -> usize {
        symbols
            .iter()
            .take_while(|s| {
                matches!(s, Symbol::T(Terminal::Trm(_))) || matches!(s, Symbol::T(Terminal::End))
            })
            .count()
    }
}

impl Display for SymbolString {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .map(|e| format!("{}", e))
                .collect::<Vec<String>>()
                .join(", ")
        )
    }
}

#[cfg(test)]
mod test {
    use crate::grammar::SymbolString;
    use crate::Symbol;

    fn t(t: &str) -> Symbol {
        Symbol::t(t)
    }

    fn n(n: &str) -> Symbol {
        Symbol::n(n)
    }

    fn e() -> Symbol {
        Symbol::e()
    }

    lazy_static! {
        pub static ref TEST_DATA: Vec<(
            SymbolString,
            (&'static str, usize, usize),
            Option<(usize, usize)>
        )> = vec![
            (SymbolString(vec![]), ("B", 1, 0), None),
            (SymbolString(vec![t("a"), n("A")]), ("B", 1, 0), None),
            (
                SymbolString(vec![t("a"), n("B"), n("A")]),
                ("B", 1, 0),
                None
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a")]),
                ("B", 1, 0),
                Some((1, 1))
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a"), t("a")]),
                ("B", 1, 0),
                Some((1, 1))
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a"), t("a")]),
                ("B", 2, 0),
                Some((1, 2))
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a"), t("a"), t("a")]),
                ("B", 2, 0),
                Some((1, 2))
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a"), t("a"), e()]),
                ("B", 2, 0),
                Some((1, 2))
            ),
            (
                SymbolString(vec![t("a"), n("B"), t("a"), e()]),
                ("B", 2, 0),
                Some((1, 2))
            ),
            (
                SymbolString(vec![t("a"), n("B"), e()]),
                ("B", 2, 0),
                Some((1, 1))
            ),
            (
                SymbolString(vec![t("a"), n("B"), e()]),
                ("B", 2, 1),
                Some((1, 1))
            ),
            (
                SymbolString(vec![t("a"), n("B"), e()]),
                ("B", 1, 0),
                Some((1, 1))
            ),
        ];
    }

    #[test]
    fn test_is_k_complete_for_nt_at() {
        TEST_DATA
            .iter()
            .for_each(|(symbol_string, (nt, k, start), expected)| {
                assert_eq!(
                    expected,
                    &symbol_string.is_k_complete_for_nt_at(nt, *k, *start)
                )
            });
    }
}