1use super::{ClassSet, Flags, Node, PropertyKind};
11
12pub type Captures = Vec<Option<(usize, usize)>>;
14
15pub struct Match {
17 pub start: usize,
19 pub end: usize,
21 pub captures: Captures,
23}
24
25#[derive(Clone, Copy, PartialEq, Eq)]
27pub enum Anchoring {
28 Search,
30 At(usize),
32}
33
34pub fn exec(
36 node: &Node,
37 groups: usize,
38 flags: Flags,
39 input: &[char],
40 from: usize,
41 anchoring: Anchoring,
42) -> Option<Match> {
43 let matcher = Matcher { input, flags };
44 let starts: Box<dyn Iterator<Item = usize>> = match anchoring {
45 Anchoring::At(position) => Box::new(std::iter::once(position)),
46 Anchoring::Search => Box::new(from..=input.len()),
47 };
48 for start in starts {
49 if start > input.len() {
50 break;
51 }
52 let caps: Captures = vec![None; groups + 1];
53 let mut found = None;
54 let mut record = |end: usize, caps: &Captures| {
55 let mut caps = caps.clone();
56 caps[0] = Some((start, end));
57 found = Some(Match {
58 start,
59 end,
60 captures: caps,
61 });
62 true
65 };
66 if matcher.seq(std::slice::from_ref(node), start, &caps, &mut record) {
67 return found;
68 }
69 }
70 None
71}
72
73struct Matcher<'a> {
74 input: &'a [char],
75 flags: Flags,
76}
77
78impl Matcher<'_> {
79 fn at(&self, position: usize) -> Option<char> {
80 self.input.get(position).copied()
81 }
82
83 fn fold(&self, c: char) -> char {
84 if self.flags.ignore_case {
85 c.to_lowercase().next().unwrap_or(c)
88 } else {
89 c
90 }
91 }
92
93 fn chars_equal(&self, a: char, b: char) -> bool {
94 if self.flags.ignore_case {
95 self.fold(a) == self.fold(b)
96 } else {
97 a == b
98 }
99 }
100
101 fn set_lengths(&self, set: &ClassSet, position: usize) -> Vec<usize> {
108 let mut lengths = self.set_lengths_unsorted(set, position);
109 lengths.sort_unstable_by(|a, b| b.cmp(a));
110 lengths.dedup();
111 lengths
112 }
113
114 fn set_lengths_unsorted(&self, set: &ClassSet, position: usize) -> Vec<usize> {
115 match set {
116 ClassSet::Char(expected) => match self.at(position) {
117 Some(actual) if self.chars_equal(actual, *expected) => vec![1],
118 _ => Vec::new(),
119 },
120 ClassSet::Range(lo, hi) => match self.at(position) {
121 Some(c) if self.in_range(c, *lo, *hi) => vec![1],
122 _ => Vec::new(),
123 },
124 ClassSet::Property { kind, negated } => match self.at(position) {
125 Some(c) if self.property_holds(*kind, *negated, c) => vec![1],
126 _ => Vec::new(),
127 },
128 ClassSet::Predefined { negated, ranges } => match self.at(position) {
129 Some(c) => {
130 let inside = ranges.iter().any(|(lo, hi)| self.in_range(c, *lo, *hi));
131 if inside != *negated {
132 vec![1]
133 } else {
134 Vec::new()
135 }
136 }
137 None => Vec::new(),
138 },
139 ClassSet::Strings(members) => members
140 .iter()
141 .filter(|member| self.matches_sequence(member, position))
142 .map(|member| member.len())
143 .collect(),
144 ClassSet::Union(operands) => operands
145 .iter()
146 .flat_map(|operand| self.set_lengths_unsorted(operand, position))
147 .collect(),
148 ClassSet::Intersection(operands) => {
149 let mut iter = operands.iter();
150 let Some(first) = iter.next() else {
151 return Vec::new();
152 };
153 let mut lengths = self.set_lengths(first, position);
154 for operand in iter {
155 let other = self.set_lengths(operand, position);
156 lengths.retain(|length| other.contains(length));
157 }
158 lengths
159 }
160 ClassSet::Difference(left, right) => {
161 let mut lengths = self.set_lengths(left, position);
162 let excluded = self.set_lengths(right, position);
163 lengths.retain(|length| !excluded.contains(length));
164 lengths
165 }
166 ClassSet::Negated(inner) => match self.at(position) {
169 Some(c) if !self.set_lengths(inner, position).contains(&1) => {
170 let _ = c;
171 vec![1]
172 }
173 _ => Vec::new(),
174 },
175 }
176 }
177
178 fn matches_sequence(&self, member: &[char], position: usize) -> bool {
180 member
181 .iter()
182 .enumerate()
183 .all(|(index, expected)| match self.at(position + index) {
184 Some(actual) => self.chars_equal(actual, *expected),
185 None => false,
186 })
187 }
188
189 fn in_range(&self, c: char, lo: char, hi: char) -> bool {
191 self.in_class(c, &[(lo, hi)])
192 }
193
194 fn property_holds(&self, kind: PropertyKind, negated: bool, c: char) -> bool {
202 let mut candidates = vec![c];
203 if self.flags.ignore_case {
204 candidates.push(self.fold(c));
205 if let Some(upper) = c.to_uppercase().next() {
206 candidates.push(upper);
207 }
208 if let Some(lower) = c.to_lowercase().next() {
209 candidates.push(lower);
210 }
211 }
212 if self.flags.unicode_sets {
213 let holds = candidates
215 .into_iter()
216 .any(|candidate| kind.holds(candidate));
217 holds != negated
218 } else {
219 candidates
221 .into_iter()
222 .any(|candidate| kind.holds(candidate) != negated)
223 }
224 }
225
226 fn in_class(&self, c: char, ranges: &[(char, char)]) -> bool {
235 let folded = self.fold(c);
236 ranges.iter().any(|(lo, hi)| {
237 (*lo..=*hi).contains(&c) || (*lo..=*hi).contains(&folded) || {
238 let (folded_lo, folded_hi) = (self.fold(*lo), self.fold(*hi));
239 folded_lo <= folded_hi && (folded_lo..=folded_hi).contains(&folded)
240 }
241 })
242 }
243
244 fn seq(
246 &self,
247 nodes: &[Node],
248 position: usize,
249 caps: &Captures,
250 k: &mut dyn FnMut(usize, &Captures) -> bool,
251 ) -> bool {
252 let Some((first, rest)) = nodes.split_first() else {
253 return k(position, caps);
254 };
255 self.node(first, position, caps, &mut |next, caps| {
256 self.seq(rest, next, caps, k)
257 })
258 }
259
260 fn node(
262 &self,
263 node: &Node,
264 position: usize,
265 caps: &Captures,
266 k: &mut dyn FnMut(usize, &Captures) -> bool,
267 ) -> bool {
268 match node {
269 Node::Empty => k(position, caps),
270 Node::Char(expected) => match self.at(position) {
271 Some(actual) if self.chars_equal(actual, *expected) => k(position + 1, caps),
272 _ => false,
273 },
274 Node::Any => match self.at(position) {
275 Some(c) if self.flags.dot_all || c != '\n' => k(position + 1, caps),
276 _ => false,
277 },
278 Node::Class(negated, ranges) => match self.at(position) {
279 Some(c) if self.in_class(c, ranges) != *negated => k(position + 1, caps),
280 _ => false,
281 },
282 Node::Property { kind, negated } => match self.at(position) {
285 Some(c) if self.property_holds(*kind, *negated, c) => k(position + 1, caps),
286 _ => false,
287 },
288 Node::Set(set) => {
293 for length in self.set_lengths(set, position) {
294 if k(position + length, caps) {
295 return true;
296 }
297 }
298 false
299 }
300 Node::Start => {
301 let at_start =
302 position == 0 || (self.flags.multiline && self.after_newline(position));
303 if at_start { k(position, caps) } else { false }
304 }
305 Node::End => {
306 let at_end = position == self.input.len()
307 || (self.flags.multiline && self.at_newline(position));
308 if at_end { k(position, caps) } else { false }
309 }
310 Node::WordBoundary(want) => {
311 let before = position
312 .checked_sub(1)
313 .and_then(|p| self.at(p))
314 .is_some_and(is_word);
315 let after = self.at(position).is_some_and(is_word);
316 if (before != after) == *want {
317 k(position, caps)
318 } else {
319 false
320 }
321 }
322 Node::Group { index, node } => match index {
323 None => self.node(node, position, caps, k),
325 Some(index) => {
326 self.node(node, position, caps, &mut |end, inner| {
329 let mut inner = inner.clone();
330 if let Some(slot) = inner.get_mut(*index) {
331 *slot = Some((position, end));
332 }
333 k(end, &inner)
334 })
335 }
336 },
337 Node::Concat(nodes) => self.seq(nodes, position, caps, k),
338 Node::Alt(branches) => {
339 for branch in branches {
340 if self.node(branch, position, caps, k) {
341 return true;
342 }
343 }
344 false
345 }
346 Node::Repeat {
347 node,
348 min,
349 max,
350 greedy,
351 } => self.repeat(node, *min, *max, *greedy, 0, position, caps, k),
352 Node::Backref(index) => {
353 let Some(Some((start, end))) = caps.get(*index) else {
354 return k(position, caps);
357 };
358 let (start, end) = (*start, *end);
359 if end - start > self.input.len() - position {
360 return false;
361 }
362 let ok = (0..end - start).all(|offset| {
363 self.chars_equal(self.input[start + offset], self.input[position + offset])
364 });
365 if ok {
366 k(position + (end - start), caps)
367 } else {
368 false
369 }
370 }
371 Node::Look {
372 node,
373 ahead,
374 negated,
375 } => {
376 if !*ahead {
377 return false;
379 }
380 let mut captured = None;
383 let found = self.node(node, position, caps, &mut |_, inner| {
384 captured = Some(inner.clone());
385 true
386 });
387 match (found, negated) {
388 (true, false) => {
389 let inner = captured.unwrap_or_else(|| caps.clone());
390 k(position, &inner)
391 }
392 (true, true) => false,
393 (false, _) => {
394 if *negated {
395 k(position, caps)
396 } else {
397 false
398 }
399 }
400 }
401 }
402 }
403 }
404
405 #[allow(clippy::too_many_arguments)]
406 fn repeat(
407 &self,
408 node: &Node,
409 min: u32,
410 max: Option<u32>,
411 greedy: bool,
412 count: u32,
413 position: usize,
414 caps: &Captures,
415 k: &mut dyn FnMut(usize, &Captures) -> bool,
416 ) -> bool {
417 let may_iterate = max.is_none_or(|max| count < max);
418 let try_iterate = |k: &mut dyn FnMut(usize, &Captures) -> bool| {
420 if !may_iterate {
421 return false;
422 }
423 let mut entry = caps.clone();
429 if let Some((low, high)) = inner_groups(node) {
430 for slot in entry.iter_mut().take(high + 1).skip(low) {
431 *slot = None;
432 }
433 }
434 let caps = &entry;
435 self.node(node, position, caps, &mut |end, inner| {
436 if end == position && count >= min {
440 return false;
441 }
442 self.repeat(node, min, max, greedy, count + 1, end, inner, k)
443 })
444 };
445 if greedy {
446 if try_iterate(k) {
447 return true;
448 }
449 if count >= min {
450 k(position, caps)
451 } else {
452 false
453 }
454 } else {
455 if count >= min && k(position, caps) {
456 return true;
457 }
458 try_iterate(k)
459 }
460 }
461
462 fn after_newline(&self, position: usize) -> bool {
463 position > 0 && self.at(position - 1) == Some('\n')
464 }
465
466 fn at_newline(&self, position: usize) -> bool {
467 self.at(position) == Some('\n')
468 }
469}
470
471fn inner_groups(node: &Node) -> Option<(usize, usize)> {
473 let mut low = usize::MAX;
474 let mut high = 0usize;
475 fn walk(node: &Node, low: &mut usize, high: &mut usize) {
476 match node {
477 Node::Group { index, node } => {
478 if let Some(index) = index {
479 *low = (*low).min(*index);
480 *high = (*high).max(*index);
481 }
482 walk(node, low, high);
483 }
484 Node::Concat(nodes) | Node::Alt(nodes) => {
485 for node in nodes {
486 walk(node, low, high);
487 }
488 }
489 Node::Repeat { node, .. } | Node::Look { node, .. } => walk(node, low, high),
490 _ => {}
491 }
492 }
493 walk(node, &mut low, &mut high);
494 (low != usize::MAX).then_some((low, high))
495}
496
497fn is_word(c: char) -> bool {
499 c.is_alphanumeric() || c == '_'
500}