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
|
use std::fmt::Debug;
use regex_syntax::utf8::Utf8Sequences;
use crate::graph::{Disambiguate, Fork, Graph, Node, NodeId, Range, ReservedId, Rope};
use crate::mir::{Class, ClassUnicode, Literal, Mir};
impl<Leaf: Disambiguate + Debug> Graph<Leaf> {
pub fn regex(&mut self, mir: Mir, then: NodeId) -> NodeId {
self.parse_mir(&mir, then, None, None, false)
}
fn parse_mir(
&mut self,
mir: &Mir,
then: NodeId,
miss: Option<NodeId>,
reserved: Option<ReservedId>,
repeated: bool,
) -> NodeId {
match mir {
Mir::Empty => then,
Mir::Loop(mir) => {
let reserved_first = reserved.unwrap_or_else(|| self.reserve());
let (new_then, new_miss);
if let Some(old_miss) = miss {
// We have to separate the first iteration from the other iterations,
// because the `old_miss` path must only be taken if we miss the first
// iteration.
let reserved_next = self.reserve();
new_then = self.parse_mir(
mir,
reserved_next.get(),
Some(then),
Some(reserved_next),
true,
);
new_miss = self.merge(old_miss, then);
} else {
new_then = reserved_first.get();
new_miss = then;
}
self.parse_mir(mir, new_then, Some(new_miss), Some(reserved_first), true)
}
Mir::Maybe(mir) => {
let miss = match miss {
Some(id) => self.merge(id, then),
None => then,
};
self.parse_mir(mir, then, Some(miss), reserved, true)
}
Mir::Alternation(alternation) => {
let mut fork = Fork::new().miss(miss);
for mir in alternation {
let id = self.parse_mir(mir, then, None, None, repeated);
let alt = self.fork_off(id);
fork.merge(alt, self);
}
self.insert_or_push(reserved, fork)
}
Mir::Literal(literal) => {
let pattern = literal.0.to_vec();
self.insert_or_push(reserved, Rope::new(pattern, then).miss(miss))
}
Mir::Concat(concat) => {
// Take an initial guess at the capacity - estimates a little worse than an average case
// scenario by assuming every concat element is singular but has a full code-point unicode literal.
// The only way to get the actual size of the Vec is if every sub-concat node is added up.
let mut ropebuf: Vec<Range> = Vec::with_capacity(concat.len() * 4);
let mut then = then;
let mut handle_bytes = |graph: &mut Self, mir: &Mir, then: &mut NodeId| match mir {
Mir::Literal(Literal(bytes)) => {
ropebuf.extend(bytes.iter().rev().map(Into::<Range>::into));
true
}
Mir::Class(Class::Unicode(class)) if is_one_ascii(class, repeated) => {
ropebuf.push(class.ranges()[0].into());
true
}
Mir::Class(Class::Bytes(class)) if class.ranges().len() == 1 => {
ropebuf.push(class.ranges()[0].into());
true
}
_ => {
if !ropebuf.is_empty() {
let rope =
Rope::new(ropebuf.iter().cloned().rev().collect::<Vec<_>>(), *then);
*then = graph.push(rope);
ropebuf = Vec::with_capacity(concat.len() * 4);
}
false
}
};
for mir in concat[1..].iter().rev() {
if !handle_bytes(self, mir, &mut then) {
then = self.parse_mir(mir, then, None, None, false);
}
}
let first_mir = &concat[0];
if handle_bytes(self, first_mir, &mut then) {
let rope = Rope::new(ropebuf.iter().cloned().rev().collect::<Vec<_>>(), then)
.miss(miss);
self.insert_or_push(reserved, rope)
} else {
self.parse_mir(first_mir, then, miss, reserved, false)
}
}
Mir::Class(Class::Unicode(class)) if !is_ascii(class, repeated) => {
let mut ropes = class
.iter()
.flat_map(|range| Utf8Sequences::new(range.start(), range.end()))
.map(|sequence| Rope::new(sequence.as_slice(), then))
.collect::<Vec<_>>();
if ropes.len() == 1 {
let rope = ropes.remove(0);
return self.insert_or_push(reserved, rope.miss(miss));
}
let mut root = Fork::new().miss(miss);
for rope in ropes {
let fork = rope.into_fork(self);
root.merge(fork, self);
}
self.insert_or_push(reserved, root)
}
Mir::Class(class) => {
let mut fork = Fork::new().miss(miss);
let class: Vec<Range> = match class {
Class::Unicode(u) => u.iter().copied().map(Into::into).collect(),
Class::Bytes(b) => b.iter().copied().map(Into::into).collect(),
};
for range in class {
fork.add_branch(range, then, self);
}
self.insert_or_push(reserved, fork)
}
}
}
fn insert_or_push<N>(&mut self, id: Option<ReservedId>, node: N) -> NodeId
where
N: Into<Node<Leaf>>,
{
match id {
Some(id) => self.insert(id, node),
None => self.push(node),
}
}
}
/// Return whether current class unicode is ascii.
///
/// Because unicode ranges are iterated in increasing order,
/// it is only necessary to check the last range.
///
/// If the check is performed in a repetition,
/// a fast path is used by checking if end of range is 0x0010_FFFF.
fn is_ascii(class: &ClassUnicode, repeated: bool) -> bool {
class.iter().last().map_or(true, |range| {
let start = range.start() as u32;
let end = range.end() as u32;
end < 128 || (repeated && start < 128 && end == 0x0010_FFFF)
})
}
/// Return whether current class unicode is ascii and only contains
/// one range.
///
/// See [`is_ascii`] function for more details.
fn is_one_ascii(class: &ClassUnicode, repeated: bool) -> bool {
if class.ranges().len() != 1 {
return false;
}
let range = &class.ranges()[0];
let start = range.start() as u32;
let end = range.end() as u32;
end < 128 || (repeated && start < 128 && end == 0x0010_FFFF)
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
use super::*;
use crate::graph::Node;
use pretty_assertions::assert_eq;
#[test]
fn rope() {
let mut graph = Graph::new();
let mir = Mir::utf8("foobar").unwrap();
assert_eq!(mir.priority(), 12);
let leaf = graph.push(Node::Leaf("LEAF"));
let id = graph.regex(mir, leaf);
assert_eq!(graph[id], Node::Rope(Rope::new("foobar", leaf)),)
}
#[test]
fn alternation() {
let mut graph = Graph::new();
let mir = Mir::utf8("a|b").unwrap();
assert_eq!(mir.priority(), 2);
let leaf = graph.push(Node::Leaf("LEAF"));
let id = graph.regex(mir, leaf);
assert_eq!(
graph[id],
Node::Fork(Fork::new().branch(b'a', leaf).branch(b'b', leaf)),
);
}
#[test]
fn repeat() {
let mut graph = Graph::new();
let mir = Mir::utf8("[a-z]*").unwrap();
assert_eq!(mir.priority(), 0);
let leaf = graph.push(Node::Leaf("LEAF"));
let id = graph.regex(mir, leaf);
assert_eq!(
graph[id],
Node::Fork(
Fork::new()
.branch('a'..='z', id) // goto self == loop
.miss(leaf)
),
);
}
#[test]
fn maybe() {
let mut graph = Graph::new();
let mir = Mir::utf8("[a-z]?").unwrap();
assert_eq!(mir.priority(), 0);
let leaf = graph.push(Node::Leaf("LEAF"));
let id = graph.regex(mir, leaf);
assert_eq!(
graph[id],
Node::Fork(Fork::new().branch('a'..='z', leaf).miss(leaf)),
);
}
#[test]
fn long_concat_389() {
let mut graph = Graph::new();
let mir = Mir::utf8("abcdefghijklmnopqrstuvwxyz*").unwrap();
assert_eq!(mir.priority(), 50);
let leaf = graph.push(Node::Leaf("LEAF"));
let id = graph.regex(mir, leaf);
let sub_id = NodeId(NonZeroU32::new(2).unwrap());
assert_eq!(
graph[id],
Node::Rope(Rope::new("abcdefghijklmnopqrstuvwxy", sub_id))
);
assert_eq!(graph[sub_id], Node::Rope(Rope::new("z", sub_id).miss(leaf)))
}
}
|