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
use std::collections::HashMap;
use std::fmt::Write;
use super::Alphabet;
pub struct Regex<A: Alphabet> {
subs: Vec<Op<A>>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Handle(usize);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Op<A: Alphabet> {
Epsilon,
Match(A),
Star(Handle),
Or(Handle, Handle),
Concat(Handle, Handle),
}
pub struct Cached<A: Alphabet> {
regex: Regex<A>,
cache: HashMap<Op<A>, Handle>,
}
impl<A: Alphabet> Regex<A> {
pub fn new() -> Self {
Regex {
subs: vec![],
}
}
pub fn push(&mut self, op: Op<A>) -> Handle {
match op {
Op::Epsilon => (),
Op::Match(_) => (),
Op::Star(Handle(i)) => assert!(i < self.subs.len()),
Op::Or(Handle(i), Handle(j)) => assert!(i < self.subs.len() && j < self.subs.len()),
Op::Concat(Handle(i), Handle(j)) => assert!(i < self.subs.len() && j < self.subs.len()),
}
let handle = Handle(self.subs.len());
self.subs.push(op);
handle
}
pub fn root(&self) -> Option<Handle> {
self.subs.len().checked_sub(1).map(Handle)
}
pub fn cached(self) -> Cached<A> {
Cached {
regex: self,
cache: HashMap::new(),
}
}
pub fn to_string(&self) -> String {
let mut string = String::new();
self.push_from_root(self.root().unwrap(), &mut string);
string
}
fn push_from_root(&self, Handle(root): Handle, string: &mut String) {
match self.subs[root] {
Op::Epsilon => string.push_str("{e}"),
Op::Match(a) => write!(string, "{{{:?}}}", a).unwrap(),
Op::Star(sub) => {
string.push('(');
self.push_from_root(sub, string);
string.push_str(")*");
},
Op::Or(a, b) => {
string.push('(');
self.push_from_root(a, string);
string.push('|');
self.push_from_root(b, string);
string.push(')');
},
Op::Concat(a, b) => {
self.push_from_root(a, string);
self.push_from_root(b, string);
},
}
}
}
impl<A: Alphabet> Cached<A> {
pub fn new() -> Self {
Regex::new().cached()
}
pub fn insert(&mut self, op: Op<A>) -> Handle {
let regex = &mut self.regex;
let value = self.cache.entry(op)
.or_insert_with(|| regex.push(op));
*value
}
pub fn inner(&self) -> &Regex<A> {
&self.regex
}
pub fn into_inner(self) -> Regex<A> {
self.regex
}
pub fn fill_cache(&mut self) {
for (handle, op) in self.regex.subs.iter().enumerate() {
self.cache.insert(*op, Handle(handle));
}
}
}
impl<A: Alphabet> Default for Regex<A> {
fn default() -> Self {
Self::new()
}
}
impl<A: Alphabet> Default for Cached<A> {
fn default() -> Self {
Self::new()
}
}