ferroni 1.8.1

Oniguruma, continued in pure Rust, with a vscode-oniguruma-compatible TextMate scanner
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
// regint.rs - Port of regint.h
// Internal types, OpCode, Operation, BitSet, MemStatus, regex_t.

use std::collections::HashMap;

use crate::oniguruma::*;
use crate::regenc::OnigEncoding;

// === Feature Flags (C #define USE_*) ===
pub const USE_CALL: bool = true;
pub const USE_CALLOUT: bool = true;
pub const USE_BACKREF_WITH_LEVEL: bool = true;
pub const USE_CAPTURE_HISTORY: bool = true;

// === Config Constants ===
pub const DEFAULT_PARSE_DEPTH_LIMIT: u32 = 4096;
pub const INIT_MATCH_STACK_SIZE: usize = 160;
pub const DEFAULT_MATCH_STACK_LIMIT_SIZE: u32 = 0;
/// Rust-only (ADR-008): the backtrack stack never grows past this many
/// entries unless a larger `match_stack_limit` is set. C lets it grow without
/// bound when the limit is 0, so one hostile line can exhaust memory. This
/// is a separate cap and not a default for `match_stack_limit`: a non-zero
/// limit turns off other optimizations that a plain search is allowed.
pub const HARD_MATCH_STACK_CAP: usize = 10_000_000;
pub const DEFAULT_RETRY_LIMIT_IN_MATCH: u64 = 10_000_000;
pub const DEFAULT_RETRY_LIMIT_IN_SEARCH: u64 = 0;
pub const DEFAULT_TIME_LIMIT_MSEC: u64 = 0;
pub const DEFAULT_SUBEXP_CALL_LIMIT_IN_SEARCH: u64 = 0;
pub const DEFAULT_SUBEXP_CALL_MAX_NEST_LEVEL: i32 = 20;

// === Internal Constants ===
pub const CHAR_MAP_SIZE: usize = 256;
pub const INFINITE_LEN: OnigLen = ONIG_INFINITE_DISTANCE;
pub const STEP_BACK_MAX_CHAR_LEN: i32 = 65535;
pub const LOOK_BEHIND_MAX_CHAR_LEN: i32 = STEP_BACK_MAX_CHAR_LEN;
pub const INFINITE_REPEAT: i32 = -1;

#[inline]
pub fn is_infinite_repeat(n: i32) -> bool {
    n == INFINITE_REPEAT
}

// === Bytecode Types ===
pub type RelAddrType = i32;
pub type AbsAddrType = i32;
pub type LengthType = i32;
pub type RelPositionType = i32;
pub type RepeatNumType = i32;
pub type MemNumType = i32;
pub type ModeType = i32;

// === MemStatus (bit status for captures) ===
pub type MemStatusType = u32;

