-
Notifications
You must be signed in to change notification settings - Fork 446
/
mod.rs
2296 lines (2033 loc) · 80.8 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
Defines a high-level intermediate representation for regular expressions.
*/
use std::char;
use std::cmp;
use std::error;
use std::fmt;
use std::result;
use std::u8;
use crate::ast::Span;
use crate::hir::interval::{Interval, IntervalSet, IntervalSetIter};
use crate::unicode;
pub use crate::hir::visitor::{visit, Visitor};
pub use crate::unicode::CaseFoldError;
mod interval;
pub mod literal;
pub mod print;
pub mod translate;
mod visitor;
/// An error that can occur while translating an `Ast` to a `Hir`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
/// The kind of error.
kind: ErrorKind,
/// The original pattern that the translator's Ast was parsed from. Every
/// span in an error is a valid range into this string.
pattern: String,
/// The span of this error, derived from the Ast given to the translator.
span: Span,
}
impl Error {
/// Return the type of this error.
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
/// The original pattern string in which this error occurred.
///
/// Every span reported by this error is reported in terms of this string.
pub fn pattern(&self) -> &str {
&self.pattern
}
/// Return the span at which this error occurred.
pub fn span(&self) -> &Span {
&self.span
}
}
/// The type of an error that occurred while building an `Hir`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
/// This error occurs when a Unicode feature is used when Unicode
/// support is disabled. For example `(?-u:\pL)` would trigger this error.
UnicodeNotAllowed,
/// This error occurs when translating a pattern that could match a byte
/// sequence that isn't UTF-8 and `allow_invalid_utf8` was disabled.
InvalidUtf8,
/// This occurs when an unrecognized Unicode property name could not
/// be found.
UnicodePropertyNotFound,
/// This occurs when an unrecognized Unicode property value could not
/// be found.
UnicodePropertyValueNotFound,
/// This occurs when a Unicode-aware Perl character class (`\w`, `\s` or
/// `\d`) could not be found. This can occur when the `unicode-perl`
/// crate feature is not enabled.
UnicodePerlClassNotFound,
/// This occurs when the Unicode simple case mapping tables are not
/// available, and the regular expression required Unicode aware case
/// insensitivity.
UnicodeCaseUnavailable,
/// This occurs when the translator attempts to construct a character class
/// that is empty.
///
/// Note that this restriction in the translator may be removed in the
/// future.
EmptyClassNotAllowed,
/// Hints that destructuring should not be exhaustive.
///
/// This enum may grow additional variants, so this makes sure clients
/// don't count on exhaustive matching. (Otherwise, adding a new variant
/// could break existing code.)
#[doc(hidden)]
__Nonexhaustive,
}
impl ErrorKind {
// TODO: Remove this method entirely on the next breaking semver release.
#[allow(deprecated)]
fn description(&self) -> &str {
use self::ErrorKind::*;
match *self {
UnicodeNotAllowed => "Unicode not allowed here",
InvalidUtf8 => "pattern can match invalid UTF-8",
UnicodePropertyNotFound => "Unicode property not found",
UnicodePropertyValueNotFound => "Unicode property value not found",
UnicodePerlClassNotFound => {
"Unicode-aware Perl class not found \
(make sure the unicode-perl feature is enabled)"
}
UnicodeCaseUnavailable => {
"Unicode-aware case insensitivity matching is not available \
(make sure the unicode-case feature is enabled)"
}
EmptyClassNotAllowed => "empty character classes are not allowed",
__Nonexhaustive => unreachable!(),
}
}
}
impl error::Error for Error {
// TODO: Remove this method entirely on the next breaking semver release.
#[allow(deprecated)]
fn description(&self) -> &str {
self.kind.description()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
crate::error::Formatter::from(self).fmt(f)
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Remove this on the next breaking semver release.
#[allow(deprecated)]
f.write_str(self.description())
}
}
/// A high-level intermediate representation (HIR) for a regular expression.
///
/// The HIR of a regular expression represents an intermediate step between its
/// abstract syntax (a structured description of the concrete syntax) and
/// compiled byte codes. The purpose of HIR is to make regular expressions
/// easier to analyze. In particular, the AST is much more complex than the
/// HIR. For example, while an AST supports arbitrarily nested character
/// classes, the HIR will flatten all nested classes into a single set. The HIR
/// will also "compile away" every flag present in the concrete syntax. For
/// example, users of HIR expressions never need to worry about case folding;
/// it is handled automatically by the translator (e.g., by translating `(?i)A`
/// to `[aA]`).
///
/// If the HIR was produced by a translator that disallows invalid UTF-8, then
/// the HIR is guaranteed to match UTF-8 exclusively.
///
/// This type defines its own destructor that uses constant stack space and
/// heap space proportional to the size of the HIR.
///
/// The specific type of an HIR expression can be accessed via its `kind`
/// or `into_kind` methods. This extra level of indirection exists for two
/// reasons:
///
/// 1. Construction of an HIR expression *must* use the constructor methods
/// on this `Hir` type instead of building the `HirKind` values directly.
/// This permits construction to enforce invariants like "concatenations
/// always consist of two or more sub-expressions."
/// 2. Every HIR expression contains attributes that are defined inductively,
/// and can be computed cheaply during the construction process. For
/// example, one such attribute is whether the expression must match at the
/// beginning of the text.
///
/// Also, an `Hir`'s `fmt::Display` implementation prints an HIR as a regular
/// expression pattern string, and uses constant stack space and heap space
/// proportional to the size of the `Hir`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Hir {
/// The underlying HIR kind.
kind: HirKind,
/// Analysis info about this HIR, computed during construction.
info: HirInfo,
}
/// The kind of an arbitrary `Hir` expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HirKind {
/// The empty regular expression, which matches everything, including the
/// empty string.
Empty,
/// A single literal character that matches exactly this character.
Literal(Literal),
/// A single character class that matches any of the characters in the
/// class. A class can either consist of Unicode scalar values as
/// characters, or it can use bytes.
Class(Class),
/// An anchor assertion. An anchor assertion match always has zero length.
Anchor(Anchor),
/// A word boundary assertion, which may or may not be Unicode aware. A
/// word boundary assertion match always has zero length.
WordBoundary(WordBoundary),
/// A repetition operation applied to a child expression.
Repetition(Repetition),
/// A possibly capturing group, which contains a child expression.
Group(Group),
/// A concatenation of expressions. A concatenation always has at least two
/// child expressions.
///
/// A concatenation matches only if each of its child expression matches
/// one after the other.
Concat(Vec<Hir>),
/// An alternation of expressions. An alternation always has at least two
/// child expressions.
///
/// An alternation matches only if at least one of its child expression
/// matches. If multiple expressions match, then the leftmost is preferred.
Alternation(Vec<Hir>),
}
impl Hir {
/// Returns a reference to the underlying HIR kind.
pub fn kind(&self) -> &HirKind {
&self.kind
}
/// Consumes ownership of this HIR expression and returns its underlying
/// `HirKind`.
pub fn into_kind(mut self) -> HirKind {
use std::mem;
mem::replace(&mut self.kind, HirKind::Empty)
}
/// Returns an empty HIR expression.
///
/// An empty HIR expression always matches, including the empty string.
pub fn empty() -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(true);
info.set_all_assertions(true);
info.set_anchored_start(false);
info.set_anchored_end(false);
info.set_line_anchored_start(false);
info.set_line_anchored_end(false);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(true);
info.set_literal(false);
info.set_alternation_literal(false);
Hir { kind: HirKind::Empty, info }
}
/// Creates a literal HIR expression.
///
/// If the given literal has a `Byte` variant with an ASCII byte, then this
/// method panics. This enforces the invariant that `Byte` variants are
/// only used to express matching of invalid UTF-8.
pub fn literal(lit: Literal) -> Hir {
if let Literal::Byte(b) = lit {
assert!(b > 0x7F);
}
let mut info = HirInfo::new();
info.set_always_utf8(lit.is_unicode());
info.set_all_assertions(false);
info.set_anchored_start(false);
info.set_anchored_end(false);
info.set_line_anchored_start(false);
info.set_line_anchored_end(false);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(false);
info.set_literal(true);
info.set_alternation_literal(true);
Hir { kind: HirKind::Literal(lit), info }
}
/// Creates a class HIR expression.
pub fn class(class: Class) -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(class.is_always_utf8());
info.set_all_assertions(false);
info.set_anchored_start(false);
info.set_anchored_end(false);
info.set_line_anchored_start(false);
info.set_line_anchored_end(false);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(false);
info.set_literal(false);
info.set_alternation_literal(false);
Hir { kind: HirKind::Class(class), info }
}
/// Creates an anchor assertion HIR expression.
pub fn anchor(anchor: Anchor) -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(true);
info.set_all_assertions(true);
info.set_anchored_start(false);
info.set_anchored_end(false);
info.set_line_anchored_start(false);
info.set_line_anchored_end(false);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(true);
info.set_literal(false);
info.set_alternation_literal(false);
if let Anchor::StartText = anchor {
info.set_anchored_start(true);
info.set_line_anchored_start(true);
info.set_any_anchored_start(true);
}
if let Anchor::EndText = anchor {
info.set_anchored_end(true);
info.set_line_anchored_end(true);
info.set_any_anchored_end(true);
}
if let Anchor::StartLine = anchor {
info.set_line_anchored_start(true);
}
if let Anchor::EndLine = anchor {
info.set_line_anchored_end(true);
}
Hir { kind: HirKind::Anchor(anchor), info }
}
/// Creates a word boundary assertion HIR expression.
pub fn word_boundary(word_boundary: WordBoundary) -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(true);
info.set_all_assertions(true);
info.set_anchored_start(false);
info.set_anchored_end(false);
info.set_line_anchored_start(false);
info.set_line_anchored_end(false);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_literal(false);
info.set_alternation_literal(false);
// A negated word boundary matches '', so that's fine. But \b does not
// match \b, so why do we say it can match the empty string? Well,
// because, if you search for \b against 'a', it will report [0, 0) and
// [1, 1) as matches, and both of those matches correspond to the empty
// string. Thus, only *certain* empty strings match \b, which similarly
// applies to \B.
info.set_match_empty(true);
// Negated ASCII word boundaries can match invalid UTF-8.
if let WordBoundary::AsciiNegate = word_boundary {
info.set_always_utf8(false);
}
Hir { kind: HirKind::WordBoundary(word_boundary), info }
}
/// Creates a repetition HIR expression.
pub fn repetition(rep: Repetition) -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(rep.hir.is_always_utf8());
info.set_all_assertions(rep.hir.is_all_assertions());
// If this operator can match the empty string, then it can never
// be anchored.
info.set_anchored_start(
!rep.is_match_empty() && rep.hir.is_anchored_start(),
);
info.set_anchored_end(
!rep.is_match_empty() && rep.hir.is_anchored_end(),
);
info.set_line_anchored_start(
!rep.is_match_empty() && rep.hir.is_anchored_start(),
);
info.set_line_anchored_end(
!rep.is_match_empty() && rep.hir.is_anchored_end(),
);
info.set_any_anchored_start(rep.hir.is_any_anchored_start());
info.set_any_anchored_end(rep.hir.is_any_anchored_end());
info.set_match_empty(rep.is_match_empty() || rep.hir.is_match_empty());
info.set_literal(false);
info.set_alternation_literal(false);
Hir { kind: HirKind::Repetition(rep), info }
}
/// Creates a group HIR expression.
pub fn group(group: Group) -> Hir {
let mut info = HirInfo::new();
info.set_always_utf8(group.hir.is_always_utf8());
info.set_all_assertions(group.hir.is_all_assertions());
info.set_anchored_start(group.hir.is_anchored_start());
info.set_anchored_end(group.hir.is_anchored_end());
info.set_line_anchored_start(group.hir.is_line_anchored_start());
info.set_line_anchored_end(group.hir.is_line_anchored_end());
info.set_any_anchored_start(group.hir.is_any_anchored_start());
info.set_any_anchored_end(group.hir.is_any_anchored_end());
info.set_match_empty(group.hir.is_match_empty());
info.set_literal(false);
info.set_alternation_literal(false);
Hir { kind: HirKind::Group(group), info }
}
/// Returns the concatenation of the given expressions.
///
/// This flattens the concatenation as appropriate.
pub fn concat(mut exprs: Vec<Hir>) -> Hir {
match exprs.len() {
0 => Hir::empty(),
1 => exprs.pop().unwrap(),
_ => {
let mut info = HirInfo::new();
info.set_always_utf8(true);
info.set_all_assertions(true);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(true);
info.set_literal(true);
info.set_alternation_literal(true);
// Some attributes require analyzing all sub-expressions.
for e in &exprs {
let x = info.is_always_utf8() && e.is_always_utf8();
info.set_always_utf8(x);
let x = info.is_all_assertions() && e.is_all_assertions();
info.set_all_assertions(x);
let x = info.is_any_anchored_start()
|| e.is_any_anchored_start();
info.set_any_anchored_start(x);
let x =
info.is_any_anchored_end() || e.is_any_anchored_end();
info.set_any_anchored_end(x);
let x = info.is_match_empty() && e.is_match_empty();
info.set_match_empty(x);
let x = info.is_literal() && e.is_literal();
info.set_literal(x);
let x = info.is_alternation_literal()
&& e.is_alternation_literal();
info.set_alternation_literal(x);
}
// Anchored attributes require something slightly more
// sophisticated. Normally, WLOG, to determine whether an
// expression is anchored to the start, we'd only need to check
// the first expression of a concatenation. However,
// expressions like `$\b^` are still anchored to the start,
// but the first expression in the concatenation *isn't*
// anchored to the start. So the "first" expression to look at
// is actually one that is either not an assertion or is
// specifically the StartText assertion.
info.set_anchored_start(
exprs
.iter()
.take_while(|e| {
e.is_anchored_start() || e.is_all_assertions()
})
.any(|e| e.is_anchored_start()),
);
// Similarly for the end anchor, but in reverse.
info.set_anchored_end(
exprs
.iter()
.rev()
.take_while(|e| {
e.is_anchored_end() || e.is_all_assertions()
})
.any(|e| e.is_anchored_end()),
);
// Repeat the process for line anchors.
info.set_line_anchored_start(
exprs
.iter()
.take_while(|e| {
e.is_line_anchored_start() || e.is_all_assertions()
})
.any(|e| e.is_line_anchored_start()),
);
info.set_line_anchored_end(
exprs
.iter()
.rev()
.take_while(|e| {
e.is_line_anchored_end() || e.is_all_assertions()
})
.any(|e| e.is_line_anchored_end()),
);
Hir { kind: HirKind::Concat(exprs), info }
}
}
}
/// Returns the alternation of the given expressions.
///
/// This flattens the alternation as appropriate.
pub fn alternation(mut exprs: Vec<Hir>) -> Hir {
match exprs.len() {
0 => Hir::empty(),
1 => exprs.pop().unwrap(),
_ => {
let mut info = HirInfo::new();
info.set_always_utf8(true);
info.set_all_assertions(true);
info.set_anchored_start(true);
info.set_anchored_end(true);
info.set_line_anchored_start(true);
info.set_line_anchored_end(true);
info.set_any_anchored_start(false);
info.set_any_anchored_end(false);
info.set_match_empty(false);
info.set_literal(false);
info.set_alternation_literal(true);
// Some attributes require analyzing all sub-expressions.
for e in &exprs {
let x = info.is_always_utf8() && e.is_always_utf8();
info.set_always_utf8(x);
let x = info.is_all_assertions() && e.is_all_assertions();
info.set_all_assertions(x);
let x = info.is_anchored_start() && e.is_anchored_start();
info.set_anchored_start(x);
let x = info.is_anchored_end() && e.is_anchored_end();
info.set_anchored_end(x);
let x = info.is_line_anchored_start()
&& e.is_line_anchored_start();
info.set_line_anchored_start(x);
let x = info.is_line_anchored_end()
&& e.is_line_anchored_end();
info.set_line_anchored_end(x);
let x = info.is_any_anchored_start()
|| e.is_any_anchored_start();
info.set_any_anchored_start(x);
let x =
info.is_any_anchored_end() || e.is_any_anchored_end();
info.set_any_anchored_end(x);
let x = info.is_match_empty() || e.is_match_empty();
info.set_match_empty(x);
let x = info.is_alternation_literal() && e.is_literal();
info.set_alternation_literal(x);
}
Hir { kind: HirKind::Alternation(exprs), info }
}
}
}
/// Build an HIR expression for `.`.
///
/// A `.` expression matches any character except for `\n`. To build an
/// expression that matches any character, including `\n`, use the `any`
/// method.
///
/// If `bytes` is `true`, then this assumes characters are limited to a
/// single byte.
pub fn dot(bytes: bool) -> Hir {
if bytes {
let mut cls = ClassBytes::empty();
cls.push(ClassBytesRange::new(b'\0', b'\x09'));
cls.push(ClassBytesRange::new(b'\x0B', b'\xFF'));
Hir::class(Class::Bytes(cls))
} else {
let mut cls = ClassUnicode::empty();
cls.push(ClassUnicodeRange::new('\0', '\x09'));
cls.push(ClassUnicodeRange::new('\x0B', '\u{10FFFF}'));
Hir::class(Class::Unicode(cls))
}
}
/// Build an HIR expression for `(?s).`.
///
/// A `(?s).` expression matches any character, including `\n`. To build an
/// expression that matches any character except for `\n`, then use the
/// `dot` method.
///
/// If `bytes` is `true`, then this assumes characters are limited to a
/// single byte.
pub fn any(bytes: bool) -> Hir {
if bytes {
let mut cls = ClassBytes::empty();
cls.push(ClassBytesRange::new(b'\0', b'\xFF'));
Hir::class(Class::Bytes(cls))
} else {
let mut cls = ClassUnicode::empty();
cls.push(ClassUnicodeRange::new('\0', '\u{10FFFF}'));
Hir::class(Class::Unicode(cls))
}
}
/// Return true if and only if this HIR will always match valid UTF-8.
///
/// When this returns false, then it is possible for this HIR expression
/// to match invalid UTF-8.
pub fn is_always_utf8(&self) -> bool {
self.info.is_always_utf8()
}
/// Returns true if and only if this entire HIR expression is made up of
/// zero-width assertions.
///
/// This includes expressions like `^$\b\A\z` and even `((\b)+())*^`, but
/// not `^a`.
pub fn is_all_assertions(&self) -> bool {
self.info.is_all_assertions()
}
/// Return true if and only if this HIR is required to match from the
/// beginning of text. This includes expressions like `^foo`, `^(foo|bar)`,
/// `^foo|^bar` but not `^foo|bar`.
pub fn is_anchored_start(&self) -> bool {
self.info.is_anchored_start()
}
/// Return true if and only if this HIR is required to match at the end
/// of text. This includes expressions like `foo$`, `(foo|bar)$`,
/// `foo$|bar$` but not `foo$|bar`.
pub fn is_anchored_end(&self) -> bool {
self.info.is_anchored_end()
}
/// Return true if and only if this HIR is required to match from the
/// beginning of text or the beginning of a line. This includes expressions
/// like `^foo`, `(?m)^foo`, `^(foo|bar)`, `^(foo|bar)`, `(?m)^foo|^bar`
/// but not `^foo|bar` or `(?m)^foo|bar`.
///
/// Note that if `is_anchored_start` is `true`, then
/// `is_line_anchored_start` will also be `true`. The reverse implication
/// is not true. For example, `(?m)^foo` is line anchored, but not
/// `is_anchored_start`.
pub fn is_line_anchored_start(&self) -> bool {
self.info.is_line_anchored_start()
}
/// Return true if and only if this HIR is required to match at the
/// end of text or the end of a line. This includes expressions like
/// `foo$`, `(?m)foo$`, `(foo|bar)$`, `(?m)(foo|bar)$`, `foo$|bar$`,
/// `(?m)(foo|bar)$`, but not `foo$|bar` or `(?m)foo$|bar`.
///
/// Note that if `is_anchored_end` is `true`, then
/// `is_line_anchored_end` will also be `true`. The reverse implication
/// is not true. For example, `(?m)foo$` is line anchored, but not
/// `is_anchored_end`.
pub fn is_line_anchored_end(&self) -> bool {
self.info.is_line_anchored_end()
}
/// Return true if and only if this HIR contains any sub-expression that
/// is required to match at the beginning of text. Specifically, this
/// returns true if the `^` symbol (when multiline mode is disabled) or the
/// `\A` escape appear anywhere in the regex.
pub fn is_any_anchored_start(&self) -> bool {
self.info.is_any_anchored_start()
}
/// Return true if and only if this HIR contains any sub-expression that is
/// required to match at the end of text. Specifically, this returns true
/// if the `$` symbol (when multiline mode is disabled) or the `\z` escape
/// appear anywhere in the regex.
pub fn is_any_anchored_end(&self) -> bool {
self.info.is_any_anchored_end()
}
/// Return true if and only if the empty string is part of the language
/// matched by this regular expression.
///
/// This includes `a*`, `a?b*`, `a{0}`, `()`, `()+`, `^$`, `a|b?`, `\b`
/// and `\B`, but not `a` or `a+`.
pub fn is_match_empty(&self) -> bool {
self.info.is_match_empty()
}
/// Return true if and only if this HIR is a simple literal. This is only
/// true when this HIR expression is either itself a `Literal` or a
/// concatenation of only `Literal`s.
///
/// For example, `f` and `foo` are literals, but `f+`, `(foo)`, `foo()`,
/// `` are not (even though that contain sub-expressions that are literals).
pub fn is_literal(&self) -> bool {
self.info.is_literal()
}
/// Return true if and only if this HIR is either a simple literal or an
/// alternation of simple literals. This is only
/// true when this HIR expression is either itself a `Literal` or a
/// concatenation of only `Literal`s or an alternation of only `Literal`s.
///
/// For example, `f`, `foo`, `a|b|c`, and `foo|bar|baz` are alternation
/// literals, but `f+`, `(foo)`, `foo()`, ``
/// are not (even though that contain sub-expressions that are literals).
pub fn is_alternation_literal(&self) -> bool {
self.info.is_alternation_literal()
}
}
impl HirKind {
/// Return true if and only if this HIR is the empty regular expression.
///
/// Note that this is not defined inductively. That is, it only tests if
/// this kind is the `Empty` variant. To get the inductive definition,
/// use the `is_match_empty` method on [`Hir`](struct.Hir.html).
pub fn is_empty(&self) -> bool {
match *self {
HirKind::Empty => true,
_ => false,
}
}
/// Returns true if and only if this kind has any (including possibly
/// empty) subexpressions.
pub fn has_subexprs(&self) -> bool {
match *self {
HirKind::Empty
| HirKind::Literal(_)
| HirKind::Class(_)
| HirKind::Anchor(_)
| HirKind::WordBoundary(_) => false,
HirKind::Group(_)
| HirKind::Repetition(_)
| HirKind::Concat(_)
| HirKind::Alternation(_) => true,
}
}
}
/// Print a display representation of this Hir.
///
/// The result of this is a valid regular expression pattern string.
///
/// This implementation uses constant stack space and heap space proportional
/// to the size of the `Hir`.
impl fmt::Display for Hir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::hir::print::Printer;
Printer::new().print(self, f)
}
}
/// The high-level intermediate representation of a literal.
///
/// A literal corresponds to a single character, where a character is either
/// defined by a Unicode scalar value or an arbitrary byte. Unicode characters
/// are preferred whenever possible. In particular, a `Byte` variant is only
/// ever produced when it could match invalid UTF-8.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Literal {
/// A single character represented by a Unicode scalar value.
Unicode(char),
/// A single character represented by an arbitrary byte.
Byte(u8),
}
impl Literal {
/// Returns true if and only if this literal corresponds to a Unicode
/// scalar value.
pub fn is_unicode(&self) -> bool {
match *self {
Literal::Unicode(_) => true,
Literal::Byte(b) if b <= 0x7F => true,
Literal::Byte(_) => false,
}
}
}
/// The high-level intermediate representation of a character class.
///
/// A character class corresponds to a set of characters. A character is either
/// defined by a Unicode scalar value or a byte. Unicode characters are used
/// by default, while bytes are used when Unicode mode (via the `u` flag) is
/// disabled.
///
/// A character class, regardless of its character type, is represented by a
/// sequence of non-overlapping non-adjacent ranges of characters.
///
/// Note that unlike [`Literal`](enum.Literal.html), a `Bytes` variant may
/// be produced even when it exclusively matches valid UTF-8. This is because
/// a `Bytes` variant represents an intention by the author of the regular
/// expression to disable Unicode mode, which in turn impacts the semantics of
/// case insensitive matching. For example, `(?i)k` and `(?i-u)k` will not
/// match the same set of strings.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Class {
/// A set of characters represented by Unicode scalar values.
Unicode(ClassUnicode),
/// A set of characters represented by arbitrary bytes (one byte per
/// character).
Bytes(ClassBytes),
}
impl Class {
/// Apply Unicode simple case folding to this character class, in place.
/// The character class will be expanded to include all simple case folded
/// character variants.
///
/// If this is a byte oriented character class, then this will be limited
/// to the ASCII ranges `A-Z` and `a-z`.
pub fn case_fold_simple(&mut self) {
match *self {
Class::Unicode(ref mut x) => x.case_fold_simple(),
Class::Bytes(ref mut x) => x.case_fold_simple(),
}
}
/// Negate this character class in place.
///
/// After completion, this character class will contain precisely the
/// characters that weren't previously in the class.
pub fn negate(&mut self) {
match *self {
Class::Unicode(ref mut x) => x.negate(),
Class::Bytes(ref mut x) => x.negate(),
}
}
/// Returns true if and only if this character class will only ever match
/// valid UTF-8.
///
/// A character class can match invalid UTF-8 only when the following
/// conditions are met:
///
/// 1. The translator was configured to permit generating an expression
/// that can match invalid UTF-8. (By default, this is disabled.)
/// 2. Unicode mode (via the `u` flag) was disabled either in the concrete
/// syntax or in the parser builder. By default, Unicode mode is
/// enabled.
pub fn is_always_utf8(&self) -> bool {
match *self {
Class::Unicode(_) => true,
Class::Bytes(ref x) => x.is_all_ascii(),
}
}
}
/// A set of characters represented by Unicode scalar values.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassUnicode {
set: IntervalSet<ClassUnicodeRange>,
}
impl ClassUnicode {
/// Create a new class from a sequence of ranges.
///
/// The given ranges do not need to be in any specific order, and ranges
/// may overlap.
pub fn new<I>(ranges: I) -> ClassUnicode
where
I: IntoIterator<Item = ClassUnicodeRange>,
{
ClassUnicode { set: IntervalSet::new(ranges) }
}
/// Create a new class with no ranges.
pub fn empty() -> ClassUnicode {
ClassUnicode::new(vec![])
}
/// Add a new range to this set.
pub fn push(&mut self, range: ClassUnicodeRange) {
self.set.push(range);
}
/// Return an iterator over all ranges in this class.
///
/// The iterator yields ranges in ascending order.
pub fn iter(&self) -> ClassUnicodeIter<'_> {
ClassUnicodeIter(self.set.iter())
}
/// Return the underlying ranges as a slice.
pub fn ranges(&self) -> &[ClassUnicodeRange] {
self.set.intervals()
}
/// Expand this character class such that it contains all case folded
/// characters, according to Unicode's "simple" mapping. For example, if
/// this class consists of the range `a-z`, then applying case folding will
/// result in the class containing both the ranges `a-z` and `A-Z`.
///
/// # Panics
///
/// This routine panics when the case mapping data necessary for this
/// routine to complete is unavailable. This occurs when the `unicode-case`
/// feature is not enabled.
///
/// Callers should prefer using `try_case_fold_simple` instead, which will
/// return an error instead of panicking.
pub fn case_fold_simple(&mut self) {
self.set
.case_fold_simple()
.expect("unicode-case feature must be enabled");
}
/// Expand this character class such that it contains all case folded
/// characters, according to Unicode's "simple" mapping. For example, if
/// this class consists of the range `a-z`, then applying case folding will
/// result in the class containing both the ranges `a-z` and `A-Z`.
///
/// # Error
///
/// This routine returns an error when the case mapping data necessary
/// for this routine to complete is unavailable. This occurs when the
/// `unicode-case` feature is not enabled.
pub fn try_case_fold_simple(
&mut self,
) -> result::Result<(), CaseFoldError> {
self.set.case_fold_simple()
}
/// Negate this character class.
///
/// For all `c` where `c` is a Unicode scalar value, if `c` was in this
/// set, then it will not be in this set after negation.
pub fn negate(&mut self) {
self.set.negate();
}
/// Union this character class with the given character class, in place.
pub fn union(&mut self, other: &ClassUnicode) {
self.set.union(&other.set);
}
/// Intersect this character class with the given character class, in
/// place.
pub fn intersect(&mut self, other: &ClassUnicode) {
self.set.intersect(&other.set);
}
/// Subtract the given character class from this character class, in place.
pub fn difference(&mut self, other: &ClassUnicode) {
self.set.difference(&other.set);
}
/// Compute the symmetric difference of the given character classes, in
/// place.
///
/// This computes the symmetric difference of two character classes. This
/// removes all elements in this class that are also in the given class,
/// but all adds all elements from the given class that aren't in this
/// class. That is, the class will contain all elements in either class,
/// but will not contain any elements that are in both classes.
pub fn symmetric_difference(&mut self, other: &ClassUnicode) {
self.set.symmetric_difference(&other.set);
}
/// Returns true if and only if this character class will either match
/// nothing or only ASCII bytes. Stated differently, this returns false
/// if and only if this class contains a non-ASCII codepoint.
pub fn is_all_ascii(&self) -> bool {
self.set.intervals().last().map_or(true, |r| r.end <= '\x7F')
}
}
/// An iterator over all ranges in a Unicode character class.
///
/// The lifetime `'a` refers to the lifetime of the underlying class.
#[derive(Debug)]
pub struct ClassUnicodeIter<'a>(IntervalSetIter<'a, ClassUnicodeRange>);
impl<'a> Iterator for ClassUnicodeIter<'a> {
type Item = &'a ClassUnicodeRange;
fn next(&mut self) -> Option<&'a ClassUnicodeRange> {
self.0.next()
}
}
/// A single range of characters represented by Unicode scalar values.
///
/// The range is closed. That is, the start and end of the range are included
/// in the range.
#[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct ClassUnicodeRange {
start: char,
end: char,
}
impl fmt::Debug for ClassUnicodeRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let start = if !self.start.is_whitespace() && !self.start.is_control()
{
self.start.to_string()
} else {
format!("0x{:X}", self.start as u32)
};
let end = if !self.end.is_whitespace() && !self.end.is_control() {
self.end.to_string()
} else {
format!("0x{:X}", self.end as u32)
};
f.debug_struct("ClassUnicodeRange")
.field("start", &start)
.field("end", &end)
.finish()
}
}
impl Interval for ClassUnicodeRange {
type Bound = char;