-
Notifications
You must be signed in to change notification settings - Fork 461
/
Copy pathcompiler.rs
2346 lines (2202 loc) · 84.1 KB
/
compiler.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
use core::{borrow::Borrow, cell::RefCell};
use alloc::{sync::Arc, vec, vec::Vec};
use regex_syntax::{
hir::{self, Hir},
utf8::{Utf8Range, Utf8Sequences},
ParserBuilder,
};
use crate::{
nfa::thompson::{
builder::Builder,
error::BuildError,
literal_trie::LiteralTrie,
map::{Utf8BoundedMap, Utf8SuffixKey, Utf8SuffixMap},
nfa::{Transition, NFA},
range_trie::RangeTrie,
},
util::{
look::{Look, LookMatcher},
primitives::{PatternID, StateID},
},
};
/// The configuration used for a Thompson NFA compiler.
#[derive(Clone, Debug, Default)]
pub struct Config {
utf8: Option<bool>,
reverse: Option<bool>,
nfa_size_limit: Option<Option<usize>>,
shrink: Option<bool>,
which_captures: Option<WhichCaptures>,
look_matcher: Option<LookMatcher>,
#[cfg(test)]
unanchored_prefix: Option<bool>,
}
impl Config {
/// Return a new default Thompson NFA compiler configuration.
pub fn new() -> Config {
Config::default()
}
/// Whether to enable UTF-8 mode during search or not.
///
/// A regex engine is said to be in UTF-8 mode when it guarantees that
/// all matches returned by it have spans consisting of only valid UTF-8.
/// That is, it is impossible for a match span to be returned that
/// contains any invalid UTF-8.
///
/// UTF-8 mode generally consists of two things:
///
/// 1. Whether the NFA's states are constructed such that all paths to a
/// match state that consume at least one byte always correspond to valid
/// UTF-8.
/// 2. Whether all paths to a match state that do _not_ consume any bytes
/// should always correspond to valid UTF-8 boundaries.
///
/// (1) is a guarantee made by whoever constructs the NFA.
/// If you're parsing a regex from its concrete syntax, then
/// [`syntax::Config::utf8`](crate::util::syntax::Config::utf8) can make
/// this guarantee for you. It does it by returning an error if the regex
/// pattern could every report a non-empty match span that contains invalid
/// UTF-8. So long as `syntax::Config::utf8` mode is enabled and your regex
/// successfully parses, then you're guaranteed that the corresponding NFA
/// will only ever report non-empty match spans containing valid UTF-8.
///
/// (2) is a trickier guarantee because it cannot be enforced by the NFA
/// state graph itself. Consider, for example, the regex `a*`. It matches
/// the empty strings in `☃` at positions `0`, `1`, `2` and `3`, where
/// positions `1` and `2` occur within the UTF-8 encoding of a codepoint,
/// and thus correspond to invalid UTF-8 boundaries. Therefore, this
/// guarantee must be made at a higher level than the NFA state graph
/// itself. This crate deals with this case in each regex engine. Namely,
/// when a zero-width match that splits a codepoint is found and UTF-8
/// mode enabled, then it is ignored and the engine moves on looking for
/// the next match.
///
/// Thus, UTF-8 mode is both a promise that the NFA built only reports
/// non-empty matches that are valid UTF-8, and an *instruction* to regex
/// engines that empty matches that split codepoints should be banned.
///
/// Because UTF-8 mode is fundamentally about avoiding invalid UTF-8 spans,
/// it only makes sense to enable this option when you *know* your haystack
/// is valid UTF-8. (For example, a `&str`.) Enabling UTF-8 mode and
/// searching a haystack that contains invalid UTF-8 leads to **unspecified
/// behavior**.
///
/// Therefore, it may make sense to enable `syntax::Config::utf8` while
/// simultaneously *disabling* this option. That would ensure all non-empty
/// match spans are valid UTF-8, but that empty match spans may still split
/// a codepoint or match at other places that aren't valid UTF-8.
///
/// In general, this mode is only relevant if your regex can match the
/// empty string. Most regexes don't.
///
/// This is enabled by default.
///
/// # Example
///
/// This example shows how UTF-8 mode can impact the match spans that may
/// be reported in certain cases.
///
/// ```
/// use regex_automata::{
/// nfa::thompson::{self, pikevm::PikeVM},
/// Match, Input,
/// };
///
/// let re = PikeVM::new("")?;
/// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
///
/// // UTF-8 mode is enabled by default.
/// let mut input = Input::new("☃");
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 0..0)), caps.get_match());
///
/// // Even though an empty regex matches at 1..1, our next match is
/// // 3..3 because 1..1 and 2..2 split the snowman codepoint (which is
/// // three bytes long).
/// input.set_start(1);
/// re.search(&mut cache, &input, &mut caps);
/// assert_eq!(Some(Match::must(0, 3..3)), caps.get_match());
///
/// // But if we disable UTF-8, then we'll get matches at 1..1 and 2..2:
/// let re = PikeVM::builder()
/// .thompson(thompson::Config::new().utf8(false))
/// .build("")?;
/// 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!(None, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn utf8(mut self, yes: bool) -> Config {
self.utf8 = Some(yes);
self
}
/// Reverse the NFA.
///
/// A NFA reversal is performed by reversing all of the concatenated
/// sub-expressions in the original pattern, recursively. (Look around
/// operators are also inverted.) The resulting NFA can be used to match
/// the pattern starting from the end of a string instead of the beginning
/// of a string.
///
/// Reversing the NFA is useful for building a reverse DFA, which is most
/// useful for finding the start of a match after its ending position has
/// been found. NFA execution engines typically do not work on reverse
/// NFAs. For example, currently, the Pike VM reports the starting location
/// of matches without a reverse NFA.
///
/// Currently, enabling this setting requires disabling the
/// [`captures`](Config::captures) setting. If both are enabled, then the
/// compiler will return an error. It is expected that this limitation will
/// be lifted in the future.
///
/// This is disabled by default.
///
/// # Example
///
/// This example shows how to build a DFA from a reverse NFA, and then use
/// the DFA to search backwards.
///
/// ```
/// use regex_automata::{
/// dfa::{self, Automaton},
/// nfa::thompson::{NFA, WhichCaptures},
/// HalfMatch, Input,
/// };
///
/// let dfa = dfa::dense::Builder::new()
/// .thompson(NFA::config()
/// .which_captures(WhichCaptures::None)
/// .reverse(true)
/// )
/// .build("baz[0-9]+")?;
/// let expected = Some(HalfMatch::must(0, 3));
/// assert_eq!(
/// expected,
/// dfa.try_search_rev(&Input::new("foobaz12345bar"))?,
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn reverse(mut self, yes: bool) -> Config {
self.reverse = Some(yes);
self
}
/// Sets an approximate size limit on the total heap used by the NFA being
/// compiled.
///
/// This permits imposing constraints on the size of a compiled NFA. This
/// may be useful in contexts where the regex pattern is untrusted and one
/// wants to avoid using too much memory.
///
/// This size limit does not apply to auxiliary heap used during
/// compilation that is not part of the built NFA.
///
/// Note that this size limit is applied during compilation in order for
/// the limit to prevent too much heap from being used. However, the
/// implementation may use an intermediate NFA representation that is
/// otherwise slightly bigger than the final public form. Since the size
/// limit may be applied to an intermediate representation, there is not
/// necessarily a precise correspondence between the configured size limit
/// and the heap usage of the final NFA.
///
/// There is no size limit by default.
///
/// # Example
///
/// This example demonstrates how Unicode mode can greatly increase the
/// size of the NFA.
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::nfa::thompson::NFA;
///
/// // 400KB isn't enough!
/// NFA::compiler()
/// .configure(NFA::config().nfa_size_limit(Some(400_000)))
/// .build(r"\w{20}")
/// .unwrap_err();
///
/// // ... but 500KB probably is.
/// let nfa = NFA::compiler()
/// .configure(NFA::config().nfa_size_limit(Some(500_000)))
/// .build(r"\w{20}")?;
///
/// assert_eq!(nfa.pattern_len(), 1);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn nfa_size_limit(mut self, bytes: Option<usize>) -> Config {
self.nfa_size_limit = Some(bytes);
self
}
/// Apply best effort heuristics to shrink the NFA at the expense of more
/// time/memory.
///
/// Generally speaking, if one is using an NFA to compile a DFA, then the
/// extra time used to shrink the NFA will be more than made up for during
/// DFA construction (potentially by a lot). In other words, enabling this
/// can substantially decrease the overall amount of time it takes to build
/// a DFA.
///
/// A reason to keep this disabled is if you want to compile an NFA and
/// start using it as quickly as possible without needing to build a DFA,
/// and you don't mind using a bit of extra memory for the NFA. e.g., for
/// an NFA simulation or for a lazy DFA.
///
/// NFA shrinking is currently most useful when compiling a reverse
/// NFA with large Unicode character classes. In particular, it trades
/// additional CPU time during NFA compilation in favor of generating fewer
/// NFA states.
///
/// This is disabled by default because it can increase compile times
/// quite a bit if you aren't building a full DFA.
///
/// # Example
///
/// This example shows that NFA shrinking can lead to substantial space
/// savings in some cases. Notice that, as noted above, we build a reverse
/// DFA and use a pattern with a large Unicode character class.
///
/// ```
/// # if cfg!(miri) { return Ok(()); } // miri takes too long
/// use regex_automata::nfa::thompson::{NFA, WhichCaptures};
///
/// // Currently we have to disable captures when enabling reverse NFA.
/// let config = NFA::config()
/// .which_captures(WhichCaptures::None)
/// .reverse(true);
/// let not_shrunk = NFA::compiler()
/// .configure(config.clone().shrink(false))
/// .build(r"\w")?;
/// let shrunk = NFA::compiler()
/// .configure(config.clone().shrink(true))
/// .build(r"\w")?;
///
/// // While a specific shrink factor is not guaranteed, the savings can be
/// // considerable in some cases.
/// assert!(shrunk.states().len() * 2 < not_shrunk.states().len());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn shrink(mut self, yes: bool) -> Config {
self.shrink = Some(yes);
self
}
/// Whether to include 'Capture' states in the NFA.
///
/// Currently, enabling this setting requires disabling the
/// [`reverse`](Config::reverse) setting. If both are enabled, then the
/// compiler will return an error. It is expected that this limitation will
/// be lifted in the future.
///
/// This is enabled by default.
///
/// # Example
///
/// This example demonstrates that some regex engines, like the Pike VM,
/// require capturing states to be present in the NFA to report match
/// offsets.
///
/// (Note that since this method is deprecated, the example below uses
/// [`Config::which_captures`] to disable capture states.)
///
/// ```
/// use regex_automata::nfa::thompson::{
/// pikevm::PikeVM,
/// NFA,
/// WhichCaptures,
/// };
///
/// let re = PikeVM::builder()
/// .thompson(NFA::config().which_captures(WhichCaptures::None))
/// .build(r"[a-z]+")?;
/// let mut cache = re.create_cache();
///
/// assert!(re.is_match(&mut cache, "abc"));
/// assert_eq!(None, re.find(&mut cache, "abc"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[deprecated(since = "0.3.5", note = "use which_captures instead")]
pub fn captures(self, yes: bool) -> Config {
self.which_captures(if yes {
WhichCaptures::All
} else {
WhichCaptures::None
})
}
/// Configures what kinds of capture groups are compiled into
/// [`State::Capture`](crate::nfa::thompson::State::Capture) states in a
/// Thompson NFA.
///
/// Currently, using any option except for [`WhichCaptures::None`] requires
/// disabling the [`reverse`](Config::reverse) setting. If both are
/// enabled, then the compiler will return an error. It is expected that
/// this limitation will be lifted in the future.
///
/// This is set to [`WhichCaptures::All`] by default. Callers may wish to
/// use [`WhichCaptures::Implicit`] in cases where one wants avoid the
/// overhead of capture states for explicit groups. Usually this occurs
/// when one wants to use the `PikeVM` only for determining the overall
/// match. Otherwise, the `PikeVM` could use much more memory than is
/// necessary.
///
/// # Example
///
/// This example demonstrates that some regex engines, like the Pike VM,
/// require capturing states to be present in the NFA to report match
/// offsets.
///
/// ```
/// use regex_automata::nfa::thompson::{
/// pikevm::PikeVM,
/// NFA,
/// WhichCaptures,
/// };
///
/// let re = PikeVM::builder()
/// .thompson(NFA::config().which_captures(WhichCaptures::None))
/// .build(r"[a-z]+")?;
/// let mut cache = re.create_cache();
///
/// assert!(re.is_match(&mut cache, "abc"));
/// assert_eq!(None, re.find(&mut cache, "abc"));
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// The same applies to the bounded backtracker:
///
/// ```
/// use regex_automata::nfa::thompson::{
/// backtrack::BoundedBacktracker,
/// NFA,
/// WhichCaptures,
/// };
///
/// let re = BoundedBacktracker::builder()
/// .thompson(NFA::config().which_captures(WhichCaptures::None))
/// .build(r"[a-z]+")?;
/// let mut cache = re.create_cache();
///
/// assert!(re.try_is_match(&mut cache, "abc")?);
/// assert_eq!(None, re.try_find(&mut cache, "abc")?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn which_captures(mut self, which_captures: WhichCaptures) -> Config {
self.which_captures = Some(which_captures);
self
}
/// Sets the look-around matcher that should be used with this NFA.
///
/// A look-around matcher determines how to match look-around assertions.
/// In particular, some assertions are configurable. For example, the
/// `(?m:^)` and `(?m:$)` assertions can have their line terminator changed
/// from the default of `\n` to any other byte.
///
/// # Example
///
/// This shows how to change the line terminator for multi-line assertions.
///
/// ```
/// use regex_automata::{
/// nfa::thompson::{self, pikevm::PikeVM},
/// util::look::LookMatcher,
/// Match, Input,
/// };
///
/// let mut lookm = LookMatcher::new();
/// lookm.set_line_terminator(b'\x00');
///
/// let re = PikeVM::builder()
/// .thompson(thompson::Config::new().look_matcher(lookm))
/// .build(r"(?m)^[a-z]+$")?;
/// let mut cache = re.create_cache();
///
/// // Multi-line assertions now use NUL as a terminator.
/// assert_eq!(
/// Some(Match::must(0, 1..4)),
/// re.find(&mut cache, b"\x00abc\x00"),
/// );
/// // ... and \n is no longer recognized as a terminator.
/// assert_eq!(
/// None,
/// re.find(&mut cache, b"\nabc\n"),
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn look_matcher(mut self, m: LookMatcher) -> Config {
self.look_matcher = Some(m);
self
}
/// Whether to compile an unanchored prefix into this NFA.
///
/// This is enabled by default. It is made available for tests only to make
/// it easier to unit test the output of the compiler.
#[cfg(test)]
fn unanchored_prefix(mut self, yes: bool) -> Config {
self.unanchored_prefix = Some(yes);
self
}
/// Returns whether this configuration has enabled UTF-8 mode.
pub fn get_utf8(&self) -> bool {
self.utf8.unwrap_or(true)
}
/// Returns whether this configuration has enabled reverse NFA compilation.
pub fn get_reverse(&self) -> bool {
self.reverse.unwrap_or(false)
}
/// Return the configured NFA size limit, if it exists, in the number of
/// bytes of heap used.
pub fn get_nfa_size_limit(&self) -> Option<usize> {
self.nfa_size_limit.unwrap_or(None)
}
/// Return whether NFA shrinking is enabled.
pub fn get_shrink(&self) -> bool {
self.shrink.unwrap_or(false)
}
/// Return whether NFA compilation is configured to produce capture states.
#[deprecated(since = "0.3.5", note = "use get_which_captures instead")]
pub fn get_captures(&self) -> bool {
self.get_which_captures().is_any()
}
/// Return what kinds of capture states will be compiled into an NFA.
pub fn get_which_captures(&self) -> WhichCaptures {
self.which_captures.unwrap_or(WhichCaptures::All)
}
/// Return the look-around matcher for this NFA.
pub fn get_look_matcher(&self) -> LookMatcher {
self.look_matcher.clone().unwrap_or(LookMatcher::default())
}
/// Return whether NFA compilation is configured to include an unanchored
/// prefix.
///
/// This is always false when not in test mode.
fn get_unanchored_prefix(&self) -> bool {
#[cfg(test)]
{
self.unanchored_prefix.unwrap_or(true)
}
#[cfg(not(test))]
{
true
}
}
/// 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 {
utf8: o.utf8.or(self.utf8),
reverse: o.reverse.or(self.reverse),
nfa_size_limit: o.nfa_size_limit.or(self.nfa_size_limit),
shrink: o.shrink.or(self.shrink),
which_captures: o.which_captures.or(self.which_captures),
look_matcher: o.look_matcher.or_else(|| self.look_matcher.clone()),
#[cfg(test)]
unanchored_prefix: o.unanchored_prefix.or(self.unanchored_prefix),
}
}
}
/// A configuration indicating which kinds of
/// [`State::Capture`](crate::nfa::thompson::State::Capture) states to include.
///
/// This configuration can be used with [`Config::which_captures`] to control
/// which capture states are compiled into a Thompson NFA.
///
/// The default configuration is [`WhichCaptures::All`].
#[derive(Clone, Copy, Debug)]
pub enum WhichCaptures {
/// All capture states, including those corresponding to both implicit and
/// explicit capture groups, are included in the Thompson NFA.
All,
/// Only capture states corresponding to implicit capture groups are
/// included. Implicit capture groups appear in every pattern implicitly
/// and correspond to the overall match of a pattern.
///
/// This is useful when one only cares about the overall match of a
/// pattern. By excluding capture states from explicit capture groups,
/// one might be able to reduce the memory usage of a multi-pattern regex
/// substantially if it was otherwise written to have many explicit capture
/// groups.
Implicit,
/// No capture states are compiled into the Thompson NFA.
///
/// This is useful when capture states are either not needed (for example,
/// if one is only trying to build a DFA) or if they aren't supported (for
/// example, a reverse NFA).
None,
}
impl Default for WhichCaptures {
fn default() -> WhichCaptures {
WhichCaptures::All
}
}
impl WhichCaptures {
/// Returns true if this configuration indicates that no capture states
/// should be produced in an NFA.
pub fn is_none(&self) -> bool {
matches!(*self, WhichCaptures::None)
}
/// Returns true if this configuration indicates that some capture states
/// should be added to an NFA. Note that this might only include capture
/// states for implicit capture groups.
pub fn is_any(&self) -> bool {
!self.is_none()
}
}
/*
This compiler below uses Thompson's construction algorithm. The compiler takes
a regex-syntax::Hir as input and emits an NFA graph as output. The NFA graph
is structured in a way that permits it to be executed by a virtual machine and
also used to efficiently build a DFA.
The compiler deals with a slightly expanded set of NFA states than what is
in a final NFA (as exhibited by builder::State and nfa::State). Notably a
compiler state includes an empty node that has exactly one unconditional
epsilon transition to the next state. In other words, it's a "goto" instruction
if one views Thompson's NFA as a set of bytecode instructions. These goto
instructions are removed in a subsequent phase before returning the NFA to the
caller. The purpose of these empty nodes is that they make the construction
algorithm substantially simpler to implement. We remove them before returning
to the caller because they can represent substantial overhead when traversing
the NFA graph (either while searching using the NFA directly or while building
a DFA).
In the future, it would be nice to provide a Glushkov compiler as well, as it
would work well as a bit-parallel NFA for smaller regexes. But the Thompson
construction is one I'm more familiar with and seems more straight-forward to
deal with when it comes to large Unicode character classes.
Internally, the compiler uses interior mutability to improve composition in the
face of the borrow checker. In particular, we'd really like to be able to write
things like this:
self.c_concat(exprs.iter().map(|e| self.c(e)))
Which elegantly uses iterators to build up a sequence of compiled regex
sub-expressions and then hands it off to the concatenating compiler routine.
Without interior mutability, the borrow checker won't let us borrow `self`
mutably both inside and outside the closure at the same time.
*/
/// A builder for compiling an NFA from a regex's high-level intermediate
/// representation (HIR).
///
/// This compiler provides a way to translate a parsed regex pattern into an
/// NFA state graph. The NFA state graph can either be used directly to execute
/// a search (e.g., with a Pike VM), or it can be further used to build a DFA.
///
/// This compiler provides APIs both for compiling regex patterns directly from
/// their concrete syntax, or via a [`regex_syntax::hir::Hir`].
///
/// This compiler has various options that may be configured via
/// [`thompson::Config`](Config).
///
/// Note that a compiler is not the same as a [`thompson::Builder`](Builder).
/// A `Builder` provides a lower level API that is uncoupled from a regex
/// pattern's concrete syntax or even its HIR. Instead, it permits stitching
/// together an NFA by hand. See its docs for examples.
///
/// # Example: compilation from concrete syntax
///
/// This shows how to compile an NFA from a pattern string while setting a size
/// limit on how big the NFA is allowed to be (in terms of bytes of heap used).
///
/// ```
/// use regex_automata::{
/// nfa::thompson::{NFA, pikevm::PikeVM},
/// Match,
/// };
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(0, 3..4));
/// re.captures(&mut cache, "!@#A#@!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: compilation from HIR
///
/// This shows how to hand assemble a regular expression via its HIR, and then
/// compile an NFA directly from it.
///
/// ```
/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
/// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
///
/// let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![
/// ClassBytesRange::new(b'0', b'9'),
/// ClassBytesRange::new(b'A', b'Z'),
/// ClassBytesRange::new(b'_', b'_'),
/// ClassBytesRange::new(b'a', b'z'),
/// ])));
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build_from_hir(&hir)?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(0, 3..4));
/// re.captures(&mut cache, "!@#A#@!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct Compiler {
/// A regex parser, used when compiling an NFA directly from a pattern
/// string.
parser: ParserBuilder,
/// The compiler configuration.
config: Config,
/// The builder for actually constructing an NFA. This provides a
/// convenient abstraction for writing a compiler.
builder: RefCell<Builder>,
/// State used for compiling character classes to UTF-8 byte automata.
/// State is not retained between character class compilations. This just
/// serves to amortize allocation to the extent possible.
utf8_state: RefCell<Utf8State>,
/// State used for arranging character classes in reverse into a trie.
trie_state: RefCell<RangeTrie>,
/// State used for caching common suffixes when compiling reverse UTF-8
/// automata (for Unicode character classes).
utf8_suffix: RefCell<Utf8SuffixMap>,
}
impl Compiler {
/// Create a new NFA builder with its default configuration.
pub fn new() -> Compiler {
Compiler {
parser: ParserBuilder::new(),
config: Config::default(),
builder: RefCell::new(Builder::new()),
utf8_state: RefCell::new(Utf8State::new()),
trie_state: RefCell::new(RangeTrie::new()),
utf8_suffix: RefCell::new(Utf8SuffixMap::new(1000)),
}
}
/// Compile the given regular expression pattern into an NFA.
///
/// If there was a problem parsing the regex, then that error is returned.
///
/// Otherwise, if there was a problem building the NFA, then an error is
/// returned. The only error that can occur is if the compiled regex would
/// exceed the size limits configured on this builder, or if any part of
/// the NFA would exceed the integer representations used. (For example,
/// too many states might plausibly occur on a 16-bit target.)
///
/// # Example
///
/// ```
/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(0, 3..4));
/// re.captures(&mut cache, "!@#A#@!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn build(&self, pattern: &str) -> Result<NFA, BuildError> {
self.build_many(&[pattern])
}
/// Compile the given regular expression patterns into a single NFA.
///
/// When matches are returned, the pattern ID corresponds to the index of
/// the pattern in the slice given.
///
/// # Example
///
/// ```
/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build_many(&[
/// r"(?-u)\s",
/// r"(?-u)\w",
/// ])?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(1, 1..2));
/// re.captures(&mut cache, "!A! !A!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn build_many<P: AsRef<str>>(
&self,
patterns: &[P],
) -> Result<NFA, BuildError> {
let mut hirs = vec![];
for p in patterns {
hirs.push(
self.parser
.build()
.parse(p.as_ref())
.map_err(BuildError::syntax)?,
);
debug!("parsed: {:?}", p.as_ref());
}
self.build_many_from_hir(&hirs)
}
/// Compile the given high level intermediate representation of a regular
/// expression into an NFA.
///
/// If there was a problem building the NFA, then an error is returned. The
/// only error that can occur is if the compiled regex would exceed the
/// size limits configured on this builder, or if any part of the NFA would
/// exceed the integer representations used. (For example, too many states
/// might plausibly occur on a 16-bit target.)
///
/// # Example
///
/// ```
/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
/// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
///
/// let hir = Hir::class(Class::Bytes(ClassBytes::new(vec![
/// ClassBytesRange::new(b'0', b'9'),
/// ClassBytesRange::new(b'A', b'Z'),
/// ClassBytesRange::new(b'_', b'_'),
/// ClassBytesRange::new(b'a', b'z'),
/// ])));
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build_from_hir(&hir)?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(0, 3..4));
/// re.captures(&mut cache, "!@#A#@!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn build_from_hir(&self, expr: &Hir) -> Result<NFA, BuildError> {
self.build_many_from_hir(&[expr])
}
/// Compile the given high level intermediate representations of regular
/// expressions into a single NFA.
///
/// When matches are returned, the pattern ID corresponds to the index of
/// the pattern in the slice given.
///
/// # Example
///
/// ```
/// use regex_automata::{nfa::thompson::{NFA, pikevm::PikeVM}, Match};
/// use regex_syntax::hir::{Hir, Class, ClassBytes, ClassBytesRange};
///
/// let hirs = &[
/// Hir::class(Class::Bytes(ClassBytes::new(vec![
/// ClassBytesRange::new(b'\t', b'\r'),
/// ClassBytesRange::new(b' ', b' '),
/// ]))),
/// Hir::class(Class::Bytes(ClassBytes::new(vec![
/// ClassBytesRange::new(b'0', b'9'),
/// ClassBytesRange::new(b'A', b'Z'),
/// ClassBytesRange::new(b'_', b'_'),
/// ClassBytesRange::new(b'a', b'z'),
/// ]))),
/// ];
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build_many_from_hir(hirs)?;
///
/// let re = PikeVM::new_from_nfa(nfa)?;
/// let mut cache = re.create_cache();
/// let mut caps = re.create_captures();
/// let expected = Some(Match::must(1, 1..2));
/// re.captures(&mut cache, "!A! !A!", &mut caps);
/// assert_eq!(expected, caps.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn build_many_from_hir<H: Borrow<Hir>>(
&self,
exprs: &[H],
) -> Result<NFA, BuildError> {
self.compile(exprs)
}
/// Apply the given NFA configuration options to this builder.
///
/// # Example
///
/// ```
/// use regex_automata::nfa::thompson::NFA;
///
/// let config = NFA::config().nfa_size_limit(Some(1_000));
/// let nfa = NFA::compiler().configure(config).build(r"(?-u)\w")?;
/// assert_eq!(nfa.pattern_len(), 1);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn configure(&mut self, config: Config) -> &mut Compiler {
self.config = self.config.overwrite(config);
self
}
/// Set the syntax configuration for this builder using
/// [`syntax::Config`](crate::util::syntax::Config).
///
/// This permits setting things like case insensitivity, Unicode and multi
/// line mode.
///
/// This syntax configuration only applies when an NFA is built directly
/// from a pattern string. If an NFA is built from an HIR, then all syntax
/// settings are ignored.
///
/// # Example
///
/// ```
/// use regex_automata::{nfa::thompson::NFA, util::syntax};
///
/// let syntax_config = syntax::Config::new().unicode(false);
/// let nfa = NFA::compiler().syntax(syntax_config).build(r"\w")?;
/// // If Unicode were enabled, the number of states would be much bigger.
/// assert!(nfa.states().len() < 15);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn syntax(
&mut self,
config: crate::util::syntax::Config,
) -> &mut Compiler {
config.apply(&mut self.parser);
self
}
}
impl Compiler {
/// Compile the sequence of HIR expressions given. Pattern IDs are
/// allocated starting from 0, in correspondence with the slice given.
///
/// It is legal to provide an empty slice. In that case, the NFA returned
/// has no patterns and will never match anything.
fn compile<H: Borrow<Hir>>(&self, exprs: &[H]) -> Result<NFA, BuildError> {
if exprs.len() > PatternID::LIMIT {
return Err(BuildError::too_many_patterns(exprs.len()));
}
if self.config.get_reverse()
&& self.config.get_which_captures().is_any()
{
return Err(BuildError::unsupported_captures());
}
self.builder.borrow_mut().clear();
self.builder.borrow_mut().set_utf8(self.config.get_utf8());
self.builder.borrow_mut().set_reverse(self.config.get_reverse());
self.builder
.borrow_mut()
.set_look_matcher(self.config.get_look_matcher());
self.builder
.borrow_mut()
.set_size_limit(self.config.get_nfa_size_limit())?;
// We always add an unanchored prefix unless we were specifically told
// not to (for tests only), or if we know that the regex is anchored
// for all matches. When an unanchored prefix is not added, then the
// NFA's anchored and unanchored start states are equivalent.
let all_anchored = exprs.iter().all(|e| {
let props = e.borrow().properties();
if self.config.get_reverse() {
props.look_set_suffix().contains(hir::Look::End)
} else {
props.look_set_prefix().contains(hir::Look::Start)
}
});
let anchored = !self.config.get_unanchored_prefix() || all_anchored;
let unanchored_prefix = if anchored {
self.c_empty()?
} else {
self.c_at_least(&Hir::dot(hir::Dot::AnyByte), false, 0)?
};
let compiled = self.c_alt_iter(exprs.iter().map(|e| {
let _ = self.start_pattern()?;
let one = self.c_cap(0, None, e.borrow())?;
let match_state_id = self.add_match()?;
self.patch(one.end, match_state_id)?;
let _ = self.finish_pattern(one.start)?;
Ok(ThompsonRef { start: one.start, end: match_state_id })
}))?;
self.patch(unanchored_prefix.end, compiled.start)?;
let nfa = self
.builder
.borrow_mut()
.build(compiled.start, unanchored_prefix.start)?;
debug!("HIR-to-NFA compilation complete, config: {:?}", self.config);
Ok(nfa)
}
/// Compile an arbitrary HIR expression.
fn c(&self, expr: &Hir) -> Result<ThompsonRef, BuildError> {
use regex_syntax::hir::{Class, HirKind::*};
match *expr.kind() {