tsv_ts 0.8.0

TypeScript/JS formatter, type stripper and acorn-compatible parser — part of tsv
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
//! The source type strip: TypeScript source in, JS source out, by blanking.
//!
//! Every type-only range becomes whitespace — one space per UTF-16 unit, with each line
//! terminator inside it kept verbatim — so every surviving character keeps its line and
//! UTF-16 column and no sourcemap is needed. The only other bytes written are single
//! `;` / `(` / `)` substitutions inside a blanked range, where pure blanking would let ASI
//! (or a line break before `=>` or a call's `(`) change the parse. TypeScript with runtime
//! semantics (`enum`, a value `namespace`, parameter properties, `import =`, `export =`,
//! `<T>x`) is refused, never transformed.
//!
//! The verdicts are TypeScript's erasure semantics, the ones ts-blank-space and Node's
//! `module.stripTypeScriptTypes` share. They are not the Svelte compiler's: that product
//! erases a tree, follows Svelte's own oracle, and shares no code with this one.
//!
//! The parse goal is the format path's (`strip_in`): a named goal is exact, and an
//! unset one reads the source as a module, retried as a script only if that fails. No
//! verdict below depends on the goal; a script's `with` body is one more lone statement
//! body.
//!
//! Two passes after the parse: one walk over the AST (`walk`) collects the type-only ranges,
//! the hazard substitutions and the refusals, locating the bytes the AST holds no position
//! for (a modifier keyword, a `?` / `!` mark, a paren the parser stripped) with
//! `tsv_lang::source_scan`; then one copy of the source (`blank`) writes the blanks. The
//! strip shares nothing with the printer.
//!
//! **The hazards.** Each substitution is one character inside a blanked range:
//!
//! - a `;` starting a statement or class member blanked whole after JS that does not end in
//!   `;` (`let x = y⏎type T = 1⏎(z)`), in ts-blank-space's cases, plus one: a statement
//!   blanked whole as the lone body of an `if` / loop / label / `with` always becomes `;`,
//!   so the output stays JS and the statement after it cannot become the body
//!   (`if (a) g()`). The one such body tsc's grammar allows, as the body of an `if`, a loop
//!   or a `with`, is an overload signature, which ts-blank-space blanks plain;
//! - a `;` starting a bodiless signature (an overload, an abstract method, an index
//!   signature) after an expression left open — a statement or field initializer with no
//!   `;` — where the line after it would continue that expression: it opens with `(`, `[`,
//!   a template, `+` / `-` (not `++` / `--`), `/`, `*`, or a key `in` / `instanceof`, and
//!   only with an operator after a postfix `++` / `--`. ts-blank-space misses these;
//! - a `;` in place of a statement-final `as` / `satisfies` (`let x = y as T⏎(z)`);
//! - a `;` in place of a blanked first modifier before a computed key (`a = 1⏎public [k]`),
//!   or, after a field whose initializer has no `;`, before a generator method or a key
//!   named `in` / `instanceof` (`a = x⏎private in`, which would read `x in …`);
//! - a `)` moved to the end of an arrow's blanked return type when a line break precedes
//!   the `=>`, and a `(` moved to the start of blanked type parameters when a line break
//!   precedes the parameters' `(`.
//!
//! A line break here is any ECMAScript line terminator (LF, CR, U+2028, U+2029), where
//! ts-blank-space tests LF alone.
//!
//! **Assumed tsc-checked.** The parser accepts some shapes tsc rejects that carry a value —
//! a class field `declare x = 1` or `abstract x = 1`, `declare let a = 1`, a bodied member
//! of a `declare class` or `declare namespace`. Each is blanked whole, as ts-blank-space
//! blanks it (Node refuses some), so the value it would have carried is silently gone;
//! refusing them is the diagnostics layer's job, not the strip's.
//!
//! The fixtures under `tests/fixtures_strip/` define the output, graded by
//! `tests/strip_fixtures_tests.rs`.

mod blank;
mod scan;
mod walk;

use std::fmt;
use std::ops::Range;

use tsv_lang::{Error, ErrorKind, ErrorReport};