pub const MEM_STATUS_BITS_NUM: usize = 32;

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_clear(stats: &mut MemStatusType) {
    *stats = 0;
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_on_all(stats: &mut MemStatusType) {
    *stats = !0u32;
}

#[inline]
pub fn mem_status_at(stats: MemStatusType, n: usize) -> bool {
    if n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        (stats & 1) != 0
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_at0(stats: MemStatusType, n: usize) -> bool {
    if n > 0 && n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        (stats & 1) != 0
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_is_all_on(stats: MemStatusType) -> bool {
    (stats & 1) != 0
}

#[inline]
pub fn mem_status_on(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM {
        if n != 0 {
            *stats |= 1u32 << n;
        }
    } else {
        *stats |= 1;
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_on_simple(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM {
        *stats |= 1u32 << n;
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_limit_at(stats: MemStatusType, n: usize) -> bool {
    if n < MEM_STATUS_BITS_NUM {
        (stats & (1u32 << n)) != 0
    } else {
        false
    }
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mem_status_limit_on(stats: &mut MemStatusType, n: usize) {
    if n < MEM_STATUS_BITS_NUM && n != 0 {
        *stats |= 1u32 << n;
    }
}

// === BitSet (256 bits for ASCII character classes) ===
pub const BITS_PER_BYTE: usize = 8;
pub const SINGLE_BYTE_SIZE: usize = 1 << BITS_PER_BYTE;
pub const BITS_IN_ROOM: usize = 32;
pub const BITSET_REAL_SIZE: usize = SINGLE_BYTE_SIZE / BITS_IN_ROOM;
pub type Bits = u32;
pub type BitSet = [Bits; BITSET_REAL_SIZE];

pub const SIZE_BITSET: usize = std::mem::size_of::<BitSet>();

#[inline]
pub fn bitset_clear(bs: &mut BitSet) {
    for slot in bs.iter_mut() {
        *slot = 0;
    }
}

#[inline]
pub fn bs_room(pos: usize) -> usize {
    pos >> 5
}

#[inline]
pub fn bs_bit(pos: usize) -> u32 {
    1u32 << (pos & 0x1f)
}

#[inline]
pub fn bitset_at(bs: &BitSet, pos: usize) -> bool {
    (bs[bs_room(pos)] & bs_bit(pos)) != 0
}

/// The positions of the set bits of `bs`, ascending. Visits whole words, so
/// sparse sets cost their population rather than 256 bit tests.
#[inline]
pub fn bitset_members(bs: &BitSet) -> impl Iterator<Item = usize> + '_ {
    bs.iter().enumerate().flat_map(|(room, &word)| {
        let mut bits = word;
        std::iter::from_fn(move || {
            (bits != 0).then(|| {
                let pos = room * BITS_IN_ROOM + bits.trailing_zeros() as usize;
                bits &= bits - 1;
                pos
            })
        })
    })
}

#[inline]
pub fn bitset_set_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] |= bs_bit(pos);
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn bitset_clear_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] &= !bs_bit(pos);
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn bitset_invert_bit(bs: &mut BitSet, pos: usize) {
    bs[bs_room(pos)] ^= bs_bit(pos);
}

// === Anchor Flags ===
pub const ANCR_PREC_READ: i32 = 1 << 0;
pub const ANCR_PREC_READ_NOT: i32 = 1 << 1;
pub const ANCR_LOOK_BEHIND: i32 = 1 << 2;
pub const ANCR_LOOK_BEHIND_NOT: i32 = 1 << 3;
pub const ANCR_BEGIN_BUF: i32 = 1 << 4;
pub const ANCR_BEGIN_LINE: i32 = 1 << 5;
pub const ANCR_BEGIN_POSITION: i32 = 1 << 6;
pub const ANCR_END_BUF: i32 = 1 << 7;
pub const ANCR_SEMI_END_BUF: i32 = 1 << 8;
pub const ANCR_END_LINE: i32 = 1 << 9;
pub const ANCR_WORD_BOUNDARY: i32 = 1 << 10;
pub const ANCR_NO_WORD_BOUNDARY: i32 = 1 << 11;
pub const ANCR_WORD_BEGIN: i32 = 1 << 12;
pub const ANCR_WORD_END: i32 = 1 << 13;
pub const ANCR_ANYCHAR_INF: i32 = 1 << 14;
pub const ANCR_ANYCHAR_INF_ML: i32 = 1 << 15;
pub const ANCR_TEXT_SEGMENT_BOUNDARY: i32 = 1 << 16;
pub const ANCR_NO_TEXT_SEGMENT_BOUNDARY: i32 = 1 << 17;
pub const ANCR_ANYCHAR_INF_MASK: i32 = ANCR_ANYCHAR_INF | ANCR_ANYCHAR_INF_ML;

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn anchor_has_body(anchor_type: i32) -> bool {
    anchor_type < ANCR_BEGIN_BUF
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_word_anchor_type(anchor_type: i32) -> bool {
    anchor_type == ANCR_WORD_BOUNDARY
        || anchor_type == ANCR_NO_WORD_BOUNDARY
        || anchor_type == ANCR_WORD_BEGIN
        || anchor_type == ANCR_WORD_END
}

// === OpCode Enum ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum OpCode {
    Finish = 0,
    End = 1,
    Str1 = 2,
    Str2 = 3,
    Str3 = 4,
    Str4 = 5,
    Str5 = 6,
    StrN = 7,
    StrMb2n1 = 8,
    StrMb2n2 = 9,
    StrMb2n3 = 10,
    StrMb2n = 11,
    StrMb3n = 12,
    StrMbn = 13,
    CClass = 14,
    CClassMb = 15,
    CClassMix = 16,
    CClassNot = 17,
    CClassMbNot = 18,
    CClassMixNot = 19,
    AnyChar = 20,
    AnyCharMl = 21,
    AnyCharStar = 22,
    AnyCharMlStar = 23,
    AnyCharStarPeekNext = 24,
    AnyCharMlStarPeekNext = 25,
    Word = 26,
    WordAscii = 27,
    NoWord = 28,
    NoWordAscii = 29,
    WordBoundary = 30,
    NoWordBoundary = 31,
    WordBegin = 32,
    WordEnd = 33,
    TextSegmentBoundary = 34,
    BeginBuf = 35,
    EndBuf = 36,
    BeginLine = 37,
    EndLine = 38,
    SemiEndBuf = 39,
    CheckPosition = 40,
    BackRef1 = 41,
    BackRef2 = 42,
    BackRefN = 43,
    BackRefNIc = 44,
    BackRefMulti = 45,
    BackRefMultiIc = 46,
    BackRefWithLevel = 47,
    BackRefWithLevelIc = 48,
    BackRefCheck = 49,
    BackRefCheckWithLevel = 50,
    MemStart = 51,
    MemStartPush = 52,
    MemEndPush = 53,
    MemEndPushRec = 54,
    MemEnd = 55,
    MemEndRec = 56,
    Fail = 57,
    Jump = 58,
    Push = 59,
    PushSuper = 60,
    Pop = 61,
    PopToMark = 62,
    PushOrJumpExact1 = 63,
    PushIfPeekNext = 64,
    Repeat = 65,
    RepeatNg = 66,
    RepeatInc = 67,
    RepeatIncNg = 68,
    EmptyCheckStart = 69,
    EmptyCheckEnd = 70,
    EmptyCheckEndMemst = 71,
    EmptyCheckEndMemstPush = 72,
    Move = 73,
    StepBackStart = 74,
    StepBackNext = 75,
    CutToMark = 76,
    Mark = 77,
    SaveVal = 78,
    UpdateVar = 79,
    Call = 80,
    Return = 81,
    CalloutContents = 82,
    CalloutName = 83,
    CClassStar = 84,
    CClassMixStar = 85,
    CClassMbStar = 86,
    WordStar = 87,
    WordAsciiStar = 88,
    CClassStarPeekNext = 89,
    WordAsciiStarPeekNext = 90,
    AltLiterals = 91,
    CClassNotStar = 92,
    CClassMbNotStar = 93,
    CClassMixNotStar = 94,
    /// Rust-only (ADR-008): a fixed-length look-behind whose body is the
    /// single character or string instruction that follows it.
    LookBehindOp = 95,
    /// Rust-only (ADR-008): `PushOrJumpExact1` with a byte set. Pushes the
    /// alternative only when the current byte can start the main path.
    PushOrJumpByteSet = 96,
    /// A bounded run of identical ASCII character classes.
    CClassRun = 97,
    /// Rust-only (ADR-008): positive ASCII class star with no exit choices.
    /// Emitted only by the explicitly enabled decimal rewrite pass.
    CClassPossessiveStar = 98,
    /// Rust-only (ADR-008): decimal prefix reserving the final digit for its tail.
    DecimalTailPrefix = 99,
}

// === SaveType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum SaveType {
    Keep = 0,
    S = 1,
    RightRange = 2,
}

// === UpdateVarType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum UpdateVarType {
    KeepFromStackLast = 0,
    SFromStack = 1,
    RightRangeFromStack = 2,
    RightRangeFromSStack = 3,
    RightRangeToS = 4,
    RightRangeInit = 5,
}

// === CheckPositionType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum CheckPositionType {
    SearchStart = 0,
    CurrentRightRange = 1,
}

// === TextSegmentBoundaryType ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum TextSegmentBoundaryType {
    ExtendedGraphemeCluster = 0,
    Word = 1,
}

// === Stack Pop Level ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum StackPopLevel {
    Free = 0,
    MemStart = 1,
    All = 2,
}

