Debian Codegraph @

third_party/rust/regex-syntax/src/hir/mod.rs

raw
1 /*!
2 Defines a high-level intermediate (HIR) representation for regular expressions.
3
4 The HIR is represented by the [`Hir`] type, and it principally constructed via
5 [translation](translate) from an [`Ast`](crate::ast::Ast). Alternatively, users
6 may use the smart constructors defined on `Hir` to build their own by hand. The
7 smart constructors simultaneously simplify and "optimize" the HIR, and are also
8 the same routines used by translation.
9
10 Most regex engines only have an HIR like this, and usually construct it
11 directly from the concrete syntax. This crate however first parses the
12 concrete syntax into an `Ast`, and only then creates the HIR from the `Ast`,
13 as mentioned above. It's done this way to facilitate better error reporting,
14 and to have a structured representation of a regex that faithfully represents
15 its concrete syntax. Namely, while an `Hir` value can be converted back to an
16 equivalent regex pattern string, it is unlikely to look like the original due
17 to its simplified structure.
18 */
19
20 use core::{char, cmp};
21
22 use alloc::{
23 boxed::Box,
24 format,
25 string::{String, ToString},
26 vec,
27 vec::Vec,
28 };
29
30 use crate::{
31 ast::Span,
32 hir::interval::{Interval, IntervalSet, IntervalSetIter},
33 unicode,
34 };
35
36 pub use crate::{
37 hir::visitor::{visit, Visitor},
38 unicode::CaseFoldError,
39 };
40
41 mod interval;
42 pub mod literal;
43 pub mod print;
44 pub mod translate;
45 mod visitor;
46
47 /// An error that can occur while translating an `Ast` to a `Hir`.
48 #[derive(Clone, Debug, Eq, PartialEq)]
49 pub struct Error {
50 /// The kind of error.
51 kind: ErrorKind,
52 /// The original pattern that the translator's Ast was parsed from. Every
53 /// span in an error is a valid range into this string.
54 pattern: String,
55 /// The span of this error, derived from the Ast given to the translator.
56 span: Span,
57 }
58
59 impl Error {
60 /// Return the type of this error.
61 pub fn kind(&self) -> &ErrorKind {
62 &self.kind
63 }
64
65 /// The original pattern string in which this error occurred.
66 ///
67 /// Every span reported by this error is reported in terms of this string.
68 pub fn pattern(&self) -> &str {
69 &self.pattern
70 }
71
72 /// Return the span at which this error occurred.
73 pub fn span(&self) -> &Span {
74 &self.span
75 }
76 }
77
78 /// The type of an error that occurred while building an `Hir`.
79 ///
80 /// This error type is marked as `non_exhaustive`. This means that adding a
81 /// new variant is not considered a breaking change.
82 #[non_exhaustive]
83 #[derive(Clone, Debug, Eq, PartialEq)]
84 pub enum ErrorKind {
85 /// This error occurs when a Unicode feature is used when Unicode
86 /// support is disabled. For example `(?-u:\pL)` would trigger this error.
87 UnicodeNotAllowed,
88 /// This error occurs when translating a pattern that could match a byte
89 /// sequence that isn't UTF-8 and `utf8` was enabled.
90 InvalidUtf8,
91 /// This error occurs when one uses a non-ASCII byte for a line terminator,
92 /// but where Unicode mode is enabled and UTF-8 mode is disabled.
93 InvalidLineTerminator,
94 /// This occurs when an unrecognized Unicode property name could not
95 /// be found.
96 UnicodePropertyNotFound,
97 /// This occurs when an unrecognized Unicode property value could not
98 /// be found.
99 UnicodePropertyValueNotFound,
100 /// This occurs when a Unicode-aware Perl character class (`\w`, `\s` or
101 /// `\d`) could not be found. This can occur when the `unicode-perl`
102 /// crate feature is not enabled.
103 UnicodePerlClassNotFound,
104 /// This occurs when the Unicode simple case mapping tables are not
105 /// available, and the regular expression required Unicode aware case
106 /// insensitivity.
107 UnicodeCaseUnavailable,
108 }
109
110 #[cfg(feature = "std")]
111 impl std::error::Error for Error {}
112
113 impl core::fmt::Display for Error {
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 crate::error::Formatter::from(self).fmt(f)
116 }
117 }
118
119 impl core::fmt::Display for ErrorKind {
120 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
121 use self::ErrorKind::*;
122
123 let msg = match *self {
124 UnicodeNotAllowed => "Unicode not allowed here",
125 InvalidUtf8 => "pattern can match invalid UTF-8",
126 InvalidLineTerminator => "invalid line terminator, must be ASCII",
127 UnicodePropertyNotFound => "Unicode property not found",
128 UnicodePropertyValueNotFound => "Unicode property value not found",
129 UnicodePerlClassNotFound => {
130 "Unicode-aware Perl class not found \
131 (make sure the unicode-perl feature is enabled)"
132 }
133 UnicodeCaseUnavailable => {
134 "Unicode-aware case insensitivity matching is not available \
135 (make sure the unicode-case feature is enabled)"
136 }
137 };
138 f.write_str(msg)
139 }
140 }
141
142 /// A high-level intermediate representation (HIR) for a regular expression.
143 ///
144 /// An HIR value is a combination of a [`HirKind`] and a set of [`Properties`].
145 /// An `HirKind` indicates what kind of regular expression it is (a literal,
146 /// a repetition, a look-around assertion, etc.), where as a `Properties`
147 /// describes various facts about the regular expression. For example, whether
148 /// it matches UTF-8 or if it matches the empty string.
149 ///
150 /// The HIR of a regular expression represents an intermediate step between
151 /// its abstract syntax (a structured description of the concrete syntax) and
152 /// an actual regex matcher. The purpose of HIR is to make regular expressions
153 /// easier to analyze. In particular, the AST is much more complex than the
154 /// HIR. For example, while an AST supports arbitrarily nested character
155 /// classes, the HIR will flatten all nested classes into a single set. The HIR
156 /// will also "compile away" every flag present in the concrete syntax. For
157 /// example, users of HIR expressions never need to worry about case folding;
158 /// it is handled automatically by the translator (e.g., by translating
159 /// `(?i:A)` to `[aA]`).
160 ///
161 /// The specific type of an HIR expression can be accessed via its `kind`
162 /// or `into_kind` methods. This extra level of indirection exists for two
163 /// reasons:
164 ///
165 /// 1. Construction of an HIR expression *must* use the constructor methods on
166 /// this `Hir` type instead of building the `HirKind` values directly. This
167 /// permits construction to enforce invariants like "concatenations always
168 /// consist of two or more sub-expressions."
169 /// 2. Every HIR expression contains attributes that are defined inductively,
170 /// and can be computed cheaply during the construction process. For example,
171 /// one such attribute is whether the expression must match at the beginning of
172 /// the haystack.
173 ///
174 /// In particular, if you have an `HirKind` value, then there is intentionally
175 /// no way to build an `Hir` value from it. You instead need to do case
176 /// analysis on the `HirKind` value and build the `Hir` value using its smart
177 /// constructors.
178 ///
179 /// # UTF-8
180 ///
181 /// If the HIR was produced by a translator with
182 /// [`TranslatorBuilder::utf8`](translate::TranslatorBuilder::utf8) enabled,
183 /// then the HIR is guaranteed to match UTF-8 exclusively for all non-empty
184 /// matches.
185 ///
186 /// For empty matches, those can occur at any position. It is the
187 /// responsibility of the regex engine to determine whether empty matches are
188 /// permitted between the code units of a single codepoint.
189 ///
190 /// # Stack space
191 ///
192 /// This type defines its own destructor that uses constant stack space and
193 /// heap space proportional to the size of the HIR.
194 ///
195 /// Also, an `Hir`'s `fmt::Display` implementation prints an HIR as a regular
196 /// expression pattern string, and uses constant stack space and heap space
197 /// proportional to the size of the `Hir`. The regex it prints is guaranteed to
198 /// be _semantically_ equivalent to the original concrete syntax, but it may
199 /// look very different. (And potentially not practically readable by a human.)
200 ///
201 /// An `Hir`'s `fmt::Debug` implementation currently does not use constant
202 /// stack space. The implementation will also suppress some details (such as
203 /// the `Properties` inlined into every `Hir` value to make it less noisy).
204 #[derive(Clone, Eq, PartialEq)]
205 pub struct Hir {
206 /// The underlying HIR kind.
207 kind: HirKind,
208 /// Analysis info about this HIR, computed during construction.
209 props: Properties,
210 }
211
212 /// Methods for accessing the underlying `HirKind` and `Properties`.
213 impl Hir {
214 /// Returns a reference to the underlying HIR kind.
215 pub fn kind(&self) -> &HirKind {
216 &self.kind
217 }
218
219 /// Consumes ownership of this HIR expression and returns its underlying
220 /// `HirKind`.
221 pub fn into_kind(mut self) -> HirKind {
222 core::mem::replace(&mut self.kind, HirKind::Empty)
223 }
224
225 /// Returns the properties computed for this `Hir`.
226 pub fn properties(&self) -> &Properties {
227 &self.props
228 }
229
230 /// Splits this HIR into its constituent parts.
231 ///
232 /// This is useful because `let Hir { kind, props } = hir;` does not work
233 /// because of `Hir`'s custom `Drop` implementation.
234 fn into_parts(mut self) -> (HirKind, Properties) {
235 (
236 core::mem::replace(&mut self.kind, HirKind::Empty),
237 core::mem::replace(&mut self.props, Properties::empty()),
238 )
239 }
240 }
241
242 /// Smart constructors for HIR values.
243 ///
244 /// These constructors are called "smart" because they do inductive work or
245 /// simplifications. For example, calling `Hir::repetition` with a repetition
246 /// like `a{0}` will actually return a `Hir` with a `HirKind::Empty` kind
247 /// since it is equivalent to an empty regex. Another example is calling
248 /// `Hir::concat(vec![expr])`. Instead of getting a `HirKind::Concat`, you'll
249 /// just get back the original `expr` since it's precisely equivalent.
250 ///
251 /// Smart constructors enable maintaining invariants about the HIR data type
252 /// while also simulanteously keeping the representation as simple as possible.
253 impl Hir {
254 /// Returns an empty HIR expression.
255 ///
256 /// An empty HIR expression always matches, including the empty string.
257 #[inline]
258 pub fn empty() -> Hir {
259 let props = Properties::empty();
260 Hir { kind: HirKind::Empty, props }
261 }
262
263 /// Returns an HIR expression that can never match anything. That is,
264 /// the size of the set of strings in the language described by the HIR
265 /// returned is `0`.
266 ///
267 /// This is distinct from [`Hir::empty`] in that the empty string matches
268 /// the HIR returned by `Hir::empty`. That is, the set of strings in the
269 /// language describe described by `Hir::empty` is non-empty.
270 ///
271 /// Note that currently, the HIR returned uses an empty character class to
272 /// indicate that nothing can match. An equivalent expression that cannot
273 /// match is an empty alternation, but all such "fail" expressions are
274 /// normalized (via smart constructors) to empty character classes. This is
275 /// because empty character classes can be spelled in the concrete syntax
276 /// of a regex (e.g., `\P{any}` or `(?-u:[^\x00-\xFF])` or `[a&&b]`), but
277 /// empty alternations cannot.
278 #[inline]
279 pub fn fail() -> Hir {
280 let class = Class::Bytes(ClassBytes::empty());
281 let props = Properties::class(&class);
282 // We can't just call Hir::class here because it defers to Hir::fail
283 // in order to canonicalize the Hir value used to represent "cannot
284 // match."
285 Hir { kind: HirKind::Class(class), props }
286 }
287
288 /// Creates a literal HIR expression.
289 ///
290 /// This accepts anything that can be converted into a `Box<[u8]>`.
291 ///
292 /// Note that there is no mechanism for storing a `char` or a `Box<str>`
293 /// in an HIR. Everything is "just bytes." Whether a `Literal` (or
294 /// any HIR node) matches valid UTF-8 exclusively can be queried via
295 /// [`Properties::is_utf8`].
296 ///
297 /// # Example
298 ///
299 /// This example shows that concatenations of `Literal` HIR values will
300 /// automatically get flattened and combined together. So for example, even
301 /// if you concat multiple `Literal` values that are themselves not valid
302 /// UTF-8, they might add up to valid UTF-8. This also demonstrates just
303 /// how "smart" Hir's smart constructors are.
304 ///
305 /// ```
306 /// use regex_syntax::hir::{Hir, HirKind, Literal};
307 ///
308 /// let literals = vec![
309 /// Hir::literal([0xE2]),
310 /// Hir::literal([0x98]),
311 /// Hir::literal([0x83]),
312 /// ];
313 /// // Each literal, on its own, is invalid UTF-8.
314 /// assert!(literals.iter().all(|hir| !hir.properties().is_utf8()));
315 ///
316 /// let concat = Hir::concat(literals);
317 /// // But the concatenation is valid UTF-8!
318 /// assert!(concat.properties().is_utf8());
319 ///
320 /// // And also notice that the literals have been concatenated into a
321 /// // single `Literal`, to the point where there is no explicit `Concat`!
322 /// let expected = HirKind::Literal(Literal(Box::from("☃".as_bytes())));
323 /// assert_eq!(&expected, concat.kind());
324 /// ```
325 #[inline]
326 pub fn literal<B: Into<Box<[u8]>>>(lit: B) -> Hir {
327 let bytes = lit.into();
328 if bytes.is_empty() {
329 return Hir::empty();
330 }
331
332 let lit = Literal(bytes);
333 let props = Properties::literal(&lit);
334 Hir { kind: HirKind::Literal(lit), props }
335 }
336
337 /// Creates a class HIR expression. The class may either be defined over
338 /// ranges of Unicode codepoints or ranges of raw byte values.
339 ///
340 /// Note that an empty class is permitted. An empty class is equivalent to
341 /// `Hir::fail()`.
342 #[inline]
343 pub fn class(class: Class) -> Hir {
344 if class.is_empty() {
345 return Hir::fail();
346 } else if let Some(bytes) = class.literal() {
347 return Hir::literal(bytes);
348 }
349 let props = Properties::class(&class);
350 Hir { kind: HirKind::Class(class), props }
351 }
352
353 /// Creates a look-around assertion HIR expression.
354 #[inline]
355 pub fn look(look: Look) -> Hir {
356 let props = Properties::look(look);
357 Hir { kind: HirKind::Look(look), props }
358 }
359
360 /// Creates a repetition HIR expression.
361 #[inline]
362 pub fn repetition(mut rep: Repetition) -> Hir {
363 // If the sub-expression of a repetition can only match the empty
364 // string, then we force its maximum to be at most 1.
365 if rep.sub.properties().maximum_len() == Some(0) {
366 rep.min = cmp::min(rep.min, 1);
367 rep.max = rep.max.map(|n| cmp::min(n, 1)).or(Some(1));
368 }
369 // The regex 'a{0}' is always equivalent to the empty regex. This is
370 // true even when 'a' is an expression that never matches anything
371 // (like '\P{any}').
372 //
373 // Additionally, the regex 'a{1}' is always equivalent to 'a'.
374 if rep.min == 0 && rep.max == Some(0) {
375 return Hir::empty();
376 } else if rep.min == 1 && rep.max == Some(1) {
377 return *rep.sub;
378 }
379 let props = Properties::repetition(&rep);
380 Hir { kind: HirKind::Repetition(rep), props }
381 }
382
383 /// Creates a capture HIR expression.
384 ///
385 /// Note that there is no explicit HIR value for a non-capturing group.
386 /// Since a non-capturing group only exists to override precedence in the
387 /// concrete syntax and since an HIR already does its own grouping based on
388 /// what is parsed, there is no need to explicitly represent non-capturing
389 /// groups in the HIR.
390 #[inline]
391 pub fn capture(capture: Capture) -> Hir {
392 let props = Properties::capture(&capture);
393 Hir { kind: HirKind::Capture(capture), props }
394 }
395
396 /// Returns the concatenation of the given expressions.
397 ///
398 /// This attempts to flatten and simplify the concatenation as appropriate.
399 ///
400 /// # Example
401 ///
402 /// This shows a simple example of basic flattening of both concatenations
403 /// and literals.
404 ///
405 /// ```
406 /// use regex_syntax::hir::Hir;
407 ///
408 /// let hir = Hir::concat(vec![
409 /// Hir::concat(vec![
410 /// Hir::literal([b'a']),
411 /// Hir::literal([b'b']),
412 /// Hir::literal([b'c']),
413 /// ]),
414 /// Hir::concat(vec![
415 /// Hir::literal([b'x']),
416 /// Hir::literal([b'y']),
417 /// Hir::literal([b'z']),
418 /// ]),
419 /// ]);
420 /// let expected = Hir::literal("abcxyz".as_bytes());
421 /// assert_eq!(expected, hir);
422 /// ```
423 pub fn concat(subs: Vec<Hir>) -> Hir {
424 // We rebuild the concatenation by simplifying it. Would be nice to do
425 // it in place, but that seems a little tricky?
426 let mut new = vec![];
427 // This gobbles up any adjacent literals in a concatenation and smushes
428 // them together. Basically, when we see a literal, we add its bytes
429 // to 'prior_lit', and whenever we see anything else, we first take
430 // any bytes in 'prior_lit' and add it to the 'new' concatenation.
431 let mut prior_lit: Option<Vec<u8>> = None;
432 for sub in subs {
433 let (kind, props) = sub.into_parts();
434 match kind {
435 HirKind::Literal(Literal(bytes)) => {
436 if let Some(ref mut prior_bytes) = prior_lit {
437 prior_bytes.extend_from_slice(&bytes);
438 } else {
439 prior_lit = Some(bytes.to_vec());
440 }
441 }
442 // We also flatten concats that are direct children of another
443 // concat. We only need to do this one level deep since
444 // Hir::concat is the only way to build concatenations, and so
445 // flattening happens inductively.
446 HirKind::Concat(subs2) => {
447 for sub2 in subs2 {
448 let (kind2, props2) = sub2.into_parts();
449 match kind2 {
450 HirKind::Literal(Literal(bytes)) => {
451 if let Some(ref mut prior_bytes) = prior_lit {
452 prior_bytes.extend_from_slice(&bytes);
453 } else {
454 prior_lit = Some(bytes.to_vec());
455 }
456 }
457 kind2 => {
458 if let Some(prior_bytes) = prior_lit.take() {
459 new.push(Hir::literal(prior_bytes));
460 }
461 new.push(Hir { kind: kind2, props: props2 });
462 }
463 }
464 }
465 }
466 // We can just skip empty HIRs.
467 HirKind::Empty => {}
468 kind => {
469 if let Some(prior_bytes) = prior_lit.take() {
470 new.push(Hir::literal(prior_bytes));
471 }
472 new.push(Hir { kind, props });
473 }
474 }
475 }
476 if let Some(prior_bytes) = prior_lit.take() {
477 new.push(Hir::literal(prior_bytes));
478 }
479 if new.is_empty() {
480 return Hir::empty();
481 } else if new.len() == 1 {
482 return new.pop().unwrap();
483 }
484 let props = Properties::concat(&new);
485 Hir { kind: HirKind::Concat(new), props }
486 }
487
488 /// Returns the alternation of the given expressions.
489 ///
490 /// This flattens and simplifies the alternation as appropriate. This may
491 /// include factoring out common prefixes or even rewriting the alternation
492 /// as a character class.
493 ///
494 /// Note that an empty alternation is equivalent to `Hir::fail()`. (It
495 /// is not possible for one to write an empty alternation, or even an
496 /// alternation with a single sub-expression, in the concrete syntax of a
497 /// regex.)
498 ///
499 /// # Example
500 ///
501 /// This is a simple example showing how an alternation might get
502 /// simplified.
503 ///
504 /// ```
505 /// use regex_syntax::hir::{Hir, Class, ClassUnicode, ClassUnicodeRange};
506 ///
507 /// let hir = Hir::alternation(vec![
508 /// Hir::literal([b'a']),
509 /// Hir::literal([b'b']),
510 /// Hir::literal([b'c']),
511 /// Hir::literal([b'd']),
512 /// Hir::literal([b'e']),
513 /// Hir::literal([b'f']),
514 /// ]);
515 /// let expected = Hir::class(Class::Unicode(ClassUnicode::new([
516 /// ClassUnicodeRange::new('a', 'f'),
517 /// ])));
518 /// assert_eq!(expected, hir);
519 /// ```
520 ///
521 /// And another example showing how common prefixes might get factored
522 /// out.
523 ///
524 /// ```
525 /// use regex_syntax::hir::{Hir, Class, ClassUnicode, ClassUnicodeRange};
526 ///
527 /// let hir = Hir::alternation(vec![
528 /// Hir::concat(vec![
529 /// Hir::literal("abc".as_bytes()),
530 /// Hir::class(Class::Unicode(ClassUnicode::new([
531 /// ClassUnicodeRange::new('A', 'Z'),
532 /// ]))),
533 /// ]),
534 /// Hir::concat(vec![
535 /// Hir::literal("abc".as_bytes()),
536 /// Hir::class(Class::Unicode(ClassUnicode::new([
537 /// ClassUnicodeRange::new('a', 'z'),
538 /// ]))),
539 /// ]),
540 /// ]);
541 /// let expected = Hir::concat(vec![
542 /// Hir::literal("abc".as_bytes()),
543 /// Hir::alternation(vec![
544 /// Hir::class(Class::Unicode(ClassUnicode::new([
545 /// ClassUnicodeRange::new('A', 'Z'),
546 /// ]))),
547 /// Hir::class(Class::Unicode(ClassUnicode::new([
548 /// ClassUnicodeRange::new('a', 'z'),
549 /// ]))),
550 /// ]),
551 /// ]);
552 /// assert_eq!(expected, hir);
553 /// ```
554 ///
555 /// Note that these sorts of simplifications are not guaranteed.
556 pub fn alternation(subs: Vec<Hir>) -> Hir {
557 // We rebuild the alternation by simplifying it. We proceed similarly
558 // as the concatenation case. But in this case, there's no literal
559 // simplification happening. We're just flattening alternations.
560 let mut new = Vec::with_capacity(subs.len());
561 for sub in subs {
562 let (kind, props) = sub.into_parts();
563 match kind {
564 HirKind::Alternation(subs2) => {
565 new.extend(subs2);
566 }
567 kind => {
568 new.push(Hir { kind, props });
569 }
570 }
571 }
572 if new.is_empty() {
573 return Hir::fail();
574 } else if new.len() == 1 {
575 return new.pop().unwrap();
576 }
577 // Now that it's completely flattened, look for the special case of
578 // 'char1|char2|...|charN' and collapse that into a class. Note that
579 // we look for 'char' first and then bytes. The issue here is that if
580 // we find both non-ASCII codepoints and non-ASCII singleton bytes,
581 // then it isn't actually possible to smush them into a single class.
582 // (Because classes are either "all codepoints" or "all bytes." You
583 // can have a class that both matches non-ASCII but valid UTF-8 and
584 // invalid UTF-8.) So we look for all chars and then all bytes, and
585 // don't handle anything else.
586 if let Some(singletons) = singleton_chars(&new) {
587 let it = singletons
588 .into_iter()
589 .map(|ch| ClassUnicodeRange { start: ch, end: ch });
590 return Hir::class(Class::Unicode(ClassUnicode::new(it)));
591 }
592 if let Some(singletons) = singleton_bytes(&new) {
593 let it = singletons
594 .into_iter()
595 .map(|b| ClassBytesRange { start: b, end: b });
596 return Hir::class(Class::Bytes(ClassBytes::new(it)));
597 }
598 // Similar to singleton chars, we can also look for alternations of
599 // classes. Those can be smushed into a single class.
600 if let Some(cls) = class_chars(&new) {
601 return Hir::class(cls);
602 }
603 if let Some(cls) = class_bytes(&new) {
604 return Hir::class(cls);
605 }
606 // Factor out a common prefix if we can, which might potentially
607 // simplify the expression and unlock other optimizations downstream.
608 // It also might generally make NFA matching and DFA construction
609 // faster by reducing the scope of branching in the regex.
610 new = match lift_common_prefix(new) {
611 Ok(hir) => return hir,
612 Err(unchanged) => unchanged,
613 };
614 let props = Properties::alternation(&new);
615 Hir { kind: HirKind::Alternation(new), props }
616 }
617
618 /// Returns an HIR expression for `.`.
619 ///
620 /// * [`Dot::AnyChar`] maps to `(?su-R:.)`.
621 /// * [`Dot::AnyByte`] maps to `(?s-Ru:.)`.
622 /// * [`Dot::AnyCharExceptLF`] maps to `(?u-Rs:.)`.
623 /// * [`Dot::AnyCharExceptCRLF`] maps to `(?Ru-s:.)`.
624 /// * [`Dot::AnyByteExceptLF`] maps to `(?-Rsu:.)`.
625 /// * [`Dot::AnyByteExceptCRLF`] maps to `(?R-su:.)`.
626 ///
627 /// # Example
628 ///
629 /// Note that this is a convenience routine for constructing the correct
630 /// character class based on the value of `Dot`. There is no explicit "dot"
631 /// HIR value. It is just an abbreviation for a common character class.
632 ///
633 /// ```
634 /// use regex_syntax::hir::{Hir, Dot, Class, ClassBytes, ClassBytesRange};
635 ///
636 /// let hir = Hir::dot(Dot::AnyByte);
637 /// let expected = Hir::class(Class::Bytes(ClassBytes::new([
638 /// ClassBytesRange::new(0x00, 0xFF),
639 /// ])));
640 /// assert_eq!(expected, hir);
641 /// ```
642 #[inline]
643 pub fn dot(dot: Dot) -> Hir {
644 match dot {
645 Dot::AnyChar => {
646 let mut cls = ClassUnicode::empty();
647 cls.push(ClassUnicodeRange::new('\0', '\u{10FFFF}'));
648 Hir::class(Class::Unicode(cls))
649 }
650 Dot::AnyByte => {
651 let mut cls = ClassBytes::empty();
652 cls.push(ClassBytesRange::new(b'\0', b'\xFF'));
653 Hir::class(Class::Bytes(cls))
654 }
655 Dot::AnyCharExcept(ch) => {
656 let mut cls =
657 ClassUnicode::new([ClassUnicodeRange::new(ch, ch)]);
658 cls.negate();
659 Hir::class(Class::Unicode(cls))
660 }
661 Dot::AnyCharExceptLF => {
662 let mut cls = ClassUnicode::empty();
663 cls.push(ClassUnicodeRange::new('\0', '\x09'));
664 cls.push(ClassUnicodeRange::new('\x0B', '\u{10FFFF}'));
665 Hir::class(Class::Unicode(cls))
666 }
667 Dot::AnyCharExceptCRLF => {
668 let mut cls = ClassUnicode::empty();
669 cls.push(ClassUnicodeRange::new('\0', '\x09'));
670 cls.push(ClassUnicodeRange::new('\x0B', '\x0C'));
671 cls.push(ClassUnicodeRange::new('\x0E', '\u{10FFFF}'));
672 Hir::class(Class::Unicode(cls))
673 }
674 Dot::AnyByteExcept(byte) => {
675 let mut cls =
676 ClassBytes::new([ClassBytesRange::new(byte, byte)]);
677 cls.negate();
678 Hir::class(Class::Bytes(cls))
679 }
680 Dot::AnyByteExceptLF => {
681 let mut cls = ClassBytes::empty();
682 cls.push(ClassBytesRange::new(b'\0', b'\x09'));
683 cls.push(ClassBytesRange::new(b'\x0B', b'\xFF'));
684 Hir::class(Class::Bytes(cls))
685 }
686 Dot::AnyByteExceptCRLF => {
687 let mut cls = ClassBytes::empty();
688 cls.push(ClassBytesRange::new(b'\0', b'\x09'));
689 cls.push(ClassBytesRange::new(b'\x0B', b'\x0C'));
690 cls.push(ClassBytesRange::new(b'\x0E', b'\xFF'));
691 Hir::class(Class::Bytes(cls))
692 }
693 }
694 }
695 }
696
697 /// The underlying kind of an arbitrary [`Hir`] expression.
698 ///
699 /// An `HirKind` is principally useful for doing case analysis on the type
700 /// of a regular expression. If you're looking to build new `Hir` values,
701 /// then you _must_ use the smart constructors defined on `Hir`, like
702 /// [`Hir::repetition`], to build new `Hir` values. The API intentionally does
703 /// not expose any way of building an `Hir` directly from an `HirKind`.
704 #[derive(Clone, Debug, Eq, PartialEq)]
705 pub enum HirKind {
706 /// The empty regular expression, which matches everything, including the
707 /// empty string.
708 Empty,
709 /// A literalstring that matches exactly these bytes.
710 Literal(Literal),
711 /// A single character class that matches any of the characters in the
712 /// class. A class can either consist of Unicode scalar values as
713 /// characters, or it can use bytes.
714 ///
715 /// A class may be empty. In which case, it matches nothing.
716 Class(Class),
717 /// A look-around assertion. A look-around match always has zero length.
718 Look(Look),
719 /// A repetition operation applied to a sub-expression.
720 Repetition(Repetition),
721 /// A capturing group, which contains a sub-expression.
722 Capture(Capture),
723 /// A concatenation of expressions.
724 ///
725 /// A concatenation matches only if each of its sub-expressions match one
726 /// after the other.
727 ///
728 /// Concatenations are guaranteed by `Hir`'s smart constructors to always
729 /// have at least two sub-expressions.
730 Concat(Vec<Hir>),
731 /// An alternation of expressions.
732 ///
733 /// An alternation matches only if at least one of its sub-expressions
734 /// match. If multiple sub-expressions match, then the leftmost is
735 /// preferred.
736 ///
737 /// Alternations are guaranteed by `Hir`'s smart constructors to always
738 /// have at least two sub-expressions.
739 Alternation(Vec<Hir>),
740 }
741
742 impl HirKind {
743 /// Returns a slice of this kind's sub-expressions, if any.
744 pub fn subs(&self) -> &[Hir] {
745 use core::slice::from_ref;
746
747 match *self {
748 HirKind::Empty
749 | HirKind::Literal(_)
750 | HirKind::Class(_)
751 | HirKind::Look(_) => &[],
752 HirKind::Repetition(Repetition { ref sub, .. }) => from_ref(sub),
753 HirKind::Capture(Capture { ref sub, .. }) => from_ref(sub),
754 HirKind::Concat(ref subs) => subs,
755 HirKind::Alternation(ref subs) => subs,
756 }
757 }
758 }
759
760 impl core::fmt::Debug for Hir {
761 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
762 self.kind.fmt(f)
763 }
764 }
765
766 /// Print a display representation of this Hir.
767 ///
768 /// The result of this is a valid regular expression pattern string.
769 ///
770 /// This implementation uses constant stack space and heap space proportional
771 /// to the size of the `Hir`.
772 impl core::fmt::Display for Hir {
773 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
774 crate::hir::print::Printer::new().print(self, f)
775 }
776 }
777
778 /// The high-level intermediate representation of a literal.
779 ///
780 /// A literal corresponds to `0` or more bytes that should be matched
781 /// literally. The smart constructors defined on `Hir` will automatically
782 /// concatenate adjacent literals into one literal, and will even automatically
783 /// replace empty literals with `Hir::empty()`.
784 ///
785 /// Note that despite a literal being represented by a sequence of bytes, its
786 /// `Debug` implementation will attempt to print it as a normal string. (That
787 /// is, not a sequence of decimal numbers.)
788 #[derive(Clone, Eq, PartialEq)]
789 pub struct Literal(pub Box<[u8]>);
790
791 impl core::fmt::Debug for Literal {
792 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
793 crate::debug::Bytes(&self.0).fmt(f)
794 }
795 }
796
797 /// The high-level intermediate representation of a character class.
798 ///
799 /// A character class corresponds to a set of characters. A character is either
800 /// defined by a Unicode scalar value or a byte. Unicode characters are used
801 /// by default, while bytes are used when Unicode mode (via the `u` flag) is
802 /// disabled.
803 ///
804 /// A character class, regardless of its character type, is represented by a
805 /// sequence of non-overlapping non-adjacent ranges of characters.
806 ///
807 /// Note that `Bytes` variant may be produced even when it exclusively matches
808 /// valid UTF-8. This is because a `Bytes` variant represents an intention by
809 /// the author of the regular expression to disable Unicode mode, which in turn
810 /// impacts the semantics of case insensitive matching. For example, `(?i)k`
811 /// and `(?i-u)k` will not match the same set of strings.
812 #[derive(Clone, Eq, PartialEq)]
813 pub enum Class {
814 /// A set of characters represented by Unicode scalar values.
815 Unicode(ClassUnicode),
816 /// A set of characters represented by arbitrary bytes (one byte per
817 /// character).
818 Bytes(ClassBytes),
819 }
820
821 impl Class {
822 /// Apply Unicode simple case folding to this character class, in place.
823 /// The character class will be expanded to include all simple case folded
824 /// character variants.
825 ///
826 /// If this is a byte oriented character class, then this will be limited
827 /// to the ASCII ranges `A-Z` and `a-z`.
828 ///
829 /// # Panics
830 ///
831 /// This routine panics when the case mapping data necessary for this
832 /// routine to complete is unavailable. This occurs when the `unicode-case`
833 /// feature is not enabled and the underlying class is Unicode oriented.
834 ///
835 /// Callers should prefer using `try_case_fold_simple` instead, which will
836 /// return an error instead of panicking.
837 pub fn case_fold_simple(&mut self) {
838 match *self {
839 Class::Unicode(ref mut x) => x.case_fold_simple(),
840 Class::Bytes(ref mut x) => x.case_fold_simple(),
841 }
842 }
843
844 /// Apply Unicode simple case folding to this character class, in place.
845 /// The character class will be expanded to include all simple case folded
846 /// character variants.
847 ///
848 /// If this is a byte oriented character class, then this will be limited
849 /// to the ASCII ranges `A-Z` and `a-z`.
850 ///
851 /// # Error
852 ///
853 /// This routine returns an error when the case mapping data necessary
854 /// for this routine to complete is unavailable. This occurs when the
855 /// `unicode-case` feature is not enabled and the underlying class is
856 /// Unicode oriented.
857 pub fn try_case_fold_simple(
858 &mut self,
859 ) -> core::result::Result<(), CaseFoldError> {
860 match *self {
861 Class::Unicode(ref mut x) => x.try_case_fold_simple()?,
862 Class::Bytes(ref mut x) => x.case_fold_simple(),
863 }
864 Ok(())
865 }
866
867 /// Negate this character class in place.
868 ///
869 /// After completion, this character class will contain precisely the
870 /// characters that weren't previously in the class.
871 pub fn negate(&mut self) {
872 match *self {
873 Class::Unicode(ref mut x) => x.negate(),
874 Class::Bytes(ref mut x) => x.negate(),
875 }
876 }
877
878 /// Returns true if and only if this character class will only ever match
879 /// valid UTF-8.
880 ///
881 /// A character class can match invalid UTF-8 only when the following
882 /// conditions are met:
883 ///
884 /// 1. The translator was configured to permit generating an expression
885 /// that can match invalid UTF-8. (By default, this is disabled.)
886 /// 2. Unicode mode (via the `u` flag) was disabled either in the concrete
887 /// syntax or in the parser builder. By default, Unicode mode is
888 /// enabled.
889 pub fn is_utf8(&self) -> bool {
890 match *self {
891 Class::Unicode(_) => true,
892 Class::Bytes(ref x) => x.is_ascii(),
893 }
894 }
895
896 /// Returns the length, in bytes, of the smallest string matched by this
897 /// character class.
898 ///
899 /// For non-empty byte oriented classes, this always returns `1`. For
900 /// non-empty Unicode oriented classes, this can return `1`, `2`, `3` or
901 /// `4`. For empty classes, `None` is returned. It is impossible for `0` to
902 /// be returned.
903 ///
904 /// # Example
905 ///
906 /// This example shows some examples of regexes and their corresponding
907 /// minimum length, if any.
908 ///
909 /// ```
910 /// use regex_syntax::{hir::Properties, parse};
911 ///
912 /// // The empty string has a min length of 0.
913 /// let hir = parse(r"")?;
914 /// assert_eq!(Some(0), hir.properties().minimum_len());
915 /// // As do other types of regexes that only match the empty string.
916 /// let hir = parse(r"^$\b\B")?;
917 /// assert_eq!(Some(0), hir.properties().minimum_len());
918 /// // A regex that can match the empty string but match more is still 0.
919 /// let hir = parse(r"a*")?;
920 /// assert_eq!(Some(0), hir.properties().minimum_len());
921 /// // A regex that matches nothing has no minimum defined.
922 /// let hir = parse(r"[a&&b]")?;
923 /// assert_eq!(None, hir.properties().minimum_len());
924 /// // Character classes usually have a minimum length of 1.
925 /// let hir = parse(r"\w")?;
926 /// assert_eq!(Some(1), hir.properties().minimum_len());
927 /// // But sometimes Unicode classes might be bigger!
928 /// let hir = parse(r"\p{Cyrillic}")?;
929 /// assert_eq!(Some(2), hir.properties().minimum_len());
930 ///
931 /// # Ok::<(), Box<dyn std::error::Error>>(())
932 /// ```
933 pub fn minimum_len(&self) -> Option<usize> {
934 match *self {
935 Class::Unicode(ref x) => x.minimum_len(),
936 Class::Bytes(ref x) => x.minimum_len(),
937 }
938 }
939
940 /// Returns the length, in bytes, of the longest string matched by this
941 /// character class.
942 ///
943 /// For non-empty byte oriented classes, this always returns `1`. For
944 /// non-empty Unicode oriented classes, this can return `1`, `2`, `3` or
945 /// `4`. For empty classes, `None` is returned. It is impossible for `0` to
946 /// be returned.
947 ///
948 /// # Example
949 ///
950 /// This example shows some examples of regexes and their corresponding
951 /// maximum length, if any.
952 ///
953 /// ```
954 /// use regex_syntax::{hir::Properties, parse};
955 ///
956 /// // The empty string has a max length of 0.
957 /// let hir = parse(r"")?;
958 /// assert_eq!(Some(0), hir.properties().maximum_len());
959 /// // As do other types of regexes that only match the empty string.
960 /// let hir = parse(r"^$\b\B")?;
961 /// assert_eq!(Some(0), hir.properties().maximum_len());
962 /// // A regex that matches nothing has no maximum defined.
963 /// let hir = parse(r"[a&&b]")?;
964 /// assert_eq!(None, hir.properties().maximum_len());
965 /// // Bounded repeats work as you expect.
966 /// let hir = parse(r"x{2,10}")?;
967 /// assert_eq!(Some(10), hir.properties().maximum_len());
968 /// // An unbounded repeat means there is no maximum.
969 /// let hir = parse(r"x{2,}")?;
970 /// assert_eq!(None, hir.properties().maximum_len());
971 /// // With Unicode enabled, \w can match up to 4 bytes!
972 /// let hir = parse(r"\w")?;
973 /// assert_eq!(Some(4), hir.properties().maximum_len());
974 /// // Without Unicode enabled, \w matches at most 1 byte.
975 /// let hir = parse(r"(?-u)\w")?;
976 /// assert_eq!(Some(1), hir.properties().maximum_len());
977 ///
978 /// # Ok::<(), Box<dyn std::error::Error>>(())
979 /// ```
980 pub fn maximum_len(&self) -> Option<usize> {
981 match *self {
982 Class::Unicode(ref x) => x.maximum_len(),
983 Class::Bytes(ref x) => x.maximum_len(),
984 }
985 }
986
987 /// Returns true if and only if this character class is empty. That is,
988 /// it has no elements.
989 ///
990 /// An empty character can never match anything, including an empty string.
991 pub fn is_empty(&self) -> bool {
992 match *self {
993 Class::Unicode(ref x) => x.ranges().is_empty(),
994 Class::Bytes(ref x) => x.ranges().is_empty(),
995 }
996 }
997
998 /// If this class consists of exactly one element (whether a codepoint or a
999 /// byte), then return it as a literal byte string.
1000 ///
1001 /// If this class is empty or contains more than one element, then `None`
1002 /// is returned.
1003 pub fn literal(&self) -> Option<Vec<u8>> {
1004 match *self {
1005 Class::Unicode(ref x) => x.literal(),
1006 Class::Bytes(ref x) => x.literal(),
1007 }
1008 }
1009 }
1010
1011 impl core::fmt::Debug for Class {
1012 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1013 use crate::debug::Byte;
1014
1015 let mut fmter = f.debug_set();
1016 match *self {
1017 Class::Unicode(ref cls) => {
1018 for r in cls.ranges().iter() {
1019 fmter.entry(&(r.start..=r.end));
1020 }
1021 }
1022 Class::Bytes(ref cls) => {
1023 for r in cls.ranges().iter() {
1024 fmter.entry(&(Byte(r.start)..=Byte(r.end)));
1025 }
1026 }
1027 }
1028 fmter.finish()
1029 }
1030 }
1031
1032 /// A set of characters represented by Unicode scalar values.
1033 #[derive(Clone, Debug, Eq, PartialEq)]
1034 pub struct ClassUnicode {
1035 set: IntervalSet<ClassUnicodeRange>,
1036 }
1037
1038 impl ClassUnicode {
1039 /// Create a new class from a sequence of ranges.
1040 ///
1041 /// The given ranges do not need to be in any specific order, and ranges
1042 /// may overlap. Ranges will automatically be sorted into a canonical
1043 /// non-overlapping order.
1044 pub fn new<I>(ranges: I) -> ClassUnicode
1045 where
1046 I: IntoIterator<Item = ClassUnicodeRange>,
1047 {
1048 ClassUnicode { set: IntervalSet::new(ranges) }
1049 }
1050
1051 /// Create a new class with no ranges.
1052 ///
1053 /// An empty class matches nothing. That is, it is equivalent to
1054 /// [`Hir::fail`].
1055 pub fn empty() -> ClassUnicode {
1056 ClassUnicode::new(vec![])
1057 }
1058
1059 /// Add a new range to this set.
1060 pub fn push(&mut self, range: ClassUnicodeRange) {
1061 self.set.push(range);
1062 }
1063
1064 /// Return an iterator over all ranges in this class.
1065 ///
1066 /// The iterator yields ranges in ascending order.
1067 pub fn iter(&self) -> ClassUnicodeIter<'_> {
1068 ClassUnicodeIter(self.set.iter())
1069 }
1070
1071 /// Return the underlying ranges as a slice.
1072 pub fn ranges(&self) -> &[ClassUnicodeRange] {
1073 self.set.intervals()
1074 }
1075
1076 /// Expand this character class such that it contains all case folded
1077 /// characters, according to Unicode's "simple" mapping. For example, if
1078 /// this class consists of the range `a-z`, then applying case folding will
1079 /// result in the class containing both the ranges `a-z` and `A-Z`.
1080 ///
1081 /// # Panics
1082 ///
1083 /// This routine panics when the case mapping data necessary for this
1084 /// routine to complete is unavailable. This occurs when the `unicode-case`
1085 /// feature is not enabled.
1086 ///
1087 /// Callers should prefer using `try_case_fold_simple` instead, which will
1088 /// return an error instead of panicking.
1089 pub fn case_fold_simple(&mut self) {
1090 self.set
1091 .case_fold_simple()
1092 .expect("unicode-case feature must be enabled");
1093 }
1094
1095 /// Expand this character class such that it contains all case folded
1096 /// characters, according to Unicode's "simple" mapping. For example, if
1097 /// this class consists of the range `a-z`, then applying case folding will
1098 /// result in the class containing both the ranges `a-z` and `A-Z`.
1099 ///
1100 /// # Error
1101 ///
1102 /// This routine returns an error when the case mapping data necessary
1103 /// for this routine to complete is unavailable. This occurs when the
1104 /// `unicode-case` feature is not enabled.
1105 pub fn try_case_fold_simple(
1106 &mut self,
1107 ) -> core::result::Result<(), CaseFoldError> {
1108 self.set.case_fold_simple()
1109 }
1110
1111 /// Negate this character class.
1112 ///
1113 /// For all `c` where `c` is a Unicode scalar value, if `c` was in this
1114 /// set, then it will not be in this set after negation.
1115 pub fn negate(&mut self) {
1116 self.set.negate();
1117 }
1118
1119 /// Union this character class with the given character class, in place.
1120 pub fn union(&mut self, other: &ClassUnicode) {
1121 self.set.union(&other.set);
1122 }
1123
1124 /// Intersect this character class with the given character class, in
1125 /// place.
1126 pub fn intersect(&mut self, other: &ClassUnicode) {
1127 self.set.intersect(&other.set);
1128 }
1129
1130 /// Subtract the given character class from this character class, in place.
1131 pub fn difference(&mut self, other: &ClassUnicode) {
1132 self.set.difference(&other.set);
1133 }
1134
1135 /// Compute the symmetric difference of the given character classes, in
1136 /// place.
1137 ///
1138 /// This computes the symmetric difference of two character classes. This
1139 /// removes all elements in this class that are also in the given class,
1140 /// but all adds all elements from the given class that aren't in this
1141 /// class. That is, the class will contain all elements in either class,
1142 /// but will not contain any elements that are in both classes.
1143 pub fn symmetric_difference(&mut self, other: &ClassUnicode) {
1144 self.set.symmetric_difference(&other.set);
1145 }
1146
1147 /// Returns true if and only if this character class will either match
1148 /// nothing or only ASCII bytes. Stated differently, this returns false
1149 /// if and only if this class contains a non-ASCII codepoint.
1150 pub fn is_ascii(&self) -> bool {
1151 self.set.intervals().last().map_or(true, |r| r.end <= '\x7F')
1152 }
1153
1154 /// Returns the length, in bytes, of the smallest string matched by this
1155 /// character class.
1156 ///
1157 /// Returns `None` when the class is empty.
1158 pub fn minimum_len(&self) -> Option<usize> {
1159 let first = self.ranges().get(0)?;
1160 // Correct because c1 < c2 implies c1.len_utf8() < c2.len_utf8().
1161 Some(first.start.len_utf8())
1162 }
1163
1164 /// Returns the length, in bytes, of the longest string matched by this
1165 /// character class.
1166 ///
1167 /// Returns `None` when the class is empty.
1168 pub fn maximum_len(&self) -> Option<usize> {
1169 let last = self.ranges().last()?;
1170 // Correct because c1 < c2 implies c1.len_utf8() < c2.len_utf8().
1171 Some(last.end.len_utf8())
1172 }
1173
1174 /// If this class consists of exactly one codepoint, then return it as
1175 /// a literal byte string.
1176 ///
1177 /// If this class is empty or contains more than one codepoint, then `None`
1178 /// is returned.
1179 pub fn literal(&self) -> Option<Vec<u8>> {
1180 let rs = self.ranges();
1181 if rs.len() == 1 && rs[0].start == rs[0].end {
1182 Some(rs[0].start.encode_utf8(&mut [0; 4]).to_string().into_bytes())
1183 } else {
1184 None
1185 }
1186 }
1187
1188 /// If this class consists of only ASCII ranges, then return its
1189 /// corresponding and equivalent byte class.
1190 pub fn to_byte_class(&self) -> Option<ClassBytes> {
1191 if !self.is_ascii() {
1192 return None;
1193 }
1194 Some(ClassBytes::new(self.ranges().iter().map(|r| {
1195 // Since we are guaranteed that our codepoint range is ASCII, the
1196 // 'u8::try_from' calls below are guaranteed to be correct.
1197 ClassBytesRange {
1198 start: u8::try_from(r.start).unwrap(),
1199 end: u8::try_from(r.end).unwrap(),
1200 }
1201 })))
1202 }
1203 }
1204
1205 /// An iterator over all ranges in a Unicode character class.
1206 ///
1207 /// The lifetime `'a` refers to the lifetime of the underlying class.
1208 #[derive(Debug)]
1209 pub struct ClassUnicodeIter<'a>(IntervalSetIter<'a, ClassUnicodeRange>);
1210
1211 impl<'a> Iterator for ClassUnicodeIter<'a> {
1212 type Item = &'a ClassUnicodeRange;
1213
1214 fn next(&mut self) -> Option<&'a ClassUnicodeRange> {
1215 self.0.next()
1216 }
1217 }
1218
1219 /// A single range of characters represented by Unicode scalar values.
1220 ///
1221 /// The range is closed. That is, the start and end of the range are included
1222 /// in the range.
1223 #[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)]
1224 pub struct ClassUnicodeRange {
1225 start: char,
1226 end: char,
1227 }
1228
1229 impl core::fmt::Debug for ClassUnicodeRange {
1230 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1231 let start = if !self.start.is_whitespace() && !self.start.is_control()
1232 {
1233 self.start.to_string()
1234 } else {
1235 format!("0x{:X}", u32::from(self.start))
1236 };
1237 let end = if !self.end.is_whitespace() && !self.end.is_control() {
1238 self.end.to_string()
1239 } else {
1240 format!("0x{:X}", u32::from(self.end))
1241 };
1242 f.debug_struct("ClassUnicodeRange")
1243 .field("start", &start)
1244 .field("end", &end)
1245 .finish()
1246 }
1247 }
1248
1249 impl Interval for ClassUnicodeRange {
1250 type Bound = char;
1251
1252 #[inline]
1253 fn lower(&self) -> char {
1254 self.start
1255 }
1256 #[inline]
1257 fn upper(&self) -> char {
1258 self.end
1259 }
1260 #[inline]
1261 fn set_lower(&mut self, bound: char) {
1262 self.start = bound;
1263 }
1264 #[inline]
1265 fn set_upper(&mut self, bound: char) {
1266 self.end = bound;
1267 }
1268
1269 /// Apply simple case folding to this Unicode scalar value range.
1270 ///
1271 /// Additional ranges are appended to the given vector. Canonical ordering
1272 /// is *not* maintained in the given vector.
1273 fn case_fold_simple(
1274 &self,
1275 ranges: &mut Vec<ClassUnicodeRange>,
1276 ) -> Result<(), unicode::CaseFoldError> {
1277 let mut folder = unicode::SimpleCaseFolder::new()?;
1278 if !folder.overlaps(self.start, self.end) {
1279 return Ok(());
1280 }
1281 let (start, end) = (u32::from(self.start), u32::from(self.end));
1282 for cp in (start..=end).filter_map(char::from_u32) {
1283 for &cp_folded in folder.mapping(cp) {
1284 ranges.push(ClassUnicodeRange::new(cp_folded, cp_folded));
1285 }
1286 }
1287 Ok(())
1288 }
1289 }
1290
1291 impl ClassUnicodeRange {
1292 /// Create a new Unicode scalar value range for a character class.
1293 ///
1294 /// The returned range is always in a canonical form. That is, the range
1295 /// returned always satisfies the invariant that `start <= end`.
1296 pub fn new(start: char, end: char) -> ClassUnicodeRange {
1297 ClassUnicodeRange::create(start, end)
1298 }
1299
1300 /// Return the start of this range.
1301 ///
1302 /// The start of a range is always less than or equal to the end of the
1303 /// range.
1304 pub fn start(&self) -> char {
1305 self.start
1306 }
1307
1308 /// Return the end of this range.
1309 ///
1310 /// The end of a range is always greater than or equal to the start of the
1311 /// range.
1312 pub fn end(&self) -> char {
1313 self.end
1314 }
1315
1316 /// Returns the number of codepoints in this range.
1317 pub fn len(&self) -> usize {
1318 let diff = 1 + u32::from(self.end) - u32::from(self.start);
1319 // This is likely to panic in 16-bit targets since a usize can only fit
1320 // 2^16. It's not clear what to do here, other than to return an error
1321 // when building a Unicode class that contains a range whose length
1322 // overflows usize. (Which, to be honest, is probably quite common on
1323 // 16-bit targets. For example, this would imply that '.' and '\p{any}'
1324 // would be impossible to build.)
1325 usize::try_from(diff).expect("char class len fits in usize")
1326 }
1327 }
1328
1329 /// A set of characters represented by arbitrary bytes (where one byte
1330 /// corresponds to one character).
1331 #[derive(Clone, Debug, Eq, PartialEq)]
1332 pub struct ClassBytes {
1333 set: IntervalSet<ClassBytesRange>,
1334 }
1335
1336 impl ClassBytes {
1337 /// Create a new class from a sequence of ranges.
1338 ///
1339 /// The given ranges do not need to be in any specific order, and ranges
1340 /// may overlap. Ranges will automatically be sorted into a canonical
1341 /// non-overlapping order.
1342 pub fn new<I>(ranges: I) -> ClassBytes
1343 where
1344 I: IntoIterator<Item = ClassBytesRange>,
1345 {
1346 ClassBytes { set: IntervalSet::new(ranges) }
1347 }
1348
1349 /// Create a new class with no ranges.
1350 ///
1351 /// An empty class matches nothing. That is, it is equivalent to
1352 /// [`Hir::fail`].
1353 pub fn empty() -> ClassBytes {
1354 ClassBytes::new(vec![])
1355 }
1356
1357 /// Add a new range to this set.
1358 pub fn push(&mut self, range: ClassBytesRange) {
1359 self.set.push(range);
1360 }
1361
1362 /// Return an iterator over all ranges in this class.
1363 ///
1364 /// The iterator yields ranges in ascending order.
1365 pub fn iter(&self) -> ClassBytesIter<'_> {
1366 ClassBytesIter(self.set.iter())
1367 }
1368
1369 /// Return the underlying ranges as a slice.
1370 pub fn ranges(&self) -> &[ClassBytesRange] {
1371 self.set.intervals()
1372 }
1373
1374 /// Expand this character class such that it contains all case folded
1375 /// characters. For example, if this class consists of the range `a-z`,
1376 /// then applying case folding will result in the class containing both the
1377 /// ranges `a-z` and `A-Z`.
1378 ///
1379 /// Note that this only applies ASCII case folding, which is limited to the
1380 /// characters `a-z` and `A-Z`.
1381 pub fn case_fold_simple(&mut self) {
1382 self.set.case_fold_simple().expect("ASCII case folding never fails");
1383 }
1384
1385 /// Negate this byte class.
1386 ///
1387 /// For all `b` where `b` is a any byte, if `b` was in this set, then it
1388 /// will not be in this set after negation.
1389 pub fn negate(&mut self) {
1390 self.set.negate();
1391 }
1392
1393 /// Union this byte class with the given byte class, in place.
1394 pub fn union(&mut self, other: &ClassBytes) {
1395 self.set.union(&other.set);
1396 }
1397
1398 /// Intersect this byte class with the given byte class, in place.
1399 pub fn intersect(&mut self, other: &ClassBytes) {
1400 self.set.intersect(&other.set);
1401 }
1402
1403 /// Subtract the given byte class from this byte class, in place.
1404 pub fn difference(&mut self, other: &ClassBytes) {
1405 self.set.difference(&other.set);
1406 }
1407
1408 /// Compute the symmetric difference of the given byte classes, in place.
1409 ///
1410 /// This computes the symmetric difference of two byte classes. This
1411 /// removes all elements in this class that are also in the given class,
1412 /// but all adds all elements from the given class that aren't in this
1413 /// class. That is, the class will contain all elements in either class,
1414 /// but will not contain any elements that are in both classes.
1415 pub fn symmetric_difference(&mut self, other: &ClassBytes) {
1416 self.set.symmetric_difference(&other.set);
1417 }
1418
1419 /// Returns true if and only if this character class will either match
1420 /// nothing or only ASCII bytes. Stated differently, this returns false
1421 /// if and only if this class contains a non-ASCII byte.
1422 pub fn is_ascii(&self) -> bool {
1423 self.set.intervals().last().map_or(true, |r| r.end <= 0x7F)
1424 }
1425
1426 /// Returns the length, in bytes, of the smallest string matched by this
1427 /// character class.
1428 ///
1429 /// Returns `None` when the class is empty.
1430 pub fn minimum_len(&self) -> Option<usize> {
1431 if self.ranges().is_empty() {
1432 None
1433 } else {
1434 Some(1)
1435 }
1436 }
1437
1438 /// Returns the length, in bytes, of the longest string matched by this
1439 /// character class.
1440 ///
1441 /// Returns `None` when the class is empty.
1442 pub fn maximum_len(&self) -> Option<usize> {
1443 if self.ranges().is_empty() {
1444 None
1445 } else {
1446 Some(1)
1447 }
1448 }
1449
1450 /// If this class consists of exactly one byte, then return it as
1451 /// a literal byte string.
1452 ///
1453 /// If this class is empty or contains more than one byte, then `None`
1454 /// is returned.
1455 pub fn literal(&self) -> Option<Vec<u8>> {
1456 let rs = self.ranges();
1457 if rs.len() == 1 && rs[0].start == rs[0].end {
1458 Some(vec![rs[0].start])
1459 } else {
1460 None
1461 }
1462 }
1463
1464 /// If this class consists of only ASCII ranges, then return its
1465 /// corresponding and equivalent Unicode class.
1466 pub fn to_unicode_class(&self) -> Option<ClassUnicode> {
1467 if !self.is_ascii() {
1468 return None;
1469 }
1470 Some(ClassUnicode::new(self.ranges().iter().map(|r| {
1471 // Since we are guaranteed that our byte range is ASCII, the
1472 // 'char::from' calls below are correct and will not erroneously
1473 // convert a raw byte value into its corresponding codepoint.
1474 ClassUnicodeRange {
1475 start: char::from(r.start),
1476 end: char::from(r.end),
1477 }
1478 })))
1479 }
1480 }
1481
1482 /// An iterator over all ranges in a byte character class.
1483 ///
1484 /// The lifetime `'a` refers to the lifetime of the underlying class.
1485 #[derive(Debug)]
1486 pub struct ClassBytesIter<'a>(IntervalSetIter<'a, ClassBytesRange>);
1487
1488 impl<'a> Iterator for ClassBytesIter<'a> {
1489 type Item = &'a ClassBytesRange;
1490
1491 fn next(&mut self) -> Option<&'a ClassBytesRange> {
1492 self.0.next()
1493 }
1494 }
1495
1496 /// A single range of characters represented by arbitrary bytes.
1497 ///
1498 /// The range is closed. That is, the start and end of the range are included
1499 /// in the range.
1500 #[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)]
1501 pub struct ClassBytesRange {
1502 start: u8,
1503 end: u8,
1504 }
1505
1506 impl Interval for ClassBytesRange {
1507 type Bound = u8;
1508
1509 #[inline]
1510 fn lower(&self) -> u8 {
1511 self.start
1512 }
1513 #[inline]
1514 fn upper(&self) -> u8 {
1515 self.end
1516 }
1517 #[inline]
1518 fn set_lower(&mut self, bound: u8) {
1519 self.start = bound;
1520 }
1521 #[inline]
1522 fn set_upper(&mut self, bound: u8) {
1523 self.end = bound;
1524 }
1525
1526 /// Apply simple case folding to this byte range. Only ASCII case mappings
1527 /// (for a-z) are applied.
1528 ///
1529 /// Additional ranges are appended to the given vector. Canonical ordering
1530 /// is *not* maintained in the given vector.
1531 fn case_fold_simple(
1532 &self,
1533 ranges: &mut Vec<ClassBytesRange>,
1534 ) -> Result<(), unicode::CaseFoldError> {
1535 if !ClassBytesRange::new(b'a', b'z').is_intersection_empty(self) {
1536 let lower = cmp::max(self.start, b'a');
1537 let upper = cmp::min(self.end, b'z');
1538 ranges.push(ClassBytesRange::new(lower - 32, upper - 32));
1539 }
1540 if !ClassBytesRange::new(b'A', b'Z').is_intersection_empty(self) {
1541 let lower = cmp::max(self.start, b'A');
1542 let upper = cmp::min(self.end, b'Z');
1543 ranges.push(ClassBytesRange::new(lower + 32, upper + 32));
1544 }
1545 Ok(())
1546 }
1547 }
1548
1549 impl ClassBytesRange {
1550 /// Create a new byte range for a character class.
1551 ///
1552 /// The returned range is always in a canonical form. That is, the range
1553 /// returned always satisfies the invariant that `start <= end`.
1554 pub fn new(start: u8, end: u8) -> ClassBytesRange {
1555 ClassBytesRange::create(start, end)
1556 }
1557
1558 /// Return the start of this range.
1559 ///
1560 /// The start of a range is always less than or equal to the end of the
1561 /// range.
1562 pub fn start(&self) -> u8 {
1563 self.start
1564 }
1565
1566 /// Return the end of this range.
1567 ///
1568 /// The end of a range is always greater than or equal to the start of the
1569 /// range.
1570 pub fn end(&self) -> u8 {
1571 self.end
1572 }
1573
1574 /// Returns the number of bytes in this range.
1575 pub fn len(&self) -> usize {
1576 usize::from(self.end.checked_sub(self.start).unwrap())
1577 .checked_add(1)
1578 .unwrap()
1579 }
1580 }
1581
1582 impl core::fmt::Debug for ClassBytesRange {
1583 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1584 f.debug_struct("ClassBytesRange")
1585 .field("start", &crate::debug::Byte(self.start))
1586 .field("end", &crate::debug::Byte(self.end))
1587 .finish()
1588 }
1589 }
1590
1591 /// The high-level intermediate representation for a look-around assertion.
1592 ///
1593 /// An assertion match is always zero-length. Also called an "empty match."
1594 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1595 pub enum Look {
1596 /// Match the beginning of text. Specifically, this matches at the starting
1597 /// position of the input.
1598 Start = 1 << 0,
1599 /// Match the end of text. Specifically, this matches at the ending
1600 /// position of the input.
1601 End = 1 << 1,
1602 /// Match the beginning of a line or the beginning of text. Specifically,
1603 /// this matches at the starting position of the input, or at the position
1604 /// immediately following a `\n` character.
1605 StartLF = 1 << 2,
1606 /// Match the end of a line or the end of text. Specifically, this matches
1607 /// at the end position of the input, or at the position immediately
1608 /// preceding a `\n` character.
1609 EndLF = 1 << 3,
1610 /// Match the beginning of a line or the beginning of text. Specifically,
1611 /// this matches at the starting position of the input, or at the position
1612 /// immediately following either a `\r` or `\n` character, but never after
1613 /// a `\r` when a `\n` follows.
1614 StartCRLF = 1 << 4,
1615 /// Match the end of a line or the end of text. Specifically, this matches
1616 /// at the end position of the input, or at the position immediately
1617 /// preceding a `\r` or `\n` character, but never before a `\n` when a `\r`
1618 /// precedes it.
1619 EndCRLF = 1 << 5,
1620 /// Match an ASCII-only word boundary. That is, this matches a position
1621 /// where the left adjacent character and right adjacent character
1622 /// correspond to a word and non-word or a non-word and word character.
1623 WordAscii = 1 << 6,
1624 /// Match an ASCII-only negation of a word boundary.
1625 WordAsciiNegate = 1 << 7,
1626 /// Match a Unicode-aware word boundary. That is, this matches a position
1627 /// where the left adjacent character and right adjacent character
1628 /// correspond to a word and non-word or a non-word and word character.
1629 WordUnicode = 1 << 8,
1630 /// Match a Unicode-aware negation of a word boundary.
1631 WordUnicodeNegate = 1 << 9,
1632 }
1633
1634 impl Look {
1635 /// Flip the look-around assertion to its equivalent for reverse searches.
1636 /// For example, `StartLF` gets translated to `EndLF`.
1637 ///
1638 /// Some assertions, such as `WordUnicode`, remain the same since they
1639 /// match the same positions regardless of the direction of the search.
1640 #[inline]
1641 pub const fn reversed(self) -> Look {
1642 match self {
1643 Look::Start => Look::End,
1644 Look::End => Look::Start,
1645 Look::StartLF => Look::EndLF,
1646 Look::EndLF => Look::StartLF,
1647 Look::StartCRLF => Look::EndCRLF,
1648 Look::EndCRLF => Look::StartCRLF,
1649 Look::WordAscii => Look::WordAscii,
1650 Look::WordAsciiNegate => Look::WordAsciiNegate,
1651 Look::WordUnicode => Look::WordUnicode,
1652 Look::WordUnicodeNegate => Look::WordUnicodeNegate,
1653 }
1654 }
1655
1656 /// Return the underlying representation of this look-around enumeration
1657 /// as an integer. Giving the return value to the [`Look::from_repr`]
1658 /// constructor is guaranteed to return the same look-around variant that
1659 /// one started with within a semver compatible release of this crate.
1660 #[inline]
1661 pub const fn as_repr(self) -> u16 {
1662 // AFAIK, 'as' is the only way to zero-cost convert an int enum to an
1663 // actual int.
1664 self as u16
1665 }
1666
1667 /// Given the underlying representation of a `Look` value, return the
1668 /// corresponding `Look` value if the representation is valid. Otherwise
1669 /// `None` is returned.
1670 #[inline]
1671 pub const fn from_repr(repr: u16) -> Option<Look> {
1672 match repr {
1673 0b00_0000_0001 => Some(Look::Start),
1674 0b00_0000_0010 => Some(Look::End),
1675 0b00_0000_0100 => Some(Look::StartLF),
1676 0b00_0000_1000 => Some(Look::EndLF),
1677 0b00_0001_0000 => Some(Look::StartCRLF),
1678 0b00_0010_0000 => Some(Look::EndCRLF),
1679 0b00_0100_0000 => Some(Look::WordAscii),
1680 0b00_1000_0000 => Some(Look::WordAsciiNegate),
1681 0b01_0000_0000 => Some(Look::WordUnicode),
1682 0b10_0000_0000 => Some(Look::WordUnicodeNegate),
1683 _ => None,
1684 }
1685 }
1686
1687 /// Returns a convenient single codepoint representation of this
1688 /// look-around assertion. Each assertion is guaranteed to be represented
1689 /// by a distinct character.
1690 ///
1691 /// This is useful for succinctly representing a look-around assertion in
1692 /// human friendly but succinct output intended for a programmer working on
1693 /// regex internals.
1694 #[inline]
1695 pub const fn as_char(self) -> char {
1696 match self {
1697 Look::Start => 'A',
1698 Look::End => 'z',
1699 Look::StartLF => '^',
1700 Look::EndLF => '$',
1701 Look::StartCRLF => 'r',
1702 Look::EndCRLF => 'R',
1703 Look::WordAscii => 'b',
1704 Look::WordAsciiNegate => 'B',
1705 Look::WordUnicode => '𝛃',
1706 Look::WordUnicodeNegate => '𝚩',
1707 }
1708 }
1709 }
1710
1711 /// The high-level intermediate representation for a capturing group.
1712 ///
1713 /// A capturing group always has an index and a child expression. It may
1714 /// also have a name associated with it (e.g., `(?P<foo>\w)`), but it's not
1715 /// necessary.
1716 ///
1717 /// Note that there is no explicit representation of a non-capturing group
1718 /// in a `Hir`. Instead, non-capturing grouping is handled automatically by
1719 /// the recursive structure of the `Hir` itself.
1720 #[derive(Clone, Debug, Eq, PartialEq)]
1721 pub struct Capture {
1722 /// The capture index of the capture.
1723 pub index: u32,
1724 /// The name of the capture, if it exists.
1725 pub name: Option<Box<str>>,
1726 /// The expression inside the capturing group, which may be empty.
1727 pub sub: Box<Hir>,
1728 }
1729
1730 /// The high-level intermediate representation of a repetition operator.
1731 ///
1732 /// A repetition operator permits the repetition of an arbitrary
1733 /// sub-expression.
1734 #[derive(Clone, Debug, Eq, PartialEq)]
1735 pub struct Repetition {
1736 /// The minimum range of the repetition.
1737 ///
1738 /// Note that special cases like `?`, `+` and `*` all get translated into
1739 /// the ranges `{0,1}`, `{1,}` and `{0,}`, respectively.
1740 ///
1741 /// When `min` is zero, this expression can match the empty string
1742 /// regardless of what its sub-expression is.
1743 pub min: u32,
1744 /// The maximum range of the repetition.
1745 ///
1746 /// Note that when `max` is `None`, `min` acts as a lower bound but where
1747 /// there is no upper bound. For something like `x{5}` where the min and
1748 /// max are equivalent, `min` will be set to `5` and `max` will be set to
1749 /// `Some(5)`.
1750 pub max: Option<u32>,
1751 /// Whether this repetition operator is greedy or not. A greedy operator
1752 /// will match as much as it can. A non-greedy operator will match as
1753 /// little as it can.
1754 ///
1755 /// Typically, operators are greedy by default and are only non-greedy when
1756 /// a `?` suffix is used, e.g., `(expr)*` is greedy while `(expr)*?` is
1757 /// not. However, this can be inverted via the `U` "ungreedy" flag.
1758 pub greedy: bool,
1759 /// The expression being repeated.
1760 pub sub: Box<Hir>,
1761 }
1762
1763 impl Repetition {
1764 /// Returns a new repetition with the same `min`, `max` and `greedy`
1765 /// values, but with its sub-expression replaced with the one given.
1766 pub fn with(&self, sub: Hir) -> Repetition {
1767 Repetition {
1768 min: self.min,
1769 max: self.max,
1770 greedy: self.greedy,
1771 sub: Box::new(sub),
1772 }
1773 }
1774 }
1775
1776 /// A type describing the different flavors of `.`.
1777 ///
1778 /// This type is meant to be used with [`Hir::dot`], which is a convenience
1779 /// routine for building HIR values derived from the `.` regex.
1780 #[non_exhaustive]
1781 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1782 pub enum Dot {
1783 /// Matches the UTF-8 encoding of any Unicode scalar value.
1784 ///
1785 /// This is equivalent to `(?su:.)` and also `\p{any}`.
1786 AnyChar,
1787 /// Matches any byte value.
1788 ///
1789 /// This is equivalent to `(?s-u:.)` and also `(?-u:[\x00-\xFF])`.
1790 AnyByte,
1791 /// Matches the UTF-8 encoding of any Unicode scalar value except for the
1792 /// `char` given.
1793 ///
1794 /// This is equivalent to using `(?u-s:.)` with the line terminator set
1795 /// to a particular ASCII byte. (Because of peculiarities in the regex
1796 /// engines, a line terminator must be a single byte. It follows that when
1797 /// UTF-8 mode is enabled, this single byte must also be a Unicode scalar
1798 /// value. That is, ti must be ASCII.)
1799 ///
1800 /// (This and `AnyCharExceptLF` both exist because of legacy reasons.
1801 /// `AnyCharExceptLF` will be dropped in the next breaking change release.)
1802 AnyCharExcept(char),
1803 /// Matches the UTF-8 encoding of any Unicode scalar value except for `\n`.
1804 ///
1805 /// This is equivalent to `(?u-s:.)` and also `[\p{any}--\n]`.
1806 AnyCharExceptLF,
1807 /// Matches the UTF-8 encoding of any Unicode scalar value except for `\r`
1808 /// and `\n`.
1809 ///
1810 /// This is equivalent to `(?uR-s:.)` and also `[\p{any}--\r\n]`.
1811 AnyCharExceptCRLF,
1812 /// Matches any byte value except for the `u8` given.
1813 ///
1814 /// This is equivalent to using `(?-us:.)` with the line terminator set
1815 /// to a particular ASCII byte. (Because of peculiarities in the regex
1816 /// engines, a line terminator must be a single byte. It follows that when
1817 /// UTF-8 mode is enabled, this single byte must also be a Unicode scalar
1818 /// value. That is, ti must be ASCII.)
1819 ///
1820 /// (This and `AnyByteExceptLF` both exist because of legacy reasons.
1821 /// `AnyByteExceptLF` will be dropped in the next breaking change release.)
1822 AnyByteExcept(u8),
1823 /// Matches any byte value except for `\n`.
1824 ///
1825 /// This is equivalent to `(?-su:.)` and also `(?-u:[[\x00-\xFF]--\n])`.
1826 AnyByteExceptLF,
1827 /// Matches any byte value except for `\r` and `\n`.
1828 ///
1829 /// This is equivalent to `(?R-su:.)` and also `(?-u:[[\x00-\xFF]--\r\n])`.
1830 AnyByteExceptCRLF,
1831 }
1832
1833 /// A custom `Drop` impl is used for `HirKind` such that it uses constant stack
1834 /// space but heap space proportional to the depth of the total `Hir`.
1835 impl Drop for Hir {
1836 fn drop(&mut self) {
1837 use core::mem;
1838
1839 match *self.kind() {
1840 HirKind::Empty
1841 | HirKind::Literal(_)
1842 | HirKind::Class(_)
1843 | HirKind::Look(_) => return,
1844 HirKind::Capture(ref x) if x.sub.kind.subs().is_empty() => return,
1845 HirKind::Repetition(ref x) if x.sub.kind.subs().is_empty() => {
1846 return
1847 }
1848 HirKind::Concat(ref x) if x.is_empty() => return,
1849 HirKind::Alternation(ref x) if x.is_empty() => return,
1850 _ => {}
1851 }
1852
1853 let mut stack = vec![mem::replace(self, Hir::empty())];
1854 while let Some(mut expr) = stack.pop() {
1855 match expr.kind {
1856 HirKind::Empty
1857 | HirKind::Literal(_)
1858 | HirKind::Class(_)
1859 | HirKind::Look(_) => {}
1860 HirKind::Capture(ref mut x) => {
1861 stack.push(mem::replace(&mut x.sub, Hir::empty()));
1862 }
1863 HirKind::Repetition(ref mut x) => {
1864 stack.push(mem::replace(&mut x.sub, Hir::empty()));
1865 }
1866 HirKind::Concat(ref mut x) => {
1867 stack.extend(x.drain(..));
1868 }
1869 HirKind::Alternation(ref mut x) => {
1870 stack.extend(x.drain(..));
1871 }
1872 }
1873 }
1874 }
1875 }
1876
1877 /// A type that collects various properties of an HIR value.
1878 ///
1879 /// Properties are always scalar values and represent meta data that is
1880 /// computed inductively on an HIR value. Properties are defined for all
1881 /// HIR values.
1882 ///
1883 /// All methods on a `Properties` value take constant time and are meant to
1884 /// be cheap to call.
1885 #[derive(Clone, Debug, Eq, PartialEq)]
1886 pub struct Properties(Box<PropertiesI>);
1887
1888 /// The property definition. It is split out so that we can box it, and
1889 /// there by make `Properties` use less stack size. This is kind-of important
1890 /// because every HIR value has a `Properties` attached to it.
1891 ///
1892 /// This does have the unfortunate consequence that creating any HIR value
1893 /// always leads to at least one alloc for properties, but this is generally
1894 /// true anyway (for pretty much all HirKinds except for look-arounds).
1895 #[derive(Clone, Debug, Eq, PartialEq)]
1896 struct PropertiesI {
1897 minimum_len: Option<usize>,
1898 maximum_len: Option<usize>,
1899 look_set: LookSet,
1900 look_set_prefix: LookSet,
1901 look_set_suffix: LookSet,
1902 look_set_prefix_any: LookSet,
1903 look_set_suffix_any: LookSet,
1904 utf8: bool,
1905 explicit_captures_len: usize,
1906 static_explicit_captures_len: Option<usize>,
1907 literal: bool,
1908 alternation_literal: bool,
1909 }
1910
1911 impl Properties {
1912 /// Returns the length (in bytes) of the smallest string matched by this
1913 /// HIR.
1914 ///
1915 /// A return value of `0` is possible and occurs when the HIR can match an
1916 /// empty string.
1917 ///
1918 /// `None` is returned when there is no minimum length. This occurs in
1919 /// precisely the cases where the HIR matches nothing. i.e., The language
1920 /// the regex matches is empty. An example of such a regex is `\P{any}`.
1921 #[inline]
1922 pub fn minimum_len(&self) -> Option<usize> {
1923 self.0.minimum_len
1924 }
1925
1926 /// Returns the length (in bytes) of the longest string matched by this
1927 /// HIR.
1928 ///
1929 /// A return value of `0` is possible and occurs when nothing longer than
1930 /// the empty string is in the language described by this HIR.
1931 ///
1932 /// `None` is returned when there is no longest matching string. This
1933 /// occurs when the HIR matches nothing or when there is no upper bound on
1934 /// the length of matching strings. Example of such regexes are `\P{any}`
1935 /// (matches nothing) and `a+` (has no upper bound).
1936 #[inline]
1937 pub fn maximum_len(&self) -> Option<usize> {
1938 self.0.maximum_len
1939 }
1940
1941 /// Returns a set of all look-around assertions that appear at least once
1942 /// in this HIR value.
1943 #[inline]
1944 pub fn look_set(&self) -> LookSet {
1945 self.0.look_set
1946 }
1947
1948 /// Returns a set of all look-around assertions that appear as a prefix for
1949 /// this HIR value. That is, the set returned corresponds to the set of
1950 /// assertions that must be passed before matching any bytes in a haystack.
1951 ///
1952 /// For example, `hir.look_set_prefix().contains(Look::Start)` returns true
1953 /// if and only if the HIR is fully anchored at the start.
1954 #[inline]
1955 pub fn look_set_prefix(&self) -> LookSet {
1956 self.0.look_set_prefix
1957 }
1958
1959 /// Returns a set of all look-around assertions that appear as a _possible_
1960 /// prefix for this HIR value. That is, the set returned corresponds to the
1961 /// set of assertions that _may_ be passed before matching any bytes in a
1962 /// haystack.
1963 ///
1964 /// For example, `hir.look_set_prefix_any().contains(Look::Start)` returns
1965 /// true if and only if it's possible for the regex to match through a
1966 /// anchored assertion before consuming any input.
1967 #[inline]
1968 pub fn look_set_prefix_any(&self) -> LookSet {
1969 self.0.look_set_prefix_any
1970 }
1971
1972 /// Returns a set of all look-around assertions that appear as a suffix for
1973 /// this HIR value. That is, the set returned corresponds to the set of
1974 /// assertions that must be passed in order to be considered a match after
1975 /// all other consuming HIR expressions.
1976 ///
1977 /// For example, `hir.look_set_suffix().contains(Look::End)` returns true
1978 /// if and only if the HIR is fully anchored at the end.
1979 #[inline]
1980 pub fn look_set_suffix(&self) -> LookSet {
1981 self.0.look_set_suffix
1982 }
1983
1984 /// Returns a set of all look-around assertions that appear as a _possible_
1985 /// suffix for this HIR value. That is, the set returned corresponds to the
1986 /// set of assertions that _may_ be passed before matching any bytes in a
1987 /// haystack.
1988 ///
1989 /// For example, `hir.look_set_suffix_any().contains(Look::End)` returns
1990 /// true if and only if it's possible for the regex to match through a
1991 /// anchored assertion at the end of a match without consuming any input.
1992 #[inline]
1993 pub fn look_set_suffix_any(&self) -> LookSet {
1994 self.0.look_set_suffix_any
1995 }
1996
1997 /// Return true if and only if the corresponding HIR will always match
1998 /// valid UTF-8.
1999 ///
2000 /// When this returns false, then it is possible for this HIR expression to
2001 /// match invalid UTF-8, including by matching between the code units of
2002 /// a single UTF-8 encoded codepoint.
2003 ///
2004 /// Note that this returns true even when the corresponding HIR can match
2005 /// the empty string. Since an empty string can technically appear between
2006 /// UTF-8 code units, it is possible for a match to be reported that splits
2007 /// a codepoint which could in turn be considered matching invalid UTF-8.
2008 /// However, it is generally assumed that such empty matches are handled
2009 /// specially by the search routine if it is absolutely required that
2010 /// matches not split a codepoint.
2011 ///
2012 /// # Example
2013 ///
2014 /// This code example shows the UTF-8 property of a variety of patterns.
2015 ///
2016 /// ```
2017 /// use regex_syntax::{ParserBuilder, parse};
2018 ///
2019 /// // Examples of 'is_utf8() == true'.
2020 /// assert!(parse(r"a")?.properties().is_utf8());
2021 /// assert!(parse(r"[^a]")?.properties().is_utf8());
2022 /// assert!(parse(r".")?.properties().is_utf8());
2023 /// assert!(parse(r"\W")?.properties().is_utf8());
2024 /// assert!(parse(r"\b")?.properties().is_utf8());
2025 /// assert!(parse(r"\B")?.properties().is_utf8());
2026 /// assert!(parse(r"(?-u)\b")?.properties().is_utf8());
2027 /// assert!(parse(r"(?-u)\B")?.properties().is_utf8());
2028 /// // Unicode mode is enabled by default, and in
2029 /// // that mode, all \x hex escapes are treated as
2030 /// // codepoints. So this actually matches the UTF-8
2031 /// // encoding of U+00FF.
2032 /// assert!(parse(r"\xFF")?.properties().is_utf8());
2033 ///
2034 /// // Now we show examples of 'is_utf8() == false'.
2035 /// // The only way to do this is to force the parser
2036 /// // to permit invalid UTF-8, otherwise all of these
2037 /// // would fail to parse!
2038 /// let parse = |pattern| {
2039 /// ParserBuilder::new().utf8(false).build().parse(pattern)
2040 /// };
2041 /// assert!(!parse(r"(?-u)[^a]")?.properties().is_utf8());
2042 /// assert!(!parse(r"(?-u).")?.properties().is_utf8());
2043 /// assert!(!parse(r"(?-u)\W")?.properties().is_utf8());
2044 /// // Conversely to the equivalent example above,
2045 /// // when Unicode mode is disabled, \x hex escapes
2046 /// // are treated as their raw byte values.
2047 /// assert!(!parse(r"(?-u)\xFF")?.properties().is_utf8());
2048 /// // Note that just because we disabled UTF-8 in the
2049 /// // parser doesn't mean we still can't use Unicode.
2050 /// // It is enabled by default, so \xFF is still
2051 /// // equivalent to matching the UTF-8 encoding of
2052 /// // U+00FF by default.
2053 /// assert!(parse(r"\xFF")?.properties().is_utf8());
2054 /// // Even though we use raw bytes that individually
2055 /// // are not valid UTF-8, when combined together, the
2056 /// // overall expression *does* match valid UTF-8!
2057 /// assert!(parse(r"(?-u)\xE2\x98\x83")?.properties().is_utf8());
2058 ///
2059 /// # Ok::<(), Box<dyn std::error::Error>>(())
2060 /// ```
2061 #[inline]
2062 pub fn is_utf8(&self) -> bool {
2063 self.0.utf8
2064 }
2065
2066 /// Returns the total number of explicit capturing groups in the
2067 /// corresponding HIR.
2068 ///
2069 /// Note that this does not include the implicit capturing group
2070 /// corresponding to the entire match that is typically included by regex
2071 /// engines.
2072 ///
2073 /// # Example
2074 ///
2075 /// This method will return `0` for `a` and `1` for `(a)`:
2076 ///
2077 /// ```
2078 /// use regex_syntax::parse;
2079 ///
2080 /// assert_eq!(0, parse("a")?.properties().explicit_captures_len());
2081 /// assert_eq!(1, parse("(a)")?.properties().explicit_captures_len());
2082 ///
2083 /// # Ok::<(), Box<dyn std::error::Error>>(())
2084 /// ```
2085 #[inline]
2086 pub fn explicit_captures_len(&self) -> usize {
2087 self.0.explicit_captures_len
2088 }
2089
2090 /// Returns the total number of explicit capturing groups that appear in
2091 /// every possible match.
2092 ///
2093 /// If the number of capture groups can vary depending on the match, then
2094 /// this returns `None`. That is, a value is only returned when the number
2095 /// of matching groups is invariant or "static."
2096 ///
2097 /// Note that this does not include the implicit capturing group
2098 /// corresponding to the entire match.
2099 ///
2100 /// # Example
2101 ///
2102 /// This shows a few cases where a static number of capture groups is
2103 /// available and a few cases where it is not.
2104 ///
2105 /// ```
2106 /// use regex_syntax::parse;
2107 ///
2108 /// let len = |pattern| {
2109 /// parse(pattern).map(|h| {
2110 /// h.properties().static_explicit_captures_len()
2111 /// })
2112 /// };
2113 ///
2114 /// assert_eq!(Some(0), len("a")?);
2115 /// assert_eq!(Some(1), len("(a)")?);
2116 /// assert_eq!(Some(1), len("(a)|(b)")?);
2117 /// assert_eq!(Some(2), len("(a)(b)|(c)(d)")?);
2118 /// assert_eq!(None, len("(a)|b")?);
2119 /// assert_eq!(None, len("a|(b)")?);
2120 /// assert_eq!(None, len("(b)*")?);
2121 /// assert_eq!(Some(1), len("(b)+")?);
2122 ///
2123 /// # Ok::<(), Box<dyn std::error::Error>>(())
2124 /// ```
2125 #[inline]
2126 pub fn static_explicit_captures_len(&self) -> Option<usize> {
2127 self.0.static_explicit_captures_len
2128 }
2129
2130 /// Return true if and only if this HIR is a simple literal. This is
2131 /// only true when this HIR expression is either itself a `Literal` or a
2132 /// concatenation of only `Literal`s.
2133 ///
2134 /// For example, `f` and `foo` are literals, but `f+`, `(foo)`, `foo()` and
2135 /// the empty string are not (even though they contain sub-expressions that
2136 /// are literals).
2137 #[inline]
2138 pub fn is_literal(&self) -> bool {
2139 self.0.literal
2140 }
2141
2142 /// Return true if and only if this HIR is either a simple literal or an
2143 /// alternation of simple literals. This is only
2144 /// true when this HIR expression is either itself a `Literal` or a
2145 /// concatenation of only `Literal`s or an alternation of only `Literal`s.
2146 ///
2147 /// For example, `f`, `foo`, `a|b|c`, and `foo|bar|baz` are alternation
2148 /// literals, but `f+`, `(foo)`, `foo()`, and the empty pattern are not
2149 /// (even though that contain sub-expressions that are literals).
2150 #[inline]
2151 pub fn is_alternation_literal(&self) -> bool {
2152 self.0.alternation_literal
2153 }
2154
2155 /// Returns the total amount of heap memory usage, in bytes, used by this
2156 /// `Properties` value.
2157 #[inline]
2158 pub fn memory_usage(&self) -> usize {
2159 core::mem::size_of::<PropertiesI>()
2160 }
2161
2162 /// Returns a new set of properties that corresponds to the union of the
2163 /// iterator of properties given.
2164 ///
2165 /// This is useful when one has multiple `Hir` expressions and wants
2166 /// to combine them into a single alternation without constructing the
2167 /// corresponding `Hir`. This routine provides a way of combining the
2168 /// properties of each `Hir` expression into one set of properties
2169 /// representing the union of those expressions.
2170 ///
2171 /// # Example: union with HIRs that never match
2172 ///
2173 /// This example shows that unioning properties together with one that
2174 /// represents a regex that never matches will "poison" certain attributes,
2175 /// like the minimum and maximum lengths.
2176 ///
2177 /// ```
2178 /// use regex_syntax::{hir::Properties, parse};
2179 ///
2180 /// let hir1 = parse("ab?c?")?;
2181 /// assert_eq!(Some(1), hir1.properties().minimum_len());
2182 /// assert_eq!(Some(3), hir1.properties().maximum_len());
2183 ///
2184 /// let hir2 = parse(r"[a&&b]")?;
2185 /// assert_eq!(None, hir2.properties().minimum_len());
2186 /// assert_eq!(None, hir2.properties().maximum_len());
2187 ///
2188 /// let hir3 = parse(r"wxy?z?")?;
2189 /// assert_eq!(Some(2), hir3.properties().minimum_len());
2190 /// assert_eq!(Some(4), hir3.properties().maximum_len());
2191 ///
2192 /// let unioned = Properties::union([
2193 /// hir1.properties(),
2194 /// hir2.properties(),
2195 /// hir3.properties(),
2196 /// ]);
2197 /// assert_eq!(None, unioned.minimum_len());
2198 /// assert_eq!(None, unioned.maximum_len());
2199 ///
2200 /// # Ok::<(), Box<dyn std::error::Error>>(())
2201 /// ```
2202 ///
2203 /// The maximum length can also be "poisoned" by a pattern that has no
2204 /// upper bound on the length of a match. The minimum length remains
2205 /// unaffected:
2206 ///
2207 /// ```
2208 /// use regex_syntax::{hir::Properties, parse};
2209 ///
2210 /// let hir1 = parse("ab?c?")?;
2211 /// assert_eq!(Some(1), hir1.properties().minimum_len());
2212 /// assert_eq!(Some(3), hir1.properties().maximum_len());
2213 ///
2214 /// let hir2 = parse(r"a+")?;
2215 /// assert_eq!(Some(1), hir2.properties().minimum_len());
2216 /// assert_eq!(None, hir2.properties().maximum_len());
2217 ///
2218 /// let hir3 = parse(r"wxy?z?")?;
2219 /// assert_eq!(Some(2), hir3.properties().minimum_len());
2220 /// assert_eq!(Some(4), hir3.properties().maximum_len());
2221 ///
2222 /// let unioned = Properties::union([
2223 /// hir1.properties(),
2224 /// hir2.properties(),
2225 /// hir3.properties(),
2226 /// ]);
2227 /// assert_eq!(Some(1), unioned.minimum_len());
2228 /// assert_eq!(None, unioned.maximum_len());
2229 ///
2230 /// # Ok::<(), Box<dyn std::error::Error>>(())
2231 /// ```
2232 pub fn union<I, P>(props: I) -> Properties
2233 where
2234 I: IntoIterator<Item = P>,
2235 P: core::borrow::Borrow<Properties>,
2236 {
2237 let mut it = props.into_iter().peekable();
2238 // While empty alternations aren't possible, we still behave as if they
2239 // are. When we have an empty alternate, then clearly the look-around
2240 // prefix and suffix is empty. Otherwise, it is the intersection of all
2241 // prefixes and suffixes (respectively) of the branches.
2242 let fix = if it.peek().is_none() {
2243 LookSet::empty()
2244 } else {
2245 LookSet::full()
2246 };
2247 // And also, an empty alternate means we have 0 static capture groups,
2248 // but we otherwise start with the number corresponding to the first
2249 // alternate. If any subsequent alternate has a different number of
2250 // static capture groups, then we overall have a variation and not a
2251 // static number of groups.
2252 let static_explicit_captures_len =
2253 it.peek().and_then(|p| p.borrow().static_explicit_captures_len());
2254 // The base case is an empty alternation, which matches nothing.
2255 // Note though that empty alternations aren't possible, because the
2256 // Hir::alternation smart constructor rewrites those as empty character
2257 // classes.
2258 let mut props = PropertiesI {
2259 minimum_len: None,
2260 maximum_len: None,
2261 look_set: LookSet::empty(),
2262 look_set_prefix: fix,
2263 look_set_suffix: fix,
2264 look_set_prefix_any: LookSet::empty(),
2265 look_set_suffix_any: LookSet::empty(),
2266 utf8: true,
2267 explicit_captures_len: 0,
2268 static_explicit_captures_len,
2269 literal: false,
2270 alternation_literal: true,
2271 };
2272 let (mut min_poisoned, mut max_poisoned) = (false, false);
2273 // Handle properties that need to visit every child hir.
2274 for prop in it {
2275 let p = prop.borrow();
2276 props.look_set.set_union(p.look_set());
2277 props.look_set_prefix.set_intersect(p.look_set_prefix());
2278 props.look_set_suffix.set_intersect(p.look_set_suffix());
2279 props.look_set_prefix_any.set_union(p.look_set_prefix_any());
2280 props.look_set_suffix_any.set_union(p.look_set_suffix_any());
2281 props.utf8 = props.utf8 && p.is_utf8();
2282 props.explicit_captures_len = props
2283 .explicit_captures_len
2284 .saturating_add(p.explicit_captures_len());
2285 if props.static_explicit_captures_len
2286 != p.static_explicit_captures_len()
2287 {
2288 props.static_explicit_captures_len = None;
2289 }
2290 props.alternation_literal =
2291 props.alternation_literal && p.is_literal();
2292 if !min_poisoned {
2293 if let Some(xmin) = p.minimum_len() {
2294 if props.minimum_len.map_or(true, |pmin| xmin < pmin) {
2295 props.minimum_len = Some(xmin);
2296 }
2297 } else {
2298 props.minimum_len = None;
2299 min_poisoned = true;
2300 }
2301 }
2302 if !max_poisoned {
2303 if let Some(xmax) = p.maximum_len() {
2304 if props.maximum_len.map_or(true, |pmax| xmax > pmax) {
2305 props.maximum_len = Some(xmax);
2306 }
2307 } else {
2308 props.maximum_len = None;
2309 max_poisoned = true;
2310 }
2311 }
2312 }
2313 Properties(Box::new(props))
2314 }
2315 }
2316
2317 impl Properties {
2318 /// Create a new set of HIR properties for an empty regex.
2319 fn empty() -> Properties {
2320 let inner = PropertiesI {
2321 minimum_len: Some(0),
2322 maximum_len: Some(0),
2323 look_set: LookSet::empty(),
2324 look_set_prefix: LookSet::empty(),
2325 look_set_suffix: LookSet::empty(),
2326 look_set_prefix_any: LookSet::empty(),
2327 look_set_suffix_any: LookSet::empty(),
2328 // It is debatable whether an empty regex always matches at valid
2329 // UTF-8 boundaries. Strictly speaking, at a byte oriented view,
2330 // it is clearly false. There are, for example, many empty strings
2331 // between the bytes encoding a '☃'.
2332 //
2333 // However, when Unicode mode is enabled, the fundamental atom
2334 // of matching is really a codepoint. And in that scenario, an
2335 // empty regex is defined to only match at valid UTF-8 boundaries
2336 // and to never split a codepoint. It just so happens that this
2337 // enforcement is somewhat tricky to do for regexes that match
2338 // the empty string inside regex engines themselves. It usually
2339 // requires some layer above the regex engine to filter out such
2340 // matches.
2341 //
2342 // In any case, 'true' is really the only coherent option. If it
2343 // were false, for example, then 'a*' would also need to be false
2344 // since it too can match the empty string.
2345 utf8: true,
2346 explicit_captures_len: 0,
2347 static_explicit_captures_len: Some(0),
2348 literal: false,
2349 alternation_literal: false,
2350 };
2351 Properties(Box::new(inner))
2352 }
2353
2354 /// Create a new set of HIR properties for a literal regex.
2355 fn literal(lit: &Literal) -> Properties {
2356 let inner = PropertiesI {
2357 minimum_len: Some(lit.0.len()),
2358 maximum_len: Some(lit.0.len()),
2359 look_set: LookSet::empty(),
2360 look_set_prefix: LookSet::empty(),
2361 look_set_suffix: LookSet::empty(),
2362 look_set_prefix_any: LookSet::empty(),
2363 look_set_suffix_any: LookSet::empty(),
2364 utf8: core::str::from_utf8(&lit.0).is_ok(),
2365 explicit_captures_len: 0,
2366 static_explicit_captures_len: Some(0),
2367 literal: true,
2368 alternation_literal: true,
2369 };
2370 Properties(Box::new(inner))
2371 }
2372
2373 /// Create a new set of HIR properties for a character class.
2374 fn class(class: &Class) -> Properties {
2375 let inner = PropertiesI {
2376 minimum_len: class.minimum_len(),
2377 maximum_len: class.maximum_len(),
2378 look_set: LookSet::empty(),
2379 look_set_prefix: LookSet::empty(),
2380 look_set_suffix: LookSet::empty(),
2381 look_set_prefix_any: LookSet::empty(),
2382 look_set_suffix_any: LookSet::empty(),
2383 utf8: class.is_utf8(),
2384 explicit_captures_len: 0,
2385 static_explicit_captures_len: Some(0),
2386 literal: false,
2387 alternation_literal: false,
2388 };
2389 Properties(Box::new(inner))
2390 }
2391
2392 /// Create a new set of HIR properties for a look-around assertion.
2393 fn look(look: Look) -> Properties {
2394 let inner = PropertiesI {
2395 minimum_len: Some(0),
2396 maximum_len: Some(0),
2397 look_set: LookSet::singleton(look),
2398 look_set_prefix: LookSet::singleton(look),
2399 look_set_suffix: LookSet::singleton(look),
2400 look_set_prefix_any: LookSet::singleton(look),
2401 look_set_suffix_any: LookSet::singleton(look),
2402 // This requires a little explanation. Basically, we don't consider
2403 // matching an empty string to be equivalent to matching invalid
2404 // UTF-8, even though technically matching every empty string will
2405 // split the UTF-8 encoding of a single codepoint when treating a
2406 // UTF-8 encoded string as a sequence of bytes. Our defense here is
2407 // that in such a case, a codepoint should logically be treated as
2408 // the fundamental atom for matching, and thus the only valid match
2409 // points are between codepoints and not bytes.
2410 //
2411 // More practically, this is true here because it's also true
2412 // for 'Hir::empty()', otherwise something like 'a*' would be
2413 // considered to match invalid UTF-8. That in turn makes this
2414 // property borderline useless.
2415 utf8: true,
2416 explicit_captures_len: 0,
2417 static_explicit_captures_len: Some(0),
2418 literal: false,
2419 alternation_literal: false,
2420 };
2421 Properties(Box::new(inner))
2422 }
2423
2424 /// Create a new set of HIR properties for a repetition.
2425 fn repetition(rep: &Repetition) -> Properties {
2426 let p = rep.sub.properties();
2427 let minimum_len = p.minimum_len().map(|child_min| {
2428 let rep_min = usize::try_from(rep.min).unwrap_or(usize::MAX);
2429 child_min.saturating_mul(rep_min)
2430 });
2431 let maximum_len = rep.max.and_then(|rep_max| {
2432 let rep_max = usize::try_from(rep_max).ok()?;
2433 let child_max = p.maximum_len()?;
2434 child_max.checked_mul(rep_max)
2435 });
2436
2437 let mut inner = PropertiesI {
2438 minimum_len,
2439 maximum_len,
2440 look_set: p.look_set(),
2441 look_set_prefix: LookSet::empty(),
2442 look_set_suffix: LookSet::empty(),
2443 look_set_prefix_any: p.look_set_prefix_any(),
2444 look_set_suffix_any: p.look_set_suffix_any(),
2445 utf8: p.is_utf8(),
2446 explicit_captures_len: p.explicit_captures_len(),
2447 static_explicit_captures_len: p.static_explicit_captures_len(),
2448 literal: false,
2449 alternation_literal: false,
2450 };
2451 // If the repetition operator can match the empty string, then its
2452 // lookset prefix and suffixes themselves remain empty since they are
2453 // no longer required to match.
2454 if rep.min > 0 {
2455 inner.look_set_prefix = p.look_set_prefix();
2456 inner.look_set_suffix = p.look_set_suffix();
2457 }
2458 // If the static captures len of the sub-expression is not known or
2459 // is greater than zero, then it automatically propagates to the
2460 // repetition, regardless of the repetition. Otherwise, it might
2461 // change, but only when the repetition can match 0 times.
2462 if rep.min == 0
2463 && inner.static_explicit_captures_len.map_or(false, |len| len > 0)
2464 {
2465 // If we require a match 0 times, then our captures len is
2466 // guaranteed to be zero. Otherwise, if we *can* match the empty
2467 // string, then it's impossible to know how many captures will be
2468 // in the resulting match.
2469 if rep.max == Some(0) {
2470 inner.static_explicit_captures_len = Some(0);
2471 } else {
2472 inner.static_explicit_captures_len = None;
2473 }
2474 }
2475 Properties(Box::new(inner))
2476 }
2477
2478 /// Create a new set of HIR properties for a capture.
2479 fn capture(capture: &Capture) -> Properties {
2480 let p = capture.sub.properties();
2481 Properties(Box::new(PropertiesI {
2482 explicit_captures_len: p.explicit_captures_len().saturating_add(1),
2483 static_explicit_captures_len: p
2484 .static_explicit_captures_len()
2485 .map(|len| len.saturating_add(1)),
2486 literal: false,
2487 alternation_literal: false,
2488 ..*p.0.clone()
2489 }))
2490 }
2491
2492 /// Create a new set of HIR properties for a concatenation.
2493 fn concat(concat: &[Hir]) -> Properties {
2494 // The base case is an empty concatenation, which matches the empty
2495 // string. Note though that empty concatenations aren't possible,
2496 // because the Hir::concat smart constructor rewrites those as
2497 // Hir::empty.
2498 let mut props = PropertiesI {
2499 minimum_len: Some(0),
2500 maximum_len: Some(0),
2501 look_set: LookSet::empty(),
2502 look_set_prefix: LookSet::empty(),
2503 look_set_suffix: LookSet::empty(),
2504 look_set_prefix_any: LookSet::empty(),
2505 look_set_suffix_any: LookSet::empty(),
2506 utf8: true,
2507 explicit_captures_len: 0,
2508 static_explicit_captures_len: Some(0),
2509 literal: true,
2510 alternation_literal: true,
2511 };
2512 // Handle properties that need to visit every child hir.
2513 for x in concat.iter() {
2514 let p = x.properties();
2515 props.look_set.set_union(p.look_set());
2516 props.utf8 = props.utf8 && p.is_utf8();
2517 props.explicit_captures_len = props
2518 .explicit_captures_len
2519 .saturating_add(p.explicit_captures_len());
2520 props.static_explicit_captures_len = p
2521 .static_explicit_captures_len()
2522 .and_then(|len1| {
2523 Some((len1, props.static_explicit_captures_len?))
2524 })
2525 .and_then(|(len1, len2)| Some(len1.saturating_add(len2)));
2526 props.literal = props.literal && p.is_literal();
2527 props.alternation_literal =
2528 props.alternation_literal && p.is_alternation_literal();
2529 if let Some(minimum_len) = props.minimum_len {
2530 match p.minimum_len() {
2531 None => props.minimum_len = None,
2532 Some(len) => {
2533 // We use saturating arithmetic here because the
2534 // minimum is just a lower bound. We can't go any
2535 // higher than what our number types permit.
2536 props.minimum_len =
2537 Some(minimum_len.saturating_add(len));
2538 }
2539 }
2540 }
2541 if let Some(maximum_len) = props.maximum_len {
2542 match p.maximum_len() {
2543 None => props.maximum_len = None,
2544 Some(len) => {
2545 props.maximum_len = maximum_len.checked_add(len)
2546 }
2547 }
2548 }
2549 }
2550 // Handle the prefix properties, which only requires visiting
2551 // child exprs until one matches more than the empty string.
2552 let mut it = concat.iter();
2553 while let Some(x) = it.next() {
2554 props.look_set_prefix.set_union(x.properties().look_set_prefix());
2555 props
2556 .look_set_prefix_any
2557 .set_union(x.properties().look_set_prefix_any());
2558 if x.properties().maximum_len().map_or(true, |x| x > 0) {
2559 break;
2560 }
2561 }
2562 // Same thing for the suffix properties, but in reverse.
2563 let mut it = concat.iter().rev();
2564 while let Some(x) = it.next() {
2565 props.look_set_suffix.set_union(x.properties().look_set_suffix());
2566 props
2567 .look_set_suffix_any
2568 .set_union(x.properties().look_set_suffix_any());
2569 if x.properties().maximum_len().map_or(true, |x| x > 0) {
2570 break;
2571 }
2572 }
2573 Properties(Box::new(props))
2574 }
2575
2576 /// Create a new set of HIR properties for a concatenation.
2577 fn alternation(alts: &[Hir]) -> Properties {
2578 Properties::union(alts.iter().map(|hir| hir.properties()))
2579 }
2580 }
2581
2582 /// A set of look-around assertions.
2583 ///
2584 /// This is useful for efficiently tracking look-around assertions. For
2585 /// example, an [`Hir`] provides properties that return `LookSet`s.
2586 #[derive(Clone, Copy, Default, Eq, PartialEq)]
2587 pub struct LookSet {
2588 /// The underlying representation this set is exposed to make it possible
2589 /// to store it somewhere efficiently. The representation is that
2590 /// of a bitset, where each assertion occupies bit `i` where `i =
2591 /// Look::as_repr()`.
2592 ///
2593 /// Note that users of this internal representation must permit the full
2594 /// range of `u16` values to be represented. For example, even if the
2595 /// current implementation only makes use of the 10 least significant bits,
2596 /// it may use more bits in a future semver compatible release.
2597 pub bits: u16,
2598 }
2599
2600 impl LookSet {
2601 /// Create an empty set of look-around assertions.
2602 #[inline]
2603 pub fn empty() -> LookSet {
2604 LookSet { bits: 0 }
2605 }
2606
2607 /// Create a full set of look-around assertions.
2608 ///
2609 /// This set contains all possible look-around assertions.
2610 #[inline]
2611 pub fn full() -> LookSet {
2612 LookSet { bits: !0 }
2613 }
2614
2615 /// Create a look-around set containing the look-around assertion given.
2616 ///
2617 /// This is a convenience routine for creating an empty set and inserting
2618 /// one look-around assertions.
2619 #[inline]
2620 pub fn singleton(look: Look) -> LookSet {
2621 LookSet::empty().insert(look)
2622 }
2623
2624 /// Returns the total number of look-around assertions in this set.
2625 #[inline]
2626 pub fn len(self) -> usize {
2627 // OK because max value always fits in a u8, which in turn always
2628 // fits in a usize, regardless of target.
2629 usize::try_from(self.bits.count_ones()).unwrap()
2630 }
2631
2632 /// Returns true if and only if this set is empty.
2633 #[inline]
2634 pub fn is_empty(self) -> bool {
2635 self.len() == 0
2636 }
2637
2638 /// Returns true if and only if the given look-around assertion is in this
2639 /// set.
2640 #[inline]
2641 pub fn contains(self, look: Look) -> bool {
2642 self.bits & look.as_repr() != 0
2643 }
2644
2645 /// Returns true if and only if this set contains any anchor assertions.
2646 /// This includes both "start/end of haystack" and "start/end of line."
2647 #[inline]
2648 pub fn contains_anchor(&self) -> bool {
2649 self.contains_anchor_haystack() || self.contains_anchor_line()
2650 }
2651
2652 /// Returns true if and only if this set contains any "start/end of
2653 /// haystack" anchors. This doesn't include "start/end of line" anchors.
2654 #[inline]
2655 pub fn contains_anchor_haystack(&self) -> bool {
2656 self.contains(Look::Start) || self.contains(Look::End)
2657 }
2658
2659 /// Returns true if and only if this set contains any "start/end of line"
2660 /// anchors. This doesn't include "start/end of haystack" anchors. This
2661 /// includes both `\n` line anchors and CRLF (`\r\n`) aware line anchors.
2662 #[inline]
2663 pub fn contains_anchor_line(&self) -> bool {
2664 self.contains(Look::StartLF)
2665 || self.contains(Look::EndLF)
2666 || self.contains(Look::StartCRLF)
2667 || self.contains(Look::EndCRLF)
2668 }
2669
2670 /// Returns true if and only if this set contains any "start/end of line"
2671 /// anchors that only treat `\n` as line terminators. This does not include
2672 /// haystack anchors or CRLF aware line anchors.
2673 #[inline]
2674 pub fn contains_anchor_lf(&self) -> bool {
2675 self.contains(Look::StartLF) || self.contains(Look::EndLF)
2676 }
2677
2678 /// Returns true if and only if this set contains any "start/end of line"
2679 /// anchors that are CRLF-aware. This doesn't include "start/end of
2680 /// haystack" or "start/end of line-feed" anchors.
2681 #[inline]
2682 pub fn contains_anchor_crlf(&self) -> bool {
2683 self.contains(Look::StartCRLF) || self.contains(Look::EndCRLF)
2684 }
2685
2686 /// Returns true if and only if this set contains any word boundary or
2687 /// negated word boundary assertions. This include both Unicode and ASCII
2688 /// word boundaries.
2689 #[inline]
2690 pub fn contains_word(self) -> bool {
2691 self.contains_word_unicode() || self.contains_word_ascii()
2692 }
2693
2694 /// Returns true if and only if this set contains any Unicode word boundary
2695 /// or negated Unicode word boundary assertions.
2696 #[inline]
2697 pub fn contains_word_unicode(self) -> bool {
2698 self.contains(Look::WordUnicode)
2699 || self.contains(Look::WordUnicodeNegate)
2700 }
2701
2702 /// Returns true if and only if this set contains any ASCII word boundary
2703 /// or negated ASCII word boundary assertions.
2704 #[inline]
2705 pub fn contains_word_ascii(self) -> bool {
2706 self.contains(Look::WordAscii) || self.contains(Look::WordAsciiNegate)
2707 }
2708
2709 /// Returns an iterator over all of the look-around assertions in this set.
2710 #[inline]
2711 pub fn iter(self) -> LookSetIter {
2712 LookSetIter { set: self }
2713 }
2714
2715 /// Return a new set that is equivalent to the original, but with the given
2716 /// assertion added to it. If the assertion is already in the set, then the
2717 /// returned set is equivalent to the original.
2718 #[inline]
2719 pub fn insert(self, look: Look) -> LookSet {
2720 LookSet { bits: self.bits | look.as_repr() }
2721 }
2722
2723 /// Updates this set in place with the result of inserting the given
2724 /// assertion into this set.
2725 #[inline]
2726 pub fn set_insert(&mut self, look: Look) {
2727 *self = self.insert(look);
2728 }
2729
2730 /// Return a new set that is equivalent to the original, but with the given
2731 /// assertion removed from it. If the assertion is not in the set, then the
2732 /// returned set is equivalent to the original.
2733 #[inline]
2734 pub fn remove(self, look: Look) -> LookSet {
2735 LookSet { bits: self.bits & !look.as_repr() }
2736 }
2737
2738 /// Updates this set in place with the result of removing the given
2739 /// assertion from this set.
2740 #[inline]
2741 pub fn set_remove(&mut self, look: Look) {
2742 *self = self.remove(look);
2743 }
2744
2745 /// Returns a new set that is the result of subtracting the given set from
2746 /// this set.
2747 #[inline]
2748 pub fn subtract(self, other: LookSet) -> LookSet {
2749 LookSet { bits: self.bits & !other.bits }
2750 }
2751
2752 /// Updates this set in place with the result of subtracting the given set
2753 /// from this set.
2754 #[inline]
2755 pub fn set_subtract(&mut self, other: LookSet) {
2756 *self = self.subtract(other);
2757 }
2758
2759 /// Returns a new set that is the union of this and the one given.
2760 #[inline]
2761 pub fn union(self, other: LookSet) -> LookSet {
2762 LookSet { bits: self.bits | other.bits }
2763 }
2764
2765 /// Updates this set in place with the result of unioning it with the one
2766 /// given.
2767 #[inline]
2768 pub fn set_union(&mut self, other: LookSet) {
2769 *self = self.union(other);
2770 }
2771
2772 /// Returns a new set that is the intersection of this and the one given.
2773 #[inline]
2774 pub fn intersect(self, other: LookSet) -> LookSet {
2775 LookSet { bits: self.bits & other.bits }
2776 }
2777
2778 /// Updates this set in place with the result of intersecting it with the
2779 /// one given.
2780 #[inline]
2781 pub fn set_intersect(&mut self, other: LookSet) {
2782 *self = self.intersect(other);
2783 }
2784
2785 /// Return a `LookSet` from the slice given as a native endian 16-bit
2786 /// integer.
2787 ///
2788 /// # Panics
2789 ///
2790 /// This panics if `slice.len() < 2`.
2791 #[inline]
2792 pub fn read_repr(slice: &[u8]) -> LookSet {
2793 let bits = u16::from_ne_bytes(slice[..2].try_into().unwrap());
2794 LookSet { bits }
2795 }
2796
2797 /// Write a `LookSet` as a native endian 16-bit integer to the beginning
2798 /// of the slice given.
2799 ///
2800 /// # Panics
2801 ///
2802 /// This panics if `slice.len() < 2`.
2803 #[inline]
2804 pub fn write_repr(self, slice: &mut [u8]) {
2805 let raw = self.bits.to_ne_bytes();
2806 slice[0] = raw[0];
2807 slice[1] = raw[1];
2808 }
2809 }
2810
2811 impl core::fmt::Debug for LookSet {
2812 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2813 if self.is_empty() {
2814 return write!(f, "∅");
2815 }
2816 for look in self.iter() {
2817 write!(f, "{}", look.as_char())?;
2818 }
2819 Ok(())
2820 }
2821 }
2822
2823 /// An iterator over all look-around assertions in a [`LookSet`].
2824 ///
2825 /// This iterator is created by [`LookSet::iter`].
2826 #[derive(Clone, Debug)]
2827 pub struct LookSetIter {
2828 set: LookSet,
2829 }
2830
2831 impl Iterator for LookSetIter {
2832 type Item = Look;
2833
2834 #[inline]
2835 fn next(&mut self) -> Option<Look> {
2836 if self.set.is_empty() {
2837 return None;
2838 }
2839 // We'll never have more than u8::MAX distinct look-around assertions,
2840 // so 'repr' will always fit into a u16.
2841 let repr = u16::try_from(self.set.bits.trailing_zeros()).unwrap();
2842 let look = Look::from_repr(1 << repr)?;
2843 self.set = self.set.remove(look);
2844 Some(look)
2845 }
2846 }
2847
2848 /// Given a sequence of HIR values where each value corresponds to a Unicode
2849 /// class (or an all-ASCII byte class), return a single Unicode class
2850 /// corresponding to the union of the classes found.
2851 fn class_chars(hirs: &[Hir]) -> Option<Class> {
2852 let mut cls = ClassUnicode::new(vec![]);
2853 for hir in hirs.iter() {
2854 match *hir.kind() {
2855 HirKind::Class(Class::Unicode(ref cls2)) => {
2856 cls.union(cls2);
2857 }
2858 HirKind::Class(Class::Bytes(ref cls2)) => {
2859 cls.union(&cls2.to_unicode_class()?);
2860 }
2861 _ => return None,
2862 };
2863 }
2864 Some(Class::Unicode(cls))
2865 }
2866
2867 /// Given a sequence of HIR values where each value corresponds to a byte class
2868 /// (or an all-ASCII Unicode class), return a single byte class corresponding
2869 /// to the union of the classes found.
2870 fn class_bytes(hirs: &[Hir]) -> Option<Class> {
2871 let mut cls = ClassBytes::new(vec![]);
2872 for hir in hirs.iter() {
2873 match *hir.kind() {
2874 HirKind::Class(Class::Unicode(ref cls2)) => {
2875 cls.union(&cls2.to_byte_class()?);
2876 }
2877 HirKind::Class(Class::Bytes(ref cls2)) => {
2878 cls.union(cls2);
2879 }
2880 _ => return None,
2881 };
2882 }
2883 Some(Class::Bytes(cls))
2884 }
2885
2886 /// Given a sequence of HIR values where each value corresponds to a literal
2887 /// that is a single `char`, return that sequence of `char`s. Otherwise return
2888 /// None. No deduplication is done.
2889 fn singleton_chars(hirs: &[Hir]) -> Option<Vec<char>> {
2890 let mut singletons = vec![];
2891 for hir in hirs.iter() {
2892 let literal = match *hir.kind() {
2893 HirKind::Literal(Literal(ref bytes)) => bytes,
2894 _ => return None,
2895 };
2896 let ch = match crate::debug::utf8_decode(literal) {
2897 None => return None,
2898 Some(Err(_)) => return None,
2899 Some(Ok(ch)) => ch,
2900 };
2901 if literal.len() != ch.len_utf8() {
2902 return None;
2903 }
2904 singletons.push(ch);
2905 }
2906 Some(singletons)
2907 }
2908
2909 /// Given a sequence of HIR values where each value corresponds to a literal
2910 /// that is a single byte, return that sequence of bytes. Otherwise return
2911 /// None. No deduplication is done.
2912 fn singleton_bytes(hirs: &[Hir]) -> Option<Vec<u8>> {
2913 let mut singletons = vec![];
2914 for hir in hirs.iter() {
2915 let literal = match *hir.kind() {
2916 HirKind::Literal(Literal(ref bytes)) => bytes,
2917 _ => return None,
2918 };
2919 if literal.len() != 1 {
2920 return None;
2921 }
2922 singletons.push(literal[0]);
2923 }
2924 Some(singletons)
2925 }
2926
2927 /// Looks for a common prefix in the list of alternation branches given. If one
2928 /// is found, then an equivalent but (hopefully) simplified Hir is returned.
2929 /// Otherwise, the original given list of branches is returned unmodified.
2930 ///
2931 /// This is not quite as good as it could be. Right now, it requires that
2932 /// all branches are 'Concat' expressions. It also doesn't do well with
2933 /// literals. For example, given 'foofoo|foobar', it will not refactor it to
2934 /// 'foo(?:foo|bar)' because literals are flattened into their own special
2935 /// concatenation. (One wonders if perhaps 'Literal' should be a single atom
2936 /// instead of a string of bytes because of this. Otherwise, handling the
2937 /// current representation in this routine will be pretty gnarly. Sigh.)
2938 fn lift_common_prefix(hirs: Vec<Hir>) -> Result<Hir, Vec<Hir>> {
2939 if hirs.len() <= 1 {
2940 return Err(hirs);
2941 }
2942 let mut prefix = match hirs[0].kind() {
2943 HirKind::Concat(ref xs) => &**xs,
2944 _ => return Err(hirs),
2945 };
2946 if prefix.is_empty() {
2947 return Err(hirs);
2948 }
2949 for h in hirs.iter().skip(1) {
2950 let concat = match h.kind() {
2951 HirKind::Concat(ref xs) => xs,
2952 _ => return Err(hirs),
2953 };
2954 let common_len = prefix
2955 .iter()
2956 .zip(concat.iter())
2957 .take_while(|(x, y)| x == y)
2958 .count();
2959 prefix = &prefix[..common_len];
2960 if prefix.is_empty() {
2961 return Err(hirs);
2962 }
2963 }
2964 let len = prefix.len();
2965 assert_ne!(0, len);
2966 let mut prefix_concat = vec![];
2967 let mut suffix_alts = vec![];
2968 for h in hirs {
2969 let mut concat = match h.into_kind() {
2970 HirKind::Concat(xs) => xs,
2971 // We required all sub-expressions to be
2972 // concats above, so we're only here if we
2973 // have a concat.
2974 _ => unreachable!(),
2975 };
2976 suffix_alts.push(Hir::concat(concat.split_off(len)));
2977 if prefix_concat.is_empty() {
2978 prefix_concat = concat;
2979 }
2980 }
2981 let mut concat = prefix_concat;
2982 concat.push(Hir::alternation(suffix_alts));
2983 Ok(Hir::concat(concat))
2984 }
2985
2986 #[cfg(test)]
2987 mod tests {
2988 use super::*;
2989
2990 fn uclass(ranges: &[(char, char)]) -> ClassUnicode {
2991 let ranges: Vec<ClassUnicodeRange> = ranges
2992 .iter()
2993 .map(|&(s, e)| ClassUnicodeRange::new(s, e))
2994 .collect();
2995 ClassUnicode::new(ranges)
2996 }
2997
2998 fn bclass(ranges: &[(u8, u8)]) -> ClassBytes {
2999 let ranges: Vec<ClassBytesRange> =
3000 ranges.iter().map(|&(s, e)| ClassBytesRange::new(s, e)).collect();
3001 ClassBytes::new(ranges)
3002 }
3003
3004 fn uranges(cls: &ClassUnicode) -> Vec<(char, char)> {
3005 cls.iter().map(|x| (x.start(), x.end())).collect()
3006 }
3007
3008 #[cfg(feature = "unicode-case")]
3009 fn ucasefold(cls: &ClassUnicode) -> ClassUnicode {
3010 let mut cls_ = cls.clone();
3011 cls_.case_fold_simple();
3012 cls_
3013 }
3014
3015 fn uunion(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode {
3016 let mut cls_ = cls1.clone();
3017 cls_.union(cls2);
3018 cls_
3019 }
3020
3021 fn uintersect(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode {
3022 let mut cls_ = cls1.clone();
3023 cls_.intersect(cls2);
3024 cls_
3025 }
3026
3027 fn udifference(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode {
3028 let mut cls_ = cls1.clone();
3029 cls_.difference(cls2);
3030 cls_
3031 }
3032
3033 fn usymdifference(
3034 cls1: &ClassUnicode,
3035 cls2: &ClassUnicode,
3036 ) -> ClassUnicode {
3037 let mut cls_ = cls1.clone();
3038 cls_.symmetric_difference(cls2);
3039 cls_
3040 }
3041
3042 fn unegate(cls: &ClassUnicode) -> ClassUnicode {
3043 let mut cls_ = cls.clone();
3044 cls_.negate();
3045 cls_
3046 }
3047
3048 fn branges(cls: &ClassBytes) -> Vec<(u8, u8)> {
3049 cls.iter().map(|x| (x.start(), x.end())).collect()
3050 }
3051
3052 fn bcasefold(cls: &ClassBytes) -> ClassBytes {
3053 let mut cls_ = cls.clone();
3054 cls_.case_fold_simple();
3055 cls_
3056 }
3057
3058 fn bunion(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes {
3059 let mut cls_ = cls1.clone();
3060 cls_.union(cls2);
3061 cls_
3062 }
3063
3064 fn bintersect(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes {
3065 let mut cls_ = cls1.clone();
3066 cls_.intersect(cls2);
3067 cls_
3068 }
3069
3070 fn bdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes {
3071 let mut cls_ = cls1.clone();
3072 cls_.difference(cls2);
3073 cls_
3074 }
3075
3076 fn bsymdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes {
3077 let mut cls_ = cls1.clone();
3078 cls_.symmetric_difference(cls2);
3079 cls_
3080 }
3081
3082 fn bnegate(cls: &ClassBytes) -> ClassBytes {
3083 let mut cls_ = cls.clone();
3084 cls_.negate();
3085 cls_
3086 }
3087
3088 #[test]
3089 fn class_range_canonical_unicode() {
3090 let range = ClassUnicodeRange::new('\u{00FF}', '\0');
3091 assert_eq!('\0', range.start());
3092 assert_eq!('\u{00FF}', range.end());
3093 }
3094
3095 #[test]
3096 fn class_range_canonical_bytes() {
3097 let range = ClassBytesRange::new(b'\xFF', b'\0');
3098 assert_eq!(b'\0', range.start());
3099 assert_eq!(b'\xFF', range.end());
3100 }
3101
3102 #[test]
3103 fn class_canonicalize_unicode() {
3104 let cls = uclass(&[('a', 'c'), ('x', 'z')]);
3105 let expected = vec![('a', 'c'), ('x', 'z')];
3106 assert_eq!(expected, uranges(&cls));
3107
3108 let cls = uclass(&[('x', 'z'), ('a', 'c')]);
3109 let expected = vec![('a', 'c'), ('x', 'z')];
3110 assert_eq!(expected, uranges(&cls));
3111
3112 let cls = uclass(&[('x', 'z'), ('w', 'y')]);
3113 let expected = vec![('w', 'z')];
3114 assert_eq!(expected, uranges(&cls));
3115
3116 let cls = uclass(&[
3117 ('c', 'f'),
3118 ('a', 'g'),
3119 ('d', 'j'),
3120 ('a', 'c'),
3121 ('m', 'p'),
3122 ('l', 's'),
3123 ]);
3124 let expected = vec![('a', 'j'), ('l', 's')];
3125 assert_eq!(expected, uranges(&cls));
3126
3127 let cls = uclass(&[('x', 'z'), ('u', 'w')]);
3128 let expected = vec![('u', 'z')];
3129 assert_eq!(expected, uranges(&cls));
3130
3131 let cls = uclass(&[('\x00', '\u{10FFFF}'), ('\x00', '\u{10FFFF}')]);
3132 let expected = vec![('\x00', '\u{10FFFF}')];
3133 assert_eq!(expected, uranges(&cls));
3134
3135 let cls = uclass(&[('a', 'a'), ('b', 'b')]);
3136 let expected = vec![('a', 'b')];
3137 assert_eq!(expected, uranges(&cls));
3138 }
3139
3140 #[test]
3141 fn class_canonicalize_bytes() {
3142 let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]);
3143 let expected = vec![(b'a', b'c'), (b'x', b'z')];
3144 assert_eq!(expected, branges(&cls));
3145
3146 let cls = bclass(&[(b'x', b'z'), (b'a', b'c')]);
3147 let expected = vec![(b'a', b'c'), (b'x', b'z')];
3148 assert_eq!(expected, branges(&cls));
3149
3150 let cls = bclass(&[(b'x', b'z'), (b'w', b'y')]);
3151 let expected = vec![(b'w', b'z')];
3152 assert_eq!(expected, branges(&cls));
3153
3154 let cls = bclass(&[
3155 (b'c', b'f'),
3156 (b'a', b'g'),
3157 (b'd', b'j'),
3158 (b'a', b'c'),
3159 (b'm', b'p'),
3160 (b'l', b's'),
3161 ]);
3162 let expected = vec![(b'a', b'j'), (b'l', b's')];
3163 assert_eq!(expected, branges(&cls));
3164
3165 let cls = bclass(&[(b'x', b'z'), (b'u', b'w')]);
3166 let expected = vec![(b'u', b'z')];
3167 assert_eq!(expected, branges(&cls));
3168
3169 let cls = bclass(&[(b'\x00', b'\xFF'), (b'\x00', b'\xFF')]);
3170 let expected = vec![(b'\x00', b'\xFF')];
3171 assert_eq!(expected, branges(&cls));
3172
3173 let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]);
3174 let expected = vec![(b'a', b'b')];
3175 assert_eq!(expected, branges(&cls));
3176 }
3177
3178 #[test]
3179 #[cfg(feature = "unicode-case")]
3180 fn class_case_fold_unicode() {
3181 let cls = uclass(&[
3182 ('C', 'F'),
3183 ('A', 'G'),
3184 ('D', 'J'),
3185 ('A', 'C'),
3186 ('M', 'P'),
3187 ('L', 'S'),
3188 ('c', 'f'),
3189 ]);
3190 let expected = uclass(&[
3191 ('A', 'J'),
3192 ('L', 'S'),
3193 ('a', 'j'),
3194 ('l', 's'),
3195 ('\u{17F}', '\u{17F}'),
3196 ]);
3197 assert_eq!(expected, ucasefold(&cls));
3198
3199 let cls = uclass(&[('A', 'Z')]);
3200 let expected = uclass(&[
3201 ('A', 'Z'),
3202 ('a', 'z'),
3203 ('\u{17F}', '\u{17F}'),
3204 ('\u{212A}', '\u{212A}'),
3205 ]);
3206 assert_eq!(expected, ucasefold(&cls));
3207
3208 let cls = uclass(&[('a', 'z')]);
3209 let expected = uclass(&[
3210 ('A', 'Z'),
3211 ('a', 'z'),
3212 ('\u{17F}', '\u{17F}'),
3213 ('\u{212A}', '\u{212A}'),
3214 ]);
3215 assert_eq!(expected, ucasefold(&cls));
3216
3217 let cls = uclass(&[('A', 'A'), ('_', '_')]);
3218 let expected = uclass(&[('A', 'A'), ('_', '_'), ('a', 'a')]);
3219 assert_eq!(expected, ucasefold(&cls));
3220
3221 let cls = uclass(&[('A', 'A'), ('=', '=')]);
3222 let expected = uclass(&[('=', '='), ('A', 'A'), ('a', 'a')]);
3223 assert_eq!(expected, ucasefold(&cls));
3224
3225 let cls = uclass(&[('\x00', '\x10')]);
3226 assert_eq!(cls, ucasefold(&cls));
3227
3228 let cls = uclass(&[('k', 'k')]);
3229 let expected =
3230 uclass(&[('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}')]);
3231 assert_eq!(expected, ucasefold(&cls));
3232
3233 let cls = uclass(&[('@', '@')]);
3234 assert_eq!(cls, ucasefold(&cls));
3235 }
3236
3237 #[test]
3238 #[cfg(not(feature = "unicode-case"))]
3239 fn class_case_fold_unicode_disabled() {
3240 let mut cls = uclass(&[
3241 ('C', 'F'),
3242 ('A', 'G'),
3243 ('D', 'J'),
3244 ('A', 'C'),
3245 ('M', 'P'),
3246 ('L', 'S'),
3247 ('c', 'f'),
3248 ]);
3249 assert!(cls.try_case_fold_simple().is_err());
3250 }
3251
3252 #[test]
3253 #[should_panic]
3254 #[cfg(not(feature = "unicode-case"))]
3255 fn class_case_fold_unicode_disabled_panics() {
3256 let mut cls = uclass(&[
3257 ('C', 'F'),
3258 ('A', 'G'),
3259 ('D', 'J'),
3260 ('A', 'C'),
3261 ('M', 'P'),
3262 ('L', 'S'),
3263 ('c', 'f'),
3264 ]);
3265 cls.case_fold_simple();
3266 }
3267
3268 #[test]
3269 fn class_case_fold_bytes() {
3270 let cls = bclass(&[
3271 (b'C', b'F'),
3272 (b'A', b'G'),
3273 (b'D', b'J'),
3274 (b'A', b'C'),
3275 (b'M', b'P'),
3276 (b'L', b'S'),
3277 (b'c', b'f'),
3278 ]);
3279 let expected =
3280 bclass(&[(b'A', b'J'), (b'L', b'S'), (b'a', b'j'), (b'l', b's')]);
3281 assert_eq!(expected, bcasefold(&cls));
3282
3283 let cls = bclass(&[(b'A', b'Z')]);
3284 let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]);
3285 assert_eq!(expected, bcasefold(&cls));
3286
3287 let cls = bclass(&[(b'a', b'z')]);
3288 let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]);
3289 assert_eq!(expected, bcasefold(&cls));
3290
3291 let cls = bclass(&[(b'A', b'A'), (b'_', b'_')]);
3292 let expected = bclass(&[(b'A', b'A'), (b'_', b'_'), (b'a', b'a')]);
3293 assert_eq!(expected, bcasefold(&cls));
3294
3295 let cls = bclass(&[(b'A', b'A'), (b'=', b'=')]);
3296 let expected = bclass(&[(b'=', b'='), (b'A', b'A'), (b'a', b'a')]);
3297 assert_eq!(expected, bcasefold(&cls));
3298
3299 let cls = bclass(&[(b'\x00', b'\x10')]);
3300 assert_eq!(cls, bcasefold(&cls));
3301
3302 let cls = bclass(&[(b'k', b'k')]);
3303 let expected = bclass(&[(b'K', b'K'), (b'k', b'k')]);
3304 assert_eq!(expected, bcasefold(&cls));
3305
3306 let cls = bclass(&[(b'@', b'@')]);
3307 assert_eq!(cls, bcasefold(&cls));
3308 }
3309
3310 #[test]
3311 fn class_negate_unicode() {
3312 let cls = uclass(&[('a', 'a')]);
3313 let expected = uclass(&[('\x00', '\x60'), ('\x62', '\u{10FFFF}')]);
3314 assert_eq!(expected, unegate(&cls));
3315
3316 let cls = uclass(&[('a', 'a'), ('b', 'b')]);
3317 let expected = uclass(&[('\x00', '\x60'), ('\x63', '\u{10FFFF}')]);
3318 assert_eq!(expected, unegate(&cls));
3319
3320 let cls = uclass(&[('a', 'c'), ('x', 'z')]);
3321 let expected = uclass(&[
3322 ('\x00', '\x60'),
3323 ('\x64', '\x77'),
3324 ('\x7B', '\u{10FFFF}'),
3325 ]);
3326 assert_eq!(expected, unegate(&cls));
3327
3328 let cls = uclass(&[('\x00', 'a')]);
3329 let expected = uclass(&[('\x62', '\u{10FFFF}')]);
3330 assert_eq!(expected, unegate(&cls));
3331
3332 let cls = uclass(&[('a', '\u{10FFFF}')]);
3333 let expected = uclass(&[('\x00', '\x60')]);
3334 assert_eq!(expected, unegate(&cls));
3335
3336 let cls = uclass(&[('\x00', '\u{10FFFF}')]);
3337 let expected = uclass(&[]);
3338 assert_eq!(expected, unegate(&cls));
3339
3340 let cls = uclass(&[]);
3341 let expected = uclass(&[('\x00', '\u{10FFFF}')]);
3342 assert_eq!(expected, unegate(&cls));
3343
3344 let cls =
3345 uclass(&[('\x00', '\u{10FFFD}'), ('\u{10FFFF}', '\u{10FFFF}')]);
3346 let expected = uclass(&[('\u{10FFFE}', '\u{10FFFE}')]);
3347 assert_eq!(expected, unegate(&cls));
3348
3349 let cls = uclass(&[('\x00', '\u{D7FF}')]);
3350 let expected = uclass(&[('\u{E000}', '\u{10FFFF}')]);
3351 assert_eq!(expected, unegate(&cls));
3352
3353 let cls = uclass(&[('\x00', '\u{D7FE}')]);
3354 let expected = uclass(&[('\u{D7FF}', '\u{10FFFF}')]);
3355 assert_eq!(expected, unegate(&cls));
3356
3357 let cls = uclass(&[('\u{E000}', '\u{10FFFF}')]);
3358 let expected = uclass(&[('\x00', '\u{D7FF}')]);
3359 assert_eq!(expected, unegate(&cls));
3360
3361 let cls = uclass(&[('\u{E001}', '\u{10FFFF}')]);
3362 let expected = uclass(&[('\x00', '\u{E000}')]);
3363 assert_eq!(expected, unegate(&cls));
3364 }
3365
3366 #[test]
3367 fn class_negate_bytes() {
3368 let cls = bclass(&[(b'a', b'a')]);
3369 let expected = bclass(&[(b'\x00', b'\x60'), (b'\x62', b'\xFF')]);
3370 assert_eq!(expected, bnegate(&cls));
3371
3372 let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]);
3373 let expected = bclass(&[(b'\x00', b'\x60'), (b'\x63', b'\xFF')]);
3374 assert_eq!(expected, bnegate(&cls));
3375
3376 let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]);
3377 let expected = bclass(&[
3378 (b'\x00', b'\x60'),
3379 (b'\x64', b'\x77'),
3380 (b'\x7B', b'\xFF'),
3381 ]);
3382 assert_eq!(expected, bnegate(&cls));
3383
3384 let cls = bclass(&[(b'\x00', b'a')]);
3385 let expected = bclass(&[(b'\x62', b'\xFF')]);
3386 assert_eq!(expected, bnegate(&cls));
3387
3388 let cls = bclass(&[(b'a', b'\xFF')]);
3389 let expected = bclass(&[(b'\x00', b'\x60')]);
3390 assert_eq!(expected, bnegate(&cls));
3391
3392 let cls = bclass(&[(b'\x00', b'\xFF')]);
3393 let expected = bclass(&[]);
3394 assert_eq!(expected, bnegate(&cls));
3395
3396 let cls = bclass(&[]);
3397 let expected = bclass(&[(b'\x00', b'\xFF')]);
3398 assert_eq!(expected, bnegate(&cls));
3399
3400 let cls = bclass(&[(b'\x00', b'\xFD'), (b'\xFF', b'\xFF')]);
3401 let expected = bclass(&[(b'\xFE', b'\xFE')]);
3402 assert_eq!(expected, bnegate(&cls));
3403 }
3404
3405 #[test]
3406 fn class_union_unicode() {
3407 let cls1 = uclass(&[('a', 'g'), ('m', 't'), ('A', 'C')]);
3408 let cls2 = uclass(&[('a', 'z')]);
3409 let expected = uclass(&[('a', 'z'), ('A', 'C')]);
3410 assert_eq!(expected, uunion(&cls1, &cls2));
3411 }
3412
3413 #[test]
3414 fn class_union_bytes() {
3415 let cls1 = bclass(&[(b'a', b'g'), (b'm', b't'), (b'A', b'C')]);
3416 let cls2 = bclass(&[(b'a', b'z')]);
3417 let expected = bclass(&[(b'a', b'z'), (b'A', b'C')]);
3418 assert_eq!(expected, bunion(&cls1, &cls2));
3419 }
3420
3421 #[test]
3422 fn class_intersect_unicode() {
3423 let cls1 = uclass(&[]);
3424 let cls2 = uclass(&[('a', 'a')]);
3425 let expected = uclass(&[]);
3426 assert_eq!(expected, uintersect(&cls1, &cls2));
3427
3428 let cls1 = uclass(&[('a', 'a')]);
3429 let cls2 = uclass(&[('a', 'a')]);
3430 let expected = uclass(&[('a', 'a')]);
3431 assert_eq!(expected, uintersect(&cls1, &cls2));
3432
3433 let cls1 = uclass(&[('a', 'a')]);
3434 let cls2 = uclass(&[('b', 'b')]);
3435 let expected = uclass(&[]);
3436 assert_eq!(expected, uintersect(&cls1, &cls2));
3437
3438 let cls1 = uclass(&[('a', 'a')]);
3439 let cls2 = uclass(&[('a', 'c')]);
3440 let expected = uclass(&[('a', 'a')]);
3441 assert_eq!(expected, uintersect(&cls1, &cls2));
3442
3443 let cls1 = uclass(&[('a', 'b')]);
3444 let cls2 = uclass(&[('a', 'c')]);
3445 let expected = uclass(&[('a', 'b')]);
3446 assert_eq!(expected, uintersect(&cls1, &cls2));
3447
3448 let cls1 = uclass(&[('a', 'b')]);
3449 let cls2 = uclass(&[('b', 'c')]);
3450 let expected = uclass(&[('b', 'b')]);
3451 assert_eq!(expected, uintersect(&cls1, &cls2));
3452
3453 let cls1 = uclass(&[('a', 'b')]);
3454 let cls2 = uclass(&[('c', 'd')]);
3455 let expected = uclass(&[]);
3456 assert_eq!(expected, uintersect(&cls1, &cls2));
3457
3458 let cls1 = uclass(&[('b', 'c')]);
3459 let cls2 = uclass(&[('a', 'd')]);
3460 let expected = uclass(&[('b', 'c')]);
3461 assert_eq!(expected, uintersect(&cls1, &cls2));
3462
3463 let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3464 let cls2 = uclass(&[('a', 'h')]);
3465 let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3466 assert_eq!(expected, uintersect(&cls1, &cls2));
3467
3468 let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3469 let cls2 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3470 let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3471 assert_eq!(expected, uintersect(&cls1, &cls2));
3472
3473 let cls1 = uclass(&[('a', 'b'), ('g', 'h')]);
3474 let cls2 = uclass(&[('d', 'e'), ('k', 'l')]);
3475 let expected = uclass(&[]);
3476 assert_eq!(expected, uintersect(&cls1, &cls2));
3477
3478 let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
3479 let cls2 = uclass(&[('h', 'h')]);
3480 let expected = uclass(&[('h', 'h')]);
3481 assert_eq!(expected, uintersect(&cls1, &cls2));
3482
3483 let cls1 = uclass(&[('a', 'b'), ('e', 'f'), ('i', 'j')]);
3484 let cls2 = uclass(&[('c', 'd'), ('g', 'h'), ('k', 'l')]);
3485 let expected = uclass(&[]);
3486 assert_eq!(expected, uintersect(&cls1, &cls2));
3487
3488 let cls1 = uclass(&[('a', 'b'), ('c', 'd'), ('e', 'f')]);
3489 let cls2 = uclass(&[('b', 'c'), ('d', 'e'), ('f', 'g')]);
3490 let expected = uclass(&[('b', 'f')]);
3491 assert_eq!(expected, uintersect(&cls1, &cls2));
3492 }
3493
3494 #[test]
3495 fn class_intersect_bytes() {
3496 let cls1 = bclass(&[]);
3497 let cls2 = bclass(&[(b'a', b'a')]);
3498 let expected = bclass(&[]);
3499 assert_eq!(expected, bintersect(&cls1, &cls2));
3500
3501 let cls1 = bclass(&[(b'a', b'a')]);
3502 let cls2 = bclass(&[(b'a', b'a')]);
3503 let expected = bclass(&[(b'a', b'a')]);
3504 assert_eq!(expected, bintersect(&cls1, &cls2));
3505
3506 let cls1 = bclass(&[(b'a', b'a')]);
3507 let cls2 = bclass(&[(b'b', b'b')]);
3508 let expected = bclass(&[]);
3509 assert_eq!(expected, bintersect(&cls1, &cls2));
3510
3511 let cls1 = bclass(&[(b'a', b'a')]);
3512 let cls2 = bclass(&[(b'a', b'c')]);
3513 let expected = bclass(&[(b'a', b'a')]);
3514 assert_eq!(expected, bintersect(&cls1, &cls2));
3515
3516 let cls1 = bclass(&[(b'a', b'b')]);
3517 let cls2 = bclass(&[(b'a', b'c')]);
3518 let expected = bclass(&[(b'a', b'b')]);
3519 assert_eq!(expected, bintersect(&cls1, &cls2));
3520
3521 let cls1 = bclass(&[(b'a', b'b')]);
3522 let cls2 = bclass(&[(b'b', b'c')]);
3523 let expected = bclass(&[(b'b', b'b')]);
3524 assert_eq!(expected, bintersect(&cls1, &cls2));
3525
3526 let cls1 = bclass(&[(b'a', b'b')]);
3527 let cls2 = bclass(&[(b'c', b'd')]);
3528 let expected = bclass(&[]);
3529 assert_eq!(expected, bintersect(&cls1, &cls2));
3530
3531 let cls1 = bclass(&[(b'b', b'c')]);
3532 let cls2 = bclass(&[(b'a', b'd')]);
3533 let expected = bclass(&[(b'b', b'c')]);
3534 assert_eq!(expected, bintersect(&cls1, &cls2));
3535
3536 let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3537 let cls2 = bclass(&[(b'a', b'h')]);
3538 let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3539 assert_eq!(expected, bintersect(&cls1, &cls2));
3540
3541 let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3542 let cls2 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3543 let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3544 assert_eq!(expected, bintersect(&cls1, &cls2));
3545
3546 let cls1 = bclass(&[(b'a', b'b'), (b'g', b'h')]);
3547 let cls2 = bclass(&[(b'd', b'e'), (b'k', b'l')]);
3548 let expected = bclass(&[]);
3549 assert_eq!(expected, bintersect(&cls1, &cls2));
3550
3551 let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]);
3552 let cls2 = bclass(&[(b'h', b'h')]);
3553 let expected = bclass(&[(b'h', b'h')]);
3554 assert_eq!(expected, bintersect(&cls1, &cls2));
3555
3556 let cls1 = bclass(&[(b'a', b'b'), (b'e', b'f'), (b'i', b'j')]);
3557 let cls2 = bclass(&[(b'c', b'd'), (b'g', b'h'), (b'k', b'l')]);
3558 let expected = bclass(&[]);
3559 assert_eq!(expected, bintersect(&cls1, &cls2));
3560
3561 let cls1 = bclass(&[(b'a', b'b'), (b'c', b'd'), (b'e', b'f')]);
3562 let cls2 = bclass(&[(b'b', b'c'), (b'd', b'e'), (b'f', b'g')]);
3563 let expected = bclass(&[(b'b', b'f')]);
3564 assert_eq!(expected, bintersect(&cls1, &cls2));
3565 }
3566
3567 #[test]
3568 fn class_difference_unicode() {
3569 let cls1 = uclass(&[('a', 'a')]);
3570 let cls2 = uclass(&[('a', 'a')]);
3571 let expected = uclass(&[]);
3572 assert_eq!(expected, udifference(&cls1, &cls2));
3573
3574 let cls1 = uclass(&[('a', 'a')]);
3575 let cls2 = uclass(&[]);
3576 let expected = uclass(&[('a', 'a')]);
3577 assert_eq!(expected, udifference(&cls1, &cls2));
3578
3579 let cls1 = uclass(&[]);
3580 let cls2 = uclass(&[('a', 'a')]);
3581 let expected = uclass(&[]);
3582 assert_eq!(expected, udifference(&cls1, &cls2));
3583
3584 let cls1 = uclass(&[('a', 'z')]);
3585 let cls2 = uclass(&[('a', 'a')]);
3586 let expected = uclass(&[('b', 'z')]);
3587 assert_eq!(expected, udifference(&cls1, &cls2));
3588
3589 let cls1 = uclass(&[('a', 'z')]);
3590 let cls2 = uclass(&[('z', 'z')]);
3591 let expected = uclass(&[('a', 'y')]);
3592 assert_eq!(expected, udifference(&cls1, &cls2));
3593
3594 let cls1 = uclass(&[('a', 'z')]);
3595 let cls2 = uclass(&[('m', 'm')]);
3596 let expected = uclass(&[('a', 'l'), ('n', 'z')]);
3597 assert_eq!(expected, udifference(&cls1, &cls2));
3598
3599 let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]);
3600 let cls2 = uclass(&[('a', 'z')]);
3601 let expected = uclass(&[]);
3602 assert_eq!(expected, udifference(&cls1, &cls2));
3603
3604 let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]);
3605 let cls2 = uclass(&[('d', 'v')]);
3606 let expected = uclass(&[('a', 'c')]);
3607 assert_eq!(expected, udifference(&cls1, &cls2));
3608
3609 let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]);
3610 let cls2 = uclass(&[('b', 'g'), ('s', 'u')]);
3611 let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]);
3612 assert_eq!(expected, udifference(&cls1, &cls2));
3613
3614 let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]);
3615 let cls2 = uclass(&[('b', 'd'), ('e', 'g'), ('s', 'u')]);
3616 let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]);
3617 assert_eq!(expected, udifference(&cls1, &cls2));
3618
3619 let cls1 = uclass(&[('x', 'z')]);
3620 let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]);
3621 let expected = uclass(&[('x', 'z')]);
3622 assert_eq!(expected, udifference(&cls1, &cls2));
3623
3624 let cls1 = uclass(&[('a', 'z')]);
3625 let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]);
3626 let expected = uclass(&[('d', 'd'), ('h', 'r'), ('v', 'z')]);
3627 assert_eq!(expected, udifference(&cls1, &cls2));
3628 }
3629
3630 #[test]
3631 fn class_difference_bytes() {
3632 let cls1 = bclass(&[(b'a', b'a')]);
3633 let cls2 = bclass(&[(b'a', b'a')]);
3634 let expected = bclass(&[]);
3635 assert_eq!(expected, bdifference(&cls1, &cls2));
3636
3637 let cls1 = bclass(&[(b'a', b'a')]);
3638 let cls2 = bclass(&[]);
3639 let expected = bclass(&[(b'a', b'a')]);
3640 assert_eq!(expected, bdifference(&cls1, &cls2));
3641
3642 let cls1 = bclass(&[]);
3643 let cls2 = bclass(&[(b'a', b'a')]);
3644 let expected = bclass(&[]);
3645 assert_eq!(expected, bdifference(&cls1, &cls2));
3646
3647 let cls1 = bclass(&[(b'a', b'z')]);
3648 let cls2 = bclass(&[(b'a', b'a')]);
3649 let expected = bclass(&[(b'b', b'z')]);
3650 assert_eq!(expected, bdifference(&cls1, &cls2));
3651
3652 let cls1 = bclass(&[(b'a', b'z')]);
3653 let cls2 = bclass(&[(b'z', b'z')]);
3654 let expected = bclass(&[(b'a', b'y')]);
3655 assert_eq!(expected, bdifference(&cls1, &cls2));
3656
3657 let cls1 = bclass(&[(b'a', b'z')]);
3658 let cls2 = bclass(&[(b'm', b'm')]);
3659 let expected = bclass(&[(b'a', b'l'), (b'n', b'z')]);
3660 assert_eq!(expected, bdifference(&cls1, &cls2));
3661
3662 let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]);
3663 let cls2 = bclass(&[(b'a', b'z')]);
3664 let expected = bclass(&[]);
3665 assert_eq!(expected, bdifference(&cls1, &cls2));
3666
3667 let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]);
3668 let cls2 = bclass(&[(b'd', b'v')]);
3669 let expected = bclass(&[(b'a', b'c')]);
3670 assert_eq!(expected, bdifference(&cls1, &cls2));
3671
3672 let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]);
3673 let cls2 = bclass(&[(b'b', b'g'), (b's', b'u')]);
3674 let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]);
3675 assert_eq!(expected, bdifference(&cls1, &cls2));
3676
3677 let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]);
3678 let cls2 = bclass(&[(b'b', b'd'), (b'e', b'g'), (b's', b'u')]);
3679 let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]);
3680 assert_eq!(expected, bdifference(&cls1, &cls2));
3681
3682 let cls1 = bclass(&[(b'x', b'z')]);
3683 let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]);
3684 let expected = bclass(&[(b'x', b'z')]);
3685 assert_eq!(expected, bdifference(&cls1, &cls2));
3686
3687 let cls1 = bclass(&[(b'a', b'z')]);
3688 let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]);
3689 let expected = bclass(&[(b'd', b'd'), (b'h', b'r'), (b'v', b'z')]);
3690 assert_eq!(expected, bdifference(&cls1, &cls2));
3691 }
3692
3693 #[test]
3694 fn class_symmetric_difference_unicode() {
3695 let cls1 = uclass(&[('a', 'm')]);
3696 let cls2 = uclass(&[('g', 't')]);
3697 let expected = uclass(&[('a', 'f'), ('n', 't')]);
3698 assert_eq!(expected, usymdifference(&cls1, &cls2));
3699 }
3700
3701 #[test]
3702 fn class_symmetric_difference_bytes() {
3703 let cls1 = bclass(&[(b'a', b'm')]);
3704 let cls2 = bclass(&[(b'g', b't')]);
3705 let expected = bclass(&[(b'a', b'f'), (b'n', b't')]);
3706 assert_eq!(expected, bsymdifference(&cls1, &cls2));
3707 }
3708
3709 // We use a thread with an explicit stack size to test that our destructor
3710 // for Hir can handle arbitrarily sized expressions in constant stack
3711 // space. In case we run on a platform without threads (WASM?), we limit
3712 // this test to Windows/Unix.
3713 #[test]
3714 #[cfg(any(unix, windows))]
3715 fn no_stack_overflow_on_drop() {
3716 use std::thread;
3717
3718 let run = || {
3719 let mut expr = Hir::empty();
3720 for _ in 0..100 {
3721 expr = Hir::capture(Capture {
3722 index: 1,
3723 name: None,
3724 sub: Box::new(expr),
3725 });
3726 expr = Hir::repetition(Repetition {
3727 min: 0,
3728 max: Some(1),
3729 greedy: true,
3730 sub: Box::new(expr),
3731 });
3732
3733 expr = Hir {
3734 kind: HirKind::Concat(vec![expr]),
3735 props: Properties::empty(),
3736 };
3737 expr = Hir {
3738 kind: HirKind::Alternation(vec![expr]),
3739 props: Properties::empty(),
3740 };
3741 }
3742 assert!(!matches!(*expr.kind(), HirKind::Empty));
3743 };
3744
3745 // We run our test on a thread with a small stack size so we can
3746 // force the issue more easily.
3747 //
3748 // NOTE(2023-03-21): See the corresponding test in 'crate::ast::tests'
3749 // for context on the specific stack size chosen here.
3750 thread::Builder::new()
3751 .stack_size(16 << 10)
3752 .spawn(run)
3753 .unwrap()
3754 .join()
3755 .unwrap();
3756 }
3757
3758 #[test]
3759 fn look_set_iter() {
3760 let set = LookSet::empty();
3761 assert_eq!(0, set.iter().count());
3762
3763 let set = LookSet::full();
3764 assert_eq!(10, set.iter().count());
3765
3766 let set =
3767 LookSet::empty().insert(Look::StartLF).insert(Look::WordUnicode);
3768 assert_eq!(2, set.iter().count());
3769
3770 let set = LookSet::empty().insert(Look::StartLF);
3771 assert_eq!(1, set.iter().count());
3772
3773 let set = LookSet::empty().insert(Look::WordAsciiNegate);
3774 assert_eq!(1, set.iter().count());
3775 }
3776
3777 #[test]
3778 fn look_set_debug() {
3779 let res = format!("{:?}", LookSet::empty());
3780 assert_eq!("∅", res);
3781 let res = format!("{:?}", LookSet::full());
3782 assert_eq!("Az^$rRbB𝛃𝚩", res);
3783 }
3784 }