/// Strip the types from TypeScript `source`, keeping every surviving character at its line
/// and UTF-16 column.
///
/// No goal is named, so the source is read as [`format()`](crate::format()) reads it: as a
/// module, retried as a script only if that fails (see [Goals](crate#goals)). The output is
/// JS at the goal the source was read at; nothing the walk decides depends on the goal.
/// [`strip_with_goal`] names one exactly.
///
/// ```
/// use tsv_ts::{StripError, UnsupportedConstruct, strip};
///
/// assert_eq!(strip("let x: number = 1;").unwrap().code, "let x         = 1;");
///
/// // an angle-bracket assertion cannot be blanked away: refused, with its span
/// let source = "let x = <T>y;";
/// let error = strip(source).unwrap_err();
/// let StripError::Unsupported { construct, .. } = &error else {
///     panic!("expected a refusal");
/// };
/// assert_eq!(*construct, UnsupportedConstruct::TypeAssertion);
/// assert_eq!(construct.as_str(), "type_assertion");
/// // the refused bytes, and where they start as the JS a binding returns reports it
/// assert_eq!(error.span(), Some(8..12));
/// let report = error.to_report().unwrap();
/// assert_eq!((report.start.line, report.start.column), (1, 8));
/// assert_eq!(error.message(), "cannot strip an angle-bracket type assertion");
/// assert_eq!(error.to_string(), "cannot strip an angle-bracket type assertion (1:9)");
/// assert_eq!(
///     format!("{error:#}"),
///     "cannot strip an angle-bracket type assertion\n1:9 let x = <T>y;\n            ^ here"
/// );
/// ```
///
/// # Errors
///
/// [`StripError::Parse`] when `source` does not parse at either goal (the error reported
/// is the one [Goals](crate#goals) picks); [`StripError::Unsupported`] when it holds
/// TypeScript syntax that type blanking cannot erase.
pub fn strip(source: &str) -> Result<Stripped, StripError> {
    strip_one_shot(source, None)
}

/// [`strip`] at exactly `goal`, with no Module-to-Script fallback: a source the goal's
/// grammar rejects is a [`StripError::Parse`] even when the other goal would accept it.
///
/// ```
/// use tsv_ts::{Goal, StripError, strip_with_goal};
///
/// let source = "import a from 'b'; let x: T;";
/// assert!(matches!(strip_with_goal(source, Goal::Script), Err(StripError::Parse(_))));
/// assert_eq!(
///     strip_with_goal(source, Goal::Module).unwrap().code,
///     "import a from 'b'; let x   ;"
/// );
/// ```
///
/// # Errors
///
/// [`StripError::Parse`] when `source` does not parse at `goal`; [`StripError::Unsupported`]
/// as [`strip`].
pub fn strip_with_goal(source: &str, goal: crate::Goal) -> Result<Stripped, StripError> {
    strip_one_shot(source, Some(goal))
}

/// The one-shot strips' arena: a fresh one sized to the source, dropped on return — the
/// [`Stripped`] output is owned.
fn strip_one_shot(source: &str, goal: Option<crate::Goal>) -> Result<Stripped, StripError> {
    let arena = bumpalo::Bump::with_capacity(tsv_lang::estimated_ast_arena_capacity(source.len()));
    strip_in(source, goal, &arena)
}

/// The strip over a caller-owned `arena` — the hidden primitive beneath [`strip`] and
/// [`strip_with_goal`], for a hot loop that keeps one arena warm across sources (the
/// bindings' per-thread arena), reset by the caller between calls.
///
/// The parse is `__private::parse_with_goal_or_fallback`'s: `Some(goal)` is exact, and
/// `None` parses at `Module`, retried at `Script` only if that fails.
///
/// # Errors
///
/// As [`strip`].
pub fn strip_in(
    source: &str,
    goal: Option<crate::Goal>,
    arena: &bumpalo::Bump,
) -> Result<Stripped, StripError> {
    let program = crate::__private::parse_with_goal_or_fallback(source, goal, arena)
        .map_err(StripError::Parse)?;
    let mut walk = walk::Walk::new(source, arena);
    walk.program(&program);
    let mut edits = walk.finish()?;
    // nothing type-only: the source is the JS, copied once with no walk over the edits
    let code = if edits.is_empty() {
        source.to_owned()
    } else {
        blank::apply(source, &mut edits)
    };
    Ok(Stripped { code })
}

