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
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::hash::Hash;
use std::rc::Rc;

// ===================================================================================================
// Enums
// ===================================================================================================

/// A `DFA`'s evaluation of an input, which is either `Accept` or `Reject`.
#[derive(Debug)]
pub enum Evaluation {
    Accept,
    Reject,
}

// ===================================================================================================
// DFA struct
// ===================================================================================================

/// A Deterministic Finite State Automaton (DFA) \[[wikipedia](https://en.wikipedia.org/wiki/Deterministic_finite_automaton)\]
///
/// The `DFA` struct aims to preserve the integrity of a DFA state diagram.
///
/// * A *dead* state is defined as a **non-accept** state from which all transitions implicitly lead back to itself.
/// * A *goal* state is defined as an **accept** state from which all transitions implicitly lead back to itself.
#[derive(Debug, Default)]
pub struct DFA<S, T>
where
    S: Eq + Hash + Clone + Debug,
    T: Eq + Hash + Clone + Debug,
{
    recognizes: String,
    states: HashSet<Rc<S>>,
    accept_states: HashSet<Rc<S>>,
    dead_states: HashSet<Rc<S>>,
    goal_states: HashSet<Rc<S>>,
    transitions: HashMap<T, HashMap<Rc<S>, Rc<S>>>,
    start: Option<Rc<S>>,
    current: Rc<S>,
}

impl<S, T> DFA<S, T>
where
    S: Eq + Hash + Clone + Debug,
    T: Eq + Hash + Clone + Debug,
{
    /// Returns a description of the language that this `DFA` recognizes.
    pub fn recognizes(&self) -> &str {
        &self.recognizes
    }

    /// Returns an iterator over the `DFA`'s states in no particular order.
    pub fn states(&self) -> impl Iterator<Item = Rc<S>> + '_ {
        self.states.iter().cloned()
    }

    /// Returns an iterator over the `DFA`'s *dead* states in no particular order.
    pub fn dead_states(&self) -> impl Iterator<Item = Rc<S>> + '_ {
        self.dead_states.iter().cloned()
    }

    /// Returns an iterator over the `DFA`'s *goal* states in no particular order.
    pub fn goal_states(&self) -> impl Iterator<Item = Rc<S>> + '_ {
        self.goal_states.iter().cloned()
    }

    /// Returns an iterator over the `DFA`'s alphabet in no particular order.
    pub fn alphabet(&self) -> impl Iterator<Item = &T> + '_ {
        self.transitions.keys()
    }

    /// Returns the start state of the `DFA`.
    ///
    /// * Panics if no start state is defined for the DFA.
    pub fn start(&self) -> Rc<S> {
        self.start
            .as_ref()
            .expect("DFA::start(): No start state was defined for this DFA.")
            .clone()
    }

    /// Returns the current state that the DFA is in.
    pub fn current(&self) -> Rc<S> {
        self.current.clone()
    }

    /// Moves the current state back to the start state.
    pub fn restart(&mut self) {
        self.current = self.start.as_ref().unwrap().clone();
    }

    /// Moves the current state to the next state given some transition.
    ///
    /// * Panics if the transition is not part of the alphabet.  
    /// * Panics if the transition has no defined destination from the current state.
    pub fn next(&mut self, transition: &T) {
        match self.transitions.get(transition) {
            Some(state_pairs) => match state_pairs.get(&self.current) {
                Some(destination) => self.current = destination.clone(),
                None => {
                    if self.dead_states.get(&self.current).is_some() {
                        return;
                    }
                    if self.goal_states.get(&self.current).is_some() {
                        return;
                    }
                    panic!("DFA::next(): There is no path defined from state ({:?}) on transition ({:?})", self.current, transition);
                }
            },
            None => panic!(
                "DFA::next(): Attempted to move with unknown transition ({:?})",
                transition
            ),
        }
    }

    /// Moves the current state to the next state given a transition and returns new state.
    ///
    /// * Panics if the transition is not part of the alphabet.  
    /// * Panics if the transition has no defined destination from the current state.
    pub fn get_next(&mut self, transition: &T) -> Rc<S> {
        self.next(transition);
        self.current.clone()
    }

    /// Evaluates the current state on whether or not it is an accept state.
    pub fn eval_current(&self) -> Evaluation {
        if self.accept_states.get(&self.current).is_some() {
            Evaluation::Accept
        } else {
            Evaluation::Reject
        }
    }

    /// Evaluates an input that will be either accepted or rejected by the DFA.
    ///
    /// * Panics if the input contains symbols that are not in the DFA's alphabet.
    pub fn evaluate<R>(&mut self, inputs: impl Iterator<Item = R>) -> Evaluation
    where
        R: Borrow<T>,
    {
        self.restart();
        for transition in inputs {
            self.next(transition.borrow());
        }
        self.eval_current()
    }
}

