regexr 0.1.2

A high-performance regex engine built from scratch with JIT compilation and SIMD acceleration
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
//! Glushkov Construction (Position Automaton) for Shift-Or.
//!
//! Unlike Thompson's construction, Glushkov produces an ε-free NFA where:
//! - Each state corresponds to exactly one character position in the pattern
//! - 1 state transition = 1 byte consumed
//!
//! This makes it ideal for the Shift-Or (Bitap) algorithm where:
//! `state = ((state << 1) | 1) & mask[byte]`

use crate::hir::{Hir, HirExpr};

/// Maximum positions supported by standard Shift-Or (limited by u64 bit width).
pub const MAX_POSITIONS: usize = 64;

/// Maximum positions supported by Wide Shift-Or (using [u64; 4]).
pub const MAX_POSITIONS_WIDE: usize = 256;

/// A 256-bit set for wide state vectors.
///
/// Used by ShiftOrWide to support patterns with 65-256 positions.
/// Operations are implemented to work efficiently with the Shift-Or algorithm.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BitSet256 {
    /// 4 x u64 for 256 bits. `parts[0]` holds bits 0-63, `parts[1]` holds bits 64-127, etc.
    pub parts: [u64; 4],
}

impl BitSet256 {
    /// Creates a new empty bit set (all zeros).
    #[inline]
    pub const fn empty() -> Self {
        Self { parts: [0; 4] }
    }

    /// Creates a new bit set with all bits set to 1.
    #[inline]
    pub const fn all_ones() -> Self {
        Self { parts: [!0u64; 4] }
    }

    /// Creates a bit set with a single bit set.
    #[inline]
    pub fn singleton(pos: usize) -> Self {
        let mut set = Self::empty();
        set.set(pos);
        set
    }

    /// Sets the bit at the given position.
    #[inline]
    pub fn set(&mut self, pos: usize) {
        let word = pos / 64;
        let bit = pos % 64;
        if word < 4 {
            self.parts[word] |= 1u64 << bit;
        }
    }

    /// Clears the bit at the given position.
    #[inline]
    pub fn clear(&mut self, pos: usize) {
        let word = pos / 64;
        let bit = pos % 64;
        if word < 4 {
            self.parts[word] &= !(1u64 << bit);
        }
    }

    /// Returns true if the bit at the given position is set.
    #[inline]
    pub fn get(&self, pos: usize) -> bool {
        let word = pos / 64;
        let bit = pos % 64;
        if word < 4 {
            (self.parts[word] >> bit) & 1 != 0
        } else {
            false
        }
    }

    /// Returns true if all bits are zero.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.parts[0] == 0 && self.parts[1] == 0 && self.parts[2] == 0 && self.parts[3] == 0
    }

    /// Returns true if all bits are one.
    #[inline]
    pub fn is_all_ones(&self) -> bool {
        self.parts[0] == !0u64
            && self.parts[1] == !0u64
            && self.parts[2] == !0u64
            && self.parts[3] == !0u64
    }

    /// Computes the bitwise OR of two bit sets.
    #[inline]
    pub fn union(self, other: Self) -> Self {
        Self {
            parts: [
                self.parts[0] | other.parts[0],
                self.parts[1] | other.parts[1],
                self.parts[2] | other.parts[2],
                self.parts[3] | other.parts[3],
            ],
        }
    }

    /// Computes the bitwise AND of two bit sets.
    #[inline]
    pub fn intersection(self, other: Self) -> Self {
        Self {
            parts: [
                self.parts[0] & other.parts[0],
                self.parts[1] & other.parts[1],
                self.parts[2] & other.parts[2],
                self.parts[3] & other.parts[3],
            ],
        }
    }

    /// Computes the bitwise NOT of this bit set.
    #[inline]
    pub fn complement(self) -> Self {
        Self {
            parts: [
                !self.parts[0],
                !self.parts[1],
                !self.parts[2],
                !self.parts[3],
            ],
        }
    }

    /// Computes self OR other, storing result in self.
    #[inline]
    pub fn union_assign(&mut self, other: Self) {
        self.parts[0] |= other.parts[0];
        self.parts[1] |= other.parts[1];
        self.parts[2] |= other.parts[2];
        self.parts[3] |= other.parts[3];
    }

    /// Iterator over all set bit positions.
    /// Yields positions in ascending order.
    #[inline]
    pub fn iter_ones(&self) -> BitSet256Iter {
        BitSet256Iter {
            set: *self,
            word_idx: 0,
        }
    }
}