/// A successful [`strip`].
///
/// ```
/// # fn main() -> Result<(), tsv_ts::StripError> {
/// let stripped = tsv_ts::strip("function f<T>(a: T): T { return a; }")?;
/// assert_eq!(stripped.code, "function f   (a   )    { return a; }");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stripped {
    /// The JS: the source with every type-only range blanked, the source itself when
    /// nothing is type-only.
    pub code: String,
    // TODO: `imports` — the static import and re-export specifiers the walk visits, for a
    // parallel module loader. Reserved as shape; it lands with a consumer.
}

// A new variant compiles silently at every in-workspace match, which `#[non_exhaustive]`
// forces to carry a `_` arm: give it an arm of its own in tsv_wasm's and tsv_napi's
// `strip_typescript` and in tsv_debug's `strip` command and strip-fixture grader.
/// Why [`strip`] produced no output. Either way the failure is a [`Error`]
/// ([`StripError::error`]), so it displays, spans and reports as every other tsv error does:
/// one line under `{}`, the `line:col` header, excerpt and caret under `{:#}`.
///
/// ```
/// use tsv_ts::{ErrorKind, StripError, UnsupportedConstruct, strip};
///
/// match strip("enum E { A }") {
///     Err(StripError::Unsupported { construct, .. }) => {
///         assert_eq!(construct, UnsupportedConstruct::Enum);
///     }
///     other => panic!("expected a refusal, got {other:?}"),
/// }
/// let err = strip("let x =").unwrap_err();
/// assert!(matches!(err, StripError::Parse(_)));
/// assert_eq!(err.kind(), ErrorKind::Syntax);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StripError {
    /// The source does not parse. Transparent: it displays as the inner [`Error`] does, and
    /// [`std::error::Error::source`] answers the inner error's own `source()` rather than the
    /// inner error itself, so an error-chain printer prints its message once.
    Parse(Error),
    /// The source holds TypeScript syntax that type blanking cannot erase: a construct
    /// with runtime semantics, or an assertion whose blanking would regroup the expression.
    /// Fields may be added, so a pattern over it takes `..`.
    #[non_exhaustive]
    Unsupported {
        /// What was refused.
        construct: UnsupportedConstruct,
        /// The refusal as an [`Error`] of [`ErrorKind::Refusal`]: its span the refused
        /// construct's bytes, its message `cannot strip <the construct>` over the frame of
        /// the span's start ([`Error::to_report`]'s `start`).
        error: Error,
    },
}

/// The TypeScript [`strip`] refuses: syntax that type blanking cannot erase, because
/// erasure would have to transform it rather than blank it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UnsupportedConstruct {
    /// A non-`declare` `enum`, `const enum` included.
    Enum,
    /// A non-`declare` `namespace` holding a value member.
    ValueNamespace,
    /// A parameter property: `public` / `private` / `protected` / `readonly` / `override`
    /// on a constructor parameter. The span is the first such modifier.
    ParameterProperty,
    /// `import x = require('y')` / `import x = A.B`, `import type` and `export import`
    /// included.
    ImportEquals,
    /// `export = x`.
    ExportEquals,
    /// An angle-bracket type assertion, `<T>x`.
    TypeAssertion,
    /// An `as` / `satisfies` whose blanking would change how the expression around it
    /// groups: a binary operator after the assertion that binds tighter than the one inside
    /// it, so the blanked `a + b as T / c` reads `a + (b / c)` (a different program); or a
    /// unary operand of `**`, so the blanked `-a as T ** 2` reads `-a ** 2` (a syntax
    /// error). The span is the assertion expression.
    AssertionGrouping,
}

