Skip to main content

bynk_ts/program/
types.rs

1#[cfg(doc)]
2use super::{TsDecl, TsLit, TsObjectEntry};
3use super::{TsExpr, TsParam};
4
5/// A type-position node. `Named` (extended with type arguments — a real gap
6/// the reference sketch left unaddressed: `Record<string,
7/// Array<{...}>>`/`Promise<Response>` both need one, and a bare `Named`
8/// with no type-argument slot cannot represent either), `Array` (extended
9/// with a `readonly` modifier — P7.9's own real gap: every `List`/`Query`
10/// element type `bynk-emit`'s `ts_type_ref*`/`ts_ty` families build is
11/// `readonly T[]`, not plain `T[]`), `Object`, and `Fn` (P7.9's own second
12/// real gap — the query-thunk wrapper `(() => readonly T[])` and a real
13/// parametered function type `(a0: T0, …) => Ret` both need one) — not the
14/// sketch's `Union`/`Intersection`/`Literal`/`TypeParam`/`Readonly` (still
15/// unused; `readonly` here is a modifier on `Array`, not the sketch's own
16/// separate `Readonly` wrapper variant).
17#[derive(Debug, Clone, PartialEq)]
18pub enum TsType {
19    /// A named type, optionally generic — `string`/`unknown` (no type
20    /// arguments) or `Record<string, T>`/`Promise<Response>` (some).
21    Named {
22        name: String,
23        type_args: Vec<TsType>,
24    },
25    /// `T[]` (`readonly: false`) or `readonly T[]` (`readonly: true`) —
26    /// TypeScript's own postfix array-type syntax (not the equivalent
27    /// `Array<T>`/`ReadonlyArray<T>` generic spelling either family uses).
28    ///
29    /// The printer parenthesises `element` wherever a bare postfix `[]`
30    /// would bind to the wrong thing (#1898): a readonly array (`readonly
31    /// T[][]` is TS1354), a [`TsType::Fn`] (whose `[]` would bind to its
32    /// return type), a [`TsType::Union`] and a [`TsType::Intersection`]
33    /// (`A | B[]` reads as `A | (B[])`). So `Array` over any element prints
34    /// correctly as built — a caller must not wrap the element itself, or
35    /// it double-parenthesises. The rule is `needs_parens_as_array_element`
36    /// in `printer.rs`. This closes the hazard the review of #1315/#1316
37    /// recorded here.
38    Array {
39        element: Box<TsType>,
40        readonly: bool,
41    },
42    /// A type-position object shape, e.g. `{ type: string; payload: unknown }`
43    /// — semicolon-separated, always printed on one line (see
44    /// [`TsExpr::Object`]'s own doc for the value-position contrast). An
45    /// `interface`'s own *members* are each printed on their own line by
46    /// [`TsDecl::Interface`]'s printer, independent of this variant's own
47    /// (always-inline) rendering — the two only look different because
48    /// `TsDecl::Interface` is the thing choosing to put each member on its
49    /// own line, not because `Object` has two rendering modes.
50    ///
51    /// #1323 replaced the plain `Vec<(String, TsType, bool)>` (`optional`
52    /// only, #1321) with [`TsTypeMember`] — `workers_entry.rs`'s own real
53    /// gap needed both a `readonly` modifier (every structural type this
54    /// file builds is `readonly`-qualified, e.g. `{ readonly cron: string;
55    /// readonly scheduledTime: number }`) and a method-signature member
56    /// (`ack(): void`, `retry(): void`, `waitUntil(promise: Promise<
57    /// unknown>): void`), neither representable by one more anonymous
58    /// tuple `bool` — a fourth positional `bool` next to `optional` would
59    /// be genuinely ambiguous at call sites (`readonly` vs. `optional`, ordered
60    /// how?), the same reasoning [`TsObjectEntry`] already used over a raw
61    /// tuple for the value-position sibling.
62    Object(Vec<TsTypeMember>),
63    /// `(a0: T0, a1: T1, …) => Ret` — a function type. Parameters carry no
64    /// name of their own (just their type); the printer numbers them
65    /// positionally (`a0`, `a1`, …), matching the exact convention
66    /// `bynk-emit`'s own pre-P7.9 `ts_type_ref_with`/`ts_ty` already used
67    /// (TypeScript requires *some* name in function-type syntax, and
68    /// nothing about a `TypeRef::Fn`/`Ty::Fn` parameter carries a real one
69    /// to use instead). A zero-`params` `Fn` is the query-thunk wrapper
70    /// shape, `() => Ret`. Inside a [`TsType::Array`] the printer
71    /// parenthesises it (`readonly ((a0: T) => U)[]`); see that variant's
72    /// own doc.
73    ///
74    /// `names` (1A.18b, #3719): optional parameter names, for a function type
75    /// whose names are part of its spelling (`(acc: A, x: T) => A`, the list
76    /// kernel's `fold`). Empty is the positional `a0, a1, …` form above, which
77    /// every other site builds; otherwise one name per entry of `params`, in
78    /// order.
79    ///
80    /// `rest` (1A.40c, #3996): the last parameter is a rest parameter, printed `...name: T`, so
81    /// the type spells a variadic function (`(...bynkArgs: unknown[]) => unknown`). Its name is
82    /// taken from `names`, so a rest `Fn` carries names; `false` is every other function type.
83    Fn {
84        params: Vec<TsType>,
85        names: Vec<String>,
86        rest: bool,
87        ret: Box<TsType>,
88    },
89    /// `A | B | C` — a type-position union. Added in review of #1315:
90    /// `bynk-emit`'s `ts_ty` builds a real union type for a resolved
91    /// multi-actor sum (`Ty::ActorSum`, discriminated-union members tagged
92    /// by actor name), a shape none of `Named`/`Array`/`Object`/`Fn` can
93    /// represent — a real, grounded gap the same way `readonly`/`Fn`
94    /// themselves were (P7.9's own accepted proposal), not a speculative
95    /// addition. Each member prints through the ordinary `render_type`
96    /// recursion; a member that is itself a `Union` is legal to construct
97    /// but nothing in `bynk-emit` builds one today. Inside a
98    /// [`TsType::Array`] the printer parenthesises it (`(A | B)[]`); see that
99    /// variant's own doc.
100    ///
101    /// `multiline` (#1339): `false` (via [`TsType::union`]) is this variant's
102    /// original single-line `A | B | C` form, unchanged. `true` (via
103    /// [`TsType::multiline_union`]) is `emit_sum_type`'s own real
104    /// discriminated-union shape — one variant per line, a leading `|` on
105    /// every line *except* the first (which gets equivalent spacing
106    /// instead), the closing `;` appended directly to the last variant's own
107    /// line. Mirrors [`TsExpr::Object`]'s own `multiline` field precedent
108    /// (#1317), but — unlike that one — needs no depth-aware wrapper: the
109    /// pre-conversion `writeln!` code this reproduces always used a fixed
110    /// two-space indent regardless of nesting (this shape is only ever a
111    /// top-level `export type` alias body, never nested inside another
112    /// type), so `render_type` stays entirely depth-unaware here too. Only
113    /// rendered correctly from [`TsDecl::TypeAlias`]'s own top-level
114    /// render — not reachable, and not given a defined rendering, from any
115    /// nested position (an array element, a type argument, …), the same
116    /// named boundary [`TsExpr::Object`]'s own `multiline` doc already
117    /// draws for its own nested case.
118    Union {
119        members: Vec<TsType>,
120        multiline: bool,
121    },
122    /// `A & B` — a type-position intersection. #1339's own real gap:
123    /// `emit_refined_type`'s own branded-type alias,
124    /// `{base} & { readonly __brand: "..." }`, has no representation among
125    /// `Named`/`Array`/`Object`/`Fn`/`Union` — mirrors `Union`'s own
126    /// shape/precedent exactly (a flat `Vec`, each member printed through
127    /// the ordinary `render_type` recursion, joined by ` & `), single-line
128    /// only (nothing in `bynk-emit` builds a multi-line intersection).
129    Intersection(Vec<TsType>),
130    /// A mapped type, `{ -readonly [K in keyof T]: V }`: one property per key of
131    /// `keys_of`, typed `value` (which may mention `key`).
132    ///
133    /// `readonly` is the modifier on the generated properties: `None` leaves them as
134    /// they are, `Some(Add)` prints `+readonly` and `Some(Remove)` prints `-readonly`.
135    /// `keys_of` is the operand of `keyof`, so the constraint is always
136    /// `key in keyof keys_of`. `key` is a name the type binds for `value`. Always
137    /// printed on one line, as a [`TsType::Object`] is.
138    Mapped {
139        readonly: Option<TsMappedModifier>,
140        key: String,
141        keys_of: Box<TsType>,
142        value: Box<TsType>,
143    },
144    /// `typeof x`: the type of a value. The operand is an identifier or a chain of
145    /// member accesses (`typeof a.b`), the only expressions TypeScript allows here;
146    /// it is a use of that value for `name_closure`.
147    TypeOf(Box<TsExpr>),
148    /// `T[K]`: an indexed access type, `object` indexed by `index` (a key type such
149    /// as [`TsType::StringLiteral`] or a mapped type's own key).
150    Indexed {
151        object: Box<TsType>,
152        index: Box<TsType>,
153    },
154    /// A string literal type, `"k"`, escaped as a [`TsLit::Str`] is.
155    StringLiteral(String),
156    /// A non-negative integer literal type, `0`, as a tuple index (`T[0]`).
157    NumberLiteral(u32),
158    /// `(T)`: a type in parentheses, always. The printer already parenthesises where a
159    /// postfix operator would misread (an array element, an indexed object); this is for a
160    /// position the printer does not know about, such as the thunk type a `Query` annotation
161    /// is written as, `(() => T)`. It prints as the parentheses around the inner type's own
162    /// spelling, and `name_closure` looks through it.
163    Paren(Box<TsType>),
164}
165
166/// The modifier on a [`TsType::Mapped`] type's `readonly`.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum TsMappedModifier {
169    /// `+readonly`.
170    Add,
171    /// `-readonly`.
172    Remove,
173}
174
175impl TsType {
176    /// A plain named type with no type arguments — `string`, `unknown`,
177    /// `Request`, …
178    pub fn named(name: impl Into<String>) -> Self {
179        TsType::Named {
180            name: name.into(),
181            type_args: Vec::new(),
182        }
183    }
184
185    /// A generic named type — `Record<K, V>`, `Promise<T>`, …
186    pub fn named_with_args(name: impl Into<String>, type_args: Vec<TsType>) -> Self {
187        TsType::Named {
188            name: name.into(),
189            type_args,
190        }
191    }
192
193    /// `T[]` — the non-`readonly` array shape.
194    pub fn array(element: TsType) -> Self {
195        TsType::Array {
196            element: Box::new(element),
197            readonly: false,
198        }
199    }
200
201    /// `readonly T[]`.
202    pub fn readonly_array(element: TsType) -> Self {
203        TsType::Array {
204            element: Box::new(element),
205            readonly: true,
206        }
207    }
208
209    /// `A | B | C` — the original single-line union form, unchanged.
210    pub fn union(members: Vec<TsType>) -> Self {
211        TsType::Union {
212            members,
213            multiline: false,
214        }
215    }
216
217    /// `emit_sum_type`'s own real multi-line discriminated-union shape — see
218    /// [`TsType::Union`]'s own doc for the exact rendering rules and why
219    /// this needs no depth parameter.
220    pub fn multiline_union(members: Vec<TsType>) -> Self {
221        TsType::Union {
222            members,
223            multiline: true,
224        }
225    }
226
227    /// `A & B` — an intersection type.
228    pub fn intersection(members: Vec<TsType>) -> Self {
229        TsType::Intersection(members)
230    }
231
232    /// `{ [key in keyof keys_of]: value }`, with no `readonly` modifier.
233    pub fn mapped(key: impl Into<String>, keys_of: TsType, value: TsType) -> Self {
234        TsType::Mapped {
235            readonly: None,
236            key: key.into(),
237            keys_of: Box::new(keys_of),
238            value: Box::new(value),
239        }
240    }
241
242    /// The same mapped type with its properties' `readonly` modifier set.
243    pub fn with_mapped_readonly(mut self, modifier: TsMappedModifier) -> Self {
244        if let TsType::Mapped { readonly, .. } = &mut self {
245            *readonly = Some(modifier);
246        } else {
247            debug_assert!(false, "with_mapped_readonly: not a mapped type");
248        }
249        self
250    }
251
252    /// `typeof name`.
253    pub fn type_of(operand: TsExpr) -> Self {
254        TsType::TypeOf(Box::new(operand))
255    }
256
257    /// `object[index]`.
258    pub fn indexed(object: TsType, index: TsType) -> Self {
259        TsType::Indexed {
260            object: Box::new(object),
261            index: Box::new(index),
262        }
263    }
264
265    /// `(inner)`: the type in parentheses.
266    pub fn paren(inner: TsType) -> Self {
267        TsType::Paren(Box::new(inner))
268    }
269
270    /// The string literal type `"text"`.
271    pub fn string_literal(text: impl Into<String>) -> Self {
272        TsType::StringLiteral(text.into())
273    }
274
275    /// The integer literal type `n` (a tuple index: `Parameters<F>[0]`).
276    pub fn number_literal(n: u32) -> Self {
277        TsType::NumberLiteral(n)
278    }
279}
280
281/// One member of a [`TsType::Object`] structural type — a property (`Prop`)
282/// or a method signature (`Method`, #1323's own real gap: `ack(): void`,
283/// `retry(): void`, `waitUntil(promise: Promise<unknown>): void` — no body,
284/// a type-position sibling to [`TsObjectEntry::Method`], which does carry
285/// one). `Method`'s own parameters reuse [`TsParam`] directly (not a bare
286/// `Vec<TsType>` the way [`TsType::Fn`]'s anonymous, positionally-numbered
287/// parameters do) — `waitUntil`'s own real parameter has a real name
288/// (`promise`) the printed text must show, unlike `Fn`'s callers, none of
289/// which have one to show.
290#[derive(Debug, Clone, PartialEq)]
291pub enum TsTypeMember {
292    Prop {
293        name: String,
294        ty: TsType,
295        optional: bool,
296        readonly: bool,
297    },
298    /// `generics`/`doc` added by #1357: `emit_capability`'s own interface
299    /// methods are genuinely generic (`op<T>(...): ret;`, no
300    /// monomorphisation) and doc-commented — bare generic names, matching
301    /// every other real generics-list precedent in this crate; `doc`
302    /// mirrors `TsObjectEntry::Method.doc`'s own identical field (#1337).
303    /// Both default empty/`None` via [`TsTypeMember::method`]'s own
304    /// existing constructor — every one of its 6 real pre-#1357 callers is
305    /// unaffected.
306    ///
307    /// `doc` renders from exactly one of this variant's two reachable
308    /// positions: `TsDecl::Interface`'s own render arm (a real, multi-line
309    /// declaration body with `depth` available, so it calls
310    /// `render_doc_comment` before a documented member's own line — the
311    /// only place `doc` is honoured). A `Method` reached through
312    /// `TsType::Object`'s own inline, single-line shape (a type-position
313    /// object literal, e.g. `{ a: X; b(): Y }`) has no line budget for a
314    /// JSDoc block at all — `doc: Some(_)` there is a real, `debug_assert`-
315    /// guarded misuse (`render_type`'s own `TsType::Object` arm), the same
316    /// "loud, not silently dropped" precedent review of #1338 already
317    /// established for `render_object_entry_inline`'s identical
318    /// `TsObjectEntry::Method.doc` case.
319    Method {
320        name: String,
321        generics: Vec<String>,
322        params: Vec<TsParam>,
323        ret: TsType,
324        doc: Option<String>,
325    },
326    /// `[key_name: key_ty]: value_ty` — a TypeScript index signature.
327    /// #1323's own real gap: `workers_entry.rs`'s multi-param `on call`
328    /// dispatch casts its raw JSON args object through `{ [k: string]:
329    /// JsonValue }` before indexing it by field name — textually distinct
330    /// from the semantically-equivalent `Record<string, JsonValue>` (a
331    /// `Named` type with type arguments), which `bynk-emit`'s own
332    /// pre-conversion `writeln!` never wrote here. The one real site.
333    Index {
334        key_name: String,
335        key_ty: TsType,
336        value_ty: TsType,
337    },
338}
339
340impl TsTypeMember {
341    /// `name: ty` — the ordinary, non-`optional`, non-`readonly` case.
342    pub fn prop(name: impl Into<String>, ty: TsType) -> Self {
343        TsTypeMember::Prop {
344            name: name.into(),
345            ty,
346            optional: false,
347            readonly: false,
348        }
349    }
350
351    /// `name?: ty`.
352    pub fn optional_prop(name: impl Into<String>, ty: TsType) -> Self {
353        TsTypeMember::Prop {
354            name: name.into(),
355            ty,
356            optional: true,
357            readonly: false,
358        }
359    }
360
361    /// `readonly name: ty`.
362    pub fn readonly_prop(name: impl Into<String>, ty: TsType) -> Self {
363        TsTypeMember::Prop {
364            name: name.into(),
365            ty,
366            optional: false,
367            readonly: true,
368        }
369    }
370
371    /// `name(params): ret` — no body, no generics, no doc comment.
372    pub fn method(name: impl Into<String>, params: Vec<TsParam>, ret: TsType) -> Self {
373        TsTypeMember::Method {
374            name: name.into(),
375            generics: Vec::new(),
376            params,
377            ret,
378            doc: None,
379        }
380    }
381
382    /// `[key_name: key_ty]: value_ty`.
383    pub fn index(key_name: impl Into<String>, key_ty: TsType, value_ty: TsType) -> Self {
384        TsTypeMember::Index {
385            key_name: key_name.into(),
386            key_ty,
387            value_ty,
388        }
389    }
390}