resharp 0.6.14

high-performance regex engine with intersection and complement operations
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
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
use resharp_algebra::nulls::Nullability;
use resharp_algebra::solver::{Solver, TSetId};
use resharp_algebra::{Kind, NodeId, RegexBuilder};
use std::collections::{BTreeMap, BTreeSet};

use crate::Error;

#[cfg(feature = "debug")]
fn pp_sets(b: &RegexBuilder, sets: &[TSetId]) -> String {
    sets.iter()
        .map(|&s| b.solver_ref().pp(s))
        .collect::<Vec<_>>()
        .join(";")
}

pub(crate) fn calc_prefix_sets_inner(
    b: &mut RegexBuilder,
    start: NodeId,
    strip_prefix: bool,
) -> Result<Vec<TSetId>, crate::Error> {
    let mut result = Vec::new();
    let mut node = start;
    let mut redundant = BTreeSet::new();
    redundant.insert(NodeId::BOT);
    redundant.insert(start);
    let mut visited: BTreeSet<NodeId> = BTreeSet::new();

    loop {
        if !result.is_empty() && redundant.contains(&node) {
            break;
        }

        if !result.is_empty() && !visited.insert(node) {
            result.clear();
            break;
        }

        if b.any_nonbegin_nullable(node) {
            break;
        }

        let der = b
            .der(node, Nullability::CENTER)
            .map_err(crate::Error::Algebra)?;
        let mut targets: Vec<(NodeId, TSetId)> = Vec::new();
        b.collect_der_targets(der, TSetId::FULL, &mut targets);
        let full_union = if !strip_prefix {
            targets
                .iter()
                .filter(|(t, _)| *t != NodeId::BOT)
                .fold(TSetId::EMPTY, |acc, &(_, cs)| b.solver().or_id(acc, cs))
        } else {
            TSetId::EMPTY
        };

        targets.retain(|(t, _)| !redundant.contains(t));

        if targets.is_empty() {
            result.clear();
            break;
        }

        if targets.len() == 1 {
            let (target, char_set) = targets[0];
            if target == node {
                result.clear();
                break;
            }
            let set = if !strip_prefix && full_union != TSetId::EMPTY {
                full_union
            } else {
                char_set
            };
            result.push(set);
            node = target;
        } else {
            break;
        }
    }

    Ok(result)
}

/// True (anchored) prefix sets from the reversed pattern.
pub fn calc_prefix_sets(
    b: &mut RegexBuilder,
    rev_start: NodeId,
) -> Result<Vec<TSetId>, crate::Error> {
    let rev_start = b.nonbegins(rev_start);
    let safe = b.strip_prefix_safe(rev_start);
    calc_prefix_sets_inner(b, safe, true)
}

/// potential start prefix, but does not guarantee the match starts here.
/// eg .*a.* -> a does guarantee there is a match, but not where it starts
pub fn calc_potential_start_prune(
    b: &mut RegexBuilder,
    node: NodeId,
    max_prefix_len: usize,
    max_frontier_size: usize,
    exclude_initial: bool,
) -> Result<Vec<TSetId>, crate::Error> {
    let node = b.prune_begin(node);
    let node = b.strip_prefix_safe(node);
    calc_potential_start(b, node, max_prefix_len, max_frontier_size, exclude_initial)
}

/// potential start prefix, may have false positives, but no false negatives.
pub fn calc_potential_start(
    b: &mut RegexBuilder,
    initial_node: NodeId,
    max_prefix_len: usize,
    max_frontier_size: usize,
    exclude_initial: bool,
) -> Result<Vec<TSetId>, crate::Error> {
    let mut nodes: BTreeSet<NodeId> = BTreeSet::new();
    nodes.insert(initial_node);
    let mut depth: BTreeMap<NodeId, usize> = BTreeMap::new();
    depth.insert(initial_node, 0);

    let mut result = Vec::new();
    let mut step: usize = 0;

    let mut sat_stack: Vec<(resharp_algebra::TRegexId, TSetId)> = Vec::new();

    loop {
        if nodes.is_empty() || nodes.len() > max_frontier_size || result.len() >= max_prefix_len {
            break;
        }

        if nodes.iter().any(|&n| b.any_nonbegin_nullable(n)) {
            break;
        }

        let mut union_set = TSetId::EMPTY;
        let mut next_nodes: BTreeSet<NodeId> = BTreeSet::new();
        let next_step = step + 1;

        for &node in &nodes.clone() {
            let der = b
                .der(node, Nullability::CENTER)
                .map_err(crate::Error::Algebra)?;
            sat_stack.push((der, TSetId::FULL));
            b.iter_sat(&mut sat_stack, &mut |b, target, char_set| {
                if exclude_initial && target == initial_node {
                    return;
                }
                if target == NodeId::BOT {
                    return;
                }
                union_set = b.solver().or_id(union_set, char_set);
                next_nodes.insert(target);
                depth.entry(target).or_insert(next_step);
            });
        }

        if next_nodes.is_empty() || union_set == TSetId::EMPTY {
            if next_nodes.is_empty() {
                result.clear();
            }
            break;
        }

        result.push(union_set);
        nodes = next_nodes;
        step = next_step;
    }

    Ok(result)
}

fn collect_loop_factored_bodies(b: &RegexBuilder, init: NodeId) -> Option<Vec<NodeId>> {
    let mut bodies = Vec::new();
    let mut stack = vec![init];
    while let Some(n) = stack.pop() {
        if n.is_inter(b) {
            stack.push(n.left(b));
            stack.push(n.right(b));
        } else if n.is_concat(b) && n.left(b) == NodeId::TS {
            bodies.push(n.right(b));
        } else {
            return None;
        }
    }
    Some(bodies)
}

fn synthesize_inter_constraint(b: &mut RegexBuilder, init: NodeId) -> Option<NodeId> {
    if !init.is_inter(b) {
        return None;
    }
    let bodies = collect_loop_factored_bodies(b, init)?;
    if bodies.is_empty() {
        return None;
    }
    Some(b.mk_unions(bodies.into_iter()))
}

/// Detect a reverse start `[_*] ~(_*X) tail`. Returns `(rc, boundary, tail)`
/// where `rc` is the begin-relaxed node `~(_*X) tail`, `boundary = [^X]`.
pub(crate) fn rev_boundary_shape(
    b: &mut RegexBuilder,
    rev_start: NodeId,
) -> Option<(NodeId, TSetId, NodeId)> {
    let stripped = if rev_start.is_concat(b) && rev_start.left(b) == NodeId::TS {
        rev_start.right(b)
    } else {
        rev_start
    };
    let rc = b.prune_begin_eps(stripped);
    if !rc.is_concat(b) {
        return None;
    }
    let lead = rc.left(b);
    let tail = rc.right(b);
    if !lead.is_compl(b) {
        return None;
    }
    let inner = lead.left(b);
    if !inner.is_concat(b) || inner.left(b) != NodeId::TS {
        return None;
    }
    let pred = inner.right(b);
    if !pred.is_pred(b) {
        return None;
    }
    let cc = pred.pred_tset(b);
    let boundary = b.solver().not_id(cc);
    if boundary == TSetId::EMPTY {
        return None;
    }
    Some((rc, boundary, tail))
}