// === Optimize Type ===
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OptimizeType {
    None,
    Str,
    StrFast,
    StrFastStepForward,
    Map,
}

// === CClass Flags ===
pub const FLAG_NCCLASS_NOT: u32 = 1 << 0;
pub const FLAG_NCCLASS_SHARE: u32 = 1 << 1;

// === Operation (Bytecode Instruction) ===
//
// In C this is a struct with opcode + union. In Rust we use struct + enum payload.
// The opcode field is stored separately for direct access (needed for dispatch).
pub struct Operation {
    pub opcode: OpCode,
    pub payload: OperationPayload,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CClassAsciiFastKind {
    None,
    Eq(u8),
    EqFoldLower(u8),
}

pub enum OperationPayload {
    None,
    /// Captures around the repeated decimal/optional-underscore body, outer first.
    DecimalTailPrefix {
        captures: Vec<MemNumType>,
    },
    Exact {
        s: [u8; 16],
    },
    ExactN {
        s: Vec<u8>,
        n: LengthType,
    },
    ExactLenN {
        s: Vec<u8>,
        n: LengthType,
        len: LengthType,
    },
    CClass {
        bsp: Box<BitSet>,
        ascii_fast: CClassAsciiFastKind,
    },
    CClassRun {
        bsp: Box<BitSet>,
        len: u8,
    },
    CClassMb {
        mb: Vec<u32>,
    },
    CClassMix {
        mb: Vec<u32>,
        bsp: Box<BitSet>,
    },
    AnyCharStarPeekNext {
        c: u8,
    },
    CClassStarPeekNext {
        bsp: Box<BitSet>,
        c: u8,
    },
    WordAsciiStarPeekNext {
        c: u8,
    },
    WordBoundary {
        mode: ModeType,
    },
    TextSegmentBoundary {
        boundary_type: TextSegmentBoundaryType,
        not: bool,
    },
    CheckPosition {
        check_type: CheckPositionType,
    },
    BackRefN {
        n1: MemNumType,
    },
    BackRefGeneral {
        num: i32,
        ns: Vec<MemNumType>,
        nest_level: i32,
    },
    MemoryStart {
        num: MemNumType,
    },
    MemoryEnd {
        num: MemNumType,
    },
    Jump {
        addr: RelAddrType,
    },
    Push {
        addr: RelAddrType,
    },
    PushOrJumpExact1 {
        addr: RelAddrType,
        c: u8,
        /// Rust-only (ADR-008): on a guarded `Push`, the backtracks its jump
        /// counts for the push it skips (see `guard_skipped_retries`).
        /// Upstream's own instruction counts none.
        skipped_retries: u32,
    },
    PushIfPeekNext {
        addr: RelAddrType,
        c: u8,
    },
    PopToMark {
        id: MemNumType,
    },
    Repeat {
        id: MemNumType,
        addr: RelAddrType,
    },
    RepeatInc {
        id: MemNumType,
    },
    EmptyCheckStart {
        mem: MemNumType,
    },
    EmptyCheckEnd {
        mem: MemNumType,
        empty_status_mem: MemStatusType,
    },
    Move {
        n: RelPositionType,
    },
    StepBackStart {
        initial: LengthType,
        remaining: LengthType,
        addr: RelAddrType,
    },
    CutToMark {
        id: MemNumType,
        restore_pos: bool,
    },
    Mark {
        id: MemNumType,
        save_pos: bool,
    },
    SaveVal {
        save_type: SaveType,
        id: MemNumType,
    },
    UpdateVar {
        var_type: UpdateVarType,
        id: MemNumType,
        clear: bool,
    },
    Call {
        addr: AbsAddrType,
    },
    Return,
    CalloutContents {
        num: MemNumType,
    },
    CalloutName {
        num: MemNumType,
        id: MemNumType,
    },
    AltLiterals {
        trie_idx: u32,
    },
    LookBehindOp {
        /// Characters to step back, as `StepBackStart`.
        char_len: u32,
        /// `(?<!...)` rather than `(?<=...)`.
        not: bool,
    },
    PushOrJumpByteSet {
        addr: RelAddrType,
        /// The bytes the main path can consume first.
        bsp: Box<BitSet>,
        /// The backtracks the jump counts for the push it skips (see
        /// `guard_skipped_retries`).
        skipped_retries: u32,
    },
}

// === Callout constants ===
pub const CALLOUT_IN_PROGRESS: i32 = OnigCalloutIn::Progress as i32;
pub const CALLOUT_IN_RETRACTION: i32 = OnigCalloutIn::Retraction as i32;
pub const CALLOUT_IN_BOTH: i32 = CALLOUT_IN_PROGRESS | CALLOUT_IN_RETRACTION;

/// Builtin callout IDs (hard-coded instead of global name registry)
pub const CALLOUT_BUILTIN_FAIL: i32 = 0;
pub const CALLOUT_BUILTIN_MAX: i32 = 1;
pub const CALLOUT_BUILTIN_COUNT: i32 = 2;
pub const CALLOUT_BUILTIN_CMP: i32 = 3;
pub const CALLOUT_BUILTIN_SKIP: i32 = 4;

/// Result codes for callout functions
pub const ONIG_CALLOUT_FAIL: i32 = 1;
pub const ONIG_CALLOUT_SUCCESS: i32 = 0;

// === Callout argument ===
#[derive(Clone, Debug)]
pub enum CalloutArg {
    Long(i64),
    Char(u8),
    Tag(Vec<u8>),
    Str(Vec<u8>),
}

// === CalloutListEntry ===
pub struct CalloutListEntry {
    pub of: i32,         // 0=contents, 1=name
    pub callout_in: i32, // CALLOUT_IN_PROGRESS / RETRACTION / BOTH
    pub builtin_id: i32, // CALLOUT_BUILTIN_MAX etc., -1 for contents
    pub tag: Option<Vec<u8>>,
    pub tag_start: usize, // byte offset of tag start in pattern
    pub tag_end: usize,   // byte offset of tag end in pattern
    pub args: Vec<CalloutArg>,
    pub content_end: Option<Vec<u8>>, // Content end bytes for content callouts
}

// === RepeatRange ===
#[derive(Clone, Debug)]
pub struct RepeatRange {
    pub lower: i32,
    pub upper: i32,
    pub u_offset: i32,
}

// === RegexExt (Callout Extension) ===
pub struct RegexExt {
    pub pattern: Vec<u8>,
    pub tag_table: Option<HashMap<Vec<u8>, i32>>,
    pub callout_num: i32,
    pub callout_list: Vec<CalloutListEntry>,
}

// === regex_t (re_pattern_buffer) ===
pub struct RegexType {
    /// Rust-only: findings of the compile-time backtracking check.
    pub(crate) backtrack_warnings: Vec<crate::backtrack_lint::BacktrackWarning>,
    /// Rust-only: reports from the explicitly enabled AST rewrite pass.
    pub(crate) backtrack_rewrites: Vec<crate::backtrack_rewrite::BacktrackingRewrite>,
    // bytecode
    pub(crate) ops: Vec<Operation>,
    pub(crate) string_pool: Vec<u8>,

