-
Notifications
You must be signed in to change notification settings - Fork 452
/
Copy pathdfa.rs
1942 lines (1817 loc) · 73.4 KB
/
dfa.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
/*!
The DFA matching engine.
A DFA provides faster matching because the engine is in exactly one state at
any point in time. In the NFA, there may be multiple active states, and
considerable CPU cycles are spent shuffling them around. In finite automata
speak, the DFA follows epsilon transitions in the regex far less than the NFA.
A DFA is a classic trade off between time and space. The NFA is slower, but
its memory requirements are typically small and predictable. The DFA is faster,
but given the right regex and the right input, the number of states in the
DFA can grow exponentially. To mitigate this space problem, we do two things:
1. We implement an *online* DFA. That is, the DFA is constructed from the NFA
during a search. When a new state is computed, it is stored in a cache so
that it may be reused. An important consequence of this implementation
is that states that are never reached for a particular input are never
computed. (This is impossible in an "offline" DFA which needs to compute
all possible states up front.)
2. If the cache gets too big, we wipe it and continue matching.
In pathological cases, a new state can be created for every byte of input.
(e.g., The regex `(a|b)*a(a|b){20}` on a long sequence of a's and b's.)
In this case, performance regresses to slightly slower than the full NFA
simulation, in large part because the cache becomes useless. If the cache
is wiped too frequently, the DFA quits and control falls back to one of the
NFA simulations.
Because of the "lazy" nature of this DFA, the inner matching loop is
considerably more complex than one might expect out of a DFA. A number of
tricks are employed to make it fast. Tread carefully.
N.B. While this implementation is heavily commented, Russ Cox's series of
articles on regexes is strongly recommended: https://swtch.com/~rsc/regexp/
(As is the DFA implementation in RE2, which heavily influenced this
implementation.)
*/
use std::collections::HashMap;
use std::fmt;
use std::iter::repeat;
use std::mem;
use std::sync::Arc;
use exec::ProgramCache;
use prog::{Inst, Program};
use sparse::SparseSet;
/// Return true if and only if the given program can be executed by a DFA.
///
/// Generally, a DFA is always possible. A pathological case where it is not
/// possible is if the number of NFA states exceeds `u32::MAX`, in which case,
/// this function will return false.
///
/// This function will also return false if the given program has any Unicode
/// instructions (Char or Ranges) since the DFA operates on bytes only.
pub fn can_exec(insts: &Program) -> bool {
use prog::Inst::*;
// If for some reason we manage to allocate a regex program with more
// than i32::MAX instructions, then we can't execute the DFA because we
// use 32 bit instruction pointer deltas for memory savings.
// If i32::MAX is the largest positive delta,
// then -i32::MAX == i32::MIN + 1 is the largest negative delta,
// and we are OK to use 32 bits.
if insts.dfa_size_limit == 0 || insts.len() > ::std::i32::MAX as usize {
return false;
}
for inst in insts {
match *inst {
Char(_) | Ranges(_) => return false,
EmptyLook(_) | Match(_) | Save(_) | Split(_) | Bytes(_) => {}
}
}
true
}
/// A reusable cache of DFA states.
///
/// This cache is reused between multiple invocations of the same regex
/// program. (It is not shared simultaneously between threads. If there is
/// contention, then new caches are created.)
#[derive(Debug)]
pub struct Cache {
/// Group persistent DFA related cache state together. The sparse sets
/// listed below are used as scratch space while computing uncached states.
inner: CacheInner,
/// qcur and qnext are ordered sets with constant time
/// addition/membership/clearing-whole-set and linear time iteration. They
/// are used to manage the sets of NFA states in DFA states when computing
/// cached DFA states. In particular, the order of the NFA states matters
/// for leftmost-first style matching. Namely, when computing a cached
/// state, the set of NFA states stops growing as soon as the first Match
/// instruction is observed.
qcur: SparseSet,
qnext: SparseSet,
}
/// `CacheInner` is logically just a part of Cache, but groups together fields
/// that aren't passed as function parameters throughout search. (This split
/// is mostly an artifact of the borrow checker. It is happily paid.)
#[derive(Debug)]
struct CacheInner {
/// A cache of pre-compiled DFA states, keyed by the set of NFA states
/// and the set of empty-width flags set at the byte in the input when the
/// state was observed.
///
/// A StatePtr is effectively a `*State`, but to avoid various inconvenient
/// things, we just pass indexes around manually. The performance impact of
/// this is probably an instruction or two in the inner loop. However, on
/// 64 bit, each StatePtr is half the size of a *State.
compiled: StateMap,
/// The transition table.
///
/// The transition table is laid out in row-major order, where states are
/// rows and the transitions for each state are columns. At a high level,
/// given state `s` and byte `b`, the next state can be found at index
/// `s * 256 + b`.
///
/// This is, of course, a lie. A StatePtr is actually a pointer to the
/// *start* of a row in this table. When indexing in the DFA's inner loop,
/// this removes the need to multiply the StatePtr by the stride. Yes, it
/// matters. This reduces the number of states we can store, but: the
/// stride is rarely 256 since we define transitions in terms of
/// *equivalence classes* of bytes. Each class corresponds to a set of
/// bytes that never discriminate a distinct path through the DFA from each
/// other.
trans: Transitions,
/// A set of cached start states, which are limited to the number of
/// permutations of flags set just before the initial byte of input. (The
/// index into this vec is a `EmptyFlags`.)
///
/// N.B. A start state can be "dead" (i.e., no possible match), so we
/// represent it with a StatePtr.
start_states: Vec<StatePtr>,
/// Stack scratch space used to follow epsilon transitions in the NFA.
/// (This permits us to avoid recursion.)
///
/// The maximum stack size is the number of NFA states.
stack: Vec<InstPtr>,
/// The total number of times this cache has been flushed by the DFA
/// because of space constraints.
flush_count: u64,
/// The total heap size of the DFA's cache. We use this to determine when
/// we should flush the cache.
size: usize,
/// Scratch space used when building instruction pointer lists for new
/// states. This helps amortize allocation.
insts_scratch_space: Vec<u8>,
}
/// The transition table.
///
/// It is laid out in row-major order, with states as rows and byte class
/// transitions as columns.
///
/// The transition table is responsible for producing valid `StatePtrs`. A
/// `StatePtr` points to the start of a particular row in this table. When
/// indexing to find the next state this allows us to avoid a multiplication
/// when computing an index into the table.
#[derive(Clone)]
struct Transitions {
/// The table.
table: Vec<StatePtr>,
/// The stride.
num_byte_classes: usize,
}
/// Fsm encapsulates the actual execution of the DFA.
#[derive(Debug)]
pub struct Fsm<'a> {
/// prog contains the NFA instruction opcodes. DFA execution uses either
/// the `dfa` instructions or the `dfa_reverse` instructions from
/// `exec::ExecReadOnly`. (It never uses `ExecReadOnly.nfa`, which may have
/// Unicode opcodes that cannot be executed by the DFA.)
prog: &'a Program,
/// The start state. We record it here because the pointer may change
/// when the cache is wiped.
start: StatePtr,
/// The current position in the input.
at: usize,
/// Should we quit after seeing the first match? e.g., When the caller
/// uses `is_match` or `shortest_match`.
quit_after_match: bool,
/// The last state that matched.
///
/// When no match has occurred, this is set to STATE_UNKNOWN.
///
/// This is only useful when matching regex sets. The last match state
/// is useful because it contains all of the match instructions seen,
/// thereby allowing us to enumerate which regexes in the set matched.
last_match_si: StatePtr,
/// The input position of the last cache flush. We use this to determine
/// if we're thrashing in the cache too often. If so, the DFA quits so
/// that we can fall back to the NFA algorithm.
last_cache_flush: usize,
/// All cached DFA information that is persisted between searches.
cache: &'a mut CacheInner,
}
/// The result of running the DFA.
///
/// Generally, the result is either a match or not a match, but sometimes the
/// DFA runs too slowly because the cache size is too small. In that case, it
/// gives up with the intent of falling back to the NFA algorithm.
///
/// The DFA can also give up if it runs out of room to create new states, or if
/// it sees non-ASCII bytes in the presence of a Unicode word boundary.
#[derive(Clone, Debug)]
pub enum Result<T> {
Match(T),
NoMatch(usize),
Quit,
}
impl<T> Result<T> {
/// Returns true if this result corresponds to a match.
pub fn is_match(&self) -> bool {
match *self {
Result::Match(_) => true,
Result::NoMatch(_) | Result::Quit => false,
}
}
/// Maps the given function onto T and returns the result.
///
/// If this isn't a match, then this is a no-op.
#[cfg(feature = "perf-literal")]
pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> Result<U> {
match self {
Result::Match(t) => Result::Match(f(t)),
Result::NoMatch(x) => Result::NoMatch(x),
Result::Quit => Result::Quit,
}
}
/// Sets the non-match position.
///
/// If this isn't a non-match, then this is a no-op.
fn set_non_match(self, at: usize) -> Result<T> {
match self {
Result::NoMatch(_) => Result::NoMatch(at),
r => r,
}
}
}
/// `State` is a DFA state. It contains an ordered set of NFA states (not
/// necessarily complete) and a smattering of flags.
///
/// The flags are packed into the first byte of data.
///
/// States don't carry their transitions. Instead, transitions are stored in
/// a single row-major table.
///
/// Delta encoding is used to store the instruction pointers.
/// The first instruction pointer is stored directly starting
/// at data[1], and each following pointer is stored as an offset
/// to the previous one. If a delta is in the range -127..127,
/// it is packed into a single byte; Otherwise the byte 128 (-128 as an i8)
/// is coded as a flag, followed by 4 bytes encoding the delta.
#[derive(Clone, Eq, Hash, PartialEq)]
struct State {
data: Arc<[u8]>,
}
/// `InstPtr` is a 32 bit pointer into a sequence of opcodes (i.e., it indexes
/// an NFA state).
///
/// Throughout this library, this is usually set to `usize`, but we force a
/// `u32` here for the DFA to save on space.
type InstPtr = u32;
/// Adds ip to data using delta encoding with respect to prev.
///
/// After completion, `data` will contain `ip` and `prev` will be set to `ip`.
fn push_inst_ptr(data: &mut Vec<u8>, prev: &mut InstPtr, ip: InstPtr) {
let delta = (ip as i32) - (*prev as i32);
write_vari32(data, delta);
*prev = ip;
}
struct InstPtrs<'a> {
base: usize,
data: &'a [u8],
}
impl<'a> Iterator for InstPtrs<'a> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if self.data.is_empty() {
return None;
}
let (delta, nread) = read_vari32(self.data);
let base = self.base as i32 + delta;
debug_assert!(base >= 0);
debug_assert!(nread > 0);
self.data = &self.data[nread..];
self.base = base as usize;
Some(self.base)
}
}
impl State {
fn flags(&self) -> StateFlags {
StateFlags(self.data[0])
}
fn inst_ptrs(&self) -> InstPtrs {
InstPtrs { base: 0, data: &self.data[1..] }
}
}
/// `StatePtr` is a 32 bit pointer to the start of a row in the transition
/// table.
///
/// It has many special values. There are two types of special values:
/// sentinels and flags.
///
/// Sentinels corresponds to special states that carry some kind of
/// significance. There are three such states: unknown, dead and quit states.
///
/// Unknown states are states that haven't been computed yet. They indicate
/// that a transition should be filled in that points to either an existing
/// cached state or a new state altogether. In general, an unknown state means
/// "follow the NFA's epsilon transitions."
///
/// Dead states are states that can never lead to a match, no matter what
/// subsequent input is observed. This means that the DFA should quit
/// immediately and return the longest match it has found thus far.
///
/// Quit states are states that imply the DFA is not capable of matching the
/// regex correctly. Currently, this is only used when a Unicode word boundary
/// exists in the regex *and* a non-ASCII byte is observed.
///
/// The other type of state pointer is a state pointer with special flag bits.
/// There are two flags: a start flag and a match flag. The lower bits of both
/// kinds always contain a "valid" `StatePtr` (indicated by the `STATE_MAX`
/// mask).
///
/// The start flag means that the state is a start state, and therefore may be
/// subject to special prefix scanning optimizations.
///
/// The match flag means that the state is a match state, and therefore the
/// current position in the input (while searching) should be recorded.
///
/// The above exists mostly in the service of making the inner loop fast.
/// In particular, the inner *inner* loop looks something like this:
///
/// ```ignore
/// while state <= STATE_MAX and i < len(text):
/// state = state.next[i]
/// ```
///
/// This is nice because it lets us execute a lazy DFA as if it were an
/// entirely offline DFA (i.e., with very few instructions). The loop will
/// quit only when we need to examine a case that needs special attention.
type StatePtr = u32;
/// An unknown state means that the state has not been computed yet, and that
/// the only way to progress is to compute it.
const STATE_UNKNOWN: StatePtr = 1 << 31;
/// A dead state means that the state has been computed and it is known that
/// once it is entered, no future match can ever occur.
const STATE_DEAD: StatePtr = STATE_UNKNOWN + 1;
/// A quit state means that the DFA came across some input that it doesn't
/// know how to process correctly. The DFA should quit and another matching
/// engine should be run in its place.
const STATE_QUIT: StatePtr = STATE_DEAD + 1;
/// A start state is a state that the DFA can start in.
///
/// Note that start states have their lower bits set to a state pointer.
const STATE_START: StatePtr = 1 << 30;
/// A match state means that the regex has successfully matched.
///
/// Note that match states have their lower bits set to a state pointer.
const STATE_MATCH: StatePtr = 1 << 29;
/// The maximum state pointer. This is useful to mask out the "valid" state
/// pointer from a state with the "start" or "match" bits set.
///
/// It doesn't make sense to use this with unknown, dead or quit state
/// pointers, since those pointers are sentinels and never have their lower
/// bits set to anything meaningful.
const STATE_MAX: StatePtr = STATE_MATCH - 1;
/// Byte is a u8 in spirit, but a u16 in practice so that we can represent the
/// special EOF sentinel value.
#[derive(Copy, Clone, Debug)]
struct Byte(u16);
/// A set of flags for zero-width assertions.
#[derive(Clone, Copy, Eq, Debug, Default, Hash, PartialEq)]
struct EmptyFlags {
start: bool,
end: bool,
start_line: bool,
end_line: bool,
word_boundary: bool,
not_word_boundary: bool,
}
/// A set of flags describing various configurations of a DFA state. This is
/// represented by a `u8` so that it is compact.
#[derive(Clone, Copy, Eq, Default, Hash, PartialEq)]
struct StateFlags(u8);
impl Cache {
/// Create new empty cache for the DFA engine.
pub fn new(prog: &Program) -> Self {
// We add 1 to account for the special EOF byte.
let num_byte_classes = (prog.byte_classes[255] as usize + 1) + 1;
let starts = vec![STATE_UNKNOWN; 256];
let mut cache = Cache {
inner: CacheInner {
compiled: StateMap::new(num_byte_classes),
trans: Transitions::new(num_byte_classes),
start_states: starts,
stack: vec![],
flush_count: 0,
size: 0,
insts_scratch_space: vec![],
},
qcur: SparseSet::new(prog.insts.len()),
qnext: SparseSet::new(prog.insts.len()),
};
cache.inner.reset_size();
cache
}
}
impl CacheInner {
/// Resets the cache size to account for fixed costs, such as the program
/// and stack sizes.
fn reset_size(&mut self) {
self.size = (self.start_states.len() * mem::size_of::<StatePtr>())
+ (self.stack.len() * mem::size_of::<InstPtr>());
}
}
impl<'a> Fsm<'a> {
#[cfg_attr(feature = "perf-inline", inline(always))]
pub fn forward(
prog: &'a Program,
cache: &ProgramCache,
quit_after_match: bool,
text: &[u8],
at: usize,
) -> Result<usize> {
let mut cache = cache.borrow_mut();
let cache = &mut cache.dfa;
let mut dfa = Fsm {
prog: prog,
start: 0, // filled in below
at: at,
quit_after_match: quit_after_match,
last_match_si: STATE_UNKNOWN,
last_cache_flush: at,
cache: &mut cache.inner,
};
let (empty_flags, state_flags) = dfa.start_flags(text, at);
dfa.start =
match dfa.start_state(&mut cache.qcur, empty_flags, state_flags) {
None => return Result::Quit,
Some(STATE_DEAD) => return Result::NoMatch(at),
Some(si) => si,
};
debug_assert!(dfa.start != STATE_UNKNOWN);
dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text)
}
#[cfg_attr(feature = "perf-inline", inline(always))]
pub fn reverse(
prog: &'a Program,
cache: &ProgramCache,
quit_after_match: bool,
text: &[u8],
at: usize,
) -> Result<usize> {
let mut cache = cache.borrow_mut();
let cache = &mut cache.dfa_reverse;
let mut dfa = Fsm {
prog: prog,
start: 0, // filled in below
at: at,
quit_after_match: quit_after_match,
last_match_si: STATE_UNKNOWN,
last_cache_flush: at,
cache: &mut cache.inner,
};
let (empty_flags, state_flags) = dfa.start_flags_reverse(text, at);
dfa.start =
match dfa.start_state(&mut cache.qcur, empty_flags, state_flags) {
None => return Result::Quit,
Some(STATE_DEAD) => return Result::NoMatch(at),
Some(si) => si,
};
debug_assert!(dfa.start != STATE_UNKNOWN);
dfa.exec_at_reverse(&mut cache.qcur, &mut cache.qnext, text)
}
#[cfg_attr(feature = "perf-inline", inline(always))]
pub fn forward_many(
prog: &'a Program,
cache: &ProgramCache,
matches: &mut [bool],
text: &[u8],
at: usize,
) -> Result<usize> {
debug_assert!(matches.len() == prog.matches.len());
let mut cache = cache.borrow_mut();
let cache = &mut cache.dfa;
let mut dfa = Fsm {
prog: prog,
start: 0, // filled in below
at: at,
quit_after_match: false,
last_match_si: STATE_UNKNOWN,
last_cache_flush: at,
cache: &mut cache.inner,
};
let (empty_flags, state_flags) = dfa.start_flags(text, at);
dfa.start =
match dfa.start_state(&mut cache.qcur, empty_flags, state_flags) {
None => return Result::Quit,
Some(STATE_DEAD) => return Result::NoMatch(at),
Some(si) => si,
};
debug_assert!(dfa.start != STATE_UNKNOWN);
let result = dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text);
if result.is_match() {
if matches.len() == 1 {
matches[0] = true;
} else {
debug_assert!(dfa.last_match_si != STATE_UNKNOWN);
debug_assert!(dfa.last_match_si != STATE_DEAD);
for ip in dfa.state(dfa.last_match_si).inst_ptrs() {
if let Inst::Match(slot) = dfa.prog[ip] {
matches[slot] = true;
}
}
}
}
result
}
/// Executes the DFA on a forward NFA.
///
/// {qcur,qnext} are scratch ordered sets which may be non-empty.
#[cfg_attr(feature = "perf-inline", inline(always))]
fn exec_at(
&mut self,
qcur: &mut SparseSet,
qnext: &mut SparseSet,
text: &[u8],
) -> Result<usize> {
// For the most part, the DFA is basically:
//
// last_match = null
// while current_byte != EOF:
// si = current_state.next[current_byte]
// if si is match
// last_match = si
// return last_match
//
// However, we need to deal with a few things:
//
// 1. This is an *online* DFA, so the current state's next list
// may not point to anywhere yet, so we must go out and compute
// them. (They are then cached into the current state's next list
// to avoid re-computation.)
// 2. If we come across a state that is known to be dead (i.e., never
// leads to a match), then we can quit early.
// 3. If the caller just wants to know if a match occurs, then we
// can quit as soon as we know we have a match. (Full leftmost
// first semantics require continuing on.)
// 4. If we're in the start state, then we can use a pre-computed set
// of prefix literals to skip quickly along the input.
// 5. After the input is exhausted, we run the DFA on one symbol
// that stands for EOF. This is useful for handling empty width
// assertions.
// 6. We can't actually do state.next[byte]. Instead, we have to do
// state.next[byte_classes[byte]], which permits us to keep the
// 'next' list very small.
//
// Since there's a bunch of extra stuff we need to consider, we do some
// pretty hairy tricks to get the inner loop to run as fast as
// possible.
debug_assert!(!self.prog.is_reverse);
// The last match is the currently known ending match position. It is
// reported as an index to the most recent byte that resulted in a
// transition to a match state and is always stored in capture slot `1`
// when searching forwards. Its maximum value is `text.len()`.
let mut result = Result::NoMatch(self.at);
let (mut prev_si, mut next_si) = (self.start, self.start);
let mut at = self.at;
while at < text.len() {
// This is the real inner loop. We take advantage of special bits
// set in the state pointer to determine whether a state is in the
// "common" case or not. Specifically, the common case is a
// non-match non-start non-dead state that has already been
// computed. So long as we remain in the common case, this inner
// loop will chew through the input.
//
// We also unroll the loop 4 times to amortize the cost of checking
// whether we've consumed the entire input. We are also careful
// to make sure that `prev_si` always represents the previous state
// and `next_si` always represents the next state after the loop
// exits, even if it isn't always true inside the loop.
while next_si <= STATE_MAX && at < text.len() {
// Argument for safety is in the definition of next_si.
prev_si = unsafe { self.next_si(next_si, text, at) };
at += 1;
if prev_si > STATE_MAX || at + 2 >= text.len() {
mem::swap(&mut prev_si, &mut next_si);
break;
}
next_si = unsafe { self.next_si(prev_si, text, at) };
at += 1;
if next_si > STATE_MAX {
break;
}
prev_si = unsafe { self.next_si(next_si, text, at) };
at += 1;
if prev_si > STATE_MAX {
mem::swap(&mut prev_si, &mut next_si);
break;
}
next_si = unsafe { self.next_si(prev_si, text, at) };
at += 1;
}
if next_si & STATE_MATCH > 0 {
// A match state is outside of the common case because it needs
// special case analysis. In particular, we need to record the
// last position as having matched and possibly quit the DFA if
// we don't need to keep matching.
next_si &= !STATE_MATCH;
result = Result::Match(at - 1);
if self.quit_after_match {
return result;
}
self.last_match_si = next_si;
prev_si = next_si;
// This permits short-circuiting when matching a regex set.
// In particular, if this DFA state contains only match states,
// then it's impossible to extend the set of matches since
// match states are final. Therefore, we can quit.
if self.prog.matches.len() > 1 {
let state = self.state(next_si);
let just_matches =
state.inst_ptrs().all(|ip| self.prog[ip].is_match());
if just_matches {
return result;
}
}
// Another inner loop! If the DFA stays in this particular
// match state, then we can rip through all of the input
// very quickly, and only recording the match location once
// we've left this particular state.
let cur = at;
while (next_si & !STATE_MATCH) == prev_si
&& at + 2 < text.len()
{
// Argument for safety is in the definition of next_si.
next_si = unsafe {
self.next_si(next_si & !STATE_MATCH, text, at)
};
at += 1;
}
if at > cur {
result = Result::Match(at - 2);
}
} else if next_si & STATE_START > 0 {
// A start state isn't in the common case because we may
// what to do quick prefix scanning. If the program doesn't
// have a detected prefix, then start states are actually
// considered common and this case is never reached.
debug_assert!(self.has_prefix());
next_si &= !STATE_START;
prev_si = next_si;
at = match self.prefix_at(text, at) {
None => return Result::NoMatch(text.len()),
Some(i) => i,
};
} else if next_si >= STATE_UNKNOWN {
if next_si == STATE_QUIT {
return Result::Quit;
}
// Finally, this corresponds to the case where the transition
// entered a state that can never lead to a match or a state
// that hasn't been computed yet. The latter being the "slow"
// path.
let byte = Byte::byte(text[at - 1]);
// We no longer care about the special bits in the state
// pointer.
prev_si &= STATE_MAX;
// Record where we are. This is used to track progress for
// determining whether we should quit if we've flushed the
// cache too much.
self.at = at;
next_si = match self.next_state(qcur, qnext, prev_si, byte) {
None => return Result::Quit,
Some(STATE_DEAD) => return result.set_non_match(at),
Some(si) => si,
};
debug_assert!(next_si != STATE_UNKNOWN);
if next_si & STATE_MATCH > 0 {
next_si &= !STATE_MATCH;
result = Result::Match(at - 1);
if self.quit_after_match {
return result;
}
self.last_match_si = next_si;
}
prev_si = next_si;
} else {
prev_si = next_si;
}
}
// Run the DFA once more on the special EOF senitnel value.
// We don't care about the special bits in the state pointer any more,
// so get rid of them.
prev_si &= STATE_MAX;
prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) {
None => return Result::Quit,
Some(STATE_DEAD) => return result.set_non_match(text.len()),
Some(si) => si & !STATE_START,
};
debug_assert!(prev_si != STATE_UNKNOWN);
if prev_si & STATE_MATCH > 0 {
prev_si &= !STATE_MATCH;
self.last_match_si = prev_si;
result = Result::Match(text.len());
}
result
}
/// Executes the DFA on a reverse NFA.
#[cfg_attr(feature = "perf-inline", inline(always))]
fn exec_at_reverse(
&mut self,
qcur: &mut SparseSet,
qnext: &mut SparseSet,
text: &[u8],
) -> Result<usize> {
// The comments in `exec_at` above mostly apply here too. The main
// difference is that we move backwards over the input and we look for
// the longest possible match instead of the leftmost-first match.
//
// N.B. The code duplication here is regrettable. Efforts to improve
// it without sacrificing performance are welcome. ---AG
debug_assert!(self.prog.is_reverse);
let mut result = Result::NoMatch(self.at);
let (mut prev_si, mut next_si) = (self.start, self.start);
let mut at = self.at;
while at > 0 {
while next_si <= STATE_MAX && at > 0 {
// Argument for safety is in the definition of next_si.
at -= 1;
prev_si = unsafe { self.next_si(next_si, text, at) };
if prev_si > STATE_MAX || at <= 4 {
mem::swap(&mut prev_si, &mut next_si);
break;
}
at -= 1;
next_si = unsafe { self.next_si(prev_si, text, at) };
if next_si > STATE_MAX {
break;
}
at -= 1;
prev_si = unsafe { self.next_si(next_si, text, at) };
if prev_si > STATE_MAX {
mem::swap(&mut prev_si, &mut next_si);
break;
}
at -= 1;
next_si = unsafe { self.next_si(prev_si, text, at) };
}
if next_si & STATE_MATCH > 0 {
next_si &= !STATE_MATCH;
result = Result::Match(at + 1);
if self.quit_after_match {
return result;
}
self.last_match_si = next_si;
prev_si = next_si;
let cur = at;
while (next_si & !STATE_MATCH) == prev_si && at >= 2 {
// Argument for safety is in the definition of next_si.
at -= 1;
next_si = unsafe {
self.next_si(next_si & !STATE_MATCH, text, at)
};
}
if at < cur {
result = Result::Match(at + 2);
}
} else if next_si >= STATE_UNKNOWN {
if next_si == STATE_QUIT {
return Result::Quit;
}
let byte = Byte::byte(text[at]);
prev_si &= STATE_MAX;
self.at = at;
next_si = match self.next_state(qcur, qnext, prev_si, byte) {
None => return Result::Quit,
Some(STATE_DEAD) => return result.set_non_match(at),
Some(si) => si,
};
debug_assert!(next_si != STATE_UNKNOWN);
if next_si & STATE_MATCH > 0 {
next_si &= !STATE_MATCH;
result = Result::Match(at + 1);
if self.quit_after_match {
return result;
}
self.last_match_si = next_si;
}
prev_si = next_si;
} else {
prev_si = next_si;
}
}
// Run the DFA once more on the special EOF senitnel value.
prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) {
None => return Result::Quit,
Some(STATE_DEAD) => return result.set_non_match(0),
Some(si) => si,
};
debug_assert!(prev_si != STATE_UNKNOWN);
if prev_si & STATE_MATCH > 0 {
prev_si &= !STATE_MATCH;
self.last_match_si = prev_si;
result = Result::Match(0);
}
result
}
/// next_si transitions to the next state, where the transition input
/// corresponds to text[i].
///
/// This elides bounds checks, and is therefore unsafe.
#[cfg_attr(feature = "perf-inline", inline(always))]
unsafe fn next_si(&self, si: StatePtr, text: &[u8], i: usize) -> StatePtr {
// What is the argument for safety here?
// We have three unchecked accesses that could possibly violate safety:
//
// 1. The given byte of input (`text[i]`).
// 2. The class of the byte of input (`classes[text[i]]`).
// 3. The transition for the class (`trans[si + cls]`).
//
// (1) is only safe when calling next_si is guarded by
// `i < text.len()`.
//
// (2) is the easiest case to guarantee since `text[i]` is always a
// `u8` and `self.prog.byte_classes` always has length `u8::MAX`.
// (See `ByteClassSet.byte_classes` in `compile.rs`.)
//
// (3) is only safe if (1)+(2) are safe. Namely, the transitions
// of every state are defined to have length equal to the number of
// byte classes in the program. Therefore, a valid class leads to a
// valid transition. (All possible transitions are valid lookups, even
// if it points to a state that hasn't been computed yet.) (3) also
// relies on `si` being correct, but StatePtrs should only ever be
// retrieved from the transition table, which ensures they are correct.
debug_assert!(i < text.len());
let b = *text.get_unchecked(i);
debug_assert!((b as usize) < self.prog.byte_classes.len());
let cls = *self.prog.byte_classes.get_unchecked(b as usize);
self.cache.trans.next_unchecked(si, cls as usize)
}
/// Computes the next state given the current state and the current input
/// byte (which may be EOF).
///
/// If STATE_DEAD is returned, then there is no valid state transition.
/// This implies that no permutation of future input can lead to a match
/// state.
///
/// STATE_UNKNOWN can never be returned.
fn exec_byte(
&mut self,
qcur: &mut SparseSet,
qnext: &mut SparseSet,
mut si: StatePtr,
b: Byte,
) -> Option<StatePtr> {
use prog::Inst::*;
// Initialize a queue with the current DFA state's NFA states.
qcur.clear();
for ip in self.state(si).inst_ptrs() {
qcur.insert(ip);
}
// Before inspecting the current byte, we may need to also inspect
// whether the position immediately preceding the current byte
// satisfies the empty assertions found in the current state.
//
// We only need to do this step if there are any empty assertions in
// the current state.
let is_word_last = self.state(si).flags().is_word();
let is_word = b.is_ascii_word();
if self.state(si).flags().has_empty() {
// Compute the flags immediately preceding the current byte.
// This means we only care about the "end" or "end line" flags.
// (The "start" flags are computed immediately proceding the
// current byte and is handled below.)
let mut flags = EmptyFlags::default();
if b.is_eof() {
flags.end = true;
flags.end_line = true;
} else if b.as_byte().map_or(false, |b| b == b'\n') {
flags.end_line = true;
}
if is_word_last == is_word {
flags.not_word_boundary = true;
} else {
flags.word_boundary = true;
}
// Now follow epsilon transitions from every NFA state, but make
// sure we only follow transitions that satisfy our flags.
qnext.clear();
for &ip in &*qcur {
self.follow_epsilons(usize_to_u32(ip), qnext, flags);
}
mem::swap(qcur, qnext);
}
// Now we set flags for immediately after the current byte. Since start
// states are processed separately, and are the only states that can
// have the StartText flag set, we therefore only need to worry about
// the StartLine flag here.
//
// We do also keep track of whether this DFA state contains a NFA state
// that is a matching state. This is precisely how we delay the DFA
// matching by one byte in order to process the special EOF sentinel
// byte. Namely, if this DFA state containing a matching NFA state,
// then it is the *next* DFA state that is marked as a match.
let mut empty_flags = EmptyFlags::default();
let mut state_flags = StateFlags::default();
empty_flags.start_line = b.as_byte().map_or(false, |b| b == b'\n');
if b.is_ascii_word() {
state_flags.set_word();
}
// Now follow all epsilon transitions again, but only after consuming
// the current byte.
qnext.clear();
for &ip in &*qcur {
match self.prog[ip as usize] {
// These states never happen in a byte-based program.
Char(_) | Ranges(_) => unreachable!(),
// These states are handled when following epsilon transitions.
Save(_) | Split(_) | EmptyLook(_) => {}
Match(_) => {
state_flags.set_match();
if !self.continue_past_first_match() {
break;
} else if self.prog.matches.len() > 1
&& !qnext.contains(ip as usize)
{
// If we are continuing on to find other matches,
// then keep a record of the match states we've seen.
qnext.insert(ip);
}
}
Bytes(ref inst) => {
if b.as_byte().map_or(false, |b| inst.matches(b)) {
self.follow_epsilons(
inst.goto as InstPtr,
qnext,
empty_flags,
);
}
}
}
}
let cache = if b.is_eof() && self.prog.matches.len() > 1 {
// If we're processing the last byte of the input and we're
// matching a regex set, then make the next state contain the
// previous states transitions. We do this so that the main
// matching loop can extract all of the match instructions.
mem::swap(qcur, qnext);
// And don't cache this state because it's totally bunk.
false
} else {
true
};
// We've now built up the set of NFA states that ought to comprise the