Skip to main content

bynk_ts/program/
expr.rs

1#[cfg(doc)]
2use super::{TsClassMethod, TsDecl};
3use super::{TsParam, TsStmt, TsType, VerbatimOrigin};
4use bynk_syntax::span::Span;
5
6/// An expression. Only the shapes `events_fanout.rs` concretely uses
7/// (Decision B) — not the reference sketch's full `TsExpr` list (`Arrow`,
8/// `Cond`, `TemplateLit`, `Spread` are all unused in the grounding file and
9/// deliberately not built here). Arc C slice 3 (#1321, `workers.rs`) adds
10/// `Arrow`, `OptionalMember`/`OptionalIndex` (Decision A, gaps 3/4) — this
11/// slice's own real, grounded needs.
12#[derive(Debug, Clone, PartialEq)]
13pub enum TsExpr {
14    /// A real identifier — the only content this variant is for. #1539
15    /// (review of `design/reviews/2026-08-30-post-restructuring-review.md`
16    /// Part 3/Part 5 §1): before this doc existed, `bynk-emit` also smuggled
17    /// non-identifier text through it at 15 call sites in `emit.rs` alone —
18    /// a quoted string literal, `this.<method>` member access, a complete
19    /// `!(<pred>)` unary expression — an untagged `Verbatim`-shaped escape
20    /// hatch [`TsStmt::verbatim`]'s own doc already named the concern for
21    /// (Q2's "makes the ratchet a compile-time construct, not a grep"), just
22    /// with no tag and no probe watching it. Every one of those call sites
23    /// now either builds the matching real node (`Lit(TsLit::Str)`, `Member`,
24    /// `Unary`) or routes through [`TsExpr::VerbatimExpr`] instead — this
25    /// variant no longer holds anything but a genuine identifier.
26    Ident(String),
27    /// A residual, not-yet-converted expression carrying a [`VerbatimOrigin`]
28    /// tag — [`TsStmt::verbatim`]'s own discipline, closed for expressions
29    /// too (#1539). Printed exactly as [`TsExpr::Ident`] always was (raw
30    /// text, no escaping of its own — the caller is responsible for
31    /// producing valid, already-escaped TypeScript, the same contract
32    /// `TsStmt::verbatim`'s own text carries), but now visible to
33    /// [`crate::verbatim_violations`] and `xtask`'s own `verbatim_origins`/
34    /// `verbatim_sites` gated probes, which had nothing to watch at the
35    /// expression level before this variant existed. What ends up here after
36    /// #1539's own conversion pass: a generic-typed method/constructor
37    /// callee (`Call`/`New` have no `type_args` field), a block-bodied IIFE
38    /// with no matching `TsArrowBody` shape, and a `pred_condition_and_
39    /// message`-style message that is already pre-escaped or unescaped by
40    /// contract (a second escaping pass through `TsLit::Str` would corrupt
41    /// it) — none of these has a real node to convert to without expanding
42    /// this crate's own type algebra well past what #1539 asks for.
43    VerbatimExpr(String, VerbatimOrigin),
44    /// Expression text that also declares the names it uses (1A.36b-1): the
45    /// expression twin of [`TsStmt::raw_using`]. `text` prints exactly as an
46    /// [`TsExpr::Ident`]'s does and is bracketed as one is, so a caller whose
47    /// expression is *printed nodes* joined into one line (a form no node can
48    /// hold) keeps it, and `names` are the identifiers the text spells without
49    /// declaring, which `name_closure` counts as uses. The names are taken from
50    /// the nodes the text was printed from (`unbound_names_in` over them), never
51    /// scanned out of the text.
52    RawUsing(String, Vec<String>),
53    /// `object.property`.
54    Member {
55        object: Box<TsExpr>,
56        property: String,
57    },
58    /// `object?.property` — the optional-chaining form of [`TsExpr::Member`].
59    /// A distinct variant, not an `optional: bool` flag on `Member` itself
60    /// (#1321's own Decision A, gap 4, left the mechanism to the
61    /// implementation): a flag would touch every one of `Member`'s
62    /// already-many real call sites (`events_fanout.rs`, this crate's own
63    /// printer tests) that never need one, where a separate variant touches
64    /// none of them — narrower, matching this track's own repeated
65    /// "smallest correct scope" judgment. `workers.rs`'s own secret-probe
66    /// idiom (`emit_websocket_upgrade`/`emit_http_wrapper`/
67    /// `emit_secret_lookup`, three identical real sites) is the only
68    /// grounding.
69    OptionalMember {
70        object: Box<TsExpr>,
71        property: String,
72    },
73    /// `callee<A, B>`: a TypeScript instantiation expression (1A.20, #3721,
74    /// Decision A). A generic call is `Call { callee: TypeApp { .. }, args }`
75    /// (`f<T>(a)`) and a generic constructor `New { callee: TypeApp { .. }, args }`
76    /// (`new C<T>(a)`), so `Call` and `New` stay as they are. Postfix like
77    /// [`TsExpr::Member`]: the callee is bracketed under the rule `Call`'s own
78    /// callee uses.
79    ///
80    /// Valid only as the callee of a `Call` or a `New`: `f<T>.x` is TS1477 and `f<>` is a
81    /// syntax error, so `type_args` must not be empty and the printer asserts it, as it does
82    /// for [`TsExpr::Spread`].
83    TypeApp {
84        callee: Box<TsExpr>,
85        type_args: Vec<TsType>,
86    },
87    /// `((name = default): ret => { body })()`: an immediately invoked arrow whose one untyped
88    /// parameter takes its value from a default, which JS evaluates at call time, before the body
89    /// runs (1A.21, #3722). `Json.encodePlain` evaluates its argument this way before the body
90    /// raises a flag. A node of its own, rather than a default on [`TsParam`], so the 189 parameter
91    /// literals stay as they are. Prints as a call, so it takes the brackets a call takes.
92    DefaultIife {
93        name: String,
94        default: Box<TsExpr>,
95        return_type: TsType,
96        body: Vec<TsStmt>,
97    },
98    /// An array printed one item per line, each with a trailing comma and the
99    /// closing bracket back at the enclosing depth, wherever it sits (1A.14:
100    /// `par`'s `await __bynkSettleAll([…])`). Unlike [`TsExpr::Array`] with
101    /// `multiline: true`, which breaks only as a whole statement's initialiser,
102    /// this breaks as a call argument too.
103    LinesArray(Vec<TsExpr>),
104    /// `object[index]`.
105    Index {
106        object: Box<TsExpr>,
107        index: Box<TsExpr>,
108    },
109    /// `object?.[index]` — the optional-chaining form of [`TsExpr::Index`],
110    /// the same real grounding and the same "separate variant, not a flag"
111    /// reasoning as [`TsExpr::OptionalMember`].
112    OptionalIndex {
113        object: Box<TsExpr>,
114        index: Box<TsExpr>,
115    },
116    /// `(params) => body` (`is_async: false`) or `async (params) => body`
117    /// (`is_async: true`) — an arrow function, expression- or block-bodied
118    /// (see [`TsArrowBody`]). `is_async` added by #1327: `emit_composition_root`'s
119    /// own `__eventsDispatch` closure (`async (events: Array<...>) => {...}`)
120    /// is the first real `Arrow` site that's async — mirrors
121    /// `TsDecl::Function`'s own `is_async` field (#1325), added for the same
122    /// reason. `generics`/`return_type` added by #1339: `emit_sum_type`'s
123    /// own generic payload-constructor arrows (`<T>(name: T): Sum<T> =>
124    /// (...)`) need both — bare generic names only (empty for every
125    /// non-generic site, the overwhelming majority), matching
126    /// `TsObjectEntry::Method.generics`'s own (#1337) identical convention;
127    /// `return_type` mirrors `TsDecl::Function.return_type`'s own existing
128    /// `Option<TsType>` shape — a real gap the accepted proposal's own
129    /// grounding named `generics` for but missed: every one of this file's
130    /// own real generic-payload arrows carries an explicit return-type
131    /// annotation the arrow itself owns (`: {name}{params}`), not something
132    /// the body's own type alone determines.
133    ///
134    /// `body`'s type became [`TsArrowBody`] (#1435, Arc E slice 1): from
135    /// P7.8 through #1434 this field was a bare `Box<TsExpr>` — expression-
136    /// bodied only, "extend narrowly" (the same posture `TsBinaryOp` takes
137    /// for its own operator table), since every real site up to and
138    /// including #1339's generic payload-constructor arrows had an
139    /// expression body. `serialisation.rs`'s `serialise_field_expr_wire`
140    /// (`bynk-emit`) is the first real site that doesn't: its `Float`
141    /// non-finite guard is a genuine statement-bodied IIFE (`((v: number) =>
142    /// { if (!Number.isFinite(v)) throw new Error(...); return v as
143    /// JsonValue; })(value)`), not reducible to one expression. Widening the
144    /// existing field (`TsArrowBody::Expr(Box<TsExpr>)` |
145    /// `TsArrowBody::Block(Vec<TsStmt>)`) rather than adding a second
146    /// sibling `TsExpr` variant matches this file's own repeated
147    /// "extend the existing variant when every real site still needs the
148    /// same node kind, only the body shape differs" precedent
149    /// (`TsObjectEntry::Method.inline`, #1337) — every prior `Arrow`
150    /// construction site across the workspace wraps its already-correct
151    /// expression body in `TsArrowBody::Expr(..)`, a mechanical change with
152    /// no behavior difference.
153    Arrow {
154        params: Vec<TsParam>,
155        is_async: bool,
156        generics: Vec<String>,
157        return_type: Option<TsType>,
158        body: Box<TsArrowBody>,
159    },
160    Call {
161        callee: Box<TsExpr>,
162        args: Vec<TsExpr>,
163    },
164    New {
165        callee: Box<TsExpr>,
166        args: Vec<TsExpr>,
167    },
168    /// A value object literal, e.g. `{ status: 204 }` — comma-separated.
169    /// `multiline: false` (the ordinary case, via [`TsExpr::object`])
170    /// always prints on one line, matching [`TsType::Object`]'s own
171    /// (semicolon-separated) single-line convention for the *type*-position
172    /// shape. `multiline: true` (via [`TsExpr::multiline_object`]) is a
173    /// real, grounded gap found implementing Arc C's first slice (#1317):
174    /// `events_fanout.rs`'s own `__eventRoutes` table is a top-level
175    /// `const` initializer with one entry per line, each with its own
176    /// trailing comma, closing brace at the *statement's* own indent —
177    /// TypeScript's ordinary multi-line object-literal convention, which
178    /// nothing in this crate could represent before this addition. Only
179    /// statement/declaration-level renderers (which already carry `depth`)
180    /// can render this correctly — `printer/multiline.rs`'s own `render_stmt_level_
181    /// expr`, and (#1355) `render_multiline_object_entry`'s own `Prop` arm,
182    /// for a `multiline: true` object nested one level inside ANOTHER
183    /// multiline object as one of its own entries' values —
184    /// `emit_messages_bundle`'s own real doubly-nested `{ locale: { code:
185    /// expr, ... }, ... }` table. A `multiline: true` object nested any
186    /// OTHER way (an array element, a call argument, a `Prop`'s value
187    /// inside a non-multiline object, …) still renders via the ordinary
188    /// depth-unaware `render_expr` recursion, which cannot honour
189    /// `multiline` — not reachable from any real `bynk-emit` call site
190    /// today, but worth knowing before nesting one that way.
191    ///
192    /// `end_span` (1A.32a) is only read for `multiline: true`: the source span the
193    /// closing `}` line maps to, so what follows the last entry belongs to the
194    /// declaration the object initialises rather than to the last entry's final
195    /// body line. `None` records nothing. Build one with
196    /// [`TsExpr::multiline_object_ending_at`].
197    Object {
198        entries: Vec<TsObjectEntry>,
199        multiline: bool,
200        end_span: Option<Span>,
201    },
202    /// An array literal, e.g. `[{ binding: "x", service: "y" }]`.
203    /// `multiline: false` (the ordinary case, via [`TsExpr::array`]) always
204    /// prints on one line, comma-separated — every real site before this
205    /// slice. `multiline: true` (via [`TsExpr::multiline_array`]) is #1325's
206    /// own real gap: `emit_test_main`'s own `modules` array (one `{ name,
207    /// run }` entry per test, one per line, each with its own trailing
208    /// comma, closing `]` at the statement's own indent) — the exact same
209    /// shape [`TsExpr::Object`]'s own `multiline` field already represents
210    /// for object literals, just for an array. Same reachability boundary as
211    /// `Object`'s own `multiline` field (see its own doc, updated by
212    /// #1355): `render_stmt_level_expr` and `render_multiline_object_
213    /// entry`'s own `Prop` arm both honour it; nested any other way, a
214    /// `multiline: true` array falls back to single-line via the ordinary
215    /// depth-unaware `render_expr` recursion.
216    Array {
217        items: Vec<TsExpr>,
218        multiline: bool,
219    },
220    /// `` `text${expr}more text` `` — a template literal. `parts.len()` is
221    /// always `exprs.len() + 1` (`parts[0]` before the first substitution,
222    /// `parts[i+1]` after `exprs[i]`, …). #1325's own real, first grounding
223    /// for this shape (`bynk-ts`'s own module doc named `TemplateLit`
224    /// explicitly "unused in the grounding file" until now):
225    /// `emit_test_main`'s own `` `${m.name}:` ``/`` `${passed} passed,
226    /// ${failed} failed.` `` lines.
227    ///
228    /// **`parts` are printed verbatim — the printer applies no escaping of
229    /// its own.** The same "the field is already a raw-text slot" reasoning
230    /// [`TsDecl::Import`]'s own `names` field doc already uses, not a new
231    /// pattern: `emit_test_main`'s own two real ✓/✗ substitution lines embed
232    /// a literal `✓`/`✗` JS unicode escape as pre-formed ASCII
233    /// text (six literal characters, not the actual glyph) — an escaper
234    /// mirroring [`TsLit::Str`]'s own (which escapes every `\` it sees)
235    /// would double that literal backslash into `\\u2713`, corrupting the
236    /// exact byte-golden output this slice must match. Every real part in
237    /// `emit_test_main` is static, compiler-authored text (never Bynk user
238    /// data), so there is no real content this boundary loses safety on
239    /// today — a future caller passing untrusted/dynamic text into `parts`
240    /// is responsible for pre-escaping backtick/`` ${ ``/`\` itself before
241    /// constructing one.
242    TemplateLit {
243        parts: Vec<String>,
244        exprs: Vec<TsExpr>,
245    },
246    Await(Box<TsExpr>),
247    /// `expr as ty`.
248    As {
249        expr: Box<TsExpr>,
250        ty: TsType,
251    },
252    /// `expr as const`: a const assertion, which keeps a literal's own type
253    /// (`{ tag: "Some" as const }`). It is not an `As` over a type named
254    /// `const`: `const` is a keyword here, not a type.
255    AsConst(Box<TsExpr>),
256    Unary {
257        op: TsUnaryOp,
258        expr: Box<TsExpr>,
259    },
260    Binary {
261        op: TsBinaryOp,
262        left: Box<TsExpr>,
263        right: Box<TsExpr>,
264    },
265    /// `test ? consequent : alternate` — #1323's own real gap: `method ===
266    /// "HEAD" ? headResponse(__response) : __response` (once per `GET`
267    /// route) and `method === "OPTIONS" ? 204 : 405` (the method-fallthrough
268    /// path). The lowest-precedence expression form after `Arrow` — needs
269    /// the same parenthesization-rule coverage `Arrow` got in review of
270    /// #1322 (`needs_parens_as_operand`/`render_binary_operand`/`As`'s own
271    /// local rule), added proactively in this same slice rather than left
272    /// for a review round to re-find.
273    Conditional {
274        test: Box<TsExpr>,
275        consequent: Box<TsExpr>,
276        alternate: Box<TsExpr>,
277    },
278    /// [`TsExpr::Conditional`] broken over three lines (1A.38a): the test, then
279    /// `? consequent` and `: alternate` each on a line of their own, one level
280    /// deeper than the statement that holds it. A separate variant rather than a
281    /// `multiline` field, so none of the existing `Conditional` constructions
282    /// changes; it takes every precedence and parenthesisation rule `Conditional`
283    /// does. Build it with [`TsExpr::multiline_conditional`].
284    MultilineConditional {
285        test: Box<TsExpr>,
286        consequent: Box<TsExpr>,
287        alternate: Box<TsExpr>,
288    },
289    /// An explicit, printer-preserved parenthesization — distinct from every
290    /// other variant's own precedence-*derived* parens (`render_operand`/
291    /// `render_binary_operand`), which the printer adds or omits based on
292    /// what the wrapped expression *is*. `Paren` instead always prints
293    /// `(<inner>)` regardless of `inner`'s own shape or precedence. #1323's
294    /// own real, narrow need: `workers_entry.rs`'s CORS-preflight guard
295    /// wraps its own path-match condition in unconditional parens
296    /// (`&& ({cond})`) even when `cond` reduces to a single equality check
297    /// with no operator lower-precedence than the outer `&&` — a real case
298    /// the precedence-derived rules correctly do *not* parenthesize (they're
299    /// answering "is this needed for correctness", not "did the source
300    /// always write parens here"). Not a general escape hatch: every other
301    /// real site in this file's own content still goes through the ordinary
302    /// precedence machinery unchanged.
303    Paren(Box<TsExpr>),
304    /// `...x`, a spread element (1A.18a, #3719). Legal only as an item of
305    /// [`TsExpr::Array`] or an argument of [`TsExpr::Call`] (1A.32b), where it prints
306    /// `...` then its operand with no brackets
307    /// of its own: a spread operand is an assignment expression, so anything but a
308    /// comma expression (which `TsExpr` cannot build) stands there as it is. A new
309    /// variant rather than an item type on `Array`, which every existing array
310    /// site would then have to change.
311    Spread(Box<TsExpr>),
312    /// `operand!`, the non-null assertion (1A.23, #3724): the persisted-store arms read a
313    /// `modify` callback's current value, typed `V | undefined`, as a `V` once the key is known
314    /// present. Postfix like [`TsExpr::Member`]: the operand is bracketed under the rule a
315    /// member's object uses.
316    NonNull(Box<TsExpr>),
317    /// `target = value`, an assignment *expression* (1A.18b, #3719): the one
318    /// place a value is assigned and used at once, `(__h[__k] = __h[__k] ?? [])
319    /// .push(__u)`. An assignment as a whole statement is
320    /// `TsStmtKind::Assign`. The printer brackets it wherever it is an
321    /// operand; a builder that wants the brackets for readability, as that
322    /// example does, adds an explicit [`TsExpr::Paren`].
323    Assign {
324        target: Box<TsExpr>,
325        value: Box<TsExpr>,
326    },
327    /// `target += value` (1A.18b, #3719), the list kernel's `average` sum. A
328    /// sibling of [`TsExpr::Assign`], used as an expression statement.
329    AddAssign {
330        target: Box<TsExpr>,
331        value: Box<TsExpr>,
332    },
333    /// `target ??= value` (1A.36b-1): assigns only when the target is `null` or
334    /// `undefined`, and yields the target's value. A sibling of [`TsExpr::Assign`]
335    /// that a cached constant's accessor is built from, bracketed as it is.
336    NullishAssign {
337        target: Box<TsExpr>,
338        value: Box<TsExpr>,
339    },
340    Lit(TsLit),
341    /// `(a, b, c)` (1A.35a part B): a comma expression, which evaluates each
342    /// item in order and yields the last. It prints with its own brackets, so it
343    /// is safe in any operand or argument position. Needs at least two items.
344    Sequence(Vec<TsExpr>),
345    /// `callee?.(args)` (1A.35a part B): an optional call, which yields
346    /// `undefined` without calling when `callee` is nullish.
347    OptionalCall {
348        callee: Box<TsExpr>,
349        args: Vec<TsExpr>,
350    },
351    /// A function expression with a statement body (1A.35a part B), the form
352    /// that can be a generator: `async function* (params) { body }`. An arrow
353    /// cannot `yield`, so the `Stream` generators need this. It prints as an
354    /// operand bracketed, so an immediately invoked one reads
355    /// `(function () { … })()`.
356    Function {
357        is_async: bool,
358        is_generator: bool,
359        params: Vec<TsParam>,
360        return_type: Option<TsType>,
361        body: Vec<TsStmt>,
362    },
363    /// `yield <expr>` (1A.35a part B), legal in a generator [`TsExpr::Function`]'s
364    /// body. It binds looser than any operator, so it is bracketed as an operand.
365    Yield(Box<TsExpr>),
366}
367
368/// [`TsExpr::Arrow`]'s own `body` shape (#1435, Arc E slice 1) — see that
369/// field's own doc for why this is a widened field rather than a second
370/// `TsExpr` variant. `Expr` is every real site before this slice (and the
371/// overwhelming majority after it): the arrow's body is one expression,
372/// printed with no surrounding braces. `Block` is `serialisation.rs`'s own
373/// `Float` non-finite guard, the first real statement-bodied arrow anywhere
374/// in this tree — printed as a real braced block, reusing this crate's
375/// own printer's existing compact-statement-list renderer
376/// (`render_compact_stmts`, the same one `TsStmtKind::InlineBlock` already
377/// shares with `render_branch`'s own same-line `if`/`else`) rather than a
378/// third copy of that "one physical line, semicolon-separated" logic. Every
379/// real `Block` site today is exactly this one-line IIFE shape (an arrow
380/// with no other real use of a genuinely multi-line block body has been
381/// found); a future multi-line block-bodied arrow is a real, separate gap
382/// this variant does not yet cover.
383#[derive(Debug, Clone, PartialEq)]
384pub enum TsArrowBody {
385    Expr(Box<TsExpr>),
386    Block(Vec<TsStmt>),
387    /// A genuinely multi-line block body (back-half paydown 1A.12): `{`, one
388    /// statement per line one level deeper than the line the arrow starts on,
389    /// and `}` back at that line's indent. Unlike [`TsArrowBody::Block`]'s
390    /// compact one-line form, it may hold any statement, nested at its real
391    /// depth, and it records no source-map checkpoints for them.
392    Multiline(Vec<TsStmt>),
393    /// A block body printed on one line by flattening (back-half paydown 1A.39a): each statement
394    /// is printed at depth 0, its lines trimmed and joined with single spaces, and the whole is
395    /// bracketed `{ .. }`. A statement that prints over several lines (a braced `if`) therefore
396    /// sits on the line as `if (c) { return x; }`. It is the layout the ICU `select` arm and the
397    /// witness decoder have always had, and it records no source-map checkpoints. Unlike
398    /// [`TsArrowBody::Block`], which holds statements that each print on one line, it admits any
399    /// statement and never falls back to the multi-line form.
400    ///
401    /// **It trims every printed line**, so a statement that holds a template literal spanning
402    /// lines (or any text with significant leading whitespace) would be rewritten. A debug build
403    /// asserts that no statement prints one.
404    Flat(Vec<TsStmt>),
405}
406
407impl TsExpr {
408    /// [`TsExpr::RawUsing`]: `text`, with the `names` it uses declared.
409    pub fn raw_using(text: impl Into<String>, names: Vec<String>) -> Self {
410        TsExpr::RawUsing(text.into(), names)
411    }
412
413    /// A `bigint` literal: the digits of `n` (a leading `-` allowed), printed with the `n` suffix.
414    pub fn bigint(n: impl std::fmt::Display) -> Self {
415        let digits = n.to_string();
416        debug_assert!(
417            !digits.is_empty()
418                && digits
419                    .strip_prefix('-')
420                    .unwrap_or(&digits)
421                    .bytes()
422                    .all(|b| b.is_ascii_digit()),
423            "a bigint literal holds decimal digits only: {digits:?}"
424        );
425        TsExpr::Lit(TsLit::BigInt(digits))
426    }
427
428    /// Whether this expression must be bracketed to be the object of a member access
429    /// (`<expr>.name`, `<expr>(..)`). The printer brackets a binary, a cast, an arrow, a
430    /// conditional or an assignment there itself, but not an `await`, a unary operator or a
431    /// number literal (`Num` or `Raw`), which would read as `await f().op()` or `1.op()`: those
432    /// are the forms that keep a bracket the caller writes. A `Spread` is included
433    /// defensively: it is legal only as an array item, so a receiver is never one today.
434    pub fn needs_receiver_brackets(&self) -> bool {
435        match self {
436            TsExpr::Await(_)
437            | TsExpr::Unary { .. }
438            | TsExpr::Lit(TsLit::Num(_) | TsLit::BigInt(_) | TsLit::Raw(_))
439            | TsExpr::Spread(_) => true,
440            TsExpr::Lit(TsLit::Str(_) | TsLit::Null | TsLit::Bool(_))
441            | TsExpr::Ident(..)
442            | TsExpr::VerbatimExpr(..)
443            | TsExpr::RawUsing(..)
444            | TsExpr::Member { .. }
445            | TsExpr::OptionalMember { .. }
446            | TsExpr::TypeApp { .. }
447            | TsExpr::DefaultIife { .. }
448            | TsExpr::LinesArray(..)
449            | TsExpr::Index { .. }
450            | TsExpr::OptionalIndex { .. }
451            | TsExpr::Arrow { .. }
452            | TsExpr::Call { .. }
453            | TsExpr::New { .. }
454            | TsExpr::Object { .. }
455            | TsExpr::Array { .. }
456            | TsExpr::TemplateLit { .. }
457            | TsExpr::As { .. }
458            | TsExpr::AsConst(..)
459            | TsExpr::Binary { .. }
460            | TsExpr::Conditional { .. }
461            | TsExpr::MultilineConditional { .. }
462            | TsExpr::Paren(..)
463            | TsExpr::NonNull(..)
464            | TsExpr::Assign { .. }
465            | TsExpr::AddAssign { .. }
466            | TsExpr::NullishAssign { .. }
467            | TsExpr::Sequence(..)
468            | TsExpr::OptionalCall { .. }
469            | TsExpr::Function { .. }
470            | TsExpr::Yield(..) => false,
471        }
472    }
473
474    /// The ordinary, single-line object literal, `Prop`-only — every entry
475    /// is `key: value`. `events_fanout.rs`'s own entries (and this crate's
476    /// own printer tests) are all this shape; kept taking a plain
477    /// `Vec<(String, TsExpr)>` rather than `Vec<TsObjectEntry>` so none of
478    /// those existing call sites needed to change when `TsObjectEntry` was
479    /// added (#1321) — see [`TsExpr::object_entries`] for the mixed-entry
480    /// form `workers.rs` itself needs (shorthand/spread/method entries).
481    pub fn object(entries: Vec<(String, TsExpr)>) -> Self {
482        TsExpr::Object {
483            entries: entries
484                .into_iter()
485                .map(|(k, v)| TsObjectEntry::prop(k, v))
486                .collect(),
487            multiline: false,
488            end_span: None,
489        }
490    }
491
492    /// One entry per line, each with its own trailing comma — see
493    /// [`TsExpr::Object`]'s own doc for the real shape and the
494    /// depth-awareness this needs at the print site. `Prop`-only, the same
495    /// convenience [`TsExpr::object`]'s own doc explains.
496    pub fn multiline_object(entries: Vec<(String, TsExpr)>) -> Self {
497        TsExpr::Object {
498            entries: entries
499                .into_iter()
500                .map(|(k, v)| TsObjectEntry::prop(k, v))
501                .collect(),
502            multiline: true,
503            end_span: None,
504        }
505    }
506
507    /// The single-line object literal, taking [`TsObjectEntry`] directly —
508    /// for a mixed entry list (shorthand/spread/method alongside `Prop`),
509    /// which [`TsExpr::object`]'s own `Vec<(String, TsExpr)>` convenience
510    /// can't represent. #1321's own real grounding: `workers.rs`'s local
511    /// capability-provider `deps` object mixes shorthand names
512    /// (`{ cap1, cap2 }`) with explicit `key: value` entries
513    /// (`__exec: exec`) in one literal.
514    pub fn object_entries(entries: Vec<TsObjectEntry>) -> Self {
515        TsExpr::Object {
516            entries,
517            multiline: false,
518            end_span: None,
519        }
520    }
521
522    /// [`TsExpr::multiline_object`]'s own `TsObjectEntry` sibling —
523    /// #1321's own real grounding: `workers.rs`'s `compose`-returned
524    /// surface object is one shorthand-async-`Method` entry per wrapper,
525    /// one per line.
526    pub fn multiline_object_entries(entries: Vec<TsObjectEntry>) -> Self {
527        TsExpr::Object {
528            entries,
529            multiline: true,
530            end_span: None,
531        }
532    }
533
534    /// [`TsExpr::multiline_object_entries`] whose closing `}` line maps to
535    /// `end_span` (1A.32a) — a service object's closing line belongs to the
536    /// service, not to its last handler's final body line.
537    pub fn multiline_object_ending_at(entries: Vec<TsObjectEntry>, end_span: Span) -> Self {
538        TsExpr::Object {
539            entries,
540            multiline: true,
541            end_span: Some(end_span),
542        }
543    }
544
545    /// A [`TsExpr::MultilineConditional`]: `test`, then `? consequent` and
546    /// `: alternate` on their own lines.
547    pub fn multiline_conditional(test: TsExpr, consequent: TsExpr, alternate: TsExpr) -> Self {
548        TsExpr::MultilineConditional {
549            test: Box::new(test),
550            consequent: Box::new(consequent),
551            alternate: Box::new(alternate),
552        }
553    }
554
555    /// The ordinary, single-line array literal — every real site before
556    /// #1325.
557    pub fn array(items: Vec<TsExpr>) -> Self {
558        TsExpr::Array {
559            items,
560            multiline: false,
561        }
562    }
563
564    /// One entry per line, each with its own trailing comma — see
565    /// [`TsExpr::Array`]'s own doc for the real shape and the
566    /// depth-awareness this needs at the print site. #1325's own real
567    /// grounding: `emit_test_main`'s own `modules` array.
568    pub fn multiline_array(items: Vec<TsExpr>) -> Self {
569        TsExpr::Array {
570            items,
571            multiline: true,
572        }
573    }
574
575    /// A template literal — see [`TsExpr::TemplateLit`]'s own doc for the
576    /// real shape and its no-escaping boundary. The sole caller-facing
577    /// invariant (`parts.len() == exprs.len() + 1`) is asserted here rather
578    /// than left to `render_expr`'s own `parts`-driven loop, which would
579    /// otherwise silently drop trailing `exprs` on a malformed tree instead
580    /// of failing loudly (review of #1326, finding 1).
581    pub fn template_lit(parts: Vec<String>, exprs: Vec<TsExpr>) -> Self {
582        debug_assert_eq!(
583            parts.len(),
584            exprs.len() + 1,
585            "TsExpr::template_lit: parts.len() must be exprs.len() + 1 \
586             (parts[0] before the first substitution, parts[i+1] after \
587             exprs[i], …) — got {} parts and {} exprs",
588            parts.len(),
589            exprs.len()
590        );
591        TsExpr::TemplateLit { parts, exprs }
592    }
593}
594
595/// One entry of a [`TsExpr::Object`] literal. Only `Prop` existed before
596/// #1321 (`events_fanout.rs`'s own grounding never needed the other three) —
597/// `workers.rs`'s own dominant shape (Decision A, gap 1) is a literal
598/// object whose entries are shorthand async methods (every `on call`/`on
599/// http`/… wrapper attaches this way), its local capability-`deps` object
600/// mixes bare shorthand names with explicit `key: value` pairs, and three
601/// real sites spread another object into one (gap 2, folded in here rather
602/// than as its own top-level `TsExpr` variant — a spread only ever appears
603/// as an object- or array-literal entry in this file, never as a
604/// standalone expression, so scoping it to entry position is the narrower
605/// correct change).
606#[derive(Debug, Clone, PartialEq)]
607pub enum TsObjectEntry {
608    /// `key: value`, with an optional JSDoc block before it (printed the
609    /// way [`TsObjectEntry::Method`]'s `doc` is). Build it with
610    /// [`TsObjectEntry::prop`] and [`TsObjectEntry::with_doc`].
611    Prop {
612        key: String,
613        value: TsExpr,
614        doc: Option<String>,
615    },
616    /// `key` alone — object-literal property shorthand, e.g. `{ cap1,
617    /// cap2 }`. Distinct from `Prop(name, TsExpr::Ident(name))`, which
618    /// prints `name: name`, not the shorthand form real TypeScript
619    /// property-shorthand text actually is.
620    Shorthand(String),
621    /// A shorthand async method entry, e.g. `async foo(a: T) { ... },` —
622    /// `workers.rs`'s own dominant shape (Decision A, gap 1): every
623    /// wrapper helper (`emit_call_wrapper`, `emit_event_wrapper`, …)
624    /// attaches to the returned `compose` surface this way — none of
625    /// `workers.rs`'s own real sites annotates a return type, so
626    /// `return_type` stayed unneeded until #1323's own real gap:
627    /// `workers_entry.rs`'s `export default { fetch, scheduled?, queue? }`
628    /// entries all carry one (`: Promise<Response>`/`: Promise<void>`), the
629    /// same field [`TsClassMethod::return_type`] already has for the
630    /// declaration-position sibling this mirrors.
631    ///
632    /// `generics` and `doc` (#1337's own real gaps, both found only by the
633    /// zero-diff fixture check — not the accepted proposal's own citation,
634    /// which searched the project-form fixture corpus only;
635    /// `402_generic_instance_method` is single-file form, and while
636    /// `65_money_uses_time`/`64_full_time_commons` ARE project form, the
637    /// citation's own doc-comment search used the wrong marker, `///`
638    /// rather than this language's real `---`-delimited doc block —
639    /// both gaps outside what that first pass actually checked):
640    ///
641    /// - `generics`: a method on a generic type erases to
642    ///   `{name}<{generics}>(self: {Type}<{generics}>, …)` — `Box.map<A,
643    ///   U>`, the type's own `A` plus the method's own `U`. Bare names
644    ///   only, no bounds/defaults — every real generic parameter list this
645    ///   tree ever builds is (matching [`crate::printer::print_type`]'s
646    ///   own `TsType::Named`-only-name convention for the identical
647    ///   reason), so a full `Vec<TsParam>` (with its own unneeded
648    ///   `ty`/`optional` fields) would be the wrong shape here.
649    /// - `doc`: a JSDoc block immediately preceding the method entry, at
650    ///   the same indent — `Timestamp.diff`/`Timestamp.add`
651    ///   (`65_money_uses_time`) both carry one. Printed the identical way
652    ///   `TsStmtKind::DocComment` is (same escaping, same blank-line
653    ///   convention), reusing that one renderer rather than a second copy
654    ///   — this field exists because an object-entry method has no
655    ///   `TsStmt` slot of its own to hold a preceding statement in.
656    Method {
657        name: String,
658        is_async: bool,
659        generics: Vec<String>,
660        params: Vec<TsParam>,
661        return_type: Option<TsType>,
662        doc: Option<String>,
663        /// `false` (every method entry landed before #1337): `body` renders
664        /// as an ordinary braced, multi-line block. `true`: `body` renders
665        /// compactly on the SAME line as the signature — `{ <stmts>; }`,
666        /// reusing this crate's own established compact-statement
667        /// machinery (`TsStmtKind::InlineBlock`'s own sibling shape). A
668        /// real gap #1337's own zero-diff check found:
669        /// `emit_forwarded_methods`'s own pre-conversion `writeln!` always
670        /// built the WHOLE entry — signature and one-statement body alike —
671        /// on one physical line (`"  {method}({params}): {ret} {{ return
672        /// …; }},"`), a genuinely different real shape from every other
673        /// `Method` entry in this tree, all of which are multi-line.
674        inline: bool,
675        body: Vec<TsStmt>,
676        /// As [`TsClassMethod::span`]: where the entry's first printed line (its
677        /// doc comment, if it has one) maps to. `None` records nothing.
678        span: Option<Span>,
679    },
680    /// `...expr` — an object-spread entry (Decision A, gap 2), e.g. `{
681    /// ...deps, identity: __caller }`.
682    Spread(TsExpr),
683}
684
685impl TsObjectEntry {
686    /// An undocumented `key: value` entry: the shape of nearly every `Prop`.
687    pub fn prop(key: impl Into<String>, value: TsExpr) -> Self {
688        TsObjectEntry::Prop {
689            key: key.into(),
690            value,
691            doc: None,
692        }
693    }
694
695    /// This entry with a JSDoc block before it. Only a `Prop` carries one: a
696    /// doc on any other entry is a caller bug, caught in debug builds (in
697    /// release it is ignored). See `doc` on [`TsObjectEntry::Prop`].
698    #[must_use]
699    pub fn with_doc(mut self, text: impl Into<String>) -> Self {
700        debug_assert!(
701            matches!(self, TsObjectEntry::Prop { .. }),
702            "with_doc: only a `Prop` entry carries a doc"
703        );
704        if let TsObjectEntry::Prop { doc, .. } = &mut self {
705            *doc = Some(text.into());
706        }
707        self
708    }
709
710    /// A multi-line, non-generic, undocumented method entry with no span: the
711    /// shape of nearly every method entry. Build any other with the variant
712    /// directly.
713    pub fn method(
714        name: impl Into<String>,
715        is_async: bool,
716        params: Vec<TsParam>,
717        return_type: Option<TsType>,
718        body: Vec<TsStmt>,
719    ) -> Self {
720        TsObjectEntry::Method {
721            name: name.into(),
722            is_async,
723            generics: Vec::new(),
724            params,
725            return_type,
726            doc: None,
727            inline: false,
728            body,
729            span: None,
730        }
731    }
732
733    /// This entry with its body compact on the signature's own line (a no-op for an
734    /// entry that is not a method). See `inline` on [`TsObjectEntry::Method`].
735    #[must_use]
736    pub fn inlined(mut self) -> Self {
737        if let TsObjectEntry::Method { inline, .. } = &mut self {
738            *inline = true;
739        }
740        self
741    }
742}
743
744/// `!x` (`events_fanout.rs`'s `!Array.isArray(subs)`, `!binding`) and
745/// `typeof x` (#1321, `workers.rs`'s own secret-probe idiom: `typeof
746/// __secret !== "string"`) — the two unary operators real content uses, not
747/// the full JS/TS table.
748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
749pub enum TsUnaryOp {
750    Not,
751    Typeof,
752    /// Arithmetic negation, `-x` (1A.3, #3696). Printed with its operand
753    /// parenthesised by the same rule as `!`, and a negated negation as
754    /// `-(-x)`, never the decrement `--x`.
755    Neg,
756    /// `void x` (1A.32c-1): evaluates its operand and discards it, as the
757    /// idiom for marking a parameter used. Printed with its operand
758    /// bracketed by the same rule as `!` and `typeof`.
759    Void,
760    /// `++x` (1A.35a part B): the prefix increment, which yields the new value.
761    PreIncrement,
762}
763
764/// `??` (`events_fanout.rs`'s `env ?? {}`), plus three more real operators
765/// #1321 (`workers.rs`) grounds: `||`/`&&` (the Bearer-header presence
766/// checks, `__authz === null || !__authz.startsWith(...)` /
767/// `__authz !== null && __authz.startsWith(...)`) and `===`/`!==`
768/// (pervasive throughout the file's own tagged-result and header checks).
769/// #1323 (`workers_entry.rs`) grounds one more: `>` (the request-body-
770/// ceiling guard's own `Number(__contentLength) > <cap>` — the one real
771/// site anywhere in `bynk-emit` that needs a relational, not equality,
772/// comparison). Not the
773/// full JS/TS operator table (Decision B's own "extend narrowly" posture) —
774/// see the printer's own `binary_precedence` (`bynk-ts/src/printer/precedence.rs`,
775/// private) for why a nested `Binary` operand's parenthesisation needed to
776/// become precedence-aware once more than one operator existed. Arc C, step
777/// (11) (#1388) grounds one more: `+` (string concatenation) — the
778/// ICU-formatting cluster's own dominant structural pattern, every
779/// literal/placeholder segment in a message template joins this way. Real
780/// JS/TS precedence (binds tighter than every comparison/logical operator
781/// this table already has) and real left-associativity (`"a" + "b" + "c"`
782/// needs no parens, the same way a same-operator `||`/`&&` chain already
783/// prints flat) both matter here, not just the operator symbol itself.
784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
785pub enum TsBinaryOp {
786    NullishCoalescing,
787    Or,
788    And,
789    StrictEq,
790    StrictNotEq,
791    GreaterThan,
792    /// `instanceof` — Arc C slice 34 (`tests_emit.rs` slice D, #1403)'s own
793    /// real gap: `emit_test_case_function`'s own catch clause
794    /// (`e instanceof ExpectationError`) is the first real `instanceof`
795    /// anywhere in `bynk-emit`'s own content. Real JS/TS precedence puts it
796    /// at the same tier as the relational comparisons (`<`/`>`) — sharing
797    /// [`TsBinaryOp::LessThan`]'s own tier, not a new one — rendered as the
798    /// keyword `" instanceof "`, textually the same shape as `&&`/`||`
799    /// rather than symbol punctuation.
800    InstanceOf,
801    /// `<` — Arc C slice 33 (`tests_emit.rs` slice C, #1401)'s own real gap:
802    /// `emit_stub_class`'s `ReturnsEach` sequence-cursor guard
803    /// (`this.__seq_N < <bound>`) is the first real `<` comparison anywhere
804    /// in `bynk-emit`'s own content. Same precedence tier as
805    /// [`TsBinaryOp::GreaterThan`] (real JS/TS relational operators all
806    /// share one level) — added alongside it rather than folding into a
807    /// single "relational" variant, matching this enum's own existing
808    /// one-variant-per-real-operator convention.
809    LessThan,
810    Add,
811    /// `in` — Arc E slice 5 (`serialisation.rs`, #1443)'s own real gap:
812    /// `emit_record_codec`'s per-field default-value prevalidation line
813    /// (`"<field>" in obj ? obj["<field>"] : <default>`) needs a real "is
814    /// this wire key present at all" test, distinct from `!== undefined`
815    /// (Events slice 3a, #972's own Decision D: a wire key present with an
816    /// explicit `null`/`{"kind":"None"}` value must NOT fall through to the
817    /// default, only a genuinely *absent* key may). Real JS/TS grammar puts
818    /// `in` at the exact same `RelationalExpression` precedence tier as
819    /// `<`/`>`/`instanceof` (all five — plus `<=`/`>=`, unmodelled here —
820    /// share one level in the spec), so it joins [`TsBinaryOp::LessThan`]'s
821    /// tier rather than a new one, the same "share, don't multiply, tiers"
822    /// convention `InstanceOf`/`LessThan` already set. Rendered as the
823    /// keyword `" in "`, the same textual-keyword-operator shape
824    /// `InstanceOf` already established (not symbol punctuation).
825    In,
826    /// `>=` — #1471's own real gap: `pred_condition_and_message`'s
827    /// (`bynk-emit`) `NonNegative`/`InRange`/`InRangeF`/`MinLength` arms
828    /// each build a real "at least" comparison (`{receiver} >= 0`,
829    /// `{receiver} >= {a}`, `{receiver}.length >= {n}`) that this enum had
830    /// no home for — [`TsBinaryOp::In`]'s own doc already named this exact
831    /// gap ("plus `<=`/`>=`, unmodelled here"). Same `RelationalExpression`
832    /// precedence tier as [`TsBinaryOp::GreaterThan`]/[`TsBinaryOp::
833    /// LessThan`]/[`TsBinaryOp::InstanceOf`]/[`TsBinaryOp::In`] (real
834    /// JS/TS puts all six at one level), rendered `" >= "` — symbol
835    /// punctuation, matching `GreaterThan`/`LessThan`'s own convention,
836    /// not a keyword like `InstanceOf`/`In`.
837    GreaterThanEq,
838    /// `<=` — the same gap's other half: `InRange`/`InRangeF`/`MaxLength`'s
839    /// own "at most" comparison (`{receiver} <= {b}`, `{receiver}.length
840    /// <= {n}`). Same tier and rendering convention as
841    /// [`TsBinaryOp::GreaterThanEq`], symmetric with it the way
842    /// `GreaterThan`/`LessThan` already are.
843    LessThanEq,
844    /// `*` — #2955's own real gap: the `Decimal` range check
845    /// (`decimal_range_expr`) scales each side to a common scale with
846    /// `bigint` arithmetic (`coefficient * 10n ** …`). Multiplicative tier,
847    /// one above [`TsBinaryOp::Add`].
848    Mul,
849    /// `**` — the same gap's other half (`10n ** globalThis.BigInt(scale)`).
850    /// Exponentiation tier, one above [`TsBinaryOp::Mul`]. Right-associative
851    /// in JS/TS, so the printer's default "same operator nested in itself
852    /// parenthesises" rule keeps any chained `**` correct.
853    Exp,
854    /// `-` (binary) — slice 1A.5 (#3703): Bynk's `Sub`. Shares
855    /// [`TsBinaryOp::Add`]'s tier; left-associative, so a right-nested
856    /// same-tier operand keeps its brackets (`a - (b - c)`).
857    Sub,
858    /// `/` — slice 1A.5 (#3703): Bynk's `Div`. Shares [`TsBinaryOp::Mul`]'s
859    /// tier; left-associative.
860    Div,
861}
862
863/// A literal — the three kinds `events_fanout.rs` uses (a string, a number,
864/// `null`), plus `Bool` (#1323's own real gap: `workers_entry.rs`'s
865/// `CorsPolicy.credentials`/`SecurityPolicy.nosniff` object-literal fields
866/// are real booleans, e.g. `credentials: true`, `nosniff: false` — nothing
867/// before this slice's own grounding ever built one).
868#[derive(Debug, Clone, PartialEq)]
869pub enum TsLit {
870    Str(String),
871    /// Rendered verbatim, as text — TypeScript's own numeric-literal
872    /// grammar is not this crate's problem to re-derive; the caller passes
873    /// the exact digits it wants printed.
874    Num(String),
875    /// A `bigint` literal: the decimal digits, with an optional leading `-`, and no suffix. The
876    /// printer adds the `n`. Build it with [`TsExpr::bigint`].
877    BigInt(String),
878    Null,
879    Bool(bool),
880    /// The complete literal text, printed exactly as given — no quoting, no
881    /// escaping, nothing added or removed. #1325's own real, narrow gap:
882    /// `emit_test_main`'s own `const PREFIX = "system · ";` embeds
883    /// a literal JS unicode escape (six ASCII characters, `·`) as
884    /// pre-formed text — [`TsLit::Str`]'s own escaper (which turns every `\`
885    /// it sees into `\\`) would double that literal backslash, corrupting
886    /// this specific byte-golden output. The same "already a raw-text slot"
887    /// boundary [`TsExpr::TemplateLit`]'s own `parts` field documents, just
888    /// for a whole literal (quotes included) rather than a template
889    /// literal's own static segments. One real site — not a general
890    /// escaping bypass for ordinary string content, which stays on
891    /// `TsLit::Str`.
892    Raw(String),
893}