/// Iterator over set bits in a BitSet256.
pub struct BitSet256Iter {
    set: BitSet256,
    word_idx: usize,
}

impl Iterator for BitSet256Iter {
    type Item = usize;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // Find next word with set bits
        while self.word_idx < 4 {
            let word = self.set.parts[self.word_idx];
            if word != 0 {
                let bit_idx = word.trailing_zeros() as usize;
                let pos = self.word_idx * 64 + bit_idx;
                // Clear this bit
                self.set.parts[self.word_idx] &= word - 1;
                return Some(pos);
            }
            self.word_idx += 1;
        }
        None
    }
}

/// A Glushkov NFA (Position Automaton).
///
/// Unlike Thompson NFA, this has no ε-transitions.
/// Each position corresponds to one character in the pattern.
#[derive(Debug, Clone)]
pub struct GlushkovNfa {
    /// What bytes each position accepts.
    /// `positions[i]` is a 256-bit set indicating which bytes position i accepts.
    pub positions: Vec<ByteSet>,

    /// Follow sets: `follow[i]` contains positions that can follow position i.
    pub follow: Vec<u64>,

    /// Positions that can start a match (First set).
    pub first: u64,

    /// Positions that can end a match (Last set).
    pub last: u64,

    /// Whether the pattern can match the empty string.
    pub nullable: bool,

    /// Number of positions (excluding the implicit start state).
    pub position_count: usize,
}

/// A set of bytes (256 bits).
#[derive(Debug, Clone, Default)]
pub struct ByteSet {
    /// 4 x u64 for 256 bits.
    bits: [u64; 4],
}

impl ByteSet {
    /// Creates an empty byte set.
    pub fn new() -> Self {
        Self { bits: [0; 4] }
    }

    /// Creates a byte set containing a single byte.
    pub fn singleton(byte: u8) -> Self {
        let mut set = Self::new();
        set.insert(byte);
        set
    }

    /// Creates a byte set from a range of bytes (inclusive).
    pub fn from_range(start: u8, end: u8) -> Self {
        let mut set = Self::new();
        for b in start..=end {
            set.insert(b);
        }
        set
    }

    /// Creates a byte set containing all bytes.
    pub fn all() -> Self {
        Self { bits: [!0u64; 4] }
    }

    /// Inserts a byte into the set.
    pub fn insert(&mut self, byte: u8) {
        let idx = byte as usize / 64;
        let bit = byte as usize % 64;
        self.bits[idx] |= 1u64 << bit;
    }

    /// Checks if the set contains a byte.
    pub fn contains(&self, byte: u8) -> bool {
        let idx = byte as usize / 64;
        let bit = byte as usize % 64;
        (self.bits[idx] >> bit) & 1 != 0
    }

    /// Returns true if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.bits.iter().all(|&b| b == 0)
    }

    /// Computes the union of two byte sets.
    pub fn union(&self, other: &ByteSet) -> ByteSet {
        ByteSet {
            bits: [
                self.bits[0] | other.bits[0],
                self.bits[1] | other.bits[1],
                self.bits[2] | other.bits[2],
                self.bits[3] | other.bits[3],
            ],
        }
    }

    /// Computes the complement of the byte set.
    pub fn complement(&self) -> ByteSet {
        ByteSet {
            bits: [!self.bits[0], !self.bits[1], !self.bits[2], !self.bits[3]],
        }
    }
}

/// Result of analyzing an HIR expression for Glushkov construction.
#[derive(Debug, Clone)]
struct ExprInfo {
    /// First set: positions that can start matching this expression.
    first: u64,
    /// Last set: positions that can end matching this expression.
    last: u64,
    /// Whether this expression can match the empty string.
    nullable: bool,
}

impl ExprInfo {
    fn empty() -> Self {
        Self {
            first: 0,
            last: 0,
            nullable: true,
        }
    }
}

/// Builds a Glushkov NFA from HIR.
pub struct GlushkovBuilder {
    /// Byte sets for each position.
    positions: Vec<ByteSet>,
    /// Follow sets for each position.
    follow: Vec<u64>,
}

impl GlushkovBuilder {
    /// Creates a new builder.
    pub fn new() -> Self {
        Self {
            positions: Vec::new(),
            follow: Vec::new(),
        }
    }