impl UnsupportedConstruct {
    /// The construct's wire name — snake_case, the `construct` a JS refusal carries
    /// (`enum`, `value_namespace`, `parameter_property`, `import_equals`, `export_equals`,
    /// `type_assertion`, `assertion_grouping`).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Enum => "enum",
            Self::ValueNamespace => "value_namespace",
            Self::ParameterProperty => "parameter_property",
            Self::ImportEquals => "import_equals",
            Self::ExportEquals => "export_equals",
            Self::TypeAssertion => "type_assertion",
            Self::AssertionGrouping => "assertion_grouping",
        }
    }

    /// The construct as a refusal's message names it, after `cannot strip `: the message's
    /// wording, read only by the refusal's own rendering.
    #[must_use]
    pub(crate) const fn description(self) -> &'static str {
        match self {
            Self::Enum => "an enum",
            Self::ValueNamespace => "a namespace with a value member",
            Self::ParameterProperty => "a parameter property",
            Self::ImportEquals => "an 'import =' declaration",
            Self::ExportEquals => "an 'export =' assignment",
            Self::TypeAssertion => "an angle-bracket type assertion",
            Self::AssertionGrouping => "an assertion whose blanking would regroup its expression",
        }
    }
}

impl StripError {
    /// A refusal of `construct` over the bytes `span` of `source`, the text that was stripped.
    fn unsupported(construct: UnsupportedConstruct, source: &str, span: Range<usize>) -> Self {
        let message = format!("cannot strip {}", construct.description());
        let error = Error::refusal(
            &message,
            source,
            span.start,
            span.end,
            crate::WIRE_COORDINATES,
        );
        StripError::Unsupported { construct, error }
    }

    /// The failure as a [`Error`]: a parse error's own, or the refusal's — one
    /// type to print, span and report whichever variant it is.
    #[must_use]
    pub fn error(&self) -> &Error {
        match self {
            Self::Parse(error) | Self::Unsupported { error, .. } => error,
        }
    }

    /// What kind of failure this is: a refusal ([`ErrorKind::Refusal`]) for
    /// [`StripError::Unsupported`], and the parse error's own kind for
    /// [`StripError::Parse`] — a syntax error, a depth limit or a source over the size cap.
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        self.error().kind()
    }

    /// What went wrong, on one line and without where — [`Error::message`]: a parse error's
    /// own, or the refusal's `cannot strip …` naming the construct. Every failure has one,
    /// a source over the size cap included, and it equals [`StripError::to_report`]'s
    /// `message` whenever that is `Some`. Composed on each call (an allocated `String`).
    #[must_use]
    pub fn message(&self) -> String {
        self.error().message()
    }

    /// The failure's byte range in the source that was stripped — UTF-8 byte offsets, not
    /// the UTF-16 wire coordinates [`StripError::to_report`] gives. A parse error's is
    /// [`Error::span`] (an empty `p..p` at a syntax error or a depth limit, `None` for a
    /// source over the size cap); a refusal's is the refused construct's bytes.
    #[must_use]
    pub fn span(&self) -> Option<Range<usize>> {
        self.error().span()
    }

    /// The failure as a binding reports it — [`Error::to_report`]: `None` only for a source
    /// over the size cap; a refusal always reports.
    #[must_use]
    pub fn to_report(&self) -> Option<ErrorReport> {
        self.error().to_report()
    }
}

/// The inner [`Error`]'s own display, for both variants: one line, the frame under `{:#}`.
impl fmt::Display for StripError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.error(), f)
    }
}

// A strip's output and its failure cross threads (a loader's worker pool), a failure
// outlives the call (a boxed `dyn Error`), and both are held across a caught panic
// (`catch_unwind` around a call); pin that so a field added later cannot take it away
// unnoticed.
const _: () = {
    const fn assert_auto_traits<
        T: Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe + 'static,
    >() {
    }
    assert_auto_traits::<StripError>();
    assert_auto_traits::<Stripped>();
};

impl std::error::Error for StripError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        // transparent, as `Display` is: the inner error's own source, never itself
        std::error::Error::source(self.error())
    }
}

#[cfg(test)]
mod tests {
    use super::{StripError, UnsupportedConstruct, strip};

    fn strip_error(source: &str) -> StripError {
        match strip(source) {
            Err(error) => error,
            Ok(stripped) => panic!("expected a strip error, stripped to {:?}", stripped.code),
        }
    }

