roas-codegen 0.1.0

Generate Rust and Go types from OpenAPI 2.0 / 3.0 / 3.1 / 3.2 descriptions
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
//! A schema's `pattern`, read as the ECMAScript regular expression JSON
//! Schema names and printed as one that Rust's `regex` and Go's `regexp`
//! read the same way.
//!
//! The two engines disagree on far more than they fail to compile: `\d`
//! is Unicode in Rust and ASCII in Go, `.` excludes different line
//! terminators, and so on. So nothing is passed through as written. Every
//! character set — a shorthand, a class, `.`, a single character — is
//! computed as the code points ECMAScript gives it and printed as explicit
//! ranges, and what cannot be made to mean the same everywhere (lookaround,
//! backreferences, `\b`, Unicode properties, inline flags, counts Go will
//! not compile) is refused with a reason, never approximated.

use oxc_allocator::Allocator;
use oxc_regular_expression::ast::{
    Alternative, BoundaryAssertionKind, Character, CharacterClass, CharacterClassContents,
    CharacterClassContentsKind, CharacterClassEscapeKind, CharacterKind, Disjunction, Term,
};
use oxc_regular_expression::{LiteralParser, Options};

/// The largest repetition count Go compiles.
const MAX_COUNT: u64 = 1000;
const MAX_CHAR: u32 = 0x10FFFF;
/// Go's `regexp/syntax` size limit (`maxSize`): 128 MiB of 40-byte
/// instructions.
const GO_MAX_SIZE: u64 = (128 << 20) / 40;
/// Go caches node sizes and can count some twice after rewriting a
/// regex (measured up to 1.72x the true size), so a margin of half is
/// kept rather than its exact limit.
const GO_SIZE_LIMIT: u64 = GO_MAX_SIZE / 2;
const TOO_LARGE_FOR_GO: &str = "it is larger than Go's regexp safely compiles";
/// The longest pattern read, in bytes.
const MAX_LEN: usize = 16 * 1024;
/// How deep groups may nest. oxc's parser recurses per level and needs
/// tens of KiB a level in a debug build, so this keeps a 2 MiB thread
/// safe; no real schema nests near it.
const MAX_NESTING: usize = 64;
const SURROGATES: (u32, u32) = (0xD800, 0xDFFF);
const LEGACY: &str =
    "it is valid only without the Unicode flag, where part of it can match half of a character";

/// `pattern` as a regex both targets read alike, or why it cannot be one.
pub(crate) fn translate(pattern: &str) -> Result<String, String> {
    // oxc drops a trailing lone backslash in Unicode mode, where
    // ECMAScript refuses the pattern.
    if pattern.bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1 {
        return Err("not an ECMAScript regular expression: \\ at end of pattern".into());
    }
    // oxc's work grows faster than the pattern (named groups are compared
    // pairwise): a pattern longer than any real one is refused unread.
    if pattern.len() > MAX_LEN {
        return Err(format!(
            "a pattern longer than {MAX_LEN} bytes is not supported"
        ));
    }
    // The parser and the printer recurse per group: a pattern nested past
    // what Rust compiles anyway is refused before it can exhaust the stack.
    if nesting(pattern) > MAX_NESTING {
        return Err(format!(
            "nesting deeper than {MAX_NESTING} is not supported"
        ));
    }
    let allocator = Allocator::default();
    // Unicode mode, as JSON Schema recommends: an astral character is one
    // character, as it is to Rust and Go.
    let (ast, legacy) =
        match LiteralParser::new(&allocator, pattern, Some("u"), Options::default()).parse() {
            Ok(ast) => (ast, false),
            // Many schemas are written for the legacy grammar (`\-` outside a
            // class, say). It means the same as long as nothing in it can
            // match half of an astral character, which `Printer` checks.
            // A property escape the Unicode grammar refuses (a typo, or one
            // newer than the parser) would be literal text in the legacy
            // one: refused rather than matched as `p{…}`.
            Err(unicode) if property_escape(pattern) => {
                return Err(format!(
                    "its Unicode property escape is not supported: {}",
                    unicode
                        .message
                        .trim_start_matches("Invalid regular expression: ")
                ));
            }
            Err(unicode) => {
                match LiteralParser::new(&allocator, pattern, None, Options::default()).parse() {
                    Ok(ast) => (ast, true),
                    Err(_) => {
                        return Err(format!(
                            "it cannot be read as an ECMAScript regular expression: {}",
                            unicode
                                .message
                                .trim_start_matches("Invalid regular expression: ")
                        ));
                    }
                }
            }
        };
    let mut printer = Printer {
        legacy,
        source: pattern,
        names: Default::default(),
        budget: MAX_COUNT,
        out: String::new(),
    };
    if printer.disjunction(&ast.body)? > GO_SIZE_LIMIT {
        return Err(TOO_LARGE_FOR_GO.into());
    }
    // The printer's output is meant to compile; this is the proof, with
    // the limits the generated Rust code compiles it under. Go's other
    // limits are the repetition budget and the size above.
    regex::Regex::new(&printer.out)
        .map_err(|e| format!("its translation does not compile: {e}"))?;
    Ok(printer.out)
}