    /// Builds a Glushkov NFA from HIR.
    ///
    /// This uses a single-pass algorithm that allocates positions and computes
    /// follow sets simultaneously, ensuring correct position tracking.
    pub fn build(&mut self, hir: &Hir) -> Option<GlushkovNfa> {
        // Check for features that Glushkov/Shift-Or can't handle
        if hir.props.has_backrefs || hir.props.has_lookaround {
            return None;
        }

        // Clear state
        self.positions.clear();
        self.follow.clear();

        // Single-pass: allocate positions AND compute follow sets
        let info = self.build_expr(&hir.expr)?;

        // Check if we have too many positions
        if self.positions.len() > MAX_POSITIONS {
            return None;
        }

        Some(GlushkovNfa {
            positions: self.positions.clone(),
            follow: self.follow.clone(),
            first: info.first,
            last: info.last,
            nullable: info.nullable,
            position_count: self.positions.len(),
        })
    }

    /// Single-pass construction: allocate positions and compute follow sets.
    fn build_expr(&mut self, expr: &HirExpr) -> Option<ExprInfo> {
        match expr {
            HirExpr::Empty => Some(ExprInfo::empty()),

            HirExpr::Literal(bytes) => {
                if bytes.is_empty() {
                    return Some(ExprInfo::empty());
                }

                let first_pos = self.positions.len();

                // Each byte gets its own position
                for &b in bytes {
                    if self.positions.len() >= MAX_POSITIONS {
                        return None;
                    }
                    self.positions.push(ByteSet::singleton(b));
                    self.follow.push(0); // Initialize follow set
                }

                let last_pos = self.positions.len() - 1;

                // Set follow: each position follows the previous within the literal
                for i in first_pos..last_pos {
                    self.follow[i] |= 1u64 << (i + 1);
                }

                Some(ExprInfo {
                    first: 1u64 << first_pos,
                    last: 1u64 << last_pos,
                    nullable: false,
                })
            }

            HirExpr::Class(class) => {
                if self.positions.len() >= MAX_POSITIONS {
                    return None;
                }

                let pos = self.positions.len();
                let mut byte_set = ByteSet::new();

                for &(start, end) in &class.ranges {
                    for b in start..=end {
                        byte_set.insert(b);
                    }
                }

                if class.negated {
                    byte_set = byte_set.complement();
                }

                self.positions.push(byte_set);
                self.follow.push(0); // Initialize follow set

                Some(ExprInfo {
                    first: 1u64 << pos,
                    last: 1u64 << pos,
                    nullable: false,
                })
            }

            HirExpr::Concat(exprs) => {
                if exprs.is_empty() {
                    return Some(ExprInfo::empty());
                }

                let mut result = self.build_expr(&exprs[0])?;

                for expr in &exprs[1..] {
                    let next = self.build_expr(expr)?;

                    // Follow(last(A)) includes First(B)
                    for pos in 0..MAX_POSITIONS {
                        if (result.last >> pos) & 1 != 0 && pos < self.follow.len() {
                            self.follow[pos] |= next.first;
                        }
                    }

                    // Update result
                    let new_first = if result.nullable {
                        result.first | next.first
                    } else {
                        result.first
                    };

                    let new_last = if next.nullable {
                        next.last | result.last
                    } else {
                        next.last
                    };

                    result = ExprInfo {
                        first: new_first,
                        last: new_last,
                        nullable: result.nullable && next.nullable,
                    };
                }

                Some(result)
            }

            HirExpr::Alt(exprs) => {
                if exprs.is_empty() {
                    return Some(ExprInfo::empty());
                }

                let mut result = self.build_expr(&exprs[0])?;

                for expr in &exprs[1..] {
                    let alt = self.build_expr(expr)?;
                    result = ExprInfo {
                        first: result.first | alt.first,
                        last: result.last | alt.last,
                        nullable: result.nullable || alt.nullable,
                    };
                }

                Some(result)
            }

            HirExpr::Repeat(rep) => {
                // Handle bounded repeats by unrolling.
                // This is necessary because Glushkov NFA requires distinct positions
                // for each character match. A pattern like a{3} needs 3 positions,
                // not 1 position with a self-loop.

                let min = rep.min;
                let max = rep.max;

                match (min, max) {
                    // E? = {0,1} - optional, no unrolling needed
                    (0, Some(1)) => {
                        let inner = self.build_expr(&rep.expr)?;
                        Some(ExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: true,
                        })
                    }

                    // E* = {0,} - zero or more with self-loop
                    (0, None) => {
                        let inner = self.build_expr(&rep.expr)?;
                        // Add self-loop: last -> first
                        for pos in 0..MAX_POSITIONS {
                            if (inner.last >> pos) & 1 != 0 && pos < self.follow.len() {
                                self.follow[pos] |= inner.first;
                            }
                        }
                        Some(ExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: true,
                        })
                    }

                    // E+ = {1,} - one or more with self-loop
                    (1, None) => {
                        let inner = self.build_expr(&rep.expr)?;
                        // Add self-loop: last -> first
                        for pos in 0..MAX_POSITIONS {
                            if (inner.last >> pos) & 1 != 0 && pos < self.follow.len() {
                                self.follow[pos] |= inner.first;
                            }
                        }
                        Some(ExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: inner.nullable,
                        })
                    }

                    // E{n} or E{n,m} or E{n,} where n > 1 - needs unrolling
                    _ => self.build_bounded_repeat(&rep.expr, min, max),
                }
            }

            HirExpr::Capture(cap) => self.build_expr(&cap.expr),

            HirExpr::Anchor(_) => Some(ExprInfo::empty()),

            HirExpr::Lookaround(_) | HirExpr::Backref(_) => None,

            // Unicode codepoint classes are not supported in Glushkov/Shift-Or
            // They use a special instruction that consumes variable-length UTF-8
            HirExpr::UnicodeCpClass(_) => None,
        }
    }

    /// Builds a bounded repeat by unrolling into concatenated copies.
    ///
    /// For E{n,m}:
    /// - Unroll n required copies: E E E ... (n times)
    /// - Unroll m-n optional copies that can each be skipped
    ///
    /// For E{n,}:
    /// - Unroll n copies, with the last one having a self-loop
    fn build_bounded_repeat(
        &mut self,
        expr: &HirExpr,
        min: u32,
        max: Option<u32>,
    ) -> Option<ExprInfo> {
        // Handle E{0,m} - all optional
        if min == 0 {
            return self.build_optional_repeat(expr, max.unwrap_or(1) as usize);
        }

        let min = min as usize;

        // Build required copies: E E E ... (min times)
        // First copy
        let mut result = self.build_expr(expr)?;
        let mut prev_last = result.last;

        // Remaining required copies
        for _ in 1..min {
            let copy = self.build_expr(expr)?;

            // Connect previous last to current first
            for pos in 0..MAX_POSITIONS {
                if (prev_last >> pos) & 1 != 0 && pos < self.follow.len() {
                    self.follow[pos] |= copy.first;
                }
            }

            // Update result
            // First stays the same (from the first copy)
            // Last becomes the current copy's last
            result.last = copy.last;
            result.nullable = result.nullable && copy.nullable;
            prev_last = copy.last;
        }

        // Handle the optional/unbounded part
        match max {
            None => {
                // E{n,} - add self-loop on the last positions
                // The last positions should be able to transition back to themselves
                // or to the start of another copy of the inner expression.
                // Since we want "one or more additional matches", we add a self-loop.
                for pos in 0..MAX_POSITIONS {
                    if (result.last >> pos) & 1 != 0 && pos < self.follow.len() {
                        self.follow[pos] |= result.last;
                    }
                }
                Some(result)
            }
            Some(max_val) => {
                let max = max_val as usize;
                let optional_count = max - min;

                if optional_count == 0 {
                    // E{n} - exact count, no optional part
                    return Some(result);
                }

                // E{n,m} - add optional copies
                // Each optional copy can be skipped, so we track all possible end positions
                let mut can_end = result.last;

                for _ in 0..optional_count {
                    let copy = self.build_expr(expr)?;

                    // Connect previous last positions to current first
                    for pos in 0..MAX_POSITIONS {
                        if (prev_last >> pos) & 1 != 0 && pos < self.follow.len() {
                            self.follow[pos] |= copy.first;
                        }
                    }

                    // Update tracking
                    prev_last = copy.last;
                    can_end |= copy.last; // This copy's end is also a valid end
                }

                result.last = can_end;
                Some(result)
            }
        }
    }

    /// Builds an optional repeat E{0,m} as a chain where any position can end.
    fn build_optional_repeat(&mut self, expr: &HirExpr, max: usize) -> Option<ExprInfo> {
        if max == 0 {
            return Some(ExprInfo::empty());
        }

        // Build first optional copy
        let first_copy = self.build_expr(expr)?;
        let mut result = ExprInfo {
            first: first_copy.first,
            last: first_copy.last,
            nullable: true, // Always nullable since min=0
        };
        let mut prev_last = first_copy.last;

        // Build remaining optional copies
        for _ in 1..max {
            let copy = self.build_expr(expr)?;

            // Connect previous last to current first
            for pos in 0..MAX_POSITIONS {
                if (prev_last >> pos) & 1 != 0 && pos < self.follow.len() {
                    self.follow[pos] |= copy.first;
                }
            }

            // Last includes all copies' last positions (any can be the end)
            result.last |= copy.last;
            prev_last = copy.last;
        }

        Some(result)
    }
}

