Skip to main content

bynk_emit/emitter/
serialisation.rs

1//! Per-type serialise / deserialise helper generation for workers mode
2//! (v0.8 §3.4 / §5.2).
3//!
4//! Every Bynk type that crosses a context boundary needs:
5//!   - `serialise_<Type>(value): JsonValue` — structural lowering.
6//!   - `deserialise_<Type>(json): Result<<Type>, BoundaryError>` —
7//!     structural validation + refinement re-validation, then a nominal
8//!     cast back to the receiving context's view.
9//!
10//! Helpers live in the *owning* module — commons modules emit helpers for
11//! commons types, context modules emit helpers for the types they declare.
12
13mod expr;
14mod factory;
15mod field;
16mod generics;
17mod record_sum;
18mod refined;
19mod support;
20
21use support::DepthCodecs;
22
23pub(crate) use expr::{
24    agent_wire_passes_through, deserialise_expr, deserialise_expr_via, peel_list_option,
25    serialise_expr, serialise_ref_via, witness_codec_expr,
26};
27pub use expr::{deserialise_ref_via, serialise_expr_via};
28pub(crate) use factory::{
29    codec_factory_ground_roots, codec_factory_ident, codec_factory_name, codec_factory_root,
30    emit_codec_factory,
31};
32pub(crate) use generics::emit_generic_helpers;
33pub use generics::emit_generic_helpers_qualified;
34
35use std::sync::Arc;
36
37use bynk_syntax::ast::{TypeBody, TypeDecl, TypeRef};
38
39use crate::emitter::RuntimeUse;
40use bynk_ts::{TsDecl, TsStmt};
41
42use record_sum::{emit_record, emit_sum};
43use refined::emit_refined;
44
45// -- Helpers over the shared builders (`crate::ts_build`) ----------------------
46
47/// #661: a *type qualifier* — maps a callee-owned type name to the type-only
48/// namespace prefix (`"commerce_payment."`) the caller must use to *name* it,
49/// while the caller generates that type's codec **locally** under a bare name.
50///
51/// A name absent from the map (or mapped to `""`) is named bare: the owner's
52/// own module, a base/generic type, or a commons type the caller already
53/// declares or imports locally. Only a consumed context's *own* boundary types
54/// (`AuthId`, `PaymentError`) are qualified — the caller has no local
55/// declaration to name, so the codec's type positions reach through the
56/// `import type * as <ns>` alias. Codec *function* names are never qualified:
57/// the caller's `deserialise_AuthId` calls its own local `deserialise_*`, which
58/// is the whole point of the increment.
59///
60/// #1846: a value with no trailing `.` is a whole qualified name instead
61/// (`"t_vault.Code"`), for a callee's unexported type the caller renamed;
62/// see [`qual_type`].
63type Qual = std::collections::HashMap<String, String>;
64
65/// #1437 (Arc E slice 2): [`crate::emitter::ts_types::ts_type_ref_qualified_multi_ts_type`]
66/// as a real `TsType`, over this file's own dotted-prefix [`Qual`] convention
67/// — a real, empirically-found convention mismatch, not assumed compatible
68/// from the two functions' identical `HashMap<String, String>` shapes alone.
69/// `Qual`'s own values already carry the trailing separator (`"shop_payment."`,
70/// this type's own doc), concatenated directly by [`qual_type`]; the
71/// existing renderer's own qualify closure (`emitter.rs`'s `ts_type_ref_to_ts_type`,
72/// `TypeRef::Named`'s arm) instead appends its OWN `.` (`format!("{ns}.{}",
73/// id.name)`), so passing `Qual` through unmodified doubles the separator
74/// (`shop_payment..PayError`) — caught by `coverage_behaviour.rs`'s real `tsc
75/// --strict` run (`TS1003: Identifier expected`), not by the byte-golden
76/// fixture corpus, which has no consumed-context boundary type reaching this
77/// exact generic-instantiation path. An absent/empty `Qual` entry (this
78/// type's own "named bare" case) maps to `None` here, not `Some("")` — the
79/// latter would render a stray leading `.` the same way a non-empty value's
80/// doubled separator does. `pub(crate)`, not private: `emitter/lower.rs`'s
81/// own `Json.decode[T]` test-scaffold arm is this file's one external
82/// caller, replacing its own direct call to the now-deleted
83/// `ts_type_ref_qualified`.
84pub(crate) fn qualified_ts_type(t: &TypeRef, qual: &Qual) -> bynk_ts::TsType {
85    // Review of #1438: the deleted `ts_inner_type` carried an explicit
86    // `unreachable!()` for these five variants (`bynk.types.
87    // function_at_boundary` rejects them before the serialisation machinery
88    // ever sees one); `ts_type_ref_qualified_multi_ts_type` has no such arm
89    // (it also serves non-boundary positions, where all five are legal), so
90    // folding into it silently turned a loud panic into a plausible-looking
91    // annotation next to a `serialise_*`/`deserialise_*` helper that cannot
92    // codec it. Unreachable today, made loud rather than silently relied on
93    // — the same precedent this crate's own unreachable-invariant
94    // `debug_assert!`s already set (e.g. the empty-args `TypeRef::App` one
95    // in `emitter.rs`).
96    debug_assert!(
97        !matches!(
98            t,
99            TypeRef::Fn(..)
100                | TypeRef::Query(..)
101                | TypeRef::Stream(..)
102                | TypeRef::Connection(..)
103                | TypeRef::History(..)
104        ),
105        "function/query/stream types are rejected at boundaries"
106    );
107    let bare: Qual = qual
108        .iter()
109        .filter(|(_, v)| v.ends_with('.'))
110        .filter_map(|(k, v)| {
111            let ns = v.trim_end_matches('.');
112            (!ns.is_empty()).then(|| (k.clone(), ns.to_string()))
113        })
114        .collect();
115    // #1846: a whole-name entry replaces the name outright (see [`qual_type`]).
116    let whole: std::collections::HashMap<String, String> = qual
117        .iter()
118        .filter(|(_, v)| !v.is_empty() && !v.ends_with('.'))
119        .map(|(k, v)| (k.clone(), v.clone()))
120        .collect();
121    if whole.is_empty() {
122        crate::emitter::ts_types::ts_type_ref_qualified_multi_ts_type(t, &bare)
123    } else {
124        crate::emitter::ts_types::ts_type_ref_qualified_multi_ts_type(
125            &rename_type_ref(t, &whole),
126            &bare,
127        )
128    }
129}
130
131/// The namespace prefix for a type name under `qual` (`""` when unqualified).
132/// The TS type a codec for `name` names. A [`Qual`] value is either a
133/// namespace prefix ending in `.` (`"t_vault."`, giving `t_vault.Code`) or,
134/// #1846, a whole qualified name with no trailing `.` (`"t_vault.Code"`): the
135/// form a callee's *unexported* type takes, renamed in the caller's copy of
136/// the callee's table (`t_vault__Code`) so its codecs can't collide with a
137/// caller type of the same name, while its TS type stays the callee's own.
138fn qual_type(qual: &Qual, name: &str) -> String {
139    match qual.get(name) {
140        Some(v) if v.ends_with('.') => format!("{v}{name}"),
141        Some(v) if !v.is_empty() => v.clone(),
142        _ => name.to_string(),
143    }
144}
145
146/// [`Provenance::Consumed`] for a name [`Qual`] qualifies, either form, owned
147/// by the namespace's unit; [`Provenance::Owned`] otherwise.
148fn qual_provenance(qual: &Qual, name: &str) -> Provenance {
149    match qual.get(name) {
150        Some(v) if !v.is_empty() => Provenance::Consumed {
151            owner_unit: v.split('.').next().unwrap_or_default().to_string(),
152        },
153        _ => Provenance::Owned,
154    }
155}
156
157// #855 (Phase 1): `collect_boundary_types`, `collect_type_names`,
158// `recursive_generic_names`, `subst_type_ref`, `record_inst_fields`,
159// `sum_inst_variants`, and `app_ts_name` moved to `bynk-check`'s wire IR
160// (`bynk_check::wire`) as pure, AST-only walks with no TS emission — see that
161// module's doc comment for the seam. Re-exported here under their original
162// names (and, for `app_ts_name`, its original signature under an alias to
163// its new `inst_codec_suffix` name) so every call site in this file and
164// elsewhere in `bynk-emit` keeps compiling unchanged; `recursive_generic_names`,
165// `collect_type_names`, and `subst_type_ref` had no callers outside the
166// functions that moved with them, so they are not re-exported.
167pub(crate) use bynk_check::wire::collect_boundary_types;
168pub(crate) use bynk_check::wire::inst_codec_suffix as app_ts_name;
169pub(crate) use bynk_check::wire::record_inst_fields;
170pub(crate) use bynk_check::wire::rename_type_ref;
171pub(crate) use bynk_check::wire::sum_inst_variants;
172
173// #855 (Phase 2 step 5): the scalar-codec decision vocabulary — which TS
174// branch `emit_refined` takes is now read off a `WireScalar`'s
175// `Revalidation` (built via `wire_type`) rather than re-derived inline from
176// `qual`/`decl.body`. `json_kind_of` replaces `ts_base_for_serialisation`'s
177// *classification*; this file keeps the TS-token spelling (`json_kind_ts`,
178// below) per the seam in `wire.rs`'s module doc.
179use bynk_check::wire::{Provenance, WireRef, recursive_codec_suffixes, wire_ref};
180
181/// #855 (Phase 2 step 6): resolve one `TypeRef` occurrence to its [`WireRef`]
182/// shape for `emit_field_deserialise` / `serialise_field_expr_via`. `wire_ref`
183/// documents its `types` parameter as unconsulted (single-level resolution,
184/// kept only for signature symmetry with the transitive walks) — an empty
185/// table costs nothing (`HashMap::new()` does not allocate) and avoids
186/// threading a real one through `emit_record_codec` / `emit_sum_codec` /
187/// `emit_generic_helpers_qualified`, which is out of scope for this step
188/// (records/sums/generic-helpers are steps 7/8/9).
189fn wire_ref_of(t: &TypeRef) -> WireRef {
190    wire_ref(t, &std::collections::HashMap::new())
191}
192
193/// Emit `serialise_<T>` and `deserialise_<T>` for every named type the
194/// owner declares that crosses a boundary. `owner_qualified` is the
195/// qualified name used as the brand path so that refinement-violation
196/// messages identify the origin context.
197pub(crate) fn emit_helpers_for_owner(
198    type_names: &[String],
199    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
200    owner_qualified: &str,
201    ru: &RuntimeUse,
202) -> Vec<TsDecl> {
203    emit_helpers_for_owner_qualified(type_names, types, owner_qualified, &Qual::new(), ru)
204}
205
206/// Collects `decls` into real statements — the shared shape every caller of
207/// `emit_helpers_for_owner`/`emit_generic_helpers` (and their
208/// `_qualified` twins) collects into its own returned `Vec<TsStmt>`. Arc F
209/// slice 1 (#1451): consolidates what used to be ten separate `write!`-family
210/// call sites into this one; #1478 made it the one real implementation
211/// (dropping a hand-duplicated `out: &mut String`-printing sibling); #1479
212/// removed that sibling's own last two production callers (`project/
213/// tests_emit.rs`'s codec-helper glue), so every caller in the crate is on
214/// this `Vec<TsStmt>` form directly now. #1486: no more explicit blank
215/// `TsStmt` after each declaration — none of these are import/comment-kind,
216/// so the printer's automatic top-level spacing policy already supplies
217/// exactly one blank between every adjacent pair (and after the last one,
218/// before whatever follows) once a real caller prints through it.
219pub fn decls_as_stmts(decls: Vec<TsDecl>) -> Vec<TsStmt> {
220    decls.into_iter().map(|d| TsStmt::decl(d, None)).collect()
221}
222
223/// As [`decls_as_stmts`], plus one *extra* forced trailing blank `TsStmt`
224/// when anything was collected — the shared `if emitted_any { ... }`
225/// trailer every `emit_helpers_for_owner`/[`emit_helpers_for_owner_
226/// qualified`] caller needs. Under the pre-#1486 flat-print regime this
227/// trailer's own blank stacked on top of `decls_as_stmts`'s own per-decl
228/// blank (one `TsStmt::blank` after every decl, including the last),
229/// giving this group's own tail *two* blank lines total — a genuine,
230/// stronger "owner group" section break (confirmed against
231/// `118_workers_target_with_consume`'s own real fixture output: the
232/// `local_boundary` helpers group and the following `by_commons`
233/// re-export group are separated by two blank lines, not one), not a
234/// redundant duplicate of the ordinary one-blank-between-decls spacing
235/// [`decls_as_stmts`] now gets for free from the printer's automatic
236/// policy. `no_blank_before` on the extra blank itself suppresses *its
237/// own* automatic lead-in (which would otherwise stack with the ordinary
238/// one the policy already supplies between the last real decl and this
239/// blank), leaving exactly one blank line from this statement's own
240/// render plus the policy's own ordinary blank before whatever follows —
241/// two lines total, matching the pre-#1486 text exactly.
242pub fn decls_as_stmts_block(decls: Vec<TsDecl>) -> Vec<TsStmt> {
243    let emitted_any = !decls.is_empty();
244    let mut stmts = decls_as_stmts(decls);
245    if emitted_any {
246        let mut extra_blank = TsStmt::blank(None);
247        extra_blank.no_blank_before = true;
248        stmts.push(extra_blank);
249    }
250    stmts
251}
252
253/// #661: as `emit_helpers_for_owner`, but the caller supplies a type
254/// `Qual`. With an empty qualifier this is the owner's own module (every
255/// type named bare, refined validation through `.of`). With a non-empty one it
256/// is a *consumer* generating its own view of another context's boundary
257/// types: the qualified names reach through the `import type * as <ns>` alias,
258/// and refined validation inlines (transparent) or casts structurally (opaque)
259/// because the owner's `.of` is not importable.
260pub fn emit_helpers_for_owner_qualified(
261    type_names: &[String],
262    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
263    _owner_qualified: &str,
264    qual: &Qual,
265    ru: &RuntimeUse,
266) -> Vec<TsDecl> {
267    // Only emit helpers for *named* types declared by this owner. Skip
268    // unknown names — they belong to another module or to the runtime's
269    // generic helpers (Result / Option).
270    let mut decls = Vec::new();
271    let codecs = recursive_codec_suffixes(types);
272    for name in type_names {
273        let Some(decl) = types.get(name) else {
274            continue;
275        };
276        // v0.174 (#592): a generic record has no single `serialise_<Name>` —
277        // each boundary instantiation gets its own monomorphised codec
278        // (`serialise_Paginated_User`) via `emit_generic_helpers`. Never emit a
279        // bare, un-parameterised helper for the declaration itself.
280        if !decl.type_params.is_empty() {
281            continue;
282        }
283        // K-streams (#2623): a type carrying a `Stream` has no codec. The
284        // checker keeps it off every boundary, so nothing calls one.
285        if bynk_syntax::ast::type_carries_stream(name, types) {
286            continue;
287        }
288        decls.extend(emit_one(name, decl, types, qual, &codecs, ru));
289    }
290    decls
291}
292
293/// Arc F slice 1 (#1451): returns the real `bynk_ts::TsDecl` nodes for
294/// `name` directly — no `out: &mut String` parameter. The boundary-collect
295/// step ([`decls_as_stmts`]) now happens once, at the caller.
296fn emit_one(
297    name: &str,
298    decl: &TypeDecl,
299    types: &std::collections::HashMap<String, Arc<TypeDecl>>,
300    qual: &Qual,
301    codecs: &DepthCodecs,
302    ru: &RuntimeUse,
303) -> Vec<TsDecl> {
304    match &decl.body {
305        // #1441 (Arc E slice 4): `emit_refined` itself now builds real
306        // `bynk_ts::TsDecl` nodes.
307        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {
308            emit_refined(name, decl, types, qual, ru)
309        }
310        // #1443 (Arc E slice 5): `emit_record` itself now builds real
311        // `bynk_ts::TsDecl` nodes.
312        TypeBody::Record(_) => emit_record(name, decl, types, qual, codecs, ru),
313        // #1445 (Arc E slice 6): `emit_sum` itself now builds real
314        // `bynk_ts::TsDecl` nodes.
315        TypeBody::Sum(_) => emit_sum(name, decl, types, qual, codecs, ru),
316    }
317}
318
319// #855 (Phase 1): `inner_ts_name` moved to `bynk_check::wire` as
320// `codec_suffix`; `collect_codec_closure` moved verbatim (pure, AST-only —
321// see that module's doc for the seam). Re-exported under their original
322// names so call sites here and elsewhere in `bynk-emit` keep compiling
323// unchanged.
324pub(crate) use bynk_check::wire::codec_suffix as inner_ts_name;
325pub use bynk_check::wire::collect_codec_closure;
326
327// #855 (Phase 1): `collect_generic_instantiations` and `GenericInst` (now
328// `WireInst` — see that type's doc for why its variant names are kept as
329// `ResultInst`/`OptionInst`/… rather than the plan's bare spelling, deferred
330// to Phase 2) moved to `bynk_check::wire`; `walk_generic_inst` moved with
331// them (no callers outside the functions that moved). Re-exported under
332// their original names so call sites here and elsewhere in `bynk-emit` keep
333// compiling unchanged.
334pub(crate) use bynk_check::wire::WireInst as GenericInst;
335pub(crate) use bynk_check::wire::collect_generic_instantiations;
336
337/// #3066: whether a codec root names one of `names` (a suite's own types)
338/// anywhere, through generic arguments. Such a root is served by the suite
339/// runner's own local codecs ([`super::emit::emit_suite_decls`]), not the
340/// module-level closure, which cannot name a type declared inside a runner.
341pub fn root_names_any(root: &TypeRef, names: &std::collections::HashSet<String>) -> bool {
342    !names.is_empty()
343        && super::workers::named_types_in(root)
344            .iter()
345            .any(|n| names.contains(n))
346}
347
348#[cfg(test)]
349mod qualified_ts_type_tests {
350    use super::*;
351    use bynk_syntax::ast::Ident;
352    use bynk_syntax::span::Span;
353
354    fn named(name: &str) -> TypeRef {
355        TypeRef::Named(Ident {
356            name: name.to_string(),
357            span: Span::new(0, 0),
358        })
359    }
360
361    /// Review of #1438, finding 2: the exact regression this slice
362    /// introduced and fixed (`shop_payment..PayError`, a doubled
363    /// separator) — pinned directly, not left to depend on a real `tsc`
364    /// run in `bynk-tests/tests/coverage_behaviour.rs`.
365    #[test]
366    fn dotted_qual_entry_renders_a_single_separator() {
367        let qual: Qual = [("PayError".to_string(), "shop_payment.".to_string())]
368            .into_iter()
369            .collect();
370        assert_eq!(
371            bynk_ts::print_type(&qualified_ts_type(&named("PayError"), &qual)),
372            "shop_payment.PayError"
373        );
374    }
375
376    #[test]
377    fn absent_qual_entry_renders_bare() {
378        let qual: Qual = Qual::new();
379        assert_eq!(
380            bynk_ts::print_type(&qualified_ts_type(&named("PayError"), &qual)),
381            "PayError"
382        );
383    }
384
385    /// An empty-string entry is `Qual`'s own "named bare" convention (this
386    /// type's own doc) — must map to `None`, not `Some("")`, or it renders
387    /// a stray leading `.`.
388    #[test]
389    fn empty_qual_entry_renders_bare_not_a_stray_dot() {
390        let qual: Qual = [("PayError".to_string(), String::new())]
391            .into_iter()
392            .collect();
393        assert_eq!(
394            bynk_ts::print_type(&qualified_ts_type(&named("PayError"), &qual)),
395            "PayError"
396        );
397    }
398}