ved 0.3.0

The verbose ed — an ed clone with friendly errors and a built-in help system
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
// ved's BRE engine — compiled, with capturing groups and
// backreferences.
//
// Step 1 was a direct port of Pike's recursive matcher: three
// functions, no compile step, the pattern itself is the program.
// That original is preserved in git history (commit c53f626).
//
// Step 2 introduced a compile step (closer to Ken Thompson's
// original ed) and bracket expressions ([abc], [^abc], [a-z]).
//
// Step 3 wrapped the compiled form in a Regex struct, returning
// match positions via a Match struct.
//
// Step 4 added capturing groups: \(...\) in BRE syntax. The
// compiler emits GroupStart/GroupEnd markers, and a small Caps
// struct threads through the recursion by value so that failed
// branches automatically discard partial captures.
//
// Step 5 added backreferences: \1-\9 in the pattern replay
// whatever the corresponding group captured. The match functions
// now receive full_text so backreferences can look up captured
// substrings from earlier in the input.
//
// Known limitation: \(...\)* (star applied to a whole group) is
// not yet supported. Star can only apply to a single atom. This
// is uncommon in ed usage and can be added later if needed.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)

/// One matchable thing: a literal byte, any-character wildcard, or
/// a bracket character class.
///
/// `Literal` matches exactly one byte — correct for both ASCII and
/// multi-byte UTF-8, since a multi-byte pattern character compiles
/// to one `Literal` per byte, consumed in lockstep with the matching
/// bytes in the text. `Dot` and `Class` are the two atoms that used
/// to assume one byte was one character; they now consume a whole
/// UTF-8 sequence (see `atom_width`).
#[derive(Debug)]
enum Atom {
    Literal(u8),
    Dot,
    Class {
        negated: bool,
        members: Vec<Vec<u8>>,
    },
}

/// The number of bytes in the UTF-8 sequence led by `byte`. Falls
/// back to 1 for a continuation byte or any other value that isn't a
/// valid lead byte. Text from a buffer line is always valid UTF-8
/// and every caller here only ever asks this of a byte that's
/// already at a character boundary, so the fallback is defensive
/// rather than a case that's expected to fire.
fn utf8_len(byte: u8) -> usize {
    match byte {
        0x00..=0x7F => 1,
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF7 => 4,
        _ => 1,
    }
}

/// The byte-width of the character at the front of `text`, or 0 if
/// `text` is empty. Exposed for callers outside this module that
/// need to step over one whole character in text they already know
/// is valid UTF-8 — `run_substitute`'s global substitute has to
/// advance this way over a zero-width match (from a pattern like
/// `x*` or `.*` that can match nothing), and stepping a raw byte
/// there would reopen the same character-splitting bug this module
/// closes internally.
pub fn char_width(text: &[u8]) -> usize {
    if text.is_empty() {
        0
    } else {
        utf8_len(text[0]).min(text.len())
    }
}

/// One element of a compiled pattern.
#[derive(Debug)]
enum Element {
    One(Atom),
    Star(Atom),
    Caret,
    Dollar,
    GroupStart(usize),
    GroupEnd(usize),
    BackRef(usize),
}

/// The number of capturing groups a BRE can address, as \1-\9.
const NGROUPS: usize = 9;

/// Capture state for up to 9 groups, threaded through matching
/// by value. Small enough to copy on every recursive call (9
/// usizes + 9 usizes + 9 bools = ~153 bytes).
#[derive(Debug, Clone, Copy)]
struct Caps {
    start: [usize; NGROUPS],
    end: [usize; NGROUPS],
    valid: [bool; NGROUPS],
}

impl Caps {
    fn new() -> Self {
        Caps {
            start: [0; NGROUPS],
            end: [0; NGROUPS],
            valid: [false; NGROUPS],
        }
    }
}

/// A compiled BRE pattern, ready for matching.
#[derive(Debug)]
pub struct Regex {
    elements: Vec<Element>,
}

/// The result of a successful match: byte offsets into the text,
/// plus any captured groups.
#[derive(Debug)]
pub struct Match {
    pub start: usize,
    pub end: usize,
    caps: Caps,
}

impl Match {
    /// Get the byte range of capturing group `n` (1-9).
    /// Returns None if the group wasn't part of the pattern or
    /// didn't participate in the match.
    pub fn group(&self, n: usize) -> Option<(usize, usize)> {
        if (1..=NGROUPS).contains(&n) && self.caps.valid[n - 1] {
            Some((self.caps.start[n - 1], self.caps.end[n - 1]))
        } else {
            None
        }
    }
}

// ── Compiler ─────────────────────────────────────────────────