impl Default for GlushkovBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl GlushkovNfa {
    /// Checks if this NFA is compatible with Shift-Or.
    pub fn is_shift_or_compatible(&self) -> bool {
        self.position_count <= MAX_POSITIONS
    }

    /// Builds the Shift-Or mask table from this Glushkov NFA.
    ///
    /// Returns masks where `mask[byte]` has bit `i` as 0 if position `i` can accept `byte`,
    /// 1 otherwise (Shift-Or uses inverted logic).
    pub fn build_shift_or_masks(&self) -> [u64; 256] {
        let mut masks = [!0u64; 256];

        for (pos_idx, byte_set) in self.positions.iter().enumerate() {
            for byte in 0..=255u8 {
                if byte_set.contains(byte) {
                    // Clear bit to indicate this position can accept this byte
                    masks[byte as usize] &= !(1u64 << pos_idx);
                }
            }
        }

        masks
    }

    /// Builds the initial state for Shift-Or.
    ///
    /// In Shift-Or, we track "not yet reached" with 1 bits.
    /// Initially, positions in First set can be reached.
    pub fn build_initial_state(&self) -> u64 {
        // All bits set to 1 (not reached), except we'll handle First set during matching
        !0u64
    }

    /// Builds the accept mask for Shift-Or.
    ///
    /// Positions in Last set are accepting positions.
    pub fn build_accept_mask(&self) -> u64 {
        // Inverted: 0 bits indicate accepting positions
        !self.last
    }
}