    // capture info
    pub(crate) num_mem: i32,
    pub(crate) num_repeat: i32,
    pub(crate) num_empty_check: i32,
    pub(crate) num_call: i32,
    pub(crate) capture_history: MemStatusType,
    pub(crate) push_mem_start: MemStatusType,
    pub(crate) push_mem_end: MemStatusType,
    pub(crate) stack_pop_level: StackPopLevel,
    pub(crate) repeat_range: Vec<RepeatRange>,

    // metadata
    pub(crate) enc: OnigEncoding,
    pub(crate) options: OnigOptionType,
    /// Owned syntax configuration captured at compile time. Keeping a clone
    /// avoids tying a compiled regex to the lifetime of its caller's syntax.
    pub(crate) syntax: OnigSyntaxType,
    pub(crate) case_fold_flag: OnigCaseFoldType,
    pub(crate) name_table: Option<crate::regparse_types::NameTable>,

    // optimization
    pub(crate) optimize: OptimizeType,
    pub(crate) threshold_len: i32,
    pub(crate) anchor: i32,
    pub(crate) anc_dist_min: OnigLen,
    pub(crate) anc_dist_max: OnigLen,
    pub(crate) sub_anchor: i32,
    pub(crate) exact: Vec<u8>,
    /// Reuse the forward literal search plan across haystacks (ADR-008).
    pub(crate) exact_finder: Option<Box<memchr::memmem::Finder<'static>>>,
    pub(crate) map: [u8; CHAR_MAP_SIZE],
    pub(crate) map_offset: i32,
    pub(crate) map_bytes: [u8; 3],
    pub(crate) map_byte_count: u8,
    /// Rust-only (ADR-008): the ASCII part of `map` as byte ranges, for a
    /// map search that checks eight ASCII bytes at a time.
    pub(crate) map_ascii_ranges: MapAsciiRanges,
    pub(crate) dist_min: OnigLen,
    pub(crate) dist_max: OnigLen,
    /// True when capture registers are needed for matching semantics even if
    /// the caller does not request a region (e.g. backrefs, recursive mem ops).
    pub(crate) needs_capture_tracking: bool,