fn calc_rev_boundary_prefix(
    b: &mut RegexBuilder,
    rev_start: NodeId,
) -> Result<Option<Vec<TSetId>>, crate::Error> {
    let Some((_, boundary, tail)) = rev_boundary_shape(b, rev_start) else {
        return Ok(None);
    };
    let tail_sets = calc_potential_start(b, tail, 16, 64, false)?;
    if tail_sets.is_empty() {
        return Ok(None);
    }
    let mut out = Vec::with_capacity(tail_sets.len() + 1);
    out.push(boundary);
    out.extend(tail_sets);
    Ok(Some(out))
}

pub(crate) fn calc_combined_prefix(
    b: &mut RegexBuilder,
    init: NodeId,
    fingerprint_depth: usize,
    max_prefix_len: usize,
    max_frontier_size: usize,
) -> Result<Vec<TSetId>, crate::Error> {
    let potential = calc_potential_start(b, init, max_prefix_len, max_frontier_size, true)?;
    let head = if let Some(c) = synthesize_inter_constraint(b, init) {
        let constrained = b.mk_inter(init, c);
        let mut h =
            calc_potential_start(b, constrained, fingerprint_depth, max_frontier_size, false)?;
        h.truncate(fingerprint_depth);
        h
    } else {
        Vec::new()
    };
    if head.is_empty() {
        return Ok(potential);
    }
    let mut out = potential;
    if out.len() < head.len() {
        return Ok(head);
    }
    for (i, &h) in head.iter().enumerate() {
        out[i] = b.solver().and_id(out[i], h);
    }
    Ok(out)
}

#[derive(Clone, Debug)]
pub struct PrefixSet {
    pub sets: Vec<TSetId>,
    /// per-byte cost (lower = faster). `u64::MAX` for empty
    pub cost: u64,
}

/// Prefix sets for both directions.
pub struct PrefixSets {
    /// Potential-start fwd sets (full node, self-loop bytes included).
    pub fwd_potential: PrefixSet,
    /// Potential-start fwd sets after stripping a leading `_*`.
    pub fwd_potential_stripped: PrefixSet,
    /// Tight anchored rev prefix (right-to-left).
    pub rev_anchored: PrefixSet,
    /// Fingerprint head intersected with potential-start tail; narrower than bare potential-start.
    pub rev_potential: PrefixSet,
    /// `rev_start` with the leading `_*`/begin pruned: the mandatory reverse
    /// body. This is the canonical node to search for an interior literal.
    pub rev_stripped: NodeId,
}

impl PrefixSets {
    /// Compute all prefix sets for `node` (fwd) and `rev_start` (reversed, not yet stripped).
    pub fn compute(
        b: &mut RegexBuilder,
        node: NodeId,
        rev_start: NodeId,
    ) -> Result<Self, crate::Error> {
        let fwd_body = strip_leading_lookbehind(b, node);
        let stripped_node = b.strip_prefix_safe(node);
        let fwd_body_stripped = strip_leading_lookbehind(b, stripped_node);
        let fwd_potential_sets = calc_potential_start(b, fwd_body, 16, 64, false)?;
        let fwd_potential_stripped_sets =
            calc_potential_start(b, fwd_body_stripped, 16, 64, false)?;
        let rev_anchored_sets = calc_prefix_sets(b, rev_start)?;
        let rev_combined_init = {
            let n = b.prune_begin(rev_start);
            b.strip_prefix_safe(n)
        };
        let rev_stripped = rev_combined_init;
        let mut rev_potential_sets =
            if let Some(s) = calc_rev_boundary_prefix(b, rev_start)? {
                s
            } else {
                calc_combined_prefix(b, rev_combined_init, 3, 16, 64)?
            };
        if rev_potential_sets.is_empty() {
            if let Ok(body) = b.strip_lb(node) {
                if body != node {
                    if let Ok(body_rev) = b.reverse(body) {
                        if let Ok(bare) = b.strip_lb(body_rev) {
                            rev_potential_sets = calc_potential_start(b, bare, 16, 64, false)?;
                        }
                    }
                }
            }
        }

        let body_shape = classify_body_shape(b, fwd_body, &fwd_potential_sets);
        let mut mk = |sets: Vec<TSetId>, dir: Direction| PrefixSet {
            cost: cost_for(b, &sets, dir, body_shape),
            sets,
        };

        let fwd_potential = mk(fwd_potential_sets, Direction::Fwd);
        let fwd_potential_stripped = mk(fwd_potential_stripped_sets, Direction::Fwd);
        let rev_anchored = mk(rev_anchored_sets, Direction::Rev);
        let rev_potential = mk(rev_potential_sets, Direction::Rev);
        Ok(Self {
            fwd_potential,
            fwd_potential_stripped,
            rev_anchored,
            rev_potential,
            rev_stripped,
        })
    }