/// Compiles an HIR to a Glushkov NFA.
pub fn compile_glushkov(hir: &Hir) -> Option<GlushkovNfa> {
    let mut builder = GlushkovBuilder::new();
    builder.build(hir)
}

// ============================================================================
// Wide Glushkov NFA (supports up to 256 positions)
// ============================================================================

/// A Wide Glushkov NFA supporting up to 256 positions.
///
/// Uses BitSet256 instead of u64 for state vectors, allowing patterns
/// with 65-256 character positions to use the efficient Shift-Or algorithm
/// instead of falling back to the slower PikeVM.
#[derive(Debug, Clone)]
pub struct GlushkovWideNfa {
    /// What bytes each position accepts.
    pub positions: Vec<ByteSet>,

    /// Follow sets: `follow[i]` contains positions that can follow position i.
    pub follow: Vec<BitSet256>,

    /// Positions that can start a match (First set).
    pub first: BitSet256,

    /// Positions that can end a match (Last set).
    pub last: BitSet256,

    /// Whether the pattern can match the empty string.
    pub nullable: bool,

    /// Number of positions.
    pub position_count: usize,
}

impl GlushkovWideNfa {
    /// Checks if this NFA is compatible with Wide Shift-Or.
    pub fn is_shift_or_wide_compatible(&self) -> bool {
        self.position_count <= MAX_POSITIONS_WIDE && self.position_count > 0
    }

    /// Builds the Wide Shift-Or mask table from this Glushkov NFA.
    ///
    /// Returns masks where `mask[byte]` has bit `i` as 0 if position `i` can accept `byte`,
    /// 1 otherwise (Shift-Or uses inverted logic).
    pub fn build_shift_or_masks(&self) -> [BitSet256; 256] {
        let mut masks = [BitSet256::all_ones(); 256];

        for (pos_idx, byte_set) in self.positions.iter().enumerate() {
            for byte in 0..=255u8 {
                if byte_set.contains(byte) {
                    // Clear bit to indicate this position can accept this byte
                    masks[byte as usize].clear(pos_idx);
                }
            }
        }

        masks
    }

    /// Builds the accept mask for Wide Shift-Or.
    ///
    /// Positions in Last set are accepting positions.
    pub fn build_accept_mask(&self) -> BitSet256 {
        // Inverted: 0 bits indicate accepting positions
        self.last.complement()
    }
}

/// Result of analyzing an HIR expression for Wide Glushkov construction.
#[derive(Debug, Clone)]
struct WideExprInfo {
    first: BitSet256,
    last: BitSet256,
    nullable: bool,
}

