Skip to main content

bynk_check/checker/
codable.rs

1//! Which types are `Codable`, and the checks that need it. Constrained generics
2//! slice 3 (#2715; the model is the track's Q4/Q7 in
3//! `design/archive/retired-tracks.md`).
4//!
5//! `Codable` is automatic, never derived, and its meaning is one predicate: the
6//! domain `Json.decode` accepts , which `Json.encode`,
7//! `Json.decode` and a `Codable` bound all share so they cannot drift. A type is
8//! `Codable` when it is:
9//!
10//! - a base type (including `Float` and `Bytes`), or a refined or opaque type;
11//! - `Option`, `List`, `Set`, `Map` or `Result` of `Codable` types;
12//! - a record, sum or enum, or a generic instantiation whose arguments are
13//!   `Codable`;
14//! - a type parameter declared `T: Codable` (checked separately: see
15//!   `super::equality::require_codable_vars`).
16//!
17//! Not `Codable`: top-level `()` (it encodes but does not decode), functions,
18//! `Effect`, `Query`, `Stream` and anything that carries one, `Connection`, the
19//! HTTP and queue result types, `Asset`, request headers, token claims,
20//! statements, actors, a recursive generic record, and an unbounded type
21//! parameter. The declaration-position rule (`context_checks::reject_fn_types`)
22//! stays separate: its answer depends on the position.
23//!
24//! A `Codable` type parameter gets a hidden codec witness (`__codec_T`), ordered
25//! with the comparator witnesses by [`witness_list`].
26
27use std::collections::{HashMap, HashSet};
28use std::sync::Arc;
29
30use bynk_syntax::ast::{FnDecl, FnName, TypeDecl};
31use bynk_syntax::error::CompileError;
32use bynk_syntax::span::Span;
33
34use super::equality::{has_codable, has_ord, require_codable_vars};
35use super::ordering::{OrdSite, check_ord};
36use super::{Ctx, Ty, TyId, Types};
37
38/// The domain a `Json` codec covers. A type variable counts when it is in `vars`
39/// (the type parameters in scope); whether it declared `Codable` is
40/// `require_codable_vars`'s question.
41pub(crate) fn json_codable(
42    t: TyId,
43    types: &HashMap<String, Arc<TypeDecl>>,
44    tys: &Types,
45    vars: &HashSet<String>,
46) -> bool {
47    match &*tys.get(t) {
48        // R4.3: an already-diagnosed type doesn't also earn a
49        // `bynk.types.json_uncodable` diagnostic — the resolution failure was
50        // reported once, at its own site.
51        Ty::Error | Ty::Never => true,
52        // #2784: a `bynk.crypto` key is non-extractable and never sent, so it has no codec.
53        Ty::Named { name, .. } if crate::context_checks::is_crypto_key_type(name, types) => false,
54        // K-streams (#2623): a record or sum carrying a `Stream` has no codec.
55        Ty::Named { name, .. } if bynk_syntax::ast::type_carries_stream(name, types) => false,
56        // v0.174 (#592): a generic record instantiation is boundary-serialisable
57        // through its monomorphised codec exactly when its type arguments are.
58        Ty::Named { args, .. } if !args.is_empty() => {
59            args.iter().all(|a| json_codable(*a, types, tys, vars))
60        }
61        Ty::Base(_) | Ty::Named { .. } | Ty::Unit => true,
62        Ty::Result(a, b) => {
63            json_codable(*a, types, tys, vars) && json_codable(*b, types, tys, vars)
64        }
65        Ty::Option(a) | Ty::List(a) | Ty::Set(a) => json_codable(*a, types, tys, vars),
66        Ty::Map(k, v) => json_codable(*k, types, tys, vars) && json_codable(*v, types, tys, vars),
67        Ty::Var(name) => vars.contains(name),
68        Ty::Fn { .. }
69        | Ty::Effect(_)
70        | Ty::Query(_)
71        | Ty::Stream(_)
72        | Ty::TestConnection(_)
73        | Ty::Connection(_)
74        | Ty::HttpResult(_)
75        | Ty::HttpOutcome(_)
76        | Ty::QueueResult
77        | Ty::BoundaryRejection
78        | Ty::Asset
79        | Ty::RequestHeaders
80        | Ty::RequestQuery
81        | Ty::RequestCookies
82        | Ty::TokenClaims
83        | Ty::ValidationError
84        | Ty::DecodeError
85        | Ty::Actor(_)
86        | Ty::ActorSum(_) => false,
87    }
88}
89
90/// #2991: the first `Option` payload that can encode as `null` in `t`, as plain
91/// JSON would write it (`context_checks::null_payload_option`, the rule of a
92/// plain HTTP route), for a checked type. `t` must already be `Codable`: types
93/// with no codec are not walked.
94pub(crate) fn null_payload_option_ty(
95    t: TyId,
96    types: &HashMap<String, Arc<TypeDecl>>,
97    tys: &Types,
98) -> Option<String> {
99    let tref = codable_type_ref(t, tys)?;
100    crate::context_checks::null_payload_option(&tref, types, &mut HashSet::new())
101}
102
103/// A `Codable` checker type as the `TypeRef` the codec machinery reads. `None`
104/// for a type with no codec (it never reaches here: `json_codable` ran first).
105fn codable_type_ref(t: TyId, tys: &Types) -> Option<bynk_syntax::ast::TypeRef> {
106    use bynk_syntax::ast::{Ident, TypeRef};
107    let sp = Span::new(0, 0);
108    let b = |t: TyId| codable_type_ref(t, tys).map(Box::new);
109    Some(match &*tys.get(t) {
110        Ty::Base(base) => TypeRef::Base(*base, sp),
111        Ty::Named { name, args, .. } if !args.is_empty() => TypeRef::App {
112            name: Ident {
113                name: name.clone(),
114                span: sp,
115            },
116            args: args
117                .iter()
118                .map(|a| codable_type_ref(*a, tys))
119                .collect::<Option<Vec<_>>>()?,
120            span: sp,
121        },
122        Ty::Named { name, .. } => TypeRef::Named(Ident {
123            name: name.clone(),
124            span: sp,
125        }),
126        Ty::Result(a, e) => TypeRef::Result(b(*a)?, b(*e)?, sp),
127        Ty::Option(a) => TypeRef::Option(b(*a)?, sp),
128        Ty::List(a) => TypeRef::List(b(*a)?, sp),
129        Ty::Set(a) => TypeRef::Set(b(*a)?, sp),
130        Ty::Map(k, v) => TypeRef::Map(b(*k)?, b(*v)?, sp),
131        Ty::Unit => TypeRef::Unit(sp),
132        _ => return None,
133    })
134}
135
136/// The `bynk.crypto` key type (`SigningKey`/`VerifyKey`) `t` is or contains, if any.
137pub(crate) fn crypto_key_in(
138    t: TyId,
139    types: &HashMap<String, Arc<TypeDecl>>,
140    tys: &Types,
141) -> Option<String> {
142    match &*tys.get(t) {
143        Ty::Named { name, .. } if crate::context_checks::is_crypto_key_type(name, types) => {
144            Some(name.clone())
145        }
146        Ty::Named { args, .. } => args.iter().find_map(|a| crypto_key_in(*a, types, tys)),
147        Ty::Result(a, b) | Ty::Map(a, b) => {
148            crypto_key_in(*a, types, tys).or_else(|| crypto_key_in(*b, types, tys))
149        }
150        Ty::Option(a) | Ty::List(a) | Ty::Set(a) => crypto_key_in(*a, types, tys),
151        _ => None,
152    }
153}
154
155/// The note a `Codable`/`Json` rejection of `t` adds when a crypto key is the cause.
156pub(crate) fn key_note(
157    t: TyId,
158    types: &HashMap<String, Arc<TypeDecl>>,
159    tys: &Types,
160) -> Option<String> {
161    crypto_key_in(t, types, tys).map(|k| {
162        format!(
163            "a `{k}` is held non-extractable by the platform and never sent or persisted \
164             (`bynk.types.key_at_boundary`); keep the key bytes in `Secrets` and import the \
165             key again where it is used"
166        )
167    })
168}
169
170/// The variable-dependent half of a `Codable` requirement on `ty`: every type
171/// parameter in it is declared `Codable`. Reports and returns `false` otherwise.
172/// A user generic type over a type parameter is allowed: its codec is built
173/// from the declaration and the witnesses of its arguments (#2792).
174pub(crate) fn require_codable_rigid(ctx: &mut Ctx, ty: TyId, span: Span, clause: &str) -> bool {
175    require_codable_vars(ctx, ty, span, clause)
176}
177
178/// What a use of `Codable` is for, which decides the diagnostic's wording.
179pub(crate) enum CodableSite<'a> {
180    /// A call to a `Codable`-bounded callee: `callee` requires `param: Codable`.
181    Call { callee: &'a str, param: &'a str },
182    /// A call to a capability operation whose `param` is `Codable`.
183    Op { op: &'a str, param: &'a str },
184}
185
186/// Check that `ty` can be a `Codable` instantiation at `span`: it is in the
187/// codec domain, top-level `()` excepted, it names no recursive generic or
188/// statement, and every type parameter in it is declared `Codable`.
189pub(crate) fn check_codable(ctx: &mut Ctx, ty: TyId, span: Span, site: &CodableSite) -> bool {
190    let tys = ctx.tys;
191    let (what, param) = match site {
192        CodableSite::Call { callee, param } => (format!("`{callee}`"), *param),
193        CodableSite::Op { op, param } => (format!("capability operation `{op}`"), *param),
194    };
195    let clause = format!("{what} requires `{param}: Codable`");
196    if let Some(rec) = super::kernels::first_recursive_generic(ty, &ctx.input.types, tys) {
197        ctx.errors
198            .push(super::kernels::recursive_generic_error(&rec, span));
199        return false;
200    }
201    if let Some(statement) = super::d1::carried_statement(ty, &ctx.input.types, tys) {
202        ctx.errors.push(super::d1::statement_at_boundary(
203            span,
204            "a `Codable` type",
205            &statement,
206        ));
207        return false;
208    }
209    if !json_codable(ty, &ctx.input.types, tys, &ctx.type_vars) || ty == tys.intern(Ty::Unit) {
210        let shown = tys.display(ty);
211        let key_note = key_note(ty, &ctx.input.types, tys);
212        let mut err = CompileError::new(
213            "bynk.types.not_codable",
214            span,
215            format!("{clause}, but this call makes `{param}` `{shown}`, which is not `Codable`"),
216        )
217        .with_note(
218            "`Codable` types are the ones `Json.decode` accepts: base types, named types, \
219                 and the built-in containers over them — not `()`, functions, effects, streams \
220                 (or a type that carries one), `bynk.crypto` keys, or error builtins",
221        );
222        if let Some(n) = key_note {
223            err = err.with_note(n);
224        }
225        ctx.errors.push(err);
226        return false;
227    }
228    require_codable_rigid(ctx, ty, span, &clause)
229}
230
231/// Which hidden witness a type parameter takes.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum WitnessKind {
234    /// A comparator, for `T: Ord` (`__cmp_T`).
235    Cmp,
236    /// A codec, for `T: Codable` (`__codec_T`).
237    Codec,
238}
239
240/// One hidden trailing parameter of a bounded generic function.
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct WitnessParam {
243    /// The type parameter's name.
244    pub param: String,
245    pub kind: WitnessKind,
246}
247
248/// The hidden witness parameters of `f`, in order: the receiver type's
249/// parameters first, then the function's own, each in declaration order; within
250/// one parameter the comparator comes before the codec (the order of
251/// `CONSTRAINTS`). A bound is declared inline (`T: Ord`), in a `where` entry, or,
252/// for a receiver parameter, on the type. The emitter adds one trailing parameter
253/// per entry and every call site passes one argument per entry, so this order is
254/// the contract between them across units; it is not part of the published ABI.
255pub fn witness_list(f: &FnDecl, types: &HashMap<String, Arc<TypeDecl>>) -> Vec<WitnessParam> {
256    let where_has = |name: &str, has: fn(&[bynk_syntax::ast::Ident]) -> bool| {
257        f.where_bounds
258            .iter()
259            .any(|wb| wb.param.name == name && has(&wb.bounds))
260    };
261    let mut out = Vec::new();
262    let mut push = |name: &str, bounds: &[bynk_syntax::ast::Ident]| {
263        if has_ord(bounds) || where_has(name, has_ord) {
264            out.push(WitnessParam {
265                param: name.to_string(),
266                kind: WitnessKind::Cmp,
267            });
268        }
269        if has_codable(bounds) || where_has(name, has_codable) {
270            out.push(WitnessParam {
271                param: name.to_string(),
272                kind: WitnessKind::Codec,
273            });
274        }
275    };
276    if let FnName::Method { type_name, .. } = &f.name
277        && let Some(decl) = types.get(&type_name.name)
278    {
279        for tp in &decl.type_params {
280            push(&tp.name.name, &tp.bounds);
281        }
282    }
283    for tp in &f.type_params {
284        push(&tp.name.name, &tp.bounds);
285    }
286    out
287}
288
289/// At a call, check each witness-bearing type parameter of the callee (`params`,
290/// in witness order) against its instantiation (`subst`) and collect the
291/// instantiations: the call's witnesses. `None` after reporting the first
292/// violation.
293pub(crate) fn check_declared_witness_args(
294    callee: &str,
295    call_span: Span,
296    params: &[WitnessParam],
297    subst: &HashMap<String, TyId>,
298    ctx: &mut Ctx,
299) -> Option<Vec<TyId>> {
300    let mut out = Vec::new();
301    for w in params {
302        let &arg_ty = subst.get(&w.param)?;
303        let param = w.param.as_str();
304        let ok = match w.kind {
305            WitnessKind::Cmp => check_ord(ctx, arg_ty, call_span, &OrdSite::Call { callee, param }),
306            WitnessKind::Codec => {
307                check_codable(ctx, arg_ty, call_span, &CodableSite::Call { callee, param })
308            }
309        };
310        if !ok {
311            return None;
312        }
313        out.push(arg_ty);
314    }
315    Some(out)
316}
317
318// -- capability operations --
319
320/// Whether `t` mentions any of `names`, as a bare name or a generic argument.
321pub fn mentions_any(t: &bynk_syntax::ast::TypeRef, names: &[String]) -> bool {
322    if names.is_empty() {
323        return false;
324    }
325    let mut found = Vec::new();
326    crate::project_model::type_ref_names(t, &HashSet::new(), &mut found);
327    found.iter().any(|n| names.contains(n))
328}
329
330/// The type parameters of a capability operation declared `Codable`.
331pub fn codable_op_params(op: &bynk_syntax::ast::CapabilityOp) -> Vec<String> {
332    op.type_params
333        .iter()
334        .filter(|tp| has_codable(&tp.bounds))
335        .map(|tp| tp.name.name.clone())
336        .collect()
337}
338
339/// The internal annotation a first-party operation uses to declare what a reply
340/// that does not decode means (#3458): `@onUndecodable(miss)` or
341/// `@onUndecodable(fault)`. Not user-visible surface: the resolver refuses it
342/// outside the standard library.
343pub const REPLY_POLICY_ANNOTATION: &str = "onUndecodable";
344
345/// What a capability operation's reply that does not decode as its payload type
346/// means, declared per operation (#3458). The default is a fault.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum ReplyPolicy {
349    /// The call faults, naming the capability, operation, type and path.
350    Fault,
351    /// The call returns `None`, and a warning goes to the runtime console.
352    Miss,
353}
354
355/// The policy word an `@onUndecodable(...)` annotation carries, when it is a
356/// single bare `miss` or `fault`.
357pub fn reply_policy_word(ann: &bynk_syntax::ast::Annotation) -> Option<ReplyPolicy> {
358    let [arg] = ann.args.as_slice() else {
359        return None;
360    };
361    if arg.label.is_some() {
362        return None;
363    }
364    match &arg.value.kind {
365        bynk_syntax::ast::ExprKind::Ident(id) => match id.name.as_str() {
366            "miss" => Some(ReplyPolicy::Miss),
367            "fault" => Some(ReplyPolicy::Fault),
368            _ => None,
369        },
370        _ => None,
371    }
372}
373
374/// The failure policy an operation declares for an undecodable reply: its
375/// `@onUndecodable(..)` annotation, or a fault when it has none.
376pub fn op_reply_policy(op: &bynk_syntax::ast::CapabilityOp) -> ReplyPolicy {
377    op.annotations
378        .iter()
379        .find(|a| a.name.name == REPLY_POLICY_ANNOTATION)
380        .and_then(reply_policy_word)
381        .unwrap_or(ReplyPolicy::Fault)
382}
383
384/// The failure policy of a typed read, `None` for any other operation (#3458): one
385/// whose `Effect[P]` payload mentions a `Codable` type parameter of its own.
386/// Hover renders it, so the clause is read off the same rule the call site uses.
387pub fn typed_read_policy(op: &bynk_syntax::ast::CapabilityOp) -> Option<ReplyPolicy> {
388    let codable = codable_op_params(op);
389    match &op.return_type {
390        bynk_syntax::ast::TypeRef::Effect(payload, _) if mentions_any(payload, &codable) => {
391            Some(op_reply_policy(op))
392        }
393        _ => None,
394    }
395}
396
397/// How a call to a capability operation with `Codable` parameters is lowered:
398/// the provider receives plain JSON, never a witness (DECISION D).
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct CapEncoding {
401    /// Per argument: the instantiated parameter type to encode whole with its
402    /// codec, or `None` for an argument that passes through unchanged. An
403    /// argument is encoded when its declared type mentions a `Codable` type
404    /// parameter.
405    pub encode: Vec<Option<TyId>>,
406    /// Per type parameter: whether the emitted interface still mentions it. A
407    /// parameter that only occurs in encoded arguments is dropped from the
408    /// interface (those arguments are `unknown`), and so from a call's type
409    /// arguments.
410    pub keep_type_args: Vec<bool>,
411    /// Typed reads (#3458): set when the operation's `Effect[P]` payload `P`
412    /// mentions a `Codable` type parameter. The provider replies with plain
413    /// JSON and the call site decodes it as the instantiated `P`.
414    pub reply: Option<ReplyDecode>,
415}
416
417/// How a call site decodes the reply of a typed read (#3458).
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct ReplyDecode {
420    /// The instantiated payload `P` of the operation's `Effect[P]`, decoded whole.
421    pub payload: TyId,
422    /// What a reply that does not decode means, as the operation declares it.
423    pub policy: ReplyPolicy,
424}
425
426/// The encoding of a call to an operation, given its pattern parameter types
427/// (`params`), return type and the call's `subst`. `None` when the operation has
428/// no `Codable` parameter, so every other call lowers as it always did.
429pub(crate) fn op_encoding(
430    type_params: &[String],
431    codable: &[String],
432    params: &[TyId],
433    ret: TyId,
434    policy: ReplyPolicy,
435    subst: &HashMap<String, TyId>,
436    tys: &Types,
437) -> Option<Arc<CapEncoding>> {
438    if codable.is_empty() {
439        return None;
440    }
441    let mentions_codable = |t: TyId| {
442        let mut vars = HashSet::new();
443        super::equality::collect_vars(t, tys, &mut vars);
444        vars.iter().any(|v| codable.contains(v))
445    };
446    let encode: Vec<Option<TyId>> = params
447        .iter()
448        .map(|p| mentions_codable(*p).then(|| super::substitute(*p, subst, tys)))
449        .collect();
450    let mut kept = HashSet::new();
451    for (p, e) in params.iter().zip(&encode) {
452        if e.is_none() {
453            super::equality::collect_vars(*p, tys, &mut kept);
454        }
455    }
456    // A payload that mentions a `Codable` parameter is decoded whole from plain
457    // JSON, so the interface returns `unknown` there and the parameter does not
458    // survive in it.
459    let reply = match &*tys.get(ret) {
460        Ty::Effect(payload) if mentions_codable(*payload) => Some(ReplyDecode {
461            payload: super::substitute(*payload, subst, tys),
462            policy,
463        }),
464        _ => None,
465    };
466    if reply.is_none() {
467        super::equality::collect_vars(ret, tys, &mut kept);
468    }
469    Some(Arc::new(CapEncoding {
470        encode,
471        keep_type_args: type_params.iter().map(|tp| kept.contains(tp)).collect(),
472        reply,
473    }))
474}
475
476/// At a call to a capability operation, check each `Codable` type parameter
477/// against its instantiation. Reports and returns `false` on the first failure.
478pub(crate) fn check_op_codable_args(
479    op: &str,
480    span: Span,
481    codable: &[String],
482    subst: &HashMap<String, TyId>,
483    ctx: &mut Ctx,
484) -> bool {
485    for param in codable {
486        let Some(&ty) = subst.get(param) else {
487            continue;
488        };
489        if !check_codable(ctx, ty, span, &CodableSite::Op { op, param }) {
490            return false;
491        }
492    }
493    true
494}
495
496/// #3458: the payload of a typed read is decoded whole, so the instantiated `P`
497/// of `Effect[P]` must be `Codable` too (`Result[T, FetchError]` is not).
498pub(crate) fn check_reply_codable(
499    op: &str,
500    span: Span,
501    codable: &[String],
502    wire: &CapEncoding,
503    ctx: &mut Ctx,
504) -> bool {
505    let (Some(reply), Some(param)) = (&wire.reply, codable.first()) else {
506        return true;
507    };
508    check_codable(ctx, reply.payload, span, &CodableSite::Op { op, param })
509}