struct Printer<'a> {
    /// Parsed without the Unicode flag: a code unit is a character, so a
    /// set touching the surrogates could match half an astral character.
    legacy: bool,
    /// The pattern as written: a character's span reads into it.
    source: &'a str,
    /// Group names seen so far.
    names: std::collections::HashSet<String>,
    /// How many times what is printed next may be repeated, through every
    /// count around it: Go refuses a nesting whose counts multiply past
    /// 1000.
    budget: u64,
    out: String,
}

/// A set of code points: sorted, disjoint, non-adjacent inclusive ranges.
type Set = Vec<(u32, u32)>;

impl Printer<'_> {
    // Each part returns its size as Go's `calcSize` counts it (at least
    // one per node): Go refuses a regex past `GO_MAX_SIZE` at compile time,
    // by its own count, which can exceed the true size: see
    // `GO_SIZE_LIMIT`.

    fn disjunction(&mut self, d: &Disjunction<'_>) -> Result<u64, String> {
        let mut size = 0u64;
        for (i, alternative) in d.body.iter().enumerate() {
            if i > 0 {
                self.out.push('|');
                size = size.saturating_add(1);
            }
            size = size.saturating_add(self.alternative(alternative)?);
        }
        Ok(size.max(1))
    }

    fn alternative(&mut self, a: &Alternative<'_>) -> Result<u64, String> {
        let mut size = 0u64;
        for term in &a.body {
            size = size.saturating_add(self.term(term)?);
        }
        Ok(size.max(1))
    }

    fn group(&mut self, d: &Disjunction<'_>) -> Result<u64, String> {
        self.out.push_str("(?:");
        let size = self.disjunction(d)?;
        self.out.push(')');
        Ok(size)
    }

    fn term(&mut self, term: &Term<'_>) -> Result<u64, String> {
        match term {
            Term::BoundaryAssertion(b) => match b.kind {
                BoundaryAssertionKind::Start => self.out.push('^'),
                BoundaryAssertionKind::End => self.out.push('$'),
                // The buffer boundaries (`u` mode only): both targets spell
                // these two as ECMAScript does. Neither has `\Z`.
                BoundaryAssertionKind::StartBuffer => self.out.push_str("\\A"),
                BoundaryAssertionKind::EndBuffer => self.out.push_str("\\z"),
                BoundaryAssertionKind::EndBufferOptionalNewline => {
                    return Err("the `\\Z` boundary is not supported".into());
                }
                BoundaryAssertionKind::Boundary | BoundaryAssertionKind::NegativeBoundary => {
                    return Err("word boundaries (`\\b`, `\\B`) are not supported".into());
                }
            },
            Term::LookAroundAssertion(_) => {
                return Err("lookaround is not supported".into());
            }
            Term::Quantifier(q) => {
                if q.min > MAX_COUNT || q.max.is_some_and(|max| max > MAX_COUNT) {
                    return Err(format!(
                        "a repetition count above {MAX_COUNT} is not supported"
                    ));
                }
                // Go's own rule (`repeatIsValid`): a `{…}` count, its
                // maximum or else its minimum, divides what may be nested
                // inside it; `*`, `+` and `?` do not count.
                let saved = self.budget;
                if !matches!((q.min, q.max), (0, None) | (1, None) | (0, Some(1))) {
                    match q.max.unwrap_or(q.min) {
                        // Go checks what is inside afresh: `{0}` lifts
                        // nothing.
                        0 => self.budget = MAX_COUNT,
                        m if m > self.budget => {
                            return Err(format!(
                                "nested repetition counts multiplying past {MAX_COUNT} are not supported"
                            ));
                        }
                        m => self.budget /= m,
                    }
                }
                let sub = self.term(&q.body)?;
                self.budget = saved;
                // Go checks each node as it parses it, so a body hidden by
                // `{0}` still counts.
                if sub > GO_SIZE_LIMIT {
                    return Err(TOO_LARGE_FOR_GO.into());
                }
                // Laziness changes which match is found, never whether one
                // is: a check only asks the latter.
                let size = match (q.min, q.max) {
                    (0, None) => {
                        self.out.push('*');
                        sub.saturating_add(2)
                    }
                    (1, None) => {
                        self.out.push('+');
                        sub.saturating_add(1)
                    }
                    (0, Some(1)) => {
                        self.out.push('?');
                        sub.saturating_add(1)
                    }
                    (min, None) => {
                        self.out.push_str(&format!("{{{min},}}"));
                        min.saturating_mul(sub).saturating_add(1)
                    }
                    (min, Some(max)) => {
                        if min == max {
                            self.out.push_str(&format!("{{{min}}}"));
                        } else {
                            self.out.push_str(&format!("{{{min},{max}}}"));
                        }
                        max.saturating_mul(sub).saturating_add(max - min)
                    }
                };
                return Ok(size.max(1));
            }
            Term::Character(c) => {
                self.character(c)?;
                self.set(vec![(c.value, c.value)])?;
            }
            Term::Dot(_) => self.set(complement(&normalize(vec![
                (0x0A, 0x0A),
                (0x0D, 0x0D),
                (0x2028, 0x2029),
            ])))?,
            Term::CharacterClassEscape(e) => self.set(escape(e.kind))?,
            Term::UnicodePropertyEscape(_) => {
                return Err("Unicode property escapes are not supported".into());
            }
            Term::CharacterClass(class) => {
                let set = self.class(class)?;
                self.set(set)?;
            }
            Term::CapturingGroup(g) => {
                // `(?:…)` is no node of its own.
                // oxc accepts a name repeated inside its own group, which
                // ECMAScript refuses; any repeat is refused here.
                if let Some(name) = &g.name
                    && !self.names.insert(name.as_str().to_owned())
                {
                    return Err(format!("the group name `{name}` is repeated"));
                }
                return self.group(&g.body);
            }
            Term::IgnoreGroup(g) => {
                if g.modifiers.is_some() {
                    return Err("inline flags are not supported".into());
                }
                return self.group(&g.body);
            }
            Term::IndexedReference(_) | Term::NamedReference(_) => {
                return Err("backreferences are not supported".into());
            }
        }
        Ok(1)
    }

    /// A single character the pattern spells out.
    fn character(&self, c: &Character) -> Result<(), String> {
        // Annex B reads `\400` as `\40` then `0`, and oxc drops the `0`.
        if matches!(
            c.kind,
            CharacterKind::Octal1 | CharacterKind::Octal2 | CharacterKind::Octal3
        ) {
            return Err("legacy octal escapes are not supported".into());
        }
        // The legacy grammar reads a `\c` that starts no control escape
        // (`[\c]`, `\c1`) as a literal backslash, which the Unicode one
        // refuses: a backslash must be written escaped.
        if c.value == u32::from(b'\\')
            && self
                .source
                .get(c.span.start as usize..c.span.end as usize)
                .is_none_or(|text| text == "\\")
        {
            return Err("this `\\c` escape is not supported".into());
        }
        self.explicit(c.value, c.value)
    }

    /// A range the pattern spells out: a surrogate there matches only a
    /// lone surrogate, which a decoded string never holds as one.
    fn explicit(&self, lo: u32, hi: u32) -> Result<(), String> {
        if lo <= SURROGATES.1 && hi >= SURROGATES.0 {
            return Err(if self.legacy {
                LEGACY.into()
            } else {
                "surrogate code points are not supported".into()
            });
        }
        Ok(())
    }

    fn class(&self, class: &CharacterClass<'_>) -> Result<Set, String> {
        if class.kind != CharacterClassContentsKind::Union {
            return Err("class set operations are not supported".into());
        }
        let mut set = Vec::new();
        for item in &class.body {
            match item {
                CharacterClassContents::CharacterClassRange(r) => {
                    self.character(&r.min)?;
                    self.character(&r.max)?;
                    self.explicit(r.min.value, r.max.value)?;
                    set.push((r.min.value, r.max.value));
                }
                CharacterClassContents::CharacterClassEscape(e) => set.extend(escape(e.kind)),
                CharacterClassContents::Character(c) => {
                    self.character(c)?;
                    set.push((c.value, c.value));
                }
                CharacterClassContents::UnicodePropertyEscape(_) => {
                    return Err("Unicode property escapes are not supported".into());
                }
                CharacterClassContents::NestedCharacterClass(_)
                | CharacterClassContents::ClassStringDisjunction(_) => {
                    return Err("class set operations are not supported".into());
                }
            }
        }
        let set = normalize(set);
        Ok(if class.negative {
            complement(&set)
        } else {
            set
        })
    }

    /// One character from `set`, printed as explicit ranges.
    fn set(&mut self, set: Set) -> Result<(), String> {
        if self.legacy && overlaps(&set, SURROGATES) {
            return Err(LEGACY.into());
        }
        let set = without_surrogates(&set);
        match set.as_slice() {
            // Matches nothing: an empty class, or one of surrogates only.
            [] => self.out.push_str("[^\\x{0}-\\x{10FFFF}]"),
            [(lo, hi)] if lo == hi => push_char(&mut self.out, *lo, false),
            ranges => {
                self.out.push('[');
                for &(lo, hi) in ranges {
                    push_char(&mut self.out, lo, true);
                    if hi > lo {
                        if hi > lo + 1 {
                            self.out.push('-');
                        }
                        push_char(&mut self.out, hi, true);
                    }
                }
                self.out.push(']');
            }
        }
        Ok(())
    }
}