impl WideExprInfo {
    fn empty() -> Self {
        Self {
            first: BitSet256::empty(),
            last: BitSet256::empty(),
            nullable: true,
        }
    }
}

/// Builds a Wide Glushkov NFA from HIR.
pub struct GlushkovWideBuilder {
    positions: Vec<ByteSet>,
    follow: Vec<BitSet256>,
}

impl GlushkovWideBuilder {
    /// Creates a new builder.
    pub fn new() -> Self {
        Self {
            positions: Vec::new(),
            follow: Vec::new(),
        }
    }

    /// Builds a Wide Glushkov NFA from HIR.
    pub fn build(&mut self, hir: &Hir) -> Option<GlushkovWideNfa> {
        // Check for features that Glushkov/Shift-Or can't handle
        if hir.props.has_backrefs || hir.props.has_lookaround {
            return None;
        }

        // Clear state
        self.positions.clear();
        self.follow.clear();

        // Single-pass: allocate positions AND compute follow sets
        let info = self.build_expr(&hir.expr)?;

        // Check if we have too many positions
        if self.positions.len() > MAX_POSITIONS_WIDE {
            return None;
        }

        Some(GlushkovWideNfa {
            positions: self.positions.clone(),
            follow: self.follow.clone(),
            first: info.first,
            last: info.last,
            nullable: info.nullable,
            position_count: self.positions.len(),
        })
    }

    /// Single-pass construction for wide NFA.
    fn build_expr(&mut self, expr: &HirExpr) -> Option<WideExprInfo> {
        match expr {
            HirExpr::Empty => Some(WideExprInfo::empty()),

            HirExpr::Literal(bytes) => {
                if bytes.is_empty() {
                    return Some(WideExprInfo::empty());
                }

                let first_pos = self.positions.len();

                // Each byte gets its own position
                for &b in bytes {
                    if self.positions.len() >= MAX_POSITIONS_WIDE {
                        return None;
                    }
                    self.positions.push(ByteSet::singleton(b));
                    self.follow.push(BitSet256::empty());
                }

                let last_pos = self.positions.len() - 1;

                // Set follow: each position follows the previous within the literal
                for i in first_pos..last_pos {
                    self.follow[i].set(i + 1);
                }

                Some(WideExprInfo {
                    first: BitSet256::singleton(first_pos),
                    last: BitSet256::singleton(last_pos),
                    nullable: false,
                })
            }

            HirExpr::Class(class) => {
                if self.positions.len() >= MAX_POSITIONS_WIDE {
                    return None;
                }

                let pos = self.positions.len();
                let mut byte_set = ByteSet::new();

                for &(start, end) in &class.ranges {
                    for b in start..=end {
                        byte_set.insert(b);
                    }
                }

                if class.negated {
                    byte_set = byte_set.complement();
                }

                self.positions.push(byte_set);
                self.follow.push(BitSet256::empty());

                Some(WideExprInfo {
                    first: BitSet256::singleton(pos),
                    last: BitSet256::singleton(pos),
                    nullable: false,
                })
            }

            HirExpr::Concat(exprs) => {
                if exprs.is_empty() {
                    return Some(WideExprInfo::empty());
                }

                let mut result = self.build_expr(&exprs[0])?;

                for expr in &exprs[1..] {
                    let next = self.build_expr(expr)?;

                    // Follow(last(A)) includes First(B)
                    for pos in result.last.iter_ones() {
                        if pos < self.follow.len() {
                            self.follow[pos].union_assign(next.first);
                        }
                    }

                    // Update result
                    let new_first = if result.nullable {
                        result.first.union(next.first)
                    } else {
                        result.first
                    };

                    let new_last = if next.nullable {
                        next.last.union(result.last)
                    } else {
                        next.last
                    };

                    result = WideExprInfo {
                        first: new_first,
                        last: new_last,
                        nullable: result.nullable && next.nullable,
                    };
                }

                Some(result)
            }

            HirExpr::Alt(exprs) => {
                if exprs.is_empty() {
                    return Some(WideExprInfo::empty());
                }

                let mut result = self.build_expr(&exprs[0])?;

                for expr in &exprs[1..] {
                    let alt = self.build_expr(expr)?;
                    result = WideExprInfo {
                        first: result.first.union(alt.first),
                        last: result.last.union(alt.last),
                        nullable: result.nullable || alt.nullable,
                    };
                }

                Some(result)
            }

            HirExpr::Repeat(rep) => {
                // Handle bounded repeats by unrolling (same logic as standard Glushkov)
                let min = rep.min;
                let max = rep.max;

                match (min, max) {
                    // E? = {0,1} - optional, no unrolling needed
                    (0, Some(1)) => {
                        let inner = self.build_expr(&rep.expr)?;
                        Some(WideExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: true,
                        })
                    }

                    // E* = {0,} - zero or more with self-loop
                    (0, None) => {
                        let inner = self.build_expr(&rep.expr)?;
                        for pos in inner.last.iter_ones() {
                            if pos < self.follow.len() {
                                self.follow[pos].union_assign(inner.first);
                            }
                        }
                        Some(WideExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: true,
                        })
                    }

                    // E+ = {1,} - one or more with self-loop
                    (1, None) => {
                        let inner = self.build_expr(&rep.expr)?;
                        for pos in inner.last.iter_ones() {
                            if pos < self.follow.len() {
                                self.follow[pos].union_assign(inner.first);
                            }
                        }
                        Some(WideExprInfo {
                            first: inner.first,
                            last: inner.last,
                            nullable: inner.nullable,
                        })
                    }

                    // E{n} or E{n,m} or E{n,} where n > 1 - needs unrolling
                    _ => self.build_bounded_repeat_wide(&rep.expr, min, max),
                }
            }