impl Regex {
    /// Compile a BRE pattern from raw bytes.
    pub fn compile(pattern: &[u8]) -> Regex {
        let mut elements = Vec::new();
        let mut i = 0;
        let mut group_num: usize = 0;
        let mut group_stack: Vec<usize> = Vec::new();

        // ^ only anchors at the very start of the pattern.
        if i < pattern.len() && pattern[i] == b'^' {
            elements.push(Element::Caret);
            i += 1;
        }

        while i < pattern.len() {
            // $ only anchors at the very end of the pattern.
            if pattern[i] == b'$' && i + 1 == pattern.len() {
                elements.push(Element::Dollar);
                i += 1;
                continue;
            }

            // Backslash sequences: \( \) for groups, \1-\9 for
            // backreferences, \0NN for octal byte literal, \X for
            // literal X.
            if pattern[i] == b'\\' && i + 1 < pattern.len() {
                // \0NN — 3-digit octal byte literal. Leading 0 only
                // (so \1..\9 stay reserved for backreferences). Two
                // octal digits after the leading zero cover 0-077.
                if pattern[i + 1] == b'0'
                    && i + 4 <= pattern.len()
                    && (b'0'..=b'7').contains(&pattern[i + 2])
                    && (b'0'..=b'7').contains(&pattern[i + 3])
                {
                    let byte = (pattern[i + 2] - b'0') * 8 + (pattern[i + 3] - b'0');
                    let atom = Atom::Literal(byte);
                    i += 4;
                    if i < pattern.len() && pattern[i] == b'*' {
                        elements.push(Element::Star(atom));
                        i += 1;
                    } else {
                        elements.push(Element::One(atom));
                    }
                    continue;
                }
                match pattern[i + 1] {
                    b'(' => {
                        group_num += 1;
                        group_stack.push(group_num);
                        elements.push(Element::GroupStart(group_num));
                        i += 2;
                        continue;
                    }
                    b')' => {
                        if let Some(n) = group_stack.pop() {
                            elements.push(Element::GroupEnd(n));
                        }
                        i += 2;
                        continue;
                    }
                    c @ b'1'..=b'9' => {
                        let n = (c - b'0') as usize;
                        elements.push(Element::BackRef(n));
                        i += 2;
                        continue;
                    }
                    c => {
                        // \X is literal X (handles \., \*, \[, \\, etc.)
                        let atom = Atom::Literal(c);
                        i += 2;
                        if i < pattern.len() && pattern[i] == b'*' {
                            elements.push(Element::Star(atom));
                            i += 1;
                        } else {
                            elements.push(Element::One(atom));
                        }
                        continue;
                    }
                }
            }

            // Parse one atom.
            let (atom, next) = parse_atom(pattern, i);
            i = next;

            // If followed by *, wrap in Star; otherwise One.
            if i < pattern.len() && pattern[i] == b'*' {
                elements.push(Element::Star(atom));
                i += 1;
            } else {
                elements.push(Element::One(atom));
            }
        }

        Regex { elements }
    }

    // ── Matcher ──────────────────────────────────────────────

    /// Search for this pattern anywhere in `text`. Returns the
    /// position of the first match, or None.
    ///
    /// The search only tries starting offsets on a UTF-8 character
    /// boundary. `.` and bracket atoms are width-aware once a match
    /// attempt is under way, but that alone isn't enough: a failed
    /// attempt starting at a real character boundary can still fail
    /// deep enough into the pattern that, without this, the next
    /// byte tried would land mid-character — and Dot's fallback for
    /// a non-lead byte (see `utf8_len`) would then happily accept
    /// it, returning a match that starts or ends mid-character after
    /// all. Skipping straight to the next boundary closes that.
    pub fn find(&self, text: &[u8]) -> Option<Match> {
        let elements = &self.elements;
        let anchored = !elements.is_empty() && matches!(elements[0], Element::Caret);
        let elems = if anchored { &elements[1..] } else { elements };

        let mut offset = 0;
        loop {
            let caps = Caps::new();
            if let Some((len, caps)) = self.match_here(elems, &text[offset..], offset, caps, text) {
                return Some(Match {
                    start: offset,
                    end: offset + len,
                    caps,
                });
            }
            if anchored || offset >= text.len() {
                return None;
            }
            offset += utf8_len(text[offset]).min(text.len() - offset);
        }
    }

