elisprs 0.1.20

Emacs Lisp as a fusevm frontend: a reader and compiler to fusevm::Chunk on an ElispHost object heap, with no bespoke VM or JIT
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
//! Emacs-Lisp regexp → `regex` crate translation.
//!
//! Emacs regexps invert the convention of POSIX-ERE / PCRE engines: grouping,
//! alternation and bounded repetition are spelled with a leading backslash
//! (`\(`, `\|`, `\{`), while the bare characters `(` `)` `|` `{` `}` are
//! literals. The `regex` crate is the opposite. This module walks an elisp
//! pattern and emits an equivalent pattern in the crate's dialect so the engine
//! can be reused wholesale instead of writing a matcher by hand.
//!
//! Coverage is the common, portable subset of elisp regexp syntax: grouping
//! (incl. shy `\(?:` and explicitly-numbered `\(?N:`), alternation, bounded
//! repeats (with Emacs's collapsing of postfix runs), anchors (`\``, `\'`, `\<`, `\>`,
//! `\_<`, `\_>`, context-dependent `^`/`$`, `\=` as point), word/symbol/whitespace
//! escapes (`\w \W \b \B \s- \sw`), character alternatives `[...]`, and
//! backreferences `\1`..`\9`.
//!
//! The last two are NOT pass-throughs, though they look like ones. A `\`, a `[`
//! and a non-terminating `]` are ordinary members in an elisp alternative and
//! metacharacters to the crate; a `[:NAME:]` class is recognized on Emacs's
//! terms (`re_wctype_parse`) rather than by scanning to the next `]`; and a
//! backreference names an EMACS group number, which under explicit numbering is
//! not the position fancy-regex would give it. Emacs also validates `\N` while
//! reading the pattern, so an out-of-range or self-referential one has to be
//! diagnosed here and not left to the engine.

/// Translate an Emacs regexp string into the `regex` crate's syntax.
///
/// The translator also *diagnoses* — with Emacs's own wording (`regex-emacs.c`),
/// because the error string is part of the `invalid-regexp` error data that elisp
/// code catches and prints — and *tolerates* what Emacs tolerates. A repetition
/// operator with nothing to repeat is a literal in Emacs (`(string-match "*x" "x")`
/// is 0, not an error), and a reversed range like `[z-a]` simply never matches
/// rather than failing to compile. Both would otherwise surface as a
/// `fancy-regex` parse failure whose message names byte offsets in the
/// *translated* pattern — meaningless to the elisp caller.
/// Resolves a syntax-class designator (`w`, `_`, `<`, …) to the character
/// ranges that carry it, so `\sC` can be compiled against the syntax table in
/// force where the regexp is compiled.
///
/// A trait object rather than a direct host call because this module is a pure
/// translator with no arena access; `crate::builtins::compile_cf` supplies the
/// live table and [`translate`] keeps a no-table path for the unit tests.
pub trait SyntaxLookup {
    /// Ascending, non-overlapping `[lo, hi]` character ranges in class `class`.
    /// An empty result means the class is genuinely empty in this table — `\s!`
    /// with no generic-comment-fence character, say — and `\sC` then matches
    /// nothing, which is not the same as having no table at all.
    fn ranges(&self, class: char) -> Vec<(u32, u32)>;
    /// Ascending, non-overlapping ranges of the characters whose category set
    /// in the current category table contains CATEGORY (`\cC`). Empty without
    /// a table.
    fn category_ranges(&self, _category: u8) -> Vec<(u32, u32)> {
        Vec::new()
    }
    /// Whether a syntax table is reachable. False only for [`NoSyntax`].
    fn available(&self) -> bool {
        true
    }
    /// What `\=` (point) translates to. A buffer search starts its match
    /// attempt at point, which is where fancy-regex's `\G` matches; the host
    /// answers with point itself, which a backward search needs.
    fn at_dot(&self) -> String {
        r"\G".to_string()
    }
}

/// The syntax lookup used when no table is available (the module's own tests).
/// `translate` then falls back to the hardcoded whitespace/word sets it used
/// before syntax tables were consulted.
pub struct NoSyntax;
impl SyntaxLookup for NoSyntax {
    fn ranges(&self, _class: char) -> Vec<(u32, u32)> {
        Vec::new()
    }
    fn available(&self) -> bool {
        false
    }
}

pub fn translate(pat: &str) -> Result<String, String> {
    translate_with(pat, &NoSyntax)
}

/// [`translate`], resolving `\sC` / `\SC` against `syn`.
pub fn translate_with(pat: &str, syn: &dyn SyntaxLookup) -> Result<String, String> {
    translate_groups(pat, syn).map(|(re, _)| re)
}