    /// Lower is rarer and more profitable for SIMD skip. `u64::MAX` for an empty sequence.
    #[allow(dead_code)]
    pub fn rarity(b: &mut RegexBuilder, sets: &[TSetId]) -> u64 {
        rarest_freq(b, sets)
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Direction {
    Fwd,
    Rev,
}

/// Cost wrapper that handles the non-SIMD target stub.
fn cost_for(b: &mut RegexBuilder, sets: &[TSetId], dir: Direction, body_shape: NodeShape) -> u64 {
    scan_cost(b, sets, dir, body_shape)
}

/// Estimated per-byte scan cost: `scan_per_byte + fire_rate * verify_per_fire`.
fn scan_cost(b: &mut RegexBuilder, sets: &[TSetId], dir: Direction, body_shape: NodeShape) -> u64 {
    if sets.is_empty() {
        return u64::MAX;
    }
    let counts: Vec<usize> = sets
        .iter()
        .map(|&s| b.solver().collect_bytes(s).len())
        .collect();
    let freqs: Vec<u64> = sets
        .iter()
        .map(|&s| {
            b.solver()
                .collect_bytes(s)
                .iter()
                .map(|&byte| crate::simd::BYTE_FREQ[byte as usize] as u64)
                .sum()
        })
        .collect();
    let total = TOTAL_BYTE_FREQ as f64;
    let rarest = freqs
        .iter()
        .zip(counts.iter())
        .enumerate()
        .filter(|&(_, (&f, _))| f > 0)
        .min_by_key(|&(_, (&f, _))| f);
    let single_position = matches!(dir, Direction::Fwd)
        && rarest.is_some_and(|(_, (_, &c))| c > 16);
    let fire = if single_position {
        rarest.map(|(_, (&f, _))| f as f64).unwrap_or(total) / total
    } else {
        let mut nz: Vec<u64> = freqs.iter().copied().filter(|&f| f > 0).collect();
        if nz.is_empty() {
            return u64::MAX;
        }
        nz.sort_unstable();
        let num_simd = nz.len().min(3);
        let prod: f64 = nz[..num_simd].iter().map(|&f| f as f64).product();
        prod / total.powi(num_simd as i32)
    };

    let (scan_per_byte, verify_per_fire) = match dir {
        Direction::Rev => (0.05, 20.0),
        Direction::Fwd => (
            0.05,
            match body_shape {
                NodeShape::TrailingStar => 1.0,
                NodeShape::Bounded => 50.0,
                NodeShape::Unbounded => 5000.0,
            },
        ),
    };
    let cost = scan_per_byte + fire * verify_per_fire;
    (cost * 1e9) as u64
}

/// Shape of the node after prefix, controlling fwd-direction verify cost.
#[derive(Copy, Clone, Debug)]
pub enum NodeShape {
    TrailingStar,
    Bounded,
    Unbounded,
}

pub(crate) const SKIP_FREQ_THRESHOLD: u32 = 75_000;

/// Threshold above which a byte set is treated as wildcard-like.
const WIDE_SET_BYTES: u32 = 200;

fn is_pure_trailing_run(b: &mut RegexBuilder, node: NodeId) -> bool {
    let mut cur = node;
    loop {
        if cur.is_star(b) {
            return true;
        }
        if cur.is_lookahead(b) {
            cur = cur.right(b);
            continue;
        }
        if cur.is_inter(b) {
            let (l, r) = (cur.left(b), cur.right(b));
            cur = if l.is_compl(b) { r } else { l };
            continue;
        }
        if !cur.is_concat(b) {
            return false;
        }
        let left = cur.left(b);
        if b.get_min_max_length(left).1 == u32::MAX {
            return false;
        }
        cur = cur.right(b);
    }
}

/// Classify body shape past the fwd prefix to set verify cost.
fn classify_body_shape(
    b: &mut RegexBuilder,
    fwd_body: NodeId,
    fwd_potential: &[TSetId],
) -> NodeShape {
    if b.ends_with_ts(fwd_body) {
        return NodeShape::TrailingStar;
    }
    let rarest_wide = !fwd_potential.is_empty()
        && fwd_potential
            .iter()
            .map(|&s| b.solver().byte_count(s))
            .min()
            .is_some_and(|c| c > 16);
    if is_pure_trailing_run(b, fwd_body) {
        return NodeShape::TrailingStar;
    }
    if rarest_wide && b.get_min_max_length(fwd_body).1 == u32::MAX {
        return NodeShape::Unbounded;
    }
    match fwd_potential.last() {
        Some(&last) if b.solver().byte_count(last) > WIDE_SET_BYTES => NodeShape::Unbounded,
        _ => NodeShape::Bounded,
    }
}
#[cfg(feature = "convergence_prefix")]
const CONV_PENALTY: u64 = 8;
#[cfg(feature = "convergence_prefix")]
const CONV_WIDE_LOOP_BYTES: u32 = 128;
#[cfg(feature = "convergence_prefix")]
const CONV_BOUNDED_MAX: u32 = 12;

#[cfg(feature = "convergence_prefix")]
fn conv_b_interior_unbounded(b: &mut RegexBuilder, b_node: NodeId) -> bool {
    use resharp_algebra::nulls::Nullability;
    let mut seen_wide_unbounded = false;
    let mut curr = b_node;
    loop {
        let is_concat = curr.is_concat(b);
        let head = if is_concat { curr.left(b) } else { curr };
        let (hmin, hmax) = b.get_min_max_length(head);
        if seen_wide_unbounded && hmin > 0 {
            return true;
        }
        if hmax == u32::MAX {
            let lead = match b.der(head, Nullability::CENTER) {
                Ok(d) => {
                    let mut stack = vec![(d, TSetId::FULL)];
                    let mut acc = TSetId::EMPTY;
                    b.iter_sat(&mut stack, &mut |bb, _n, set| {
                        acc = bb.solver().or_id(acc, set);
                    });
                    acc
                }
                Err(_) => b.solver().not_id(TSetId::EMPTY),
            };
            if b.solver().byte_count(lead) >= CONV_WIDE_LOOP_BYTES {
                seen_wide_unbounded = true;
            }
        }
        if is_concat {
            curr = curr.right(b);
        } else {
            break;
        }
    }
    false
}
const TEDDY_MAX_FREQ_SUM: u64 = 25_000;
// sum of BYTE_FREQ[0..256] in the corpus
pub(crate) const TOTAL_BYTE_FREQ: u64 = 252_052;
/// a position must be at least this rare to count as a selective Teddy lane;
/// a bare multi-class fingerprint with no rare anchor is rejected
const TEDDY_WEAK_POSITION_FREQ: u64 = 8_000;
// when to use memchr instead of a full prefix
const TEDDY_MEMCHR_MAX_FREQ: u64 = 2_500;
const TEDDY_MEMCHR_MAX_FREQ_F: u64 = 1_500;
#[cfg(feature = "convergence_prefix")]
const CONV_MEMCHR_MAX: u64 = 5_000;
const RARE_BYTE_FREQ_LIMIT: u16 = 25_000;

/// Forward literal prefix for patterns with no `_*` stripping.
/// Returns `Some` only when the pattern has a tight literal prefix and the
/// rarest byte in it is not too common.
pub fn build_strict_literal_prefix(
    b: &mut RegexBuilder,
    node: NodeId,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    {
        let sets = calc_prefix_sets_inner(b, node, false)?;
        if sets.is_empty() {
            return Ok(None);
        }
        let byte_sets: Vec<Vec<u8>> = sets.iter().map(|&s| b.solver().collect_bytes(s)).collect();
        if !byte_sets.iter().all(|bs| bs.len() == 1) {
            return Ok(None);
        }
        let needle: Vec<u8> = byte_sets.iter().map(|bs| bs[0]).collect();
        let lit = crate::simd::FwdLiteralSearch::new(&needle);
        if crate::simd::BYTE_FREQ[lit.rare_byte() as usize] >= RARE_BYTE_FREQ_LIMIT {
            return Ok(None);
        }
        Ok(Some(crate::accel::FwdPrefixSearch::Literal(lit)))
    }
}

pub fn build_fwd_prefix(
    b: &mut RegexBuilder,
    node: NodeId,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    if !crate::simd::has_simd() {
        return Ok(None);
    }
    build_fwd_prefix_simd(b, node)
}

fn try_build_fwd_search(
    b: &mut RegexBuilder,
    sets: &[TSetId],
    allow_common: bool,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    let byte_sets_raw: Vec<Vec<u8>> = sets
        .iter()
        .map(|&set| b.solver().collect_bytes(set))
        .collect();
    try_build_fwd_search_raw(&byte_sets_raw, allow_common)
}

fn try_build_fwd_search_raw(
    byte_sets_raw: &[Vec<u8>],
    allow_common: bool,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    let lit_len = byte_sets_raw.iter().take_while(|bs| bs.len() == 1).count();
    if lit_len >= 3 {
        let needle: Vec<u8> = byte_sets_raw[..lit_len].iter().map(|bs| bs[0]).collect();
        let lit = crate::simd::FwdLiteralSearch::new(&needle);
        if lit_len == byte_sets_raw.len()
            || crate::simd::BYTE_FREQ[lit.rare_byte() as usize] < RARE_BYTE_FREQ_LIMIT
        {
            return Ok(Some(crate::accel::FwdPrefixSearch::Literal(lit)));
        }
    }

    let mut freqs: Vec<(usize, u64)> = byte_sets_raw
        .iter()
        .enumerate()
        .map(|(i, bytes)| {
            let freq: u64 = bytes
                .iter()
                .map(|&b| crate::simd::BYTE_FREQ[b as usize] as u64)
                .sum();
            (i, freq)
        })
        .filter(|&(_, f)| f > 0)
        .collect();
    if freqs.is_empty() {
        return Ok(None);
    }
    freqs.sort_by_key(|&(_, f)| f);

    let rarest_idx = freqs[0].0;
    let rarest_freq_sum = freqs[0].1;
    let rarest_len = byte_sets_raw[rarest_idx].len();

    let narrow_positions = byte_sets_raw
        .iter()
        .map(|bs| {
            bs.iter()
                .map(|&b| crate::simd::BYTE_FREQ[b as usize] as u64)
                .sum::<u64>()
        })
        .filter(|&f| f <= TEDDY_WEAK_POSITION_FREQ)
        .count();
    let non_full_positions = byte_sets_raw.iter().filter(|bs| bs.len() < 256).count();
    if byte_sets_raw.len() > 1 && non_full_positions <= 1 {
        if cfg!(feature = "debug") {
            eprintln!(
                "  [fwd-prefix] reject: only {} discriminating position(s) in {}-byte prefix",
                non_full_positions,
                byte_sets_raw.len()
            );
        }
        return Ok(None);
    }
    let degenerate = byte_sets_raw.len() == 1;
    if degenerate && rarest_freq_sum > TEDDY_MEMCHR_MAX_FREQ_F {
        let _ = narrow_positions;
        if cfg!(feature = "debug") {
            eprintln!(
                "  [fwd-prefix] teddy-degenerate, trying range: rarest_freq={} > {} (narrow_positions={})",
                rarest_freq_sum, TEDDY_MEMCHR_MAX_FREQ_F, narrow_positions
            );
        }
        return try_build_fwd_range_prefix(byte_sets_raw, rarest_idx, allow_common).map(|r| r.0);
    }

    if rarest_len > 16 {
        return try_build_fwd_range_prefix(byte_sets_raw, rarest_idx, false).map(|r| r.0);
    }

    // Reject Teddy when the rarest position is too common (high false-positive
    // rate). Try a range-based prefix first; if that also fails, skip entirely.
    if rarest_freq_sum > TEDDY_MAX_FREQ_SUM {
        return try_build_fwd_range_prefix(byte_sets_raw, rarest_idx, false).map(|r| r.0);
    }

    let freq_order: Vec<usize> = freqs.iter().map(|&(i, _)| i).collect();

    if cfg!(feature = "debug") {
        let _ = &freqs;
        eprintln!(
            "  [fwd-prefix] anchor=pos{} ({} bytes)",
            freq_order[0],
            byte_sets_raw[freq_order[0]].len()
        );
    }

    let all_sets: Vec<crate::accel::TSet> = byte_sets_raw
        .iter()
        .map(|bytes| crate::accel::TSet::from_bytes(bytes))
        .collect();

    Ok(Some(crate::accel::FwdPrefixSearch::Prefix(
        crate::simd::FwdPrefixSearch::new(
            byte_sets_raw.len(),
            &freq_order,
            byte_sets_raw,
            all_sets,
        ),
    )))
}

fn rarest_freq(b: &mut RegexBuilder, sets: &[TSetId]) -> u64 {
    sets.iter()
        .map(|&s| {
            b.solver()
                .collect_bytes(s)
                .iter()
                .map(|&byte| crate::simd::BYTE_FREQ[byte as usize] as u64)
                .sum::<u64>()
        })
        .min()
        .unwrap_or(u64::MAX)
}

fn build_fwd_prefix_from_sets(
    b: &mut RegexBuilder,
    full_sets: &[TSetId],
    allow_common: bool,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    if !full_sets.is_empty() {
        return try_build_fwd_search(b, full_sets, allow_common);
    }
    Ok(None)
}

fn every_first_byte_is_full_match(b: &mut RegexBuilder, node: NodeId) -> bool {
    let der = match b.der(node, Nullability::CENTER) {
        Ok(d) => d,
        Err(_) => return false,
    };
    let mut targets: Vec<(NodeId, TSetId)> = Vec::new();
    b.collect_der_targets(der, TSetId::FULL, &mut targets);
    let mut any = false;
    for (t, _) in targets {
        if t == NodeId::BOT {
            continue;
        }
        any = true;
        if !b.nullability(t).has(Nullability::CENTER) {
            return false;
        }
    }
    any
}

fn build_fwd_prefix_simd(
    b: &mut RegexBuilder,
    node: NodeId,
) -> Result<Option<crate::accel::FwdPrefixSearch>, crate::Error> {
    let full_sets = calc_potential_start(b, node, 16, 64, false)?;
    let allow_common = every_first_byte_is_full_match(b, node);
    build_fwd_prefix_from_sets(b, &full_sets, allow_common)
}

const MAX_RANGE_SETS: usize = 3;

fn try_build_fwd_range_prefix(
    byte_sets_raw: &[Vec<u8>],
    anchor_pos: usize,
    allow_common: bool,
) -> Result<(Option<crate::accel::FwdPrefixSearch>, bool), crate::Error> {
    let anchor_bytes = &byte_sets_raw[anchor_pos];
    let freq_sum: u32 = anchor_bytes
        .iter()
        .map(|&b| crate::simd::BYTE_FREQ[b as usize] as u32)
        .sum();
    // Space (0x20) is saturated at u16::MAX (65535); we want to reject it as
    // a sole anchor since it's the most common byte in typical text.
    const RANGE_FREQ_THRESHOLD: u32 = 65_535;
    if !allow_common && freq_sum >= RANGE_FREQ_THRESHOLD {
        if cfg!(feature = "debug") {
            eprintln!(
                "  [fwd-prefix-range] reject: {} bytes, freq_sum={} >= {}",
                anchor_bytes.len(),
                freq_sum,
                RANGE_FREQ_THRESHOLD
            );
        }
        return Ok((None, false));
    }
    let tset = crate::accel::TSet::from_bytes(anchor_bytes);
    let exact_ranges: Vec<(u8, u8)> = Solver::pp_collect_ranges(&tset).into_iter().collect();
    if exact_ranges.is_empty() {
        return Ok((None, false));
    }
    let ranges: Vec<(u8, u8)> = if exact_ranges.len() <= MAX_RANGE_SETS {
        exact_ranges
    } else {
        let ascii_only: Vec<u8> = anchor_bytes.iter().copied().filter(|&b| b < 0x80).collect();
        let has_high = anchor_bytes.iter().any(|&b| b >= 0x80);
        if !has_high {
            return Ok((None, false));
        }
        let ascii_tset = crate::accel::TSet::from_bytes(&ascii_only);
        let mut coarse: Vec<(u8, u8)> =
            Solver::pp_collect_ranges(&ascii_tset).into_iter().collect();
        coarse.push((0x80, 0xFF));
        if coarse.len() > MAX_RANGE_SETS {
            return Ok((None, false));
        }
        if cfg!(feature = "debug") {
            eprintln!(
                "  [fwd-prefix-range] coarsened {} ranges -> {} (high-byte fold)",
                exact_ranges.len(),
                coarse.len()
            );
        }
        coarse
    };
    let all_sets: Vec<crate::accel::TSet> = byte_sets_raw
        .iter()
        .map(|bytes| crate::accel::TSet::from_bytes(bytes))
        .collect();
    if cfg!(feature = "debug") {
        eprintln!(
            "  [fwd-prefix-range] anchor=pos{} ranges={:?} len={}",
            anchor_pos,
            ranges,
            byte_sets_raw.len()
        );
    }
    Ok((
        Some(crate::accel::FwdPrefixSearch::Range(
            crate::simd::FwdRangeSearch::new(byte_sets_raw.len(), anchor_pos, ranges, all_sets),
        )),
        false,
    ))
}

/// Build a `RevTeddySearch` from byte sets, or return `None` if the sets are
/// too wide to be useful.  `len >= 2` required (single-byte case is handled by
/// the DFA skip system).
pub(crate) fn build_rev_prefix_search(
    b: &mut RegexBuilder,
    sets: &[TSetId],
    memchr_max: u64,
) -> Option<crate::accel::RevTeddySearch> {
    if sets.len() < 1 {
        return None;
    }
    let byte_sets_raw: Vec<Vec<u8>> = sets
        .iter()
        .map(|&set| b.solver().collect_bytes(set))
        .collect();
    let num_simd = sets.len().min(3);
    // per-position freq for every position in the full rev prefix
    let pos_freq: Vec<u64> = byte_sets_raw
        .iter()
        .map(|bs| {
            bs.iter()
                .map(|&b| crate::simd::BYTE_FREQ[b as usize] as u64)
                .sum::<u64>()
        })
        .collect();
    let mut tail_offset = 0usize;
    let mut best_prod = u128::MAX;
    for off in 0..=byte_sets_raw.len() - num_simd {
        let prod: u128 = pos_freq[off..off + num_simd]
            .iter()
            .map(|&f| f as u128)
            .product();
        if prod < best_prod {
            best_prod = prod;
            tail_offset = off;
        }
    }
    let freq_sums: Vec<u64> = pos_freq[tail_offset..tail_offset + num_simd].to_vec();
    let rarest_freq_sum = *freq_sums.iter().min().unwrap_or(&u64::MAX);
    if rarest_freq_sum > TEDDY_MAX_FREQ_SUM {
        return None;
    }
    let narrow = freq_sums
        .iter()
        .filter(|&&f| f <= TEDDY_WEAK_POSITION_FREQ)
        .count();
    if narrow < 2 && rarest_freq_sum > memchr_max {
        return None;
    }
    let combined_freq: u128 = freq_sums.iter().map(|&f| f as u128).product();
    let threshold: u128 = 12 * (TOTAL_BYTE_FREQ as u128).pow(num_simd as u32) / 256;
    if combined_freq > threshold {
        return None;
    }
    let window = &byte_sets_raw[tail_offset..tail_offset + num_simd];
    let all_sets: Vec<crate::accel::TSet> = window
        .iter()
        .map(|bytes| crate::accel::TSet::from_bytes(bytes))
        .collect();
    Some(crate::accel::RevTeddySearch::new(
        num_simd,
        window,
        all_sets,
        tail_offset,
    ))
}

/// Runtime prefix acceleration
#[cfg_attr(debug_assertions, derive(Debug))]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize, Clone)
)]
pub enum PrefixKind {
    AnchoredRev,
    AnchoredFwd(crate::accel::FwdPrefixSearch),
    AnchoredFwdLb(crate::accel::FwdPrefixSearch),
    PotentialStart,
    #[cfg(feature = "convergence_prefix")]
    Convergence,
}