    /// Try to match `elements` at the beginning of `text`.
    /// `pos` is the absolute offset in the original text (needed
    /// for recording group boundaries). `full_text` is the
    /// complete original input (needed for backreference lookups).
    /// Returns the number of bytes consumed and the capture state
    /// on success.
    fn match_here(
        &self,
        elements: &[Element],
        text: &[u8],
        pos: usize,
        caps: Caps,
        full_text: &[u8],
    ) -> Option<(usize, Caps)> {
        if elements.is_empty() {
            return Some((0, caps));
        }
        match &elements[0] {
            Element::Dollar => {
                if text.is_empty() {
                    Some((0, caps))
                } else {
                    None
                }
            }
            Element::Caret => None,
            Element::GroupStart(n) => {
                let mut caps = caps;
                // Only \1-\9 are addressable, so Caps has nine slots.
                // A tenth group still delimits, it just isn't recorded.
                if *n <= NGROUPS {
                    caps.start[n - 1] = pos;
                }
                self.match_here(&elements[1..], text, pos, caps, full_text)
            }
            Element::GroupEnd(n) => {
                let mut caps = caps;
                if *n <= NGROUPS {
                    caps.end[n - 1] = pos;
                    caps.valid[n - 1] = true;
                }
                self.match_here(&elements[1..], text, pos, caps, full_text)
            }
            Element::BackRef(n) => {
                if !caps.valid[n - 1] {
                    return None;
                }
                let captured = &full_text[caps.start[n - 1]..caps.end[n - 1]];
                if text.starts_with(captured) {
                    let clen = captured.len();
                    self.match_here(&elements[1..], &text[clen..], pos + clen, caps, full_text)
                        .map(|(len, caps)| (len + clen, caps))
                } else {
                    None
                }
            }
            Element::Star(atom) => {
                self.match_star(atom, &elements[1..], text, pos, caps, full_text)
            }
            Element::One(atom) => match atom_width(atom, text) {
                Some(w) => self
                    .match_here(&elements[1..], &text[w..], pos + w, caps, full_text)
                    .map(|(len, caps)| (len + w, caps)),
                None => None,
            },
        }
    }

    /// POSIX BRE leftmost-longest semantics: consume as many
    /// `atom` matches (repetitions) as possible, then back off one
    /// repetition at a time until the remaining elements match.
    /// Backing off by a whole repetition rather than a byte matters
    /// once `atom` can be more than one byte wide (`.` or a bracket
    /// expression over a multi-byte character) — dropping a single
    /// byte would leave the next attempt starting mid-character.
    /// Returns total bytes consumed and captures on success.
    fn match_star(
        &self,
        atom: &Atom,
        elements: &[Element],
        text: &[u8],
        pos: usize,
        caps: Caps,
        full_text: &[u8],
    ) -> Option<(usize, Caps)> {
        // offsets[k] = bytes consumed by k repetitions of `atom`.
        let mut offsets = vec![0];
        let mut total = 0;
        while let Some(w) = atom_width(atom, &text[total..]) {
            total += w;
            offsets.push(total);
        }
        for &max in offsets.iter().rev() {
            if let Some((len, caps)) =
                self.match_here(elements, &text[max..], pos + max, caps, full_text)
            {
                return Some((max + len, caps));
            }
        }
        None
    }
}

/// Parse one atom starting at position `i` in the pattern.
/// Returns the atom and the index just past it.
fn parse_atom(pattern: &[u8], i: usize) -> (Atom, usize) {
    match pattern[i] {
        b'.' => (Atom::Dot, i + 1),
        b'[' => parse_bracket(pattern, i),
        c => (Atom::Literal(c), i + 1),
    }
}

/// Parse a bracket expression starting at the `[` at position
/// `start`. Returns a Class atom with the fully expanded member
/// list and the index just past the closing `]`.
///
/// Follows POSIX BRE bracket rules:
///   - `]` as the first character (after optional `^`) is literal
///   - `-` at the start or end is literal, not a range
///   - `a-z` in the middle is a range, expanded inline
///   - `[^...]` negates the class
///
/// A member can be a multi-byte UTF-8 character (`[é]`), taken
/// verbatim from the pattern bytes. A `lo-hi` range only expands
/// when both endpoints are single-byte, since a byte-value range
/// over multi-byte characters (`[à-ÿ]`) is a locale-collation
/// question this engine doesn't take on; a multi-byte endpoint falls
/// through to being parsed as its own literal member instead, with
/// the `-` as another literal member.
fn parse_bracket(pattern: &[u8], start: usize) -> (Atom, usize) {
    let mut i = start + 1; // skip '['

    let negated = if i < pattern.len() && pattern[i] == b'^' {
        i += 1;
        true
    } else {
        false
    };

    let mut members: Vec<Vec<u8>> = Vec::new();

    // ] as the very first character (after optional ^) is literal.
    if i < pattern.len() && pattern[i] == b']' {
        members.push(vec![b']']);
        i += 1;
    }

    while i < pattern.len() && pattern[i] != b']' {
        // Range: lo-hi, but only when - is followed by a char that
        // isn't the closing ] and both endpoints are single-byte.
        if utf8_len(pattern[i]) == 1
            && i + 2 < pattern.len()
            && pattern[i + 1] == b'-'
            && pattern[i + 2] != b']'
            && utf8_len(pattern[i + 2]) == 1
        {
            let lo = pattern[i];
            let hi = pattern[i + 2];
            for c in lo..=hi {
                members.push(vec![c]);
            }
            i += 3;
        } else {
            let w = utf8_len(pattern[i]).min(pattern.len() - i);
            members.push(pattern[i..i + w].to_vec());
            i += w;
        }
    }

    // Skip the closing ].
    if i < pattern.len() {
        i += 1;
    }

    (Atom::Class { negated, members }, i)
}