            HirExpr::Capture(cap) => self.build_expr(&cap.expr),

            HirExpr::Anchor(_) => Some(WideExprInfo::empty()),

            HirExpr::Lookaround(_) | HirExpr::Backref(_) => None,

            HirExpr::UnicodeCpClass(_) => None,
        }
    }

    /// Builds a bounded repeat for wide Glushkov NFA.
    fn build_bounded_repeat_wide(
        &mut self,
        expr: &HirExpr,
        min: u32,
        max: Option<u32>,
    ) -> Option<WideExprInfo> {
        if min == 0 {
            return self.build_optional_repeat_wide(expr, max.unwrap_or(1) as usize);
        }

        let min = min as usize;

        // Build required copies
        let mut result = self.build_expr(expr)?;
        let mut prev_last = result.last;

        for _ in 1..min {
            let copy = self.build_expr(expr)?;

            for pos in prev_last.iter_ones() {
                if pos < self.follow.len() {
                    self.follow[pos].union_assign(copy.first);
                }
            }

            result.last = copy.last;
            result.nullable = result.nullable && copy.nullable;
            prev_last = copy.last;
        }

        match max {
            None => {
                // E{n,} - add self-loop
                for pos in result.last.iter_ones() {
                    if pos < self.follow.len() {
                        self.follow[pos].union_assign(result.last);
                    }
                }
                Some(result)
            }
            Some(max_val) => {
                let max = max_val as usize;
                let optional_count = max - min;

                if optional_count == 0 {
                    return Some(result);
                }

                let mut can_end = result.last;
                for _ in 0..optional_count {
                    let copy = self.build_expr(expr)?;

                    for pos in prev_last.iter_ones() {
                        if pos < self.follow.len() {
                            self.follow[pos].union_assign(copy.first);
                        }
                    }

                    prev_last = copy.last;
                    can_end = can_end.union(copy.last);
                }

                result.last = can_end;
                Some(result)
            }
        }
    }

    /// Builds an optional repeat for wide Glushkov NFA.
    fn build_optional_repeat_wide(&mut self, expr: &HirExpr, max: usize) -> Option<WideExprInfo> {
        if max == 0 {
            return Some(WideExprInfo::empty());
        }

        let first_copy = self.build_expr(expr)?;
        let mut result = WideExprInfo {
            first: first_copy.first,
            last: first_copy.last,
            nullable: true,
        };
        let mut prev_last = first_copy.last;

        for _ in 1..max {
            let copy = self.build_expr(expr)?;

            for pos in prev_last.iter_ones() {
                if pos < self.follow.len() {
                    self.follow[pos].union_assign(copy.first);
                }
            }

            result.last = result.last.union(copy.last);
            prev_last = copy.last;
        }

        Some(result)
    }
}