    /// True when the pattern uses `\K`, so the match start can move away from
    /// the position its attempt began at. The region is then the only place
    /// that carries the whole match: `[attempt position, attempt position +
    /// match length]` no longer describes it.
    pub(crate) keep_moves_match_start: bool,

    /// First-byte prefilter map for regset dispatch.
    /// Unlike `map` (which may be repurposed as BMH skip table when optimize=StrFast),
    /// this always contains the character membership map for possible first bytes.
    /// Only valid when `has_first_byte_map` is true.
    pub(crate) first_byte_map: [u8; CHAR_MAP_SIZE],
    pub(crate) has_first_byte_map: bool,
    /// Rust-only RegSet routing hint: the optimizer (C's) has an unbounded
    /// distance, but the extra class and type maps would give one within a
    /// bounded distance of the match start. Such an entry is dispatched by
    /// its start bytes, with C's optimizer still deciding which positions it
    /// attempts; `first_byte_map` holds those maps' start bytes where they
    /// sit at the match start.
    pub(crate) start_dispatch: bool,

    // subroutine call support
    pub(crate) called_addrs: Vec<i32>, // group_num -> called entry address
    pub(crate) unset_call_addrs: Vec<(usize, i32)>, // (op_index, group_num) for patching

    // extension (callouts)
    pub(crate) extp: Option<RegexExt>,