/// Does `atom` match at the front of `text`? Returns the number of
/// bytes consumed on a match, or `None`.
///
/// `Literal` matches its one byte exactly, unchanged from before.
/// `Dot` consumes one whole character. `Class` consumes exactly the
/// matched member's byte length when a member matches; when none
/// does (the case that fires for a negated class), it consumes one
/// whole character, same as `Dot` — "not in this class" means "any
/// other character," not "any other byte."
fn atom_width(atom: &Atom, text: &[u8]) -> Option<usize> {
    if text.is_empty() {
        return None;
    }
    match atom {
        Atom::Literal(c) => (text[0] == *c).then_some(1),
        Atom::Dot => Some(utf8_len(text[0]).min(text.len())),
        Atom::Class { negated, members } => {
            let matched = members
                .iter()
                .find(|m| text.len() >= m.len() && &text[..m.len()] == m.as_slice())
                .map(Vec::len);
            match (*negated, matched) {
                (false, found) => found,
                (true, Some(_)) => None,
                (true, None) => Some(utf8_len(text[0]).min(text.len())),
            }
        }
    }
}

// ── Replacement expansion ────────────────────────────────────

/// Expand a replacement string using match results.
///
/// Handles ed's replacement conventions:
///   - `&` is replaced with the entire matched text
///   - `\1`-`\9` are replaced with captured group contents
///   - `\&` is a literal ampersand
///   - `\\` is a literal backslash
///   - Everything else is literal
pub fn expand_replacement(replacement: &[u8], m: &Match, text: &[u8]) -> Vec<u8> {
    let mut result = Vec::new();
    let mut i = 0;

    while i < replacement.len() {
        match replacement[i] {
            b'&' => {
                result.extend_from_slice(&text[m.start..m.end]);
                i += 1;
            }
            b'\\' if i + 1 < replacement.len() => {
                // \0NN — 3-digit octal byte literal. Same shape as
                // the pattern compiler: leading 0 only, two more
                // octal digits, range 0-077.
                if replacement[i + 1] == b'0'
                    && i + 4 <= replacement.len()
                    && (b'0'..=b'7').contains(&replacement[i + 2])
                    && (b'0'..=b'7').contains(&replacement[i + 3])
                {
                    let byte = (replacement[i + 2] - b'0') * 8 + (replacement[i + 3] - b'0');
                    result.push(byte);
                    i += 4;
                    continue;
                }
                match replacement[i + 1] {
                    b'&' => {
                        result.push(b'&');
                        i += 2;
                    }
                    b'\\' => {
                        result.push(b'\\');
                        i += 2;
                    }
                    c @ b'1'..=b'9' => {
                        let n = (c - b'0') as usize;
                        if let Some((s, e)) = m.group(n) {
                            result.extend_from_slice(&text[s..e]);
                        }
                        i += 2;
                    }
                    _ => {
                        result.push(replacement[i]);
                        i += 1;
                    }
                }
            }
            c => {
                result.push(c);
                i += 1;
            }
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper: compile and check for any match.
    fn has_match(pattern: &[u8], text: &[u8]) -> bool {
        Regex::compile(pattern).find(text).is_some()
    }

    // ── Step 1 tests ─────────────────────────────────────────

    // Literal matching

    #[test]
    fn literal_exact_match() {
        assert!(has_match(b"abc", b"abc"));
    }

    #[test]
    fn literal_match_in_middle() {
        assert!(has_match(b"abc", b"xabcy"));
    }

    #[test]
    fn literal_no_match() {
        assert!(!has_match(b"abc", b"xyz"));
    }

    #[test]
    fn literal_pattern_longer_than_text() {
        assert!(!has_match(b"abc", b"ab"));
    }

    #[test]
    fn empty_pattern_always_matches() {
        assert!(has_match(b"", b"hello"));
    }

    // Dot wildcard

    #[test]
    fn dot_matches_letter() {
        assert!(has_match(b"a.c", b"abc"));
    }

    #[test]
    fn dot_matches_underscore() {
        assert!(has_match(b"a.c", b"a_c"));
    }

    #[test]
    fn dot_requires_a_character() {
        assert!(!has_match(b"a.c", b"ac"));
    }

    // Dot over multi-byte UTF-8 characters (issue #13)

    #[test]
    fn dot_matches_whole_multibyte_character() {
        // "café" is c,a,f,é — the pattern has four atoms, one per
        // character, so it needs "." to consume all of é's two
        // bytes as a single unit, not just the first.
        assert!(has_match(b"caf.", b"caf\xc3\xa9")); // café
        let m = Regex::compile(b"caf.").find(b"caf\xc3\xa9").unwrap();
        assert_eq!(m.end - m.start, 5); // 3 ASCII bytes + 2-byte é
    }

    #[test]
    fn four_dots_span_cafe_but_five_do_not() {
        // "café" (c,a,f,é) is 4 characters / 5 bytes. Four "."
        // atoms should span it exactly; a byte-oriented engine
        // would also accept five, since it has 5 bytes — this is
        // the compatibility gap issue #13 closes.
        assert!(has_match(b"^....$", b"caf\xc3\xa9"));
        assert!(!has_match(b"^.....$", b"caf\xc3\xa9"));
    }

    #[test]
    fn dot_global_style_repetition_over_cafe_yields_four_matches() {
        // Reproduces the ed compatibility check from issue #10: "."
        // must find four matches in café (four characters), not five
        // (its byte count).
        let re = Regex::compile(b".");
        let text = "café".as_bytes();
        let mut pos = 0;
        let mut count = 0;
        while let Some(m) = re.find(&text[pos..]) {
            count += 1;
            pos += m.end.max(1);
        }
        assert_eq!(count, 4);
    }

    // find()'s search offset stays on character boundaries
    // (issue #13: a failed match attempt at a real boundary must not
    // fall through to trying the bytes *inside* that character as
    // their own starting offsets — Dot's byte-width fallback would
    // then accept one, reopening the same character-splitting bug
    // one level up, in the search loop rather than in a single atom.)

    #[test]
    fn failed_match_at_a_character_does_not_search_inside_it() {
        // "€" is 3 bytes (\xe2\x82\xac). "(..)y" can't match starting
        // at "€" (dot,dot lands on 'y' itself, leaving nothing for
        // the literal 'y' to match) — and it must not then be
        // offered the two bytes inside "€" as fallback starting
        // points either.
        let text = "\u{20ac}yq"; // "€yq"
        assert!(!has_match(b"\\(..\\)y", text.as_bytes()));
    }

    #[test]
    fn search_skips_a_whole_failed_character_in_one_hop() {
        // Same shape as above, but with a real match further along:
        // the search has to jump clean over "€" to the next
        // character boundary, not step through its bytes one at a
        // time on the way there.
        let text = "\u{20ac}zzy"; // "€zzy"
        let m = Regex::compile(b"..y").find(text.as_bytes()).unwrap();
        assert_eq!((m.start, m.end), (3, 6)); // "zzy", after the 3-byte €
    }

    // Star repetition

    #[test]
    fn star_zero_matches() {
        assert!(has_match(b"a*b", b"b"));
    }

    #[test]
    fn star_many_matches() {
        assert!(has_match(b"a*b", b"aaab"));
    }

    #[test]
    fn star_combined_with_slide() {
        assert!(has_match(b"a*b", b"xb"));
    }

    #[test]
    fn dot_star_matches_anything() {
        assert!(has_match(b".*", b"anything"));
    }

    // Anchors

    #[test]
    fn caret_anchors_at_start() {
        assert!(has_match(b"^abc", b"abc"));
    }

    #[test]
    fn caret_refuses_to_slide() {
        assert!(!has_match(b"^abc", b"xabc"));
    }

    #[test]
    fn dollar_anchors_at_end() {
        assert!(has_match(b"abc$", b"abc"));
    }

    #[test]
    fn dollar_refuses_tail() {
        assert!(!has_match(b"abc$", b"abcx"));
    }

    #[test]
    fn both_anchors() {
        assert!(has_match(b"^abc$", b"abc"));
    }

    #[test]
    fn empty_anchored_matches_empty() {
        assert!(has_match(b"^$", b""));
    }

    #[test]
    fn empty_anchored_rejects_nonempty() {
        assert!(!has_match(b"^$", b"x"));
    }

    // Tricky edge cases

    #[test]
    fn dollar_alone_finds_end() {
        assert!(has_match(b"$", b"anything"));
    }

    #[test]
    fn anchored_star_on_empty() {
        assert!(has_match(b"^a*$", b""));
    }

    #[test]
    fn anchored_star_many() {
        assert!(has_match(b"^a*$", b"aaa"));
    }

    #[test]
    fn anchored_star_rejects_wrong_char() {
        assert!(!has_match(b"^a*$", b"aab"));
    }

    // ── Step 2 tests: bracket expressions ────────────────────

    // Basic membership

    #[test]
    fn class_matches_member() {
        assert!(has_match(b"[abc]", b"b"));
    }

    #[test]
    fn class_rejects_nonmember() {
        assert!(!has_match(b"[abc]", b"d"));
    }

    #[test]
    fn class_in_context() {
        assert!(has_match(b"x[abc]y", b"xby"));
    }

    // Ranges

    #[test]
    fn range_matches_inside() {
        assert!(has_match(b"[a-z]", b"m"));
    }

    #[test]
    fn range_rejects_outside() {
        assert!(!has_match(b"[a-z]", b"M"));
    }

    #[test]
    fn multiple_ranges() {
        assert!(has_match(b"[a-zA-Z]", b"M"));
    }

    // Negation

    #[test]
    fn negated_class_matches_nonmember() {
        assert!(has_match(b"[^abc]", b"d"));
    }

    #[test]
    fn negated_class_rejects_member() {
        assert!(!has_match(b"^[^abc]$", b"a"));
    }

    #[test]
    fn negated_range_matches_outside() {
        assert!(has_match(b"[^0-9]", b"x"));
    }

    #[test]
    fn negated_range_rejects_inside() {
        assert!(!has_match(b"^[^0-9]$", b"5"));
    }

    // Edge cases: literal ] and -

    #[test]
    fn literal_close_bracket_first() {
        assert!(has_match(b"[]abc]", b"]"));
    }

    #[test]
    fn literal_dash_at_end() {
        assert!(has_match(b"[abc-]", b"-"));
    }

    #[test]
    fn literal_dash_at_start() {
        assert!(has_match(b"[-abc]", b"-"));
    }

    // Multi-byte UTF-8 members in a bracket expression (issue #13)

    #[test]
    fn class_matches_multibyte_member() {
        assert!(has_match("[é]".as_bytes(), "café".as_bytes()));
    }

    #[test]
    fn class_member_match_is_whole_sequence_not_shared_lead_byte() {
        // é (\xc3\xa9) and È (\xc3\x88) share a lead byte but are
        // different characters; a member match has to compare the
        // full sequence, not just that shared first byte.
        assert!(!has_match("[é]".as_bytes(), "È".as_bytes()));
    }

    #[test]
    fn negated_class_over_multibyte_text_consumes_whole_character() {
        // [^x] on café's é must reject by skipping the *whole*
        // 2-byte character, not the "not x" single byte \xc3 with
        // \xa9 left dangling for the next atom to trip over.
        let m = Regex::compile(b"[^x]").find("é".as_bytes()).unwrap();
        assert_eq!((m.start, m.end), (0, 2));
    }

    #[test]
    fn range_endpoint_that_is_multibyte_falls_back_to_literal_members() {
        // "é-z" can't be a byte-value range (é isn't one byte), so
        // é, -, and z are each their own literal member instead of
        // silently doing something byte-value-nonsensical.
        assert!(has_match("[é-z]".as_bytes(), "é".as_bytes()));
        assert!(has_match(b"[\xc3\xa9-z]", b"-"));
        assert!(has_match("[é-z]".as_bytes(), b"z"));
        assert!(!has_match("[é-z]".as_bytes(), b"m"));
    }

    // Bracket + star

    #[test]
    fn class_star_zero() {
        assert!(has_match(b"^[a-z]*$", b""));
    }

    #[test]
    fn class_star_many() {
        assert!(has_match(b"^[a-z]*$", b"hello"));
    }

    #[test]
    fn class_star_rejects() {
        assert!(!has_match(b"^[a-z]*$", b"hello!"));
    }

    #[test]
    fn one_or_more_digits() {
        assert!(has_match(b"[0-9][0-9]*", b"abc123def"));
    }

    // ── Step 3 tests: match positions ────────────────────────

    #[test]
    fn position_at_start() {
        let m = Regex::compile(b"abc").find(b"abcdef").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 3);
    }

    #[test]
    fn position_in_middle() {
        let m = Regex::compile(b"abc").find(b"xabcy").unwrap();
        assert_eq!(m.start, 1);
        assert_eq!(m.end, 4);
    }

    #[test]
    fn position_dot_star() {
        let m = Regex::compile(b".*").find(b"hello").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 5);
    }

    #[test]
    fn position_anchored_dot_star() {
        let m = Regex::compile(b"^.*$").find(b"hello").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 5);
    }

    #[test]
    fn position_digits() {
        let m = Regex::compile(b"[0-9][0-9]*").find(b"abc123def").unwrap();
        assert_eq!(m.start, 3);
        assert_eq!(m.end, 6);
    }

    // ── Greedy star (leftmost-longest) ───────────────────────

    #[test]
    fn star_is_greedy_unanchored() {
        let m = Regex::compile(b"a*").find(b"aaa").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 3);
    }

    #[test]
    fn star_backs_off_for_trailing_atom() {
        // .* must back off so the trailing 'c' can match
        let m = Regex::compile(b".*c").find(b"abcabc").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 6);
    }

    #[test]
    fn star_greedy_with_class() {
        let m = Regex::compile(b"[0-9]*").find(b"123abc").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 3);
    }

    #[test]
    fn star_followed_by_literal_backs_off() {
        // a*ab needs star to give up one 'a' so the literal 'a' can match
        let m = Regex::compile(b"a*ab").find(b"aaab").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 4);
    }

    #[test]
    fn position_no_match() {
        assert!(Regex::compile(b"xyz").find(b"hello").is_none());
    }

    #[test]
    fn position_empty_match() {
        let m = Regex::compile(b"").find(b"hello").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 0);
    }

    #[test]
    fn position_dollar() {
        let m = Regex::compile(b"abc$").find(b"xabc").unwrap();
        assert_eq!(m.start, 1);
        assert_eq!(m.end, 4);
    }

    // ── Step 4 tests: capturing groups ───────────────────────

    #[test]
    fn group_simple() {
        let m = Regex::compile(b"^\\(abc\\)$").find(b"abc").unwrap();
        assert_eq!(m.start, 0);
        assert_eq!(m.end, 3);
        assert_eq!(m.group(1), Some((0, 3)));
    }

    #[test]
    fn group_in_context() {
        let m = Regex::compile(b"^x\\(abc\\)y$").find(b"xabcy").unwrap();
        assert_eq!(m.group(1), Some((1, 4)));
    }

    #[test]
    fn group_two_groups() {
        let m = Regex::compile(b"^\\(ab\\)\\(cd\\)$").find(b"abcd").unwrap();
        assert_eq!(m.group(1), Some((0, 2)));
        assert_eq!(m.group(2), Some((2, 4)));
    }

    #[test]
    fn group_nested() {
        let m = Regex::compile(b"^\\(\\(ab\\)cd\\)$").find(b"abcd").unwrap();
        assert_eq!(m.group(1), Some((0, 4)));
        assert_eq!(m.group(2), Some((0, 2)));
    }

    #[test]
    fn group_with_dot() {
        let m = Regex::compile(b"^\\(.\\)$").find(b"x").unwrap();
        assert_eq!(m.group(1), Some((0, 1)));
    }

    #[test]
    fn group_with_class() {
        let m = Regex::compile(b"^\\([a-z][a-z]*\\)$")
            .find(b"hello")
            .unwrap();
        assert_eq!(m.group(1), Some((0, 5)));
    }

    #[test]
    fn group_no_match_returns_none() {
        assert!(Regex::compile(b"\\(abc\\)").find(b"xyz").is_none());
    }

    #[test]
    fn group_uncaptured_returns_none() {
        let m = Regex::compile(b"^\\(abc\\)$").find(b"abc").unwrap();
        assert_eq!(m.group(2), None);
    }

    #[test]
    fn group_zero_returns_none() {
        let m = Regex::compile(b"^\\(abc\\)$").find(b"abc").unwrap();
        assert_eq!(m.group(0), None);
    }

    #[test]
    fn group_ten_returns_none() {
        let m = Regex::compile(b"^\\(abc\\)$").find(b"abc").unwrap();
        assert_eq!(m.group(10), None);
    }

    // Backslash escaping

    #[test]
    fn escaped_dot_is_literal() {
        assert!(has_match(b"a\\.c", b"a.c"));
        assert!(!has_match(b"a\\.c", b"abc"));
    }

    #[test]
    fn escaped_star_is_literal() {
        assert!(has_match(b"a\\*", b"a*"));
        assert!(!has_match(b"a\\*", b"aaa"));
    }

    #[test]
    fn escaped_backslash_is_literal() {
        assert!(has_match(b"a\\\\b", b"a\\b"));
    }

    // ── Step 5 tests: backreferences ─────────────────────────

    #[test]
    fn backref_simple() {
        // \(abc\)\1 matches "abcabc"
        assert!(has_match(b"^\\(abc\\)\\1$", b"abcabc"));
    }

    #[test]
    fn backref_rejects_mismatch() {
        assert!(!has_match(b"^\\(abc\\)\\1$", b"abcdef"));
    }

    #[test]
    fn backref_with_dot() {
        // \(.\)\1 matches any repeated character
        assert!(has_match(b"^\\(.\\)\\1$", b"aa"));
        assert!(!has_match(b"^\\(.\\)\\1$", b"ab"));
    }

    #[test]
    fn backref_two_groups() {
        // \(a\)\(b\)\2\1 matches "abba"
        let m = Regex::compile(b"^\\(a\\)\\(b\\)\\2\\1$")
            .find(b"abba")
            .unwrap();
        assert_eq!(m.group(1), Some((0, 1)));
        assert_eq!(m.group(2), Some((1, 2)));
    }

    #[test]
    fn backref_to_uncaptured_fails() {
        // \1 with no group should fail to match
        assert!(!has_match(b"^\\1$", b"anything"));
    }

    #[test]
    fn backref_multi_char() {
        // \(hello\).*\1 matches "hello world hello"
        assert!(has_match(b"^\\(hello\\).*\\1$", b"hello world hello"));
    }

    #[test]
    fn backref_multi_char_rejects() {
        assert!(!has_match(b"^\\(hello\\).*\\1$", b"hello world help"));
    }

    #[test]
    fn backref_with_class() {
        // \([a-z]\)\1 finds a repeated lowercase letter
        assert!(has_match(b"\\([a-z]\\)\\1", b"xaabbx"));
        assert!(!has_match(b"^\\([a-z]\\)\\1$", b"ab"));
    }

    // ── Replacement expansion tests ──────────────────────────

    #[test]
    fn replace_literal() {
        let text = b"hello world";
        let m = Regex::compile(b"world").find(text).unwrap();
        assert_eq!(expand_replacement(b"earth", &m, text), b"earth");
    }

    #[test]
    fn replace_ampersand_whole_match() {
        let text = b"hello world";
        let m = Regex::compile(b"world").find(text).unwrap();
        assert_eq!(expand_replacement(b"[&]", &m, text), b"[world]");
    }

    #[test]
    fn replace_escaped_ampersand() {
        let text = b"hello";
        let m = Regex::compile(b"hello").find(text).unwrap();
        assert_eq!(expand_replacement(b"\\&", &m, text), b"&");
    }

    #[test]
    fn replace_backref_group() {
        let text = b"abcd";
        let m = Regex::compile(b"^\\(ab\\)\\(cd\\)$").find(text).unwrap();
        assert_eq!(expand_replacement(b"\\2-\\1", &m, text), b"cd-ab");
    }

    #[test]
    fn replace_backref_uncaptured_vanishes() {
        let text = b"abc";
        let m = Regex::compile(b"^\\(abc\\)$").find(text).unwrap();
        // \2 was never captured, so it expands to nothing
        assert_eq!(expand_replacement(b"\\1-\\2", &m, text), b"abc-");
    }

    #[test]
    fn replace_escaped_backslash() {
        let text = b"hello";
        let m = Regex::compile(b"hello").find(text).unwrap();
        assert_eq!(expand_replacement(b"a\\\\b", &m, text), b"a\\b");
    }

    #[test]
    fn replace_ampersand_with_groups() {
        let text = b"xabcy";
        let m = Regex::compile(b"x\\(abc\\)y").find(text).unwrap();
        // & is the whole match "xabcy", \1 is just "abc"
        assert_eq!(expand_replacement(b"&-\\1", &m, text), b"xabcy-abc");
    }

    // ── \NNN octal byte escapes ──────────────────────────────

    #[test]
    fn octal_escape_matches_us_separator() {
        // \037 = 0x1F (US, ASCII unit separator)
        assert!(has_match(b"\\037", b"a\x1fb"));
        assert!(!has_match(b"\\037", b"abc"));
    }

    #[test]
    fn octal_escape_matches_tab() {
        // \011 = 0x09 (TAB)
        assert!(has_match(b"a\\011b", b"a\tb"));
    }

    #[test]
    fn octal_escape_with_star() {
        // \040 = space; one or more spaces
        assert!(has_match(b"a\\040*b", b"a   b"));
        assert!(has_match(b"a\\040*b", b"ab"));
    }

    #[test]
    fn octal_escape_zero_byte() {
        // \000 = NUL
        assert!(has_match(b"\\000", b"x\0y"));
    }

    #[test]
    fn octal_escape_malformed_still_literal_zero() {
        // \0 with non-octal trailing falls back to literal '0'.
        assert!(has_match(b"\\0x", b"0x"));
    }

    #[test]
    fn backref_still_works_after_octal_added() {
        // Regression: \1 must remain a backreference, not be
        // re-interpreted as start of an octal.
        assert!(has_match(b"^\\(ab\\)\\1$", b"abab"));
    }

    #[test]
    fn replace_octal_escape_inserts_byte() {
        let text = b"foo bar";
        let m = Regex::compile(b" ").find(text).unwrap();
        // \037 = 0x1F (US)
        assert_eq!(expand_replacement(b"\\037", &m, text), b"\x1f");
    }

    #[test]
    fn replace_octal_among_other_specials() {
        let text = b"foo bar";
        let m = Regex::compile(b"foo \\(bar\\)").find(text).unwrap();
        // & captures "foo bar"; \037 inserts US; \1 inserts "bar"
        assert_eq!(
            expand_replacement(b"&\\037\\1", &m, text),
            b"foo bar\x1fbar"
        );
    }

    // ── more groups than there are slots ─────────────────────

    #[test]
    fn tenth_group_delimits_without_being_recorded() {
        // Only \\1-\\9 are addressable. A tenth group must still take
        // part in the match rather than panicking on Caps' ninth slot.
        let text = b"abcdefghij";
        let pat = b"\\(a\\)\\(b\\)\\(c\\)\\(d\\)\\(e\\)\\(f\\)\\(g\\)\\(h\\)\\(i\\)\\(j\\)";
        let m = Regex::compile(pat)
            .find(text)
            .expect("pattern should match");
        assert_eq!((m.start, m.end), (0, 10));
        assert_eq!(m.group(9), Some((8, 9)));
        assert_eq!(m.group(10), None);
    }

    #[test]
    fn many_groups_do_not_panic() {
        let text = b"aaaaaaaaaaaaaaa";
        let pat = b"\\(a\\)".repeat(15);
        assert!(Regex::compile(&pat).find(text).is_some());
    }
}