    /// A refusal's message reads like a parse error's: the construct, then the `line:col`
    /// header of the span's start (1-based column, UTF-16 units), the line, a caret.
    #[test]
    fn refusal_message_names_the_construct_at_its_point() {
        let source = "let \u{1d49c}: T = 1;\nenum E {}\n";
        let error = strip_error(source);
        assert!(matches!(
            error,
            StripError::Unsupported {
                construct: UnsupportedConstruct::Enum,
                ..
            }
        ));
        assert_eq!(error.to_string(), "cannot strip an enum (2:1)");
        assert_eq!(
            format!("{error:#}"),
            "cannot strip an enum\n2:1 enum E {}\n    ^ here"
        );
        assert_eq!(error.kind(), tsv_lang::ErrorKind::Refusal);
        assert_eq!(error.message(), "cannot strip an enum");
        let report = error.to_report().expect("a refusal reports");
        assert_eq!(report.message, error.message());
        assert_eq!(report.frame, "2:1 enum E {}\n    ^ here");
        assert_eq!((report.start.line, report.start.column), (2, 0));
    }

    /// A refusal's span is the refused construct's UTF-8 bytes — counted past a
    /// four-byte character, two UTF-16 units on the wire — and a refusal has no source.
    #[test]
    fn refusal_span_is_the_refused_bytes() {
        let source = "let \u{1d49c}: T = 1;\nenum E {}\n";
        let error = strip_error(source);
        let enum_start = source.find("enum").expect("the source holds an enum");
        assert_eq!(
            error.span(),
            Some(enum_start..enum_start + "enum E {}".len())
        );
        assert_eq!(
            &source[error.span().expect("a refusal has a span")],
            "enum E {}"
        );
        assert!(std::error::Error::source(&error).is_none());
    }

    /// A parse error's span is the inner [`Error`](tsv_lang::Error)'s own, and the variant is
    /// transparent: its `source()` is the inner error's (none), not the inner error, so a
    /// chain printer never prints the message twice.
    #[test]
    fn parse_error_span_and_source_are_the_inner_errors() {
        let source = "let \u{1d49c} = ;\n";
        let error = strip_error(source);
        let StripError::Parse(parse) = &error else {
            panic!("expected a parse error: {error:?}");
        };
        let span = error.span().expect("a syntax error has a point");
        assert_eq!(Some(span.clone()), parse.span());
        assert!(span.is_empty());
        assert_eq!(&source[span.start..], ";\n");
        assert!(std::error::Error::source(parse).is_none());
        assert!(std::error::Error::source(&error).is_none());
        assert_eq!(error.to_string(), parse.to_string());
    }

    #[test]
    fn parse_error_message_is_the_parse_errors_own() {
        let source = "let = ;\n";
        let error = strip_error(source);
        let StripError::Parse(parse) = &error else {
            panic!("expected a parse error: {error:?}");
        };
        assert_eq!(format!("{error:#}"), format!("{parse:#}"));
        assert_eq!(error.to_report(), parse.to_report());
        // the parse error's own one line, the full text's first
        assert_eq!(error.message(), parse.message());
        assert_eq!(
            format!("{error:#}").lines().next(),
            Some(error.message().as_str())
        );
        assert_eq!(
            error.to_report().expect("a syntax error reports").message,
            error.message()
        );
    }

    fn stripped(source: &str) -> String {
        match strip(source) {
            Ok(stripped) => stripped.code,
            Err(error) => panic!("expected {source:?} to strip: {error:#}"),
        }
    }

    /// The rendered parse error the strip reports for `source`, and the one the parse at
    /// `goal` reports, which it must be.
    fn parse_errors(source: &str, goal: crate::Goal) -> (String, String) {
        let StripError::Parse(stripped) = strip_error(source) else {
            panic!("expected a parse error for {source:?}");
        };
        let arena = bumpalo::Bump::new();
        let Err(parsed) = crate::__private::parse_with_goal(source, goal, &arena) else {
            panic!("expected {source:?} to fail at {goal:?}");
        };
        (stripped.to_string(), parsed.to_string())
    }