    // literal alternation tries (for AltLiterals opcode)
    pub(crate) literal_tries: Vec<crate::literal_trie::LiteralTrie>,

    /// Rust-only (ADR-008): some guarded push carries
    /// `GUARD_RETRIES_BY_CHECKS`.
    pub(crate) check_dependent_guards: bool,

    // Aho-Corasick automaton for pure literal alternation fast path.
    // `ac_alt_has_capture` is true when the alternation is wrapped in a single
    // capture group, so the fast path must also populate region[1].
    pub(crate) ac_alt: Option<aho_corasick::AhoCorasick>,
    pub(crate) ac_alt_has_capture: bool,

    /// Rust-only (ADR-008): skips for a leading class run
    /// (`crate::leading_run`).
    pub(crate) leading_run: Option<Box<crate::leading_run::LeadingRun>>,
    /// Rust-only (ADR-008): bytecode start bytes for positions C's optimizer
    /// does not narrow down (`crate::leading_run`).
    pub(crate) search_start_map: Option<Box<crate::leading_run::SearchStartMap>>,
    /// Rust-only (ADR-008): where attempts can pass the leading checks
    /// (`crate::leading_run::SearchJump`).
    pub(crate) search_jump: Option<Box<crate::leading_run::SearchJump>>,
    /// Rust-only (ADR-008): literals one of which every match contains,
    /// for RegSet fallback searches (`crate::required_literals`).
    pub(crate) required_literals: Option<Box<crate::required_literals::RequiredLiterals>>,
}

/// The ASCII bytes of an optimizer map as at most [`MapAsciiRanges::MAX`]
/// inclusive ranges. Rust-only (ADR-008): `map_search` tests eight ASCII
/// bytes at a time against them (`first_member`), instead of one table
/// lookup and one character step per byte.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct MapAsciiRanges {
    ranges: [(u8, u8); MapAsciiRanges::MAX],
    /// Zero when the map's ASCII part needs more ranges than fit.
    count: u8,
}

impl MapAsciiRanges {
    pub(crate) const MAX: usize = 6;