impl PrefixKind {
    #[cfg(feature = "diag")]
    pub(crate) fn is_fwd(&self) -> bool {
        matches!(
            self,
            PrefixKind::AnchoredFwd(_) | PrefixKind::AnchoredFwdLb(_)
        )
    }

    #[cfg(feature = "diag")]
    pub(crate) fn is_rev(&self) -> bool {
        #[cfg(feature = "convergence_prefix")]
        return matches!(
            self,
            PrefixKind::AnchoredRev | PrefixKind::PotentialStart | PrefixKind::Convergence
        );
        #[cfg(not(feature = "convergence_prefix"))]
        matches!(self, PrefixKind::AnchoredRev | PrefixKind::PotentialStart)
    }
}

#[allow(dead_code)]
pub(crate) fn try_rev_prefix(
    b: &mut RegexBuilder,
    rev_node: NodeId,
) -> Result<Option<(PrefixKind, crate::accel::RevTeddySearch)>, Error> {
    use resharp_algebra::nulls::NullsId;
    if b.get_nulls_id(rev_node) != NullsId::EMPTY {
        return Ok(None);
    }
    let anchored = calc_prefix_sets(b, rev_node)?;
    if !anchored.is_empty() {
        if let Some(s) = build_rev_prefix_search(b, &anchored, TEDDY_MEMCHR_MAX_FREQ) {
            return Ok(Some((PrefixKind::AnchoredRev, s)));
        }
    }
    let potential = calc_potential_start_prune(b, rev_node, 16, 64, true)?;
    if !potential.is_empty() {
        if let Some(s) = build_rev_prefix_search(b, &potential, TEDDY_MEMCHR_MAX_FREQ) {
            return Ok(Some((PrefixKind::PotentialStart, s)));
        }
    }
    Ok(None)
}