/// Whether `pattern` has a `\p{` or `\P{` escape: an unescaped backslash
/// before it.
fn property_escape(pattern: &str) -> bool {
    let mut chars = pattern.chars();
    while let Some(c) = chars.next() {
        if c == '\\' && matches!(chars.next(), Some('p' | 'P')) && chars.clone().next() == Some('{')
        {
            return true;
        }
    }
    false
}

/// How deep groups nest in `pattern`, read outside classes and escapes.
fn nesting(pattern: &str) -> usize {
    let (mut depth, mut deepest, mut in_class) = (0usize, 0usize, false);
    let mut chars = pattern.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                chars.next();
            }
            '[' if !in_class => in_class = true,
            ']' if in_class => in_class = false,
            '(' if !in_class => {
                depth += 1;
                deepest = deepest.max(depth);
            }
            ')' if !in_class => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    deepest
}

/// What a shorthand class means in ECMAScript, which is ASCII for `\d`
/// and `\w` but the full whitespace and line-terminator set for `\s`.
fn escape(kind: CharacterClassEscapeKind) -> Set {
    let digits = vec![(0x30, 0x39)];
    let word = normalize(vec![(0x30, 0x39), (0x41, 0x5A), (0x5F, 0x5F), (0x61, 0x7A)]);
    // WhiteSpace and LineTerminator: tab, LF, VT, FF, CR, space, NBSP,
    // the `Zs` category, LS, PS and the BOM.
    let space = normalize(vec![
        (0x09, 0x0D),
        (0x20, 0x20),
        (0xA0, 0xA0),
        (0x1680, 0x1680),
        (0x2000, 0x200A),
        (0x2028, 0x2029),
        (0x202F, 0x202F),
        (0x205F, 0x205F),
        (0x3000, 0x3000),
        (0xFEFF, 0xFEFF),
    ]);
    match kind {
        CharacterClassEscapeKind::D => digits,
        CharacterClassEscapeKind::NegativeD => complement(&digits),
        CharacterClassEscapeKind::W => word,
        CharacterClassEscapeKind::NegativeW => complement(&word),
        CharacterClassEscapeKind::S => space,
        CharacterClassEscapeKind::NegativeS => complement(&space),
    }
}

