Skip to main content

bynk_ts/
program.rs

1//! [`TsProgram`]/[`TsStmt`] — the tree. P7.5 built it wide enough only for
2//! the `Verbatim` escape hatch (Q2, `design/tracks/the-typescript-tree.md`
3//! §3.2). P7.8 (#1313) adds the real node algebra ([`TsExpr`]/[`TsType`]/
4//! [`TsDecl`], plus real [`TsStmt`] variants) — not the full §7.1 reference
5//! sketch as literally written (a variant-name list with almost no
6//! field-level design), but the subset `bynk-emit/src/emitter/
7//! events_fanout.rs` (Arc C's real next file — P7.8's own proposal
8//! corrected the track doc's stale schedule, see `design/tracks/
9//! the-typescript-tree.md` §6/§9) concretely needs, grounded against that
10//! file's own real shape rather than guessed. Building the rest of the
11//! sketch's unvalidated variants now would repeat the exact "guessing, not
12//! designing" risk `bynk-ts`'s own module doc (`lib.rs`) already named for
13//! this layer — Arc C's later slices add more variants file by file, the
14//! same precedent [`VerbatimOrigin`] already set.
15
16use crate::source_map::SourceMapBuilder;
17use bynk_syntax::span::Span;
18
19/// A whole generated TypeScript module, as an ordered sequence of top-level
20/// statements. `Vec<TsStmt>`, plain — no richer container yet (P7.6's own
21/// `Artefacts { docs: BTreeMap<PathBuf, Document> }` is where a *project's*
22/// documents get keyed; this is one document's own tree).
23#[derive(Debug, Default)]
24pub struct TsProgram {
25    pub stmts: Vec<TsStmt>,
26}
27
28impl TsProgram {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn push(&mut self, stmt: TsStmt) {
34        self.stmts.push(stmt);
35    }
36
37    /// Every `TsStmtKind::Verbatim`/[`TsExpr::VerbatimExpr`] leaf's own
38    /// text, tagged by its [`VerbatimOrigin`] — found by walking every
39    /// statement/expression container in the tree, not just the top level.
40    /// #1538's own real gap: nothing before this walked a whole `TsProgram`
41    /// to find every opaque leaf nested inside real structured content (a
42    /// `Verbatim` inside an `if` branch, a `VerbatimExpr` inside a `Call`'s
43    /// arguments, …) — the only prior way to inspect a `Verbatim`'s content
44    /// was scanning the *whole printed document* text
45    /// ([`crate::verbatim_violations`] doesn't distinguish opaque text from
46    /// a real node's own printed output), which also flags real, structured
47    /// nodes that happen to print the substring `any` (`TsType::named("any")`
48    /// residue, tracked separately by `xtask`'s own `ts_any` probe) — a
49    /// false positive for *this* check, whose whole point is the opaque
50    /// escape hatch specifically. `TsStmtKind` is `pub(crate)`, so only code
51    /// inside this crate can walk it directly; this method is the public
52    /// surface a caller outside `bynk-ts` (`bynkc`'s own
53    /// `tests/tsc_verify.rs`) uses instead.
54    ///
55    /// Every container is walked exhaustively (`match`, no wildcard arm) so
56    /// a future `TsStmt`/`TsExpr` variant fails to compile here until this
57    /// walker accounts for it — the same "compile-time construct, not a
58    /// grep" discipline [`VerbatimOrigin`]'s own doc already states for
59    /// itself. `TsStmtKind::Raw` is deliberately not walked into any
60    /// deeper than skipped: it carries no `VerbatimOrigin` at all (ADR
61    /// `arc-c-lower-rs-permanent-exclusion`'s own permanent exclusion, a
62    /// different bucket from `Verbatim`'s temporary conversion residue), so
63    /// it has nothing this method could report. [`TsType`] positions are
64    /// never walked — no `TsType` variant can hold a `Verbatim`/
65    /// `VerbatimExpr` leaf, so there is nothing to find there.
66    ///
67    /// **A real gap this walker exposed (#1538):** no `VerbatimOrigin::Emit`
68    /// leaf can currently reach a `TsProgram` returned from `bynk-emit` at
69    /// all. Every real `bynk-emit/src/emitter/emit.rs` construction site
70    /// builds a [`TsExpr::VerbatimExpr`], immediately prints it
71    /// (`crate::print_expr`/`crate::print_stmt`), and splices the resulting
72    /// text into a plain `String` a caller further up wraps in
73    /// `TsStmtKind::Raw` — not tagged with a `VerbatimOrigin` at all, and
74    /// so invisible to this walker by design (see `TsStmtKind::Raw`'s own
75    /// doc). `VerbatimExpr`'s own doc promises this content is "visible to
76    /// `crate::verbatim_violations`"; today that's only true at the instant
77    /// of construction, not once the surrounding document is returned —
78    /// closing it needs a real Arc C conversion slice, not a change here.
79    pub fn verbatim_content(&self) -> Vec<(VerbatimOrigin, &str)> {
80        let mut out = Vec::new();
81        for stmt in &self.stmts {
82            walk_stmt(stmt, &mut out);
83        }
84        out
85    }
86}
87
88fn walk_stmt<'a>(stmt: &'a TsStmt, out: &mut Vec<(VerbatimOrigin, &'a str)>) {
89    match &stmt.kind {
90        TsStmtKind::Verbatim { origin, text } => out.push((*origin, text.as_str())),
91        TsStmtKind::Decl(decl) => walk_decl(decl, out),
92        TsStmtKind::Const { init, .. } => walk_expr(init, out),
93        TsStmtKind::Let { init, .. } => {
94            if let Some(e) = init {
95                walk_expr(e, out);
96            }
97        }
98        TsStmtKind::ExprStmt(e) => walk_expr(e, out),
99        TsStmtKind::Return(e) => {
100            if let Some(e) = e {
101                walk_expr(e, out);
102            }
103        }
104        TsStmtKind::Throw(e) => walk_expr(e, out),
105        TsStmtKind::If {
106            cond,
107            then_branch,
108            else_branch,
109            same_line_else: _,
110        } => {
111            walk_expr(cond, out);
112            walk_stmt(then_branch, out);
113            if let Some(e) = else_branch {
114                walk_stmt(e, out);
115            }
116        }
117        TsStmtKind::ForOf {
118            binding: _,
119            iter,
120            body,
121        } => {
122            walk_expr(iter, out);
123            walk_stmt(body, out);
124        }
125        TsStmtKind::For {
126            name: _,
127            init,
128            test,
129            body,
130        } => {
131            walk_expr(init, out);
132            walk_expr(test, out);
133            walk_stmt(body, out);
134        }
135        TsStmtKind::TryCatch {
136            try_block,
137            catch_param: _,
138            catch_block,
139        } => {
140            walk_stmt(try_block, out);
141            walk_stmt(catch_block, out);
142        }
143        TsStmtKind::Block(stmts) | TsStmtKind::InlineBlock(stmts) => {
144            for s in stmts {
145                walk_stmt(s, out);
146            }
147        }
148        TsStmtKind::Continue => {}
149        TsStmtKind::Assign { target, value } => {
150            walk_expr(target, out);
151            walk_expr(value, out);
152        }
153        TsStmtKind::Comment(_) | TsStmtKind::DocComment(_) | TsStmtKind::Blank => {}
154        TsStmtKind::Switch {
155            discriminant,
156            cases,
157        } => {
158            walk_expr(discriminant, out);
159            for case in cases {
160                if let Some(t) = &case.test {
161                    walk_expr(t, out);
162                }
163                for s in &case.body {
164                    walk_stmt(s, out);
165                }
166            }
167        }
168        TsStmtKind::Increment(e) => walk_expr(e, out),
169        TsStmtKind::Raw(_) => {}
170    }
171}
172
173fn walk_decl<'a>(decl: &'a TsDecl, out: &mut Vec<(VerbatimOrigin, &'a str)>) {
174    match decl {
175        TsDecl::Import { .. }
176        | TsDecl::ImportNamespace { .. }
177        | TsDecl::ImportDefault { .. }
178        | TsDecl::ReExport { .. }
179        | TsDecl::ExportNames { .. }
180        | TsDecl::ReExportAll { .. }
181        | TsDecl::Interface { .. }
182        | TsDecl::TypeAlias { .. }
183        | TsDecl::DeclareConst { .. } => {}
184        TsDecl::Export(inner) => walk_decl(inner, out),
185        TsDecl::ConstDecl { init, .. } => walk_expr(init, out),
186        TsDecl::Class {
187            name: _,
188            fields: _,
189            constructor,
190            methods,
191        } => {
192            if let Some(ctor) = constructor {
193                for s in &ctor.body {
194                    walk_stmt(s, out);
195                }
196            }
197            for m in methods {
198                for s in &m.body {
199                    walk_stmt(s, out);
200                }
201            }
202        }
203        TsDecl::Function { body, .. } => {
204            for s in body {
205                walk_stmt(s, out);
206            }
207        }
208        TsDecl::ExportDefault(e) => walk_expr(e, out),
209    }
210}
211
212fn walk_arrow_body<'a>(body: &'a TsArrowBody, out: &mut Vec<(VerbatimOrigin, &'a str)>) {
213    match body {
214        TsArrowBody::Expr(e) => walk_expr(e, out),
215        TsArrowBody::Block(stmts) => {
216            for s in stmts {
217                walk_stmt(s, out);
218            }
219        }
220    }
221}
222
223fn walk_object_entry<'a>(entry: &'a TsObjectEntry, out: &mut Vec<(VerbatimOrigin, &'a str)>) {
224    match entry {
225        TsObjectEntry::Prop(_, v) => walk_expr(v, out),
226        TsObjectEntry::Shorthand(_) => {}
227        TsObjectEntry::Method { body, .. } => {
228            for s in body {
229                walk_stmt(s, out);
230            }
231        }
232        TsObjectEntry::Spread(e) => walk_expr(e, out),
233    }
234}
235
236fn walk_expr<'a>(expr: &'a TsExpr, out: &mut Vec<(VerbatimOrigin, &'a str)>) {
237    match expr {
238        TsExpr::Ident(_) => {}
239        TsExpr::VerbatimExpr(text, origin) => out.push((*origin, text.as_str())),
240        TsExpr::Member { object, .. } | TsExpr::OptionalMember { object, .. } => {
241            walk_expr(object, out);
242        }
243        TsExpr::Index { object, index } | TsExpr::OptionalIndex { object, index } => {
244            walk_expr(object, out);
245            walk_expr(index, out);
246        }
247        TsExpr::Arrow { body, .. } => walk_arrow_body(body, out),
248        TsExpr::Call { callee, args } | TsExpr::New { callee, args } => {
249            walk_expr(callee, out);
250            for a in args {
251                walk_expr(a, out);
252            }
253        }
254        TsExpr::Object { entries, .. } => {
255            for e in entries {
256                walk_object_entry(e, out);
257            }
258        }
259        TsExpr::Array { items, .. } => {
260            for i in items {
261                walk_expr(i, out);
262            }
263        }
264        TsExpr::TemplateLit { parts: _, exprs } => {
265            for e in exprs {
266                walk_expr(e, out);
267            }
268        }
269        TsExpr::Await(e) => walk_expr(e, out),
270        TsExpr::As { expr, ty: _ } => walk_expr(expr, out),
271        TsExpr::Unary { op: _, expr } => walk_expr(expr, out),
272        TsExpr::Binary { op: _, left, right } => {
273            walk_expr(left, out);
274            walk_expr(right, out);
275        }
276        TsExpr::Conditional {
277            test,
278            consequent,
279            alternate,
280        } => {
281            walk_expr(test, out);
282            walk_expr(consequent, out);
283            walk_expr(alternate, out);
284        }
285        TsExpr::Paren(e) => walk_expr(e, out),
286        TsExpr::Lit(_) => {}
287    }
288}
289
290/// One name a statement exports ([`TsStmt::exported_names`]).
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub struct ExportedName<'a> {
293    /// The exported name (an `X as Y` entry's `Y`).
294    pub name: &'a str,
295    /// Whether the statement exports a value under the name, as a `const`,
296    /// `function` or `class` does, or only a type, as an `interface`, a
297    /// `type` alias or a `type X` list entry does.
298    pub has_value: bool,
299}
300
301/// One statement — a `Verbatim`-tagged escape hatch (still constructible
302/// only via [`TsStmt::verbatim`], per #1307's Decision D — the
303/// `verbatim_sites` probe needs exactly one string to line-scan for), or,
304/// from this slice, a real structured kind. The real kinds have no such
305/// sealing: they're normal typed constructors, not a "wrap opaque text"
306/// escape hatch, so the `verbatim_sites` concern that motivates `verbatim`'s
307/// own single-constructor discipline doesn't apply to them.
308#[derive(Debug, Clone)]
309pub struct TsStmt {
310    pub(crate) kind: TsStmtKind,
311    /// Where this statement's content originated in the `.bynk` source, if
312    /// known. Only a *top-level* statement's own span is currently recorded
313    /// as a source-map checkpoint ([`crate::printer::print`], unchanged
314    /// from P7.5/R7.4's own scope) — a nested statement (inside a `Block`,
315    /// `If`, `ForOf`, `TryCatch`) still carries this field structurally, for
316    /// whichever future slice gives sub-statement source maps real value,
317    /// but the printer does not yet record a checkpoint from it. Named here
318    /// explicitly (P7.8's own accepted proposal: "an implementation-time
319    /// call within this same shape") rather than left ambiguous.
320    pub span: Option<Span>,
321    /// #1477's own real gap: a body-bearing statement — in practice always
322    /// a `TsStmtKind::Raw`/`TsStmtKind::Verbatim` opaque blob standing in
323    /// for a lowered function/method body (ADR 0391's own permanent
324    /// exclusion) — carries its *own* per-statement source-map checkpoints,
325    /// collected by the caller's own body-local `SourceMapBuilder` before
326    /// this node existed. Before this field, every real `bynk-emit` caller
327    /// that needed to merge those checkpoints into its own module map had to
328    /// reverse-engineer this node's own print-time byte offset from the
329    /// *outside* — `bynk-emit`'s own `emit_class_method_and_merge_source_map`
330    /// (`emitter/emit.rs`) recovers it by subtracting known lengths and
331    /// string-matching the printed text's own tail, degrading to a silent
332    /// skip if that search fails; still live for `emit_service`/`emit_agent`'s
333    /// own not-yet-converted call sites (#1481/#1482). `emit_free_fn` used to
334    /// recover it by separate, independent exact arithmetic, guarded by a
335    /// `debug_assert!` — #1480 converted it to set this field directly
336    /// instead, the first real `bynk-emit` caller to do so. Both existed
337    /// only because nothing reported *this* node's own real print-time
338    /// offset directly. Setting this field lets the printer itself do the
339    /// merge, at the exact offset it is about to write this node's text to
340    /// — no reverse-engineering, no silent-skip fallback (see this crate's
341    /// own private `printer::render_block_stmts` for the handling). `None`
342    /// for every real site that predates this field and every node whose own
343    /// text carries no nested checkpoints of its own — the overwhelmingly
344    /// common case, and the reason this is an `Option`, not a required
345    /// field.
346    pub nested_map: Option<SourceMapBuilder>,
347    /// #1486's own second real gap, found converting `emit_test_module`/
348    /// `emit_integration_module`: [`crate::printer::print`]'s own top-level
349    /// loop always merges a statement's [`nested_map`](Self::nested_map)
350    /// against parent source id `0` (`crate::printer::MergeTarget`'s own
351    /// review-of-#1488 fix threads a `source_id` through every *manual*
352    /// merge entry point, but `print`'s own automatic top-level case never
353    /// had a per-statement way to say "not 0") — correct for every
354    /// single-source module (`emit_project`, every other real caller so
355    /// far), but wrong for a test/integration module's own aggregate map,
356    /// which registers one source per fragment file a case's body came from
357    /// (`SourceMapBuilder::add_source`) and needs each such case's own
358    /// top-level statement merged against *that* source's id, not the
359    /// module's primary one. `0` (every site predating this field, and
360    /// every single-source module after it) keeps the automatic policy
361    /// exactly as it already was; a case/property/attack wrapper statement
362    /// sets this to its own registered source id before `print` sees it.
363    pub nested_map_source_id: usize,
364    /// #1486's own real gap, found converting `emit_project`/`emit_test_
365    /// module`/`emit_integration_module` off a single opaque top-level
366    /// `Verbatim` wrap: [`crate::printer::print`]'s own top-level loop
367    /// inserts exactly one blank line between every pair of adjacent
368    /// top-level statements (its own "readability policy" doc, right below
369    /// this field's own use site) — correct for content that was always
370    /// designed against that policy (`emit_composition_root`/`emit_test_
371    /// main`/`workers.rs`/`workers_entry.rs`, every one of them zero-diff
372    /// from day one), but `emit_agent`'s own already-shipped `Vec<TsStmt>`
373    /// (#1482, predating this field) was built against the *previous*
374    /// regime — where every real caller printed via `bynk-emit`'s own
375    /// `extend_printed`/`extend_printed_and_merged` (a flat per-stmt loop
376    /// with no automatic spacing of its own) — and genuinely needs a
377    /// same-registry-then-zero-factory pairing with **no** blank line
378    /// between them, matching the pre-conversion hand-written text this
379    /// crate's own zero-diff discipline requires preserving exactly.
380    /// `true` on a statement suppresses the automatic blank line
381    /// [`crate::printer::print`] would otherwise insert immediately before
382    /// it — the narrow, general escape hatch this real, already-shipped
383    /// content needs, not a special case hard-coded into the printer for
384    /// one specific pair of `TsDecl` variants. `false` (every site
385    /// predating this field, and the overwhelming majority after it) keeps
386    /// the automatic policy exactly as it already is.
387    pub no_blank_before: bool,
388}
389
390#[derive(Debug, Clone)]
391pub(crate) enum TsStmtKind {
392    Verbatim {
393        // Read by `TsProgram::verbatim_content` (#1538) to attribute each
394        // opaque leaf's text to its origin file.
395        origin: VerbatimOrigin,
396        text: String,
397    },
398    /// A top-level declaration ([`TsDecl`]) printed as a statement — the
399    /// bridge between `TsProgram`'s flat `Vec<TsStmt>` and the reference
400    /// sketch's separate `TsDecl` enum (an `import`/`interface`/top-level
401    /// `const`/`class` *is* one kind of top-level statement in this tree,
402    /// not a different container).
403    Decl(TsDecl),
404    /// A local `const` binding, e.g. `const { events } = ...;` or
405    /// `const subs = ...;` — distinct from [`TsDecl::ConstDecl`], which is
406    /// the top-level form. Carries a real destructuring [`TsBindingName`]
407    /// because `events_fanout.rs`'s own `const { events } = ...` needs one
408    /// (a gap beyond the accepted proposal's own variant list — a bare
409    /// `String` name cannot represent it; named explicitly as a deviation,
410    /// not invented silently).
411    Const {
412        name: TsBindingName,
413        ty: Option<TsType>,
414        init: TsExpr,
415    },
416    /// `let`'s sibling to `Const` — unused by `events_fanout.rs` itself, but
417    /// the `const`/`let` distinction is real TypeScript semantics the
418    /// printer must preserve once one of the pair exists (the accepted
419    /// proposal's own reasoning for keeping it).
420    Let {
421        name: TsBindingName,
422        ty: Option<TsType>,
423        init: Option<TsExpr>,
424    },
425    /// An expression used as a whole statement (a bare call, e.g.).
426    ExprStmt(TsExpr),
427    Return(Option<TsExpr>),
428    /// `throw <expr>;` — #1353's own real gap: `emit_contract_guarded_body`'s
429    /// own precondition/postcondition guards (`bynk-emit/src/emitter/
430    /// emit.rs`) each throw a constructed `Error` on violation — no prior
431    /// slice needed a bare `throw` (every other error-signalling site in
432    /// this tree so far has been a `Return`). Mirrors `Return`'s own shape
433    /// exactly, minus the `Option` (a `throw` always carries a value; there
434    /// is no bare `throw;` in JS/TS).
435    Throw(TsExpr),
436    /// `if (cond) <then_branch>` (optionally `else <else_branch>`).
437    /// `then_branch`/`else_branch` may each be a [`TsStmtKind::Block`]
438    /// (printed with braces) or any other single statement (printed inline
439    /// on the same line, matching `if (!Array.isArray(subs)) continue;`'s
440    /// own real, brace-free shape). `else_branch` is #1323's own real gap:
441    /// `workers_entry.rs`'s queue-consumer ack/retry dispatch (`if
442    /// (result.tag === "Ack") msg.ack(); else { ...; msg.retry(); }`) —
443    /// `events_fanout.rs`'s own grounding never used one, so P7.8 named
444    /// omitting it a deliberate choice, not an oversight; this slice's own
445    /// real content needs it for real.
446    ///
447    /// `same_line_else` is #1325's own real gap: `workers_entry.rs`'s own
448    /// real `else` sits on its own fresh line (`}\nelse {`), but
449    /// `emit_test_main`'s own real content wants the conventional `} else
450    /// {` — two already-real files disagreeing on the same construct, the
451    /// same class of tension the `Await`-under-`As` correction (#1323/
452    /// #1324) found for parenthesisation. `false` (fresh line) is the
453    /// existing, already-tested default via [`TsStmt::if_else_stmt`]; `true`
454    /// (same line) is reached only through
455    /// [`TsStmt::if_else_same_line_stmt`].
456    If {
457        cond: TsExpr,
458        then_branch: Box<TsStmt>,
459        else_branch: Option<Box<TsStmt>>,
460        same_line_else: bool,
461    },
462    /// `for (const <binding> of <iter>) <body>`.
463    ForOf {
464        binding: String,
465        iter: TsExpr,
466        body: Box<TsStmt>,
467    },
468    /// `for (let <name> = <init>; <test>; <name>++) <body>` — a C-style
469    /// indexed loop, `ForOf`'s counterpart for index-based iteration (as
470    /// opposed to `for...of`'s element-based iteration over an existing
471    /// collection). Arc E slice 7 (#1447)'s own real, narrow gap:
472    /// `bynk-emit`'s `serialisation.rs` has two real sites — `ListInst`'s
473    /// and `MapInst`'s own deserialise-side element loops, both `for (let i
474    /// = 0; i < json.length; i++) { ... }` — that walk a JSON array by
475    /// index, a shape `ForOf` cannot represent (its own `binding` names a
476    /// per-element destructuring target bound fresh each iteration, not a
477    /// counter carrying its own init/test/update clauses across
478    /// iterations). Deliberately grounded in only what those two real call
479    /// sites need, not the general C-style-for grammar — the same "extend
480    /// narrowly" posture this file's own `TsBinaryOp::In`/`LessThan`
481    /// additions already took:
482    ///   - `name`/`init` are always a plain `let <name> = <init>;`
483    ///     declaration — no destructuring, no multi-declarator list, no
484    ///     explicit type annotation (neither real site needs one).
485    ///   - The update clause always renders as the postfix increment
486    ///     `<name>++`, over `name` itself rather than a separate field —
487    ///     review of #1448 found an independent `update: TsExpr` field
488    ///     structurally redundant with `name` (both real construction sites
489    ///     could only ever pass `ident(name)`) with a genuinely dangerous
490    ///     failure mode if the two ever disagreed: unlike a wrong `test`
491    ///     (which `tsc --strict` or a non-running loop tends to surface), a
492    ///     mismatched update clause (`for (let i = 0; i < json.length;
493    ///     j++)`) compiles cleanly whenever `j` is merely in scope and hangs
494    ///     the generated worker at runtime, with nothing in the type, the
495    ///     printer, or a test to catch it. Removing the field removes the
496    ///     failure mode entirely rather than merely asserting against it —
497    ///     the same "postfix increment has no expression-position
498    ///     representation, only a dedicated statement/clause shape"
499    ///     restriction `Increment`'s own doc above already states for a
500    ///     bare `<expr>++;` statement (#1325), applied here too.
501    ///   - `body` is the loop body; both real sites pass a `Block`, though
502    ///     the same brace-vs-inline rendering `If`/`ForOf` already share
503    ///     applies to any other shape too.
504    For {
505        name: String,
506        init: TsExpr,
507        test: TsExpr,
508        body: Box<TsStmt>,
509    },
510    /// `try <try_block> catch (<catch_param>) <catch_block>` — a real gap
511    /// beyond the reference sketch (`design/bynk-greenfield-compiler.md`'s
512    /// §7.1 has no `TryCatch` at all), found and named by P7.8's own
513    /// accepted proposal: `events_fanout.rs`'s subscriber-failure-isolation
514    /// `try`/`catch` (ADR 0284) is load-bearing control flow, not
515    /// decorative. `catch_param: None` prints the bare `catch { ... }`
516    /// form (ES2019's optional catch binding) — #1321's own real gap:
517    /// `workers.rs`'s `emit_http_sum_wrapper` reads the raw request body in
518    /// a `try`/`catch` that never uses the caught error (`} catch {`, no
519    /// `(e)` at all).
520    TryCatch {
521        try_block: Box<TsStmt>,
522        catch_param: Option<String>,
523        catch_block: Box<TsStmt>,
524    },
525    /// `{ <stmts> }` — the body container for `If`/`ForOf`/`TryCatch`/
526    /// constructor and method bodies.
527    Block(Vec<TsStmt>),
528    /// A bare `continue;` — a second real gap beyond the accepted
529    /// proposal's own variant list: `events_fanout.rs` uses it twice
530    /// (`if (!Array.isArray(subs)) continue;` / `if (!binding) continue;`),
531    /// load-bearing loop control the accepted proposal's `TsStmt` list
532    /// doesn't name. No label — nothing in the grounding file needs one.
533    Continue,
534    /// `target = value;` — a third real gap, found in review of the
535    /// implementing PR (#1313): `events_fanout.rs`'s own constructor body is
536    /// exactly one statement, `this.env = (env ?? {}) as
537    /// Record<string, ServiceBinding>;` (a field assignment, not a `const`/
538    /// `let` binding), which the accepted proposal's own grounding
539    /// catalogue missed — it catalogued the `fetch` method's body in detail
540    /// but not the constructor's. `target` is deliberately a full `TsExpr`
541    /// (not a narrower "assignable" type) so it can hold `this.env` (a
542    /// `Member` expression) without a second binding-target type; nothing
543    /// about `Assign` validates that `target` is actually assignable
544    /// (`bynk-check` already does that on the `.bynk` side before emission
545    /// ever runs).
546    Assign {
547        target: TsExpr,
548        value: TsExpr,
549    },
550    /// `// <text>` — a bare line comment. Added for Arc C's own first real
551    /// conversion slice (#1317): every `bynk-emit`-generated `.ts` file
552    /// opens with the same two-line header banner
553    /// (`// Generated by bynkc — do not edit by hand.` / a file-specific
554    /// second line), and nothing before this slice could represent one.
555    /// Not speculative — a universal need every later Arc C slice hits on
556    /// its own first line, closed once here rather than left as a residual
557    /// `Verbatim` wrap that would make `verbatim_sites` show zero
558    /// improvement for real, substantial conversion work.
559    ///
560    /// Carries no semantic content the printer or checker ever reads back —
561    /// pure, inert text. Printed one `// `-prefixed line per `\n` in `text`
562    /// (`bynk-ts/src/printer.rs`'s own `render_stmt`), so a multi-line
563    /// comment is representable as one statement, though
564    /// `events_fanout.rs`'s own two-line header is built as two separate
565    /// `Comment` statements instead — matching how its two adjacent
566    /// `import` lines are two separate `TsDecl::Import` statements, not one
567    /// with an embedded line break, and exercising the printer's own new
568    /// "no blank line between adjacent `Comment`s" rule (the same
569    /// exception already established for adjacent `import`s).
570    Comment(String),
571    /// `/** ... */` — a JSDoc block comment, distinct from
572    /// [`TsStmtKind::Comment`]'s own `//`-per-line form. #1333's own real
573    /// need: `emit_doc_block` (`bynk-emit/src/emitter/emit.rs`) renders a
574    /// Bynk `///` doc comment as a real JSDoc block — printed via
575    /// [`crate::printer::print_stmt`], not [`crate::printer::print`], since
576    /// every real call site today is a shared helper spliced into a
577    /// still-unconverted caller's own buffer, the same P7.9 pattern
578    /// `ts_type_ref`/`ts_ty` already used (keep the caller's own signature,
579    /// build a real node internally, print just that fragment). Escaping
580    /// (a literal `*/` inside the text becomes `*\/`, so it can't
581    /// prematurely close the comment and let trailing text land as
582    /// executable top-level TypeScript — issue #720) and the blank-line
583    /// convention (a blank source line prints as a bare ` *`, no trailing
584    /// space) live in the printer (`render_stmt`'s own `DocComment` arm,
585    /// `crate::printer`'s own private renderer), matching
586    /// where every other statement kind's rendering rules live.
587    DocComment(String),
588    /// A bare blank line — no statement content. #1323's own real, narrow
589    /// need: `workers_entry.rs`'s `fetch` method body has an unconditional
590    /// blank line after its internal Service-Binding dispatch block, and a
591    /// conditional one after the WebSocket-upgrade dispatch (when present)
592    /// and the Events dispatch (when present) — three specific points the
593    /// pre-conversion `writeln!(out).unwrap()` wrote directly, nested
594    /// *inside* the `try` block's own statement list. Distinct from
595    /// [`crate::printer::print`]'s own top-level blank-line policy (this
596    /// module's own printer doc), which only separates `TsProgram`'s own
597    /// top-level statements — nothing before this slice needed a blank line
598    /// anywhere inside a nested block, so that policy was never generalized
599    /// to every nesting depth. A single, narrow statement kind represents
600    /// exactly this, rather than widening the top-level-only policy to a
601    /// depth it has no other real content to justify.
602    Blank,
603    /// `switch (<discriminant>) { <cases> }` — #1323's own largest gap: the
604    /// first genuinely new statement-*grouping* construct in this tree
605    /// (every prior addition was a single expression/type variant or a
606    /// straightforward one-block wrapper). `workers_entry.rs` has four real
607    /// `switch` statements (the internal `/_bynk/call/` and `/_bynk/event/`
608    /// dispatches, the `scheduled` handler's `event.cron` dispatch, the
609    /// `queue` handler's `batch.queue` dispatch); every real `case` there is
610    /// a `{ ... }`-blocked body ending in a terminal statement (`return`/
611    /// `continue`), so no fallthrough/shared-body grouping is represented —
612    /// extend narrowly, the same posture every other addition here takes.
613    /// Arc E slice 6 (#1445) widens this one further, narrowly: a
614    /// non-`default` case's own bracing is now per-case
615    /// ([`TsSwitchCase::case_braced`]) rather than unconditional —
616    /// `emit_sum_codec`'s own payload-free-variant case is real, unbraced
617    /// content, not a hypothetical.
618    Switch {
619        discriminant: TsExpr,
620        cases: Vec<TsSwitchCase>,
621    },
622    /// `{ stmt; stmt; ... }` — a braced, multi-statement block printed on
623    /// ONE generated line, distinct from [`TsStmtKind::Block`] (always
624    /// multi-line). #1323's own real gap: `workers_entry.rs`'s queue
625    /// consumer has two real sites (`if (__r.tag === "Err") { console.
626    /// error(...); msg.retry(); continue; }`; the `else` branch of the
627    /// ack/retry dispatch) where the pre-conversion `writeln!` code
628    /// deliberately packed several short statements onto one physical
629    /// line — a real, distinct formatting choice from every other
630    /// multi-statement body in this tree, which always prints one
631    /// statement per line. Only reachable through [`TsStmt::if_stmt`]/
632    /// [`TsStmt::if_else_stmt`]'s own branches in real content today.
633    InlineBlock(Vec<TsStmt>),
634    /// `<expr>++;` — a postfix increment used as a whole statement. #1325's
635    /// own real, narrow gap: `emit_test_main`'s own `passed++;`/`failed++;`
636    /// counters. No prefix form, no decrement, no expression-position use
637    /// (every real site increments a bare counter as its own statement) —
638    /// [`TsExpr::Unary`] stays prefix-only (`!`/`typeof`), since a postfix
639    /// operator used as a *statement* is a different grammatical position
640    /// from a prefix operator used as an *operand*, not a shape `Unary`
641    /// could represent by adding a variant.
642    Increment(TsExpr),
643    /// A pre-rendered, unconditional-passthrough statement blob — printed
644    /// exactly as given, with no leading indent, no added semicolon, no
645    /// added braces (matching [`TsStmtKind::Verbatim`]'s own `out.push_str(
646    /// text)` rendering, not the ordinary per-kind `indent(depth)`-prefixed
647    /// shape every other variant gets). #1337's own real need:
648    /// `emit_method`'s own body is delegated wholesale to
649    /// `emit_block_as_function_body_with_return` (`bynk-emit`'s
650    /// `emitter/lower.rs:201`) — the one splice boundary ADR
651    /// `arc-c-lower-rs-permanent-exclusion` names as a *permanent*,
652    /// deliberate exclusion from this tree (`lower.rs` is the compiler's
653    /// own second code-generation pass, comprehensive language-surface
654    /// work Arc C was never scoped to cover), not a not-yet-converted
655    /// residue [`TsStmtKind::Verbatim`] would misrepresent it as.
656    ///
657    /// Deliberately a SEPARATE variant from `Verbatim`, not a reuse of it,
658    /// even though both render identically (`out.push_str(text)`): the
659    /// `verbatim_sites`/`verbatim_origins` probes exist specifically to
660    /// track Arc C's own *temporary* conversion residue trending toward
661    /// zero — a `Raw` site is never counted there (it has no
662    /// `VerbatimOrigin` at all), because using `Verbatim` here would make
663    /// this permanent exclusion look like unfinished Arc C work a future
664    /// slice is expected to close, which it structurally cannot.
665    ///
666    /// #1339's own second real use, broadening (not narrowing) the
667    /// above: `emit_refined_type`'s own `of()` guard block splices
668    /// `emit_refined_checks`'s own output this same way — that function
669    /// keeps its exact `out: &mut String` signature (the P7.9/step-1
670    /// pattern applied one level down, not a `lower.rs`-style permanent
671    /// exclusion), but its real content is ALREADY built and printed from
672    /// real `bynk_ts::TsStmt`/`print_stmt` calls internally — genuinely
673    /// statement-shaped pre-rendered text, the same mechanical fit `Raw`
674    /// already provides, just for a different underlying reason than
675    /// `lower.rs`'s own permanent exclusion.
676    ///
677    /// #1445's own third real use (Arc E slice 6, `serialisation.rs`'s
678    /// `emit_sum_codec`, via that file's own `raw_stmts_at_depth_one`
679    /// helper): a real, currently-shipped BYTE-LEVEL quirk, not a scope
680    /// boundary. `emit_field_deserialise_wire`'s own field guards, spliced
681    /// into a sum's deserialise-side payload case, have always printed at
682    /// depth 1 (`splice_stmts`'s own fixed indent) even though they sit
683    /// structurally inside a `TsStmtKind::Switch` case's own body (which
684    /// this printer would otherwise render two levels deeper, at depth 3) —
685    /// confirmed byte-for-byte against `212_json_codec`/
686    /// `407_workers_generic_sum_boundary`'s own real fixtures. Letting the
687    /// switch case render these at their structurally-correct depth instead
688    /// would be a real, deliberate formatting change with no fixture-corpus
689    /// backing either way, which that slice's own zero-diff mandate ruled
690    /// out choosing unprompted.
691    ///
692    /// All three real uses share the one property that actually matters for
693    /// this variant's own existence: *real, already-correctly-indented (or,
694    /// for the third, real-but-deliberately-NOT-restructured) statement text
695    /// this call site cannot turn into a properly-nested `Vec<TsStmt>`
696    /// without changing scope or bytes it isn't the one authorised to
697    /// change* — not whether the reason is permanent, temporary, or a
698    /// preserved historical quirk.
699    Raw(String),
700}
701
702/// One `case`/`default` arm of a `TsStmtKind::Switch`. `test: None` is the
703/// `default:` case — every real `default` in `workers_entry.rs` prints its
704/// body directly under `default:` with no `{ }` block, while every real
705/// non-`default` `case` (regardless of `test`) always prints a `{ }`-blocked
706/// body.
707///
708/// `default_braced` (Arc C slice 33, `tests_emit.rs` slice C, #1401) —
709/// `emit_stub_class`'s own `ReturnsEach` dispatch is the first real site
710/// with a BRACED `default: { ... }`, a genuinely different convention from
711/// `workers_entry.rs`'s own unbraced one; only meaningful when `test` is
712/// `None` (a non-`default` case was unconditionally braced before
713/// `case_braced` existed, below). Kept a per-case flag rather than changing
714/// the existing unbraced-default rendering, since that would risk
715/// `workers_entry.rs`'s own real, already-zero-diff content for no benefit —
716/// the same "don't touch working, unrelated content" judgment this track
717/// makes repeatedly.
718///
719/// `case_braced` (Arc E slice 6, #1445) — the mirror-image gap `default_braced`
720/// left open: `serialisation.rs`'s `emit_sum_codec` (this tree's first real
721/// non-`default` case that is NOT `{ }`-blocked) needs `case "Pending":
722/// return { kind: "Pending" };` — unbraced — right beside a sibling
723/// payload-carrying `case "Shipped": { ... }` — braced — in the *same*
724/// switch (`212_json_codec`'s own mixed `Status` fixture, confirmed by
725/// direct grep before this field was added: a payload-free variant's case
726/// is always unbraced, a payload-carrying variant's is always braced, and a
727/// real fixture exercises both side by side). Every prior real non-`default`
728/// case (`workers_entry.rs`'s dispatches, `tests_emit.rs`'s own sequential-
729/// outcome cases) already wants braces, so those call sites all set this
730/// `true` — the same "narrow, argued, backward-compatible extension"
731/// shape `default_braced` itself set as precedent. Only meaningful when
732/// `test` is `Some(..)` (a `default` case's bracing is `default_braced`'s
733/// business, not this field's — the inverse of that field's own scoping).
734#[derive(Debug, Clone)]
735pub struct TsSwitchCase {
736    pub test: Option<TsExpr>,
737    pub body: Vec<TsStmt>,
738    pub default_braced: bool,
739    pub case_braced: bool,
740}
741
742impl TsStmt {
743    /// The one constructor for a `Verbatim`-kinded statement.
744    pub fn verbatim(origin: VerbatimOrigin, text: impl Into<String>, span: Option<Span>) -> Self {
745        Self {
746            kind: TsStmtKind::Verbatim {
747                origin,
748                text: text.into(),
749            },
750            span,
751            nested_map: None,
752            no_blank_before: false,
753            nested_map_source_id: 0,
754        }
755    }
756
757    /// Whether this is a named `import { … } from "…"` declaration (#1817): a
758    /// module assembler hoists those into its import block.
759    pub fn is_named_import(&self) -> bool {
760        matches!(self.kind, TsStmtKind::Decl(TsDecl::Import { .. }))
761    }
762
763    /// The names this statement exports (#1820): an `export` of a named
764    /// declaration, or an `export { … }` list, with or without `from`. A
765    /// module assembler re-exporting another module's names reads them here.
766    /// A `Raw` or `Verbatim` statement's text is not parsed, so an export
767    /// written that way is not reported.
768    ///
769    /// Each name says whether this statement exports a value under it (#1862
770    /// review): an `interface` or `type` alias exports only a type, and under
771    /// `isolatedModules` a type-only name is re-exported only as `type X`
772    /// (TS1205). A list entry follows [`TsDecl::Import`]'s spelling: `type X`
773    /// is type-only, and `X as Y` exports `Y`. Every other entry is taken to
774    /// carry a value, the form that re-exports both meanings.
775    pub fn exported_names(&self) -> Vec<ExportedName<'_>> {
776        let TsStmtKind::Decl(decl) = &self.kind else {
777            return Vec::new();
778        };
779        match decl {
780            TsDecl::ReExport { names, .. } | TsDecl::ExportNames { names } => names
781                .iter()
782                .map(|spec| {
783                    let (spec, has_value) = match spec.trim().strip_prefix("type ") {
784                        Some(rest) => (rest, false),
785                        None => (spec.trim(), true),
786                    };
787                    let name = spec.rsplit(" as ").next().unwrap_or(spec).trim();
788                    ExportedName { name, has_value }
789                })
790                .collect(),
791            TsDecl::Export(inner) => match inner.as_ref() {
792                TsDecl::Interface { name, .. } | TsDecl::TypeAlias { name, .. } => {
793                    vec![ExportedName {
794                        name,
795                        has_value: false,
796                    }]
797                }
798                TsDecl::ConstDecl { name, .. }
799                | TsDecl::Class { name, .. }
800                | TsDecl::Function { name, .. } => vec![ExportedName {
801                    name,
802                    has_value: true,
803                }],
804                _ => Vec::new(),
805            },
806            _ => Vec::new(),
807        }
808    }
809
810    pub fn decl(decl: TsDecl, span: Option<Span>) -> Self {
811        Self {
812            kind: TsStmtKind::Decl(decl),
813            span,
814            nested_map: None,
815            no_blank_before: false,
816            nested_map_source_id: 0,
817        }
818    }
819
820    pub fn const_stmt(
821        name: TsBindingName,
822        ty: Option<TsType>,
823        init: TsExpr,
824        span: Option<Span>,
825    ) -> Self {
826        Self {
827            kind: TsStmtKind::Const { name, ty, init },
828            span,
829            nested_map: None,
830            no_blank_before: false,
831            nested_map_source_id: 0,
832        }
833    }
834
835    pub fn let_stmt(
836        name: TsBindingName,
837        ty: Option<TsType>,
838        init: Option<TsExpr>,
839        span: Option<Span>,
840    ) -> Self {
841        Self {
842            kind: TsStmtKind::Let { name, ty, init },
843            span,
844            nested_map: None,
845            no_blank_before: false,
846            nested_map_source_id: 0,
847        }
848    }
849
850    pub fn expr_stmt(expr: TsExpr, span: Option<Span>) -> Self {
851        Self {
852            kind: TsStmtKind::ExprStmt(expr),
853            span,
854            nested_map: None,
855            no_blank_before: false,
856            nested_map_source_id: 0,
857        }
858    }
859
860    pub fn return_stmt(expr: Option<TsExpr>, span: Option<Span>) -> Self {
861        Self {
862            kind: TsStmtKind::Return(expr),
863            span,
864            nested_map: None,
865            no_blank_before: false,
866            nested_map_source_id: 0,
867        }
868    }
869
870    pub fn throw_stmt(expr: TsExpr, span: Option<Span>) -> Self {
871        Self {
872            kind: TsStmtKind::Throw(expr),
873            span,
874            nested_map: None,
875            no_blank_before: false,
876            nested_map_source_id: 0,
877        }
878    }
879
880    pub fn if_stmt(cond: TsExpr, then_branch: TsStmt, span: Option<Span>) -> Self {
881        Self {
882            kind: TsStmtKind::If {
883                cond,
884                then_branch: Box::new(then_branch),
885                else_branch: None,
886                same_line_else: false,
887            },
888            span,
889            nested_map: None,
890            no_blank_before: false,
891            nested_map_source_id: 0,
892        }
893    }
894
895    pub fn if_else_stmt(
896        cond: TsExpr,
897        then_branch: TsStmt,
898        else_branch: TsStmt,
899        span: Option<Span>,
900    ) -> Self {
901        Self {
902            kind: TsStmtKind::If {
903                cond,
904                then_branch: Box::new(then_branch),
905                else_branch: Some(Box::new(else_branch)),
906                same_line_else: false,
907            },
908            span,
909            nested_map: None,
910            no_blank_before: false,
911            nested_map_source_id: 0,
912        }
913    }
914
915    /// [`TsStmt::if_else_stmt`]'s own sibling with `} else {` on one line —
916    /// #1325's own real gap, `emit_test_main`'s own real `else` spacing. See
917    /// `TsStmtKind::If`'s own doc for why this needs to be a distinct
918    /// constructor rather than a change to the existing default.
919    pub fn if_else_same_line_stmt(
920        cond: TsExpr,
921        then_branch: TsStmt,
922        else_branch: TsStmt,
923        span: Option<Span>,
924    ) -> Self {
925        Self {
926            kind: TsStmtKind::If {
927                cond,
928                then_branch: Box::new(then_branch),
929                else_branch: Some(Box::new(else_branch)),
930                same_line_else: true,
931            },
932            span,
933            nested_map: None,
934            no_blank_before: false,
935            nested_map_source_id: 0,
936        }
937    }
938
939    pub fn for_of(
940        binding: impl Into<String>,
941        iter: TsExpr,
942        body: TsStmt,
943        span: Option<Span>,
944    ) -> Self {
945        Self {
946            kind: TsStmtKind::ForOf {
947                binding: binding.into(),
948                iter,
949                body: Box::new(body),
950            },
951            span,
952            nested_map: None,
953            no_blank_before: false,
954            nested_map_source_id: 0,
955        }
956    }
957
958    /// `for (let <name> = <init>; <test>; <update>++) <body>` — see
959    /// `TsStmtKind::For`'s own doc for exactly what this construct does
960    /// and does not represent.
961    pub fn for_stmt(
962        name: impl Into<String>,
963        init: TsExpr,
964        test: TsExpr,
965        body: TsStmt,
966        span: Option<Span>,
967    ) -> Self {
968        Self {
969            kind: TsStmtKind::For {
970                name: name.into(),
971                init,
972                test,
973                body: Box::new(body),
974            },
975            span,
976            nested_map: None,
977            no_blank_before: false,
978            nested_map_source_id: 0,
979        }
980    }
981
982    pub fn try_catch(
983        try_block: TsStmt,
984        catch_param: Option<impl Into<String>>,
985        catch_block: TsStmt,
986        span: Option<Span>,
987    ) -> Self {
988        Self {
989            kind: TsStmtKind::TryCatch {
990                try_block: Box::new(try_block),
991                catch_param: catch_param.map(Into::into),
992                catch_block: Box::new(catch_block),
993            },
994            span,
995            nested_map: None,
996            no_blank_before: false,
997            nested_map_source_id: 0,
998        }
999    }
1000
1001    pub fn block(stmts: Vec<TsStmt>, span: Option<Span>) -> Self {
1002        Self {
1003            kind: TsStmtKind::Block(stmts),
1004            span,
1005            nested_map: None,
1006            no_blank_before: false,
1007            nested_map_source_id: 0,
1008        }
1009    }
1010
1011    pub fn continue_stmt(span: Option<Span>) -> Self {
1012        Self {
1013            kind: TsStmtKind::Continue,
1014            span,
1015            nested_map: None,
1016            no_blank_before: false,
1017            nested_map_source_id: 0,
1018        }
1019    }
1020
1021    pub fn assign(target: TsExpr, value: TsExpr, span: Option<Span>) -> Self {
1022        Self {
1023            kind: TsStmtKind::Assign { target, value },
1024            span,
1025            nested_map: None,
1026            no_blank_before: false,
1027            nested_map_source_id: 0,
1028        }
1029    }
1030
1031    pub fn comment(text: impl Into<String>, span: Option<Span>) -> Self {
1032        Self {
1033            kind: TsStmtKind::Comment(text.into()),
1034            span,
1035            nested_map: None,
1036            no_blank_before: false,
1037            nested_map_source_id: 0,
1038        }
1039    }
1040
1041    pub fn doc_comment(text: impl Into<String>, span: Option<Span>) -> Self {
1042        Self {
1043            kind: TsStmtKind::DocComment(text.into()),
1044            span,
1045            nested_map: None,
1046            no_blank_before: false,
1047            nested_map_source_id: 0,
1048        }
1049    }
1050
1051    pub fn blank(span: Option<Span>) -> Self {
1052        Self {
1053            kind: TsStmtKind::Blank,
1054            span,
1055            nested_map: None,
1056            no_blank_before: false,
1057            nested_map_source_id: 0,
1058        }
1059    }
1060
1061    pub fn switch_stmt(discriminant: TsExpr, cases: Vec<TsSwitchCase>, span: Option<Span>) -> Self {
1062        Self {
1063            kind: TsStmtKind::Switch {
1064                discriminant,
1065                cases,
1066            },
1067            span,
1068            nested_map: None,
1069            no_blank_before: false,
1070            nested_map_source_id: 0,
1071        }
1072    }
1073
1074    pub fn inline_block(stmts: Vec<TsStmt>, span: Option<Span>) -> Self {
1075        Self {
1076            kind: TsStmtKind::InlineBlock(stmts),
1077            span,
1078            nested_map: None,
1079            no_blank_before: false,
1080            nested_map_source_id: 0,
1081        }
1082    }
1083
1084    pub fn increment(expr: TsExpr, span: Option<Span>) -> Self {
1085        Self {
1086            kind: TsStmtKind::Increment(expr),
1087            span,
1088            nested_map: None,
1089            no_blank_before: false,
1090            nested_map_source_id: 0,
1091        }
1092    }
1093
1094    /// The one constructor for a `Raw`-kinded statement — `text` is printed
1095    /// verbatim, exactly as given (see `TsStmtKind::Raw`'s own doc for
1096    /// why this is a distinct kind from `Verbatim`, not a reuse of it).
1097    pub fn raw(text: impl Into<String>, span: Option<Span>) -> Self {
1098        Self {
1099            kind: TsStmtKind::Raw(text.into()),
1100            span,
1101            nested_map: None,
1102            no_blank_before: false,
1103            nested_map_source_id: 0,
1104        }
1105    }
1106}
1107
1108/// A binding's own name, in either of the two shapes `events_fanout.rs`
1109/// itself uses: a plain identifier (`const subs = ...`), or an
1110/// object-destructuring pattern (`const { events } = ...`) — naming only
1111/// the destructured properties themselves (`{ a, b }`), not the renamed
1112/// (`{ a: renamed }`) or nested (`{ a: { b } }`) forms, since nothing in
1113/// the grounding file needs either.
1114#[derive(Debug, Clone)]
1115pub enum TsBindingName {
1116    Ident(String),
1117    ObjectPattern(Vec<String>),
1118}
1119
1120/// An expression. Only the shapes `events_fanout.rs` concretely uses
1121/// (Decision B) — not the reference sketch's full `TsExpr` list (`Arrow`,
1122/// `Cond`, `TemplateLit`, `Spread` are all unused in the grounding file and
1123/// deliberately not built here). Arc C slice 3 (#1321, `workers.rs`) adds
1124/// `Arrow`, `OptionalMember`/`OptionalIndex` (Decision A, gaps 3/4) — this
1125/// slice's own real, grounded needs.
1126#[derive(Debug, Clone)]
1127pub enum TsExpr {
1128    /// A real identifier — the only content this variant is for. #1539
1129    /// (review of `design/reviews/2026-08-30-post-restructuring-review.md`
1130    /// Part 3/Part 5 §1): before this doc existed, `bynk-emit` also smuggled
1131    /// non-identifier text through it at 15 call sites in `emit.rs` alone —
1132    /// a quoted string literal, `this.<method>` member access, a complete
1133    /// `!(<pred>)` unary expression — an untagged `Verbatim`-shaped escape
1134    /// hatch [`TsStmt::verbatim`]'s own doc already named the concern for
1135    /// (Q2's "makes the ratchet a compile-time construct, not a grep"), just
1136    /// with no tag and no probe watching it. Every one of those call sites
1137    /// now either builds the matching real node (`Lit(TsLit::Str)`, `Member`,
1138    /// `Unary`) or routes through [`TsExpr::VerbatimExpr`] instead — this
1139    /// variant no longer holds anything but a genuine identifier.
1140    Ident(String),
1141    /// A residual, not-yet-converted expression carrying a [`VerbatimOrigin`]
1142    /// tag — [`TsStmt::verbatim`]'s own discipline, closed for expressions
1143    /// too (#1539). Printed exactly as [`TsExpr::Ident`] always was (raw
1144    /// text, no escaping of its own — the caller is responsible for
1145    /// producing valid, already-escaped TypeScript, the same contract
1146    /// `TsStmt::verbatim`'s own text carries), but now visible to
1147    /// [`crate::verbatim_violations`] and `xtask`'s own `verbatim_origins`/
1148    /// `verbatim_sites` gated probes, which had nothing to watch at the
1149    /// expression level before this variant existed. What ends up here after
1150    /// #1539's own conversion pass: a generic-typed method/constructor
1151    /// callee (`Call`/`New` have no `type_args` field), a nested
1152    /// `As`-under-`As` cast chain the printer's own operand-parenthesisation
1153    /// rule would otherwise mis-wrap (review of #1390), a block-bodied IIFE
1154    /// with no matching `TsArrowBody` shape, and a `pred_condition_and_
1155    /// message`-style message that is already pre-escaped or unescaped by
1156    /// contract (a second escaping pass through `TsLit::Str` would corrupt
1157    /// it) — none of these has a real node to convert to without expanding
1158    /// this crate's own type algebra well past what #1539 asks for.
1159    VerbatimExpr(String, VerbatimOrigin),
1160    /// `object.property`.
1161    Member {
1162        object: Box<TsExpr>,
1163        property: String,
1164    },
1165    /// `object?.property` — the optional-chaining form of [`TsExpr::Member`].
1166    /// A distinct variant, not an `optional: bool` flag on `Member` itself
1167    /// (#1321's own Decision A, gap 4, left the mechanism to the
1168    /// implementation): a flag would touch every one of `Member`'s
1169    /// already-many real call sites (`events_fanout.rs`, this crate's own
1170    /// printer tests) that never need one, where a separate variant touches
1171    /// none of them — narrower, matching this track's own repeated
1172    /// "smallest correct scope" judgment. `workers.rs`'s own secret-probe
1173    /// idiom (`emit_websocket_upgrade`/`emit_http_wrapper`/
1174    /// `emit_secret_lookup`, three identical real sites) is the only
1175    /// grounding.
1176    OptionalMember {
1177        object: Box<TsExpr>,
1178        property: String,
1179    },
1180    /// `object[index]`.
1181    Index {
1182        object: Box<TsExpr>,
1183        index: Box<TsExpr>,
1184    },
1185    /// `object?.[index]` — the optional-chaining form of [`TsExpr::Index`],
1186    /// the same real grounding and the same "separate variant, not a flag"
1187    /// reasoning as [`TsExpr::OptionalMember`].
1188    OptionalIndex {
1189        object: Box<TsExpr>,
1190        index: Box<TsExpr>,
1191    },
1192    /// `(params) => body` (`is_async: false`) or `async (params) => body`
1193    /// (`is_async: true`) — an arrow function, expression- or block-bodied
1194    /// (see [`TsArrowBody`]). `is_async` added by #1327: `emit_composition_root`'s
1195    /// own `__eventsDispatch` closure (`async (events: Array<...>) => {...}`)
1196    /// is the first real `Arrow` site that's async — mirrors
1197    /// `TsDecl::Function`'s own `is_async` field (#1325), added for the same
1198    /// reason. `generics`/`return_type` added by #1339: `emit_sum_type`'s
1199    /// own generic payload-constructor arrows (`<T>(name: T): Sum<T> =>
1200    /// (...)`) need both — bare generic names only (empty for every
1201    /// non-generic site, the overwhelming majority), matching
1202    /// `TsObjectEntry::Method.generics`'s own (#1337) identical convention;
1203    /// `return_type` mirrors `TsDecl::Function.return_type`'s own existing
1204    /// `Option<TsType>` shape — a real gap the accepted proposal's own
1205    /// grounding named `generics` for but missed: every one of this file's
1206    /// own real generic-payload arrows carries an explicit return-type
1207    /// annotation the arrow itself owns (`: {name}{params}`), not something
1208    /// the body's own type alone determines.
1209    ///
1210    /// `body`'s type became [`TsArrowBody`] (#1435, Arc E slice 1): from
1211    /// P7.8 through #1434 this field was a bare `Box<TsExpr>` — expression-
1212    /// bodied only, "extend narrowly" (the same posture `TsBinaryOp` takes
1213    /// for its own operator table), since every real site up to and
1214    /// including #1339's generic payload-constructor arrows had an
1215    /// expression body. `serialisation.rs`'s `serialise_field_expr_wire`
1216    /// (`bynk-emit`) is the first real site that doesn't: its `Float`
1217    /// non-finite guard is a genuine statement-bodied IIFE (`((v: number) =>
1218    /// { if (!Number.isFinite(v)) throw new Error(...); return v as
1219    /// JsonValue; })(value)`), not reducible to one expression. Widening the
1220    /// existing field (`TsArrowBody::Expr(Box<TsExpr>)` |
1221    /// `TsArrowBody::Block(Vec<TsStmt>)`) rather than adding a second
1222    /// sibling `TsExpr` variant matches this file's own repeated
1223    /// "extend the existing variant when every real site still needs the
1224    /// same node kind, only the body shape differs" precedent
1225    /// (`TsObjectEntry::Method.inline`, #1337) — every prior `Arrow`
1226    /// construction site across the workspace wraps its already-correct
1227    /// expression body in `TsArrowBody::Expr(..)`, a mechanical change with
1228    /// no behavior difference.
1229    Arrow {
1230        params: Vec<TsParam>,
1231        is_async: bool,
1232        generics: Vec<String>,
1233        return_type: Option<TsType>,
1234        body: Box<TsArrowBody>,
1235    },
1236    Call {
1237        callee: Box<TsExpr>,
1238        args: Vec<TsExpr>,
1239    },
1240    New {
1241        callee: Box<TsExpr>,
1242        args: Vec<TsExpr>,
1243    },
1244    /// A value object literal, e.g. `{ status: 204 }` — comma-separated.
1245    /// `multiline: false` (the ordinary case, via [`TsExpr::object`])
1246    /// always prints on one line, matching [`TsType::Object`]'s own
1247    /// (semicolon-separated) single-line convention for the *type*-position
1248    /// shape. `multiline: true` (via [`TsExpr::multiline_object`]) is a
1249    /// real, grounded gap found implementing Arc C's first slice (#1317):
1250    /// `events_fanout.rs`'s own `__eventRoutes` table is a top-level
1251    /// `const` initializer with one entry per line, each with its own
1252    /// trailing comma, closing brace at the *statement's* own indent —
1253    /// TypeScript's ordinary multi-line object-literal convention, which
1254    /// nothing in this crate could represent before this addition. Only
1255    /// statement/declaration-level renderers (which already carry `depth`)
1256    /// can render this correctly — `printer.rs`'s own `render_stmt_level_
1257    /// expr`, and (#1355) `render_multiline_object_entry`'s own `Prop` arm,
1258    /// for a `multiline: true` object nested one level inside ANOTHER
1259    /// multiline object as one of its own entries' values —
1260    /// `emit_messages_bundle`'s own real doubly-nested `{ locale: { code:
1261    /// expr, ... }, ... }` table. A `multiline: true` object nested any
1262    /// OTHER way (an array element, a call argument, a `Prop`'s value
1263    /// inside a non-multiline object, …) still renders via the ordinary
1264    /// depth-unaware `render_expr` recursion, which cannot honour
1265    /// `multiline` — not reachable from any real `bynk-emit` call site
1266    /// today, but worth knowing before nesting one that way.
1267    Object {
1268        entries: Vec<TsObjectEntry>,
1269        multiline: bool,
1270    },
1271    /// An array literal, e.g. `[{ binding: "x", service: "y" }]`.
1272    /// `multiline: false` (the ordinary case, via [`TsExpr::array`]) always
1273    /// prints on one line, comma-separated — every real site before this
1274    /// slice. `multiline: true` (via [`TsExpr::multiline_array`]) is #1325's
1275    /// own real gap: `emit_test_main`'s own `modules` array (one `{ name,
1276    /// run }` entry per test, one per line, each with its own trailing
1277    /// comma, closing `]` at the statement's own indent) — the exact same
1278    /// shape [`TsExpr::Object`]'s own `multiline` field already represents
1279    /// for object literals, just for an array. Same reachability boundary as
1280    /// `Object`'s own `multiline` field (see its own doc, updated by
1281    /// #1355): `render_stmt_level_expr` and `render_multiline_object_
1282    /// entry`'s own `Prop` arm both honour it; nested any other way, a
1283    /// `multiline: true` array falls back to single-line via the ordinary
1284    /// depth-unaware `render_expr` recursion.
1285    Array {
1286        items: Vec<TsExpr>,
1287        multiline: bool,
1288    },
1289    /// `` `text${expr}more text` `` — a template literal. `parts.len()` is
1290    /// always `exprs.len() + 1` (`parts[0]` before the first substitution,
1291    /// `parts[i+1]` after `exprs[i]`, …). #1325's own real, first grounding
1292    /// for this shape (`bynk-ts`'s own module doc named `TemplateLit`
1293    /// explicitly "unused in the grounding file" until now):
1294    /// `emit_test_main`'s own `` `${m.name}:` ``/`` `${passed} passed,
1295    /// ${failed} failed.` `` lines.
1296    ///
1297    /// **`parts` are printed verbatim — the printer applies no escaping of
1298    /// its own.** The same "the field is already a raw-text slot" reasoning
1299    /// [`TsDecl::Import`]'s own `names` field doc already uses, not a new
1300    /// pattern: `emit_test_main`'s own two real ✓/✗ substitution lines embed
1301    /// a literal `✓`/`✗` JS unicode escape as pre-formed ASCII
1302    /// text (six literal characters, not the actual glyph) — an escaper
1303    /// mirroring [`TsLit::Str`]'s own (which escapes every `\` it sees)
1304    /// would double that literal backslash into `\\u2713`, corrupting the
1305    /// exact byte-golden output this slice must match. Every real part in
1306    /// `emit_test_main` is static, compiler-authored text (never Bynk user
1307    /// data), so there is no real content this boundary loses safety on
1308    /// today — a future caller passing untrusted/dynamic text into `parts`
1309    /// is responsible for pre-escaping backtick/`` ${ ``/`\` itself before
1310    /// constructing one.
1311    TemplateLit {
1312        parts: Vec<String>,
1313        exprs: Vec<TsExpr>,
1314    },
1315    Await(Box<TsExpr>),
1316    /// `expr as ty`.
1317    As {
1318        expr: Box<TsExpr>,
1319        ty: TsType,
1320    },
1321    Unary {
1322        op: TsUnaryOp,
1323        expr: Box<TsExpr>,
1324    },
1325    Binary {
1326        op: TsBinaryOp,
1327        left: Box<TsExpr>,
1328        right: Box<TsExpr>,
1329    },
1330    /// `test ? consequent : alternate` — #1323's own real gap: `method ===
1331    /// "HEAD" ? headResponse(__response) : __response` (once per `GET`
1332    /// route) and `method === "OPTIONS" ? 204 : 405` (the method-fallthrough
1333    /// path). The lowest-precedence expression form after `Arrow` — needs
1334    /// the same parenthesization-rule coverage `Arrow` got in review of
1335    /// #1322 (`needs_parens_as_operand`/`render_binary_operand`/`As`'s own
1336    /// local rule), added proactively in this same slice rather than left
1337    /// for a review round to re-find.
1338    Conditional {
1339        test: Box<TsExpr>,
1340        consequent: Box<TsExpr>,
1341        alternate: Box<TsExpr>,
1342    },
1343    /// An explicit, printer-preserved parenthesization — distinct from every
1344    /// other variant's own precedence-*derived* parens (`render_operand`/
1345    /// `render_binary_operand`), which the printer adds or omits based on
1346    /// what the wrapped expression *is*. `Paren` instead always prints
1347    /// `(<inner>)` regardless of `inner`'s own shape or precedence. #1323's
1348    /// own real, narrow need: `workers_entry.rs`'s CORS-preflight guard
1349    /// wraps its own path-match condition in unconditional parens
1350    /// (`&& ({cond})`) even when `cond` reduces to a single equality check
1351    /// with no operator lower-precedence than the outer `&&` — a real case
1352    /// the precedence-derived rules correctly do *not* parenthesize (they're
1353    /// answering "is this needed for correctness", not "did the source
1354    /// always write parens here"). Not a general escape hatch: every other
1355    /// real site in this file's own content still goes through the ordinary
1356    /// precedence machinery unchanged.
1357    Paren(Box<TsExpr>),
1358    Lit(TsLit),
1359}
1360
1361/// [`TsExpr::Arrow`]'s own `body` shape (#1435, Arc E slice 1) — see that
1362/// field's own doc for why this is a widened field rather than a second
1363/// `TsExpr` variant. `Expr` is every real site before this slice (and the
1364/// overwhelming majority after it): the arrow's body is one expression,
1365/// printed with no surrounding braces. `Block` is `serialisation.rs`'s own
1366/// `Float` non-finite guard, the first real statement-bodied arrow anywhere
1367/// in this tree — printed as a real braced block, reusing this crate's
1368/// own printer's existing compact-statement-list renderer
1369/// (`render_compact_stmts`, the same one `TsStmtKind::InlineBlock` already
1370/// shares with `render_branch`'s own same-line `if`/`else`) rather than a
1371/// third copy of that "one physical line, semicolon-separated" logic. Every
1372/// real `Block` site today is exactly this one-line IIFE shape (an arrow
1373/// with no other real use of a genuinely multi-line block body has been
1374/// found); a future multi-line block-bodied arrow is a real, separate gap
1375/// this variant does not yet cover.
1376#[derive(Debug, Clone)]
1377pub enum TsArrowBody {
1378    Expr(Box<TsExpr>),
1379    Block(Vec<TsStmt>),
1380}
1381
1382impl TsExpr {
1383    /// The ordinary, single-line object literal, `Prop`-only — every entry
1384    /// is `key: value`. `events_fanout.rs`'s own entries (and this crate's
1385    /// own printer tests) are all this shape; kept taking a plain
1386    /// `Vec<(String, TsExpr)>` rather than `Vec<TsObjectEntry>` so none of
1387    /// those existing call sites needed to change when `TsObjectEntry` was
1388    /// added (#1321) — see [`TsExpr::object_entries`] for the mixed-entry
1389    /// form `workers.rs` itself needs (shorthand/spread/method entries).
1390    pub fn object(entries: Vec<(String, TsExpr)>) -> Self {
1391        TsExpr::Object {
1392            entries: entries
1393                .into_iter()
1394                .map(|(k, v)| TsObjectEntry::Prop(k, v))
1395                .collect(),
1396            multiline: false,
1397        }
1398    }
1399
1400    /// One entry per line, each with its own trailing comma — see
1401    /// [`TsExpr::Object`]'s own doc for the real shape and the
1402    /// depth-awareness this needs at the print site. `Prop`-only, the same
1403    /// convenience [`TsExpr::object`]'s own doc explains.
1404    pub fn multiline_object(entries: Vec<(String, TsExpr)>) -> Self {
1405        TsExpr::Object {
1406            entries: entries
1407                .into_iter()
1408                .map(|(k, v)| TsObjectEntry::Prop(k, v))
1409                .collect(),
1410            multiline: true,
1411        }
1412    }
1413
1414    /// The single-line object literal, taking [`TsObjectEntry`] directly —
1415    /// for a mixed entry list (shorthand/spread/method alongside `Prop`),
1416    /// which [`TsExpr::object`]'s own `Vec<(String, TsExpr)>` convenience
1417    /// can't represent. #1321's own real grounding: `workers.rs`'s local
1418    /// capability-provider `deps` object mixes shorthand names
1419    /// (`{ cap1, cap2 }`) with explicit `key: value` entries
1420    /// (`__exec: exec`) in one literal.
1421    pub fn object_entries(entries: Vec<TsObjectEntry>) -> Self {
1422        TsExpr::Object {
1423            entries,
1424            multiline: false,
1425        }
1426    }
1427
1428    /// [`TsExpr::multiline_object`]'s own `TsObjectEntry` sibling —
1429    /// #1321's own real grounding: `workers.rs`'s `compose`-returned
1430    /// surface object is one shorthand-async-`Method` entry per wrapper,
1431    /// one per line.
1432    pub fn multiline_object_entries(entries: Vec<TsObjectEntry>) -> Self {
1433        TsExpr::Object {
1434            entries,
1435            multiline: true,
1436        }
1437    }
1438
1439    /// The ordinary, single-line array literal — every real site before
1440    /// #1325.
1441    pub fn array(items: Vec<TsExpr>) -> Self {
1442        TsExpr::Array {
1443            items,
1444            multiline: false,
1445        }
1446    }
1447
1448    /// One entry per line, each with its own trailing comma — see
1449    /// [`TsExpr::Array`]'s own doc for the real shape and the
1450    /// depth-awareness this needs at the print site. #1325's own real
1451    /// grounding: `emit_test_main`'s own `modules` array.
1452    pub fn multiline_array(items: Vec<TsExpr>) -> Self {
1453        TsExpr::Array {
1454            items,
1455            multiline: true,
1456        }
1457    }
1458
1459    /// A template literal — see [`TsExpr::TemplateLit`]'s own doc for the
1460    /// real shape and its no-escaping boundary. The sole caller-facing
1461    /// invariant (`parts.len() == exprs.len() + 1`) is asserted here rather
1462    /// than left to `render_expr`'s own `parts`-driven loop, which would
1463    /// otherwise silently drop trailing `exprs` on a malformed tree instead
1464    /// of failing loudly (review of #1326, finding 1).
1465    pub fn template_lit(parts: Vec<String>, exprs: Vec<TsExpr>) -> Self {
1466        debug_assert_eq!(
1467            parts.len(),
1468            exprs.len() + 1,
1469            "TsExpr::template_lit: parts.len() must be exprs.len() + 1 \
1470             (parts[0] before the first substitution, parts[i+1] after \
1471             exprs[i], …) — got {} parts and {} exprs",
1472            parts.len(),
1473            exprs.len()
1474        );
1475        TsExpr::TemplateLit { parts, exprs }
1476    }
1477}
1478
1479/// One entry of a [`TsExpr::Object`] literal. Only `Prop` existed before
1480/// #1321 (`events_fanout.rs`'s own grounding never needed the other three) —
1481/// `workers.rs`'s own dominant shape (Decision A, gap 1) is a literal
1482/// object whose entries are shorthand async methods (every `on call`/`on
1483/// http`/… wrapper attaches this way), its local capability-`deps` object
1484/// mixes bare shorthand names with explicit `key: value` pairs, and three
1485/// real sites spread another object into one (gap 2, folded in here rather
1486/// than as its own top-level `TsExpr` variant — a spread only ever appears
1487/// as an object- or array-literal entry in this file, never as a
1488/// standalone expression, so scoping it to entry position is the narrower
1489/// correct change).
1490#[derive(Debug, Clone)]
1491pub enum TsObjectEntry {
1492    /// `key: value`.
1493    Prop(String, TsExpr),
1494    /// `key` alone — object-literal property shorthand, e.g. `{ cap1,
1495    /// cap2 }`. Distinct from `Prop(name, TsExpr::Ident(name))`, which
1496    /// prints `name: name`, not the shorthand form real TypeScript
1497    /// property-shorthand text actually is.
1498    Shorthand(String),
1499    /// A shorthand async method entry, e.g. `async foo(a: T) { ... },` —
1500    /// `workers.rs`'s own dominant shape (Decision A, gap 1): every
1501    /// wrapper helper (`emit_call_wrapper`, `emit_event_wrapper`, …)
1502    /// attaches to the returned `compose` surface this way — none of
1503    /// `workers.rs`'s own real sites annotates a return type, so
1504    /// `return_type` stayed unneeded until #1323's own real gap:
1505    /// `workers_entry.rs`'s `export default { fetch, scheduled?, queue? }`
1506    /// entries all carry one (`: Promise<Response>`/`: Promise<void>`), the
1507    /// same field [`TsClassMethod::return_type`] already has for the
1508    /// declaration-position sibling this mirrors.
1509    ///
1510    /// `generics` and `doc` (#1337's own real gaps, both found only by the
1511    /// zero-diff fixture check — not the accepted proposal's own citation,
1512    /// which searched the project-form fixture corpus only;
1513    /// `402_generic_instance_method` is single-file form, and while
1514    /// `65_money_uses_time`/`64_full_time_commons` ARE project form, the
1515    /// citation's own doc-comment search used the wrong marker, `///`
1516    /// rather than this language's real `---`-delimited doc block —
1517    /// both gaps outside what that first pass actually checked):
1518    ///
1519    /// - `generics`: a method on a generic type erases to
1520    ///   `{name}<{generics}>(self: {Type}<{generics}>, …)` — `Box.map<A,
1521    ///   U>`, the type's own `A` plus the method's own `U`. Bare names
1522    ///   only, no bounds/defaults — every real generic parameter list this
1523    ///   tree ever builds is (matching [`crate::printer::print_type`]'s
1524    ///   own `TsType::Named`-only-name convention for the identical
1525    ///   reason), so a full `Vec<TsParam>` (with its own unneeded
1526    ///   `ty`/`optional` fields) would be the wrong shape here.
1527    /// - `doc`: a JSDoc block immediately preceding the method entry, at
1528    ///   the same indent — `Timestamp.diff`/`Timestamp.add`
1529    ///   (`65_money_uses_time`) both carry one. Printed the identical way
1530    ///   `TsStmtKind::DocComment` is (same escaping, same blank-line
1531    ///   convention), reusing that one renderer rather than a second copy
1532    ///   — this field exists because an object-entry method has no
1533    ///   `TsStmt` slot of its own to hold a preceding statement in.
1534    Method {
1535        name: String,
1536        is_async: bool,
1537        generics: Vec<String>,
1538        params: Vec<TsParam>,
1539        return_type: Option<TsType>,
1540        doc: Option<String>,
1541        /// `false` (every method entry landed before #1337): `body` renders
1542        /// as an ordinary braced, multi-line block. `true`: `body` renders
1543        /// compactly on the SAME line as the signature — `{ <stmts>; }`,
1544        /// reusing this crate's own established compact-statement
1545        /// machinery (`TsStmtKind::InlineBlock`'s own sibling shape). A
1546        /// real gap #1337's own zero-diff check found:
1547        /// `emit_forwarded_methods`'s own pre-conversion `writeln!` always
1548        /// built the WHOLE entry — signature and one-statement body alike —
1549        /// on one physical line (`"  {method}({params}): {ret} {{ return
1550        /// …; }},"`), a genuinely different real shape from every other
1551        /// `Method` entry in this tree, all of which are multi-line.
1552        inline: bool,
1553        body: Vec<TsStmt>,
1554    },
1555    /// `...expr` — an object-spread entry (Decision A, gap 2), e.g. `{
1556    /// ...deps, identity: __caller }`.
1557    Spread(TsExpr),
1558}
1559
1560/// `!x` (`events_fanout.rs`'s `!Array.isArray(subs)`, `!binding`) and
1561/// `typeof x` (#1321, `workers.rs`'s own secret-probe idiom: `typeof
1562/// __secret !== "string"`) — the two unary operators real content uses, not
1563/// the full JS/TS table.
1564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1565pub enum TsUnaryOp {
1566    Not,
1567    Typeof,
1568}
1569
1570/// `??` (`events_fanout.rs`'s `env ?? {}`), plus three more real operators
1571/// #1321 (`workers.rs`) grounds: `||`/`&&` (the Bearer-header presence
1572/// checks, `__authz === null || !__authz.startsWith(...)` /
1573/// `__authz !== null && __authz.startsWith(...)`) and `===`/`!==`
1574/// (pervasive throughout the file's own tagged-result and header checks).
1575/// #1323 (`workers_entry.rs`) grounds one more: `>` (the request-body-
1576/// ceiling guard's own `Number(__contentLength) > <cap>` — the one real
1577/// site anywhere in `bynk-emit` that needs a relational, not equality,
1578/// comparison). Not the
1579/// full JS/TS operator table (Decision B's own "extend narrowly" posture) —
1580/// see the printer's own `binary_precedence` (`bynk-ts/src/printer.rs`,
1581/// private) for why a nested `Binary` operand's parenthesisation needed to
1582/// become precedence-aware once more than one operator existed. Arc C, step
1583/// (11) (#1388) grounds one more: `+` (string concatenation) — the
1584/// ICU-formatting cluster's own dominant structural pattern, every
1585/// literal/placeholder segment in a message template joins this way. Real
1586/// JS/TS precedence (binds tighter than every comparison/logical operator
1587/// this table already has) and real left-associativity (`"a" + "b" + "c"`
1588/// needs no parens, the same way a same-operator `||`/`&&` chain already
1589/// prints flat) both matter here, not just the operator symbol itself.
1590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1591pub enum TsBinaryOp {
1592    NullishCoalescing,
1593    Or,
1594    And,
1595    StrictEq,
1596    StrictNotEq,
1597    GreaterThan,
1598    /// `instanceof` — Arc C slice 34 (`tests_emit.rs` slice D, #1403)'s own
1599    /// real gap: `emit_test_case_function`'s own catch clause
1600    /// (`e instanceof ExpectationError`) is the first real `instanceof`
1601    /// anywhere in `bynk-emit`'s own content. Real JS/TS precedence puts it
1602    /// at the same tier as the relational comparisons (`<`/`>`) — sharing
1603    /// [`TsBinaryOp::LessThan`]'s own tier, not a new one — rendered as the
1604    /// keyword `" instanceof "`, textually the same shape as `&&`/`||`
1605    /// rather than symbol punctuation.
1606    InstanceOf,
1607    /// `<` — Arc C slice 33 (`tests_emit.rs` slice C, #1401)'s own real gap:
1608    /// `emit_stub_class`'s `ReturnsEach` sequence-cursor guard
1609    /// (`this.__seq_N < <bound>`) is the first real `<` comparison anywhere
1610    /// in `bynk-emit`'s own content. Same precedence tier as
1611    /// [`TsBinaryOp::GreaterThan`] (real JS/TS relational operators all
1612    /// share one level) — added alongside it rather than folding into a
1613    /// single "relational" variant, matching this enum's own existing
1614    /// one-variant-per-real-operator convention.
1615    LessThan,
1616    Add,
1617    /// `in` — Arc E slice 5 (`serialisation.rs`, #1443)'s own real gap:
1618    /// `emit_record_codec`'s per-field default-value prevalidation line
1619    /// (`"<field>" in obj ? obj["<field>"] : <default>`) needs a real "is
1620    /// this wire key present at all" test, distinct from `!== undefined`
1621    /// (Events slice 3a, #972's own Decision D: a wire key present with an
1622    /// explicit `null`/`{"kind":"None"}` value must NOT fall through to the
1623    /// default, only a genuinely *absent* key may). Real JS/TS grammar puts
1624    /// `in` at the exact same `RelationalExpression` precedence tier as
1625    /// `<`/`>`/`instanceof` (all five — plus `<=`/`>=`, unmodelled here —
1626    /// share one level in the spec), so it joins [`TsBinaryOp::LessThan`]'s
1627    /// tier rather than a new one, the same "share, don't multiply, tiers"
1628    /// convention `InstanceOf`/`LessThan` already set. Rendered as the
1629    /// keyword `" in "`, the same textual-keyword-operator shape
1630    /// `InstanceOf` already established (not symbol punctuation).
1631    In,
1632    /// `>=` — #1471's own real gap: `pred_condition_and_message`'s
1633    /// (`bynk-emit`) `NonNegative`/`InRange`/`InRangeF`/`MinLength` arms
1634    /// each build a real "at least" comparison (`{receiver} >= 0`,
1635    /// `{receiver} >= {a}`, `{receiver}.length >= {n}`) that this enum had
1636    /// no home for — [`TsBinaryOp::In`]'s own doc already named this exact
1637    /// gap ("plus `<=`/`>=`, unmodelled here"). Same `RelationalExpression`
1638    /// precedence tier as [`TsBinaryOp::GreaterThan`]/[`TsBinaryOp::
1639    /// LessThan`]/[`TsBinaryOp::InstanceOf`]/[`TsBinaryOp::In`] (real
1640    /// JS/TS puts all six at one level), rendered `" >= "` — symbol
1641    /// punctuation, matching `GreaterThan`/`LessThan`'s own convention,
1642    /// not a keyword like `InstanceOf`/`In`.
1643    GreaterThanEq,
1644    /// `<=` — the same gap's other half: `InRange`/`InRangeF`/`MaxLength`'s
1645    /// own "at most" comparison (`{receiver} <= {b}`, `{receiver}.length
1646    /// <= {n}`). Same tier and rendering convention as
1647    /// [`TsBinaryOp::GreaterThanEq`], symmetric with it the way
1648    /// `GreaterThan`/`LessThan` already are.
1649    LessThanEq,
1650}
1651
1652/// A literal — the three kinds `events_fanout.rs` uses (a string, a number,
1653/// `null`), plus `Bool` (#1323's own real gap: `workers_entry.rs`'s
1654/// `CorsPolicy.credentials`/`SecurityPolicy.nosniff` object-literal fields
1655/// are real booleans, e.g. `credentials: true`, `nosniff: false` — nothing
1656/// before this slice's own grounding ever built one).
1657#[derive(Debug, Clone)]
1658pub enum TsLit {
1659    Str(String),
1660    /// Rendered verbatim, as text — TypeScript's own numeric-literal
1661    /// grammar is not this crate's problem to re-derive; the caller passes
1662    /// the exact digits it wants printed.
1663    Num(String),
1664    Null,
1665    Bool(bool),
1666    /// The complete literal text, printed exactly as given — no quoting, no
1667    /// escaping, nothing added or removed. #1325's own real, narrow gap:
1668    /// `emit_test_main`'s own `const PREFIX = "system · ";` embeds
1669    /// a literal JS unicode escape (six ASCII characters, `·`) as
1670    /// pre-formed text — [`TsLit::Str`]'s own escaper (which turns every `\`
1671    /// it sees into `\\`) would double that literal backslash, corrupting
1672    /// this specific byte-golden output. The same "already a raw-text slot"
1673    /// boundary [`TsExpr::TemplateLit`]'s own `parts` field documents, just
1674    /// for a whole literal (quotes included) rather than a template
1675    /// literal's own static segments. One real site — not a general
1676    /// escaping bypass for ordinary string content, which stays on
1677    /// `TsLit::Str`.
1678    Raw(String),
1679}
1680
1681/// A type-position node. `Named` (extended with type arguments — a real gap
1682/// the reference sketch left unaddressed: `Record<string,
1683/// Array<{...}>>`/`Promise<Response>` both need one, and a bare `Named`
1684/// with no type-argument slot cannot represent either), `Array` (extended
1685/// with a `readonly` modifier — P7.9's own real gap: every `List`/`Query`
1686/// element type `bynk-emit`'s `ts_type_ref*`/`ts_ty` families build is
1687/// `readonly T[]`, not plain `T[]`), `Object`, and `Fn` (P7.9's own second
1688/// real gap — the query-thunk wrapper `(() => readonly T[])` and a real
1689/// parametered function type `(a0: T0, …) => Ret` both need one) — not the
1690/// sketch's `Union`/`Intersection`/`Literal`/`TypeParam`/`Readonly` (still
1691/// unused; `readonly` here is a modifier on `Array`, not the sketch's own
1692/// separate `Readonly` wrapper variant).
1693#[derive(Debug, Clone)]
1694pub enum TsType {
1695    /// A named type, optionally generic — `string`/`unknown` (no type
1696    /// arguments) or `Record<string, T>`/`Promise<Response>` (some).
1697    Named {
1698        name: String,
1699        type_args: Vec<TsType>,
1700    },
1701    /// `T[]` (`readonly: false`) or `readonly T[]` (`readonly: true`) —
1702    /// TypeScript's own postfix array-type syntax (not the equivalent
1703    /// `Array<T>`/`ReadonlyArray<T>` generic spelling either family uses).
1704    ///
1705    /// The printer parenthesises `element` wherever a bare postfix `[]`
1706    /// would bind to the wrong thing (#1898): a readonly array (`readonly
1707    /// T[][]` is TS1354), a [`TsType::Fn`] (whose `[]` would bind to its
1708    /// return type), a [`TsType::Union`] and a [`TsType::Intersection`]
1709    /// (`A | B[]` reads as `A | (B[])`). So `Array` over any element prints
1710    /// correctly as built — a caller must not wrap the element itself, or
1711    /// it double-parenthesises. The rule is `needs_parens_as_array_element`
1712    /// in `printer.rs`. This closes the hazard the review of #1315/#1316
1713    /// recorded here.
1714    Array {
1715        element: Box<TsType>,
1716        readonly: bool,
1717    },
1718    /// A type-position object shape, e.g. `{ type: string; payload: unknown }`
1719    /// — semicolon-separated, always printed on one line (see
1720    /// [`TsExpr::Object`]'s own doc for the value-position contrast). An
1721    /// `interface`'s own *members* are each printed on their own line by
1722    /// [`TsDecl::Interface`]'s printer, independent of this variant's own
1723    /// (always-inline) rendering — the two only look different because
1724    /// `TsDecl::Interface` is the thing choosing to put each member on its
1725    /// own line, not because `Object` has two rendering modes.
1726    ///
1727    /// #1323 replaced the plain `Vec<(String, TsType, bool)>` (`optional`
1728    /// only, #1321) with [`TsTypeMember`] — `workers_entry.rs`'s own real
1729    /// gap needed both a `readonly` modifier (every structural type this
1730    /// file builds is `readonly`-qualified, e.g. `{ readonly cron: string;
1731    /// readonly scheduledTime: number }`) and a method-signature member
1732    /// (`ack(): void`, `retry(): void`, `waitUntil(promise: Promise<
1733    /// unknown>): void`), neither representable by one more anonymous
1734    /// tuple `bool` — a fourth positional `bool` next to `optional` would
1735    /// be genuinely ambiguous at call sites (`readonly` vs. `optional`, ordered
1736    /// how?), the same reasoning [`TsObjectEntry`] already used over a raw
1737    /// tuple for the value-position sibling.
1738    Object(Vec<TsTypeMember>),
1739    /// `(a0: T0, a1: T1, …) => Ret` — a function type. Parameters carry no
1740    /// name of their own (just their type); the printer numbers them
1741    /// positionally (`a0`, `a1`, …), matching the exact convention
1742    /// `bynk-emit`'s own pre-P7.9 `ts_type_ref_with`/`ts_ty` already used
1743    /// (TypeScript requires *some* name in function-type syntax, and
1744    /// nothing about a `TypeRef::Fn`/`Ty::Fn` parameter carries a real one
1745    /// to use instead). A zero-`params` `Fn` is the query-thunk wrapper
1746    /// shape, `() => Ret`. Inside a [`TsType::Array`] the printer
1747    /// parenthesises it (`readonly ((a0: T) => U)[]`); see that variant's
1748    /// own doc.
1749    Fn {
1750        params: Vec<TsType>,
1751        ret: Box<TsType>,
1752    },
1753    /// `A | B | C` — a type-position union. Added in review of #1315:
1754    /// `bynk-emit`'s `ts_ty` builds a real union type for a resolved
1755    /// multi-actor sum (`Ty::ActorSum`, discriminated-union members tagged
1756    /// by actor name), a shape none of `Named`/`Array`/`Object`/`Fn` can
1757    /// represent — a real, grounded gap the same way `readonly`/`Fn`
1758    /// themselves were (P7.9's own accepted proposal), not a speculative
1759    /// addition. Each member prints through the ordinary `render_type`
1760    /// recursion; a member that is itself a `Union` is legal to construct
1761    /// but nothing in `bynk-emit` builds one today. Inside a
1762    /// [`TsType::Array`] the printer parenthesises it (`(A | B)[]`); see that
1763    /// variant's own doc.
1764    ///
1765    /// `multiline` (#1339): `false` (via [`TsType::union`]) is this variant's
1766    /// original single-line `A | B | C` form, unchanged. `true` (via
1767    /// [`TsType::multiline_union`]) is `emit_sum_type`'s own real
1768    /// discriminated-union shape — one variant per line, a leading `|` on
1769    /// every line *except* the first (which gets equivalent spacing
1770    /// instead), the closing `;` appended directly to the last variant's own
1771    /// line. Mirrors [`TsExpr::Object`]'s own `multiline` field precedent
1772    /// (#1317), but — unlike that one — needs no depth-aware wrapper: the
1773    /// pre-conversion `writeln!` code this reproduces always used a fixed
1774    /// two-space indent regardless of nesting (this shape is only ever a
1775    /// top-level `export type` alias body, never nested inside another
1776    /// type), so `render_type` stays entirely depth-unaware here too. Only
1777    /// rendered correctly from [`TsDecl::TypeAlias`]'s own top-level
1778    /// render — not reachable, and not given a defined rendering, from any
1779    /// nested position (an array element, a type argument, …), the same
1780    /// named boundary [`TsExpr::Object`]'s own `multiline` doc already
1781    /// draws for its own nested case.
1782    Union {
1783        members: Vec<TsType>,
1784        multiline: bool,
1785    },
1786    /// `A & B` — a type-position intersection. #1339's own real gap:
1787    /// `emit_refined_type`'s own branded-type alias,
1788    /// `{base} & { readonly __brand: "..." }`, has no representation among
1789    /// `Named`/`Array`/`Object`/`Fn`/`Union` — mirrors `Union`'s own
1790    /// shape/precedent exactly (a flat `Vec`, each member printed through
1791    /// the ordinary `render_type` recursion, joined by ` & `), single-line
1792    /// only (nothing in `bynk-emit` builds a multi-line intersection).
1793    Intersection(Vec<TsType>),
1794}
1795
1796impl TsType {
1797    /// A plain named type with no type arguments — `string`, `unknown`,
1798    /// `Request`, …
1799    pub fn named(name: impl Into<String>) -> Self {
1800        TsType::Named {
1801            name: name.into(),
1802            type_args: Vec::new(),
1803        }
1804    }
1805
1806    /// A generic named type — `Record<K, V>`, `Promise<T>`, …
1807    pub fn named_with_args(name: impl Into<String>, type_args: Vec<TsType>) -> Self {
1808        TsType::Named {
1809            name: name.into(),
1810            type_args,
1811        }
1812    }
1813
1814    /// `T[]` — the non-`readonly` array shape.
1815    pub fn array(element: TsType) -> Self {
1816        TsType::Array {
1817            element: Box::new(element),
1818            readonly: false,
1819        }
1820    }
1821
1822    /// `readonly T[]`.
1823    pub fn readonly_array(element: TsType) -> Self {
1824        TsType::Array {
1825            element: Box::new(element),
1826            readonly: true,
1827        }
1828    }
1829
1830    /// `A | B | C` — the original single-line union form, unchanged.
1831    pub fn union(members: Vec<TsType>) -> Self {
1832        TsType::Union {
1833            members,
1834            multiline: false,
1835        }
1836    }
1837
1838    /// `emit_sum_type`'s own real multi-line discriminated-union shape — see
1839    /// [`TsType::Union`]'s own doc for the exact rendering rules and why
1840    /// this needs no depth parameter.
1841    pub fn multiline_union(members: Vec<TsType>) -> Self {
1842        TsType::Union {
1843            members,
1844            multiline: true,
1845        }
1846    }
1847
1848    /// `A & B` — an intersection type.
1849    pub fn intersection(members: Vec<TsType>) -> Self {
1850        TsType::Intersection(members)
1851    }
1852}
1853
1854/// One member of a [`TsType::Object`] structural type — a property (`Prop`)
1855/// or a method signature (`Method`, #1323's own real gap: `ack(): void`,
1856/// `retry(): void`, `waitUntil(promise: Promise<unknown>): void` — no body,
1857/// a type-position sibling to [`TsObjectEntry::Method`], which does carry
1858/// one). `Method`'s own parameters reuse [`TsParam`] directly (not a bare
1859/// `Vec<TsType>` the way [`TsType::Fn`]'s anonymous, positionally-numbered
1860/// parameters do) — `waitUntil`'s own real parameter has a real name
1861/// (`promise`) the printed text must show, unlike `Fn`'s callers, none of
1862/// which have one to show.
1863#[derive(Debug, Clone)]
1864pub enum TsTypeMember {
1865    Prop {
1866        name: String,
1867        ty: TsType,
1868        optional: bool,
1869        readonly: bool,
1870    },
1871    /// `generics`/`doc` added by #1357: `emit_capability`'s own interface
1872    /// methods are genuinely generic (`op<T>(...): ret;`, no
1873    /// monomorphisation) and doc-commented — bare generic names, matching
1874    /// every other real generics-list precedent in this crate; `doc`
1875    /// mirrors `TsObjectEntry::Method.doc`'s own identical field (#1337).
1876    /// Both default empty/`None` via [`TsTypeMember::method`]'s own
1877    /// existing constructor — every one of its 6 real pre-#1357 callers is
1878    /// unaffected.
1879    ///
1880    /// `doc` renders from exactly one of this variant's two reachable
1881    /// positions: `TsDecl::Interface`'s own render arm (a real, multi-line
1882    /// declaration body with `depth` available, so it calls
1883    /// `render_doc_comment` before a documented member's own line — the
1884    /// only place `doc` is honoured). A `Method` reached through
1885    /// `TsType::Object`'s own inline, single-line shape (a type-position
1886    /// object literal, e.g. `{ a: X; b(): Y }`) has no line budget for a
1887    /// JSDoc block at all — `doc: Some(_)` there is a real, `debug_assert`-
1888    /// guarded misuse (`render_type`'s own `TsType::Object` arm), the same
1889    /// "loud, not silently dropped" precedent review of #1338 already
1890    /// established for `render_object_entry_inline`'s identical
1891    /// `TsObjectEntry::Method.doc` case.
1892    Method {
1893        name: String,
1894        generics: Vec<String>,
1895        params: Vec<TsParam>,
1896        ret: TsType,
1897        doc: Option<String>,
1898    },
1899    /// `[key_name: key_ty]: value_ty` — a TypeScript index signature.
1900    /// #1323's own real gap: `workers_entry.rs`'s multi-param `on call`
1901    /// dispatch casts its raw JSON args object through `{ [k: string]:
1902    /// JsonValue }` before indexing it by field name — textually distinct
1903    /// from the semantically-equivalent `Record<string, JsonValue>` (a
1904    /// `Named` type with type arguments), which `bynk-emit`'s own
1905    /// pre-conversion `writeln!` never wrote here. The one real site.
1906    Index {
1907        key_name: String,
1908        key_ty: TsType,
1909        value_ty: TsType,
1910    },
1911}
1912
1913impl TsTypeMember {
1914    /// `name: ty` — the ordinary, non-`optional`, non-`readonly` case.
1915    pub fn prop(name: impl Into<String>, ty: TsType) -> Self {
1916        TsTypeMember::Prop {
1917            name: name.into(),
1918            ty,
1919            optional: false,
1920            readonly: false,
1921        }
1922    }
1923
1924    /// `name?: ty`.
1925    pub fn optional_prop(name: impl Into<String>, ty: TsType) -> Self {
1926        TsTypeMember::Prop {
1927            name: name.into(),
1928            ty,
1929            optional: true,
1930            readonly: false,
1931        }
1932    }
1933
1934    /// `readonly name: ty`.
1935    pub fn readonly_prop(name: impl Into<String>, ty: TsType) -> Self {
1936        TsTypeMember::Prop {
1937            name: name.into(),
1938            ty,
1939            optional: false,
1940            readonly: true,
1941        }
1942    }
1943
1944    /// `name(params): ret` — no body, no generics, no doc comment.
1945    pub fn method(name: impl Into<String>, params: Vec<TsParam>, ret: TsType) -> Self {
1946        TsTypeMember::Method {
1947            name: name.into(),
1948            generics: Vec::new(),
1949            params,
1950            ret,
1951            doc: None,
1952        }
1953    }
1954
1955    /// `[key_name: key_ty]: value_ty`.
1956    pub fn index(key_name: impl Into<String>, key_ty: TsType, value_ty: TsType) -> Self {
1957        TsTypeMember::Index {
1958            key_name: key_name.into(),
1959            key_ty,
1960            value_ty,
1961        }
1962    }
1963}
1964
1965/// One function/method/constructor parameter.
1966#[derive(Debug, Clone)]
1967pub struct TsParam {
1968    pub name: String,
1969    pub ty: Option<TsType>,
1970    /// `name?: ty` — `events_fanout.rs`'s own `env?: unknown` constructor
1971    /// parameter needs this; nothing in the grounding file needs a default
1972    /// value, so only optionality is represented, not defaults.
1973    pub optional: bool,
1974}
1975
1976/// One `class` field.
1977#[derive(Debug, Clone)]
1978pub struct TsClassField {
1979    pub name: String,
1980    pub ty: TsType,
1981    /// `private` — the one visibility modifier `events_fanout.rs` uses
1982    /// (`private env: ...`). Not a decorator or a constructor parameter
1983    /// property (R7.1 forbids both categorically — there is no variant
1984    /// shape here that could construct either).
1985    pub private: bool,
1986}
1987
1988/// A class's own constructor.
1989#[derive(Debug, Clone)]
1990pub struct TsClassCtor {
1991    pub params: Vec<TsParam>,
1992    pub body: Vec<TsStmt>,
1993}
1994
1995/// One class method.
1996#[derive(Debug, Clone)]
1997pub struct TsClassMethod {
1998    pub name: String,
1999    /// `private {name}(...)`, e.g. `loadState`/`commitState` — the
2000    /// grounding pass's own predicted gap (#1366), closed by Arc C's own
2001    /// `emit_agent` class-scaffold slice: every real `TsClassMethod` site
2002    /// before this one (`emit_provider` #1359's own op methods) was
2003    /// public-only. Rendered before `async`, matching the one real site's
2004    /// own modifier order (`private async loadState()`, not `async private
2005    /// loadState()`).
2006    pub private: bool,
2007    pub is_async: bool,
2008    pub params: Vec<TsParam>,
2009    pub return_type: Option<TsType>,
2010    /// A JSDoc block immediately preceding the method — the grounding
2011    /// pass's own second predicted gap (#1366), closed alongside `private`'s
2012    /// own sibling site: `emit_agent`'s own per-handler methods each carry
2013    /// a doc comment (`emit_doc_block`'s pre-conversion standalone call),
2014    /// the same need `TsObjectEntry::Method.doc` (#1337) and
2015    /// `TsTypeMember::Method.doc` (#1357) already solved for their own node
2016    /// kinds. Rendered the identical way those two already are — a
2017    /// `TsStmtKind::DocComment`-shaped block at the method's own indent,
2018    /// immediately before its header line.
2019    pub doc: Option<String>,
2020    pub body: Vec<TsStmt>,
2021}
2022
2023/// A top-level declaration. `Import`, `Export`, `Interface`, `ConstDecl`,
2024/// and `Class` were `events_fanout.rs`'s own grounding (P7.8's own note:
2025/// "not the sketch's `Function`/`TypeAlias` — unused in the grounding
2026/// file"). #1321 (`workers.rs`) needed both after all — a real gap the
2027/// accepted proposal's own Framing didn't name (its own "no other gap
2028/// surfaced" checked `TsStmt`/`TsExpr`/`TsType` shapes, not `TsDecl` ones):
2029/// `compose.ts`'s own `export function compose(env: Env, …) { … }` is a
2030/// top-level function declaration, and (when the Worker has agents or
2031/// publishes events) a `type DurableObjectNamespace = { … };` fallback
2032/// alias sits alongside it. Named explicitly as a deviation from the
2033/// accepted proposal's own catalogue, not silently added — both are
2034/// mechanical, direct `TsDecl` siblings of `ConstDecl`/`Class` already
2035/// here, the same "small, grounded, same class of gap" this track's own
2036/// history repeatedly found and closed (P7.8's `Assign`/`Continue`/
2037/// `TryCatch`, Arc C slice 1's `Comment`).
2038#[derive(Debug, Clone)]
2039pub enum TsDecl {
2040    /// `import { a, b } from "spec";` (`type_only: false`) or
2041    /// `import type { a, b } from "spec";` (`type_only: true`). Only the
2042    /// named-imports form — `events_fanout.rs` never uses a default
2043    /// import, so none is represented. `names` entries are pushed verbatim
2044    /// (`printer.rs`'s own `names.join(", ")`), so a renamed import
2045    /// (`__messagesLocales as __locale_declaredLocales`, `workers.rs`'s own
2046    /// locale-negotiation import) is one opaque `String` entry, not a
2047    /// structured rename — the same "the field is already a raw-text slot"
2048    /// reasoning that also covers a `type`-prefixed single specifier
2049    /// (`"type KVNamespace"`) inside an otherwise non-`type_only` import.
2050    Import {
2051        type_only: bool,
2052        names: Vec<String>,
2053        from: String,
2054    },
2055    /// `import * as alias from "spec";` — a namespace import, structurally
2056    /// different from [`TsDecl::Import`]'s braced named-imports form (no
2057    /// `{ }`, one bound name for the whole module). #1321's own real gap:
2058    /// `workers.rs`'s `compose.ts` imports `handlers.js` and each
2059    /// referenced unit's binding module this way; `events_fanout.rs` never
2060    /// used one. `type_only` (Arc C, step (10), #1392) mirrors
2061    /// [`TsDecl::Import`]'s own identical field, a parallel gap by
2062    /// omission, not deliberate design — `emit_cross_context_namespace_
2063    /// imports`'s own real `import type * as ns from "...";` form (a
2064    /// Workers-mode consumed-context import reaching the callee's types
2065    /// only, #661) had no way to represent the `type` keyword until now.
2066    ImportNamespace {
2067        type_only: bool,
2068        alias: String,
2069        from: String,
2070    },
2071    /// `import name from "spec";` — a default import, structurally
2072    /// different from both [`TsDecl::Import`] (braced named-imports form)
2073    /// and [`TsDecl::ImportNamespace`] (`* as` form) — no braces, no `* as`,
2074    /// one bound local name for the module's own default export. No
2075    /// `type_only` form — nothing in the grounding file default-imports a
2076    /// type. Arc C, slice 37 (#1409, `tests_emit.rs`'s own slice G): a
2077    /// per-participant `import worker_{ns} from "../workers/{dir}/
2078    /// index.js";` (the participant's own Worker entry module's default
2079    /// export) is the first real default import anywhere in `bynk-emit`'s
2080    /// own converted content — every prior import site is either named
2081    /// ([`TsDecl::Import`]) or namespace ([`TsDecl::ImportNamespace`]).
2082    ImportDefault { alias: String, from: String },
2083    /// `export { a, b } from "spec";` — a re-export, structurally distinct
2084    /// from both [`TsDecl::Import`] (which binds locally, carries no
2085    /// `export` keyword) and [`TsDecl::Export`] (which wraps a whole
2086    /// declaration, not a braced name list re-pointed at another module).
2087    /// #1323's own real gap: `workers_entry.rs` re-exports each agent's
2088    /// Durable Object class from `./handlers.js`, and (when the context
2089    /// publishes events) the fan-out DO's class from `./events_fanout.js`.
2090    /// No `type_only` form — nothing in the grounding file re-exports a
2091    /// type-only name.
2092    ReExport { names: Vec<String>, from: String },
2093    /// `export { a, b };` — exports names already bound in this module (an
2094    /// import's, typically), with no `from` clause, which [`TsDecl::ReExport`]
2095    /// always carries. A Workers context re-exports the boundary codecs it
2096    /// imports from a `uses`d commons this way. #1820: a structured variant,
2097    /// not opaque text, so [`TsStmt::exported_names`] reports what the module
2098    /// exports to a barrel that must find the names two modules both export.
2099    ExportNames { names: Vec<String> },
2100    /// `export * from "spec";` — a wildcard re-export, structurally distinct
2101    /// from [`TsDecl::ReExport`] (which always carries a braced name list —
2102    /// an empty `names` there would render the ill-formed `export {  }
2103    /// from "spec";`, not this). Mirrors [`TsDecl::ImportNamespace`]'s own
2104    /// "no braces, no name list, one bound target" shape, on the export
2105    /// side. #1329's own real gap: `emit_commons_barrel`
2106    /// (`bynk-emit/src/project/tests_emit.rs`) builds a multi-file
2107    /// `commons` unit's barrel module as one `export *` line per
2108    /// constituent source file.
2109    ReExportAll { from: String },
2110    /// Marks the wrapped declaration `export`ed — `export class Foo { .. }`
2111    /// is `Export(Box::new(Class { .. }))`. A wrapper, not a per-variant
2112    /// `exported: bool` field, matching the reference sketch's own naming
2113    /// (`TsDecl::Export` is a peer variant, not a modifier on each other
2114    /// one).
2115    Export(Box<TsDecl>),
2116    /// `type_params`/per-member `readonly` (#1339's own real gap):
2117    /// `emit_record_type`'s own `export interface {name}{params} {
2118    /// readonly {field}: {ty}; ... }` — bare generic names (matching
2119    /// `ts_type_params`'s/`TsObjectEntry::Method.generics`'s own
2120    /// convention) and a `readonly` modifier every real field here
2121    /// carries. `members` reuses [`TsTypeMember`] (the exact same shape
2122    /// [`TsType::Object`]'s own structural members already use) rather
2123    /// than a bespoke tuple, since `readonly` is already that type's own
2124    /// field — this interface's real content has never needed
2125    /// `Method`/`Index`, but nothing about reusing the shared type
2126    /// forecloses a future slice that does.
2127    Interface {
2128        name: String,
2129        type_params: Vec<String>,
2130        members: Vec<TsTypeMember>,
2131    },
2132    /// A top-level `const` — distinct from `TsStmtKind::Const` (private —
2133    /// reachable through [`TsStmt::const_stmt`]), the local
2134    /// form.
2135    ConstDecl {
2136        name: String,
2137        ty: Option<TsType>,
2138        init: TsExpr,
2139    },
2140    Class {
2141        name: String,
2142        fields: Vec<TsClassField>,
2143        constructor: Option<TsClassCtor>,
2144        methods: Vec<TsClassMethod>,
2145    },
2146    /// `function name(params): ret { body }` (`is_async: false`) or `async
2147    /// function name(params): ret { body }` (`is_async: true`) — a top-level
2148    /// function declaration. `is_async` added by #1325: `workers.rs`'s own
2149    /// one real site (`compose`) is never async, so the field didn't exist
2150    /// until `emit_test_main`'s own top-level `async function main() {...}`
2151    /// needed it — the exact "extend narrowly, add it when a future slice's
2152    /// own grounding needs it" deferral this variant's own history already
2153    /// named. `generics` added by #1351: `emit_free_fn`'s own v0.20a erased
2154    /// generics (`export function foo<T>(...)`) — bare names only, empty
2155    /// for every non-generic site (`compose`/`main`), matching every other
2156    /// real generics-list precedent in this crate
2157    /// (`TsObjectEntry::Method.generics` #1337, `TsExpr::Arrow.generics`
2158    /// #1339). `inline` added by #1369 (Arc C, slice 20, step (9)'s own
2159    /// second sub-slice): `emit_agent`'s own zero-factory function
2160    /// (`function __zeroOf{Name}State(): {Name}State { return {...}; }`) is
2161    /// a genuinely single-physical-line declaration — braces and body share
2162    /// the header's own line, not `render_block_stmts`'s always-multi-line
2163    /// shape. `false` (every site landed before #1369) renders the ordinary
2164    /// multi-line body; `true` reuses `render_inline_block`'s own compact
2165    /// `{ stmt; stmt; }` shape directly at the declaration's own header
2166    /// line, the same "one more bool, mirroring an existing precedent"
2167    /// scope `TsObjectEntry::Method.inline` (#1337) already set for the
2168    /// identical single-line-vs-multi-line tension at a different node kind.
2169    Function {
2170        name: String,
2171        generics: Vec<String>,
2172        params: Vec<TsParam>,
2173        return_type: Option<TsType>,
2174        body: Vec<TsStmt>,
2175        is_async: bool,
2176        inline: bool,
2177    },
2178    /// `type name = ty;` (non-generic) or `type name<T, U> = ty;` (via
2179    /// `type_params`, #1339's own real gap: `emit_sum_type`'s own generic
2180    /// sum types erase to `export type Foo<T> = ...`) — a top-level type
2181    /// alias. `workers.rs`'s own real site: the `DurableObjectNamespace`
2182    /// local fallback type (emitted only when the Worker has agents or
2183    /// publishes events), never generic — `type_params` is empty there.
2184    TypeAlias {
2185        name: String,
2186        type_params: Vec<String>,
2187        ty: TsType,
2188    },
2189    /// `export default <expr>;` — a default export of an *expression*, not
2190    /// a declaration. #1323's own real gap (`workers_entry.rs`'s own
2191    /// top-level shape, `export default { fetch, scheduled?, queue? }`):
2192    /// [`TsDecl::Export`] wraps a [`TsDecl`] (a `Class`/`ConstDecl`/etc.,
2193    /// something with its own name), which cannot represent exporting a
2194    /// bare, unnamed object-literal expression — so this is its own
2195    /// variant, not `Export(Box::new(ConstDecl { .. }))` with a synthetic
2196    /// name that would print wrong.
2197    ExportDefault(TsExpr),
2198    /// `declare const name: ty;` — an ambient binding with no initialiser,
2199    /// narrowing a global TypeScript otherwise doesn't know about. #1325's
2200    /// own real, narrow site: `emit_test_main`'s own `declare const process:
2201    /// { exit(code: number): never; env: { [k: string]: string | undefined
2202    /// } };`, narrowing Node's `process` global without a `@types/node`
2203    /// dependency. Distinct from [`TsDecl::ConstDecl`] (always has a real
2204    /// `init` expression) — a `declare const` has none, by definition; a
2205    /// `TsDecl::ConstDecl` with a synthetic placeholder `init` would print
2206    /// wrong (`= <something>;` where nothing should appear at all).
2207    DeclareConst { name: String, ty: TsType },
2208}
2209
2210/// Which family of residual, not-yet-converted emission a [`TsStmt::verbatim`]
2211/// statement came from. A closed enum, deliberately — "makes the ratchet a
2212/// compile-time construct, not a grep" (Q2's own settling text). Named
2213/// file-by-file as Arc C actually needs them (`ast_importers`'s own five-file
2214/// floor is the precedent for how this track names residue), not
2215/// pre-populated for the whole ~19-slice Arc C schedule up front.
2216///
2217/// Deliberately **not** `#[non_exhaustive]`: a `match` over every variant —
2218/// in this crate, or in `bynk-emit` once Arc C reads it — must fail to
2219/// compile the moment a new variant is added, forcing every consumer to
2220/// account for it explicitly. A non-exhaustive enum would let a wildcard arm
2221/// silently absorb a new residue family instead, exactly the "grep, not a
2222/// compile-time construct" Q2's own settling text rejected. P7.8's own
2223/// grounding work found that `Contracts`/`Secrets`/`RuntimeUse` were seeded
2224/// against files that turn out not to need `bynk-ts` conversion at all
2225/// (`design/tracks/the-typescript-tree.md` §9) — recorded there, not fixed
2226/// by removing the variants here, since that's separate follow-on work.
2227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2228pub enum VerbatimOrigin {
2229    /// `bynk-emit/src/emitter/contracts.rs`.
2230    Contracts,
2231    /// `bynk-emit/src/emitter/secrets.rs`.
2232    Secrets,
2233    /// `bynk-emit/src/emitter/runtime_use.rs`.
2234    RuntimeUse,
2235    /// P7.6's own transitional wrap (#1309): the whole of a still-`String`-
2236    /// producing `bynk-emit` document (an entry point, `compose.ts`, the
2237    /// runtime module, an adapter binding, a test module, …), carried into
2238    /// `Document::Ts` so `Artefacts` never stores a bare `String` for TS
2239    /// output (R7.8) even before Arc C converts the function that built it.
2240    /// Deliberately **not** file-specific like the three variants above —
2241    /// this is Arc B's own infrastructure slice, not an Arc C conversion, so
2242    /// it covers everything Arc C hasn't reached yet, one call site per
2243    /// document `bynk-emit/src/project.rs`/`project/tests_emit.rs`
2244    /// constructs (not funnelled through a shared helper: a shared wrap
2245    /// point would collapse every one of those call sites to a single
2246    /// textual `TsStmt::verbatim(` occurrence, defeating `verbatim_sites`'
2247    /// own purpose of counting how much is genuinely still unconverted).
2248    /// Retires site by site as Arc C converts each underlying emitter
2249    /// function to return a real `TsProgram` directly — at which point that
2250    /// document's own construction site stops calling `TsStmt::verbatim` at
2251    /// all, not by this variant being deleted first.
2252    NotYetConverted,
2253    /// `bynk-emit/src/emitter/emit.rs`'s own residual [`TsExpr::VerbatimExpr`]
2254    /// leaves (#1539) — a generic-typed callee, a printer-unsafe nested `As`
2255    /// chain, a block-bodied ICU IIFE, and a pre-escaped/unescaped predicate
2256    /// message, none reducible to a real node without expanding this crate's
2257    /// own type algebra past what #1539 asks for. Expression-level, not
2258    /// statement-level like the three file-specific variants above (this is
2259    /// the first `VerbatimOrigin` a `TsExpr` carries, not a `TsStmt`), but
2260    /// named the same file-by-file way.
2261    Emit,
2262}
2263
2264#[cfg(test)]
2265mod tests {
2266    use super::*;
2267
2268    #[test]
2269    fn verbatim_carries_its_own_span() {
2270        let span = Span::new(3, 8);
2271        let stmt = TsStmt::verbatim(VerbatimOrigin::RuntimeUse, "x", Some(span));
2272        assert_eq!(stmt.span, Some(span));
2273    }
2274
2275    #[test]
2276    fn a_program_prints_its_statements_in_push_order() {
2277        // Kept as a construction-order check (not a print check — printer.rs
2278        // owns that) since `TsStmtKind` is `pub(crate)` and no longer
2279        // exposes a uniform `text()` accessor once non-`Verbatim` kinds
2280        // exist; span order is what's left to check at this layer.
2281        let mut program = TsProgram::new();
2282        program.push(TsStmt::verbatim(VerbatimOrigin::Contracts, "a", None));
2283        program.push(TsStmt::verbatim(
2284            VerbatimOrigin::Secrets,
2285            "b",
2286            Some(Span::new(0, 1)),
2287        ));
2288        assert_eq!(program.stmts[0].span, None);
2289        assert_eq!(program.stmts[1].span, Some(Span::new(0, 1)));
2290    }
2291
2292    /// Review of #1326, finding 1: `TsExpr::template_lit`'s own
2293    /// `debug_assert_eq!` must actually fire on a malformed tree, not just
2294    /// exist as documentation — proves the guard guards, the same "prove
2295    /// it" discipline this crate applies to every other invariant.
2296    #[test]
2297    #[should_panic(expected = "parts.len() must be exprs.len() + 1")]
2298    fn template_lit_rejects_a_parts_exprs_count_mismatch() {
2299        let _ = TsExpr::template_lit(
2300            vec!["a".to_string()],
2301            vec![TsExpr::Ident("too_many".to_string())],
2302        );
2303    }
2304}