    /// The ranges of `map` below 0x80, or none if they do not fit.
    pub(crate) fn of(map: &[u8; CHAR_MAP_SIZE]) -> Self {
        let mut out = Self::default();
        let mut at = 0;
        while at < 0x80 {
            if map[at] == 0 {
                at += 1;
                continue;
            }
            let lo = at;
            while at < 0x80 && map[at] != 0 {
                at += 1;
            }
            if out.count as usize == Self::MAX {
                return Self::default();
            }
            out.ranges[out.count as usize] = (lo as u8, (at - 1) as u8);
            out.count += 1;
        }
        out
    }

    /// Whether `first_member` applies: the map has an ASCII member.
    #[inline]
    pub(crate) fn usable(&self) -> bool {
        self.count != 0
    }

    /// For eight ASCII bytes (little-endian, every high bit clear), the
    /// index of the first byte inside a range. Adding `0x80 - lo` sets a
    /// byte's high bit exactly when the byte is at least `lo`, and adding
    /// `0x7F - hi` when it is above `hi`; no sum carries into the next byte.
    #[inline]
    pub(crate) fn first_member(&self, chunk: u64) -> Option<usize> {
        const ONES: u64 = 0x0101_0101_0101_0101;
        const HIGH: u64 = 0x8080_8080_8080_8080;
        debug_assert_eq!(chunk & HIGH, 0, "ASCII bytes only");
        let mut hits = 0;
        for &(lo, hi) in &self.ranges[..self.count as usize] {
            let at_least_lo = chunk + ONES * (0x80 - lo as u64);
            let above_hi = chunk + ONES * (0x7F - hi as u64);
            hits |= at_least_lo & !above_hi;
        }
        let hits = hits & HIGH;
        (hits != 0).then(|| hits.trailing_zeros() as usize / 8)
    }
}

/// Set in a guard's `skipped_retries` when the backtracks it skips depend on
/// position checks on its main path (anchors, word boundaries, fused
/// look-behinds); the other bits then hold the largest count. Such a guard
/// jumps only where an upper bound of the count is good enough (see
/// `guard_may_jump` in `regexec.rs`), and pushes like the unguarded
/// instruction otherwise.
pub(crate) const GUARD_RETRIES_BY_CHECKS: u32 = 1 << 31;

// === Optimization data structures ===
pub const OPT_EXACT_MAXLEN: usize = 24;

#[derive(Clone, Copy, Default)]
pub struct MinMaxLen {
    pub min: OnigLen,
    pub max: OnigLen,
}

impl MinMaxLen {
    pub fn new() -> Self {
        MinMaxLen { min: 0, max: 0 }
    }

    pub fn clear(&mut self) {
        self.min = 0;
        self.max = 0;
    }

    pub fn set(&mut self, min: OnigLen, max: OnigLen) {
        self.min = min;
        self.max = max;
    }

    pub fn add(&mut self, other: &MinMaxLen) {
        self.min = crate::regcomp::distance_add(self.min, other.min);
        self.max = crate::regcomp::distance_add(self.max, other.max);
    }

    pub fn alt_merge(&mut self, other: &MinMaxLen) {
        if self.min > other.min {
            self.min = other.min;
        }
        if self.max < other.max {
            self.max = other.max;
        }
    }

    pub fn is_equal(&self, other: &MinMaxLen) -> bool {
        self.min == other.min && self.max == other.max
    }
}

#[derive(Clone, Copy, Default)]
pub struct OptAnc {
    pub left: i32,
    pub right: i32,
}

impl OptAnc {
    pub fn new() -> Self {
        OptAnc { left: 0, right: 0 }
    }

    pub fn clear(&mut self) {
        self.left = 0;
        self.right = 0;
    }
}

#[derive(Clone, Copy, Default)]
pub struct OptStr {
    pub mm: MinMaxLen,
    pub anc: OptAnc,
    pub reach_end: i32,
    pub len: usize,
    pub s: [u8; OPT_EXACT_MAXLEN],
}

impl OptStr {
    pub fn new() -> Self {
        OptStr {
            mm: MinMaxLen::new(),
            anc: OptAnc::new(),
            reach_end: 0,
            len: 0,
            s: [0u8; OPT_EXACT_MAXLEN],
        }
    }

    pub fn clear(&mut self) {
        self.mm.clear();
        self.anc.clear();
        self.reach_end = 0;
        self.len = 0;
        self.s[0] = 0;
    }