fn normalize(mut set: Set) -> Set {
    set.sort_unstable();
    let mut out: Set = Vec::with_capacity(set.len());
    for (lo, hi) in set {
        let (lo, hi) = (lo.min(hi), lo.max(hi));
        match out.last_mut() {
            Some(last) if lo <= last.1.saturating_add(1) => last.1 = last.1.max(hi),
            _ => out.push((lo, hi)),
        }
    }
    out
}

fn complement(set: &Set) -> Set {
    let mut out = Vec::new();
    let mut next = 0u32;
    for &(lo, hi) in set {
        if lo > next {
            out.push((next, lo - 1));
        }
        next = hi.saturating_add(1);
    }
    if next <= MAX_CHAR {
        out.push((next, MAX_CHAR));
    }
    out
}

fn overlaps(set: &Set, (lo, hi): (u32, u32)) -> bool {
    set.iter().any(|&(a, b)| a <= hi && b >= lo)
}

fn without_surrogates(set: &Set) -> Set {
    let (s_lo, s_hi) = SURROGATES;
    let mut out = Vec::new();
    for &(lo, hi) in set {
        if lo < s_lo {
            out.push((lo, hi.min(s_lo - 1)));
        }
        if hi > s_hi {
            out.push((lo.max(s_hi + 1), hi));
        }
    }
    out
}

