bynk_ts/program/decl.rs
1use super::{TsExpr, TsStmt, TsType, TsTypeMember};
2use bynk_syntax::span::Span;
3
4/// One function/method/constructor parameter.
5#[derive(Debug, Clone, PartialEq)]
6pub struct TsParam {
7 pub name: String,
8 pub ty: Option<TsType>,
9 /// `name?: ty` — `events_fanout.rs`'s own `env?: unknown` constructor
10 /// parameter needs this. `optional` and a [`TsParam::default`] do not combine
11 /// (`x?: T = v` is a TypeScript error); the printer asserts it.
12 pub optional: bool,
13 /// `...name: T` — a rest parameter (1A.32b: the history driver's console mute,
14 /// `(...__a: unknown[]) => …`). Prints before the name; `optional` and `rest`
15 /// do not combine.
16 pub rest: bool,
17 /// `[a, b]` (1A.35a part B): the parameter destructures an array, and these
18 /// are its element names (an empty name is a hole). It prints in place of
19 /// `name`, which is then unused. Build it with [`TsParam::array_pattern`].
20 pub array_pattern: Option<Vec<String>>,
21 /// `name: ty = default` (1A.38b): the value the parameter takes when its
22 /// argument is left out (`query: Q = {}`). Build one with
23 /// [`TsParam::with_default`]; `optional` and a default do not combine. The default
24 /// is printed without a source-map segment of its own.
25 pub default: Option<TsExpr>,
26}
27
28impl TsParam {
29 /// A required parameter, with its type if it has one.
30 pub fn new(name: impl Into<String>, ty: Option<TsType>) -> Self {
31 Self {
32 name: name.into(),
33 ty,
34 optional: false,
35 rest: false,
36 array_pattern: None,
37 default: None,
38 }
39 }
40
41 /// This parameter with a default value, `name: T = default`.
42 #[must_use]
43 pub fn with_default(mut self, default: TsExpr) -> Self {
44 debug_assert!(
45 !self.optional && !self.rest,
46 "with_default: an optional or rest parameter takes no default"
47 );
48 self.default = Some(default);
49 self
50 }
51
52 /// A parameter that destructures an array: `([a, b]) => …`.
53 pub fn array_pattern(names: Vec<String>, ty: Option<TsType>) -> Self {
54 Self {
55 array_pattern: Some(names),
56 ..Self::new(String::new(), ty)
57 }
58 }
59
60 /// An optional parameter (`name?: T`).
61 pub fn optional(name: impl Into<String>, ty: Option<TsType>) -> Self {
62 Self {
63 optional: true,
64 ..Self::new(name, ty)
65 }
66 }
67
68 /// This parameter as a rest parameter (`...name: T`).
69 #[must_use]
70 pub fn rest(mut self) -> Self {
71 self.rest = true;
72 self
73 }
74}
75
76/// One `class` field.
77#[derive(Debug, Clone, PartialEq)]
78pub struct TsClassField {
79 pub name: String,
80 /// The field's type. `None` for a field that has only an initialiser, whose type TypeScript
81 /// infers (`__seq_0 = 0;`); build one with [`TsClassField::inferred`].
82 pub ty: Option<TsType>,
83 /// The field's initialiser (`name: T = init;`). `None` for an ordinary field, which the
84 /// constructor or a factory assigns.
85 pub init: Option<TsExpr>,
86 /// `private` — the one visibility modifier `events_fanout.rs` uses
87 /// (`private env: ...`). Not a decorator or a constructor parameter
88 /// property (R7.1 forbids both categorically — there is no variant
89 /// shape here that could construct either).
90 pub private: bool,
91 /// `name!: T;` — a definite-assignment assertion, for a field the
92 /// constructor does not set but whoever builds the object does (1A.32b: an
93 /// agent's `__key`, assigned by its factory or its dispatch before any
94 /// handler runs). Printed after the name, before the `:`.
95 pub definite: bool,
96}
97
98impl TsClassField {
99 /// A public, ordinarily-assigned field. Mark it with [`TsClassField::private`]
100 /// or [`TsClassField::definite`].
101 pub fn new(name: impl Into<String>, ty: TsType) -> Self {
102 Self {
103 name: name.into(),
104 ty: Some(ty),
105 init: None,
106 private: false,
107 definite: false,
108 }
109 }
110
111 /// A public field with an initialiser and no written type (`name = init;`), whose type
112 /// TypeScript infers from it (1B.5c: a stub class's `__seq_0 = 0;`).
113 pub fn inferred(name: impl Into<String>, init: TsExpr) -> Self {
114 Self {
115 name: name.into(),
116 ty: None,
117 init: Some(init),
118 private: false,
119 definite: false,
120 }
121 }
122
123 /// This field with the `private` modifier.
124 #[must_use]
125 pub fn private(mut self) -> Self {
126 self.private = true;
127 self
128 }
129
130 /// This field with a definite-assignment assertion (`name!: T;`).
131 #[must_use]
132 pub fn definite(mut self) -> Self {
133 self.definite = true;
134 self
135 }
136}
137
138/// A class's own constructor.
139#[derive(Debug, Clone, PartialEq)]
140pub struct TsClassCtor {
141 pub params: Vec<TsParam>,
142 pub body: Vec<TsStmt>,
143}
144
145/// One class method.
146#[derive(Debug, Clone, PartialEq)]
147pub struct TsClassMethod {
148 pub name: String,
149 /// `private {name}(...)`, e.g. `loadState`/`commitState` — the
150 /// grounding pass's own predicted gap (#1366), closed by Arc C's own
151 /// `emit_agent` class-scaffold slice: every real `TsClassMethod` site
152 /// before this one (`emit_provider` #1359's own op methods) was
153 /// public-only. Rendered before `async`, matching the one real site's
154 /// own modifier order (`private async loadState()`, not `async private
155 /// loadState()`).
156 pub private: bool,
157 pub is_async: bool,
158 pub params: Vec<TsParam>,
159 pub return_type: Option<TsType>,
160 /// A JSDoc block immediately preceding the method — the grounding
161 /// pass's own second predicted gap (#1366), closed alongside `private`'s
162 /// own sibling site: `emit_agent`'s own per-handler methods each carry
163 /// a doc comment (`emit_doc_block`'s pre-conversion standalone call),
164 /// the same need `TsObjectEntry::Method.doc` (#1337) and
165 /// `TsTypeMember::Method.doc` (#1357) already solved for their own node
166 /// kinds. Rendered the identical way those two already are — a
167 /// `TsStmtKind::DocComment`-shaped block at the method's own indent,
168 /// immediately before its header line.
169 pub doc: Option<String>,
170 pub body: Vec<TsStmt>,
171 /// The source span the method's first printed line maps to (its doc comment,
172 /// if it has one), so the header and prologue anchor to the method's own
173 /// declaration rather than to the previous member's last body line (#2280,
174 /// 1A.32a). `None` records nothing.
175 pub span: Option<Span>,
176}
177
178impl TsClassMethod {
179 /// A public, undocumented method with no span. Set `private`, `doc` or `span`
180 /// with struct update (`TsClassMethod { private: true, ..TsClassMethod::new(..) }`)
181 /// when one is needed.
182 pub fn new(
183 name: impl Into<String>,
184 is_async: bool,
185 params: Vec<TsParam>,
186 return_type: Option<TsType>,
187 body: Vec<TsStmt>,
188 ) -> Self {
189 Self {
190 name: name.into(),
191 private: false,
192 is_async,
193 params,
194 return_type,
195 doc: None,
196 body,
197 span: None,
198 }
199 }
200
201 /// This method with the `private` modifier.
202 #[must_use]
203 pub fn private(mut self) -> Self {
204 self.private = true;
205 self
206 }
207}
208
209/// A top-level declaration. `Import`, `Export`, `Interface`, `ConstDecl`,
210/// and `Class` were `events_fanout.rs`'s own grounding (P7.8's own note:
211/// "not the sketch's `Function`/`TypeAlias` — unused in the grounding
212/// file"). #1321 (`workers.rs`) needed both after all — a real gap the
213/// accepted proposal's own Framing didn't name (its own "no other gap
214/// surfaced" checked `TsStmt`/`TsExpr`/`TsType` shapes, not `TsDecl` ones):
215/// `compose.ts`'s own `export function compose(env: Env, …) { … }` is a
216/// top-level function declaration, and (when the Worker has agents or
217/// publishes events) a `type DurableObjectNamespace = { … };` fallback
218/// alias sits alongside it. Named explicitly as a deviation from the
219/// accepted proposal's own catalogue, not silently added — both are
220/// mechanical, direct `TsDecl` siblings of `ConstDecl`/`Class` already
221/// here, the same "small, grounded, same class of gap" this track's own
222/// history repeatedly found and closed (P7.8's `Assign`/`Continue`/
223/// `TryCatch`, Arc C slice 1's `Comment`).
224#[derive(Debug, Clone, PartialEq)]
225pub enum TsDecl {
226 /// `import { a, b } from "spec";` (`type_only: false`) or
227 /// `import type { a, b } from "spec";` (`type_only: true`). Only the
228 /// named-imports form — `events_fanout.rs` never uses a default
229 /// import, so none is represented. `names` entries are pushed verbatim
230 /// (`printer.rs`'s own `names.join(", ")`), so a renamed import
231 /// (`__messagesLocales as __locale_declaredLocales`, `workers.rs`'s own
232 /// locale-negotiation import) is one opaque `String` entry, not a
233 /// structured rename — the same "the field is already a raw-text slot"
234 /// reasoning that also covers a `type`-prefixed single specifier
235 /// (`"type KVNamespace"`) inside an otherwise non-`type_only` import.
236 Import {
237 type_only: bool,
238 names: Vec<String>,
239 from: String,
240 },
241 /// `import * as alias from "spec";` — a namespace import, structurally
242 /// different from [`TsDecl::Import`]'s braced named-imports form (no
243 /// `{ }`, one bound name for the whole module). #1321's own real gap:
244 /// `workers.rs`'s `compose.ts` imports `handlers.js` and each
245 /// referenced unit's binding module this way; `events_fanout.rs` never
246 /// used one. `type_only` (Arc C, step (10), #1392) mirrors
247 /// [`TsDecl::Import`]'s own identical field, a parallel gap by
248 /// omission, not deliberate design — `emit_cross_context_namespace_
249 /// imports`'s own real `import type * as ns from "...";` form (a
250 /// Workers-mode consumed-context import reaching the callee's types
251 /// only, #661) had no way to represent the `type` keyword until now.
252 ImportNamespace {
253 type_only: bool,
254 alias: String,
255 from: String,
256 },
257 /// `import name from "spec";` — a default import, structurally
258 /// different from both [`TsDecl::Import`] (braced named-imports form)
259 /// and [`TsDecl::ImportNamespace`] (`* as` form) — no braces, no `* as`,
260 /// one bound local name for the module's own default export. No
261 /// `type_only` form — nothing in the grounding file default-imports a
262 /// type. Arc C, slice 37 (#1409, `tests_emit.rs`'s own slice G): a
263 /// per-participant `import worker_{ns} from "../workers/{dir}/
264 /// index.js";` (the participant's own Worker entry module's default
265 /// export) is the first real default import anywhere in `bynk-emit`'s
266 /// own converted content — every prior import site is either named
267 /// ([`TsDecl::Import`]) or namespace ([`TsDecl::ImportNamespace`]).
268 ///
269 /// 1A.38a: `named` carries the braced names that ride on the same statement
270 /// (`import __entry0, { isMiss as __miss0 } from "…";`, a Worker group's
271 /// member import), in [`TsDecl::Import`]'s own spelling (`a as b`,
272 /// `type T`). Empty is the plain default import every earlier site builds.
273 ImportDefault {
274 alias: String,
275 named: Vec<String>,
276 from: String,
277 },
278 /// `export { a, b } from "spec";` — a re-export, structurally distinct
279 /// from both [`TsDecl::Import`] (which binds locally, carries no
280 /// `export` keyword) and [`TsDecl::Export`] (which wraps a whole
281 /// declaration, not a braced name list re-pointed at another module).
282 /// #1323's own real gap: `workers_entry.rs` re-exports each agent's
283 /// Durable Object class from `./handlers.js`, and (when the context
284 /// publishes events) the fan-out DO's class from `./events_fanout.js`.
285 /// No `type_only` form — nothing in the grounding file re-exports a
286 /// type-only name.
287 ReExport { names: Vec<String>, from: String },
288 /// `export { a, b };` — exports names already bound in this module (an
289 /// import's, typically), with no `from` clause, which [`TsDecl::ReExport`]
290 /// always carries. A Workers context re-exports the boundary codecs it
291 /// imports from a `uses`d commons this way. #1820: a structured variant,
292 /// not opaque text, so [`TsStmt::exported_names`] reports what the module
293 /// exports to a barrel that must find the names two modules both export.
294 ExportNames { names: Vec<String> },
295 /// `export * from "spec";` — a wildcard re-export, structurally distinct
296 /// from [`TsDecl::ReExport`] (which always carries a braced name list —
297 /// an empty `names` there would render the ill-formed `export { }
298 /// from "spec";`, not this). Mirrors [`TsDecl::ImportNamespace`]'s own
299 /// "no braces, no name list, one bound target" shape, on the export
300 /// side. #1329's own real gap: `emit_commons_barrel`
301 /// (`bynk-emit/src/project/tests_emit.rs`) builds a multi-file
302 /// `commons` unit's barrel module as one `export *` line per
303 /// constituent source file.
304 ReExportAll { from: String },
305 /// Marks the wrapped declaration `export`ed — `export class Foo { .. }`
306 /// is `Export(Box::new(Class { .. }))`. A wrapper, not a per-variant
307 /// `exported: bool` field, matching the reference sketch's own naming
308 /// (`TsDecl::Export` is a peer variant, not a modifier on each other
309 /// one).
310 Export(Box<TsDecl>),
311 /// `type_params`/per-member `readonly` (#1339's own real gap):
312 /// `emit_record_type`'s own `export interface {name}{params} {
313 /// readonly {field}: {ty}; ... }` — bare generic names (matching
314 /// `ts_type_params`'s/`TsObjectEntry::Method.generics`'s own
315 /// convention) and a `readonly` modifier every real field here
316 /// carries. `members` reuses [`TsTypeMember`] (the exact same shape
317 /// [`TsType::Object`]'s own structural members already use) rather
318 /// than a bespoke tuple, since `readonly` is already that type's own
319 /// field — this interface's real content has never needed
320 /// `Method`/`Index`, but nothing about reusing the shared type
321 /// forecloses a future slice that does.
322 Interface {
323 name: String,
324 type_params: Vec<String>,
325 members: Vec<TsTypeMember>,
326 },
327 /// A top-level `const` — distinct from `TsStmtKind::Const` (private —
328 /// reachable through [`TsStmt::const_stmt`]), the local
329 /// form.
330 ConstDecl {
331 name: String,
332 ty: Option<TsType>,
333 init: TsExpr,
334 },
335 /// `class Name implements A, B { ... }`. `implements` is empty for a class that
336 /// names no interface, and prints as before. `end_span` is the source span
337 /// the closing `}` line maps to (1A.32a), so what follows the last member
338 /// belongs to the declaration rather than to that member's final body line;
339 /// `None` records nothing there. Build one with [`TsDecl::class`].
340 Class {
341 name: String,
342 implements: Vec<TsType>,
343 fields: Vec<TsClassField>,
344 constructor: Option<TsClassCtor>,
345 methods: Vec<TsClassMethod>,
346 end_span: Option<Span>,
347 },
348 /// `function name(params): ret { body }` (`is_async: false`) or `async
349 /// function name(params): ret { body }` (`is_async: true`) — a top-level
350 /// function declaration. `is_async` added by #1325: `workers.rs`'s own
351 /// one real site (`compose`) is never async, so the field didn't exist
352 /// until `emit_test_main`'s own top-level `async function main() {...}`
353 /// needed it — the exact "extend narrowly, add it when a future slice's
354 /// own grounding needs it" deferral this variant's own history already
355 /// named. `generics` added by #1351: `emit_free_fn`'s own v0.20a erased
356 /// generics (`export function foo<T>(...)`) — bare names only, empty
357 /// for every non-generic site (`compose`/`main`), matching every other
358 /// real generics-list precedent in this crate
359 /// (`TsObjectEntry::Method.generics` #1337, `TsExpr::Arrow.generics`
360 /// #1339). `inline` added by #1369 (Arc C, slice 20, step (9)'s own
361 /// second sub-slice): `emit_agent`'s own zero-factory function
362 /// (`function __zeroOf{Name}State(): {Name}State { return {...}; }`) is
363 /// a genuinely single-physical-line declaration — braces and body share
364 /// the header's own line, not `render_block_stmts`'s always-multi-line
365 /// shape. `false` (every site landed before #1369) renders the ordinary
366 /// multi-line body; `true` reuses `render_inline_block`'s own compact
367 /// `{ stmt; stmt; }` shape directly at the declaration's own header
368 /// line, the same "one more bool, mirroring an existing precedent"
369 /// scope `TsObjectEntry::Method.inline` (#1337) already set for the
370 /// identical single-line-vs-multi-line tension at a different node kind.
371 Function {
372 name: String,
373 generics: Vec<String>,
374 params: Vec<TsParam>,
375 return_type: Option<TsType>,
376 body: Vec<TsStmt>,
377 is_async: bool,
378 inline: bool,
379 },
380 /// `type name = ty;` (non-generic) or `type name<T, U> = ty;` (via
381 /// `type_params`, #1339's own real gap: `emit_sum_type`'s own generic
382 /// sum types erase to `export type Foo<T> = ...`) — a top-level type
383 /// alias. `workers.rs`'s own real site: the `DurableObjectNamespace`
384 /// local fallback type (emitted only when the Worker has agents or
385 /// publishes events), never generic — `type_params` is empty there.
386 TypeAlias {
387 name: String,
388 type_params: Vec<String>,
389 ty: TsType,
390 },
391 /// `export default <expr>;` — a default export of an *expression*, not
392 /// a declaration. #1323's own real gap (`workers_entry.rs`'s own
393 /// top-level shape, `export default { fetch, scheduled?, queue? }`):
394 /// [`TsDecl::Export`] wraps a [`TsDecl`] (a `Class`/`ConstDecl`/etc.,
395 /// something with its own name), which cannot represent exporting a
396 /// bare, unnamed object-literal expression — so this is its own
397 /// variant, not `Export(Box::new(ConstDecl { .. }))` with a synthetic
398 /// name that would print wrong.
399 ExportDefault(TsExpr),
400 /// `declare const name: ty;` — an ambient binding with no initialiser,
401 /// narrowing a global TypeScript otherwise doesn't know about. #1325's
402 /// own real, narrow site: `emit_test_main`'s own `declare const process:
403 /// { exit(code: number): never; env: { [k: string]: string | undefined
404 /// } };`, narrowing Node's `process` global without a `@types/node`
405 /// dependency. Distinct from [`TsDecl::ConstDecl`] (always has a real
406 /// `init` expression) — a `declare const` has none, by definition; a
407 /// `TsDecl::ConstDecl` with a synthetic placeholder `init` would print
408 /// wrong (`= <something>;` where nothing should appear at all).
409 DeclareConst { name: String, ty: TsType },
410}
411
412impl TsDecl {
413 /// `import <alias> from "<from>";`: a default import with no braced names.
414 pub fn import_default(alias: impl Into<String>, from: impl Into<String>) -> Self {
415 TsDecl::ImportDefault {
416 alias: alias.into(),
417 named: Vec::new(),
418 from: from.into(),
419 }
420 }
421
422 /// A class with no `implements` clause and no closing-line span: the shape
423 /// every class had before 1A.32a. Name the extras with [`TsDecl::implementing`]
424 /// and [`TsDecl::ending_at`].
425 pub fn class(
426 name: impl Into<String>,
427 fields: Vec<TsClassField>,
428 constructor: Option<TsClassCtor>,
429 methods: Vec<TsClassMethod>,
430 ) -> Self {
431 TsDecl::Class {
432 name: name.into(),
433 implements: Vec::new(),
434 fields,
435 constructor,
436 methods,
437 end_span: None,
438 }
439 }
440
441 /// This class with `implements` as its `implements` clause. A declaration that
442 /// is not a class is returned unchanged.
443 #[must_use]
444 pub fn implementing(mut self, implements: Vec<TsType>) -> Self {
445 if let TsDecl::Class {
446 implements: slot, ..
447 } = &mut self
448 {
449 *slot = implements;
450 }
451 self
452 }
453
454 /// This class with its closing `}` line mapped to `span`. A declaration that
455 /// is not a class is returned unchanged.
456 #[must_use]
457 pub fn ending_at(mut self, span: Span) -> Self {
458 if let TsDecl::Class { end_span, .. } = &mut self {
459 *end_span = Some(span);
460 }
461 self
462 }
463}