/// A [builder](https://www.geeksforgeeks.org/builder-design-pattern/) for the `DFA` struct.
#[derive(Debug, Default)]
pub struct DFABuilder<S, T>
where
    S: Eq + Hash + Clone + Debug,
    T: Eq + Hash + Clone + Debug,
{
    dfa: DFA<S, T>,
}

impl<'a, S, T> DFABuilder<S, T>
where
    S: Eq + Hash + Clone + Debug,
    T: Eq + Hash + Clone + Debug,
{
    /// Adds a description of the language that this [DFA](struct.DFA.html) will recognize.
    pub fn recognizes(mut self, description: &str) -> Self {
        if !self.dfa.recognizes.is_empty() {
            panic!("DFABuilder::recognizes(): The language that a DFA recognizes may be defined only once.");
        }
        self.dfa.recognizes = description.to_owned();
        self
    }

    /// Adds a state to the `DFA`.
    ///
    /// * Panics if a state is added after any transition has been added. Must add all states before transitions.
    pub fn add_state(mut self, state: &S) -> Self {
        if !self.dfa.transitions.is_empty() {
            panic!("DFABuilder::add_state(): All states must be added before any transitions are added.");
        }
        self.dfa.states.insert(Rc::new(state.clone()));
        self
    }

    /// Marks a state as an accept state.
    ///
    /// * Panics if the provided state does not exist in this [DFA](struct.DFA.html).
    pub fn mark_accept_state(mut self, state: &S) -> Self {
        match self.dfa.states.get(state) {
            Some(state) => {
                if let Some(state) = self.dfa.dead_states.get(state) {
                    panic!("DFABuilder::mark_accept_state(): Attempted to mark a dead state ({:?}) as an accept state.", state);
                }
                self.dfa.accept_states.insert(state.clone());
            }
            None => panic!("DFABuilder::mark_accept_state(): Attempted to mark a non-existent state ({:?}) as an accept state.", state),
        }
        self
    }

    /// Marks a state as a goal state.
    ///
    /// * This will automatically add the goal state to the list of accept states.
    /// * Panics if the provided state does not exist in this [DFA](struct.DFA.html).
    pub fn mark_goal_state(mut self, state: &S) -> Self {
        match self.dfa.states.get(state) {
            Some(state) => {
                if let Some(state) = self.dfa.dead_states.get(state) {
                    panic!(
                        "DFABuilder::mark_goal_state(): Attempted to mark a dead state ({:?}) as a goal state.",
                        state
                    );
                }
                self.dfa.accept_states.insert(state.clone());
                self.dfa.goal_states.insert(state.clone());
            }
            None => panic!(
                "DFABuilder::mark_goal_state(): Attempted to mark a non-existent state ({:?}) as a goal state.",
                state
            ),
        }
        self
    }

    /// Marks a state as a dead state.
    ///
    /// * Panics if the provided state does not exist in this [DFA](struct.DFA.html).
    pub fn mark_dead_state(mut self, state: &S) -> Self {
        match self.dfa.states.get(state) {
            Some(state) => {
                if let Some(state) = self.dfa.accept_states.get(state) {
                    panic!("DFABuilder::mark_dead_state(): Attempted to mark an accept state ({:?}) as a dead state.", state);
                }
                self.dfa.dead_states.insert(state.clone());
            }
            None => panic!(
                "DFABuilder::mark_dead_state(): Attempted to mark a non-existent state ({:?}) as a dead state.",
                state
            ),
        }
        self
    }

    /// Marks a state as the start state.
    ///
    /// * Panics if the provided state does not exist in this [DFA](struct.DFA.html).
    /// * Panics if the [DFA](struct.DFA.html) already has a defined start state.
    pub fn mark_start_state(mut self, state: &S) -> Self {
        if let Some(start) = self.dfa.start {
            panic!("DFABUilder::mark_start_state(): Attempted to mark state ({:?}) as the start state when the start state ({:?}) has already been defined.", state, start);
        }
        match self.dfa.states.get(state) {
            Some(state) => {
                self.dfa.start = Some(state.clone());
                self.dfa.current = state.clone();
            }
            None => panic!(
                "DFABuilder::mark_start_state(): Attempted to mark a non-existent state ({:?}) as a start state.",
                state
            ),
        }
        self
    }

    /// Adds a transition from one state to another.
    ///
    /// * Panics if the transition is coming from a **dead** state. A dead state's transitions cannot be overwritten.
    /// * Panics if the transition is coming from a **goal** state. A goal state's transitions cannot be overwritten.
    /// * Panics if the *from* state does not exist in the [DFA](struct.DFA.html).
    /// * Panics if the *to* state does not exist in the [DFA](struct.DFA.html).
    pub fn add_transition(mut self, from: &S, transition: &T, to: &S) -> Self {
        if let Some(state) = self.dfa.dead_states.get(from) {
            panic!("DFABuilder::add_transition(): Attempted to create a transition from state ({:?}), which is a dead state and all transitions implicitly lead to itself.", state);
        }
        if let Some(state) = self.dfa.goal_states.get(from) {
            panic!("DFABuilder::add_transition(): Attempted to create a transition from state ({:?}), which is a goal state and all transitions implicitly lead to itself.", state);
        }
        match (self.dfa.states.get(from), self.dfa.states.get(to)) {
            (Some(from), Some(to)) => {
                if let Some(state_pairs) = self.dfa.transitions.get_mut(transition) {
                    state_pairs.insert(from.clone(), to.clone());
                } else {
                    let transition = transition.clone();
                    let mut state_pairs = HashMap::new();
                    state_pairs.insert(from.clone(), to.clone());
                    self.dfa.transitions.insert(transition, state_pairs);
                }
            }
            (None, _) => panic!(
                "DFABuilder::add_transition(): Attempted to create a transition from state ({:?}), which does not exist in this DFA.",
                from
            ),
            (_, None) => panic!(
                "DFABuilder::add_transition(): Attempt to create a transition to state ({:?}), which does not exist in this DFA.",
                to
            ),
        }
        self
    }

    /// Builds a [DFA](struct.dfa.html) and consumes the builder.
    ///
    /// * Panics if the [DFA](struct.dfa.html) has no states.
    /// * Panics if the [DFA](struct.dfa.html) has no defined start state.
    /// * Panics if each state in the [DFA](struct.dfa.html) does not have a transition for every symbol in the alphabet.
    pub fn build(self) -> DFA<S, T> {
        if self.dfa.states.is_empty() {
            panic!("DFABuilder::build(): The DFA must have at least one state, but it is empty.");
        }
        if self.dfa.start.is_none() {
            panic!(
                "DFABuilder::build(): DFA must have a valid start state. No start state was defined."
            );
        }
        let transition_states =
            self.dfa.states.len() - self.dfa.dead_states.len() - self.dfa.goal_states.len();
        for state_pairs in self.dfa.transitions.values() {
            if state_pairs.keys().count() < transition_states {
                panic!("DFABuilder::build(): All transition states have a complete set of output edges for every transition.");
            }
        }
        self.dfa
    }
}