1use 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
38pub(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 Ty::Error | Ty::Never => true,
52 Ty::Named { name, .. } if crate::context_checks::is_crypto_key_type(name, types) => false,
54 Ty::Named { name, .. } if bynk_syntax::ast::type_carries_stream(name, types) => false,
56 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
90pub(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
103fn 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
136pub(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
155pub(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
170pub(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
178pub(crate) enum CodableSite<'a> {
180 Call { callee: &'a str, param: &'a str },
182 Op { op: &'a str, param: &'a str },
184}
185
186pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum WitnessKind {
234 Cmp,
236 Codec,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct WitnessParam {
243 pub param: String,
245 pub kind: WitnessKind,
246}
247
248pub 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
289pub(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
318pub 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
330pub 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
339pub const REPLY_POLICY_ANNOTATION: &str = "onUndecodable";
344
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum ReplyPolicy {
349 Fault,
351 Miss,
353}
354
355pub 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
374pub 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
384pub 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#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct CapEncoding {
401 pub encode: Vec<Option<TyId>>,
406 pub keep_type_args: Vec<bool>,
411 pub reply: Option<ReplyDecode>,
415}
416
417#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct ReplyDecode {
420 pub payload: TyId,
422 pub policy: ReplyPolicy,
424}
425
426pub(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 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
476pub(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
496pub(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}