pub(crate) fn select_prefix(
    b: &mut RegexBuilder,
    node: NodeId,
    rev_start: NodeId,
    has_look: bool,
    min_len: u32,
    max_cap: usize,
    no_fwd_prefix: bool,
    hardened: bool,
    force_convergence: bool,
) -> Result<
    (
        Option<PrefixKind>,
        Option<(crate::accel::RevTeddySearch, Option<NodeId>, Option<NodeId>)>,
        bool,
    ),
    Error,
> {
    if !crate::simd::has_simd() {
        return Ok((None, None, false));
    }
    let _ = force_convergence;
    let (kind, skip, fwd_wins, selected_cost, rev_stripped) =
        select_prefix_simd(b, node, rev_start, has_look, min_len, no_fwd_prefix, hardened)?;
    #[cfg(not(feature = "convergence_prefix"))]
    let _ = (selected_cost, rev_stripped);
    #[cfg(feature = "convergence_prefix")]
    if let Some((conv_kind, conv_skip, conv_node, b_node, conv_cost)) =
        try_convergence_prefix(b, node, rev_stripped, force_convergence)?
    {
        let penalty = if matches!(kind, Some(PrefixKind::PotentialStart)) {
            1
        } else {
            CONV_PENALTY
        };
        if force_convergence
            || kind.is_none()
            || conv_cost.saturating_mul(penalty) < selected_cost
        {
            return Ok((
                Some(conv_kind),
                Some((conv_skip, Some(conv_node), Some(b_node))),
                false,
            ));
        }
    }
    let _ = max_cap;
    Ok((kind, skip.map(|s| (s, None, None)), fwd_wins))
}