    /// With no goal named, a source the module grammar rejects is retried as a script, as
    /// the format path's parse retries it: a legacy sloppy script strips. Each expected
    /// output is ts-blank-space's, byte for byte.
    #[test]
    fn an_unset_goal_retries_a_failed_module_parse_as_a_script() {
        for (source, code) in [
            (
                "fs.chmodSync(p as string, 0755);\n",
                "fs.chmodSync(p          , 0755);\n",
            ),
            ("with (o as any) { x; }\n", "with (o       ) { x; }\n"),
            ("var await: number = 1;\n", "var await         = 1;\n"),
            ("let n = 08 as number;\n", "let n = 08          ;\n"),
            (
                "module.exports = function (mode: number = 0644) { return mode; };\n",
                "module.exports = function (mode         = 0644) { return mode; };\n",
            ),
            // the script's own hazard sites take the same `;` the module's do
            (
                "var await: any;\nawait\ntype T = 1\n(z)\n",
                "var await     ;\nawait\n;         \n(z)\n",
            ),
        ] {
            assert_eq!(stripped(source), code, "{source:?}");
        }
    }

    /// A decorated static block keeps its decorators, as any member's, and their type
    /// arguments blank; the output is ts-blank-space's, byte for byte.
    #[test]
    fn a_static_block_decorator_blanks_its_type_arguments() {
        assert_eq!(
            stripped("class A { @a<T>() static {} }\n"),
            "class A { @a   () static {} }\n"
        );
    }

    /// A `with` body is a lone statement body like an `if`'s: a statement blanked whole
    /// there becomes `;`, so the statement after it cannot become the body. ts-blank-space
    /// blanks the overload plain, which hands `f()` to the `with`.
    #[test]
    fn a_with_body_blanked_whole_becomes_an_empty_statement() {
        assert_eq!(
            stripped("with (o) type T = 1;\nf();\n"),
            "with (o) ;          \nf();\n"
        );
        assert_eq!(
            stripped("with (o) function f(): void;\nf();\n"),
            "with (o) ;                  \nf();\n"
        );
    }

    /// When both grammars reject the source, the error is the one the format path's
    /// fallback reports: the script attempt's when it reached further without dying on a
    /// module-only construct — a broken sloppy script's own typo, not the `with` the retry
    /// admits — and otherwise the module attempt's.
    #[test]
    fn a_failed_retry_reports_the_attempt_the_source_was_written_for() {
        let (stripped, script) = parse_errors("with (o) {}\nlet = ;\n", crate::Goal::Script);
        assert_eq!(stripped, script, "the sloppy script's typo");
        // a goal gate proves a module: its error is the file's own, though it sits first
        let (stripped, module) =
            parse_errors("let x: number = 0755;\nexport {};\n", crate::Goal::Module);
        assert_eq!(stripped, module, "the module's legacy octal");
        let (stripped, module) = parse_errors(
            "import type { A } from 'a';\nlet x: A = 0755;\n",
            crate::Goal::Module,
        );
        assert_eq!(stripped, module, "a type-only import is a goal gate too");
        // a script with a `"use strict"` prologue is strict at either goal: a tie, the module's
        let (stripped, module) = parse_errors(
            "\"use strict\"; let x: number = 010;\n",
            crate::Goal::Module,
        );
        assert_eq!(stripped, module, "a strict script");
    }

    /// Control: the retry runs on a module-parse failure alone, so a module-valid source
    /// strips as the module it is — a top-level `await` stays an expression.
    #[test]
    fn a_module_valid_source_is_never_read_as_a_script() {
        assert_eq!(stripped("await f() as T;\n"), "await f()     ;\n");
        assert_eq!(
            stripped("let x: number = 1;\nexport { x };\n"),
            "let x         = 1;\nexport { x };\n"
        );
    }

    /// A chain of links — members, calls, `new`, tagged templates, `!`, instantiations,
    /// `as` / `satisfies` — blanks each link's TypeScript, its operand's and its arguments',
    /// and a statement-final assertion inside one takes its `;`.
    #[test]
    fn a_chain_blanks_every_links_typescript() {
        for (source, code) in [
            (
                "x = new a.b<T>(c satisfies D)!.e;\n",
                "x = new a.b   (c            ) .e;\n",
            ),
            ("x = a!.b![\"c\"]!(d!)!;\n", "x = a .b [\"c\"] (d ) ;\n"),
            (
                "x = a<T>`q`.b<U>`r${c as D}`;\n",
                "x = a   `q`.b   `r${c     }`;\n",
            ),
            (
                "x = a.b<T>(c)<U>(d).e as F as G;\n",
                "x = a.b   (c)   (d).e          ;\n",
            ),
            (
                "x = (a as T).b(c!)?.d<E>?.(f as G);\n",
                "x = (a     ).b(c )?.d   ?.(f     );\n",
            ),
            ("x = f<T>;\n", "x = f   ;\n"),
            ("y = a.b as T\n[1].c\n", "y = a.b;    \n[1].c\n"),
            (
                "class C { p = a.b as T\n[k]: number = 1 }\n",
                "class C { p = a.b;    \n[k]         = 1 }\n",
            ),
        ] {
            assert_eq!(stripped(source), code, "{source:?}");
        }
    }