    pub fn is_full(&self) -> bool {
        self.len >= OPT_EXACT_MAXLEN
    }
}

#[derive(Clone, Copy)]
pub struct OptMap {
    pub mm: MinMaxLen,
    pub anc: OptAnc,
    pub value: i32,
    pub map: [u8; CHAR_MAP_SIZE],
}

impl OptMap {
    pub fn new() -> Self {
        OptMap {
            mm: MinMaxLen::new(),
            anc: OptAnc::new(),
            value: 0,
            map: [0u8; CHAR_MAP_SIZE],
        }
    }

    pub fn clear(&mut self) {
        self.mm.clear();
        self.anc.clear();
        self.value = 0;
        self.map = [0u8; CHAR_MAP_SIZE];
    }
}

impl Default for OptMap {
    fn default() -> Self {
        Self {
            mm: MinMaxLen::default(),
            anc: OptAnc::default(),
            value: 0,
            map: [0u8; CHAR_MAP_SIZE],
        }
    }
}

#[derive(Clone)]
pub struct OptNode {
    pub len: MinMaxLen,
    pub anc: OptAnc,
    pub sb: OptStr,
    pub sm: OptStr,
    pub spr: OptStr,
    pub map: OptMap,
}

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

impl OptNode {
    pub fn new() -> Self {
        OptNode {
            len: MinMaxLen::new(),
            anc: OptAnc::new(),
            sb: OptStr::new(),
            sm: OptStr::new(),
            spr: OptStr::new(),
            map: OptMap::new(),
        }
    }

    pub fn clear(&mut self) {
        self.len.clear();
        self.anc.clear();
        self.sb.clear();
        self.sm.clear();
        self.spr.clear();
        self.map.clear();
    }
}

// === Option check macros as functions ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_ignorecase(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_IGNORECASE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_extend(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_EXTEND)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_multiline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_MULTILINE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_singleline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_SINGLELINE)
}

#[inline]
pub fn opton_find_longest(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_FIND_LONGEST)
}

#[inline]
pub fn opton_find_not_empty(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_FIND_NOT_EMPTY)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_negate_singleline(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NEGATE_SINGLELINE)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_dont_capture_group(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_DONT_CAPTURE_GROUP)
}

#[inline]
pub fn opton_capture_group(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CAPTURE_GROUP)
}

#[inline]
pub fn opton_notbol(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOTBOL)
}

#[inline]
pub fn opton_noteol(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOTEOL)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_posix_region(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_POSIX_REGION)
}

#[inline]
pub fn opton_check_validity_of_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CHECK_VALIDITY_OF_STRING)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_callback_each_match(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_CALLBACK_EACH_MATCH)
}

#[inline]
pub fn opton_not_begin_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_BEGIN_STRING)
}

#[inline]
pub fn opton_not_end_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_END_STRING)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn opton_not_begin_position(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_NOT_BEGIN_POSITION)
}

#[inline]
pub fn opton_match_whole_string(option: OnigOptionType) -> bool {
    option.contains(ONIG_OPTION_MATCH_WHOLE_STRING)
}

// === Syntax macros ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_esc(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.esc
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anychar(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anychar
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anytime(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anytime
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_zero_or_one_time(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.zero_or_one_time
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_one_or_more_time(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.one_or_more_time
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn mc_anychar_anytime(syn: &OnigSyntaxType) -> OnigCodePoint {
    syn.meta_char_table.anychar_anytime
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_mc_esc_code(code: OnigCodePoint, syn: &OnigSyntaxType) -> bool {
    code == mc_esc(syn) && !is_syntax_op2(syn, ONIG_SYN_OP2_INEFFECTIVE_ESCAPE)
}

// === Value helpers ===
#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn digitval(code: OnigCodePoint) -> u32 {
    code - b'0' as u32
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn odigitval(code: OnigCodePoint) -> u32 {
    digitval(code)
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_code_word_ascii(code: OnigCodePoint) -> bool {
    code < 128
}

#[inline]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn is_code_digit_ascii(code: OnigCodePoint) -> bool {
    code < 128 && (code >= b'0' as u32 && code <= b'9' as u32)
}