#[cfg(feature = "convergence_prefix")]
const RESUME_STOPPER_MIN: u64 = 30_000;

#[cfg(feature = "convergence_prefix")]
fn loop_stopper_set(b: &mut RegexBuilder, body: NodeId) -> Result<TSetId, Error> {
    let der = b
        .der(body, resharp_algebra::nulls::Nullability::CENTER)
        .map_err(crate::Error::Algebra)?;
    let mut targets: Vec<(NodeId, TSetId)> = Vec::new();
    b.collect_der_targets(der, TSetId::FULL, &mut targets);
    let leading = targets
        .iter()
        .filter(|(t, _)| *t != NodeId::BOT)
        .fold(TSetId::EMPTY, |acc, &(_, cs)| b.solver().or_id(acc, cs));
    Ok(b.solver().not_id(leading))
}

#[cfg(feature = "convergence_prefix")]
fn set_byte_freq(b: &mut RegexBuilder, set: TSetId) -> u64 {
    b.solver()
        .collect_bytes(set)
        .iter()
        .map(|&c| crate::simd::BYTE_FREQ[c as usize] as u64)
        .sum()
}

#[cfg(feature = "convergence_prefix")]
fn resume_loops_die_fast(
    b: &mut RegexBuilder,
    conv_node: NodeId,
    run: &[TSetId],
) -> Result<bool, Error> {
    let run_union = run
        .iter()
        .fold(TSetId::EMPTY, |acc, &s| b.solver().or_id(acc, s));
    let mut spine: Vec<NodeId> = Vec::new();
    let mut curr = conv_node;
    loop {
        let is_concat = curr.is_concat(b);
        spine.push(if is_concat { curr.left(b) } else { curr });
        if is_concat {
            curr = curr.right(b);
        } else {
            break;
        }
    }
    let last_mandatory = spine
        .iter()
        .rposition(|&h| b.get_min_max_length(h).0 > 0);
    for (idx, &head) in spine.iter().enumerate() {
        if !head.is_star(b) {
            continue;
        }
        if last_mandatory.is_none_or(|m| idx > m) {
            continue;
        }
        let stopper = loop_stopper_set(b, head.left(b))?;
        if b.solver().is_sat_id(stopper, run_union) {
            continue;
        }
        if set_byte_freq(b, stopper) < RESUME_STOPPER_MIN {
            return Ok(false);
        }
    }
    Ok(true)
}

#[cfg(feature = "convergence_prefix")]
fn convergence_right_node(b: &RegexBuilder, fwd_node: NodeId, run: &[TSetId]) -> Option<NodeId> {
    fn head_byte(b: &RegexBuilder, h: NodeId) -> Option<u8> {
        if !h.is_pred(b) {
            return None;
        }
        let bytes = b.solver_ref().collect_bytes(h.pred_tset(b));
        (bytes.len() == 1).then(|| bytes[0])
    }
    let lit: Vec<u8> = run
        .iter()
        .rev()
        .map(|&s| {
            let bytes = b.solver_ref().collect_bytes(s);
            (bytes.len() == 1).then(|| bytes[0])
        })
        .collect::<Option<Vec<u8>>>()?;
    let mut spine: Vec<(NodeId, NodeId)> = Vec::new();
    let mut curr = fwd_node;
    loop {
        let is_concat = curr.is_concat(b);
        let head = if is_concat { curr.left(b) } else { curr };
        spine.push((curr, head));
        if is_concat {
            curr = curr.right(b);
        } else {
            break;
        }
    }
    let n = spine.len();
    if lit.is_empty() || lit.len() > n {
        return None;
    }
    let mut found: Option<usize> = None;
    for start in 0..=(n - lit.len()) {
        if (0..lit.len()).all(|k| head_byte(b, spine[start + k].1) == Some(lit[k])) {
            if found.is_some() {
                return None;
            }
            found = Some(start);
        }
    }
    let end = found? + lit.len();
    Some(if end >= n { NodeId::EPS } else { spine[end].0 })
}

#[cfg(feature = "convergence_prefix")]
fn try_convergence_prefix(
    b: &mut RegexBuilder,
    fwd_node: NodeId,
    rev_stripped: NodeId,
    force: bool,
) -> Result<Option<(PrefixKind, crate::accel::RevTeddySearch, NodeId, NodeId, u64)>, Error> {
    let (fwd_min, fwd_max) = b.get_min_max_length(fwd_node);
    if fwd_min == 0 {
        return Ok(None);
    }
    if !force
        && fwd_max <= CONV_BOUNDED_MAX
        && !b.contains_anchors(fwd_node)
        && !fwd_node.contains_lookaround(b)
    {
        return Ok(None);
    }
    let Some((conv_node, run, l_rep)) = crate::find_inner_literal(b, rev_stripped)
    else {
        return Ok(None);
    };
    let Some(b_node) = convergence_right_node(b, fwd_node, &run) else {
        return Ok(None);
    };
    if !force && !resume_loops_die_fast(b, conv_node, &run)? {
        return Ok(None);
    }
    let avoid_l = {
        let any_non_l = b.mk_pred_not(l_rep);
        b.mk_star(any_non_l)
    };
    let without_l = b.mk_inter(fwd_node, avoid_l);
    if b.is_empty_lang(without_l) != Some(true) {
        return Ok(None);
    }
    let Some(search) = build_rev_prefix_search(b, &run, CONV_MEMCHR_MAX) else {
        return Ok(None);
    };
    if !force && conv_b_interior_unbounded(b, b_node) {
        return Ok(None);
    }
    let b_potential = calc_potential_start(b, b_node, 16, 64, false)?;
    let b_shape = classify_body_shape(b, b_node, &b_potential);
    let conv_cost = scan_cost(b, &run, Direction::Fwd, b_shape);
    Ok(Some((
        PrefixKind::Convergence,
        search,
        conv_node,
        b_node,
        conv_cost,
    )))
}

fn strip_leading_lookbehind(b: &RegexBuilder, mut node: NodeId) -> NodeId {
    loop {
        if !node.is_concat(b) {
            break;
        }
        if !node.left(b).is_lookbehind(b) {
            break;
        }
        node = node.right(b);
    }
    node
}

fn node_lead_bytes(b: &mut RegexBuilder, node: NodeId) -> TSetId {
    use resharp_algebra::nulls::Nullability;
    match b.der(node, Nullability::CENTER) {
        Ok(d) => {
            let mut stack = vec![(d, TSetId::FULL)];
            let mut acc = TSetId::EMPTY;
            b.iter_sat(&mut stack, &mut |bb, _n, set| {
                acc = bb.solver().or_id(acc, set);
            });
            acc
        }
        Err(_) => b.solver().not_id(TSetId::EMPTY),
    }
}

fn loop_body_class(b: &mut RegexBuilder, node: NodeId) -> Option<TSetId> {
    if node.is_star(b) {
        return Some(node_lead_bytes(b, node));
    }
    if node.is_lookahead(b) {
        let tail = node.right(b);
        if let Some(s) = loop_body_class(b, tail) {
            return Some(s);
        }
        return Some(node_lead_bytes(b, node));
    }
    if node.is_concat(b) {
        let left = node.left(b);
        return loop_body_class(b, left);
    }
    if node.is_inter(b) {
        let (l, r) = (node.left(b), node.right(b));
        if let Some(s) = loop_body_class(b, l) {
            return Some(s);
        }
        return loop_body_class(b, r);
    }
    None
}

