forked from rust-lang/regex
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathliterals.rs
1504 lines (1391 loc) · 52.9 KB
/
literals.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
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp;
use std::fmt;
use std::iter;
use std::mem;
use std::ops;
use {Expr, CharClass, ClassRange, ByteClass, ByteRange, Repeater};
/// A set of literal byte strings extracted from a regular expression.
///
/// Every member of the set is a `Lit`, which is represented by a `Vec<u8>`.
/// (Notably, it may contain invalid UTF-8.) Every member is said to be either
/// *complete* or *cut*. A complete literal means that it extends until the
/// beginning (or end) of the regular expression. In some circumstances, this
/// can be used to indicate a match in the regular expression.
///
/// Note that a key aspect of literal extraction is knowing when to stop. It is
/// not feasible to blindly extract all literals from a regular expression,
/// even if there are finitely many. For example, the regular expression
/// `[0-9]{10}` has `10^10` distinct literals. For this reason, literal
/// extraction is bounded to some low number by default using heuristics, but
/// the limits can be tweaked.
#[derive(Clone, Eq, PartialEq)]
pub struct Literals {
lits: Vec<Lit>,
limit_size: usize,
limit_class: usize,
}
/// A single member of a set of literals extracted from a regular expression.
///
/// This type has `Deref` and `DerefMut` impls to `Vec<u8>` so that all slice
/// and `Vec` operations are available.
#[derive(Clone, Eq, Ord)]
pub struct Lit {
v: Vec<u8>,
cut: bool,
}
impl Literals {
/// Returns a new empty set of literals using default limits.
pub fn empty() -> Literals {
Literals {
lits: vec![],
limit_size: 250,
limit_class: 10,
}
}
/// Get the approximate size limit (in bytes) of this set.
pub fn limit_size(&self) -> usize {
self.limit_size
}
/// Set the approximate size limit (in bytes) of this set.
///
/// If extracting a literal would put the set over this limit, then
/// extraction stops.
///
/// The new limits will only apply to additions to this set. Existing
/// members remain unchanged, even if the set exceeds the new limit.
pub fn set_limit_size(&mut self, size: usize) -> &mut Literals {
self.limit_size = size;
self
}
/// Get the character class size limit for this set.
pub fn limit_class(&self) -> usize {
self.limit_class
}
/// Limits the size of character(or byte) classes considered.
///
/// A value of `0` prevents all character classes from being considered.
///
/// This limit also applies to case insensitive literals, since each
/// character in the case insensitive literal is converted to a class, and
/// then case folded.
///
/// The new limits will only apply to additions to this set. Existing
/// members remain unchanged, even if the set exceeds the new limit.
pub fn set_limit_class(&mut self, size: usize) -> &mut Literals {
self.limit_class = size;
self
}
/// Returns the set of literals as a slice. Its order is unspecified.
pub fn literals(&self) -> &[Lit] {
&self.lits
}
/// Returns the length of the smallest literal.
///
/// Returns None is there are no literals in the set.
pub fn min_len(&self) -> Option<usize> {
let mut min = None;
for lit in &self.lits {
match min {
None => min = Some(lit.len()),
Some(m) if lit.len() < m => min = Some(lit.len()),
_ => {}
}
}
min
}
/// Returns true if all members in this set are complete.
pub fn all_complete(&self) -> bool {
!self.lits.is_empty() && self.lits.iter().all(|l| !l.is_cut())
}
/// Returns true if any member in this set is complete.
pub fn any_complete(&self) -> bool {
self.lits.iter().any(|lit| !lit.is_cut())
}
/// Returns true if this set contains an empty literal.
pub fn contains_empty(&self) -> bool {
self.lits.iter().any(|lit| lit.is_empty())
}
/// Returns true if this set is empty or if all of its members is empty.
pub fn is_empty(&self) -> bool {
self.lits.is_empty() || self.lits.iter().all(|lit| lit.is_empty())
}
/// Returns a new empty set of literals using this set's limits.
pub fn to_empty(&self) -> Literals {
let mut lits = Literals::empty();
lits.set_limit_size(self.limit_size)
.set_limit_class(self.limit_class);
lits
}
/// Returns the longest common prefix of all members in this set.
pub fn longest_common_prefix(&self) -> &[u8] {
if self.is_empty() {
return &[];
}
let lit0 = &*self.lits[0];
let mut len = lit0.len();
for lit in &self.lits[1..] {
len = cmp::min(
len,
lit.iter()
.zip(lit0)
.take_while(|&(a, b)| a == b)
.count());
}
&self.lits[0][..len]
}
/// Returns the longest common suffix of all members in this set.
pub fn longest_common_suffix(&self) -> &[u8] {
if self.is_empty() {
return &[];
}
let lit0 = &*self.lits[0];
let mut len = lit0.len();
for lit in &self.lits[1..] {
len = cmp::min(
len,
lit.iter()
.rev()
.zip(lit0.iter().rev())
.take_while(|&(a, b)| a == b)
.count());
}
&self.lits[0][self.lits[0].len() - len..]
}
/// Returns a new set of literals with the given number of bytes trimmed
/// from the suffix of each literal.
///
/// If any literal would be cut out completely by trimming, then None is
/// returned.
///
/// Any duplicates that are created as a result of this transformation are
/// removed.
pub fn trim_suffix(&self, num_bytes: usize) -> Option<Literals> {
if self.min_len().map(|len| len <= num_bytes).unwrap_or(true) {
return None;
}
let mut new = self.to_empty();
for mut lit in self.lits.iter().cloned() {
let new_len = lit.len() - num_bytes;
lit.truncate(new_len);
lit.cut();
new.lits.push(lit);
}
new.lits.sort();
new.lits.dedup();
Some(new)
}
/// Returns a new set of prefixes of this set of literals that are
/// guaranteed to be unambiguous.
///
/// Any substring match with a member of the set is returned is guaranteed
/// to never overlap with a substring match of another member of the set
/// at the same starting position.
///
/// Given any two members of the returned set, neither is a substring of
/// the other.
pub fn unambiguous_prefixes(&self) -> Literals {
if self.lits.is_empty() {
return self.to_empty();
}
let mut old: Vec<Lit> = self.lits.iter().cloned().collect();
let mut new = self.to_empty();
'OUTER:
while let Some(mut candidate) = old.pop() {
if candidate.is_empty() {
continue;
}
if new.lits.is_empty() {
new.lits.push(candidate);
continue;
}
for lit2 in &mut new.lits {
if lit2.is_empty() {
continue;
}
if &candidate == lit2 {
// If the literal is already in the set, then we can
// just drop it. But make sure that cut literals are
// infectious!
candidate.cut = candidate.cut || lit2.cut;
lit2.cut = candidate.cut;
continue 'OUTER;
}
if candidate.len() < lit2.len() {
if let Some(i) = position(&candidate, &lit2) {
candidate.cut();
let mut lit3 = lit2.clone();
lit3.truncate(i);
lit3.cut();
old.push(lit3);
lit2.clear();
}
} else {
if let Some(i) = position(&lit2, &candidate) {
lit2.cut();
let mut new_candidate = candidate.clone();
new_candidate.truncate(i);
new_candidate.cut();
old.push(new_candidate);
candidate.clear();
}
}
// Oops, the candidate is already represented in the set.
if candidate.is_empty() {
continue 'OUTER;
}
}
new.lits.push(candidate);
}
new.lits.retain(|lit| !lit.is_empty());
new.lits.sort();
new.lits.dedup();
new
}
/// Returns a new set of suffixes of this set of literals that are
/// guaranteed to be unambiguous.
///
/// Any substring match with a member of the set is returned is guaranteed
/// to never overlap with a substring match of another member of the set
/// at the same ending position.
///
/// Given any two members of the returned set, neither is a substring of
/// the other.
pub fn unambiguous_suffixes(&self) -> Literals {
// This is a touch wasteful...
let mut lits = self.clone();
lits.reverse();
let mut unamb = lits.unambiguous_prefixes();
unamb.reverse();
unamb
}
/// Unions the prefixes from the given expression to this set.
///
/// If prefixes could not be added (for example, this set would exceed its
/// size limits or the set of prefixes from `expr` includes the empty
/// string), then false is returned.
///
/// Note that prefix literals extracted from `expr` are said to be complete
/// if and only if the literal extends from the beginning of `expr` to the
/// end of `expr`.
pub fn union_prefixes(&mut self, expr: &Expr) -> bool {
let mut lits = self.to_empty();
prefixes(expr, &mut lits);
!lits.is_empty() && !lits.contains_empty() && self.union(lits)
}
/// Unions the suffixes from the given expression to this set.
///
/// If suffixes could not be added (for example, this set would exceed its
/// size limits or the set of suffixes from `expr` includes the empty
/// string), then false is returned.
///
/// Note that prefix literals extracted from `expr` are said to be complete
/// if and only if the literal extends from the end of `expr` to the
/// beginning of `expr`.
pub fn union_suffixes(&mut self, expr: &Expr) -> bool {
let mut lits = self.to_empty();
suffixes(expr, &mut lits);
lits.reverse();
!lits.is_empty() && !lits.contains_empty() && self.union(lits)
}
/// Unions this set with another set.
///
/// If the union would cause the set to exceed its limits, then the union
/// is skipped and it returns false. Otherwise, if the union succeeds, it
/// returns true.
pub fn union(&mut self, lits: Literals) -> bool {
if self.num_bytes() + lits.num_bytes() > self.limit_size {
return false;
}
if lits.is_empty() {
self.lits.push(Lit::empty());
} else {
self.lits.extend(lits.lits);
}
true
}
/// Extends this set with another set.
///
/// The set of literals is extended via a cross product.
///
/// If a cross product would cause this set to exceed its limits, then the
/// cross product is skipped and it returns false. Otherwise, if the cross
/// product succeeds, it returns true.
pub fn cross_product(&mut self, lits: &Literals) -> bool {
if lits.is_empty() {
return true;
}
// Check that we make sure we stay in our limits.
let mut size_after;
if self.is_empty() || !self.any_complete() {
size_after = self.num_bytes();
for lits_lit in lits.literals() {
size_after += lits_lit.len();
}
} else {
size_after = self.lits.iter().fold(0, |accum, lit| {
accum + if lit.is_cut() { lit.len() } else { 0 }
});
for lits_lit in lits.literals() {
for self_lit in self.literals() {
if !self_lit.is_cut() {
size_after += self_lit.len() + lits_lit.len();
}
}
}
}
if size_after > self.limit_size {
return false;
}
let mut base = self.remove_complete();
if base.is_empty() {
base = vec![Lit::empty()];
}
for lits_lit in lits.literals() {
for mut self_lit in base.clone() {
self_lit.extend(&**lits_lit);
self_lit.cut = lits_lit.cut;
self.lits.push(self_lit);
}
}
true
}
/// Extends each literal in this set with the bytes given.
///
/// If the set is empty, then the given literal is added to the set.
///
/// If adding any number of bytes to all members of this set causes a limit
/// to be exceeded, then no bytes are added and false is returned. If a
/// prefix of `bytes` can be fit into this set, then it is used and all
/// resulting literals are cut.
pub fn cross_add(&mut self, bytes: &[u8]) -> bool {
// N.B. This could be implemented by simply calling cross_product with
// a literal set containing just `bytes`, but we can be smarter about
// taking shorter prefixes of `bytes` if they'll fit.
if bytes.is_empty() {
return true;
}
if self.lits.is_empty() {
let i = cmp::min(self.limit_size, bytes.len());
self.lits.push(Lit::new(bytes[..i].to_owned()));
self.lits[0].cut = i < bytes.len();
return !self.lits[0].is_cut();
}
let size = self.num_bytes();
if size + self.lits.len() >= self.limit_size {
return false;
}
let mut i = 1;
while size + (i * self.lits.len()) <= self.limit_size
&& i < bytes.len() {
i += 1;
}
for lit in &mut self.lits {
if !lit.is_cut() {
lit.extend(&bytes[..i]);
if i < bytes.len() {
lit.cut();
}
}
}
true
}
/// Adds the given literal to this set.
///
/// Returns false if adding this literal would cause the class to be too
/// big.
pub fn add(&mut self, lit: Lit) -> bool {
if self.num_bytes() + lit.len() > self.limit_size {
return false;
}
self.lits.push(lit);
true
}
/// Extends each literal in this set with the character class given.
///
/// Returns false if the character class was too big to add.
pub fn add_char_class(&mut self, cls: &CharClass) -> bool {
self._add_char_class(cls, false)
}
/// Extends each literal in this set with the character class given,
/// writing the bytes of each character in reverse.
///
/// Returns false if the character class was too big to add.
fn add_char_class_reverse(&mut self, cls: &CharClass) -> bool {
self._add_char_class(cls, true)
}
fn _add_char_class(&mut self, cls: &CharClass, reverse: bool) -> bool {
use std::char;
if self.class_exceeds_limits(cls.num_chars()) {
return false;
}
let mut base = self.remove_complete();
if base.is_empty() {
base = vec![Lit::empty()];
}
for r in cls {
let (s, e) = (r.start as u32, r.end as u32 + 1);
for c in (s..e).filter_map(char::from_u32) {
for mut lit in base.clone() {
let mut bytes = c.to_string().into_bytes();
if reverse {
bytes.reverse();
}
lit.extend(&bytes);
self.lits.push(lit);
}
}
}
true
}
/// Extends each literal in this set with the byte class given.
///
/// Returns false if the byte class was too big to add.
pub fn add_byte_class(&mut self, cls: &ByteClass) -> bool {
if self.class_exceeds_limits(cls.num_bytes()) {
return false;
}
let mut base = self.remove_complete();
if base.is_empty() {
base = vec![Lit::empty()];
}
for r in cls {
let (s, e) = (r.start as u32, r.end as u32 + 1);
for b in (s..e).map(|b| b as u8) {
for mut lit in base.clone() {
lit.push(b);
self.lits.push(lit);
}
}
}
true
}
/// Cuts every member of this set. When a member is cut, it can never
/// be extended.
pub fn cut(&mut self) {
for lit in &mut self.lits {
lit.cut();
}
}
/// Reverses all members in place.
pub fn reverse(&mut self) {
for lit in &mut self.lits {
lit.reverse();
}
}
/// Clears this set of all members.
pub fn clear(&mut self) {
self.lits.clear();
}
/// Pops all complete literals out of this set.
fn remove_complete(&mut self) -> Vec<Lit> {
let mut base = vec![];
for lit in mem::replace(&mut self.lits, vec![]) {
if lit.is_cut() {
self.lits.push(lit);
} else {
base.push(lit);
}
}
base
}
/// Returns the total number of bytes in this set.
fn num_bytes(&self) -> usize {
self.lits.iter().fold(0, |accum, lit| accum + lit.len())
}
/// Returns true if a character class with the given size would cause this
/// set to exceed its limits.
///
/// The size given should correspond to the number of items in the class.
fn class_exceeds_limits(&self, size: usize) -> bool {
if size > self.limit_class {
return true;
}
// This is an approximation since codepoints in a char class can encode
// to 1-4 bytes.
let new_byte_count =
if self.lits.is_empty() {
size
} else {
self.lits
.iter()
.fold(0, |accum, lit| {
accum + if lit.is_cut() {
// If the literal is cut, then we'll never add
// anything to it, so don't count it.
0
} else {
(lit.len() + 1) * size
}
})
};
new_byte_count > self.limit_size
}
}
fn prefixes(expr: &Expr, lits: &mut Literals) {
use Expr::*;
match *expr {
Literal { ref chars, casei: false } => {
let s: String = chars.iter().cloned().collect();
lits.cross_add(s.as_bytes());
}
Literal { ref chars, casei: true } => {
for &c in chars {
let cls = CharClass::new(vec![
ClassRange { start: c, end: c },
]).case_fold();
if !lits.add_char_class(&cls) {
lits.cut();
return;
}
}
}
LiteralBytes { ref bytes, casei: false } => {
lits.cross_add(bytes);
}
LiteralBytes { ref bytes, casei: true } => {
for &b in bytes {
let cls = ByteClass::new(vec![
ByteRange { start: b, end: b },
]).case_fold();
if !lits.add_byte_class(&cls) {
lits.cut();
return;
}
}
}
Class(ref cls) => {
if !lits.add_char_class(cls) {
lits.cut();
}
}
ClassBytes(ref cls) => {
if !lits.add_byte_class(cls) {
lits.cut();
}
}
Group { ref e, .. } => {
prefixes(&**e, lits);
}
Repeat { ref e, r: Repeater::ZeroOrOne, .. } => {
repeat_zero_or_one_literals(&**e, lits, prefixes);
}
Repeat { ref e, r: Repeater::ZeroOrMore, .. } => {
repeat_zero_or_more_literals(&**e, lits, prefixes);
}
Repeat { ref e, r: Repeater::OneOrMore, .. } => {
repeat_one_or_more_literals(&**e, lits, prefixes);
}
Repeat { ref e, r: Repeater::Range { min, max }, greedy } => {
repeat_range_literals(&**e, min, max, greedy, lits, prefixes);
}
Concat(ref es) if es.is_empty() => {}
Concat(ref es) if es.len() == 1 => prefixes(&es[0], lits),
Concat(ref es) => {
for e in es {
if let StartText = *e {
if !lits.is_empty() {
lits.cut();
break;
}
lits.add(Lit::empty());
continue;
}
let mut lits2 = lits.to_empty();
prefixes(e, &mut lits2);
if !lits.cross_product(&lits2) || !lits2.any_complete() {
// If this expression couldn't yield any literal that
// could be extended, then we need to quit. Since we're
// short-circuiting, we also need to freeze every member.
lits.cut();
break;
}
}
}
Alternate(ref es) => {
alternate_literals(es, lits, prefixes);
}
_ => lits.cut(),
}
}
fn suffixes(expr: &Expr, lits: &mut Literals) {
use Expr::*;
match *expr {
Literal { ref chars, casei: false } => {
let s: String = chars.iter().cloned().collect();
let mut bytes = s.into_bytes();
bytes.reverse();
lits.cross_add(&bytes);
}
Literal { ref chars, casei: true } => {
for &c in chars.iter().rev() {
let cls = CharClass::new(vec![
ClassRange { start: c, end: c },
]).case_fold();
if !lits.add_char_class_reverse(&cls) {
lits.cut();
return;
}
}
}
LiteralBytes { ref bytes, casei: false } => {
let b: Vec<u8> = bytes.iter().rev().cloned().collect();
lits.cross_add(&b);
}
LiteralBytes { ref bytes, casei: true } => {
for &b in bytes.iter().rev() {
let cls = ByteClass::new(vec![
ByteRange { start: b, end: b },
]).case_fold();
if !lits.add_byte_class(&cls) {
lits.cut();
return;
}
}
}
Class(ref cls) => {
if !lits.add_char_class_reverse(cls) {
lits.cut();
}
}
ClassBytes(ref cls) => {
if !lits.add_byte_class(cls) {
lits.cut();
}
}
Group { ref e, .. } => {
suffixes(&**e, lits);
}
Repeat { ref e, r: Repeater::ZeroOrOne, .. } => {
repeat_zero_or_one_literals(&**e, lits, suffixes);
}
Repeat { ref e, r: Repeater::ZeroOrMore, .. } => {
repeat_zero_or_more_literals(&**e, lits, suffixes);
}
Repeat { ref e, r: Repeater::OneOrMore, .. } => {
repeat_one_or_more_literals(&**e, lits, suffixes);
}
Repeat { ref e, r: Repeater::Range { min, max }, greedy } => {
repeat_range_literals(&**e, min, max, greedy, lits, suffixes);
}
Concat(ref es) if es.is_empty() => {}
Concat(ref es) if es.len() == 1 => suffixes(&es[0], lits),
Concat(ref es) => {
for e in es.iter().rev() {
if let EndText = *e {
if !lits.is_empty() {
lits.cut();
break;
}
lits.add(Lit::empty());
continue;
}
let mut lits2 = lits.to_empty();
suffixes(e, &mut lits2);
if !lits.cross_product(&lits2) || !lits2.any_complete() {
// If this expression couldn't yield any literal that
// could be extended, then we need to quit. Since we're
// short-circuiting, we also need to freeze every member.
lits.cut();
break;
}
}
}
Alternate(ref es) => {
alternate_literals(es, lits, suffixes);
}
_ => lits.cut(),
}
}
fn repeat_zero_or_one_literals<F: FnMut(&Expr, &mut Literals)>(
e: &Expr,
lits: &mut Literals,
mut f: F,
) {
let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty());
lits3.set_limit_size(lits.limit_size() / 2);
f(e, &mut lits3);
if lits3.is_empty() || !lits2.cross_product(&lits3) {
lits.cut();
return;
}
lits2.add(Lit::empty());
if !lits.union(lits2) {
lits.cut();
}
}
fn repeat_zero_or_more_literals<F: FnMut(&Expr, &mut Literals)>(
e: &Expr,
lits: &mut Literals,
mut f: F,
) {
let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty());
lits3.set_limit_size(lits.limit_size() / 2);
f(e, &mut lits3);
if lits3.is_empty() || !lits2.cross_product(&lits3) {
lits.cut();
return;
}
lits2.cut();
lits2.add(Lit::empty());
if !lits.union(lits2) {
lits.cut();
}
}
fn repeat_one_or_more_literals<F: FnMut(&Expr, &mut Literals)>(
e: &Expr,
lits: &mut Literals,
mut f: F,
) {
f(e, lits);
lits.cut();
}
fn repeat_range_literals<F: FnMut(&Expr, &mut Literals)>(
e: &Expr,
min: u32,
max: Option<u32>,
greedy: bool,
lits: &mut Literals,
mut f: F,
) {
use Expr::*;
if min == 0 {
// This is a bit conservative. If `max` is set, then we could
// treat this as a finite set of alternations. For now, we
// just treat it as `e*`.
f(&Repeat {
e: Box::new(e.clone()),
r: Repeater::ZeroOrMore,
greedy: greedy,
}, lits);
} else {
if min > 0 {
let n = cmp::min(lits.limit_size, min as usize);
let es = iter::repeat(e.clone()).take(n).collect();
f(&Concat(es), lits);
if n < min as usize || lits.contains_empty() {
lits.cut();
}
}
if max.map_or(true, |max| min < max) {
lits.cut();
}
}
}
fn alternate_literals<F: FnMut(&Expr, &mut Literals)>(
es: &[Expr],
lits: &mut Literals,
mut f: F,
) {
let mut lits2 = lits.to_empty();
for e in es {
let mut lits3 = lits.to_empty();
lits3.set_limit_size(lits.limit_size() / 5);
f(e, &mut lits3);
if lits3.is_empty() || !lits2.union(lits3) {
// If we couldn't find suffixes for *any* of the
// alternates, then the entire alternation has to be thrown
// away and any existing members must be frozen. Similarly,
// if the union couldn't complete, stop and freeze.
lits.cut();
return;
}
}
if !lits.cross_product(&lits2) {
lits.cut();
}
}
impl fmt::Debug for Literals {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Literals")
.field("lits", &self.lits)
.field("limit_size", &self.limit_size)
.field("limit_class", &self.limit_class)
.finish()
}
}
impl Lit {
/// Returns a new complete literal with the bytes given.
pub fn new(bytes: Vec<u8>) -> Lit {
Lit { v: bytes, cut: false }
}
/// Returns a new complete empty literal.
pub fn empty() -> Lit {
Lit { v: vec![], cut: false }
}
/// Returns true if this literal was "cut."
pub fn is_cut(&self) -> bool {
self.cut
}
/// Cuts this literal.
pub fn cut(&mut self) {
self.cut = true;
}
}
impl PartialEq for Lit {
fn eq(&self, other: &Lit) -> bool {
self.v == other.v
}
}
impl PartialOrd for Lit {
fn partial_cmp(&self, other: &Lit) -> Option<cmp::Ordering> {
self.v.partial_cmp(&other.v)
}
}
impl fmt::Debug for Lit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_cut() {
write!(f, "Cut({})", escape_unicode(&self.v))
} else {
write!(f, "Complete({})", escape_unicode(&self.v))
}
}
}
impl AsRef<[u8]> for Lit {
fn as_ref(&self) -> &[u8] { &self.v }
}
impl ops::Deref for Lit {
type Target = Vec<u8>;
fn deref(&self) -> &Vec<u8> { &self.v }
}
impl ops::DerefMut for Lit {
fn deref_mut(&mut self) -> &mut Vec<u8> { &mut self.v }
}
fn position(needle: &[u8], mut haystack: &[u8]) -> Option<usize> {
let mut i = 0;
while haystack.len() >= needle.len() {
if needle == &haystack[..needle.len()] {
return Some(i);
}
i += 1;
haystack = &haystack[1..];
}
None
}
fn escape_unicode(bytes: &[u8]) -> String {
let show = match ::std::str::from_utf8(bytes) {
Ok(v) => v.to_string(),
Err(_) => escape_bytes(bytes),
};
let mut space_escaped = String::new();
for c in show.chars() {
if c.is_whitespace() {
let escaped = if c as u32 <= 0x7F {
escape_byte(c as u8)
} else {
if c as u32 <= 0xFFFF {
format!(r"\u{{{:04x}}}", c as u32)
} else {
format!(r"\U{{{:08x}}}", c as u32)
}
};
space_escaped.push_str(&escaped);
} else {
space_escaped.push(c);
}
}
space_escaped
}
fn escape_bytes(bytes: &[u8]) -> String {
let mut s = String::new();
for &b in bytes {
s.push_str(&escape_byte(b));
}
s
}
fn escape_byte(byte: u8) -> String {
use std::ascii::escape_default;
let escaped: Vec<u8> = escape_default(byte).collect();
String::from_utf8_lossy(&escaped).into_owned()
}
#[cfg(test)]
mod tests {
use std::fmt;
use {Expr, ExprBuilder};
use super::{Literals, Lit, escape_bytes};
// To make test failures easier to read.
#[derive(Debug, Eq, PartialEq)]
struct Bytes(Vec<ULit>);
#[derive(Debug, Eq, PartialEq)]
struct Unicode(Vec<ULit>);
fn escape_lits(blits: &[Lit]) -> Vec<ULit> {
let mut ulits = vec![];
for blit in blits {
ulits.push(ULit { v: escape_bytes(&blit), cut: blit.is_cut() });
}
ulits
}
fn create_lits<I: IntoIterator<Item=Lit>>(it: I) -> Literals {
Literals {
lits: it.into_iter().collect(),
limit_size: 0,
limit_class: 0,