Debian Codegraph @

src/graph/regex.rs

raw symbols SCIP
1 use std::fmt::Debug;
2
3 use regex_syntax::utf8::Utf8Sequences;
4
5 use crate::graph::{Disambiguate, Fork, Graph, Node, NodeId, Range, ReservedId, Rope};
6 use crate::mir::{Class, ClassUnicode, Literal, Mir};
7
8 impl<Leaf: Disambiguate + Debug> Graph<Leaf> {
9 pub fn regex(&mut self, mir: Mir, then: NodeId) -> NodeId {
10 self.parse_mir(&mir, then, None, None, false)
11 }
12
13 fn parse_mir(
14 &mut self,
15 mir: &Mir,
16 then: NodeId,
17 miss: Option<NodeId>,
18 reserved: Option<ReservedId>,
19 repeated: bool,
20 ) -> NodeId {
21 match mir {
22 Mir::Empty => then,
23 Mir::Loop(mir) => {
24 let reserved_first = reserved.unwrap_or_else(|| self.reserve());
25
26 let (new_then, new_miss);
27 if let Some(old_miss) = miss {
28 // We have to separate the first iteration from the other iterations,
29 // because the `old_miss` path must only be taken if we miss the first
30 // iteration.
31 let reserved_next = self.reserve();
32 new_then = self.parse_mir(
33 mir,
34 reserved_next.get(),
35 Some(then),
36 Some(reserved_next),
37 true,
38 );
39 new_miss = self.merge(old_miss, then);
40 } else {
41 new_then = reserved_first.get();
42 new_miss = then;
43 }
44
45 self.parse_mir(mir, new_then, Some(new_miss), Some(reserved_first), true)
46 }
47 Mir::Maybe(mir) => {
48 let miss = match miss {
49 Some(id) => self.merge(id, then),
50 None => then,
51 };
52
53 self.parse_mir(mir, then, Some(miss), reserved, true)
54 }
55 Mir::Alternation(alternation) => {
56 let mut fork = Fork::new().miss(miss);
57
58 for mir in alternation {
59 let id = self.parse_mir(mir, then, None, None, repeated);
60 let alt = self.fork_off(id);
61
62 fork.merge(alt, self);
63 }
64
65 self.insert_or_push(reserved, fork)
66 }
67 Mir::Literal(literal) => {
68 let pattern = literal.0.to_vec();
69
70 self.insert_or_push(reserved, Rope::new(pattern, then).miss(miss))
71 }
72 Mir::Concat(concat) => {
73 // Take an initial guess at the capacity - estimates a little worse than an average case
74 // scenario by assuming every concat element is singular but has a full code-point unicode literal.
75 // The only way to get the actual size of the Vec is if every sub-concat node is added up.
76 let mut ropebuf: Vec<Range> = Vec::with_capacity(concat.len() * 4);
77 let mut then = then;
78
79 let mut handle_bytes = |graph: &mut Self, mir: &Mir, then: &mut NodeId| match mir {
80 Mir::Literal(Literal(bytes)) => {
81 ropebuf.extend(bytes.iter().rev().map(Into::<Range>::into));
82 true
83 }
84 Mir::Class(Class::Unicode(class)) if is_one_ascii(class, repeated) => {
85 ropebuf.push(class.ranges()[0].into());
86 true
87 }
88 Mir::Class(Class::Bytes(class)) if class.ranges().len() == 1 => {
89 ropebuf.push(class.ranges()[0].into());
90 true
91 }
92 _ => {
93 if !ropebuf.is_empty() {
94 let rope =
95 Rope::new(ropebuf.iter().cloned().rev().collect::<Vec<_>>(), *then);
96
97 *then = graph.push(rope);
98 ropebuf = Vec::with_capacity(concat.len() * 4);
99 }
100 false
101 }
102 };
103
104 for mir in concat[1..].iter().rev() {
105 if !handle_bytes(self, mir, &mut then) {
106 then = self.parse_mir(mir, then, None, None, false);
107 }
108 }
109
110 let first_mir = &concat[0];
111 if handle_bytes(self, first_mir, &mut then) {
112 let rope = Rope::new(ropebuf.iter().cloned().rev().collect::<Vec<_>>(), then)
113 .miss(miss);
114 self.insert_or_push(reserved, rope)
115 } else {
116 self.parse_mir(first_mir, then, miss, reserved, false)
117 }
118 }
119 Mir::Class(Class::Unicode(class)) if !is_ascii(class, repeated) => {
120 let mut ropes = class
121 .iter()
122 .flat_map(|range| Utf8Sequences::new(range.start(), range.end()))
123 .map(|sequence| Rope::new(sequence.as_slice(), then))
124 .collect::<Vec<_>>();
125
126 if ropes.len() == 1 {
127 let rope = ropes.remove(0);
128
129 return self.insert_or_push(reserved, rope.miss(miss));
130 }
131
132 let mut root = Fork::new().miss(miss);
133
134 for rope in ropes {
135 let fork = rope.into_fork(self);
136 root.merge(fork, self);
137 }
138
139 self.insert_or_push(reserved, root)
140 }
141 Mir::Class(class) => {
142 let mut fork = Fork::new().miss(miss);
143
144 let class: Vec<Range> = match class {
145 Class::Unicode(u) => u.iter().copied().map(Into::into).collect(),
146 Class::Bytes(b) => b.iter().copied().map(Into::into).collect(),
147 };
148
149 for range in class {
150 fork.add_branch(range, then, self);
151 }
152
153 self.insert_or_push(reserved, fork)
154 }
155 }
156 }
157
158 fn insert_or_push<N>(&mut self, id: Option<ReservedId>, node: N) -> NodeId
159 where
160 N: Into<Node<Leaf>>,
161 {
162 match id {
163 Some(id) => self.insert(id, node),
164 None => self.push(node),
165 }
166 }
167 }
168
169 /// Return whether current class unicode is ascii.
170 ///
171 /// Because unicode ranges are iterated in increasing order,
172 /// it is only necessary to check the last range.
173 ///
174 /// If the check is performed in a repetition,
175 /// a fast path is used by checking if end of range is 0x0010_FFFF.
176 fn is_ascii(class: &ClassUnicode, repeated: bool) -> bool {
177 class.iter().last().map_or(true, |range| {
178 let start = range.start() as u32;
179 let end = range.end() as u32;
180 end < 128 || (repeated && start < 128 && end == 0x0010_FFFF)
181 })
182 }
183
184 /// Return whether current class unicode is ascii and only contains
185 /// one range.
186 ///
187 /// See [`is_ascii`] function for more details.
188 fn is_one_ascii(class: &ClassUnicode, repeated: bool) -> bool {
189 if class.ranges().len() != 1 {
190 return false;
191 }
192
193 let range = &class.ranges()[0];
194 let start = range.start() as u32;
195 let end = range.end() as u32;
196 end < 128 || (repeated && start < 128 && end == 0x0010_FFFF)
197 }
198
199 #[cfg(test)]
200 mod tests {
201 use std::num::NonZeroU32;
202
203 use super::*;
204 use crate::graph::Node;
205 use pretty_assertions::assert_eq;
206
207 #[test]
208 fn rope() {
209 let mut graph = Graph::new();
210
211 let mir = Mir::utf8("foobar").unwrap();
212
213 assert_eq!(mir.priority(), 12);
214
215 let leaf = graph.push(Node::Leaf("LEAF"));
216 let id = graph.regex(mir, leaf);
217
218 assert_eq!(graph[id], Node::Rope(Rope::new("foobar", leaf)),)
219 }
220
221 #[test]
222 fn alternation() {
223 let mut graph = Graph::new();
224
225 let mir = Mir::utf8("a|b").unwrap();
226
227 assert_eq!(mir.priority(), 2);
228
229 let leaf = graph.push(Node::Leaf("LEAF"));
230 let id = graph.regex(mir, leaf);
231
232 assert_eq!(
233 graph[id],
234 Node::Fork(Fork::new().branch(b'a', leaf).branch(b'b', leaf)),
235 );
236 }
237
238 #[test]
239 fn repeat() {
240 let mut graph = Graph::new();
241
242 let mir = Mir::utf8("[a-z]*").unwrap();
243
244 assert_eq!(mir.priority(), 0);
245
246 let leaf = graph.push(Node::Leaf("LEAF"));
247 let id = graph.regex(mir, leaf);
248
249 assert_eq!(
250 graph[id],
251 Node::Fork(
252 Fork::new()
253 .branch('a'..='z', id) // goto self == loop
254 .miss(leaf)
255 ),
256 );
257 }
258
259 #[test]
260 fn maybe() {
261 let mut graph = Graph::new();
262
263 let mir = Mir::utf8("[a-z]?").unwrap();
264
265 assert_eq!(mir.priority(), 0);
266
267 let leaf = graph.push(Node::Leaf("LEAF"));
268 let id = graph.regex(mir, leaf);
269
270 assert_eq!(
271 graph[id],
272 Node::Fork(Fork::new().branch('a'..='z', leaf).miss(leaf)),
273 );
274 }
275
276 #[test]
277 fn long_concat_389() {
278 let mut graph = Graph::new();
279
280 let mir = Mir::utf8("abcdefghijklmnopqrstuvwxyz*").unwrap();
281
282 assert_eq!(mir.priority(), 50);
283
284 let leaf = graph.push(Node::Leaf("LEAF"));
285 let id = graph.regex(mir, leaf);
286 let sub_id = NodeId(NonZeroU32::new(2).unwrap());
287
288 assert_eq!(
289 graph[id],
290 Node::Rope(Rope::new("abcdefghijklmnopqrstuvwxy", sub_id))
291 );
292
293 assert_eq!(graph[sub_id], Node::Rope(Rope::new("z", sub_id).miss(leaf)))
294 }
295 }