fn fwd_interior_quadratic(b: &mut RegexBuilder, node: NodeId) -> bool {
    let mut seen_swallowing_loop = false;
    let mut prior_leads: Vec<TSetId> = Vec::new();
    let mut mandatory_prefix: Vec<TSetId> = Vec::new();
    let mut curr = node;
    loop {
        let is_concat = curr.is_concat(b);
        let head = if is_concat { curr.left(b) } else { curr };
        let (hmin, hmax) = b.get_min_max_length(head);
        let lead = node_lead_bytes(b, head);
        let single_position = hmin == 1 && hmax == 1;
        if seen_swallowing_loop && hmin > 0 {
            let absorbed = single_position
                && mandatory_prefix
                    .iter()
                    .any(|&m| b.solver().and_id(m, lead) == m);
            if !absorbed {
                return true;
            }
        }
        if hmax == u32::MAX && !prior_leads.is_empty() {
            let body = loop_body_class(b, head).unwrap_or(lead);
            let loop_chains_candidates = prior_leads
                .iter()
                .all(|&p| b.solver().is_sat_id(p, body));
            if loop_chains_candidates {
                if !is_pure_trailing_run(b, head) {
                    return true;
                }
                seen_swallowing_loop = true;
            }
        }
        if single_position {
            mandatory_prefix.push(lead);
        }
        prior_leads.push(lead);
        if is_concat {
            curr = curr.right(b);
        } else {
            break;
        }
    }
    false
}

fn select_prefix_simd(
    b: &mut RegexBuilder,
    node: NodeId,
    rev_start: NodeId,
    has_look: bool,
    min_len: u32,
    no_fwd_prefix: bool,
    hardened: bool,
) -> Result<(Option<PrefixKind>, Option<crate::accel::RevTeddySearch>, bool, u64, NodeId), Error> {
    use resharp_algebra::nulls::NullsId;
    if min_len == 0 {
        if !no_fwd_prefix && has_look && node.contains_lookbehind(b) {
            if let Some(fp) = try_build_fwd_lb(b, node)? {
                return Ok((Some(PrefixKind::AnchoredFwdLb(fp)), None, false, u64::MAX, NodeId::BOT));
            }
        }
        return Ok((None, None, false, u64::MAX, NodeId::BOT));
    }
    let sets = PrefixSets::compute(b, node, rev_start)?;
    let rev_stripped = sets.rev_stripped;

    let fwd_cost = sets
        .fwd_potential
        .cost
        .min(sets.fwd_potential_stripped.cost);
    let rev_cost = sets.rev_anchored.cost.min(sets.rev_potential.cost);
    let rev_usable = b.get_nulls_id(rev_start) == NullsId::EMPTY
        && (!sets.rev_anchored.sets.is_empty() || !sets.rev_potential.sets.is_empty());
    let (_, max_len) = b.get_min_max_length(node);
    let bounded = max_len != u32::MAX;
    let fwd_quad = !bounded && fwd_interior_quadratic(b, node);
    let fwd_wins = !fwd_quad && (bounded || fwd_cost < rev_cost);

    let fwd_candidate = if fwd_quad {
        None
    } else if no_fwd_prefix {
        if !hardened && fwd_wins {
            if has_look && node.contains_lookbehind(b) {
                match try_build_fwd_lb(b, node)? {
                    Some(fp) => Some(PrefixKind::AnchoredFwdLb(fp)),
                    None => {
                        try_build_fwd_neg_lb(b, node)?.map(|(fp, _)| PrefixKind::AnchoredFwd(fp))
                    }
                }
            } else {
                let allow_common = every_first_byte_is_full_match(b, node);
                build_fwd_prefix_from_sets(b, &sets.fwd_potential.sets, allow_common)?
                    .map(PrefixKind::AnchoredFwd)
            }
        } else {
            None
        }
    } else if has_look && node.contains_lookbehind(b) {
        match try_build_fwd_lb(b, node)? {
            Some(fp) => Some(PrefixKind::AnchoredFwdLb(fp)),
            None => try_build_fwd_neg_lb(b, node)?.map(|(fp, _)| PrefixKind::AnchoredFwd(fp)),
        }
    } else {
        let allow_common = every_first_byte_is_full_match(b, node);
        let fp = build_fwd_prefix_from_sets(b, &sets.fwd_potential.sets, allow_common)?;
        match fp {
            Some(fp) => Some(PrefixKind::AnchoredFwd(fp)),
            None if b.is_infinite(node) => {
                build_strict_literal_prefix(b, node)?.map(PrefixKind::AnchoredFwd)
            }
            None => None,
        }
    };
    let try_rev = |b: &mut RegexBuilder| -> Option<(PrefixKind, crate::accel::RevTeddySearch)> {
        if !rev_usable {
            return None;
        }
        if !sets.rev_anchored.sets.is_empty() {
            if let Some(s) = build_rev_prefix_search(b, &sets.rev_anchored.sets, TEDDY_MEMCHR_MAX_FREQ)
            {
                return Some((PrefixKind::AnchoredRev, s));
            }
        }
        if !sets.rev_potential.sets.is_empty() {
            if let Some(s) =
                build_rev_prefix_search(b, &sets.rev_potential.sets, TEDDY_MEMCHR_MAX_FREQ)
            {
                return Some((PrefixKind::PotentialStart, s));
            }
        }
        None
    };

    if fwd_wins || no_fwd_prefix {
        if let Some(kind) = fwd_candidate {
            return Ok((Some(kind), None, fwd_wins, fwd_cost, rev_stripped));
        }
    }
    if let Some((kind, s)) = try_rev(b) {
        return Ok((Some(kind), Some(s), false, rev_cost, rev_stripped));
    }
    if let Some(kind) = fwd_candidate {
        return Ok((Some(kind), None, fwd_wins, fwd_cost, rev_stripped));
    }
    Ok((None, None, false, u64::MAX, rev_stripped))
}

/// The positive byte-class a leading lookbehind contributes to a fwd prefix,
/// plus the lb length consumed. None when there is no usable fixed-length class.
pub(crate) fn fwd_lb_class(b: &mut RegexBuilder, lb: NodeId) -> Option<(NodeId, u32)> {
    if let Some(pred) = b.neg_lookbehind_prev_pred(lb) {
        return Some((pred, 1));
    }
    let lb_inner = b.get_lookbehind_inner(lb);
    let mut lb_stripped = b.nonbegins(lb_inner);
    loop {
        let stripped = b.strip_prefix_safe(lb_stripped);
        let after = b.nonbegins(stripped);
        if after == lb_stripped {
            break;
        }
        lb_stripped = after;
    }
    match b.get_fixed_length(lb_stripped) {
        Some(len @ 1..=64) => Some((lb_stripped, len)),
        _ => None,
    }
}

