Debian Codegraph @

third_party/rust/regex-automata/src/util/look.rs

raw
1 /*!
2 Types and routines for working with look-around assertions.
3
4 This module principally defines two types:
5
6 * [`Look`] enumerates all of the assertions supported by this crate.
7 * [`LookSet`] provides a way to efficiently store a set of [`Look`] values.
8 * [`LookMatcher`] provides routines for checking whether a `Look` or a
9 `LookSet` matches at a particular position in a haystack.
10 */
11
12 // LAMENTATION: Sadly, a lot of the API of `Look` and `LookSet` were basically
13 // copied verbatim from the regex-syntax crate. I would have no problems using
14 // the regex-syntax types and defining the matching routines (only found
15 // in this crate) as free functions, except the `Look` and `LookSet` types
16 // are used in lots of places. Including in places we expect to work when
17 // regex-syntax is *not* enabled, such as in the definition of the NFA itself.
18 //
19 // Thankfully the code we copy is pretty simple and there isn't much of it.
20 // Otherwise, the rest of this module deals with *matching* the assertions,
21 // which is not something that regex-syntax handles.
22
23 use crate::util::{escape::DebugByte, utf8};
24
25 /// A look-around assertion.
26 ///
27 /// An assertion matches at a position between characters in a haystack.
28 /// Namely, it does not actually "consume" any input as most parts of a regular
29 /// expression do. Assertions are a way of stating that some property must be
30 /// true at a particular point during matching.
31 ///
32 /// For example, `(?m)^[a-z]+$` is a pattern that:
33 ///
34 /// * Scans the haystack for a position at which `(?m:^)` is satisfied. That
35 /// occurs at either the beginning of the haystack, or immediately following
36 /// a `\n` character.
37 /// * Looks for one or more occurrences of `[a-z]`.
38 /// * Once `[a-z]+` has matched as much as it can, an overall match is only
39 /// reported when `[a-z]+` stops just before a `\n`.
40 ///
41 /// So in this case, `abc` and `\nabc\n` match, but `\nabc1\n` does not.
42 ///
43 /// Assertions are also called "look-around," "look-behind" and "look-ahead."
44 /// Specifically, some assertions are look-behind (like `^`), other assertions
45 /// are look-ahead (like `$`) and yet other assertions are both look-ahead and
46 /// look-behind (like `\b`).
47 ///
48 /// # Assertions in an NFA
49 ///
50 /// An assertion in a [`thompson::NFA`](crate::nfa::thompson::NFA) can be
51 /// thought of as a conditional epsilon transition. That is, a matching engine
52 /// like the [`PikeVM`](crate::nfa::thompson::pikevm::PikeVM) only permits
53 /// moving through conditional epsilon transitions when their condition
54 /// is satisfied at whatever position the `PikeVM` is currently at in the
55 /// haystack.
56 ///
57 /// How assertions are handled in a `DFA` is trickier, since a DFA does not
58 /// have epsilon transitions at all. In this case, they are compiled into the
59 /// automaton itself, at the expense of more states than what would be required
60 /// without an assertion.
61 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
62 pub enum Look {
63 /// Match the beginning of text. Specifically, this matches at the starting
64 /// position of the input.
65 Start = 1 << 0,
66 /// Match the end of text. Specifically, this matches at the ending
67 /// position of the input.
68 End = 1 << 1,
69 /// Match the beginning of a line or the beginning of text. Specifically,
70 /// this matches at the starting position of the input, or at the position
71 /// immediately following a `\n` character.
72 StartLF = 1 << 2,
73 /// Match the end of a line or the end of text. Specifically, this matches
74 /// at the end position of the input, or at the position immediately
75 /// preceding a `\n` character.
76 EndLF = 1 << 3,
77 /// Match the beginning of a line or the beginning of text. Specifically,
78 /// this matches at the starting position of the input, or at the position
79 /// immediately following either a `\r` or `\n` character, but never after
80 /// a `\r` when a `\n` follows.
81 StartCRLF = 1 << 4,
82 /// Match the end of a line or the end of text. Specifically, this matches
83 /// at the end position of the input, or at the position immediately
84 /// preceding a `\r` or `\n` character, but never before a `\n` when a `\r`
85 /// precedes it.
86 EndCRLF = 1 << 5,
87 /// Match an ASCII-only word boundary. That is, this matches a position
88 /// where the left adjacent character and right adjacent character
89 /// correspond to a word and non-word or a non-word and word character.
90 WordAscii = 1 << 6,
91 /// Match an ASCII-only negation of a word boundary.
92 WordAsciiNegate = 1 << 7,
93 /// Match a Unicode-aware word boundary. That is, this matches a position
94 /// where the left adjacent character and right adjacent character
95 /// correspond to a word and non-word or a non-word and word character.
96 WordUnicode = 1 << 8,
97 /// Match a Unicode-aware negation of a word boundary.
98 WordUnicodeNegate = 1 << 9,
99 }
100
101 impl Look {
102 /// Flip the look-around assertion to its equivalent for reverse searches.
103 /// For example, `StartLF` gets translated to `EndLF`.
104 ///
105 /// Some assertions, such as `WordUnicode`, remain the same since they
106 /// match the same positions regardless of the direction of the search.
107 #[inline]
108 pub const fn reversed(self) -> Look {
109 match self {
110 Look::Start => Look::End,
111 Look::End => Look::Start,
112 Look::StartLF => Look::EndLF,
113 Look::EndLF => Look::StartLF,
114 Look::StartCRLF => Look::EndCRLF,
115 Look::EndCRLF => Look::StartCRLF,
116 Look::WordAscii => Look::WordAscii,
117 Look::WordAsciiNegate => Look::WordAsciiNegate,
118 Look::WordUnicode => Look::WordUnicode,
119 Look::WordUnicodeNegate => Look::WordUnicodeNegate,
120 }
121 }
122
123 /// Return the underlying representation of this look-around enumeration
124 /// as an integer. Giving the return value to the [`Look::from_repr`]
125 /// constructor is guaranteed to return the same look-around variant that
126 /// one started with within a semver compatible release of this crate.
127 #[inline]
128 pub const fn as_repr(self) -> u16 {
129 // AFAIK, 'as' is the only way to zero-cost convert an int enum to an
130 // actual int.
131 self as u16
132 }
133
134 /// Given the underlying representation of a `Look` value, return the
135 /// corresponding `Look` value if the representation is valid. Otherwise
136 /// `None` is returned.
137 #[inline]
138 pub const fn from_repr(repr: u16) -> Option<Look> {
139 match repr {
140 0b00_0000_0001 => Some(Look::Start),
141 0b00_0000_0010 => Some(Look::End),
142 0b00_0000_0100 => Some(Look::StartLF),
143 0b00_0000_1000 => Some(Look::EndLF),
144 0b00_0001_0000 => Some(Look::StartCRLF),
145 0b00_0010_0000 => Some(Look::EndCRLF),
146 0b00_0100_0000 => Some(Look::WordAscii),
147 0b00_1000_0000 => Some(Look::WordAsciiNegate),
148 0b01_0000_0000 => Some(Look::WordUnicode),
149 0b10_0000_0000 => Some(Look::WordUnicodeNegate),
150 _ => None,
151 }
152 }
153
154 /// Returns a convenient single codepoint representation of this
155 /// look-around assertion. Each assertion is guaranteed to be represented
156 /// by a distinct character.
157 ///
158 /// This is useful for succinctly representing a look-around assertion in
159 /// human friendly but succinct output intended for a programmer working on
160 /// regex internals.
161 #[inline]
162 pub const fn as_char(self) -> char {
163 match self {
164 Look::Start => 'A',
165 Look::End => 'z',
166 Look::StartLF => '^',
167 Look::EndLF => '$',
168 Look::StartCRLF => 'r',
169 Look::EndCRLF => 'R',
170 Look::WordAscii => 'b',
171 Look::WordAsciiNegate => 'B',
172 Look::WordUnicode => '𝛃',
173 Look::WordUnicodeNegate => '𝚩',
174 }
175 }
176 }
177
178 /// LookSet is a memory-efficient set of look-around assertions.
179 ///
180 /// This is useful for efficiently tracking look-around assertions. For
181 /// example, a [`thompson::NFA`](crate::nfa::thompson::NFA) provides properties
182 /// that return `LookSet`s.
183 #[derive(Clone, Copy, Default, Eq, PartialEq)]
184 pub struct LookSet {
185 /// The underlying representation this set is exposed to make it possible
186 /// to store it somewhere efficiently. The representation is that
187 /// of a bitset, where each assertion occupies bit `i` where `i =
188 /// Look::as_repr()`.
189 ///
190 /// Note that users of this internal representation must permit the full
191 /// range of `u16` values to be represented. For example, even if the
192 /// current implementation only makes use of the 10 least significant bits,
193 /// it may use more bits in a future semver compatible release.
194 pub bits: u16,
195 }
196
197 impl LookSet {
198 /// Create an empty set of look-around assertions.
199 #[inline]
200 pub fn empty() -> LookSet {
201 LookSet { bits: 0 }
202 }
203
204 /// Create a full set of look-around assertions.
205 ///
206 /// This set contains all possible look-around assertions.
207 #[inline]
208 pub fn full() -> LookSet {
209 LookSet { bits: !0 }
210 }
211
212 /// Create a look-around set containing the look-around assertion given.
213 ///
214 /// This is a convenience routine for creating an empty set and inserting
215 /// one look-around assertions.
216 #[inline]
217 pub fn singleton(look: Look) -> LookSet {
218 LookSet::empty().insert(look)
219 }
220
221 /// Returns the total number of look-around assertions in this set.
222 #[inline]
223 pub fn len(self) -> usize {
224 // OK because max value always fits in a u8, which in turn always
225 // fits in a usize, regardless of target.
226 usize::try_from(self.bits.count_ones()).unwrap()
227 }
228
229 /// Returns true if and only if this set is empty.
230 #[inline]
231 pub fn is_empty(self) -> bool {
232 self.len() == 0
233 }
234
235 /// Returns true if and only if the given look-around assertion is in this
236 /// set.
237 #[inline]
238 pub fn contains(self, look: Look) -> bool {
239 self.bits & look.as_repr() != 0
240 }
241
242 /// Returns true if and only if this set contains any anchor assertions.
243 /// This includes both "start/end of haystack" and "start/end of line."
244 #[inline]
245 pub fn contains_anchor(&self) -> bool {
246 self.contains_anchor_haystack() || self.contains_anchor_line()
247 }
248
249 /// Returns true if and only if this set contains any "start/end of
250 /// haystack" anchors. This doesn't include "start/end of line" anchors.
251 #[inline]
252 pub fn contains_anchor_haystack(&self) -> bool {
253 self.contains(Look::Start) || self.contains(Look::End)
254 }
255
256 /// Returns true if and only if this set contains any "start/end of line"
257 /// anchors. This doesn't include "start/end of haystack" anchors. This
258 /// includes both `\n` line anchors and CRLF (`\r\n`) aware line anchors.
259 #[inline]
260 pub fn contains_anchor_line(&self) -> bool {
261 self.contains(Look::StartLF)
262 || self.contains(Look::EndLF)
263 || self.contains(Look::StartCRLF)
264 || self.contains(Look::EndCRLF)
265 }
266
267 /// Returns true if and only if this set contains any "start/end of line"
268 /// anchors that only treat `\n` as line terminators. This does not include
269 /// haystack anchors or CRLF aware line anchors.
270 #[inline]
271 pub fn contains_anchor_lf(&self) -> bool {
272 self.contains(Look::StartLF) || self.contains(Look::EndLF)
273 }
274
275 /// Returns true if and only if this set contains any "start/end of line"
276 /// anchors that are CRLF-aware. This doesn't include "start/end of
277 /// haystack" or "start/end of line-feed" anchors.
278 #[inline]
279 pub fn contains_anchor_crlf(&self) -> bool {
280 self.contains(Look::StartCRLF) || self.contains(Look::EndCRLF)
281 }
282
283 /// Returns true if and only if this set contains any word boundary or
284 /// negated word boundary assertions. This include both Unicode and ASCII
285 /// word boundaries.
286 #[inline]
287 pub fn contains_word(self) -> bool {
288 self.contains_word_unicode() || self.contains_word_ascii()
289 }
290
291 /// Returns true if and only if this set contains any Unicode word boundary
292 /// or negated Unicode word boundary assertions.
293 #[inline]
294 pub fn contains_word_unicode(self) -> bool {
295 self.contains(Look::WordUnicode)
296 || self.contains(Look::WordUnicodeNegate)
297 }
298
299 /// Returns true if and only if this set contains any ASCII word boundary
300 /// or negated ASCII word boundary assertions.
301 #[inline]
302 pub fn contains_word_ascii(self) -> bool {
303 self.contains(Look::WordAscii) || self.contains(Look::WordAsciiNegate)
304 }
305
306 /// Returns an iterator over all of the look-around assertions in this set.
307 #[inline]
308 pub fn iter(self) -> LookSetIter {
309 LookSetIter { set: self }
310 }
311
312 /// Return a new set that is equivalent to the original, but with the given
313 /// assertion added to it. If the assertion is already in the set, then the
314 /// returned set is equivalent to the original.
315 #[inline]
316 pub fn insert(self, look: Look) -> LookSet {
317 LookSet { bits: self.bits | look.as_repr() }
318 }
319
320 /// Updates this set in place with the result of inserting the given
321 /// assertion into this set.
322 #[inline]
323 pub fn set_insert(&mut self, look: Look) {
324 *self = self.insert(look);
325 }
326
327 /// Return a new set that is equivalent to the original, but with the given
328 /// assertion removed from it. If the assertion is not in the set, then the
329 /// returned set is equivalent to the original.
330 #[inline]
331 pub fn remove(self, look: Look) -> LookSet {
332 LookSet { bits: self.bits & !look.as_repr() }
333 }
334
335 /// Updates this set in place with the result of removing the given
336 /// assertion from this set.
337 #[inline]
338 pub fn set_remove(&mut self, look: Look) {
339 *self = self.remove(look);
340 }
341
342 /// Returns a new set that is the result of subtracting the given set from
343 /// this set.
344 #[inline]
345 pub fn subtract(self, other: LookSet) -> LookSet {
346 LookSet { bits: self.bits & !other.bits }
347 }
348
349 /// Updates this set in place with the result of subtracting the given set
350 /// from this set.
351 #[inline]
352 pub fn set_subtract(&mut self, other: LookSet) {
353 *self = self.subtract(other);
354 }
355
356 /// Returns a new set that is the union of this and the one given.
357 #[inline]
358 pub fn union(self, other: LookSet) -> LookSet {
359 LookSet { bits: self.bits | other.bits }
360 }
361
362 /// Updates this set in place with the result of unioning it with the one
363 /// given.
364 #[inline]
365 pub fn set_union(&mut self, other: LookSet) {
366 *self = self.union(other);
367 }
368
369 /// Returns a new set that is the intersection of this and the one given.
370 #[inline]
371 pub fn intersect(self, other: LookSet) -> LookSet {
372 LookSet { bits: self.bits & other.bits }
373 }
374
375 /// Updates this set in place with the result of intersecting it with the
376 /// one given.
377 #[inline]
378 pub fn set_intersect(&mut self, other: LookSet) {
379 *self = self.intersect(other);
380 }
381
382 /// Return a `LookSet` from the slice given as a native endian 16-bit
383 /// integer.
384 ///
385 /// # Panics
386 ///
387 /// This panics if `slice.len() < 2`.
388 #[inline]
389 pub fn read_repr(slice: &[u8]) -> LookSet {
390 let bits = u16::from_ne_bytes(slice[..2].try_into().unwrap());
391 LookSet { bits }
392 }
393
394 /// Write a `LookSet` as a native endian 16-bit integer to the beginning
395 /// of the slice given.
396 ///
397 /// # Panics
398 ///
399 /// This panics if `slice.len() < 2`.
400 #[inline]
401 pub fn write_repr(self, slice: &mut [u8]) {
402 let raw = self.bits.to_ne_bytes();
403 slice[0] = raw[0];
404 slice[1] = raw[1];
405 }
406
407 /// Checks that all assertions in this set can be matched.
408 ///
409 /// Some assertions, such as Unicode word boundaries, require optional (but
410 /// enabled by default) tables that may not be available. If there are
411 /// assertions in this set that require tables that are not available, then
412 /// this will return an error.
413 ///
414 /// Specifically, this returns an error when the the
415 /// `unicode-word-boundary` feature is _not_ enabled _and_ this set
416 /// contains a Unicode word boundary assertion.
417 ///
418 /// It can be useful to use this on the result of
419 /// [`NFA::look_set_any`](crate::nfa::thompson::NFA::look_set_any)
420 /// when building a matcher engine to ensure methods like
421 /// [`LookMatcher::matches_set`] do not panic at search time.
422 pub fn available(self) -> Result<(), UnicodeWordBoundaryError> {
423 if self.contains_word_unicode() {
424 UnicodeWordBoundaryError::check()?;
425 }
426 Ok(())
427 }
428 }
429
430 impl core::fmt::Debug for LookSet {
431 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
432 if self.is_empty() {
433 return write!(f, "∅");
434 }
435 for look in self.iter() {
436 write!(f, "{}", look.as_char())?;
437 }
438 Ok(())
439 }
440 }
441
442 /// An iterator over all look-around assertions in a [`LookSet`].
443 ///
444 /// This iterator is created by [`LookSet::iter`].
445 #[derive(Clone, Debug)]
446 pub struct LookSetIter {
447 set: LookSet,
448 }
449
450 impl Iterator for LookSetIter {
451 type Item = Look;
452
453 #[inline]
454 fn next(&mut self) -> Option<Look> {
455 if self.set.is_empty() {
456 return None;
457 }
458 // We'll never have more than u8::MAX distinct look-around assertions,
459 // so 'repr' will always fit into a u16.
460 let repr = u16::try_from(self.set.bits.trailing_zeros()).unwrap();
461 let look = Look::from_repr(1 << repr)?;
462 self.set = self.set.remove(look);
463 Some(look)
464 }
465 }
466
467 /// A matcher for look-around assertions.
468 ///
469 /// This matcher permits configuring aspects of how look-around assertions are
470 /// matched.
471 ///
472 /// # Example
473 ///
474 /// A `LookMatcher` can change the line terminator used for matching multi-line
475 /// anchors such as `(?m:^)` and `(?m:$)`.
476 ///
477 /// ```
478 /// use regex_automata::{
479 /// nfa::thompson::{self, pikevm::PikeVM},
480 /// util::look::LookMatcher,
481 /// Match, Input,
482 /// };
483 ///
484 /// let mut lookm = LookMatcher::new();
485 /// lookm.set_line_terminator(b'\x00');
486 ///
487 /// let re = PikeVM::builder()
488 /// .thompson(thompson::Config::new().look_matcher(lookm))
489 /// .build(r"(?m)^[a-z]+$")?;
490 /// let mut cache = re.create_cache();
491 ///
492 /// // Multi-line assertions now use NUL as a terminator.
493 /// assert_eq!(
494 /// Some(Match::must(0, 1..4)),
495 /// re.find(&mut cache, b"\x00abc\x00"),
496 /// );
497 /// // ... and \n is no longer recognized as a terminator.
498 /// assert_eq!(
499 /// None,
500 /// re.find(&mut cache, b"\nabc\n"),
501 /// );
502 ///
503 /// # Ok::<(), Box<dyn std::error::Error>>(())
504 /// ```
505 #[derive(Clone, Debug)]
506 pub struct LookMatcher {
507 lineterm: DebugByte,
508 }
509
510 impl LookMatcher {
511 /// Creates a new default matcher for look-around assertions.
512 pub fn new() -> LookMatcher {
513 LookMatcher { lineterm: DebugByte(b'\n') }
514 }
515
516 /// Sets the line terminator for use with `(?m:^)` and `(?m:$)`.
517 ///
518 /// Namely, instead of `^` matching after `\n` and `$` matching immediately
519 /// before a `\n`, this will cause it to match after and before the byte
520 /// given.
521 ///
522 /// It can occasionally be useful to use this to configure the line
523 /// terminator to the NUL byte when searching binary data.
524 ///
525 /// Note that this does not apply to CRLF-aware line anchors such as
526 /// `(?Rm:^)` and `(?Rm:$)`. CRLF-aware line anchors are hard-coded to
527 /// use `\r` and `\n`.
528 pub fn set_line_terminator(&mut self, byte: u8) -> &mut LookMatcher {
529 self.lineterm.0 = byte;
530 self
531 }
532
533 /// Returns the line terminator that was configured for this matcher.
534 ///
535 /// If no line terminator was configured, then this returns `\n`.
536 ///
537 /// Note that the line terminator should only be used for matching `(?m:^)`
538 /// and `(?m:$)` assertions. It specifically should _not_ be used for
539 /// matching the CRLF aware assertions `(?Rm:^)` and `(?Rm:$)`.
540 pub fn get_line_terminator(&self) -> u8 {
541 self.lineterm.0
542 }
543
544 /// Returns true when the position `at` in `haystack` satisfies the given
545 /// look-around assertion.
546 ///
547 /// # Panics
548 ///
549 /// This panics when testing any Unicode word boundary assertion in this
550 /// set and when the Unicode word data is not available. Specifically, this
551 /// only occurs when the `unicode-word-boundary` feature is not enabled.
552 ///
553 /// Since it's generally expected that this routine is called inside of
554 /// a matching engine, callers should check the error condition when
555 /// building the matching engine. If there is a Unicode word boundary
556 /// in the matcher and the data isn't available, then the matcher should
557 /// fail to build.
558 ///
559 /// Callers can check the error condition with [`LookSet::available`].
560 ///
561 /// This also may panic when `at > haystack.len()`. Note that `at ==
562 /// haystack.len()` is legal and guaranteed not to panic.
563 #[inline]
564 pub fn matches(&self, look: Look, haystack: &[u8], at: usize) -> bool {
565 self.matches_inline(look, haystack, at)
566 }
567
568 /// Like `matches`, but forcefully inlined.
569 #[cfg_attr(feature = "perf-inline", inline(always))]
570 pub(crate) fn matches_inline(
571 &self,
572 look: Look,
573 haystack: &[u8],
574 at: usize,
575 ) -> bool {
576 match look {
577 Look::Start => self.is_start(haystack, at),
578 Look::End => self.is_end(haystack, at),
579 Look::StartLF => self.is_start_lf(haystack, at),
580 Look::EndLF => self.is_end_lf(haystack, at),
581 Look::StartCRLF => self.is_start_crlf(haystack, at),
582 Look::EndCRLF => self.is_end_crlf(haystack, at),
583 Look::WordAscii => self.is_word_ascii(haystack, at),
584 Look::WordAsciiNegate => self.is_word_ascii_negate(haystack, at),
585 Look::WordUnicode => self.is_word_unicode(haystack, at).unwrap(),
586 Look::WordUnicodeNegate => {
587 self.is_word_unicode_negate(haystack, at).unwrap()
588 }
589 }
590 }
591
592 /// Returns true when _all_ of the assertions in the given set match at the
593 /// given position in the haystack.
594 ///
595 /// # Panics
596 ///
597 /// This panics when testing any Unicode word boundary assertion in this
598 /// set and when the Unicode word data is not available. Specifically, this
599 /// only occurs when the `unicode-word-boundary` feature is not enabled.
600 ///
601 /// Since it's generally expected that this routine is called inside of
602 /// a matching engine, callers should check the error condition when
603 /// building the matching engine. If there is a Unicode word boundary
604 /// in the matcher and the data isn't available, then the matcher should
605 /// fail to build.
606 ///
607 /// Callers can check the error condition with [`LookSet::available`].
608 ///
609 /// This also may panic when `at > haystack.len()`. Note that `at ==
610 /// haystack.len()` is legal and guaranteed not to panic.
611 #[inline]
612 pub fn matches_set(
613 &self,
614 set: LookSet,
615 haystack: &[u8],
616 at: usize,
617 ) -> bool {
618 self.matches_set_inline(set, haystack, at)
619 }
620
621 /// Like `LookSet::matches`, but forcefully inlined for perf.
622 #[cfg_attr(feature = "perf-inline", inline(always))]
623 pub(crate) fn matches_set_inline(
624 &self,
625 set: LookSet,
626 haystack: &[u8],
627 at: usize,
628 ) -> bool {
629 // This used to luse LookSet::iter with Look::matches on each element,
630 // but that proved to be quite diastrous for perf. The manual "if
631 // the set has this assertion, check it" turns out to be quite a bit
632 // faster.
633 if set.contains(Look::Start) {
634 if !self.is_start(haystack, at) {
635 return false;
636 }
637 }
638 if set.contains(Look::End) {
639 if !self.is_end(haystack, at) {
640 return false;
641 }
642 }
643 if set.contains(Look::StartLF) {
644 if !self.is_start_lf(haystack, at) {
645 return false;
646 }
647 }
648 if set.contains(Look::EndLF) {
649 if !self.is_end_lf(haystack, at) {
650 return false;
651 }
652 }
653 if set.contains(Look::StartCRLF) {
654 if !self.is_start_crlf(haystack, at) {
655 return false;
656 }
657 }
658 if set.contains(Look::EndCRLF) {
659 if !self.is_end_crlf(haystack, at) {
660 return false;
661 }
662 }
663 if set.contains(Look::WordAscii) {
664 if !self.is_word_ascii(haystack, at) {
665 return false;
666 }
667 }
668 if set.contains(Look::WordAsciiNegate) {
669 if !self.is_word_ascii_negate(haystack, at) {
670 return false;
671 }
672 }
673 if set.contains(Look::WordUnicode) {
674 if !self.is_word_unicode(haystack, at).unwrap() {
675 return false;
676 }
677 }
678 if set.contains(Look::WordUnicodeNegate) {
679 if !self.is_word_unicode_negate(haystack, at).unwrap() {
680 return false;
681 }
682 }
683 true
684 }
685
686 /// Split up the given byte classes into equivalence classes in a way that
687 /// is consistent with this look-around assertion.
688 #[cfg(feature = "alloc")]
689 pub(crate) fn add_to_byteset(
690 &self,
691 look: Look,
692 set: &mut crate::util::alphabet::ByteClassSet,
693 ) {
694 match look {
695 Look::Start | Look::End => {}
696 Look::StartLF | Look::EndLF => {
697 set.set_range(self.lineterm.0, self.lineterm.0);
698 }
699 Look::StartCRLF | Look::EndCRLF => {
700 set.set_range(b'\r', b'\r');
701 set.set_range(b'\n', b'\n');
702 }
703 Look::WordAscii
704 | Look::WordAsciiNegate
705 | Look::WordUnicode
706 | Look::WordUnicodeNegate => {
707 // We need to mark all ranges of bytes whose pairs result in
708 // evaluating \b differently. This isn't technically correct
709 // for Unicode word boundaries, but DFAs can't handle those
710 // anyway, and thus, the byte classes don't need to either
711 // since they are themselves only used in DFAs.
712 //
713 // FIXME: It seems like the calls to 'set_range' here are
714 // completely invariant, which means we could just hard-code
715 // them here without needing to write a loop. And we only need
716 // to do this dance at most once per regex.
717 //
718 // FIXME: Is this correct for \B?
719 let iswb = utf8::is_word_byte;
720 // This unwrap is OK because we guard every use of 'asu8' with
721 // a check that the input is <= 255.
722 let asu8 = |b: u16| u8::try_from(b).unwrap();
723 let mut b1: u16 = 0;
724 let mut b2: u16;
725 while b1 <= 255 {
726 b2 = b1 + 1;
727 while b2 <= 255 && iswb(asu8(b1)) == iswb(asu8(b2)) {
728 b2 += 1;
729 }
730 // The guards above guarantee that b2 can never get any
731 // bigger.
732 assert!(b2 <= 256);
733 // Subtracting 1 from b2 is always OK because it is always
734 // at least 1 greater than b1, and the assert above
735 // guarantees that the asu8 conversion will succeed.
736 set.set_range(asu8(b1), asu8(b2.checked_sub(1).unwrap()));
737 b1 = b2;
738 }
739 }
740 }
741 }
742
743 /// Returns true when [`Look::Start`] is satisfied `at` the given position
744 /// in `haystack`.
745 ///
746 /// # Panics
747 ///
748 /// This may panic when `at > haystack.len()`. Note that `at ==
749 /// haystack.len()` is legal and guaranteed not to panic.
750 #[inline]
751 pub fn is_start(&self, _haystack: &[u8], at: usize) -> bool {
752 at == 0
753 }
754
755 /// Returns true when [`Look::End`] is satisfied `at` the given position in
756 /// `haystack`.
757 ///
758 /// # Panics
759 ///
760 /// This may panic when `at > haystack.len()`. Note that `at ==
761 /// haystack.len()` is legal and guaranteed not to panic.
762 #[inline]
763 pub fn is_end(&self, haystack: &[u8], at: usize) -> bool {
764 at == haystack.len()
765 }
766
767 /// Returns true when [`Look::StartLF`] is satisfied `at` the given
768 /// position in `haystack`.
769 ///
770 /// # Panics
771 ///
772 /// This may panic when `at > haystack.len()`. Note that `at ==
773 /// haystack.len()` is legal and guaranteed not to panic.
774 #[inline]
775 pub fn is_start_lf(&self, haystack: &[u8], at: usize) -> bool {
776 self.is_start(haystack, at) || haystack[at - 1] == self.lineterm.0
777 }
778
779 /// Returns true when [`Look::EndLF`] is satisfied `at` the given position
780 /// in `haystack`.
781 ///
782 /// # Panics
783 ///
784 /// This may panic when `at > haystack.len()`. Note that `at ==
785 /// haystack.len()` is legal and guaranteed not to panic.
786 #[inline]
787 pub fn is_end_lf(&self, haystack: &[u8], at: usize) -> bool {
788 self.is_end(haystack, at) || haystack[at] == self.lineterm.0
789 }
790
791 /// Returns true when [`Look::StartCRLF`] is satisfied `at` the given
792 /// position in `haystack`.
793 ///
794 /// # Panics
795 ///
796 /// This may panic when `at > haystack.len()`. Note that `at ==
797 /// haystack.len()` is legal and guaranteed not to panic.
798 #[inline]
799 pub fn is_start_crlf(&self, haystack: &[u8], at: usize) -> bool {
800 self.is_start(haystack, at)
801 || haystack[at - 1] == b'\n'
802 || (haystack[at - 1] == b'\r'
803 && (at >= haystack.len() || haystack[at] != b'\n'))
804 }
805
806 /// Returns true when [`Look::EndCRLF`] is satisfied `at` the given
807 /// position in `haystack`.
808 ///
809 /// # Panics
810 ///
811 /// This may panic when `at > haystack.len()`. Note that `at ==
812 /// haystack.len()` is legal and guaranteed not to panic.
813 #[inline]
814 pub fn is_end_crlf(&self, haystack: &[u8], at: usize) -> bool {
815 self.is_end(haystack, at)
816 || haystack[at] == b'\r'
817 || (haystack[at] == b'\n'
818 && (at == 0 || haystack[at - 1] != b'\r'))
819 }
820
821 /// Returns true when [`Look::WordAscii`] is satisfied `at` the given
822 /// position in `haystack`.
823 ///
824 /// # Panics
825 ///
826 /// This may panic when `at > haystack.len()`. Note that `at ==
827 /// haystack.len()` is legal and guaranteed not to panic.
828 #[inline]
829 pub fn is_word_ascii(&self, haystack: &[u8], at: usize) -> bool {
830 let word_before = at > 0 && utf8::is_word_byte(haystack[at - 1]);
831 let word_after =
832 at < haystack.len() && utf8::is_word_byte(haystack[at]);
833 word_before != word_after
834 }
835
836 /// Returns true when [`Look::WordAsciiNegate`] is satisfied `at` the given
837 /// position in `haystack`.
838 ///
839 /// # Panics
840 ///
841 /// This may panic when `at > haystack.len()`. Note that `at ==
842 /// haystack.len()` is legal and guaranteed not to panic.
843 #[inline]
844 pub fn is_word_ascii_negate(&self, haystack: &[u8], at: usize) -> bool {
845 !self.is_word_ascii(haystack, at)
846 }
847
848 /// Returns true when [`Look::WordUnicode`] is satisfied `at` the given
849 /// position in `haystack`.
850 ///
851 /// # Panics
852 ///
853 /// This may panic when `at > haystack.len()`. Note that `at ==
854 /// haystack.len()` is legal and guaranteed not to panic.
855 ///
856 /// # Errors
857 ///
858 /// This returns an error when Unicode word boundary tables
859 /// are not available. Specifically, this only occurs when the
860 /// `unicode-word-boundary` feature is not enabled.
861 #[inline]
862 pub fn is_word_unicode(
863 &self,
864 haystack: &[u8],
865 at: usize,
866 ) -> Result<bool, UnicodeWordBoundaryError> {
867 let word_before = is_word_char::rev(haystack, at)?;
868 let word_after = is_word_char::fwd(haystack, at)?;
869 Ok(word_before != word_after)
870 }
871
872 /// Returns true when [`Look::WordUnicodeNegate`] is satisfied `at` the
873 /// given position in `haystack`.
874 ///
875 /// # Panics
876 ///
877 /// This may panic when `at > haystack.len()`. Note that `at ==
878 /// haystack.len()` is legal and guaranteed not to panic.
879 ///
880 /// # Errors
881 ///
882 /// This returns an error when Unicode word boundary tables
883 /// are not available. Specifically, this only occurs when the
884 /// `unicode-word-boundary` feature is not enabled.
885 #[inline]
886 pub fn is_word_unicode_negate(
887 &self,
888 haystack: &[u8],
889 at: usize,
890 ) -> Result<bool, UnicodeWordBoundaryError> {
891 // This is pretty subtle. Why do we need to do UTF-8 decoding here?
892 // Well... at time of writing, the is_word_char_{fwd,rev} routines will
893 // only return true if there is a valid UTF-8 encoding of a "word"
894 // codepoint, and false in every other case (including invalid UTF-8).
895 // This means that in regions of invalid UTF-8 (which might be a
896 // subset of valid UTF-8!), it would result in \B matching. While this
897 // would be questionable in the context of truly invalid UTF-8, it is
898 // *certainly* wrong to report match boundaries that split the encoding
899 // of a codepoint. So to work around this, we ensure that we can decode
900 // a codepoint on either side of `at`. If either direction fails, then
901 // we don't permit \B to match at all.
902 //
903 // Now, this isn't exactly optimal from a perf perspective. We could
904 // try and detect this in is_word_char::{fwd,rev}, but it's not clear
905 // if it's worth it. \B is, after all, rarely used. Even worse,
906 // is_word_char::{fwd,rev} could do its own UTF-8 decoding, and so this
907 // will wind up doing UTF-8 decoding twice. Owch. We could fix this
908 // with more code complexity, but it just doesn't feel worth it for \B.
909 //
910 // And in particular, we do *not* have to do this with \b, because \b
911 // *requires* that at least one side of `at` be a "word" codepoint,
912 // which in turn implies one side of `at` must be valid UTF-8. This in
913 // turn implies that \b can never split a valid UTF-8 encoding of a
914 // codepoint. In the case where one side of `at` is truly invalid UTF-8
915 // and the other side IS a word codepoint, then we want \b to match
916 // since it represents a valid UTF-8 boundary. It also makes sense. For
917 // example, you'd want \b\w+\b to match 'abc' in '\xFFabc\xFF'.
918 //
919 // Note also that this is not just '!is_word_unicode(..)' like it is
920 // for the ASCII case. For example, neither \b nor \B is satisfied
921 // within invalid UTF-8 sequences.
922 let word_before = at > 0
923 && match utf8::decode_last(&haystack[..at]) {
924 None | Some(Err(_)) => return Ok(false),
925 Some(Ok(_)) => is_word_char::rev(haystack, at)?,
926 };
927 let word_after = at < haystack.len()
928 && match utf8::decode(&haystack[at..]) {
929 None | Some(Err(_)) => return Ok(false),
930 Some(Ok(_)) => is_word_char::fwd(haystack, at)?,
931 };
932 Ok(word_before == word_after)
933 }
934 }
935
936 impl Default for LookMatcher {
937 fn default() -> LookMatcher {
938 LookMatcher::new()
939 }
940 }
941
942 /// An error that occurs when the Unicode-aware `\w` class is unavailable.
943 ///
944 /// This error can occur when the data tables necessary for the Unicode aware
945 /// Perl character class `\w` are unavailable. The `\w` class is used to
946 /// determine whether a codepoint is considered a word character or not when
947 /// determining whether a Unicode aware `\b` (or `\B`) matches at a particular
948 /// position.
949 ///
950 /// This error can only occur when the `unicode-word-boundary` feature is
951 /// disabled.
952 #[derive(Clone, Debug)]
953 pub struct UnicodeWordBoundaryError(());
954
955 impl UnicodeWordBoundaryError {
956 #[cfg(not(feature = "unicode-word-boundary"))]
957 pub(crate) fn new() -> UnicodeWordBoundaryError {
958 UnicodeWordBoundaryError(())
959 }
960
961 /// Returns an error if and only if Unicode word boundary data is
962 /// unavailable.
963 pub fn check() -> Result<(), UnicodeWordBoundaryError> {
964 is_word_char::check()
965 }
966 }
967
968 #[cfg(feature = "std")]
969 impl std::error::Error for UnicodeWordBoundaryError {}
970
971 impl core::fmt::Display for UnicodeWordBoundaryError {
972 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
973 write!(
974 f,
975 "Unicode-aware \\b and \\B are unavailable because the \
976 requisite data tables are missing, please enable the \
977 unicode-word-boundary feature"
978 )
979 }
980 }
981
982 // Below are FOUR different ways for checking whether whether a "word"
983 // codepoint exists at a particular position in the haystack. The four
984 // different approaches are, in order of preference:
985 //
986 // 1. Parse '\w', convert to an NFA, convert to a fully compiled DFA on the
987 // first call, and then use that DFA for all subsequent calls.
988 // 2. Do UTF-8 decoding and use regex_syntax::is_word_character if available.
989 // 3. Do UTF-8 decoding and use our own 'perl_word' table.
990 // 4. Return an error.
991 //
992 // The reason for all of these approaches is a combination of perf and
993 // permitting one to build regex-automata without the Unicode data necessary
994 // for handling Unicode-aware word boundaries. (In which case, '(?-u:\b)' would
995 // still work.)
996 //
997 // The DFA approach is the fastest, but it requires the regex parser, the
998 // NFA compiler, the DFA builder and the DFA search runtime. That's a lot to
999 // bring in, but if it's available, it's (probably) the best we can do.
1000 //
1001 // Approaches (2) and (3) are effectively equivalent, but (2) reuses the
1002 // data in regex-syntax and avoids duplicating it in regex-automata.
1003 //
1004 // Finally, (4) unconditionally returns an error since the requisite data isn't
1005 // available anywhere.
1006 //
1007 // There are actually more approaches possible that we didn't implement. For
1008 // example, if the DFA builder is available but the syntax parser is not, we
1009 // could technically hand construct our own NFA from the 'perl_word' data
1010 // table. But to avoid some pretty hairy code duplication, we would in turn
1011 // need to pull the UTF-8 compiler out of the NFA compiler. Yikes.
1012 //
1013 // A possibly more sensible alternative is to use a lazy DFA when the full
1014 // DFA builder isn't available...
1015 //
1016 // Yet another choice would be to build the full DFA and then embed it into the
1017 // source. Then we'd only need to bring in the DFA search runtime, which is
1018 // considerably smaller than the DFA builder code. The problem here is that the
1019 // Debian people have spooked me[1] into avoiding cyclic dependencies. Namely,
1020 // we'd need to build regex-cli, which depends on regex-automata in order to
1021 // build some part of regex-automata. But to be honest, something like this has
1022 // to be allowed somehow? I just don't know what the right process is.
1023 //
1024 // There are perhaps other choices as well. Why did I stop at these 4? Because
1025 // I wanted to preserve my sanity. I suspect I'll wind up adding the lazy DFA
1026 // approach eventually, as the benefits of the DFA approach are somewhat
1027 // compelling. The 'boundary-words-holmes' benchmark tests this:
1028 //
1029 // $ regex-cli bench measure -f boundary-words-holmes -e pikevm > dfa.csv
1030 //
1031 // Then I changed the code below so that the util/unicode_data/perl_word table
1032 // was used and re-ran the benchmark:
1033 //
1034 // $ regex-cli bench measure -f boundary-words-holmes -e pikevm > table.csv
1035 //
1036 // And compared them:
1037 //
1038 // $ regex-cli bench diff dfa.csv table.csv
1039 // benchmark engine dfa table
1040 // --------- ------ --- -----
1041 // internal/count/boundary-words-holmes regex/automata/pikevm 18.6 MB/s 12.9 MB/s
1042 //
1043 // Which is a nice improvement.
1044 //
1045 // UPDATE: It turns out that it takes approximately 22ms to build the reverse
1046 // DFA for \w. (And about 3ms for the forward DFA.) It's probably not much in
1047 // the grand scheme things, but that is a significant latency cost. So I'm not
1048 // sure that's a good idea. I then tried using a lazy DFA instead, and that
1049 // eliminated the overhead, but since the lazy DFA requires mutable working
1050 // memory, that requires introducing a 'Cache' for every simultaneous call.
1051 //
1052 // I ended up deciding for now to just keep the "UTF-8 decode and check the
1053 // table." The DFA and lazy DFA approaches are still below, but commented out.
1054 //
1055 // [1]: https://github.com/BurntSushi/ucd-generate/issues/11
1056
1057 /*
1058 /// A module that looks for word codepoints using lazy DFAs.
1059 #[cfg(all(
1060 feature = "unicode-word-boundary",
1061 feature = "syntax",
1062 feature = "unicode-perl",
1063 feature = "hybrid"
1064 ))]
1065 mod is_word_char {
1066 use alloc::vec::Vec;
1067
1068 use crate::{
1069 hybrid::dfa::{Cache, DFA},
1070 nfa::thompson::NFA,
1071 util::{lazy::Lazy, pool::Pool, primitives::StateID},
1072 Anchored, Input,
1073 };
1074
1075 pub(super) fn check() -> Result<(), super::UnicodeWordBoundaryError> {
1076 Ok(())
1077 }
1078
1079 #[cfg_attr(feature = "perf-inline", inline(always))]
1080 pub(super) fn fwd(
1081 haystack: &[u8],
1082 mut at: usize,
1083 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1084 static WORD: Lazy<DFA> = Lazy::new(|| DFA::new(r"\w").unwrap());
1085 static CACHE: Lazy<Pool<Cache>> =
1086 Lazy::new(|| Pool::new(|| WORD.create_cache()));
1087 let dfa = Lazy::get(&WORD);
1088 let mut cache = Lazy::get(&CACHE).get();
1089 let mut sid = dfa
1090 .start_state_forward(
1091 &mut cache,
1092 &Input::new("").anchored(Anchored::Yes),
1093 )
1094 .unwrap();
1095 while at < haystack.len() {
1096 let byte = haystack[at];
1097 sid = dfa.next_state(&mut cache, sid, byte).unwrap();
1098 at += 1;
1099 if sid.is_tagged() {
1100 if sid.is_match() {
1101 return Ok(true);
1102 } else if sid.is_dead() {
1103 return Ok(false);
1104 }
1105 }
1106 }
1107 Ok(dfa.next_eoi_state(&mut cache, sid).unwrap().is_match())
1108 }
1109
1110 #[cfg_attr(feature = "perf-inline", inline(always))]
1111 pub(super) fn rev(
1112 haystack: &[u8],
1113 mut at: usize,
1114 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1115 static WORD: Lazy<DFA> = Lazy::new(|| {
1116 DFA::builder()
1117 .thompson(NFA::config().reverse(true))
1118 .build(r"\w")
1119 .unwrap()
1120 });
1121 static CACHE: Lazy<Pool<Cache>> =
1122 Lazy::new(|| Pool::new(|| WORD.create_cache()));
1123 let dfa = Lazy::get(&WORD);
1124 let mut cache = Lazy::get(&CACHE).get();
1125 let mut sid = dfa
1126 .start_state_reverse(
1127 &mut cache,
1128 &Input::new("").anchored(Anchored::Yes),
1129 )
1130 .unwrap();
1131 while at > 0 {
1132 at -= 1;
1133 let byte = haystack[at];
1134 sid = dfa.next_state(&mut cache, sid, byte).unwrap();
1135 if sid.is_tagged() {
1136 if sid.is_match() {
1137 return Ok(true);
1138 } else if sid.is_dead() {
1139 return Ok(false);
1140 }
1141 }
1142 }
1143 Ok(dfa.next_eoi_state(&mut cache, sid).unwrap().is_match())
1144 }
1145 }
1146 */
1147
1148 /*
1149 /// A module that looks for word codepoints using fully compiled DFAs.
1150 #[cfg(all(
1151 feature = "unicode-word-boundary",
1152 feature = "syntax",
1153 feature = "unicode-perl",
1154 feature = "dfa-build"
1155 ))]
1156 mod is_word_char {
1157 use alloc::vec::Vec;
1158
1159 use crate::{
1160 dfa::{dense::DFA, Automaton, StartKind},
1161 nfa::thompson::NFA,
1162 util::{lazy::Lazy, primitives::StateID},
1163 Anchored, Input,
1164 };
1165
1166 pub(super) fn check() -> Result<(), super::UnicodeWordBoundaryError> {
1167 Ok(())
1168 }
1169
1170 #[cfg_attr(feature = "perf-inline", inline(always))]
1171 pub(super) fn fwd(
1172 haystack: &[u8],
1173 mut at: usize,
1174 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1175 static WORD: Lazy<(DFA<Vec<u32>>, StateID)> = Lazy::new(|| {
1176 let dfa = DFA::builder()
1177 .configure(DFA::config().start_kind(StartKind::Anchored))
1178 .build(r"\w")
1179 .unwrap();
1180 // OK because our regex has no look-around.
1181 let start_id = dfa.universal_start_state(Anchored::Yes).unwrap();
1182 (dfa, start_id)
1183 });
1184 let &(ref dfa, mut sid) = Lazy::get(&WORD);
1185 while at < haystack.len() {
1186 let byte = haystack[at];
1187 sid = dfa.next_state(sid, byte);
1188 at += 1;
1189 if dfa.is_special_state(sid) {
1190 if dfa.is_match_state(sid) {
1191 return Ok(true);
1192 } else if dfa.is_dead_state(sid) {
1193 return Ok(false);
1194 }
1195 }
1196 }
1197 Ok(dfa.is_match_state(dfa.next_eoi_state(sid)))
1198 }
1199
1200 #[cfg_attr(feature = "perf-inline", inline(always))]
1201 pub(super) fn rev(
1202 haystack: &[u8],
1203 mut at: usize,
1204 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1205 static WORD: Lazy<(DFA<Vec<u32>>, StateID)> = Lazy::new(|| {
1206 let dfa = DFA::builder()
1207 .configure(DFA::config().start_kind(StartKind::Anchored))
1208 // From ad hoc measurements, it looks like setting
1209 // shrink==false is slightly faster than shrink==true. I kind
1210 // of feel like this indicates that shrinking is probably a
1211 // failure, although it can help in some cases. Sigh.
1212 .thompson(NFA::config().reverse(true).shrink(false))
1213 .build(r"\w")
1214 .unwrap();
1215 // OK because our regex has no look-around.
1216 let start_id = dfa.universal_start_state(Anchored::Yes).unwrap();
1217 (dfa, start_id)
1218 });
1219 let &(ref dfa, mut sid) = Lazy::get(&WORD);
1220 while at > 0 {
1221 at -= 1;
1222 let byte = haystack[at];
1223 sid = dfa.next_state(sid, byte);
1224 if dfa.is_special_state(sid) {
1225 if dfa.is_match_state(sid) {
1226 return Ok(true);
1227 } else if dfa.is_dead_state(sid) {
1228 return Ok(false);
1229 }
1230 }
1231 }
1232 Ok(dfa.is_match_state(dfa.next_eoi_state(sid)))
1233 }
1234 }
1235 */
1236
1237 /// A module that looks for word codepoints using regex-syntax's data tables.
1238 #[cfg(all(
1239 feature = "unicode-word-boundary",
1240 feature = "syntax",
1241 feature = "unicode-perl",
1242 ))]
1243 mod is_word_char {
1244 use regex_syntax::try_is_word_character;
1245
1246 use crate::util::utf8;
1247
1248 pub(super) fn check() -> Result<(), super::UnicodeWordBoundaryError> {
1249 Ok(())
1250 }
1251
1252 #[cfg_attr(feature = "perf-inline", inline(always))]
1253 pub(super) fn fwd(
1254 haystack: &[u8],
1255 at: usize,
1256 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1257 Ok(match utf8::decode(&haystack[at..]) {
1258 None | Some(Err(_)) => false,
1259 Some(Ok(ch)) => try_is_word_character(ch).expect(
1260 "since unicode-word-boundary, syntax and unicode-perl \
1261 are all enabled, it is expected that \
1262 try_is_word_character succeeds",
1263 ),
1264 })
1265 }
1266
1267 #[cfg_attr(feature = "perf-inline", inline(always))]
1268 pub(super) fn rev(
1269 haystack: &[u8],
1270 at: usize,
1271 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1272 Ok(match utf8::decode_last(&haystack[..at]) {
1273 None | Some(Err(_)) => false,
1274 Some(Ok(ch)) => try_is_word_character(ch).expect(
1275 "since unicode-word-boundary, syntax and unicode-perl \
1276 are all enabled, it is expected that \
1277 try_is_word_character succeeds",
1278 ),
1279 })
1280 }
1281 }
1282
1283 /// A module that looks for word codepoints using regex-automata's data tables
1284 /// (which are only compiled when regex-syntax's tables aren't available).
1285 ///
1286 /// Note that the cfg should match the one in src/util/unicode_data/mod.rs for
1287 /// perl_word.
1288 #[cfg(all(
1289 feature = "unicode-word-boundary",
1290 not(all(feature = "syntax", feature = "unicode-perl")),
1291 ))]
1292 mod is_word_char {
1293 use crate::util::utf8;
1294
1295 pub(super) fn check() -> Result<(), super::UnicodeWordBoundaryError> {
1296 Ok(())
1297 }
1298
1299 #[cfg_attr(feature = "perf-inline", inline(always))]
1300 pub(super) fn fwd(
1301 haystack: &[u8],
1302 at: usize,
1303 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1304 Ok(match utf8::decode(&haystack[at..]) {
1305 None | Some(Err(_)) => false,
1306 Some(Ok(ch)) => is_word_character(ch),
1307 })
1308 }
1309
1310 #[cfg_attr(feature = "perf-inline", inline(always))]
1311 pub(super) fn rev(
1312 haystack: &[u8],
1313 at: usize,
1314 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1315 Ok(match utf8::decode_last(&haystack[..at]) {
1316 None | Some(Err(_)) => false,
1317 Some(Ok(ch)) => is_word_character(ch),
1318 })
1319 }
1320
1321 #[cfg_attr(feature = "perf-inline", inline(always))]
1322 fn is_word_character(c: char) -> bool {
1323 use crate::util::{unicode_data::perl_word::PERL_WORD, utf8};
1324
1325 // MSRV(1.59): Use 'u8::try_from(c)' instead.
1326 if u8::try_from(u32::from(c)).map_or(false, utf8::is_word_byte) {
1327 return true;
1328 }
1329 PERL_WORD
1330 .binary_search_by(|&(start, end)| {
1331 use core::cmp::Ordering;
1332
1333 if start <= c && c <= end {
1334 Ordering::Equal
1335 } else if start > c {
1336 Ordering::Greater
1337 } else {
1338 Ordering::Less
1339 }
1340 })
1341 .is_ok()
1342 }
1343 }
1344
1345 /// A module that always returns an error if Unicode word boundaries are
1346 /// disabled. When this feature is disabled, then regex-automata will not
1347 /// include its own data tables even if regex-syntax is disabled.
1348 #[cfg(not(feature = "unicode-word-boundary"))]
1349 mod is_word_char {
1350 pub(super) fn check() -> Result<(), super::UnicodeWordBoundaryError> {
1351 Err(super::UnicodeWordBoundaryError::new())
1352 }
1353
1354 #[cfg_attr(feature = "perf-inline", inline(always))]
1355 pub(super) fn fwd(
1356 _bytes: &[u8],
1357 _at: usize,
1358 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1359 Err(super::UnicodeWordBoundaryError::new())
1360 }
1361
1362 #[cfg_attr(feature = "perf-inline", inline(always))]
1363 pub(super) fn rev(
1364 _bytes: &[u8],
1365 _at: usize,
1366 ) -> Result<bool, super::UnicodeWordBoundaryError> {
1367 Err(super::UnicodeWordBoundaryError::new())
1368 }
1369 }
1370
1371 #[cfg(test)]
1372 mod tests {
1373 use super::*;
1374
1375 macro_rules! testlook {
1376 ($look:expr, $haystack:expr, $at:expr) => {
1377 LookMatcher::default().matches($look, $haystack.as_bytes(), $at)
1378 };
1379 }
1380
1381 #[test]
1382 fn look_matches_start_line() {
1383 let look = Look::StartLF;
1384
1385 assert!(testlook!(look, "", 0));
1386 assert!(testlook!(look, "\n", 0));
1387 assert!(testlook!(look, "\n", 1));
1388 assert!(testlook!(look, "a", 0));
1389 assert!(testlook!(look, "\na", 1));
1390
1391 assert!(!testlook!(look, "a", 1));
1392 assert!(!testlook!(look, "a\na", 1));
1393 }
1394
1395 #[test]
1396 fn look_matches_end_line() {
1397 let look = Look::EndLF;
1398
1399 assert!(testlook!(look, "", 0));
1400 assert!(testlook!(look, "\n", 1));
1401 assert!(testlook!(look, "\na", 0));
1402 assert!(testlook!(look, "\na", 2));
1403 assert!(testlook!(look, "a\na", 1));
1404
1405 assert!(!testlook!(look, "a", 0));
1406 assert!(!testlook!(look, "\na", 1));
1407 assert!(!testlook!(look, "a\na", 0));
1408 assert!(!testlook!(look, "a\na", 2));
1409 }
1410
1411 #[test]
1412 fn look_matches_start_text() {
1413 let look = Look::Start;
1414
1415 assert!(testlook!(look, "", 0));
1416 assert!(testlook!(look, "\n", 0));
1417 assert!(testlook!(look, "a", 0));
1418
1419 assert!(!testlook!(look, "\n", 1));
1420 assert!(!testlook!(look, "\na", 1));
1421 assert!(!testlook!(look, "a", 1));
1422 assert!(!testlook!(look, "a\na", 1));
1423 }
1424
1425 #[test]
1426 fn look_matches_end_text() {
1427 let look = Look::End;
1428
1429 assert!(testlook!(look, "", 0));
1430 assert!(testlook!(look, "\n", 1));
1431 assert!(testlook!(look, "\na", 2));
1432
1433 assert!(!testlook!(look, "\na", 0));
1434 assert!(!testlook!(look, "a\na", 1));
1435 assert!(!testlook!(look, "a", 0));
1436 assert!(!testlook!(look, "\na", 1));
1437 assert!(!testlook!(look, "a\na", 0));
1438 assert!(!testlook!(look, "a\na", 2));
1439 }
1440
1441 #[test]
1442 #[cfg(all(not(miri), feature = "unicode-word-boundary"))]
1443 fn look_matches_word_unicode() {
1444 let look = Look::WordUnicode;
1445
1446 // \xF0\x9D\x9B\x83 = 𝛃 (in \w)
1447 // \xF0\x90\x86\x80 = 𐆀 (not in \w)
1448
1449 // Simple ASCII word boundaries.
1450 assert!(testlook!(look, "a", 0));
1451 assert!(testlook!(look, "a", 1));
1452 assert!(testlook!(look, "a ", 1));
1453 assert!(testlook!(look, " a ", 1));
1454 assert!(testlook!(look, " a ", 2));
1455
1456 // Unicode word boundaries with a non-ASCII codepoint.
1457 assert!(testlook!(look, "𝛃", 0));
1458 assert!(testlook!(look, "𝛃", 4));
1459 assert!(testlook!(look, "𝛃 ", 4));
1460 assert!(testlook!(look, " 𝛃 ", 1));
1461 assert!(testlook!(look, " 𝛃 ", 5));
1462
1463 // Unicode word boundaries between non-ASCII codepoints.
1464 assert!(testlook!(look, "𝛃𐆀", 0));
1465 assert!(testlook!(look, "𝛃𐆀", 4));
1466
1467 // Non word boundaries for ASCII.
1468 assert!(!testlook!(look, "", 0));
1469 assert!(!testlook!(look, "ab", 1));
1470 assert!(!testlook!(look, "a ", 2));
1471 assert!(!testlook!(look, " a ", 0));
1472 assert!(!testlook!(look, " a ", 3));
1473
1474 // Non word boundaries with a non-ASCII codepoint.
1475 assert!(!testlook!(look, "𝛃b", 4));
1476 assert!(!testlook!(look, "𝛃 ", 5));
1477 assert!(!testlook!(look, " 𝛃 ", 0));
1478 assert!(!testlook!(look, " 𝛃 ", 6));
1479 assert!(!testlook!(look, "𝛃", 1));
1480 assert!(!testlook!(look, "𝛃", 2));
1481 assert!(!testlook!(look, "𝛃", 3));
1482
1483 // Non word boundaries with non-ASCII codepoints.
1484 assert!(!testlook!(look, "𝛃𐆀", 1));
1485 assert!(!testlook!(look, "𝛃𐆀", 2));
1486 assert!(!testlook!(look, "𝛃𐆀", 3));
1487 assert!(!testlook!(look, "𝛃𐆀", 5));
1488 assert!(!testlook!(look, "𝛃𐆀", 6));
1489 assert!(!testlook!(look, "𝛃𐆀", 7));
1490 assert!(!testlook!(look, "𝛃𐆀", 8));
1491 }
1492
1493 #[test]
1494 fn look_matches_word_ascii() {
1495 let look = Look::WordAscii;
1496
1497 // \xF0\x9D\x9B\x83 = 𝛃 (in \w)
1498 // \xF0\x90\x86\x80 = 𐆀 (not in \w)
1499
1500 // Simple ASCII word boundaries.
1501 assert!(testlook!(look, "a", 0));
1502 assert!(testlook!(look, "a", 1));
1503 assert!(testlook!(look, "a ", 1));
1504 assert!(testlook!(look, " a ", 1));
1505 assert!(testlook!(look, " a ", 2));
1506
1507 // Unicode word boundaries with a non-ASCII codepoint. Since this is
1508 // an ASCII word boundary, none of these match.
1509 assert!(!testlook!(look, "𝛃", 0));
1510 assert!(!testlook!(look, "𝛃", 4));
1511 assert!(!testlook!(look, "𝛃 ", 4));
1512 assert!(!testlook!(look, " 𝛃 ", 1));
1513 assert!(!testlook!(look, " 𝛃 ", 5));
1514
1515 // Unicode word boundaries between non-ASCII codepoints. Again, since
1516 // this is an ASCII word boundary, none of these match.
1517 assert!(!testlook!(look, "𝛃𐆀", 0));
1518 assert!(!testlook!(look, "𝛃𐆀", 4));
1519
1520 // Non word boundaries for ASCII.
1521 assert!(!testlook!(look, "", 0));
1522 assert!(!testlook!(look, "ab", 1));
1523 assert!(!testlook!(look, "a ", 2));
1524 assert!(!testlook!(look, " a ", 0));
1525 assert!(!testlook!(look, " a ", 3));
1526
1527 // Non word boundaries with a non-ASCII codepoint.
1528 assert!(testlook!(look, "𝛃b", 4));
1529 assert!(!testlook!(look, "𝛃 ", 5));
1530 assert!(!testlook!(look, " 𝛃 ", 0));
1531 assert!(!testlook!(look, " 𝛃 ", 6));
1532 assert!(!testlook!(look, "𝛃", 1));
1533 assert!(!testlook!(look, "𝛃", 2));
1534 assert!(!testlook!(look, "𝛃", 3));
1535
1536 // Non word boundaries with non-ASCII codepoints.
1537 assert!(!testlook!(look, "𝛃𐆀", 1));
1538 assert!(!testlook!(look, "𝛃𐆀", 2));
1539 assert!(!testlook!(look, "𝛃𐆀", 3));
1540 assert!(!testlook!(look, "𝛃𐆀", 5));
1541 assert!(!testlook!(look, "𝛃𐆀", 6));
1542 assert!(!testlook!(look, "𝛃𐆀", 7));
1543 assert!(!testlook!(look, "𝛃𐆀", 8));
1544 }
1545
1546 #[test]
1547 #[cfg(all(not(miri), feature = "unicode-word-boundary"))]
1548 fn look_matches_word_unicode_negate() {
1549 let look = Look::WordUnicodeNegate;
1550
1551 // \xF0\x9D\x9B\x83 = 𝛃 (in \w)
1552 // \xF0\x90\x86\x80 = 𐆀 (not in \w)
1553
1554 // Simple ASCII word boundaries.
1555 assert!(!testlook!(look, "a", 0));
1556 assert!(!testlook!(look, "a", 1));
1557 assert!(!testlook!(look, "a ", 1));
1558 assert!(!testlook!(look, " a ", 1));
1559 assert!(!testlook!(look, " a ", 2));
1560
1561 // Unicode word boundaries with a non-ASCII codepoint.
1562 assert!(!testlook!(look, "𝛃", 0));
1563 assert!(!testlook!(look, "𝛃", 4));
1564 assert!(!testlook!(look, "𝛃 ", 4));
1565 assert!(!testlook!(look, " 𝛃 ", 1));
1566 assert!(!testlook!(look, " 𝛃 ", 5));
1567
1568 // Unicode word boundaries between non-ASCII codepoints.
1569 assert!(!testlook!(look, "𝛃𐆀", 0));
1570 assert!(!testlook!(look, "𝛃𐆀", 4));
1571
1572 // Non word boundaries for ASCII.
1573 assert!(testlook!(look, "", 0));
1574 assert!(testlook!(look, "ab", 1));
1575 assert!(testlook!(look, "a ", 2));
1576 assert!(testlook!(look, " a ", 0));
1577 assert!(testlook!(look, " a ", 3));
1578
1579 // Non word boundaries with a non-ASCII codepoint.
1580 assert!(testlook!(look, "𝛃b", 4));
1581 assert!(testlook!(look, "𝛃 ", 5));
1582 assert!(testlook!(look, " 𝛃 ", 0));
1583 assert!(testlook!(look, " 𝛃 ", 6));
1584 // These don't match because they could otherwise return an offset that
1585 // splits the UTF-8 encoding of a codepoint.
1586 assert!(!testlook!(look, "𝛃", 1));
1587 assert!(!testlook!(look, "𝛃", 2));
1588 assert!(!testlook!(look, "𝛃", 3));
1589
1590 // Non word boundaries with non-ASCII codepoints. These also don't
1591 // match because they could otherwise return an offset that splits the
1592 // UTF-8 encoding of a codepoint.
1593 assert!(!testlook!(look, "𝛃𐆀", 1));
1594 assert!(!testlook!(look, "𝛃𐆀", 2));
1595 assert!(!testlook!(look, "𝛃𐆀", 3));
1596 assert!(!testlook!(look, "𝛃𐆀", 5));
1597 assert!(!testlook!(look, "𝛃𐆀", 6));
1598 assert!(!testlook!(look, "𝛃𐆀", 7));
1599 // But this one does, since 𐆀 isn't a word codepoint, and 8 is the end
1600 // of the haystack. So the "end" of the haystack isn't a word and 𐆀
1601 // isn't a word, thus, \B matches.
1602 assert!(testlook!(look, "𝛃𐆀", 8));
1603 }
1604
1605 #[test]
1606 fn look_matches_word_ascii_negate() {
1607 let look = Look::WordAsciiNegate;
1608
1609 // \xF0\x9D\x9B\x83 = 𝛃 (in \w)
1610 // \xF0\x90\x86\x80 = 𐆀 (not in \w)
1611
1612 // Simple ASCII word boundaries.
1613 assert!(!testlook!(look, "a", 0));
1614 assert!(!testlook!(look, "a", 1));
1615 assert!(!testlook!(look, "a ", 1));
1616 assert!(!testlook!(look, " a ", 1));
1617 assert!(!testlook!(look, " a ", 2));
1618
1619 // Unicode word boundaries with a non-ASCII codepoint. Since this is
1620 // an ASCII word boundary, none of these match.
1621 assert!(testlook!(look, "𝛃", 0));
1622 assert!(testlook!(look, "𝛃", 4));
1623 assert!(testlook!(look, "𝛃 ", 4));
1624 assert!(testlook!(look, " 𝛃 ", 1));
1625 assert!(testlook!(look, " 𝛃 ", 5));
1626
1627 // Unicode word boundaries between non-ASCII codepoints. Again, since
1628 // this is an ASCII word boundary, none of these match.
1629 assert!(testlook!(look, "𝛃𐆀", 0));
1630 assert!(testlook!(look, "𝛃𐆀", 4));
1631
1632 // Non word boundaries for ASCII.
1633 assert!(testlook!(look, "", 0));
1634 assert!(testlook!(look, "ab", 1));
1635 assert!(testlook!(look, "a ", 2));
1636 assert!(testlook!(look, " a ", 0));
1637 assert!(testlook!(look, " a ", 3));
1638
1639 // Non word boundaries with a non-ASCII codepoint.
1640 assert!(!testlook!(look, "𝛃b", 4));
1641 assert!(testlook!(look, "𝛃 ", 5));
1642 assert!(testlook!(look, " 𝛃 ", 0));
1643 assert!(testlook!(look, " 𝛃 ", 6));
1644 assert!(testlook!(look, "𝛃", 1));
1645 assert!(testlook!(look, "𝛃", 2));
1646 assert!(testlook!(look, "𝛃", 3));
1647
1648 // Non word boundaries with non-ASCII codepoints.
1649 assert!(testlook!(look, "𝛃𐆀", 1));
1650 assert!(testlook!(look, "𝛃𐆀", 2));
1651 assert!(testlook!(look, "𝛃𐆀", 3));
1652 assert!(testlook!(look, "𝛃𐆀", 5));
1653 assert!(testlook!(look, "𝛃𐆀", 6));
1654 assert!(testlook!(look, "𝛃𐆀", 7));
1655 assert!(testlook!(look, "𝛃𐆀", 8));
1656 }
1657
1658 #[test]
1659 fn look_set() {
1660 let mut f = LookSet::default();
1661 assert!(!f.contains(Look::Start));
1662 assert!(!f.contains(Look::End));
1663 assert!(!f.contains(Look::StartLF));
1664 assert!(!f.contains(Look::EndLF));
1665 assert!(!f.contains(Look::WordUnicode));
1666 assert!(!f.contains(Look::WordUnicodeNegate));
1667 assert!(!f.contains(Look::WordAscii));
1668 assert!(!f.contains(Look::WordAsciiNegate));
1669
1670 f = f.insert(Look::Start);
1671 assert!(f.contains(Look::Start));
1672 f = f.remove(Look::Start);
1673 assert!(!f.contains(Look::Start));
1674
1675 f = f.insert(Look::End);
1676 assert!(f.contains(Look::End));
1677 f = f.remove(Look::End);
1678 assert!(!f.contains(Look::End));
1679
1680 f = f.insert(Look::StartLF);
1681 assert!(f.contains(Look::StartLF));
1682 f = f.remove(Look::StartLF);
1683 assert!(!f.contains(Look::StartLF));
1684
1685 f = f.insert(Look::EndLF);
1686 assert!(f.contains(Look::EndLF));
1687 f = f.remove(Look::EndLF);
1688 assert!(!f.contains(Look::EndLF));
1689
1690 f = f.insert(Look::StartCRLF);
1691 assert!(f.contains(Look::StartCRLF));
1692 f = f.remove(Look::StartCRLF);
1693 assert!(!f.contains(Look::StartCRLF));
1694
1695 f = f.insert(Look::EndCRLF);
1696 assert!(f.contains(Look::EndCRLF));
1697 f = f.remove(Look::EndCRLF);
1698 assert!(!f.contains(Look::EndCRLF));
1699
1700 f = f.insert(Look::WordUnicode);
1701 assert!(f.contains(Look::WordUnicode));
1702 f = f.remove(Look::WordUnicode);
1703 assert!(!f.contains(Look::WordUnicode));
1704
1705 f = f.insert(Look::WordUnicodeNegate);
1706 assert!(f.contains(Look::WordUnicodeNegate));
1707 f = f.remove(Look::WordUnicodeNegate);
1708 assert!(!f.contains(Look::WordUnicodeNegate));
1709
1710 f = f.insert(Look::WordAscii);
1711 assert!(f.contains(Look::WordAscii));
1712 f = f.remove(Look::WordAscii);
1713 assert!(!f.contains(Look::WordAscii));
1714
1715 f = f.insert(Look::WordAsciiNegate);
1716 assert!(f.contains(Look::WordAsciiNegate));
1717 f = f.remove(Look::WordAsciiNegate);
1718 assert!(!f.contains(Look::WordAsciiNegate));
1719 }
1720
1721 #[test]
1722 fn look_set_iter() {
1723 let set = LookSet::empty();
1724 assert_eq!(0, set.iter().count());
1725
1726 let set = LookSet::full();
1727 assert_eq!(10, set.iter().count());
1728
1729 let set =
1730 LookSet::empty().insert(Look::StartLF).insert(Look::WordUnicode);
1731 assert_eq!(2, set.iter().count());
1732
1733 let set = LookSet::empty().insert(Look::StartLF);
1734 assert_eq!(1, set.iter().count());
1735
1736 let set = LookSet::empty().insert(Look::WordAsciiNegate);
1737 assert_eq!(1, set.iter().count());
1738 }
1739
1740 #[test]
1741 #[cfg(feature = "alloc")]
1742 fn look_set_debug() {
1743 let res = alloc::format!("{:?}", LookSet::empty());
1744 assert_eq!("∅", res);
1745 let res = alloc::format!("{:?}", LookSet::full());
1746 assert_eq!("Az^$rRbB𝛃𝚩", res);
1747 }
1748 }