impl Default for GlushkovWideBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Compiles an HIR to a Wide Glushkov NFA (supports up to 256 positions).
pub fn compile_glushkov_wide(hir: &Hir) -> Option<GlushkovWideNfa> {
    let mut builder = GlushkovWideBuilder::new();
    builder.build(hir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hir::translate;
    use crate::parser::parse;

    fn make_glushkov(pattern: &str) -> Option<GlushkovNfa> {
        let ast = parse(pattern).ok()?;
        let hir = translate(&ast).ok()?;
        compile_glushkov(&hir)
    }

    #[test]
    fn test_simple_literal() {
        let nfa = make_glushkov("abc").unwrap();
        assert_eq!(nfa.position_count, 3);
        assert!(!nfa.nullable);

        // Position 0 accepts 'a', position 1 accepts 'b', position 2 accepts 'c'
        assert!(nfa.positions[0].contains(b'a'));
        assert!(nfa.positions[1].contains(b'b'));
        assert!(nfa.positions[2].contains(b'c'));
    }

    #[test]
    fn test_alternation() {
        let nfa = make_glushkov("a|b").unwrap();
        assert_eq!(nfa.position_count, 2);
        assert!(!nfa.nullable);

        // First set should include both positions
        assert_eq!(nfa.first, 0b11);
        // Last set should include both positions
        assert_eq!(nfa.last, 0b11);
    }

    #[test]
    fn test_optional() {
        let nfa = make_glushkov("a?").unwrap();
        assert_eq!(nfa.position_count, 1);
        assert!(nfa.nullable); // Can match empty string
    }

    #[test]
    fn test_star() {
        let nfa = make_glushkov("a*").unwrap();
        assert_eq!(nfa.position_count, 1);
        assert!(nfa.nullable); // Can match empty string
    }

    #[test]
    fn test_plus() {
        let nfa = make_glushkov("a+").unwrap();
        assert_eq!(nfa.position_count, 1);
        assert!(!nfa.nullable); // Must match at least one 'a'
    }

    #[test]
    fn test_class() {
        let nfa = make_glushkov("[a-z]").unwrap();
        assert_eq!(nfa.position_count, 1);

        // Should accept all lowercase letters
        for c in b'a'..=b'z' {
            assert!(nfa.positions[0].contains(c));
        }

        // Should not accept uppercase
        assert!(!nfa.positions[0].contains(b'A'));
    }

    #[test]
    fn test_too_many_positions() {
        // Pattern with more than 64 character positions
        let pattern = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop";
        assert!(pattern.len() > MAX_POSITIONS);

        let result = make_glushkov(pattern);
        assert!(result.is_none());
    }

    #[test]
    fn test_shift_or_masks() {
        let nfa = make_glushkov("ab").unwrap();
        let masks = nfa.build_shift_or_masks();

        // For 'a' at position 0: bit 0 should be 0 (cleared)
        assert_eq!(masks[b'a' as usize] & 1, 0);

        // For 'b' at position 1: bit 1 should be 0 (cleared)
        assert_eq!(masks[b'b' as usize] & 2, 0);

        // For 'c' (not in pattern): all bits should be 1
        assert_eq!(masks[b'c' as usize], !0u64);
    }

    #[test]
    fn test_dot_star_glushkov() {
        // a.*b pattern: position 0 = 'a', position 1 = '.', position 2 = 'b'
        let nfa = make_glushkov("a.*b").unwrap();

        // Should have 3 positions: 'a', '.', 'b'
        assert_eq!(nfa.position_count, 3);

        // First set should only include position 0 ('a')
        assert_eq!(nfa.first, 0b001);

        // Last set should only include position 2 ('b')
        assert_eq!(nfa.last, 0b100);

        // Pattern is not nullable (can't match empty string)
        assert!(!nfa.nullable);

        // Position 0 accepts 'a'
        assert!(nfa.positions[0].contains(b'a'));
        assert!(!nfa.positions[0].contains(b'b'));

        // Position 1 accepts any byte (.)
        assert!(nfa.positions[1].contains(b'a'));
        assert!(nfa.positions[1].contains(b'b'));
        assert!(nfa.positions[1].contains(b'x'));

        // Position 2 accepts 'b'
        assert!(nfa.positions[2].contains(b'b'));
        assert!(!nfa.positions[2].contains(b'a'));

        // Follow sets:
        // Follow(0) = {1, 2} (after 'a', can go to '.' or 'b' since .* is nullable)
        assert_eq!(
            nfa.follow[0] & 0b110,
            0b110,
            "Follow(0) should include positions 1 and 2"
        );

        // Follow(1) = {1, 2} (after '.', can stay at '.' or go to 'b')
        assert_eq!(
            nfa.follow[1] & 0b110,
            0b110,
            "Follow(1) should include positions 1 and 2"
        );

        // Follow(2) = {} (after 'b', nothing follows - it's the end)
        assert_eq!(nfa.follow[2], 0, "Follow(2) should be empty");
    }
}