This repository has been archived by the owner on Jul 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathonepass.rs
2805 lines (2663 loc) · 112 KB
/
onepass.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
/*!
A DFA that can return spans for matching capturing groups.
This module is the home of a [one-pass DFA](DFA).
This module also contains a [`Builder`] and a [`Config`] for building and
configuring a one-pass DFA.
*/
// A note on naming and credit:
//
// As far as I know, Russ Cox came up with the practical vision and
// implementation of a "one-pass regex engine." He mentions and describes it
// briefly in the third article of his regexp article series:
// https://swtch.com/~rsc/regexp/regexp3.html
//
// That first implementation is in RE2, and the implementation below is most
// heavily inspired by RE2's. The key thing they have in common is that their
// transitions are defined over an alphabet of bytes. In contrast, Go's
// regex engine also has a one-pass engine, but its transitions are more firmly
// rooted on Unicode codepoints. The ideas are the same, but the implementations
// are different.
//
// So, RE2 tends to call this a "one-pass NFA." Here, we call it a "one-pass
// DFA." They're both true in their own ways:
//
// * The "one-pass" criterion is generally a property of the NFA itself. In
// particular, it is said that an NFA is one-pass if, after each byte of input
// during a search, there is at most one "VM thread" remaining to take for the
// next byte of input. That is, there is never any ambiguity as to the path to
// take through the NFA during a search.
//
// * On the other hand, once a one-pass NFA has its representation converted
// to something where a constant number of instructions is used for each byte
// of input, the implementation looks a lot more like a DFA. It's technically
// more powerful than a DFA since it has side effects (storing offsets inside
// of slots activated by a transition), but it is far closer to a DFA than an
// NFA simulation.
//
// Thus, in this crate, we call it a one-pass DFA.
use core::convert::TryFrom;
use alloc::{vec, vec::Vec};
use crate::{
dfa::{error::Error, remapper::Remapper, DEAD},
nfa::thompson::{self, NFA},
util::{
alphabet::{self, ByteClasses},
captures::Captures,
escape::DebugByte,
int::{Usize, U32, U64, U8},
iter,
look::{Look, LookSet},
primitives::{NonMaxUsize, PatternID, SmallIndex, StateID},
search::{Input, Match, MatchError, MatchKind},
sparse_set::SparseSet,
},
};
/// The configuration used for building a [one-pass DFA](DFA).
///
/// A one-pass DFA configuration is a simple data object that is typically used
/// with [`Builder::configure`]. It can be cheaply cloned.
///
/// A default configuration can be created either with `Config::new`, or
/// perhaps more conveniently, with [`DFA::config`].
#[derive(Clone, Debug, Default)]
pub struct Config {
match_kind: Option<MatchKind>,
utf8: Option<bool>,
starts_for_each_pattern: Option<bool>,
byte_classes: Option<bool>,
size_limit: Option<Option<usize>>,
}
impl Config {
/// Return a new default one-pass DFA configuration.
pub fn new() -> Config {
Config::default()
}
/// Set the desired match semantics.
///
/// The default is [`MatchKind::LeftmostFirst`], which corresponds to the
/// match semantics of Perl-like regex engines. That is, when multiple
/// patterns would match at the same leftmost position, the pattern that
/// appears first in the concrete syntax is chosen.
///
/// Currently, the only other kind of match semantics supported is
/// [`MatchKind::All`]. This corresponds to "classical DFA" construction
/// where all possible matches are visited.
///
/// When it comes to the one-pass DFA, it is rarer for preference order and
/// "longest match" to actually disagree. Since if they did disagree, then
/// the regex typically isn't one-pass. For example, searching `Samwise`
/// for `Sam|Samwise` will report `Sam` for leftmost-first matching and
/// `Samwise` for "longest match" or "all" matching. However, this regex is
/// not one-pass if taken literally. The equivalent regex, `Sam(?:|wise)`
/// is one-pass and `Sam|Samwise` may be optimized to it.
///
/// The other main difference is that "all" match semantics don't support
/// non-greedy matches. "All" match semantics always try to match as much
/// as possible.
pub fn match_kind(mut self, kind: MatchKind) -> Config {
self.match_kind = Some(kind);
self
}
/// Whether to enable UTF-8 mode or not.
///
/// When UTF-8 mode is enabled (the default) and an empty match is seen,
/// the search APIs of a one-pass DFA will never report a match that would
/// otherwise split a valid UTF-8 code unit sequence.
///
/// If this mode is enabled and invalid UTF-8 is given to search, then
/// behavior is unspecified.
///
/// Generally speaking, one should enable this when
/// [`SyntaxConfig::utf8`](crate::SyntaxConfig::utf8)
/// is enabled, and disable it otherwise.
///
/// # Example
///
/// This example demonstrates the differences between when this option is
/// enabled and disabled. The differences only arise when the one-pass DFA
/// can return matches of length zero.
///
/// In this first snippet, we show the results when UTF-8 mode is disabled.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, Match};
///
/// let re = DFA::builder()
/// .configure(DFA::config().utf8(false))
/// .build(r"")?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let mut input = re.create_input("a☃z");
///
/// // The empty string matches at every position.
///
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 0..0)), caps.get_match());
///
/// input.set_start(1);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 1..1)), caps.get_match());
///
/// input.set_start(2);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 2..2)), caps.get_match());
///
/// input.set_start(3);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 3..3)), caps.get_match());
///
/// input.set_start(4);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 4..4)), caps.get_match());
///
/// input.set_start(5);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 5..5)), caps.get_match());
///
/// // 6 > input.haystack.len(), so there's no match here.
/// input.set_start(6);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// And in this snippet, we execute the same search on the same haystack,
/// but with UTF-8 mode enabled. Notice that when we search at offsets that
/// would otherwise return a match that splits the encoding of `☃`, we
/// get no match.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, Match};
///
/// let re = DFA::builder()
/// .configure(DFA::config().utf8(true))
/// .build(r"")?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let mut input = re.create_input("a☃z");
///
/// // 0 occurs just before 'a', where the empty string matches.
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 0..0)), caps.get_match());
///
/// // 1 occurs just before the snowman.
/// input.set_start(1);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 1..1)), caps.get_match());
///
/// // 2 splits the first and second bytes of the snowman.
/// input.set_start(2);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(None, caps.get_match());
///
/// // 3 splits the second and third bytes of the snowman.
/// input.set_start(3);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(None, caps.get_match());
///
/// // 4 is right past the snowman and before the 'z'
/// input.set_start(4);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 4..4)), caps.get_match());
///
/// // 5 == input.haystack.len(), at which point, the empty string matches.
/// input.set_start(5);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 5..5)), caps.get_match());
///
/// // 6 > input.haystack.len(), so there's no match here.
/// input.set_start(6);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn utf8(mut self, yes: bool) -> Config {
self.utf8 = Some(yes);
self
}
/// Whether to compile a separate start state for each pattern in the
/// one-pass DFA.
///
/// When enabled, a separate **anchored** start state is added for each
/// pattern in the DFA. When this start state is used, then the DFA will
/// only search for matches for the pattern specified, even if there are
/// other patterns in the DFA.
///
/// The main downside of this option is that it can potentially increase
/// the size of the DFA and/or increase the time it takes to build the DFA.
///
/// You might want to enable this option when you want to both search for
/// anchored matches of any pattern or to search for anchored matches of
/// one particular pattern while using the same DFA. (Otherwise, you would
/// need to compile a new DFA for each pattern.)
///
/// By default this is disabled.
///
/// # Example
///
/// This example shows how to build a multi-regex and then search for
/// matches for a any of the patterns or matches for a specific pattern.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, Input, Match, PatternID};
///
/// let re = DFA::builder()
/// .configure(DFA::config().starts_for_each_pattern(true))
/// .build_many(&["[a-z]+", "[0-9]+"])?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
/// let haystack = "123abc";
///
/// // A normal multi-pattern search will show pattern 1 matches.
/// re.search(&mut cache, &Input::new(haystack), &mut caps);
/// assert_eq!(Some(Match::must(1, 0..3)), caps.get_match());
///
/// // If we only want to report pattern 0 matches, then we'll get no
/// // match here.
/// re.search(
/// &mut cache,
/// &Input::new(haystack).pattern(Some(PatternID::must(0))),
/// &mut caps,
/// );
/// assert_eq!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn starts_for_each_pattern(mut self, yes: bool) -> Config {
self.starts_for_each_pattern = Some(yes);
self
}
/// Whether to attempt to shrink the size of the DFA's alphabet or not.
///
/// This option is enabled by default and should never be disabled unless
/// one is debugging a one-pass DFA.
///
/// When enabled, the DFA will use a map from all possible bytes to their
/// corresponding equivalence class. Each equivalence class represents a
/// set of bytes that does not discriminate between a match and a non-match
/// in the DFA. For example, the pattern `[ab]+` has at least two
/// equivalence classes: a set containing `a` and `b` and a set containing
/// every byte except for `a` and `b`. `a` and `b` are in the same
/// equivalence class because they never discriminate between a match and a
/// non-match.
///
/// The advantage of this map is that the size of the transition table
/// can be reduced drastically from (approximately) `#states * 256 *
/// sizeof(StateID)` to `#states * k * sizeof(StateID)` where `k` is the
/// number of equivalence classes (rounded up to the nearest power of 2).
/// As a result, total space usage can decrease substantially. Moreover,
/// since a smaller alphabet is used, DFA compilation becomes faster as
/// well.
///
/// **WARNING:** This is only useful for debugging DFAs. Disabling this
/// does not yield any speed advantages. Namely, even when this is
/// disabled, a byte class map is still used while searching. The only
/// difference is that every byte will be forced into its own distinct
/// equivalence class. This is useful for debugging the actual generated
/// transitions because it lets one see the transitions defined on actual
/// bytes instead of the equivalence classes.
pub fn byte_classes(mut self, yes: bool) -> Config {
self.byte_classes = Some(yes);
self
}
/// Set a size limit on the total heap used by a one-pass DFA.
///
/// This size limit is expressed in bytes and is applied during
/// construction of a one-pass DFA. If the DFA's heap usage exceeds
/// this configured limit, then construction is stopped and an error is
/// returned.
///
/// The default is no limit.
///
/// # Example
///
/// This example shows a one-pass DFA that fails to build because of
/// a configured size limit. This particular example also serves as a
/// cautionary tale demonstrating just how big DFAs with large Unicode
/// character classes can get.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, Match};
///
/// // 6MB isn't enough!
/// DFA::builder()
/// .configure(DFA::config().size_limit(Some(6_000_000)))
/// .build(r"\w{20}")
/// .unwrap_err();
///
/// // ... but 7MB probably is!
/// // (Note that DFA sizes aren't necessarily stable between releases.)
/// let re = DFA::builder()
/// .configure(DFA::config().size_limit(Some(7_000_000)))
/// .build(r"\w{20}")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
/// let haystack = "A".repeat(20);
/// re.find(&mut cache, &haystack, &mut caps);
/// assert_eq!(Some(Match::must(0, 0..20)), caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// While one needs a little more than 3MB to represent `\w{20}`, it
/// turns out that you only need a little more than 4KB to represent
/// `(?-u:\w{20})`. So only use Unicode if you need it!
pub fn size_limit(mut self, limit: Option<usize>) -> Config {
self.size_limit = Some(limit);
self
}
/// Returns the match semantics set in this configuration.
pub fn get_match_kind(&self) -> MatchKind {
self.match_kind.unwrap_or(MatchKind::LeftmostFirst)
}
/// Returns whether UTF-8 mode should be enabled for searches.
pub fn get_utf8(&self) -> bool {
self.utf8.unwrap_or(true)
}
/// Returns whether this configuration has enabled anchored starting states
/// for every pattern in the DFA.
pub fn get_starts_for_each_pattern(&self) -> bool {
self.starts_for_each_pattern.unwrap_or(false)
}
/// Returns whether this configuration has enabled byte classes or not.
/// This is typically a debugging oriented option, as disabling it confers
/// no speed benefit.
pub fn get_byte_classes(&self) -> bool {
self.byte_classes.unwrap_or(true)
}
/// Returns the DFA size limit of this configuration if one was set.
/// The size limit is total number of bytes on the heap that a DFA is
/// permitted to use. If the DFA exceeds this limit during construction,
/// then construction is stopped and an error is returned.
pub fn get_size_limit(&self) -> Option<usize> {
self.size_limit.unwrap_or(None)
}
/// Overwrite the default configuration such that the options in `o` are
/// always used. If an option in `o` is not set, then the corresponding
/// option in `self` is used. If it's not set in `self` either, then it
/// remains not set.
pub(crate) fn overwrite(&self, o: Config) -> Config {
Config {
match_kind: o.match_kind.or(self.match_kind),
utf8: o.utf8.or(self.utf8),
starts_for_each_pattern: o
.starts_for_each_pattern
.or(self.starts_for_each_pattern),
byte_classes: o.byte_classes.or(self.byte_classes),
size_limit: o.size_limit.or(self.size_limit),
}
}
}
/// A builder for a [one-pass DFA](DFA).
///
/// This builder permits configuring options for the syntax of a pattern, the
/// NFA construction and the DFA construction. This builder is different from a
/// general purpose regex builder in that it permits fine grain configuration
/// of the construction process. The trade off for this is complexity, and
/// the possibility of setting a configuration that might not make sense. For
/// example, there are two different UTF-8 modes:
///
/// * [`SyntaxConfig::utf8`](crate::SyntaxConfig::utf8) controls whether the
/// pattern itself can contain sub-expressions that match invalid UTF-8.
/// * [`Config::utf8`] controls whether empty matches that split a Unicode
/// codepoint are reported or not.
///
/// Generally speaking, callers will want to either enable all of these or
/// disable all of these.
///
/// # Example
///
/// This example shows how to disable UTF-8 mode in the syntax and the regex
/// itself. This is generally what you want for matching on arbitrary bytes.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, Match, SyntaxConfig};
///
/// let re = DFA::builder()
/// .configure(DFA::config().utf8(false))
/// .syntax(SyntaxConfig::new().utf8(false))
/// .build(r"foo(?-u:[^b])ar.*")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// let haystack = b"foo\xFFarzz\xE2\x98\xFF\n";
/// re.find(&mut cache, haystack, &mut caps);
/// // Notice that `(?-u:[^b])` matches invalid UTF-8,
/// // but the subsequent `.*` does not! Disabling UTF-8
/// // on the syntax permits this.
/// //
/// // N.B. This example does not show the impact of
/// // disabling UTF-8 mode on a one-pass DFA Config,
/// // since that only impacts regexes that can
/// // produce matches of length 0.
/// assert_eq!(Some(Match::must(0, 0..8)), caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct Builder {
config: Config,
thompson: thompson::Compiler,
}
impl Builder {
/// Create a new one-pass DFA builder with the default configuration.
pub fn new() -> Builder {
Builder {
config: Config::default(),
thompson: thompson::Compiler::new(),
}
}
/// Build a one-pass DFA from the given pattern.
///
/// If there was a problem parsing or compiling the pattern, then an error
/// is returned.
pub fn build(&self, pattern: &str) -> Result<DFA, Error> {
self.build_many(&[pattern])
}
/// Build a one-pass DFA from the given patterns.
///
/// When matches are returned, the pattern ID corresponds to the index of
/// the pattern in the slice given.
pub fn build_many<P: AsRef<str>>(
&self,
patterns: &[P],
) -> Result<DFA, Error> {
let nfa = self.thompson.build_many(patterns).map_err(Error::nfa)?;
self.build_from_nfa(nfa)
}
/// Build a DFA from the given NFA.
///
/// # Example
///
/// This example shows how to build a DFA if you already have an NFA in
/// hand.
///
/// ```
/// use regex_automata::{dfa::onepass::DFA, nfa::thompson::NFA, Match};
///
/// // This shows how to set non-default options for building an NFA.
/// let nfa = NFA::compiler()
/// .configure(NFA::config().shrink(true))
/// .build(r"[a-z0-9]+")?;
/// let re = DFA::builder().build_from_nfa(nfa)?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
/// re.find(&mut cache, "foo123bar", &mut caps);
/// assert_eq!(Some(Match::must(0, 0..9)), caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn build_from_nfa(&self, nfa: NFA) -> Result<DFA, Error> {
// Why take ownership if we're just going to pass a reference to the
// NFA to our internal builder? Well, the first thing to note is that
// an NFA uses reference counting internally, so either choice is going
// to be cheap. So there isn't much cost either way.
//
// The real reason is that a one-pass DFA, semantically, shares
// ownership of an NFA. This is unlike other DFAs that don't share
// ownership of an NFA at all, primarily because they want to be
// self-contained in order to support cheap (de)serialization.
//
// But then why pass a '&nfa' below if we want to share ownership?
// Well, it turns out that using a '&NFA' in our internal builder
// separates its lifetime from the DFA we're building, and this turns
// out to make code a bit more composable. e.g., We can iterate over
// things inside the NFA while borrowing the builder as mutable because
// we know the NFA cannot be mutated. So TL;DR --- this weirdness is
// "because borrow checker."
InternalBuilder::new(self.config.clone(), &nfa).build()
}
/// Apply the given one-pass DFA configuration options to this builder.
pub fn configure(&mut self, config: Config) -> &mut Builder {
self.config = self.config.overwrite(config);
self
}
/// Set the syntax configuration for this builder using
/// [`SyntaxConfig`](crate::SyntaxConfig).
///
/// This permits setting things like case insensitivity, Unicode and multi
/// line mode.
///
/// These settings only apply when constructing a one-pass DFA directly
/// from a pattern.
pub fn syntax(
&mut self,
config: crate::util::syntax::SyntaxConfig,
) -> &mut Builder {
self.thompson.syntax(config);
self
}
/// Set the Thompson NFA configuration for this builder using
/// [`nfa::thompson::Config`](crate::nfa::thompson::Config).
///
/// This permits setting things like whether additional time should be
/// spent shrinking the size of the NFA.
///
/// These settings only apply when constructing a DFA directly from a
/// pattern.
pub fn thompson(&mut self, config: thompson::Config) -> &mut Builder {
self.thompson.configure(config);
self
}
}
/// An internal builder for encapsulating the state necessary to build a
/// one-pass DFA. Typical use is just `InternalBuilder::new(..).build()`.
///
/// There is no separate pass for determining whether the NFA is one-pass or
/// not. We just try to build the DFA. If during construction we discover that
/// it is not one-pass, we bail out. This is likely to lead to some undesirable
/// expense in some cases, so it might make sense to try an identify common
/// patterns in the NFA that make it definitively not one-pass. That way, we
/// can avoid ever trying to build a one-pass DFA in the first place. For
/// example, '\w*\s' is not one-pass, and since '\w' is Unicode-aware by
/// default, it's probably not a trivial cost to try and build a one-pass DFA
/// for it and then fail.
///
/// Note that some (immutable) fields are duplicated here. For example, the
/// 'nfa' and 'classes' fields are both in the 'DFA'. They are the same thing,
/// but we duplicate them because it makes composition easier below. Otherwise,
/// since the borrow checker can't see through method calls, the mutable borrow
/// we use to mutate the DFA winds up preventing borrowing from any other part
/// of the DFA, even though we aren't mutating those parts. We only do this
/// because the duplication is cheap.
#[derive(Debug)]
struct InternalBuilder<'a> {
/// The DFA we're building.
dfa: DFA,
/// An unordered collection of NFA state IDs that we haven't yet tried to
/// build into a DFA state yet.
///
/// This collection does not ultimately wind up including every NFA state
/// ID. Instead, each ID represents a "start" state for a sub-graph of the
/// NFA. The set of NFA states we then use to build a DFA state consists
/// of that "start" state and all states reachable from it via epsilon
/// transitions.
uncompiled_nfa_ids: Vec<StateID>,
/// A map from NFA state ID to DFA state ID. This is useful for easily
/// determining whether an NFA state has been used as a "starting" point
/// to build a DFA state yet. If it hasn't, then it is mapped to DEAD,
/// and since DEAD is specially added and never corresponds to any NFA
/// state, it follows that a mapping to DEAD implies the NFA state has
/// no corresponding DFA state yet.
nfa_to_dfa_id: Vec<StateID>,
/// A stack used to traverse the NFA states that make up a single DFA
/// state. Traversal occurs until the stack is empty, and we only push to
/// the stack when the state ID isn't in 'seen'. Actually, even more than
/// that, if we try to push something on to this stack that is already in
/// 'seen', then we bail out on construction completely, since it implies
/// that the NFA is not one-pass.
stack: Vec<(StateID, Epsilons)>,
/// The set of NFA states that we've visited via 'stack'.
seen: SparseSet,
/// Whether a match NFA state has been observed while constructing a
/// one-pass DFA state. Once a match state is seen, assuming we are using
/// leftmost-first match semantics, then we don't add any more transitions
/// to the DFA state we're building.
matched: bool,
/// The config passed to the builder.
///
/// This is duplicated in dfa.config.
config: Config,
/// The NFA we're building a one-pass DFA from.
///
/// This is duplicated in dfa.nfa.
nfa: &'a NFA,
/// The equivalence classes that make up the alphabet for this DFA>
///
/// This is duplicated in dfa.classes.
classes: ByteClasses,
}
impl<'a> InternalBuilder<'a> {
/// Create a new builder with an initial empty DFA.
fn new(config: Config, nfa: &'a NFA) -> InternalBuilder {
let classes = if !config.get_byte_classes() {
// A one-pass DFA will always use the equivalence class map, but
// enabling this option is useful for debugging. Namely, this will
// cause all transitions to be defined over their actual bytes
// instead of an opaque equivalence class identifier. The former is
// much easier to grok as a human.
ByteClasses::singletons()
} else {
nfa.byte_class_set().byte_classes()
};
// Normally a DFA alphabet includes the EOI symbol, but we don't need
// that in the one-pass DFA since we handle look-around explicitly
// without encoding it into the DFA. Thus, we don't need to delay
// matches by 1 byte. However, we reuse the space that *would* be used
// by the EOI transition by putting match information there (like which
// pattern matches and which look-around assertions need to hold). So
// this means our real alphabet length is 1 fewer than what the byte
// classes report, since we don't use EOI.
let alphabet_len = classes.alphabet_len().checked_sub(1).unwrap();
let stride2 = classes.stride2();
let dfa = DFA {
config: config.clone(),
nfa: nfa.clone(),
table: vec![],
starts: vec![],
// Since one-pass DFAs have a smaller state ID max than
// StateID::MAX, it follows that StateID::MAX is a valid initial
// value for min_match_id since no state ID can ever be greater
// than it. In the case of a one-pass DFA with no match states, the
// min_match_id will keep this sentinel value.
min_match_id: StateID::MAX,
classes: classes.clone(),
alphabet_len,
stride2,
pateps_offset: alphabet_len,
};
InternalBuilder {
dfa,
uncompiled_nfa_ids: vec![],
nfa_to_dfa_id: vec![DEAD; nfa.states().len()],
stack: vec![],
seen: SparseSet::new(nfa.states().len()),
matched: false,
config,
nfa,
classes,
}
}
/// Build the DFA from the NFA given to this builder. If the NFA is not
/// one-pass, then return an error. An error may also be returned if a
/// particular limit is exceeded. (Some limits, like the total heap memory
/// used, are configurable. Others, like the total patterns or slots, are
/// hard-coded based on representational limitations.)
fn build(mut self) -> Result<DFA, Error> {
if self.nfa.pattern_len().as_u64() > PatternEpsilons::PATTERN_ID_LIMIT
{
return Err(Error::one_pass_too_many_patterns(
PatternEpsilons::PATTERN_ID_LIMIT,
));
}
if self.nfa.group_info().explicit_slot_len() > Slots::LIMIT {
return Err(Error::one_pass_fail(
"too many explicit capturing groups (max is 24)",
));
}
assert_eq!(DEAD, self.add_empty_state()?);
// This is where the explicit slots start. We care about this because
// we only need to track explicit slots. The implicit slots---two for
// each pattern---are tracked as part of the search routine itself.
let explicit_slot_start = self.nfa.pattern_len() * 2;
self.add_start_state(None, self.nfa.start_anchored())?;
if self.config.get_starts_for_each_pattern() {
for pid in self.nfa.patterns() {
self.add_start_state(Some(pid), self.nfa.start_pattern(pid))?;
}
}
// NOTE: One wonders what the effects of treating 'uncompiled_nfa_ids'
// as a stack are. It is really an unordered *set* of NFA state IDs.
// If it, for example, in practice led to discovering whether a regex
// was or wasn't one-pass later than if we processed NFA state IDs in
// ascending order, then that would make this routine more costly in
// the somewhat common case of a regex that isn't one-pass.
while let Some(nfa_id) = self.uncompiled_nfa_ids.pop() {
let dfa_id = self.nfa_to_dfa_id[nfa_id];
// Once we see a match, we keep going, but don't add any new
// transitions. Normally we'd just stop, but we have to keep
// going in order to verify that our regex is actually one-pass.
self.matched = false;
// The NFA states we've already explored for this DFA state.
self.seen.clear();
// The NFA states to explore via epsilon transitions. If we ever
// try to push an NFA state that we've already seen, then the NFA
// is not one-pass because it implies there are multiple epsilon
// transition paths that lead to the same NFA state. In other
// words, there is ambiguity.
self.stack_push(nfa_id, Epsilons::empty())?;
while let Some((id, epsilons)) = self.stack.pop() {
match *self.nfa.state(id) {
thompson::State::ByteRange { ref trans } => {
self.compile_transition(dfa_id, trans, epsilons)?;
}
thompson::State::Sparse(ref sparse) => {
for trans in sparse.transitions.iter() {
self.compile_transition(dfa_id, trans, epsilons)?;
}
}
thompson::State::Look { look, next } => {
let looks = epsilons.looks().insert(look);
self.stack_push(next, epsilons.set_looks(looks))?;
}
thompson::State::Union { ref alternates } => {
for &sid in alternates.iter().rev() {
self.stack_push(sid, epsilons)?;
}
}
thompson::State::BinaryUnion { alt1, alt2 } => {
self.stack_push(alt2, epsilons)?;
self.stack_push(alt1, epsilons)?;
}
thompson::State::Capture { next, slot, .. } => {
let slot = slot.as_usize();
let epsilons = if slot < explicit_slot_start {
// If this is an implicit slot, we don't care
// about it, since we handle implicit slots in
// the search routine. We can get away with that
// because there are 2 implicit slots for every
// pattern.
epsilons
} else {
// Offset our explicit slots so that they start
// at index 0.
let offset = slot - explicit_slot_start;
epsilons.set_slots(epsilons.slots().insert(offset))
};
self.stack_push(next, epsilons)?;
}
thompson::State::Fail => {
continue;
}
thompson::State::Match { pattern_id } => {
// If we found two different paths to a match state
// for the same DFA state, then we have ambiguity.
// Thus, it's not one-pass.
if self.matched {
return Err(Error::one_pass_fail(
"multiple epsilon transitions to match state",
));
}
self.matched = true;
// Shove the matching pattern ID and the 'epsilons'
// into the current DFA state's pattern epsilons. The
// 'epsilons' includes the slots we need to capture
// before reporting the match and also the conditional
// epsilon transitions we need to check before we can
// report a match.
self.dfa.set_pattern_epsilons(
dfa_id,
PatternEpsilons::empty()
.set_pattern_id(pattern_id)
.set_epsilons(epsilons),
);
// N.B. It is tempting to just bail out here when
// compiling a leftmost-first DFA, since we will never
// compile any more transitions in that case. But we
// actually need to keep going in order to verify that
// we actually have a one-pass regex. e.g., We might
// see more Match states (e.g., for other patterns)
// that imply that we don't have a one-pass regex.
// So instead, we mark that we've found a match and
// continue on. When we go to compile a new DFA state,
// we just skip that part. But otherwise check that the
// one-pass property is upheld.
}
}
}
}
self.shuffle_states();
Ok(self.dfa)
}
/// Shuffle all match states to the end of the transition table and set
/// 'min_match_id' to the ID of the first such match state.
///
/// The point of this is to make it extremely cheap to determine whether
/// a state is a match state or not. We need to check on this on every
/// transition during a search, so it being cheap is important. This
/// permits us to check it by simply comparing two state identifiers, as
/// opposed to looking for the pattern ID in the state's `PatternInfo`.
/// (Which requires a memory load and some light arithmetic.)
fn shuffle_states(&mut self) {
let mut remapper = Remapper::new(&self.dfa);
let mut next_dest = self.dfa.last_state_id();
for i in (0..self.dfa.state_len()).rev() {
let id = self.dfa.to_state_id(i);
let is_match =
self.dfa.pattern_epsilons(id).pattern_id().is_some();
if !is_match {
continue;
}
remapper.swap(&mut self.dfa, next_dest, id);
self.dfa.min_match_id = next_dest;
next_dest = self.dfa.prev_state_id(next_dest).expect(
"match states should be a proper subset of all states",
);
}
remapper.remap(&mut self.dfa);
}
/// Compile the given NFA transition into the DFA state given.
///
/// 'Info' corresponds to any conditional epsilon transitions that need to
/// be satisfied to follow this transition, and any slots that need to be
/// saved if the transition is followed.
///
/// If this transition indicates that the NFA is not one-pass, then
/// this returns an error. (This occurs, for example, if the DFA state
/// already has a transition defined for the same input symbols as the
/// given transition, *and* the result of the old and new transitions is
/// different.)
fn compile_transition(
&mut self,
dfa_id: StateID,
trans: &thompson::Transition,
epsilons: Epsilons,
) -> Result<(), Error> {
// If we already have seen a match and we are compiling a leftmost
// first DFA, then we shouldn't add any more transitions. This is
// effectively how preference order and non-greediness is implemented.
if !self.config.get_match_kind().continue_past_first_match()
&& self.matched
{
return Ok(());
}
let next_dfa_id = self.add_dfa_state_for_nfa_state(trans.next)?;
for byte in self
.classes
.representatives(trans.start..=trans.end)
.filter_map(|r| r.as_u8())
{
let oldtrans = self.dfa.transition(dfa_id, byte);
let newtrans = Transition::new(next_dfa_id, epsilons);
// If the old transition points to the DEAD state, then we know
// 'byte' has not been mapped to any transition for this DFA state
// yet. So set it unconditionally. Otherwise, we require that the
// old and new transitions are equivalent. Otherwise, there is
// ambiguity and thus the regex is not one-pass.
if oldtrans.state_id() == DEAD {
self.dfa.set_transition(dfa_id, byte, newtrans);
} else if oldtrans != newtrans {
return Err(Error::one_pass_fail("conflicting transition"));
}
}
Ok(())
}
/// Add a start state to the DFA corresponding to the given NFA starting
/// state ID.
///
/// If adding a state would blow any limits (configured or hard-coded),
/// then an error is returned.
///
/// If the starting state is an anchored state for a particular pattern,
/// then callers must provide the pattern ID for that starting state.
/// Callers must also ensure that the first starting state added is the
/// start state for all patterns, and then each anchored starting state for
/// each pattern (if necessary) added in order. Otherwise, this panics.
fn add_start_state(
&mut self,
pid: Option<PatternID>,
nfa_id: StateID,
) -> Result<StateID, Error> {
match pid {
// With no pid, this should be the start state for all patterns
// and thus be the first one.
None => assert!(self.dfa.starts.is_empty()),
// With a pid, we want it to be at self.dfa.starts[pid+1].
Some(pid) => assert!(self.dfa.starts.len() == pid.one_more()),
}
let dfa_id = self.add_dfa_state_for_nfa_state(nfa_id)?;
self.dfa.starts.push(dfa_id);
Ok(dfa_id)
}
/// Add a new DFA state corresponding to the given NFA state. If adding a
/// state would blow any limits (configured or hard-coded), then an error
/// is returned. If a DFA state already exists for the given NFA state,
/// then that DFA state's ID is returned and no new states are added.
///
/// It is not expected that this routine is called for every NFA state.
/// Instead, an NFA state ID will usually correspond to the "start" state
/// for a sub-graph of the NFA, where all states in the sub-graph are
/// reachable via epsilon transitions (conditional or unconditional). That
/// sub-graph of NFA states is ultimately what produces a single DFA state.
fn add_dfa_state_for_nfa_state(
&mut self,
nfa_id: StateID,
) -> Result<StateID, Error> {
// If we've already built a DFA state for the given NFA state, then
// just return that. We definitely do not want to have more than one
// DFA state in existence for the same NFA state, since all but one of
// them will likely become unreachable. And at least some of them are
// likely to wind up being incomplete.
let existing_dfa_id = self.nfa_to_dfa_id[nfa_id];
if existing_dfa_id != DEAD {
return Ok(existing_dfa_id);
}
// If we don't have any DFA state yet, add it and then add the given
// NFA state to the list of states to explore.
let dfa_id = self.add_empty_state()?;
self.nfa_to_dfa_id[nfa_id] = dfa_id;
self.uncompiled_nfa_ids.push(nfa_id);
Ok(dfa_id)
}
/// Unconditionally add a new empty DFA state. If adding it would exceed
/// any limits (configured or hard-coded), then an error is returned. The
/// ID of the new state is returned on success.
///
/// The added state is *not* a match state.
fn add_empty_state(&mut self) -> Result<StateID, Error> {
let next = self.dfa.table.len();
let id = StateID::new(next).map_err(|_| Error::too_many_states())?;
if id.as_u64() > Transition::STATE_ID_LIMIT {
let state_limit =
Transition::STATE_ID_LIMIT / self.dfa.stride().as_u64();
return Err(Error::one_pass_too_many_states(state_limit));
}
self.dfa
.table
.extend(core::iter::repeat(Transition(0)).take(self.dfa.stride()));
// The default empty value for 'PatternInfo' is sadly not all zeroes.
// Instead, a special sentinel is used to indicate that there is no
// pattern. So we need to explicitly set the pattern epsilons to the
// correct "empty" PatternInfo.
self.dfa.set_pattern_epsilons(id, PatternEpsilons::empty());
if let Some(size_limit) = self.config.get_size_limit() {
if self.dfa.memory_usage() > size_limit {
return Err(Error::one_pass_exceeded_size_limit(size_limit));
}
}
Ok(id)
}
/// Push the given NFA state ID and its corresponding epsilons (slots and
/// conditional epsilon transitions) on to a stack for use in a depth first
/// traversal of a sub-graph of the NFA.
///
/// If the given NFA state ID has already been pushed on to the stack, then
/// it indicates the regex is not one-pass and this correspondingly returns
/// an error.
fn stack_push(
&mut self,
nfa_id: StateID,
epsilons: Epsilons,
) -> Result<(), Error> {
if !self.seen.insert(nfa_id) {
return Err(Error::one_pass_fail(
"multiple epsilon transitions to same state",
));