Skip to main content

bynk_emit/emitter/emit/
suite.rs

1//! Suite declarations: the local `fn`s, `type`s, `const`s and late codecs a test suite declares, which
2//! `testgen` calls (`emit_suite_fn`, `emit_suite_decls`).
3
4use super::{emit_const_in, emit_free_fn_in, emit_type_in};
5use crate::emitter::ctx::ModuleCtx;
6use crate::emitter::{RuntimeUse, UnitFacts};
7use bynk_check::checker::{TyId, TypedCommons};
8use bynk_syntax::ast::{ConstDecl, FnDecl, TypeDecl, TypeRef};
9
10/// #2834: a suite-local helper `fn` — `emit_free_fn` without the `export`,
11/// since it is declared inside a test runner and called from its body.
12pub fn emit_suite_fn(
13    f: &FnDecl,
14    commons: &TypedCommons,
15    runtime_use: &RuntimeUse,
16) -> Vec<bynk_ts::TsStmt> {
17    // A suite is only ever built for `bynk test`, which guards every contract.
18    // A suite helper cannot declare `given`, so it has no capability types to name.
19    let empty = bynk_check::resolver::CrossContextInfo::default();
20    emit_free_fn_in(
21        f,
22        commons,
23        true,
24        runtime_use,
25        &empty,
26        false,
27        true,
28        UnitFacts::detached(),
29    )
30}
31
32/// #3066: a suite's own `type` and `const` declarations, as TypeScript for the
33/// body of one test runner: the types (an interface and its companion object, or
34/// a union), their JSON codecs (so `select[T]`, `Json.encode`/`decode` and the
35/// boundary paths find `__serialise_T` / `__deserialise_T` in scope), and the
36/// constants (cached-function declarations, like a unit's). They are declared
37/// local to the runner, so another suite declaring the same name cannot collide
38/// and nothing here reaches the deployable. `typed` is the suite's view with the
39/// suite's types and constants already merged in; `qual` qualifies a target
40/// type a suite type's codec mentions, as the module-level codecs do.
41///
42/// Returns the statements with the `export` modifiers dropped (a function-local declaration
43/// cannot carry one). The driver prints them, at its own test-harness boundary.
44pub fn emit_suite_decls(
45    types: &[TypeDecl],
46    consts: &[ConstDecl],
47    typed: &TypedCommons,
48    qual: &std::collections::HashMap<String, String>,
49    runtime_use: &RuntimeUse,
50) -> Vec<bynk_ts::TsStmt> {
51    let mut stmts: Vec<bynk_ts::TsStmt> = Vec::new();
52    for t in types {
53        let Some(def) = typed.types.get(&t.name.name) else {
54            continue;
55        };
56        let shape = bynk_model::lower_suite_type_shape_ir(def, typed);
57        stmts.extend(emit_type_in(
58            t,
59            &shape,
60            typed,
61            "",
62            runtime_use,
63            UnitFacts::detached(),
64        ));
65    }
66    if !types.is_empty() {
67        // The type itself plus the wrappers a test reads one through: a
68        // `select[T]` is a `List[T]`, a `firstAs[T]` an `Option[T]`.
69        let roots = suite_base_codec_roots(types);
70        let (names, insts) = super::serialisation::collect_codec_closure(&roots, &typed.types);
71        stmts.extend(super::serialisation::decls_as_stmts_block(
72            super::serialisation::emit_helpers_for_owner_qualified(
73                &names,
74                &typed.types,
75                "",
76                qual,
77                runtime_use,
78            ),
79        ));
80        stmts.extend(super::serialisation::decls_as_stmts(
81            super::serialisation::emit_generic_helpers_qualified(
82                &insts,
83                &typed.types,
84                qual,
85                runtime_use,
86            ),
87        ));
88    }
89    let empty = bynk_check::resolver::CrossContextInfo::default();
90    for c in consts {
91        stmts.extend(emit_const_in(
92            c,
93            ModuleCtx::new(typed, &empty, runtime_use, UnitFacts::detached()),
94        ));
95    }
96    stmts
97        .into_iter()
98        .map(bynk_ts::TsStmt::without_export)
99        .collect()
100}
101
102/// The roots a suite's local codecs always cover: each non-generic type plus the
103/// `List`/`Option` wrappers a test reads one through (a `select[T]` is a
104/// `List[T]`, a `firstAs[T]` an `Option[T]`).
105fn suite_base_codec_roots(types: &[TypeDecl]) -> Vec<TypeRef> {
106    let mut roots: Vec<TypeRef> = Vec::new();
107    for t in types.iter().filter(|t| t.type_params.is_empty()) {
108        let named = TypeRef::Named(t.name.clone());
109        let span = t.name.span;
110        roots.push(TypeRef::List(Box::new(named.clone()), span));
111        roots.push(TypeRef::Option(Box::new(named.clone()), span));
112        roots.push(named);
113    }
114    roots
115}
116
117/// #3111: the codecs a runner's body reached for beyond the always-present
118/// ones ([`emit_suite_decls`]): a suite type under another generic (`Result`,
119/// a user generic, nested containers) at a `Json` boundary. `reached` is what
120/// the runner's lowering noted; only roots that name a suite type are served
121/// here (the module-level closure serves the rest). Returns the function
122/// declarations, with `export` dropped, to be spliced ahead of the body; empty
123/// when the body reached nothing new.
124pub fn emit_suite_late_codecs(
125    types: &[TypeDecl],
126    typed: &TypedCommons,
127    qual: &std::collections::HashMap<String, String>,
128    runtime_use: &RuntimeUse,
129    reached: &[TyId],
130) -> Vec<bynk_ts::TsStmt> {
131    if types.is_empty() || reached.is_empty() {
132        return Vec::new();
133    }
134    let names: std::collections::HashSet<String> =
135        types.iter().map(|t| t.name.name.clone()).collect();
136    let extra: Vec<TypeRef> = reached
137        .iter()
138        .filter_map(|t| super::ty_to_type_ref(*t, typed.tys()))
139        .filter(|r| super::serialisation::root_names_any(r, &names))
140        .collect();
141    if extra.is_empty() {
142        return Vec::new();
143    }
144    let (base_names, base_insts) =
145        super::serialisation::collect_codec_closure(&suite_base_codec_roots(types), &typed.types);
146    let (all_names, all_insts) = super::serialisation::collect_codec_closure(&extra, &typed.types);
147    let new_names: Vec<String> = all_names
148        .into_iter()
149        .filter(|n| !base_names.contains(n))
150        .collect();
151    let base_inst_names: std::collections::HashSet<String> =
152        base_insts.iter().map(|i| i.ts_name()).collect();
153    let new_insts: Vec<_> = all_insts
154        .into_iter()
155        .filter(|i| !base_inst_names.contains(&i.ts_name()))
156        .collect();
157    let mut stmts: Vec<bynk_ts::TsStmt> = Vec::new();
158    stmts.extend(super::serialisation::decls_as_stmts_block(
159        super::serialisation::emit_helpers_for_owner_qualified(
160            &new_names,
161            &typed.types,
162            "",
163            qual,
164            runtime_use,
165        ),
166    ));
167    stmts.extend(super::serialisation::decls_as_stmts(
168        super::serialisation::emit_generic_helpers_qualified(
169            &new_insts,
170            &typed.types,
171            qual,
172            runtime_use,
173        ),
174    ));
175    stmts
176        .into_iter()
177        .map(bynk_ts::TsStmt::without_export)
178        .collect()
179}