/// One character, spelled the same for both engines: ASCII letters, digits
/// and other plain symbols as themselves, a metacharacter escaped with a
/// backslash, and anything else (control, space, non-ASCII) as `\x{…}`,
/// the one hex escape both accept. `\u` would not compile in Go.
fn push_char(out: &mut String, c: u32, in_class: bool) {
    let meta: &[u8] = if in_class {
        // `&`, `~` and `-` start Rust's class operators.
        b"\\[]^-&~"
    } else {
        b"\\.+*?()[]{}|^$"
    };
    match u8::try_from(c) {
        Ok(b) if meta.contains(&b) => {
            out.push('\\');
            out.push(char::from(b));
        }
        // `#` starts a comment under Rust's `x` flag, never set here, but
        // spelling it as an escape costs nothing.
        Ok(b) if b.is_ascii_graphic() && b != b'#' => out.push(char::from(b)),
        _ => out.push_str(&format!("\\x{{{c:X}}}")),
    }
}

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

    fn ok(pattern: &str) -> String {
        translate(pattern).unwrap_or_else(|e| panic!("{pattern}: {e}"))
    }

    #[test]
    fn shorthands_are_spelled_out() {
        assert_eq!(ok(r"^\d+$"), "^[0-9]+$");
        assert_eq!(ok(r"\w"), "[0-9A-Z_a-z]");
        assert_eq!(ok(r"[\d-]"), r"[\-0-9]");
        assert_eq!(
            ok(r"\s"),
            r"[\x{9}-\x{D}\x{20}\x{A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}]"
        );
        assert_eq!(ok(r"\D"), r"[\x{0}-/:-\x{D7FF}\x{E000}-\x{10FFFF}]");
        assert_eq!(
            ok("."),
            r"[\x{0}-\x{9}\x{B}\x{C}\x{E}-\x{2027}\x{202A}-\x{D7FF}\x{E000}-\x{10FFFF}]"
        );
    }

    #[test]
    fn ecmascript_classes_are_plain() {
        // Rust would read `&&` and `--` as class operators.
        assert_eq!(ok("[a&&b]"), r"[\&ab]");
        assert_eq!(ok("[+--]"), r"[+-\-]");
        assert_eq!(ok("[]"), r"[^\x{0}-\x{10FFFF}]");
        assert_eq!(ok("[^]"), r"[\x{0}-\x{D7FF}\x{E000}-\x{10FFFF}]");
    }

    #[test]
    fn structure_is_kept() {
        assert_eq!(ok("^(a|bc)*?x{2,5}$"), "^(?:a|bc)*x{2,5}$");
        assert_eq!(ok("(?<year>[0-9]{4})-(?:x)"), "(?:[0-9]{4})-(?:x)");
        assert_eq!(ok(""), "(?:)");
        assert_eq!(ok("a{1000}"), "a{1000}");
        assert_eq!(ok("(?:a{2}){500}"), "(?:a{2}){500}");
        assert_eq!(ok("(?:a*){1000}"), "(?:a*){1000}");
        // An escaped backslash before `p{` is no property escape.
        assert_eq!(ok(r"\-\\p{x}"), r"-\\p\{x\}");
        assert_eq!(ok("(?:(?:a{1000}){0}){2}"), "(?:(?:a{1000}){0}){2}");
        assert_eq!(ok("(?:a{1000}){0}"), "(?:a{1000}){0}");
        assert_eq!(ok(r"[\\]"), r"\\");
        assert_eq!(ok(r"\cJ"), r"\x{A}");
        assert_eq!(ok(r"[\cA]"), r"\x{1}");
        assert_eq!(ok(r"\0"), r"\x{0}");
        assert!(ok(r"^https?://\S+$").starts_with("^https?://["));
        assert_eq!(ok("😀+"), r"\x{1F600}+");
        assert_eq!(ok(r"\u{1F600}"), r"\x{1F600}");
        assert_eq!(ok(r"a\.b\$"), r"a\.b\$");
        assert_eq!(ok("é"), r"\x{E9}");
        assert_eq!(ok(r"\A[a-z]+\z"), r"\A[a-z]+\z");
    }

    #[test]
    fn legacy_grammar_is_read_when_it_means_the_same() {
        // `\-` outside a class is legacy-only syntax.
        assert_eq!(ok(r"^\d{3}\-\d{4}$"), "^[0-9]{3}-[0-9]{4}$");
        // So is a control escape spelled with a digit or `_`, in a class.
        assert_eq!(ok(r"[\c1]"), r"\x{11}");
        assert_eq!(ok(r"[\c_]"), r"\x{1F}");
        // A legacy `.` could match half of an astral character.
        assert!(translate(r"\-.").is_err());
        assert!(translate(r"\-[^a]").is_err());
        assert!(translate(r"\-\S").is_err());
        assert!(translate("\\-😀").is_err());
    }

    #[test]
    fn deep_nesting_is_refused_before_parsing() {
        // At the limit, on a test thread's stack, in a debug build.
        let at = format!("{}a{}", "(".repeat(64), ")".repeat(64));
        assert!(translate(&at).is_ok());
        assert!(
            translate(&"a".repeat(16 * 1024 + 1))
                .unwrap_err()
                .contains("longer")
        );
        let deep = format!("{}a{}", "(".repeat(65), ")".repeat(65));
        assert!(translate(&deep).unwrap_err().contains("nesting"));
        // Brackets in a class or escaped do not nest.
        assert!(translate(&format!("[{}]", "(".repeat(1000))).is_ok());
        assert!(translate(&"\\(".repeat(1000)).is_ok());
    }

    #[test]
    fn what_differs_is_refused() {
        for pattern in [
            r"\bword\b",
            r"a\Z",
            "a(?=b)",
            "(?<!a)b",
            r"(a)\1",
            r"(?<n>a)\k<n>",
            r"\p{L}",
            "[\\p{L}]",
            "(?i:a)",
            "a{1001}",
            "a{0,1001}",
            r"(?:a{2}){600}",
            r"^(?:[a-z0-9]{1,63}\.){1,127}$",
            r"[\c]",
            r"[\c-x]",
            "(?<n>a|(?<n>b))",
            r"\p{Latin}",
            r"\-\P{Foo}",
            &format!("(?:{}){{1000}}", "^".repeat(3356)),
            &format!("(?:(?:{}){{1000}}){{0}}", "x".repeat(3400)),
            &format!("(?:{}){{1000}}", "^".repeat(1700)),
            "(?:(?:a{1000}){2}){0}",
            r"\-(?<n>a|(?<n>b))",
            "a\\",
            r"^\d+$\",
            r"^\S{1,1000}-\S{1,1000}-\S{1,1000}-\S{1,1000}-\S{1,1000}$",
            r"\-\400",
            r"\-[\400]",
            r"\-\1",
            r"\uD800",
            "(",
        ] {
            assert!(translate(pattern).is_err(), "{pattern}");
        }
    }
}