    /// The same chains under twenty more links, past the links a recursion walks
    /// (`CHAIN_FRAMES` in `walk.rs`): their links are walked by the chain loop, which blanks
    /// them as the recursion does.
    #[test]
    fn a_chain_past_the_recursion_blanks_as_the_recursion_does() {
        let links = ".z".repeat(20);
        for (chain, code) in [
            (
                "new a.b<T>(c satisfies D)!.e",
                "new a.b   (c            ) .e",
            ),
            ("a!.b![\"c\"]!(d!)!", "a .b [\"c\"] (d ) "),
            ("a<T>`q`.b<U>`r${c as D}`", "a   `q`.b   `r${c     }`"),
            (
                "(a.b<T>(c)<U>(d).e as F as G)",
                "(a.b   (c)   (d).e          )",
            ),
            (
                "(a as T).b(c!)?.d<E>?.(f as G)",
                "(a     ).b(c )?.d   ?.(f     )",
            ),
            ("a[b as K]!.c", "a[b     ] .c"),
            ("(a satisfies T).b", "(a            ).b"),
        ] {
            let source = format!("x = {chain}{links};\n");
            assert_eq!(
                stripped(&source),
                format!("x = {code}{links};\n"),
                "{source:?}"
            );
        }
    }

    /// An assertion's grouping check runs before its operand is walked, so a refusal inside
    /// the operand starting where the assertion does is not the one reported: the
    /// assertion's is, over its whole span. On the recursion path: a chain past
    /// `CHAIN_FRAMES` holds no assertion a binary operator follows, so none of its
    /// assertions regroups.
    #[test]
    fn a_chain_assertion_is_refused_before_its_operand_is_walked() {
        let source = "x = <T>a + b as U * c;\n";
        let error = strip_error(source);
        let StripError::Unsupported { construct, .. } = &error else {
            panic!("expected a refusal");
        };
        assert_eq!(*construct, UnsupportedConstruct::AssertionGrouping);
        assert_eq!(
            &source[error.span().expect("a refusal has a span")],
            "<T>a + b as U"
        );
    }

    /// A chain over a thousand links long strips on a small stack: its links cost heap, not
    /// a frame each.
    #[test]
    fn a_long_chain_strips_without_a_frame_per_link() {
        let source = format!("x = a{}{};\n", ".b!".repeat(1000), " as T".repeat(100));
        let stripped = std::thread::Builder::new()
            .stack_size(256 << 10)
            .spawn(move || {
                strip(&source)
                    .map(|stripped| stripped.code)
                    .map_err(|error| format!("{error:#}"))
            })
            .expect("spawn")
            .join()
            .expect("the strip ran");
        let expected = format!("x = a{}{};\n", ".b ".repeat(1000), " ".repeat(500));
        assert_eq!(stripped, Ok(expected));
    }

    #[test]
    fn every_construct_has_a_snake_case_name() {
        for (construct, name) in [
            (UnsupportedConstruct::Enum, "enum"),
            (UnsupportedConstruct::ValueNamespace, "value_namespace"),
            (
                UnsupportedConstruct::ParameterProperty,
                "parameter_property",
            ),
            (UnsupportedConstruct::ImportEquals, "import_equals"),
            (UnsupportedConstruct::ExportEquals, "export_equals"),
            (UnsupportedConstruct::TypeAssertion, "type_assertion"),
            (
                UnsupportedConstruct::AssertionGrouping,
                "assertion_grouping",
            ),
        ] {
            assert_eq!(construct.as_str(), name);
            assert!(!construct.description().is_empty());
        }
    }
}