Skip to main content

mid_tools/
nfa.rs

1use std::{
2    borrow::Cow,
3    collections::{BTreeMap, BTreeSet},
4    hash::Hash,
5};
6
7use self::dfa_builder::DfaBuilder;
8use crate::{
9    autom::Accept,
10    dfa::{self, Dfa},
11    dot,
12    free::Free,
13    partition_map::{self, Partition, PartitionMap},
14};
15
16mod dfa_builder;
17
18pub const NFA_START: usize = 0;
19
20#[derive(Debug)]
21pub struct Node<I, T = (), E = ()> {
22    nil: BTreeSet<(E, usize)>,
23    map: PartitionMap<I, BTreeSet<(E, usize)>>,
24    accept: T,
25}
26
27impl<I, T, E> Node<I, T, E> {
28    fn new(accept: T) -> Self {
29        Self {
30            nil: BTreeSet::new(),
31            map: PartitionMap::new(BTreeSet::new()),
32            accept,
33        }
34    }
35}
36
37impl<I, T, E> Node<I, T, E> {
38    #[inline]
39    pub fn nil_edges(&self) -> &BTreeSet<(E, usize)> { &self.nil }
40
41    #[inline]
42    pub fn edges(&self) -> Edges<'_, I, E> {
43        Edges {
44            nil: Some(&self.nil),
45            map: self.map.partitions(),
46        }
47    }
48}
49
50#[derive(Debug)]
51pub struct Edges<'a, I, E> {
52    nil: Option<&'a BTreeSet<(E, usize)>>,
53    map: partition_map::Partitions<'a, I, BTreeSet<(E, usize)>>,
54}
55
56impl<'a, I, E> Iterator for Edges<'a, I, E> {
57    type Item = (Option<Partition<&'a I>>, &'a BTreeSet<(E, usize)>);
58
59    fn next(&mut self) -> Option<Self::Item> {
60        if let Some(nil) = self.nil.take() {
61            return Some((None, nil));
62        }
63
64        let (part, val) = self.map.next()?;
65        Some((Some(part), val))
66    }
67}
68
69#[derive(Debug)]
70pub struct Nfa<I, T = (), E = ()>(Vec<Node<I, T, E>>);
71
72impl<I, T: Default, E> Default for Nfa<I, T, E> {
73    #[inline]
74    fn default() -> Self { Self::new() }
75}
76
77impl<I, T, E> Nfa<I, T, E> {
78    #[must_use]
79    pub fn with_start_accept(start_accept: T) -> Self {
80        let mut me = Self(vec![]);
81        assert!(me.push_accept(start_accept) == 0);
82        me
83    }
84
85    #[inline]
86    #[must_use]
87    pub fn get(&self, node: usize) -> Option<&Node<I, T, E>> { self.0.get(node) }
88
89    #[inline]
90    pub fn push_accept(&mut self, accept: T) -> usize {
91        let ret = self.0.len();
92        self.0.push(Node::new(accept));
93        ret
94    }
95}
96
97impl<I, T: Default, E> Nfa<I, T, E> {
98    #[inline]
99    #[must_use]
100    pub fn new() -> Self { Self::with_start_accept(T::default()) }
101
102    #[inline]
103    pub fn push(&mut self) -> usize { self.push_accept(T::default()) }
104}
105
106impl<I: Clone + Ord, T, E: Clone + Ord> Nfa<I, T, E> {
107    pub fn connect(&mut self, from: usize, to: usize, by: Option<Partition<I>>, out: E) -> bool {
108        assert!(to < self.0.len());
109        let from = self.0.get_mut(from).unwrap();
110
111        if let Some(part) = by {
112            let mut any = false;
113            from.map.update(part.bounds(), |_, v| {
114                let mut s = v.clone();
115                any |= s.insert((out.clone(), to));
116                s
117            });
118            any
119        } else {
120            from.nil.insert((out, to))
121        }
122    }
123}
124
125impl<
126        I: Clone + Ord,
127        T: Accept<Token: Clone + Ord + Hash>,
128        E: Accept<Token: Clone + Ord + Hash>,
129    > Nfa<I, T, E>
130{
131    #[inline]
132    #[must_use]
133    pub fn compile(&self) -> dfa_builder::Output<I, T, E> { DfaBuilder::new(self).build() }
134}
135
136impl<I: Clone + Ord, T: Accept<Token: Clone + Ord + Hash>> Nfa<I, T> {
137    #[inline]
138    #[must_use]
139    pub fn compile_moore(&self) -> dfa_builder::Moore<I, T> { DfaBuilder::new(self).build_moore() }
140}
141
142impl<I, T: Accept, E: Accept> Nfa<I, T, E> {
143    pub fn dot<'a>(
144        &self,
145        fmt_state: impl Fn(usize) -> Cow<'a, str>,
146        fmt_input: impl Fn(Partition<&I>) -> Cow<'a, str>,
147        fmt_node_tok: impl Fn(&T::Token) -> Option<Cow<'a, str>>,
148        fmt_edge_tok: impl Fn(&E::Token) -> Option<Cow<'a, str>>,
149    ) -> dot::Graph<'a> {
150        let mut free_id = Free::from(0);
151        let mut node_ids = BTreeMap::new();
152
153        dot::Graph::state_machine(
154            self.0.iter().enumerate().map(|(s, n)| {
155                (
156                    s,
157                    n.edges()
158                        .map(|(k, v)| (k, v.iter().map(|&(ref e, n)| (e, n)))),
159                    &n.accept,
160                )
161            }),
162            NFA_START,
163            |n| *node_ids.entry(n).or_insert_with(|| free_id.fresh()),
164            fmt_state,
165            |i| i.map_or_else(|| "ϵ".into(), &fmt_input),
166            fmt_node_tok,
167            fmt_edge_tok,
168        )
169    }
170}
171
172impl<I: Clone + Ord, T, E: Clone + Ord> From<Dfa<I, T, E>> for Nfa<I, T, E> {
173    fn from(value: Dfa<I, T, E>) -> Self {
174        Self(
175            value
176                .into_states()
177                .into_iter()
178                .map(|dfa::State(edges, accept)| Node {
179                    nil: BTreeSet::new(),
180                    map: edges
181                        .into_ranges()
182                        .map(|(k, v)| (k, [v].into_iter().collect()))
183                        .collect(),
184                    accept,
185                })
186                .collect(),
187        )
188    }
189}