Skip to main content

mid_tools/
dfa.rs

1use std::{borrow::Cow, collections::BTreeMap, hash::Hash, mem};
2
3use hashbrown::HashMap;
4
5use crate::{
6    autom::Accept,
7    dot,
8    free::{Free, Succ},
9    nfa::Nfa,
10    partition_map::Partition,
11    range_map::RangeMap,
12};
13
14pub mod optimize;
15
16pub const DFA_START: usize = 0;
17
18pub fn collect_state_keys<
19    S: Clone + Eq + Hash,
20    I: IntoIterator<Item = S, IntoIter: ExactSizeIterator>,
21>(
22    it: I,
23    start: &S,
24) -> HashMap<S, usize> {
25    let mut zero = None;
26
27    let it = it.into_iter();
28    let len = it.len();
29    let mut map: HashMap<_, _> = it
30        .into_iter()
31        .enumerate()
32        .map(|(i, s)| {
33            if i == 0 && s != *start {
34                assert!(zero.replace(s.clone()).is_none());
35            }
36
37            (s, i)
38        })
39        .collect();
40    assert!(map.len() == len);
41
42    if let Some(zero) = zero {
43        let [l, r] = map.get_many_mut([&zero, start]);
44        mem::swap(l.unwrap(), r.unwrap());
45    }
46
47    map
48}
49
50pub fn collect_states<
51    K: Eq + Hash,
52    V,
53    I: IntoIterator<Item = (K, V), IntoIter: ExactSizeIterator>,
54>(
55    map: &HashMap<K, usize>,
56    it: I,
57) -> (Vec<V>, Vec<K>) {
58    let it = it.into_iter();
59    let len = it.len();
60    let (states, keys): (BTreeMap<usize, _>, BTreeMap<usize, _>) = it
61        .map(|(k, v)| {
62            let id = *map.get(&k).unwrap();
63            ((id, v), (id, k))
64        })
65        .unzip();
66    assert!(states.len() == len);
67    assert!(keys.len() == len);
68    (states.into_values().collect(), keys.into_values().collect())
69}
70
71#[derive(Debug, PartialEq)]
72pub struct State<I, T = (), E = ()>(pub RangeMap<I, (E, usize)>, pub T);
73
74pub type DfaStates<I, T = (), E = ()> = Vec<State<I, T, E>>;
75
76#[derive(Debug, PartialEq)]
77pub struct Dfa<I, T = (), E = ()>(DfaStates<I, T, E>);
78
79impl<I, T, E> Dfa<I, T, E> {
80    #[inline]
81    #[must_use]
82    pub fn into_states(self) -> DfaStates<I, T, E> { self.0 }
83}
84
85impl<I, T, E> Dfa<I, T, E> {
86    #[must_use]
87    pub fn new(states: DfaStates<I, T, E>) -> Self {
88        assert!(!states.is_empty(), "Missing DFA start state");
89
90        for node in &states {
91            for &(_, out) in node.0.values() {
92                assert!(out < states.len(), "DFA delta out of bounds");
93            }
94        }
95
96        Self(states)
97    }
98
99    pub fn map_nodes<U, F: FnMut(T) -> U>(self, mut f: F) -> Dfa<I, U, E> {
100        Dfa(self
101            .0
102            .into_iter()
103            .map(|State(e, a)| State(e, f(a)))
104            .collect())
105    }
106
107    // TODO: try_trait_v2 wen eta
108    pub fn try_map_nodes<U, R, F: FnMut(T) -> Result<U, R>>(
109        self,
110        mut f: F,
111    ) -> Result<Dfa<I, U, E>, R> {
112        Ok(Dfa(self
113            .0
114            .into_iter()
115            .map(|State(e, a)| Ok(State(e, f(a)?)))
116            .collect::<Result<_, _>>()?))
117    }
118}
119
120impl<I: Clone + Ord, T, E> Dfa<I, T, E> {
121    pub fn map_edges<G: Clone + PartialEq, F: FnMut(E) -> G>(self, mut f: F) -> Dfa<I, T, G> {
122        Dfa(self
123            .0
124            .into_iter()
125            .map(|State(e, a)| {
126                State(
127                    e.into_ranges().map(|(i, (e, s))| (i, (f(e), s))).collect(),
128                    a,
129                )
130            })
131            .collect())
132    }
133}
134
135impl<I: Copy + Ord, T, E> Dfa<&I, T, E> {
136    #[must_use]
137    pub fn copied(self) -> Dfa<I, T, E> {
138        Dfa(self
139            .0
140            .into_iter()
141            .map(|State(e, a)| State(e.copied_keys(), a))
142            .collect())
143    }
144}
145
146impl<I: Clone + Ord + Hash + Succ, T: Clone + Ord + Hash, E: Clone + Ord + Hash> Dfa<I, T, E> {
147    #[must_use]
148    pub fn optimize(&self) -> optimize::Output<I, T, E> { optimize::run_default(self) }
149}
150
151impl<I: Clone + Ord, T, E: Clone + Ord> Dfa<I, T, E> {
152    #[must_use]
153    pub fn into_nfa(self) -> Nfa<I, T, E> { self.into() }
154}
155
156impl<I, T: Accept, E: Accept> Dfa<I, T, E> {
157    pub fn dot<'a>(
158        &self,
159        fmt_state: impl Fn(usize) -> Cow<'a, str>,
160        fmt_input: impl Fn(Partition<&I>) -> Cow<'a, str>,
161        fmt_node_tok: impl Fn(&T::Token) -> Option<Cow<'a, str>>,
162        fmt_edge_tok: impl Fn(&E::Token) -> Option<Cow<'a, str>>,
163    ) -> dot::Graph<'a> {
164        let mut free_id = Free::from(0);
165        let mut node_ids = BTreeMap::new();
166
167        dot::Graph::state_machine(
168            self.0
169                .iter()
170                .enumerate()
171                .map(|(s, State(e, a))| (s, e.ranges().map(|(k, &(ref e, v))| (k, [(e, v)])), a)),
172            DFA_START,
173            |n| *node_ids.entry(n).or_insert_with(|| free_id.fresh()),
174            fmt_state,
175            fmt_input,
176            fmt_node_tok,
177            fmt_edge_tok,
178        )
179    }
180}