/// [`translate_with`], additionally reporting how the emitted capture groups map
/// back to the *Emacs* group numbers.
///
/// The two numberings only coincide when the pattern uses nothing but plain
/// `\(`. Emacs's `\(?N:RE\)` names a group explicitly and then continues
/// counting from `N + 1` (`regex-emacs.c` sets `regnum = N`), so
/// `\(?5:a\)\(b\)` has groups 5 and 6 and `(match-data)` reports
/// `(0 2 nil nil nil nil nil nil nil nil 0 1 1 2)`. `fancy_regex` has no
/// explicit-numbering syntax and numbers positionally, so the same pattern
/// compiles to two groups numbered 1 and 2 there.
///
/// The returned vector is that correspondence: element `i` is the Emacs group
/// number of the compiled pattern's group `i + 1`. It is the identity vector
/// `[1, 2, 3, …]` whenever the pattern uses no explicit numbering, which is the
/// case callers can skip the remap for.
pub fn translate_groups(pat: &str, syn: &dyn SyntaxLookup) -> Result<(String, Vec<u32>), String> {
    let mut out = String::with_capacity(pat.len() + 8);
    let mut it = pat.chars().peekable();
    // Depth of open `\(` groups, so a stray `\)` is diagnosed like Emacs's.
    let mut depth: i32 = 0;
    let mut groups = Groups::default();
    // Whether a repetition operator here has something to repeat. False at the
    // start of the pattern and just after `\(` or `\|`, where Emacs reads
    // `*`/`+`/`?` as ordinary characters.
    let mut can_repeat = false;
    // regex-emacs.c's `laststart`: where in OUT the expression a postfix
    // operator applies to begins. A group's starts where its `\(` was emitted.
    let mut laststart: usize = 0;
    let mut group_starts: Vec<usize> = Vec::new();
    // Whether the expression at LASTSTART already carries a repetition. Emacs
    // applies a second operator to the whole repeated expression (`a\{2\}*` is
    // an even number of `a`s), where the crate would reject or misread it.
    let mut repeated = false;
    // `at_begline_loc_p`: a `^` is an anchor only at the start of the pattern
    // and right after `\(`, `\(?:`, `\(?N:` or `\|`; anywhere else it is an
    // ordinary character.
    let mut at_begline = true;
    while let Some(c) = it.next() {
        let tok_start = out.len();
        let begline = std::mem::replace(&mut at_begline, false);
        match c {
            '\\' => {
                let e = it.peek().copied();
                if e == Some('{') {
                    // The interval is read (and diagnosed) before Emacs looks
                    // for something to repeat; with nothing, its `\{` is a
                    // literal `{` (`unfetch_interval`) and the rest is reread.
                    let save = it.clone();
                    let mut scratch = String::new();
                    translate_escape(
                        &mut it,
                        &mut scratch,
                        &mut depth,
                        &mut can_repeat.clone(),
                        syn,
                        &mut groups,
                    )?;
                    if !can_repeat {
                        it = save;
                        it.next();
                        out.push_str(r"\{");
                        can_repeat = true;
                        laststart = tok_start;
                        repeated = false;
                        continue;
                    }
                    if repeated {
                        wrap_group(&mut out, laststart);
                    }
                    out.push_str(&scratch);
                    repeated = true;
                    continue;
                }
                translate_escape(
                    &mut it,
                    &mut out,
                    &mut depth,
                    &mut can_repeat,
                    syn,
                    &mut groups,
                )?;
                match e {
                    Some('(') => {
                        group_starts.push(tok_start);
                        at_begline = true;
                    }
                    Some(')') => {
                        laststart = group_starts.pop().unwrap_or(tok_start);
                        repeated = false;
                    }
                    Some('|') => at_begline = true,
                    _ => {
                        laststart = tok_start;
                        repeated = false;
                    }
                }
            }
            // Literal in elisp, special in the crate → escape.
            '(' | ')' | '{' | '}' | '|' => {
                out.push('\\');
                out.push(c);
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
            // Character alternative: copy through verbatim. Both dialects agree
            // on `[a-z]`, `[^...]`, a leading/`^`-leading `]`, and `[:class:]`.
            '[' => {
                copy_class(&mut it, &mut out, syn)?;
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
            // A run of postfix operators collapses to one, as regex-emacs.c
            // reads it: `*`/`+` allow many, `*`/`?` allow zero, and a `?`
            // after either kind makes the result non-greedy (`a+*` is `a*`,
            // `a*??` is `a*?`).
            '*' | '+' | '?' if can_repeat => {
                let (mut zero, mut many, mut greedy) = (false, false, true);
                let mut op = c;
                loop {
                    if op == '?' && (zero || many) {
                        greedy = false;
                    } else {
                        zero |= op != '+';
                        many |= op != '?';
                    }
                    match it.peek() {
                        Some(&n @ ('*' | '+' | '?')) => {
                            it.next();
                            op = n;
                        }
                        _ => break,
                    }
                }
                if repeated {
                    wrap_group(&mut out, laststart);
                }
                out.push(match (zero, many) {
                    (true, true) => '*',
                    (false, true) => '+',
                    _ => '?',
                });
                if !greedy {
                    out.push('?');
                }
                repeated = true;
            }
            // A repetition operator with no preceding expression is a literal
            // character in Emacs, not an error.
            '*' | '+' | '?' => {
                out.push('\\');
                out.push(c);
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
            // Postfix operators after an anchoring `^` are literals.
            '^' if begline => {
                out.push('^');
                can_repeat = false;
            }
            // `$` anchors only at the end of the pattern or before `\)`/`\|`.
            '$' if {
                let mut ahead = it.clone();
                match ahead.next() {
                    None => true,
                    Some('\\') => matches!(ahead.next(), Some(')' | '|')),
                    Some(_) => false,
                }
            } =>
            {
                out.push('$');
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
            '^' | '$' | '.' => {
                if c == '.' {
                    out.push('.');
                } else {
                    out.push('\\');
                    out.push(c);
                }
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
            // Ordinary chars share meaning across dialects.
            _ => {
                out.push(c);
                can_repeat = true;
                laststart = tok_start;
                repeated = false;
            }
        }
    }
    if depth > 0 {
        return Err(UNMATCHED_OPEN.into());
    }
    Ok((out, groups.emitted))
}

/// Make OUT from START one non-capturing group, so the postfix operator that
/// follows applies to all of it.
fn wrap_group(out: &mut String, start: usize) {
    out.insert_str(start, "(?:");
    out.push(')');
}

/// The capture-group state `regex-emacs.c` keeps while reading a pattern.
#[derive(Default)]
struct Groups {
    /// Emacs's `bufp->re_nsub`: how many groups the reader has opened so far,
    /// which is also the number the next plain `\(` takes. An explicit `\(?N:`
    /// only ever RAISES it (`if (regnum > bufp->re_nsub) bufp->re_nsub =
    /// regnum`), so a later plain `\(` continues from the maximum and not from
    /// N + 1 — `\(a\)\(b\)\(?1:c\)\(d\)` numbers `d` 3, not 2.
    nsub: u32,
    /// The Emacs number each EMITTED capture group carries, in emission order.
    /// This is what [`translate_groups`] returns, and what maps a `\N` onto the
    /// position fancy-regex gave the group.
    emitted: Vec<u32>,
    /// Emacs's compile stack: the groups whose `\)` has not been read yet. A
    /// back reference to one of them is an error even though the number exists,
    /// and a shy group is entered as 0 because no `\N` can ever name it.
    open: Vec<u32>,
}

/// The largest scalar value a Rust `char` can hold. Emacs's character space runs
/// to `#x3FFFFF` (raw bytes and unassigned codepoints live above Unicode), but a
/// `fancy_regex` class can only name real scalar values, so a syntax-class range
/// is clipped here and the surrogate block is stepped over.
const MAX_SCALAR: u32 = 0x10FFFF;

/// A `fancy_regex` character class covering `ranges` (or its complement when
/// `neg`). Empty input yields a class that cannot match — `[^\x{0}-\x{10FFFF}]`
/// for the positive form, `.`-equivalent for the negated one — because a syntax
/// class with no characters must match nothing, not everything.
fn char_class(ranges: &[(u32, u32)], neg: bool) -> String {
    let mut body = ranges_body(ranges);
    if body.is_empty() {
        // No character is in the class.
        body = "\\x{0}-\\x{10FFFF}".to_string();
        return format!("(?-i:[{}{body}])", if neg { "" } else { "^" });
    }
    // `(?-i:…)` because a syntax class is never case-folded. Emacs's matcher asks
    // `SYNTAX (c)` of the character as it stands; `case-fold-search` only folds
    // literal characters. Without the override, `case-fold-search`'s `(?i)`
    // leaked in and `(progn (modify-syntax-entry ?a "_") (string-match "\\sw"
    // "a"))` answered 0 — "a" matching the class's `A-Z` run — where Emacs 30.2
    // answers nil.
    format!("(?-i:[{}{body}])", if neg { "^" } else { "" })
}

/// The `\x{..}` members of a character-class body covering `ranges`, clipped to
/// real scalar values with the surrogate block stepped over.
fn ranges_body(ranges: &[(u32, u32)]) -> String {
    let mut body = String::new();
    for &(lo, hi) in ranges {
        if lo > MAX_SCALAR {
            continue;
        }
        let hi = hi.min(MAX_SCALAR);
        // Split around the surrogate block: D800–DFFF are not scalar values and
        // the regex parser rejects them inside a class.
        for (a, b) in [(lo, hi.min(0xD7FF)), (lo.max(0xE000), hi)] {
            if a > b || a > MAX_SCALAR {
                continue;
            }
            if a == b {
                body.push_str(&format!("\\x{{{a:X}}}"));
            } else {
                body.push_str(&format!("\\x{{{a:X}}}-\\x{{{b:X}}}"));
            }
        }
    }
    body
}

/// Emacs's own `invalid-regexp` messages (`regex-emacs.c`), reproduced verbatim:
/// elisp code catches these and prints the string.
const UNMATCHED_OPEN: &str = "Unmatched ( or \\(";
const UNMATCHED_CLOSE: &str = "Unmatched ) or \\)";
const UNMATCHED_BRACKET: &str = "Unmatched [ or [^";
const UNMATCHED_BRACE: &str = "Unmatched \\{";
const INVALID_BRACE_CONTENT: &str = "Invalid content of \\{\\}";
const TRAILING_BACKSLASH: &str = "Trailing backslash";
/// Emacs's catch-all for a malformed construct it has no specific message for —
/// what `\(?0:…\)` and `\(?a:…\)` report.
const INVALID_REGEXP: &str = "Invalid regular expression";
/// `REG_ESUBREG` — `\N` naming a group that has not been opened, or one whose
/// `\)` has not been reached yet.
const INVALID_BACKREF: &str = "Invalid back reference";
/// `REG_EEND` — what `PATFETCH` reports when the pattern runs out mid-construct.
/// Reachable only from a character alternative's range: `[a-` ends inside the
/// two-character fetch `regex-emacs.c` starts as soon as it sees the `-`.
const PREMATURE_END: &str = "Premature end of regular expression";
/// `REG_ECTYPE` — `[[:NAME:]]` for a NAME `re_wctype` does not know.
const INVALID_CLASS_NAME: &str = "Invalid character class name";
/// A `fancy_regex` construct that matches nothing, for the elisp constructs
/// Emacs compiles but that can never succeed: a reversed range, and a back
/// reference to a register no group ever writes.
pub(crate) const NEVER_MATCHES: &str = "[^\\s\\S]";

/// The character-class names `re_wctype` (`regex-emacs.c`) accepts. Anything
/// else between `[:` and `:]` is `Invalid character class name` — Emacs does not
/// fall back to treating it as ordinary members, and the comparison is exact, so
/// `[[:Alpha:]]` and `[[:alpha :]]` are both rejected.
const CLASS_NAMES: [&str; 17] = [
    "alnum",
    "alpha",
    "ascii",
    "blank",
    "cntrl",
    "digit",
    "graph",
    "lower",
    "multibyte",
    "nonascii",
    "print",
    "punct",
    "space",
    "unibyte",
    "upper",
    "word",
    "xdigit",
];

/// Whether NAME is one of [`CLASS_NAMES`] — shared with `skip-chars-forward`,
/// whose `[:NAME:]` accepts exactly the regexp engine's classes.
pub(crate) fn is_class_name(name: &str) -> bool {
    CLASS_NAMES.contains(&name)
}

fn translate_escape(
    it: &mut std::iter::Peekable<std::str::Chars>,
    out: &mut String,
    depth: &mut i32,
    can_repeat: &mut bool,
    syn: &dyn SyntaxLookup,
    groups: &mut Groups,
) -> Result<(), String> {
    let Some(e) = it.next() else {
        return Err(TRAILING_BACKSLASH.into());
    };
    // Only a group open / alternation leaves nothing to repeat after it.
    *can_repeat = !matches!(e, '(' | '|');
    match e {
        // Grouping / alternation / bounds: drop the backslash.
        '(' => {
            // `\(?…` is either a shy group `\(?:` or an explicitly-numbered group
            // `\(?N:RE\)`. fancy-regex has no explicit-numbering syntax and numbers
            // capture groups positionally, so an explicit group still emits a plain
            // capture — the Emacs number it stands for is recorded in `groups`
            // instead, and the caller remaps the spans after the match.
            if it.peek() == Some(&'?') {
                it.next(); // consume '?'
                if matches!(it.peek(), Some(d) if d.is_ascii_digit()) {
                    // `\(?N:` — read N, drop the digits and the ':', emit a plain
                    // capture, and continue Emacs's counter from N + 1 (regnum = N).
                    let mut n: u32 = 0;
                    while let Some(&d) = it.peek() {
                        if !d.is_ascii_digit() {
                            break;
                        }
                        it.next();
                        // Emacs's `regnum` is a plain int; a number this large
                        // cannot name a real group, and its own reader rejects the
                        // whole construct rather than overflowing.
                        n = n
                            .saturating_mul(10)
                            .saturating_add(d as u32 - '0' as u32)
                            .min(u32::MAX / 16);
                    }
                    // Group 0 is the whole match and cannot be named, and anything
                    // that is not `\(?DIGITS:` is not an explicit group at all —
                    // Emacs rejects both with its generic message.
                    if n == 0 || it.peek() != Some(&':') {
                        return Err(INVALID_REGEXP.into());
                    }
                    it.next(); // consume ':'
                    if n > groups.nsub {
                        groups.nsub = n;
                    }
                    groups.emitted.push(n);
                    groups.open.push(n);
                    out.push('(');
                } else {
                    // Shy group `\(?:`. Emacs's reader accepts exactly two things
                    // after `\(?` — a digit run ending in `:`, handled above, and a
                    // bare `:` — so a `\(?i:…`-style inline flag is not elisp
                    // syntax and must report Emacs's message, not the regex
                    // crate's parse error.
                    if it.peek() != Some(&':') {
                        return Err(INVALID_REGEXP.into());
                    }
                    it.next();
                    out.push_str("(?:");
                    groups.open.push(0);
                }
            } else {
                out.push('(');
                groups.nsub += 1;
                groups.emitted.push(groups.nsub);
                groups.open.push(groups.nsub);
            }
            *depth += 1;
        }
        ')' => {
            if *depth == 0 {
                return Err(UNMATCHED_CLOSE.into());
            }
            *depth -= 1;
            groups.open.pop();
            out.push(')');
        }
        '|' => out.push('|'),
        // `\{m,n\}` — Emacs validates the bounds itself, and its diagnostics are
        // what elisp code sees.
        '{' => {
            // GNU regex reads the interval strictly as digits[,digits] and
            // diagnoses the FIRST wrong thing it sees: a character that can
            // never appear in an interval (including `\X` for X ≠ `}`) is
            // "Invalid content of \{\}" even when the pattern then ends, while
            // running out of pattern with only valid interval content so far is
            // "Unmatched \{" — so `a\{2,` is Unmatched but `a\{x` is Invalid.
            let mut body = String::new();
            let mut closed = false;
            while let Some(c) = it.next() {
                if c == '\\' {
                    match it.next() {
                        Some('}') => {
                            closed = true;
                            break;
                        }
                        Some(_) => return Err(INVALID_BRACE_CONTENT.into()),
                        None => return Err(TRAILING_BACKSLASH.into()),
                    }
                } else if c.is_ascii_digit() || (c == ',' && !body.contains(',')) {
                    body.push(c);
                } else {
                    return Err(INVALID_BRACE_CONTENT.into());
                }
            }
            if !closed {
                return Err(UNMATCHED_BRACE.into());
            }
            if !valid_brace_body(&body) {
                return Err(INVALID_BRACE_CONTENT.into());
            }
            // Emacs allows an empty lower bound (`\{,3\}`, even `\{\}`) meaning
            // 0; the `regex` dialect does not, so make the 0 explicit.
            out.push('{');
            if body.is_empty() || body.starts_with(',') {
                out.push('0');
            }
            out.push_str(&body);
            out.push('}');
        }
        '}' => out.push_str(r"\}"),
        // Anchors.
        '`' => out.push_str(r"\A"),
        '\'' => out.push_str(r"\z"),
        // Word and symbol boundaries. regex-emacs.c decides them by SYNTAX:
        // `\<` / `\>` need a word constituent after / before and none on the
        // other side, `\_<` / `\_>` the same with "word or symbol
        // constituent", and `\b` / `\B` are (not) at either, where the start and
        // end of the subject always count as a boundary. The
        // crate's `\b` uses Unicode `\w`, which counts `_` as a word character
        // and knows nothing of symbol constituents, so `\_<foo\_>` matched
        // inside `foo-bar`. With a syntax table the boundaries become
        // lookarounds over the table's own classes.
        '<' | '>' | 'b' | 'B' if syn.available() => {
            let w = char_class(&syn.ranges('w'), false);
            out.push_str(&match e {
                '<' => format!("(?={w})(?<!{w})"),
                '>' => format!("(?<={w})(?!{w})"),
                'b' => format!(r"(?:\A|\z|(?<={w})(?!{w})|(?<!{w})(?={w}))"),
                _ => format!(r"(?!\A)(?!\z)(?:(?<={w})(?={w})|(?<!{w})(?!{w}))"),
            });
        }
        '_' if syn.available() && matches!(it.peek(), Some('<') | Some('>')) => {
            let mut ranges = syn.ranges('w');
            ranges.extend(syn.ranges('_'));
            let s = char_class(&ranges, false);
            out.push_str(&if it.next() == Some('<') {
                format!("(?={s})(?<!{s})")
            } else {
                format!("(?<={s})(?!{s})")
            });
        }
        '<' | '>' => out.push_str(r"\b"),
        '_' => {
            // Symbol boundaries `\_<` / `\_>` — approximate with a word boundary.
            match it.next() {
                Some('<') | Some('>') => out.push_str(r"\b"),
                Some(o) => {
                    out.push('_');
                    out.push(o);
                }
                None => out.push('_'),
            }
        }
        // regex-emacs.c `at_dot`: point in a buffer, nowhere in a string.
        '=' => out.push_str(&syn.at_dot()),
        // `\w` / `\W` are the word-constituent class of the *syntax table*
        // (`regex-emacs.c` tests `SYNTAX (c) == Sword`), not the crate's
        // `[0-9A-Za-z_]`. The two disagree on `_` under any lisp-mode table,
        // where `_` is a symbol constituent: `(string-match "\\w" "_")` is nil in
        // Emacs 30.2 and was 0 here.
        'w' | 'W' => {
            if syn.available() {
                out.push_str(&char_class(&syn.ranges('w'), e == 'W'));
            } else {
                out.push_str(if e == 'W' { r"\W" } else { r"\w" });
            }
        }
        'b' => out.push_str(r"\b"),
        'B' => out.push_str(r"\B"),
        // Syntax classes `\sC` / `\SC`, resolved against the syntax table in
        // force where this regexp is compiled.
        //
        // Emacs asks `SYNTAX (c) == class` per character while matching; this
        // translator has to answer for the whole character space up front, which
        // `SyntaxLookup` does by reading the table's runs. Getting the table
        // involved is the whole point: `\s_` matched nothing before (the arm
        // below fell through to the whitespace set), and the classes that *were*
        // hardcoded ignored `with-syntax-table` entirely.
        's' | 'S' => {
            let neg = e == 'S';
            let class = it.peek().copied();
            // `-` is `modify-syntax-entry`'s alias for the whitespace class.
            let class = class.map(|c| if c == '-' { ' ' } else { c });
            if let (true, Some(class)) = (syn.available(), class) {
                it.next();
                out.push_str(&char_class(&syn.ranges(class), neg));
                return Ok(());
            }
            match it.next() {
                // Whitespace syntax is the SYNTAX TABLE's whitespace class, not
                // the regex crate's `\s`. They differ on the line terminators:
                // `\s` matches `\n`, `\r` and `\v`, but the standard syntax table
                // classes newline as comment-end (`>`) and CR as a symbol
                // constituent, so Emacs does not. Verified against GNU Emacs 30.2:
                //
                //   (string-match "\\s-" "\n") => nil    "\r" => nil   "\v" => nil
                //   (string-match "\\s-" "\t") => 0      "\f" => 0     " "  => 0
                //   (string-match "\\s-" " ") => 0
                //
                // which is exactly `?\t ?\f ?\s 160` — the set the standard table
                // marks whitespace. Emitting `\s` made every `\s-` silently match
                // across a line boundary.
                Some('-') | Some(' ') => out.push_str(if neg { WS_SYNTAX_NEG } else { WS_SYNTAX }),
                Some('w') => out.push_str(if neg { r"\W" } else { r"\w" }),
                Some(_) | None => out.push_str(if neg { WS_SYNTAX_NEG } else { WS_SYNTAX }),
            }
        }
        // Backreferences `\1`..`\9`. Emacs validates them at COMPILE time
        // (`regex-emacs.c`): `\N` is `Invalid back reference` when N names a
        // group the reader has not opened yet (`reg > bufp->re_nsub`) and also
        // when that group is still open (`group_in_compile_stack`), so
        // `\(a\1\)` is rejected while `\(a\)\1` is not. Without this the crate
        // decided instead, and its own wording leaked into the elisp error data.
        '1'..='9' => {
            let reg = e as u32 - '0' as u32;
            if reg > groups.nsub || groups.open.contains(&reg) {
                return Err(INVALID_BACKREF.into());
            }
            // fancy-regex numbers captures positionally, so an Emacs group
            // number has to be mapped to the emitted group's position — under
            // explicit numbering the two differ (`\(?3:a\)\3` has one emitted
            // group, numbered 1 there and 3 here). Where a number was reused,
            // the last group to carry it is the one Emacs's register holds.
            match groups.emitted.iter().rposition(|&g| g == reg) {
                Some(i) => {
                    out.push('\\');
                    out.push_str(&(i + 1).to_string());
                }
                // A register explicit numbering skipped over — `\(?2:a\)\1` —
                // is never assigned, and Emacs's `duplicate` on an unset
                // register always fails. There is no such group to reference
                // here, so emit something that cannot match instead.
                None => out.push_str(NEVER_MATCHES),
            }
        }
        // Categories `\cC` / `\CC` (regex-emacs.c `categoryspec`): the
        // characters whose category set in the current category table has C.
        // Like `\sC`, the class is answered for the whole character space up
        // front. Any character names a category; one no character carries
        // matches nothing.
        'c' | 'C' => {
            let Some(cat) = it.next() else {
                return Err(PREMATURE_END.into());
            };
            let ranges = if cat.is_ascii() {
                syn.category_ranges(cat as u8)
            } else {
                Vec::new()
            };
            out.push_str(&char_class(&ranges, e == 'C'));
        }
        // Anything else: keep the escape (covers `\.`, `\*`, `\\`, `\+`, …).
        other => {
            out.push('\\');
            out.push(other);
        }
    }
    Ok(())
}

/// Whether `body` is a valid `\\{…\\}` repetition count: `m`, `m,`, `,n` or
/// `m,n` with `m <= n`. Emacs signals `Invalid content of \\{\\}` otherwise —
/// notably for a reversed bound like `a\\{2,1\\}`.
fn valid_brace_body(body: &str) -> bool {
    let parse = |s: &str| -> Option<u64> { s.parse().ok() };
    match body.split_once(',') {
        // An empty count is a valid interval in Emacs — `a\{\}` means `a\{0\}`.
        None => body.chars().all(|c| c.is_ascii_digit()),
        Some((lo, hi)) => {
            let lo_v = if lo.is_empty() { Some(0) } else { parse(lo) };
            match (lo_v, hi.is_empty()) {
                (Some(_), true) => true,
                (Some(l), false) => matches!(parse(hi), Some(h) if l <= h),
                _ => false,
            }
        }
    }
}

/// The standard syntax table's whitespace class, as a `regex` character class:
/// tab, formfeed, space, U+00A0. This is what `\s-` means in Emacs — see the
/// `'s' | 'S'` arm of [`translate_escape`] for the ground-truth transcript.
/// Newline, CR and vertical tab are deliberately absent; the regex crate's `\s`
/// includes them.
const WS_SYNTAX: &str = "[\\t\\x0C\\x{A0} ]";
/// Complement of [`WS_SYNTAX`] — the translation of `\S-`.
const WS_SYNTAX_NEG: &str = "[^\\t\\x0C\\x{A0} ]";

/// Emacs's `[:class:]` names, as class BODY text for the `regex` crate.
///
/// The `regex` crate's own POSIX classes are ASCII-only, so copying `[:alpha:]`
/// through left `(string-match "[[:alpha:]]" "Ü")` at nil where Emacs answers 0.
/// Emacs's classes are defined over the whole character set (Elisp manual,
/// "Char Classes"), so each one is re-expressed as the Unicode property the
/// manual names. `None` keeps the `regex` crate's own definition, which for
/// `digit`/`xdigit` already agrees with Emacs char for char.
///
/// `upper`/`lower` need no special handling for `case-fold-search`: the manual
/// says a non-nil `case-fold-search` makes `[:upper:]` match lower case too, and
/// `compile_cf` already compiles under `(?i)` in exactly that case, which applies
/// Unicode case folding to these classes and produces the same set.
///
/// `graph` and `print` are the manual's complements ("any character except
/// whitespace, control characters, surrogates, and unassigned codepoints"),
/// which a class body cannot express, so they are spelled as the union of the
/// general categories that remain.
///
/// `space`/`punct`/`word` read the SYNTAX TABLE in Emacs, so with a table
/// reachable (`syn.available()`) they are answered from it by
/// [`syntax_class_body`]; the Unicode-property forms below are only the fallback
/// for the table-less unit-test path.
fn posix_class(name: &str, syn: &dyn SyntaxLookup) -> Option<std::borrow::Cow<'static, str>> {
    use std::borrow::Cow;
    if syn.available() {
        if let Some(body) = syntax_class_body(name, syn) {
            return Some(Cow::Owned(body));
        }
    }
    Some(Cow::Borrowed(match name {
        "alpha" => r"\p{Alphabetic}\p{M}",
        "alnum" => r"\p{Alphabetic}\p{M}\p{Nd}",
        "space" => r"\p{White_Space}",
        "upper" => case_class_body(true),
        "lower" => case_class_body(false),
        "punct" => r"\p{P}\p{S}",
        "word" => r"\p{Alphabetic}\p{Nd}\p{M}",
        "blank" => "\t\\p{Zs}",
        // "any ASCII control character (ASCII codes 0 to 31)" — DEL is NOT one,
        // and the `regex` crate's own `[:cntrl:]` includes it.
        "cntrl" => r"\x00-\x1F",
        // "matches any ASCII character (codes 0-127)" / its complement. These two
        // and the byte-width pair below were not classes the `regex` crate knows
        // at all.
        "ascii" | "unibyte" => "[:ascii:]",
        "nonascii" | "multibyte" => "[:^ascii:]",
        // `graphicp` (`regex-emacs.c`): every assigned character that is not a
        // separator or a control.  `print` adds the separators back.  Neither is
        // expressible as a complement inside a class body, so both are the union
        // of the general categories they keep.
        "graph" => r"\p{L}\p{M}\p{N}\p{P}\p{S}\p{Co}\p{Cf}",
        "print" => r"\p{L}\p{M}\p{N}\p{P}\p{S}\p{Co}\p{Cf}\p{Z}",
        _ => return None,
    }))
}

/// The characters `[:upper:]` / `[:lower:]` match: `uppercasep (c)` is
/// `downcase (c) != c`, and `lowercasep (c)` is `!uppercasep (c) && upcase (c)
/// != c` (`buffer.h`), both over the SIMPLE case mappings -- a character whose
/// mapping is a multi-character sequence (`İ`, `ß`) has none.  Unicode's
/// `Uppercase`/`Lowercase` properties are the wrong set: they take in
/// `Other_Uppercase` (`ℂ`, `Ⓐ`) and the modifier letters (`ʰ`), which Emacs
/// does not case-map.  Built once from the standard library's case mappings.
fn case_class_body(upper: bool) -> &'static str {
    use std::sync::OnceLock;
    static BODIES: OnceLock<[String; 2]> = OnceLock::new();
    let bodies = BODIES.get_or_init(|| {
        let simple = |mut m: Box<dyn Iterator<Item = char>>, c: char| match (m.next(), m.next()) {
            (Some(x), None) => x != c,
            _ => false,
        };
        let mut up: Vec<(u32, u32)> = Vec::new();
        let mut lo: Vec<(u32, u32)> = Vec::new();
        let push = |v: &mut Vec<(u32, u32)>, c: u32| match v.last_mut() {
            Some(last) if last.1 + 1 == c => last.1 = c,
            _ => v.push((c, c)),
        };
        for c in (0..=MAX_SCALAR).filter_map(char::from_u32) {
            if simple(Box::new(c.to_lowercase()), c) {
                push(&mut up, c as u32);
            } else if simple(Box::new(c.to_uppercase()), c) {
                push(&mut lo, c as u32);
            }
        }
        [ranges_body(&lo), ranges_body(&up)]
    });
    &bodies[upper as usize]
}

/// The classes `regex-emacs.c` defines by the SYNTAX TABLE rather than by a
/// Unicode property: `ISSPACE` is `SYNTAX (c) == Swhitespace`, `ISWORD` is
/// `SYNTAX (c) == Sword`, and `ISPUNCT` is, for ASCII, a printable
/// non-alphanumeric and otherwise any character that is not a word constituent.
/// Answered against the table in force at compile time, as `\sC` is.
fn syntax_class_body(name: &str, syn: &dyn SyntaxLookup) -> Option<String> {
    match name {
        "space" => Some(ranges_body(&syn.ranges(' '))),
        "word" => Some(ranges_body(&syn.ranges('w'))),
        "punct" => {
            let mut ranges = vec![(0x21, 0x2F), (0x3A, 0x40), (0x5B, 0x60), (0x7B, 0x7E)];
            // Everything from U+0080 that is not a word constituent.
            let mut next = 0x80;
            for (lo, hi) in syn.ranges('w') {
                if hi < 0x80 {
                    continue;
                }
                let lo = lo.max(0x80);
                if lo > next {
                    ranges.push((next, lo - 1));
                }
                next = next.max(hi + 1);
            }
            if next <= MAX_SCALAR {
                ranges.push((next, MAX_SCALAR));
            }
            Some(ranges_body(&ranges))
        }
        _ => None,
    }
}

/// Copy a `[...]` character alternative from `it` into `out`, leading `[`
/// already consumed. Handles a `^` negation and a `]` that appears first (or
/// first-after-`^`) as a literal, matching elisp/POSIX rules.
fn copy_class(
    it: &mut std::iter::Peekable<std::str::Chars>,
    out: &mut String,
    syn: &dyn SyntaxLookup,
) -> Result<(), String> {
    // Collect the members first: a reversed range (`[z-a]`) has to be rewritten,
    // because Emacs matches nothing for it where the `regex` crate refuses to
    // compile at all.
    let mut buf = String::new();
    let mut closed = false;
    let out_start = out.len();
    out.push('[');
    if it.peek() == Some(&'^') {
        out.push('^');
        it.next();
    }
    // A `]` in the first position is a literal member, not the terminator —
    // and, being a member, it can open a range: `[]-a]` is `]` through `a`.
    if it.peek() == Some(&']') {
        push_member(']', out, &mut buf);
        it.next();
        copy_range(it, out, &mut buf)?;
    }
    while let Some(c) = it.next() {
        match c {
            // In an elisp char class a backslash is an ordinary character (no
            // escapes), so escape it for the `regex` crate: `[\"]` matches `\`/`"`.
            '\\' => {
                push_member('\\', out, &mut buf);
                copy_range(it, out, &mut buf)?;
            }
            // Either a POSIX class `[:alpha:]` or an ordinary `[` member — the
            // same question Emacs asks with `re_wctype_parse`, and it has to be
            // asked its way: `[[:a]b]` is NOT a class (there is no `:]`), so the
            // `[`, `:` and `a` are members and `b]` follows the alternative.
            // Scanning to the first `]` instead made it a class and swallowed
            // the rest.
            '[' => match wctype_at(it) {
                Some(name) => {
                    if !CLASS_NAMES.contains(&name.as_str()) {
                        return Err(INVALID_CLASS_NAME.into());
                    }
                    match posix_class(&name, syn) {
                        Some(repl) => out.push_str(&repl),
                        // The crate's own definition already agrees with Emacs.
                        None => out.push_str(&format!("[:{name}:]")),
                    }
                    // No range check: Emacs `continue`s the member loop here,
                    // so `[[:alpha:]-` is unmatched-bracket, not premature-end.
                }
                // A bare `[` is an ordinary member in elisp/POSIX bracket
                // expressions (e.g. `[{[]` matches `{` or `[`), but the `regex`
                // crate rejects an unescaped `[` inside a class — escape it.
                None => {
                    push_member('[', out, &mut buf);
                    copy_range(it, out, &mut buf)?;
                }
            },
            ']' => {
                out.push(']');
                closed = true;
                break;
            }
            _ => {
                push_member(c, out, &mut buf);
                copy_range(it, out, &mut buf)?;
            }
        }
    }
    if !closed {
        return Err(UNMATCHED_BRACKET.into());
    }
    // A reversed range matches nothing in Emacs; emit a class that can never
    // match rather than letting the engine reject the pattern.
    if has_reversed_range(&buf) {
        out.truncate(out_start);
        out.push_str(NEVER_MATCHES);
    }
    Ok(())
}

/// Emit one member character of a character alternative. Elisp gives `\`, `[`
/// and a `]` that is not the terminator no special meaning inside `[...]` —
/// `[{[]` matches `{` or `[`, and `[]-a]` is the range `]` through `a` — but
/// the `regex` crate reads all three, so they are escaped on the way out and
/// recorded unescaped in `buf`, which [`has_reversed_range`] reads.
fn push_member(c: char, out: &mut String, buf: &mut String) {
    match c {
        '\\' => out.push_str("\\\\"),
        '[' => out.push_str("\\["),
        ']' => out.push_str("\\]"),
        _ => out.push(c),
    }
    buf.push(c);
}

/// Consume the `-END` of a range, `it` sitting just past the member that opens
/// it. Emacs reads BOTH characters as soon as it sees the `-` (`regex-emacs.c`:
/// `if (p < pend && p[0] == '-' && p[1] != ']')`, then two `PATFETCH`es), which
/// decides two things this has to reproduce:
///
/// * a pattern that ends on the `-` fails inside the fetch, so `[a-` and `[]-`
///   report `PATFETCH`'s `Premature end of regular expression` rather than the
///   unmatched-bracket message the member loop would give one turn later;
/// * the range is consumed whole, so the trailing `-` of `[a-b-` is read as an
///   ordinary member — its own turn of the loop, with no range check — and that
///   pattern IS unmatched-bracket.
///
/// `-]` is not a range at all: the `-` stays an ordinary member.
fn copy_range(
    it: &mut std::iter::Peekable<std::str::Chars>,
    out: &mut String,
    buf: &mut String,
) -> Result<(), String> {
    let mut la = it.clone();
    if la.next() != Some('-') {
        return Ok(());
    }
    match la.next() {
        Some(']') => Ok(()),
        None => Err(PREMATURE_END.into()),
        Some(end) => {
            it.next();
            it.next();
            out.push('-');
            buf.push('-');
            push_member(end, out, buf);
            Ok(())
        }
    }
}

/// Emacs's `re_wctype_parse` (`regex-emacs.c`), with the opening `[` already
/// taken from `it`. `Some(name)` consumes the whole `[:NAME:]` and reports the
/// text between the delimiters — validity of the NAME is the caller's business,
/// because an unknown one is an error rather than a fallback. `None` is the C's
/// -1: this is not a class construct at all and the `[` is an ordinary member.
/// `it` is left untouched in that case.
///
/// The bounds are the C's: fewer than four characters from the `[`, or no `:]`
/// within the remaining count, and it is not a class — which is why `[[:]` and
/// `[[:a]b]` compile as ordinary members.
fn wctype_at(it: &mut std::iter::Peekable<std::str::Chars>) -> Option<String> {
    let rest: Vec<char> = std::iter::once('[').chain(it.clone()).collect();
    if rest.len() < 4 || rest[1] != ':' {
        return None;
    }
    let mut limit = rest.len() - 3;
    let mut i = 2;
    while !(rest.get(i) == Some(&':') && rest.get(i + 1) == Some(&']')) {
        limit -= 1;
        if limit == 0 {
            return None;
        }
        i += 1;
    }
    // `i + 2` characters of `rest` are consumed; one of them is the `[` the
    // caller already took.
    for _ in 0..i + 1 {
        it.next();
    }
    Some(rest[2..i].iter().collect())
}

/// Whether a class body contains a range whose end sorts before its start.
fn has_reversed_range(body: &str) -> bool {
    let cs: Vec<char> = body.chars().collect();
    let mut i = 0;
    while i + 2 < cs.len() {
        if cs[i + 1] == '-' && cs[i + 2] != ']' && cs[i] > cs[i + 2] {
            return true;
        }
        i += 1;
    }
    false
}

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

    fn t(p: &str) -> String {
        translate(p).unwrap()
    }

    #[test]
    fn grouping_and_alternation_invert() {
        assert_eq!(t(r"\(ab\|cd\)+"), "(ab|cd)+");
        assert_eq!(t(r"a(b)c"), r"a\(b\)c");
        assert_eq!(t(r"\(?:foo\)"), "(?:foo)");
        // Explicitly-numbered groups `\(?N:…\)` become plain captures (fancy-regex
        // numbers positionally, which is correct for sequential explicit numbers).
        assert_eq!(t(r"\(?1:foo\)"), "(foo)");
        assert_eq!(t(r"\(?1:a\)-\(?2:b\)"), "(a)-(b)");
        assert_eq!(t(r"\(?:x\)\(?1:y\)"), "(?:x)(y)");
    }

    #[test]
    fn bounds_and_anchors() {
        assert_eq!(t(r"a\{2,3\}"), "a{2,3}");
        assert_eq!(t(r"\`foo\'"), r"\Afoo\z");
        assert_eq!(t(r"\<word\>"), r"\bword\b");
    }

    #[test]
    fn classes_pass_through() {
        assert_eq!(t(r"[a-z]+"), "[a-z]+");
        // A `]` that is not the terminator is escaped, not passed through: the
        // crate reads a bare one as the terminator, so the range in `[]-a]`
        // came out as the two members `-` and `a` and stopped matching `^`.
        assert_eq!(t(r"[]ab]"), r"[\]ab]");
        assert_eq!(t(r"[]-a]"), r"[\]-a]");
        // A POSIX class does NOT pass through: the regex crate's own
        // `[:alpha:]` is ASCII-only, so `posix_class` rewrites it to the
        // Unicode properties. Without that rewrite
        // `(string-match "[[:alpha:]]" "Ü")` was nil where Emacs answers 0.
        assert_eq!(t(r"[[:alpha:]]"), r"[\p{Alphabetic}\p{M}]");
        assert_eq!(t(r"[^()]"), "[^()]");
        // A bare `[` is a literal class member in elisp (`\{[` keymap check in
        // derived.el's `derived-mode-make-docstring`); the crate needs it escaped.
        assert_eq!(t(r"[{[]"), r"[{\[]");
        assert_eq!(t(r"\\[{[]"), r"\\[{\[]");
    }

    /// `\s-` is the syntax table's whitespace class, NOT the regex crate's `\s`.
    /// This expectation was `\w+\s\w` — that spelling is what made `\s-` match a
    /// newline, because the crate's `\s` includes `\n`, `\r` and `\v` while the
    /// standard syntax table classes newline as comment-end and CR as a symbol
    /// constituent. Ground truth (GNU Emacs 30.2):
    ///
    /// ```text
    /// (string-match "\\s-" "\n") => nil    (string-match "\\s-" "\t") => 0
    /// (string-match "\\s-" "\r") => nil    (string-match "\\s-" "\f") => 0
    /// (string-match "\\s-" "\v") => nil    (string-match "\\s-" " ")  => 0
    ///                                      (string-match "\\s-" " ") => 0
    /// ```
    #[test]
    fn syntax_and_word_escapes() {
        assert_eq!(t(r"\w+\s-\sw"), "\\w+[\\t\\x0C\\x{A0} ]\\w");
    }

    /// The set `\s-` translates to must be exactly the standard syntax table's
    /// whitespace characters — pinned by matching, not by string equality, so a
    /// re-spelling of the class body that keeps the same meaning still passes.
    #[test]
    fn whitespace_syntax_class_excludes_line_terminators() {
        let re = fancy_regex::Regex::new(&t(r"\s-")).expect("compiles");
        for yes in ["\t", "\u{0C}", " ", "\u{A0}"] {
            assert!(re.is_match(yes).unwrap(), "\\s- must match {yes:?}");
        }
        for no in ["\n", "\r", "\u{0B}", "a"] {
            assert!(!re.is_match(no).unwrap(), "\\s- must not match {no:?}");
        }
    }

    /// A backreference names an EMACS group number. It only coincides with the
    /// emitted group's position while the pattern uses plain `\(`; under
    /// explicit numbering the translator has to remap it, and a number no group
    /// ever writes has to become something that cannot match.
    #[test]
    fn backreference_maps_to_the_emitted_group() {
        assert_eq!(t(r"\(a\)\1"), r"(a)\1");
        assert_eq!(t(r"\(?3:a\)\3"), r"(a)\1");
        assert_eq!(t(r"\(?2:a\)\1"), r"(a)[^\s\S]");
    }

    /// `regex-emacs.c` rejects `\N` at compile time when the group has not been
    /// opened, and when it is open but its `\)` has not been read.
    #[test]
    fn out_of_range_and_self_referential_backreferences_are_rejected() {
        for pat in [
            r"\1",
            r"x\2",
            r"\(a\)\2",
            r"\(?:a\)\1",
            r"\(a\1\)",
            r"\(\1\)",
        ] {
            assert_eq!(
                translate(pat).unwrap_err(),
                "Invalid back reference",
                "{pat} must not compile"
            );
        }
    }

    /// The character alternative's three other `regex-emacs.c` diagnostics.
    #[test]
    fn character_alternative_diagnostics() {
        assert_eq!(
            translate(r"[a-").unwrap_err(),
            "Premature end of regular expression"
        );
        // The trailing `-` is a member on its own turn of the loop, not a
        // range's dash, so this one runs out of ALTERNATIVE rather than pattern.
        assert_eq!(translate(r"[a-b-").unwrap_err(), "Unmatched [ or [^");
        assert_eq!(
            translate(r"[[:foo:]]").unwrap_err(),
            "Invalid character class name"
        );
        // Not a class at all — no `:]` within the count — so these compile, and
        // `b]` in the second is outside the alternative.
        assert_eq!(t(r"[[:]"), r"[\[:]");
        assert_eq!(t(r"[[:a]b]"), r"[\[:a]b]");
    }
}