bynk_emit/emitter/serialisation/generics.rs
1//! Generic instantiations (back-half paydown 2.3b, #4088): the helpers for each generic instantiation a
2//! module needs, and the lenient `Option` decode, with their tests. Moved out of `serialisation.rs`
3//! byte for byte.
4
5use std::sync::Arc;
6
7use bynk_check::wire::{WireField, WireSum, WireVariant, recursive_codec_suffixes};
8use bynk_syntax::ast::{BaseType, TypeBody, TypeDecl, TypeRef};
9use bynk_ts::{
10 TsBinaryOp, TsBindingName, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsStmt, TsType,
11 TsTypeMember,
12};
13
14use crate::emitter::RuntimeUse;
15use crate::ts_build::{
16 and_expr, arrow, as_expr, binary, block, call, const_, ident, if_, index, member, not_expr,
17 or_expr, ret, str_lit, strict_eq, strict_neq, typeof_expr,
18};
19
20use super::field::{emit_field_deserialise, serialise_field_expr};
21use super::record_sum::{emit_record_codec, emit_sum_codec};
22use super::support::{
23 Depth, array_shape_guard, depth_expected, depth_for, deserialise_params,
24 err_structural_mismatch, err_structural_mismatch_top, index_signature_record_ty, obj_prop,
25 object_shape_guard, path_elem, path_entry, path_field, serialise_params, value_prop,
26};
27use super::{GenericInst, app_ts_name, inner_ts_name, record_inst_fields, sum_inst_variants};
28use super::{Qual, qual_type, qualified_ts_type, wire_ref_of};
29
30/// `(v) => <serialise v>`: the element serialiser a `List` or `Set` codec maps over.
31fn element_serialiser(elem: &TypeRef, depth: Option<Depth<'_>>, ru: &RuntimeUse) -> TsExpr {
32 arrow(
33 vec![TsParam::new("v", None)],
34 serialise_field_expr(elem, &ident("v"), depth, ru),
35 )
36}
37
38/// `(globalThis as { __bynkPlainJson?: boolean }).__bynkPlainJson === true`: whether `withPlainJson`
39/// has the plain-JSON flag set. The cast prints bracketed as the member's receiver.
40fn plain_json_test() -> TsExpr {
41 strict_eq(
42 member(
43 TsExpr::As {
44 expr: Box::new(ident("globalThis")),
45 ty: TsType::Object(vec![TsTypeMember::optional_prop(
46 "__bynkPlainJson",
47 TsType::named("boolean"),
48 )]),
49 },
50 "__bynkPlainJson",
51 ),
52 TsExpr::Lit(TsLit::Bool(true)),
53 )
54}
55
56/// Constrained generics slice 2: whether a `Map` key / `Set` element declared as
57/// `t` is a JS primitive, so a plain `Map`/`Set` compares it by value. Every
58/// other `Key` type decodes into the keyed collections (`keys.ts`).
59fn is_plain_key_ref(t: &TypeRef, types: &std::collections::HashMap<String, Arc<TypeDecl>>) -> bool {
60 match t {
61 TypeRef::Base(b, _) => !matches!(b, BaseType::Bytes | BaseType::Decimal),
62 TypeRef::Named(id) => matches!(
63 types.get(&id.name).map(|d| &d.body),
64 Some(TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. })
65 if !matches!(base, BaseType::Bytes | BaseType::Decimal)
66 ),
67 TypeRef::Result(..)
68 | TypeRef::Option(..)
69 | TypeRef::Effect(..)
70 | TypeRef::HttpResult(..)
71 | TypeRef::QueueResult(_)
72 | TypeRef::Asset(_)
73 | TypeRef::RequestHeaders(_)
74 | TypeRef::RequestQuery(_)
75 | TypeRef::RequestCookies(_)
76 | TypeRef::TokenClaims(_)
77 | TypeRef::BoundaryRejection(_)
78 | TypeRef::List(..)
79 | TypeRef::Map(..)
80 | TypeRef::Set(..)
81 | TypeRef::Query(..)
82 | TypeRef::Stream(..)
83 | TypeRef::Connection(..)
84 | TypeRef::History(..)
85 | TypeRef::ValidationError(_)
86 | TypeRef::DecodeError(_)
87 | TypeRef::Unit(_)
88 | TypeRef::Fn(..)
89 | TypeRef::App { .. } => false,
90 }
91}
92
93/// The `Ok`/`Err` (or `Some`/`None`) cascade of a generic sum's wire decoder:
94///
95/// ```text
96/// if (obj["kind"] === "A") { <guard_a> <return_a> } else if (obj["kind"] === "B") { <guard_b> <return_b> }
97/// ```
98///
99/// One `If` with `same_line_else` whose else branch is the second `If`, so each
100/// branch's guards sit at their true depth (1A.38a; they used to be spliced one
101/// level shallow, as text).
102fn wire_kind_dispatch(
103 key_a: &str,
104 guard_a: Vec<TsStmt>,
105 return_a: TsStmt,
106 key_b: &str,
107 guard_b: Vec<TsStmt>,
108 return_b: TsStmt,
109) -> TsStmt {
110 let wire_kind_eq = |key: &str| strict_eq(index(ident("obj"), str_lit("kind")), str_lit(key));
111 let branch = |mut guard: Vec<TsStmt>, ret: TsStmt| {
112 guard.push(ret);
113 block(guard)
114 };
115 TsStmt::if_else_same_line_stmt(
116 wire_kind_eq(key_a),
117 branch(guard_a, return_a),
118 if_(wire_kind_eq(key_b), branch(guard_b, return_b)),
119 None,
120 )
121}
122
123/// The text appended to a bare value's `StructuralMismatch.expected` when it
124/// fails to decode as an `Option[U]`'s `U` (#1887), so the error names every
125/// form the `Option` decoder would have taken, not only `U`'s.
126const OPTION_FORMS_SUFFIX: &str =
127 " | null | {\"kind\": \"None\"} | {\"kind\": \"Some\", \"value\": ...}";
128
129/// `Ok(<value> as Option<U>)`: the `Option` decoder's one success shape.
130fn ok_option(value: TsExpr, option_ty: &TsType) -> TsStmt {
131 ret(call(ident("Ok"), vec![as_expr(value, option_ty.clone())]))
132}
133
134/// The body of `__deserialise_Option_<U>` (#1887, ADR amending 0045). The
135/// decoder is lenient: it accepts the forms the rest of the JSON world uses
136/// for an optional value, as well as the tagged form Bynk's encoder writes.
137/// It is the one `Option` codec, so the rule holds at every boundary that
138/// decodes JSON: `Json.decode`, an HTTP request body, a service-to-service
139/// call, agent-store rehydration and a WebSocket frame.
140///
141/// In order:
142///
143/// 1. `undefined` (the key is absent from the enclosing record, whose codec
144/// reads `obj["f"]` with no presence check) or `null` decodes to `None`.
145/// 2. An object whose only key is `kind`, set to `"None"`, decodes to `None`.
146/// 3. An object whose only keys are `kind` and `value`, with `kind` set to
147/// `"Some"`, decodes to `Some(U(value))`, the error path at `$.value`.
148/// 4. Anything else is a bare value and decodes to `Some(U(json))`.
149///
150/// The tagged forms are tried before the bare one, so they win when a value
151/// could be read both ways. That keeps `decode(encode(x)) == x` for every
152/// `x`, because the encoder always writes a tagged form: `Some(None)` of an
153/// `Option[Option[T]]` is `{kind: "Some", value: {kind: "None"}}`, and
154/// `Some(r)` for an `r` that itself has `kind`/`value` fields wraps `r` in
155/// an outer tag, so the inner decoder sees `r` intact. The cost falls on
156/// non-Bynk input only: a bare `{"kind": "None"}` for an `Option[Option[T]]`
157/// is `None`, not `Some(None)`.
158///
159/// `U` is decoded by a local `__decode(raw, at)` arrow, so its checks are
160/// emitted once and shared by rules 3 and 4. Its result is typed
161/// `Result<unknown, …>` and cast to `U` on success, as the old decoder cast
162/// `Some(__v)`, because `U`'s codec may return an unbranded record where
163/// this module's `U` is a branded rebrand (#527). When a bare value fails as
164/// a `StructuralMismatch` at the `Option`'s own path, the error's `expected`
165/// is extended with [`OPTION_FORMS_SUFFIX`]. A deeper error, or a
166/// `RefinementViolation`, is returned as `U` reported it.
167fn lenient_option_decode_body(
168 value_fn: &str,
169 inner_ty: &TsType,
170 option_ty: &TsType,
171 depth: Option<Depth<'_>>,
172) -> Vec<TsStmt> {
173 // #2656: the value decoder takes the depth when the `Option` is on a type
174 // cycle ([`option_value_decoder`]).
175 let value_args = |raw: TsExpr, at: TsExpr| -> Vec<TsExpr> {
176 let mut args = vec![raw, at];
177 if depth.is_some() {
178 args.push(ident("depth"));
179 }
180 args
181 };
182 let some_of = |result: &str| {
183 call(
184 ident("Some"),
185 vec![as_expr(member(ident(result), "value"), inner_ty.clone())],
186 )
187 };
188 let obj_kind_is = |kind: &str| strict_eq(index(ident("obj"), str_lit("kind")), str_lit(kind));
189 let keys_len_is = |n: &str| {
190 strict_eq(
191 member(ident("__keys"), "length"),
192 TsExpr::Lit(TsLit::Num(n.to_string())),
193 )
194 };
195 let tagged = vec![
196 TsStmt::const_stmt(
197 TsBindingName::Ident("obj".to_string()),
198 None,
199 as_expr(ident("json"), index_signature_record_ty()),
200 None,
201 ),
202 const_(
203 "__keys",
204 call(
205 member(ident("globalThis.Object"), "keys"),
206 vec![ident("obj")],
207 ),
208 ),
209 // Rule 2: exactly `{kind: "None"}`.
210 if_(
211 and_expr(obj_kind_is("None"), keys_len_is("1")),
212 block(vec![ok_option(ident("None"), option_ty)]),
213 ),
214 // Rule 3: exactly `{kind: "Some", value}`.
215 if_(
216 and_expr(
217 and_expr(obj_kind_is("Some"), keys_len_is("2")),
218 binary(TsBinaryOp::In, str_lit("value"), ident("obj")),
219 ),
220 block(vec![
221 const_(
222 "__t",
223 call(
224 ident(value_fn),
225 value_args(index(ident("obj"), str_lit("value")), path_field("value")),
226 ),
227 ),
228 if_(
229 strict_eq(member(ident("__t"), "tag"), str_lit("Err")),
230 block(vec![ret(ident("__t"))]),
231 ),
232 ok_option(some_of("__t"), option_ty),
233 ]),
234 ),
235 ];
236 let bare_error = member(ident("__b"), "error");
237 let mut extend_cond = and_expr(
238 and_expr(
239 strict_eq(
240 member(bare_error.clone(), "kind"),
241 str_lit("StructuralMismatch"),
242 ),
243 strict_eq(member(bare_error.clone(), "path"), ident("path")),
244 ),
245 not_expr(call(
246 member(member(bare_error.clone(), "expected"), "endsWith"),
247 vec![str_lit(OPTION_FORMS_SUFFIX)],
248 )),
249 );
250 // #2656: the nesting bound's error is not about the `Option`'s forms, so
251 // it is returned as the inner decoder reported it.
252 if depth.is_some() {
253 extend_cond = and_expr(
254 extend_cond,
255 strict_neq(
256 member(bare_error.clone(), "expected"),
257 str_lit(depth_expected()),
258 ),
259 );
260 }
261 vec![
262 // Rule 1: absent or `null`.
263 if_(
264 or_expr(
265 strict_eq(ident("json"), ident("undefined")),
266 strict_eq(ident("json"), TsExpr::Lit(TsLit::Null)),
267 ),
268 block(vec![ok_option(ident("None"), option_ty)]),
269 ),
270 if_(
271 and_expr(
272 strict_eq(typeof_expr(ident("json")), str_lit("object")),
273 not_expr(call(
274 member(ident("globalThis.Array"), "isArray"),
275 vec![ident("json")],
276 )),
277 ),
278 block(tagged),
279 ),
280 // Rule 4: a bare value.
281 const_(
282 "__b",
283 call(ident(value_fn), value_args(ident("json"), ident("path"))),
284 ),
285 if_(
286 strict_eq(member(ident("__b"), "tag"), str_lit("Ok")),
287 block(vec![ok_option(some_of("__b"), option_ty)]),
288 ),
289 // The suffix is appended once: for an `Option[Option[T]]` the inner
290 // decoder has already extended an error at this same path.
291 if_(
292 extend_cond,
293 block(vec![ret(call(
294 ident("Err"),
295 vec![TsExpr::object_entries(vec![
296 TsObjectEntry::Spread(bare_error.clone()),
297 TsObjectEntry::prop(
298 "expected".to_string(),
299 binary(
300 TsBinaryOp::Add,
301 member(bare_error, "expected"),
302 str_lit(OPTION_FORMS_SUFFIX),
303 ),
304 ),
305 ])],
306 ))]),
307 ),
308 ret(ident("__b")),
309 ]
310}
311
312/// `function <name>(raw, at): Result<unknown, __BoundaryError>`: decodes one
313/// `Option[U]`'s `U` from `raw`, reporting errors at `at` (#1887). The
314/// lenient `Option` decoder ([`lenient_option_decode_body`]) calls it for
315/// both the tagged `value` and a bare value, so `U`'s checks are emitted
316/// once. Module-local, not exported: only its own module's
317/// `__deserialise_Option_<U>` calls it, and an export would collide under
318/// a barrel's `export *` the way a shared helper name can.
319fn option_value_decoder(
320 name: String,
321 inner: &TypeRef,
322 depth: Option<Depth<'_>>,
323 ru: &RuntimeUse,
324) -> TsDecl {
325 let mut body = emit_field_deserialise("v", inner, &ident("raw"), &ident("at"), depth, ru);
326 body.push(ret(call(ident("Ok"), vec![ident("__v")])));
327 let mut params = vec![
328 TsParam::new("raw".to_string(), Some(TsType::named("__JsonValue"))),
329 TsParam::new("at".to_string(), Some(TsType::named("string"))),
330 ];
331 // #2656: on a type cycle, the `Option` decoder hands its depth through.
332 if depth.is_some() {
333 params.push(TsParam::new(
334 "depth".to_string(),
335 Some(TsType::named("number")),
336 ));
337 }
338 TsDecl::Function {
339 name,
340 generics: Vec::new(),
341 params,
342 return_type: Some(TsType::named_with_args(
343 "Result",
344 vec![TsType::named("unknown"), TsType::named("__BoundaryError")],
345 )),
346 body,
347 is_async: false,
348 inline: false,
349 }
350}
351
352/// Emit specialised helpers for each `Result<A, B>` / `Option<A>`
353/// instantiation. They delegate to the named-type serialisers for A and B.
354/// v0.174 (#592): also emits a monomorphised record codec per generic
355/// instantiation (`RecordInst`), which needs the declarations to substitute
356/// its type parameters.
357pub(crate) fn emit_generic_helpers(
358 insts: &[GenericInst],
359 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
360 ru: &RuntimeUse,
361) -> Vec<TsDecl> {
362 emit_generic_helpers_qualified(insts, types, &Qual::new(), ru)
363}
364
365/// #661: as `emit_generic_helpers`, but the value-type positions of each
366/// specialised helper are named through the type `Qual` — so a consumer's
367/// `deserialise_Result_AuthId_PaymentError` returns
368/// `Result<commerce_payment.AuthId, commerce_payment.PaymentError>` while its
369/// codec calls stay local. The codec *suffix* (`Result_AuthId_PaymentError`) is
370/// namespace-independent by construction, which is exactly what keeps the
371/// caller's and callee's names in agreement across the wire.
372///
373/// Arc F slice 1 (#1451): returns the real `bynk_ts::TsDecl` nodes directly —
374/// no `out: &mut String` parameter. The boundary-collect step
375/// ([`super::decls_as_stmts`]) now happens once, at the caller, instead of inline in
376/// each of this function's six match arms.
377pub fn emit_generic_helpers_qualified(
378 insts: &[GenericInst],
379 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
380 qual: &Qual,
381 ru: &RuntimeUse,
382) -> Vec<TsDecl> {
383 let mut decls = Vec::new();
384 let codecs = recursive_codec_suffixes(types);
385 for inst in insts {
386 // #2656: a container codec on a type cycle passes the nesting depth
387 // through unchanged; a generic record or sum counts a level, as a
388 // non-generic one does (`emit_record_codec`/`emit_sum_codec`).
389 let depth = depth_for(&codecs, &inst.ts_name(), false);
390 match inst {
391 // v0.174 (#592): a generic-record instantiation `Paginated[User]`
392 // emits `serialise_Paginated_User` / `deserialise_Paginated_User`,
393 // its fields specialised to the concrete arguments. The value type
394 // is the erased generic `Paginated<User>`.
395 GenericInst::RecordInst { name, args } => {
396 let fn_suffix = app_ts_name(name, args);
397 let ts_type = TsType::named_with_args(
398 qual_type(qual, name),
399 args.iter().map(|a| qualified_ts_type(a, qual)).collect(),
400 );
401 // `record_inst_fields` is `None` only for an unknown name, a
402 // non-record body, or an arity mismatch — all of which the
403 // resolver rejects (`generic_non_record` / `type_arg_count`)
404 // before a `RecordInst` is ever collected. Panic loudly rather
405 // than silently emit a call to an undefined codec (the file's
406 // convention for a checker-guaranteed invariant).
407 let fields = record_inst_fields(name, args, types).unwrap_or_else(|| {
408 unreachable!("RecordInst `{name}` is not a resolved generic record")
409 });
410 // #2607 (Decision I): a field's default rides along, paired
411 // with the field's *substituted* type, so it renders at the
412 // instantiation exactly as it would in a non-generic record —
413 // the checker only admits a default whose value holds for
414 // every instantiation (`None`, `[]`, a concrete field's
415 // literal). #855 (Phase 2 step 9): a
416 // `WireField` for a substituted instantiation type is built
417 // straight from `record_inst_fields`' resolved `TypeRef`s via
418 // `wire_ref_of`, mirroring what `wire_type`/`wire_fields`
419 // would derive for a non-generic declaration's own fields.
420 //
421 // #1969: the instantiation keeps each field's inline
422 // refinement, read off the declaration and paired by name, so
423 // a field the two lists disagree on panics rather than
424 // silently losing its check (the contract hash would still
425 // include it).
426 #[allow(clippy::type_complexity)]
427 let declared: std::collections::HashMap<
428 &str,
429 (
430 Vec<bynk_syntax::ast::PredKind>,
431 Option<&bynk_syntax::ast::Expr>,
432 ),
433 > = match types.get(name.as_str()).map(|d| &d.body) {
434 Some(bynk_syntax::ast::TypeBody::Record(r)) => r
435 .fields
436 .iter()
437 .map(|f| {
438 (
439 f.name.name.as_str(),
440 (bynk_check::wire::field_predicates(f), f.init.as_ref()),
441 )
442 })
443 .collect(),
444 _ => unreachable!("RecordInst `{name}` is not a resolved generic record"),
445 };
446 let fields: Vec<WireField> = fields
447 .into_iter()
448 .map(|(n, t)| {
449 let (predicates, init) =
450 declared.get(n.as_str()).cloned().unwrap_or_else(|| {
451 unreachable!("`{name}` has no declared field `{n}`")
452 });
453 WireField {
454 shape: wire_ref_of(&t),
455 predicates,
456 path_segment: n.clone(),
457 default: init.map(|e| (e.clone(), t.clone())),
458 name: n,
459 }
460 })
461 .collect();
462 // #1443 (Arc E slice 5): `emit_record_codec` itself now
463 // builds real `bynk_ts::TsDecl` nodes — this whole function
464 // stays `String`-based (out of this slice's scope, per the
465 // issue's own "real complications" note 3), so this call
466 // site needs the same boundary-print treatment `emit_one`'s
467 // `Record`/`Refined`/`Opaque` arms already use (#1441,
468 // #1443).
469 decls.extend(emit_record_codec(
470 &fn_suffix, &ts_type, &fields, types, &codecs, ru,
471 ));
472 }
473 // #593: a generic-sum instantiation `ApiResult[User]` emits
474 // `serialise_ApiResult_User` / `deserialise_ApiResult_User`, its
475 // variant payloads specialised to the concrete arguments. The value
476 // type is the erased generic `ApiResult<User>`. Mirrors `RecordInst`.
477 GenericInst::SumInst { name, args } => {
478 let fn_suffix = app_ts_name(name, args);
479 // #1736: qualified like `RecordInst` above: a consumed
480 // context's generic sum is named through its namespace.
481 let ts_type = TsType::named_with_args(
482 qual_type(qual, name),
483 args.iter().map(|a| qualified_ts_type(a, qual)).collect(),
484 );
485 let variants = sum_inst_variants(name, args, types).unwrap_or_else(|| {
486 unreachable!("SumInst `{name}` is not a resolved generic sum")
487 });
488 // #855 (Phase 2 step 9): a `WireSum` for a substituted
489 // instantiation is built straight from `sum_inst_variants`'
490 // resolved `TypeRef`s via `wire_ref_of`, mirroring what
491 // `wire_type`/`wire_sum` would derive for a non-generic
492 // declaration's own variants. The wire/memory discriminants
493 // are the same fixed `"kind"`/`"tag"` pair `wire_sum` uses.
494 let sum = WireSum {
495 wire_discriminant: bynk_check::wire::WIRE_DISCRIMINANT,
496 memory_discriminant: "tag",
497 variants: variants
498 .into_iter()
499 .map(|(vname, payload)| WireVariant {
500 name: vname,
501 payload: payload
502 .into_iter()
503 .map(|(fname, t)| WireField {
504 shape: wire_ref_of(&t),
505 path_segment: fname.clone(),
506 name: fname,
507 default: None,
508 predicates: Vec::new(),
509 })
510 .collect(),
511 })
512 .collect(),
513 };
514 // #1445 (Arc E slice 6): `emit_sum_codec` itself now builds
515 // real `bynk_ts::TsDecl` nodes — this whole function stays
516 // `String`-based (out of this slice's scope, per the
517 // issue's own "real complications" note 4, mirroring
518 // `RecordInst`'s own identical treatment in #1443), so this
519 // call site needs the same boundary-print treatment
520 // `emit_one`'s `Sum`/`Record`/`Refined`/`Opaque` arms
521 // already use (#1441, #1443, #1445).
522 decls.extend(emit_sum_codec(&fn_suffix, &ts_type, &sum, &codecs, ru));
523 }
524 // #1447 (Arc E slice 7): builds the `[serialise, deserialise]`
525 // pair as real `bynk_ts::TsDecl` nodes — the same shape
526 // `emit_record_codec`/`emit_sum_codec`/`emit_bytes_named_codec`
527 // already established (#1443/#1445/#1441) — and boundary-prints
528 // them the same way `RecordInst`/`SumInst` above already do.
529 // Unlike those two, there is no separate `emit_result_codec` to
530 // delegate to: this match arm IS the codec body (the issue's own
531 // scope note), so the `TsDecl::Function` construction sits
532 // inline here rather than behind a further indirection.
533 GenericInst::ResultInst { ok, err } => {
534 let ok_ts = inner_ts_name(ok);
535 let err_ts = inner_ts_name(err);
536 let ok_inner = qualified_ts_type(ok, qual);
537 let err_inner = qualified_ts_type(err, qual);
538 let result_ty = TsType::named_with_args("Result", vec![ok_inner, err_inner]);
539
540 let serialise = TsDecl::Export(Box::new(TsDecl::Function {
541 name: format!("__serialise_Result_{ok_ts}_{err_ts}"),
542 generics: Vec::new(),
543 params: serialise_params(result_ty.clone(), depth),
544 return_type: Some(TsType::named("__JsonValue")),
545 body: vec![
546 if_(
547 strict_eq(member(ident("value"), "tag"), str_lit("Ok")),
548 ret(TsExpr::object(vec![
549 ("kind".to_string(), str_lit("Ok")),
550 (
551 "value".to_string(),
552 serialise_field_expr(ok, &value_prop("value"), depth, ru),
553 ),
554 ])),
555 ),
556 ret(TsExpr::object(vec![
557 ("kind".to_string(), str_lit("Err")),
558 (
559 "error".to_string(),
560 serialise_field_expr(err, &value_prop("error"), depth, ru),
561 ),
562 ])),
563 ],
564 is_async: false,
565 inline: false,
566 }));
567
568 let mut body = object_shape_guard();
569 body.push(wire_kind_dispatch(
570 "Ok",
571 emit_field_deserialise(
572 "v",
573 ok,
574 &obj_prop("value"),
575 &path_field("value"),
576 depth,
577 ru,
578 ),
579 ret(call(
580 ident("Ok"),
581 vec![as_expr(
582 call(ident("Ok"), vec![ident("__v")]),
583 result_ty.clone(),
584 )],
585 )),
586 "Err",
587 emit_field_deserialise(
588 "e",
589 err,
590 &obj_prop("error"),
591 &path_field("error"),
592 depth,
593 ru,
594 ),
595 ret(call(
596 ident("Ok"),
597 vec![as_expr(
598 call(ident("Err"), vec![ident("__e")]),
599 result_ty.clone(),
600 )],
601 )),
602 ));
603 body.push(ret(err_structural_mismatch_top(
604 "Ok | Err",
605 call(ident("String"), vec![index(ident("obj"), str_lit("kind"))]),
606 )));
607
608 let deserialise = TsDecl::Export(Box::new(TsDecl::Function {
609 name: format!("__deserialise_Result_{ok_ts}_{err_ts}"),
610 generics: Vec::new(),
611 params: deserialise_params(depth),
612 return_type: Some(TsType::named_with_args(
613 "Result",
614 vec![result_ty, TsType::named("__BoundaryError")],
615 )),
616 body,
617 is_async: false,
618 inline: false,
619 }));
620
621 decls.extend([serialise, deserialise]);
622 }
623 GenericInst::OptionInst { inner } => {
624 let inner_ts = inner_ts_name(inner);
625 let inner_ty = qualified_ts_type(inner, qual);
626 let option_ty = TsType::named_with_args("Option", vec![inner_ty.clone()]);
627
628 // #2858: in a project with a plain-JSON route the one `Option`
629 // encoder also carries the plain branch: while `withPlainJson` has
630 // `__bynkPlainJson` set, `Some(v)` is `v` and `None` is `null`.
631 // Otherwise (and in every project without such a route) it is the
632 // tagged encoder alone.
633 let some_value =
634 serialise_field_expr(inner, &member(ident("value"), "value"), depth, ru);
635 let tagged_some = TsExpr::object(vec![
636 ("kind".to_string(), str_lit("Some")),
637 ("value".to_string(), some_value.clone()),
638 ]);
639 let tagged_none = TsExpr::object(vec![("kind".to_string(), str_lit("None"))]);
640 let body = if ru.plain_json() {
641 let plain = plain_json_test;
642 let pick = |plain_branch: TsExpr, tagged_branch: TsExpr| TsExpr::Conditional {
643 test: Box::new(plain()),
644 consequent: Box::new(plain_branch),
645 alternate: Box::new(tagged_branch),
646 };
647 vec![
648 if_(
649 strict_eq(member(ident("value"), "tag"), str_lit("Some")),
650 ret(pick(some_value, tagged_some)),
651 ),
652 ret(pick(ident("null"), tagged_none)),
653 ]
654 } else {
655 vec![
656 if_(
657 strict_eq(member(ident("value"), "tag"), str_lit("Some")),
658 ret(tagged_some),
659 ),
660 ret(tagged_none),
661 ]
662 };
663 let serialise = TsDecl::Export(Box::new(TsDecl::Function {
664 name: format!("__serialise_Option_{inner_ts}"),
665 generics: Vec::new(),
666 params: serialise_params(option_ty.clone(), depth),
667 return_type: Some(TsType::named("__JsonValue")),
668 body,
669 is_async: false,
670 inline: false,
671 }));
672
673 let value_fn = format!("__option_value_{inner_ts}");
674 let body = lenient_option_decode_body(&value_fn, &inner_ty, &option_ty, depth);
675 let value_decoder = option_value_decoder(value_fn, inner, depth, ru);
676
677 let deserialise = TsDecl::Export(Box::new(TsDecl::Function {
678 name: format!("__deserialise_Option_{inner_ts}"),
679 generics: Vec::new(),
680 params: deserialise_params(depth),
681 return_type: Some(TsType::named_with_args(
682 "Result",
683 vec![option_ty, TsType::named("__BoundaryError")],
684 )),
685 body,
686 is_async: false,
687 inline: false,
688 }));
689
690 decls.extend([serialise, value_decoder, deserialise]);
691 }
692 // v0.20b: `List[T]` — element-wise wire format (a JSON array).
693 GenericInst::ListInst { elem } => {
694 let elem_ts = inner_ts_name(elem);
695 let elem_ty = qualified_ts_type(elem, qual);
696 let readonly_elem_array = TsType::readonly_array(elem_ty.clone());
697
698 let serialise = TsDecl::Export(Box::new(TsDecl::Function {
699 name: format!("__serialise_List_{elem_ts}"),
700 generics: Vec::new(),
701 params: serialise_params(readonly_elem_array.clone(), depth),
702 return_type: Some(TsType::named("__JsonValue")),
703 body: vec![ret(call(
704 member(ident("value"), "map"),
705 vec![element_serialiser(elem, depth, ru)],
706 ))],
707 is_async: false,
708 inline: false,
709 }));
710
711 // Bind the element before validating: `json[i]` with a
712 // mutable index does not narrow under a typeof guard.
713 let mut loop_body = vec![const_("item", index(ident("json"), ident("i")))];
714 loop_body.extend(emit_field_deserialise(
715 "el",
716 elem,
717 &ident("item"),
718 &path_elem(),
719 depth,
720 ru,
721 ));
722 // The element deserialiser may come from the declaring
723 // commons and return the *unbranded* record; this module's
724 // element type may be the context's branded rebrand. Assert
725 // the element like the Option codec above does (#527).
726 loop_body.push(TsStmt::expr_stmt(
727 call(
728 member(ident("out"), "push"),
729 vec![as_expr(ident("__el"), elem_ty.clone())],
730 ),
731 None,
732 ));
733
734 let deserialise = TsDecl::Export(Box::new(TsDecl::Function {
735 name: format!("__deserialise_List_{elem_ts}"),
736 generics: Vec::new(),
737 params: deserialise_params(depth),
738 return_type: Some(TsType::named_with_args(
739 "Result",
740 vec![readonly_elem_array, TsType::named("__BoundaryError")],
741 )),
742 body: vec![
743 array_shape_guard(),
744 TsStmt::const_stmt(
745 TsBindingName::Ident("out".to_string()),
746 Some(TsType::array(elem_ty)),
747 TsExpr::array(vec![]),
748 None,
749 ),
750 TsStmt::for_stmt(
751 "i",
752 TsExpr::Lit(TsLit::Num("0".to_string())),
753 binary(
754 TsBinaryOp::LessThan,
755 ident("i"),
756 member(ident("json"), "length"),
757 ),
758 block(loop_body),
759 None,
760 ),
761 ret(call(ident("Ok"), vec![ident("out")])),
762 ],
763 is_async: false,
764 inline: false,
765 }));
766
767 decls.extend([serialise, deserialise]);
768 }
769 // K6a (#2596): `Set[T]` — a JSON array in insertion order. The
770 // decoder refuses a duplicate element: a Bynk sender never writes
771 // one, so it means the payload is not the set it claims to be.
772 GenericInst::SetInst { elem } => {
773 let elem_ts = inner_ts_name(elem);
774 let elem_ty = qualified_ts_type(elem, qual);
775 let set_ty = TsType::named_with_args("ReadonlySet", vec![elem_ty.clone()]);
776 // Slice 2 (DECISION H): a composite element decodes into the keyed
777 // set, whose `has` is value equality, so a wire duplicate is
778 // rejected whatever the element's shape.
779 let set_ctor = if is_plain_key_ref(elem, types) {
780 "globalThis.Set"
781 } else {
782 ru.note_key("__BynkKeySet");
783 "__BynkKeySet"
784 };
785 let set_ctor = TsExpr::TypeApp {
786 callee: Box::new(ident(set_ctor)),
787 type_args: vec![elem_ty.clone()],
788 };
789
790 let serialise = TsDecl::Export(Box::new(TsDecl::Function {
791 name: format!("__serialise_Set_{elem_ts}"),
792 generics: Vec::new(),
793 params: serialise_params(set_ty.clone(), depth),
794 return_type: Some(TsType::named("__JsonValue")),
795 body: vec![ret(call(
796 member(
797 call(ident("globalThis.Array.from"), vec![ident("value")]),
798 "map",
799 ),
800 vec![element_serialiser(elem, depth, ru)],
801 ))],
802 is_async: false,
803 inline: false,
804 }));
805
806 let mut loop_body = vec![const_("item", index(ident("json"), ident("i")))];
807 loop_body.extend(emit_field_deserialise(
808 "el",
809 elem,
810 &ident("item"),
811 &path_elem(),
812 depth,
813 ru,
814 ));
815 loop_body.push(if_(
816 call(
817 member(ident("out"), "has"),
818 vec![as_expr(ident("__el"), elem_ty.clone())],
819 ),
820 block(vec![ret(err_structural_mismatch(
821 &path_elem(),
822 "a distinct set element",
823 str_lit("a duplicate"),
824 ))]),
825 ));
826 loop_body.push(TsStmt::expr_stmt(
827 call(
828 member(ident("out"), "add"),
829 vec![as_expr(ident("__el"), elem_ty.clone())],
830 ),
831 None,
832 ));
833
834 let deserialise = TsDecl::Export(Box::new(TsDecl::Function {
835 name: format!("__deserialise_Set_{elem_ts}"),
836 generics: Vec::new(),
837 params: deserialise_params(depth),
838 return_type: Some(TsType::named_with_args(
839 "Result",
840 vec![set_ty, TsType::named("__BoundaryError")],
841 )),
842 body: vec![
843 array_shape_guard(),
844 const_(
845 "out",
846 TsExpr::New {
847 callee: Box::new(set_ctor.clone()),
848 args: vec![],
849 },
850 ),
851 TsStmt::for_stmt(
852 "i",
853 TsExpr::Lit(TsLit::Num("0".to_string())),
854 binary(
855 TsBinaryOp::LessThan,
856 ident("i"),
857 member(ident("json"), "length"),
858 ),
859 block(loop_body),
860 None,
861 ),
862 ret(call(ident("Ok"), vec![ident("out")])),
863 ],
864 is_async: false,
865 inline: false,
866 }));
867
868 decls.extend([serialise, deserialise]);
869 }
870 // v0.20b: `Map[K, V]` — entries-array wire format `[[k, v], …]`,
871 // uniform across String/Int keys and insertion-ordered
872 // (normative, §7).
873 GenericInst::MapInst { key, val } => {
874 let key_ts = inner_ts_name(key);
875 let val_ts = inner_ts_name(val);
876 let key_ty = qualified_ts_type(key, qual);
877 let val_ty = qualified_ts_type(val, qual);
878 let map_ty =
879 TsType::named_with_args("ReadonlyMap", vec![key_ty.clone(), val_ty.clone()]);
880 // `new Map<{key_ty}, {val_ty}>()`'s own callee has no real
881 // `TsExpr::New` generics field to hold `<key_ty, val_ty>`
882 // (see `TsStmtKind::For`'s own sibling doc for this file's
883 // one other real algebra gap this slice found) — printing a
884 // real `TsType::named_with_args("Map", ..)` node through the
885 // same `bynk_ts::print_type` boundary this arm already uses
886 // for `key_ty`/`val_ty` themselves builds the exact callee
887 // text with no `format!` needed, spliced as an opaque
888 // `Ident` the same way `ident(format!("deserialise_{type_name}"))`
889 // already reuses that variant as a raw-text callee slot
890 // elsewhere in this file (`emit_field_deserialise_wire`'s
891 // own `Named`/`Inst` arm).
892 let map_ctor = if is_plain_key_ref(key, types) {
893 "globalThis.Map"
894 } else {
895 ru.note_key("__BynkKeyMap");
896 "__BynkKeyMap"
897 };
898 let map_ctor = TsExpr::TypeApp {
899 callee: Box::new(ident(map_ctor)),
900 type_args: vec![key_ty.clone(), val_ty.clone()],
901 };
902
903 let serialise = TsDecl::Export(Box::new(TsDecl::Function {
904 name: format!("__serialise_Map_{key_ts}_{val_ts}"),
905 generics: Vec::new(),
906 params: serialise_params(map_ty.clone(), depth),
907 return_type: Some(TsType::named("__JsonValue")),
908 body: vec![
909 TsStmt::const_stmt(
910 TsBindingName::Ident("entries".to_string()),
911 Some(TsType::array(TsType::named("__JsonValue"))),
912 TsExpr::array(vec![]),
913 None,
914 ),
915 TsStmt::for_of(
916 "[k, v]",
917 ident("value"),
918 block(vec![TsStmt::expr_stmt(
919 call(
920 member(ident("entries"), "push"),
921 vec![TsExpr::array(vec![
922 serialise_field_expr(key, &ident("k"), depth, ru),
923 serialise_field_expr(val, &ident("v"), depth, ru),
924 ])],
925 ),
926 None,
927 )]),
928 None,
929 ),
930 ret(ident("entries")),
931 ],
932 is_async: false,
933 inline: false,
934 }));
935
936 let mut loop_body = vec![
937 const_("entry", index(ident("json"), ident("i"))),
938 if_(
939 or_expr(
940 not_expr(call(
941 member(ident("globalThis.Array"), "isArray"),
942 vec![ident("entry")],
943 )),
944 strict_neq(
945 member(ident("entry"), "length"),
946 TsExpr::Lit(TsLit::Num("2".to_string())),
947 ),
948 ),
949 block(vec![ret(err_structural_mismatch(
950 &path_elem(),
951 "[key, value] entry",
952 typeof_expr(ident("entry")),
953 ))]),
954 ),
955 const_(
956 "entryK",
957 index(ident("entry"), TsExpr::Lit(TsLit::Num("0".to_string()))),
958 ),
959 const_(
960 "entryV",
961 index(ident("entry"), TsExpr::Lit(TsLit::Num("1".to_string()))),
962 ),
963 ];
964 loop_body.extend(emit_field_deserialise(
965 "k",
966 key,
967 &ident("entryK"),
968 &path_entry(0),
969 depth,
970 ru,
971 ));
972 // #2707: a repeated key is refused, never last-entry-wins. `has`
973 // is value equality: a plain `Map` for a primitive key, the
974 // keyed class (canonical encoding, so `1.20` and `1.2` are one
975 // `Decimal` key) for a composite or `Decimal`/`Bytes` key.
976 loop_body.push(if_(
977 call(
978 member(ident("out"), "has"),
979 vec![as_expr(ident("__k"), key_ty.clone())],
980 ),
981 block(vec![ret(err_structural_mismatch(
982 &path_entry(0),
983 "a distinct map key",
984 str_lit("a duplicate"),
985 ))]),
986 ));
987 loop_body.extend(emit_field_deserialise(
988 "v",
989 val,
990 &ident("entryV"),
991 &path_entry(1),
992 depth,
993 ru,
994 ));
995 // Same brand assertion as the List codec (#527).
996 loop_body.push(TsStmt::expr_stmt(
997 call(
998 member(ident("out"), "set"),
999 vec![as_expr(ident("__k"), key_ty), as_expr(ident("__v"), val_ty)],
1000 ),
1001 None,
1002 ));
1003
1004 let deserialise = TsDecl::Export(Box::new(TsDecl::Function {
1005 name: format!("__deserialise_Map_{key_ts}_{val_ts}"),
1006 generics: Vec::new(),
1007 params: deserialise_params(depth),
1008 return_type: Some(TsType::named_with_args(
1009 "Result",
1010 vec![map_ty, TsType::named("__BoundaryError")],
1011 )),
1012 body: vec![
1013 array_shape_guard(),
1014 TsStmt::const_stmt(
1015 TsBindingName::Ident("out".to_string()),
1016 None,
1017 TsExpr::New {
1018 callee: Box::new(map_ctor.clone()),
1019 args: vec![],
1020 },
1021 None,
1022 ),
1023 TsStmt::for_stmt(
1024 "i",
1025 TsExpr::Lit(TsLit::Num("0".to_string())),
1026 binary(
1027 TsBinaryOp::LessThan,
1028 ident("i"),
1029 member(ident("json"), "length"),
1030 ),
1031 block(loop_body),
1032 None,
1033 ),
1034 ret(call(ident("Ok"), vec![ident("out")])),
1035 ],
1036 is_async: false,
1037 inline: false,
1038 }));
1039
1040 decls.extend([serialise, deserialise]);
1041 }
1042 }
1043 }
1044 decls
1045}
1046
1047/// #1887: the moved `bynk-tests` test `lenient_option_decode` pins the suffix a failed bare
1048/// `Option` value appends as a literal (1B.2b, #4028: it drives the driver's pipeline, so it
1049/// cannot read this private constant). This ties the two together.
1050#[cfg(test)]
1051mod option_forms_suffix_tests {
1052 #[test]
1053 fn option_forms_suffix_spelling() {
1054 assert_eq!(
1055 super::OPTION_FORMS_SUFFIX,
1056 " | null | {\"kind\": \"None\"} | {\"kind\": \"Some\", \"value\": ...}"
1057 );
1058 }
1059}
1060
1061/// 1A.38a: the codec sites that were `TsStmt::raw` text, pinned as the text they emit.
1062#[cfg(test)]
1063mod converted_site_tests {
1064 use super::*;
1065
1066 /// A wire-kind cascade nests each branch's guards at their true depth: inside the
1067 /// `if`, one level deeper than the `if` itself.
1068 #[test]
1069 fn the_wire_kind_cascade_nests_its_guards_at_their_true_depth() {
1070 let guard = |n: &str| {
1071 if_(
1072 strict_eq(ident(n), str_lit("x")),
1073 block(vec![ret(ident("fail"))]),
1074 )
1075 };
1076 let stmt = wire_kind_dispatch(
1077 "Ok",
1078 vec![guard("a")],
1079 ret(ident("ra")),
1080 "Err",
1081 vec![guard("b")],
1082 ret(ident("rb")),
1083 );
1084 assert_eq!(
1085 bynk_ts::print_stmt(&stmt, 1),
1086 " if (obj[\"kind\"] === \"Ok\") {\n if (a === \"x\") {\n return fail;\n }\n return ra;\n } else if (obj[\"kind\"] === \"Err\") {\n if (b === \"x\") {\n return fail;\n }\n return rb;\n }\n"
1087 );
1088 }
1089}