fn try_build_fwd_lb(
    b: &mut RegexBuilder,
    node: NodeId,
) -> Result<Option<crate::accel::FwdPrefixSearch>, Error> {
    #[cfg(feature = "debug")]
    eprintln!("  [try_build_fwd_lb] node={:?}", b.pp(node));
    let body = strip_leading_lookbehind(b, node);
    if body == node || node.right(b) != body {
        return Ok(None);
    }
    let lb = node.left(b);
    if !lb.is_lookbehind(b) {
        return Ok(None);
    }
    let Some((lb_stripped, _)) = fwd_lb_class(b, lb) else {
        return Ok(None);
    };
    if body_absorbs_lb(b, body, lb_stripped)? {
        #[cfg(feature = "debug")]
        eprintln!("  [fwd-lb] reject: body's leading star absorbs lb byte(s)");
        return Ok(None);
    }
    let lb_body = b.mk_concat(lb_stripped, body);
    #[cfg(feature = "debug")]
    eprintln!("  [try_build_fwd_lb] lb_stripped={:?}, body={:?}, lb_body={:?}", b.pp(lb_stripped), b.pp(body), b.pp(lb_body));
    let result = build_fwd_prefix(b, lb_body);
    #[cfg(feature = "debug")]
    eprintln!("  [try_build_fwd_lb] result={:?}", result.as_ref().map(|_| "Some"));
    result
}

/// One forbidden fixed-length suffix: a sequence of single-byte classes. A
/// candidate match start at `p` is matched (forbidden) iff `p >= len` and
/// `input[p-len+i]` is in `classes[i]` for all `i`.
#[cfg_attr(debug_assertions, derive(Debug))]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize, Clone)
)]
pub struct NegLbTerm {
    pub len: usize,
    pub classes: Vec<[u64; 4]>,
}

impl NegLbTerm {
    #[inline]
    fn matches(&self, input: &[u8], start: usize) -> bool {
        if start < self.len {
            return false;
        }
        let base = start - self.len;
        for (i, set) in self.classes.iter().enumerate() {
            let byte = input[base + i];
            if set[(byte >> 6) as usize] & (1u64 << (byte & 63)) == 0 {
                return false;
            }
        }
        true
    }
}

/// Fixed-length negative lookbehind verifier: a candidate start at `p` is
/// rejected iff any forbidden term matches the bytes before `p`.
#[cfg_attr(debug_assertions, derive(Debug))]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize, Clone)
)]
pub struct NegLb {
    pub terms: Vec<NegLbTerm>,
}

impl NegLb {
    #[inline]
    pub(crate) fn rejects(&self, input: &[u8], start: usize) -> bool {
        self.terms.iter().any(|t| t.matches(input, start))
    }
}

/// Parse a negative term `\A~(_*X)` into its single-byte class sequence, where
/// `X` is a `Pred` chain. Anything wider bails to `None`.
fn parse_neg_term(b: &mut RegexBuilder, term: NodeId) -> Option<Vec<TSetId>> {
    if !term.is_concat(b) || term.left(b) != NodeId::BEGIN {
        return None;
    }
    let compl = term.right(b);
    if !compl.is_compl(b) {
        return None;
    }
    let body_ts = compl.left(b);
    if !body_ts.is_concat(b) || body_ts.left(b) != NodeId::TS {
        return None;
    }
    let mut x = body_ts.right(b);
    let mut seq = Vec::new();
    loop {
        match b.get_kind(x) {
            Kind::Pred => {
                seq.push(x.pred_tset(b));
                break;
            }
            Kind::Concat if x.left(b).is_pred(b) => {
                seq.push(x.left(b).pred_tset(b));
                x = x.right(b);
            }
            _ => return None,
        }
    }
    if seq.is_empty() || seq.len() > 64 {
        return None;
    }
    Some(seq)
}

/// Detect a leading negative lookbehind `(?<!X)body`, where the lookbehind inner
/// is one negative term or an intersection `~(_*X1) & ~(_*X2) & ...` (e.g. a
/// hand-written guard merged with a `\b`). Returns `(body, per-term sequences)`.
/// Every term must be a single-byte-class chain; otherwise `None`.
fn neg_lb_body_and_seq(b: &mut RegexBuilder, node: NodeId) -> Option<(NodeId, Vec<Vec<TSetId>>)> {
    if !node.is_concat(b) {
        return None;
    }
    let lb = node.left(b);
    let body = node.right(b);
    if !lb.is_lookbehind(b) {
        return None;
    }
    let inner = b.get_lookbehind_inner(lb);
    let mut terms = Vec::new();
    let mut cur = inner;
    while cur.is_inter(b) {
        terms.push(parse_neg_term(b, cur.left(b))?);
        cur = cur.right(b);
    }
    terms.push(parse_neg_term(b, cur)?);
    Some((body, terms))
}

/// Build a body-literal forward prefix for a leading fixed-length negative
/// lookbehind. The lookbehind is verified separately by [`NegLb`]; the literal
/// is a necessary condition on the consumed bytes so the prefilter is sound.
pub(crate) fn try_build_fwd_neg_lb(
    b: &mut RegexBuilder,
    node: NodeId,
) -> Result<Option<(crate::accel::FwdPrefixSearch, NegLb)>, Error> {
    let Some((body, terms)) = neg_lb_body_and_seq(b, node) else {
        return Ok(None);
    };
    let Some(search) = build_fwd_prefix(b, body)? else {
        return Ok(None);
    };
    let neg = build_neg_lb(b, &terms);
    Ok(Some((search, neg)))
}

fn build_neg_lb(b: &mut RegexBuilder, terms: &[Vec<TSetId>]) -> NegLb {
    let terms = terms
        .iter()
        .map(|seq| {
            let classes = seq
                .iter()
                .map(|&set| {
                    let mut bits = [0u64; 4];
                    for byte in b.solver().collect_bytes(set) {
                        bits[(byte >> 6) as usize] |= 1u64 << (byte & 63);
                    }
                    bits
                })
                .collect();
            NegLbTerm {
                len: seq.len(),
                classes,
            }
        })
        .collect();
    NegLb { terms }
}

/// Recompute the [`NegLb`] verifier for a node already selected for a body-only
/// forward prefix (used at construction to attach the reject test).
pub(crate) fn neg_lb_classes(b: &mut RegexBuilder, node: NodeId) -> Option<NegLb> {
    let (_, terms) = neg_lb_body_and_seq(b, node)?;
    Some(build_neg_lb(b, &terms))
}

fn body_absorbs_lb(b: &mut RegexBuilder, body: NodeId, lb: NodeId) -> Result<bool, crate::Error> {
    let body_first = calc_potential_start(b, body, 1, 64, false)?;
    let lb_first = calc_potential_start(b, lb, 1, 64, false)?;
    let (Some(&bf), Some(&lf)) = (body_first.first(), lb_first.first()) else {
        return Ok(false);
    };
    let body_bytes = b.solver().collect_bytes(bf);
    let lb_bytes = b.solver().collect_bytes(lf);
    if body_bytes.len() < 64 {
        return Ok(false);
    }
    let body_set: std::collections::BTreeSet<u8> = body_bytes.iter().copied().collect();
    Ok(lb_bytes.iter().all(|b| body_set.contains(b)))
}