1use super::codable::{check_op_codable_args, check_reply_codable, op_encoding};
7use super::*;
8
9fn record_param_hint(hints: &mut HintSink, param_name: &str, arg: &Expr) {
14 if param_name == "_" || param_name == "self" {
15 return;
16 }
17 if let ExprKind::Ident(id) = &arg.kind
18 && id.name == param_name
19 {
20 return;
21 }
22 hints.record_param(arg.span, format!("{param_name}:"));
23}
24
25#[allow(clippy::too_many_arguments)]
26pub(crate) fn check_fn(
27 f: &FnDecl,
28 input: &ResolvedCommons,
29 expr_types: &mut HashMap<ExprId, TypedExpr>,
30 callees: &mut HashMap<ExprId, Callee>,
31 errors: &mut Vec<CompileError>,
32 refs: &mut RefSink,
33 hints: &mut HintSink,
34 locals: &mut LocalsSink,
35 requirements: &mut RequirementSink,
36 tys: &Types,
37) {
38 check_fn_in(
39 f,
40 false,
41 None,
42 input,
43 expr_types,
44 callees,
45 errors,
46 refs,
47 hints,
48 locals,
49 requirements,
50 tys,
51 );
52}
53
54pub struct FnCaps {
56 pub capabilities: HashMap<String, CapabilityInfo>,
58 pub declared_capabilities: HashMap<String, CapabilityInfo>,
61}
62
63#[allow(clippy::too_many_arguments)]
66pub fn check_context_fn(
67 f: &FnDecl,
68 caps: FnCaps,
69 input: &ResolvedCommons,
70 expr_types: &mut HashMap<ExprId, TypedExpr>,
71 callees: &mut HashMap<ExprId, Callee>,
72 errors: &mut Vec<CompileError>,
73 refs: &mut RefSink,
74 hints: &mut HintSink,
75 locals: &mut LocalsSink,
76 requirements: &mut RequirementSink,
77 tys: &Types,
78) {
79 check_fn_in(
80 f,
81 false,
82 Some(caps),
83 input,
84 expr_types,
85 callees,
86 errors,
87 refs,
88 hints,
89 locals,
90 requirements,
91 tys,
92 );
93}
94
95#[allow(clippy::too_many_arguments)]
98pub fn check_suite_fn(
99 f: &FnDecl,
100 input: &ResolvedCommons,
101 expr_types: &mut HashMap<ExprId, TypedExpr>,
102 callees: &mut HashMap<ExprId, Callee>,
103 errors: &mut Vec<CompileError>,
104 refs: &mut RefSink,
105 hints: &mut HintSink,
106 locals: &mut LocalsSink,
107 requirements: &mut RequirementSink,
108 tys: &Types,
109) {
110 if !f.given.is_empty() {
113 errors.extend(given_fn_refusal(f, false));
114 return;
115 }
116 check_fn_in(
117 f,
118 true,
119 None,
120 input,
121 expr_types,
122 callees,
123 errors,
124 refs,
125 hints,
126 locals,
127 requirements,
128 tys,
129 );
130}
131
132#[allow(clippy::too_many_arguments)]
135pub(crate) fn check_fn_in(
136 f: &FnDecl,
137 test_values: bool,
138 fn_caps: Option<FnCaps>,
141 input: &ResolvedCommons,
142 expr_types: &mut HashMap<ExprId, TypedExpr>,
143 callees: &mut HashMap<ExprId, Callee>,
144 errors: &mut Vec<CompileError>,
145 refs: &mut RefSink,
146 hints: &mut HintSink,
147 locals: &mut LocalsSink,
148 requirements: &mut RequirementSink,
149 tys: &Types,
150) {
151 let mut vars: HashSet<String> = f
155 .type_params
156 .iter()
157 .map(|tp| tp.name.name.clone())
158 .collect();
159 for tp in &f.type_params {
160 if input.types.contains_key(&tp.name.name) {
161 errors.push(
162 CompileError::new(
163 "bynk.generics.type_arg_mismatch",
164 tp.span,
165 format!(
166 "type parameter `{}` shadows the declared type of the same name",
167 tp.name.name
168 ),
169 )
170 .with_note("rename the type parameter"),
171 );
172 }
173 }
174 if let FnName::Method { type_name, .. } = &f.name
180 && let Some(decl) = input.types.get(&type_name.name)
181 {
182 for tp in &decl.type_params {
183 vars.insert(tp.name.name.clone());
184 }
185 }
186 let return_ty = match resolve_type_ref_in(&f.return_type, &input.types, &vars, tys) {
187 Some(t) => t,
188 None => return,
189 };
190 record_type_refs(&f.return_type, &input.types, &vars, refs);
191 let mut param_scope: HashMap<String, TyId> = HashMap::new();
192 if let FnName::Method { type_name, .. } = &f.name
197 && f.has_self
198 && let Some(decl) = input.types.get(&type_name.name)
199 {
200 let self_args = decl
201 .type_params
202 .iter()
203 .map(|tp| tys.intern(Ty::Var(tp.name.name.clone())))
204 .collect();
205 param_scope.insert("self".to_string(), named_ty_with_args(decl, self_args, tys));
206 }
207 for p in &f.params {
208 if let Some(ty) = resolve_type_ref_in(&p.type_ref, &input.types, &vars, tys) {
209 record_type_refs(&p.type_ref, &input.types, &vars, refs);
210 if p.name.name != "_" {
212 locals.record(
213 p.name.name.clone(),
214 p.name.span,
215 crate::locals::LocalKind::Param,
216 ty.display(tys),
217 f.body.span,
218 );
219 }
220 param_scope.insert(p.name.name.clone(), ty);
221 }
222 }
223 let eq = EqScope::for_fn(f, input);
224 if !vars.is_empty() {
227 super::keying::require_key_positions(
228 tys,
229 &vars,
230 &eq,
231 errors,
232 return_ty,
233 f.return_type.span(),
234 );
235 for p in &f.params {
236 if let Some(ty) = param_scope.get(&p.name.name).copied() {
237 super::keying::require_key_positions(
238 tys,
239 &vars,
240 &eq,
241 errors,
242 ty,
243 p.type_ref.span(),
244 );
245 }
246 }
247 }
248 if !f.requires.is_empty() || !f.ensures.is_empty() {
253 let result_ty = match &*tys.get(return_ty) {
254 Ty::Effect(inner) => *inner,
255 _ => return_ty,
256 };
257 let has_result_param = f.params.iter().any(|p| p.name.name == "result");
258 let fn_label = format!("function `{}`", f.name.display());
259 check_contracts(
260 &f.requires,
261 &f.ensures,
262 ¶m_scope,
263 result_ty,
264 has_result_param,
265 &fn_label,
266 input,
267 expr_types,
268 errors,
269 refs,
270 hints,
271 locals,
272 requirements,
273 callees,
274 &vars,
275 &eq,
276 tys,
277 );
278 }
279 let effectful = return_ty.is_effect(tys);
280 let mut ctx = Ctx {
281 input,
282 tys,
283 expr_types,
284 errors,
285 refs,
286 hints,
287 locals,
288 requirements,
289 callees,
290 scopes: vec![param_scope],
291 list_lens: HashMap::new(),
292 row_links: HashMap::new(),
293 is_binding_cache: HashMap::new(),
294 admitted_literals: HashMap::new(),
295 pattern_binding_types: HashMap::new(),
296 let_else_removals: HashMap::new(),
297 store_writing_lambdas: HashMap::new(),
298 question_let_binders: HashMap::new(),
299 return_ty,
300 return_ty_span: f.return_type.span(),
301 effectful,
302 agent_state_ty: None,
303 commit_seen: false,
304 caps: match fn_caps {
305 Some(c) => {
306 let given_entries: Vec<(String, Span)> = f
307 .given
308 .iter()
309 .map(|g| (g.key().to_string(), g.span))
310 .collect();
311 CapabilityCtx {
312 capabilities: c.capabilities,
313 declared_capabilities: c.declared_capabilities,
314 given_remaining: given_entries.iter().map(|(k, _)| k.clone()).collect(),
315 given_used: HashSet::new(),
316 given_entries,
317 given_anchor: Some(f.return_type.span()),
318 ..Default::default()
319 }
320 }
321 None => CapabilityCtx {
324 given_anchor: (input.is_context
325 && !test_values
326 && matches!(f.name, FnName::Free(_))
327 && effectful)
328 .then(|| f.return_type.span()),
329 ..CapabilityCtx::default()
330 },
331 },
332 in_test_body: false,
333 oidc_binder: None,
334 test_services: HashMap::new(),
335 test_actors: HashMap::new(),
336 type_vars: vars.clone(),
337 eq: eq.clone(),
338 last_witness: None,
339 store_fields: HashMap::new(),
340 in_agent_handler: false,
341 in_service_handler: false,
342 in_fn_body: true,
343 test_values,
344 };
345 let Some(body_ty) = type_of_block(&f.body, Some(return_ty), &mut ctx) else {
346 return;
347 };
348 linearity::check(
356 &f.body,
357 &f.params,
358 &input.types,
359 ctx.expr_types,
360 &ctx.pattern_binding_types,
361 &HashSet::new(),
362 ctx.errors,
363 tys,
364 );
365 if !compatible(body_ty, return_ty, tys) {
366 let err = CompileError::new(
367 "bynk.types.return_mismatch",
368 f.body.tail.span,
369 format!(
370 "function body has type `{}`, but the declared return type is `{}`",
371 body_ty.display(tys),
372 return_ty.display(tys)
373 ),
374 )
375 .with_label(f.return_type.span(), "declared return type");
376 ctx.errors.push(with_of_hint(err, body_ty, return_ty, &ctx));
377 }
378 if !f.given.is_empty() {
379 let entries = ctx.caps.given_entries.clone();
380 report_unused_given(
381 &mut ctx,
382 &entries,
383 f.return_type.span(),
384 f.return_type.span(),
385 );
386 }
387}
388
389#[allow(clippy::too_many_arguments)]
408fn check_static_initialiser(
409 init: &Expr,
410 field_type: &TypeRef,
411 input: &ResolvedCommons,
412 expr_types: &mut HashMap<ExprId, TypedExpr>,
413 callees: &mut HashMap<ExprId, Callee>,
414 errors: &mut Vec<CompileError>,
415 refs: &mut RefSink,
416 hints: &mut HintSink,
417 locals: &mut LocalsSink,
418 code: &'static str,
419 subject: &str,
420 tys: &Types,
421) {
422 let Some((field_ty, result, local_errors)) = type_static_initialiser(
423 init, field_type, input, expr_types, callees, refs, hints, locals, tys,
424 ) else {
425 return; };
427 let compatible_result = matches!(&result, Some(t) if compatible(*t, field_ty, tys));
428 if !compatible_result || !local_errors.is_empty() {
429 if local_errors
433 .iter()
434 .any(|e| e.category == "bynk.context.rebrand_construction")
435 {
436 errors.extend(
437 local_errors
438 .into_iter()
439 .filter(|e| e.category == "bynk.context.rebrand_construction"),
440 );
441 return;
442 }
443 let got = result
444 .map(|t| t.display(tys))
445 .unwrap_or_else(|| "an invalid expression".to_string());
446 errors.push(
447 CompileError::new(
448 code,
449 init.span,
450 format!(
451 "{subject} must be a static value of type `{}` (got `{got}`)",
452 field_ty.display(tys),
453 ),
454 )
455 .with_note(
456 "an initialiser is a compile-time value — a literal (including one admitted to a \
457 refined type), a sum variant of a type this context may construct, \
458 `Some`/`None`/`Ok`/`Err`, a record, or — for an opaque type — `T.unsafe(lit)` — \
459 with no reference to `self`, parameters, or capabilities",
460 ),
461 );
462 }
463}
464
465#[allow(clippy::too_many_arguments)]
471fn type_static_initialiser(
472 init: &Expr,
473 field_type: &TypeRef,
474 input: &ResolvedCommons,
475 expr_types: &mut HashMap<ExprId, TypedExpr>,
476 callees: &mut HashMap<ExprId, Callee>,
477 refs: &mut RefSink,
478 hints: &mut HintSink,
479 locals: &mut LocalsSink,
480 tys: &Types,
481) -> Option<(TyId, Option<TyId>, Vec<CompileError>)> {
482 let field_ty = resolve_type_ref(field_type, &input.types, tys)?;
483 let mut local_errors: Vec<CompileError> = Vec::new();
484 let mut init_requirements = RequirementSink::new();
487 let result = {
488 let mut ctx = Ctx {
489 input,
490 tys,
491 expr_types,
492 errors: &mut local_errors,
493 refs,
494 hints,
495 locals,
496 requirements: &mut init_requirements,
497 callees,
498 scopes: vec![HashMap::new()],
499 list_lens: HashMap::new(),
500 row_links: HashMap::new(),
501 is_binding_cache: HashMap::new(),
502 admitted_literals: HashMap::new(),
503 pattern_binding_types: HashMap::new(),
504 let_else_removals: HashMap::new(),
505 store_writing_lambdas: HashMap::new(),
506 question_let_binders: HashMap::new(),
507 return_ty: field_ty,
508 return_ty_span: init.span,
509 effectful: false,
510 agent_state_ty: None,
511 commit_seen: false,
512 caps: CapabilityCtx::default(),
513 in_test_body: false,
514 oidc_binder: None,
515 test_services: HashMap::new(),
516 test_actors: HashMap::new(),
517 type_vars: HashSet::new(),
518 eq: EqScope::default(),
519 last_witness: None,
520 store_fields: HashMap::new(),
521 in_agent_handler: false,
522 in_service_handler: false,
523 in_fn_body: false,
524 test_values: false,
525 };
526 type_of(init, Some(field_ty), &mut ctx)
527 };
528 Some((field_ty, result, local_errors))
529}
530
531#[allow(clippy::too_many_arguments)]
542pub fn check_const_decl(
543 c: &ConstDecl,
544 input: &ResolvedCommons,
545 tys: &Types,
546 expr_types: &mut HashMap<ExprId, TypedExpr>,
547 callees: &mut HashMap<ExprId, Callee>,
548 errors: &mut Vec<CompileError>,
549 refs: &mut RefSink,
550 hints: &mut HintSink,
551 locals: &mut LocalsSink,
552) {
553 errors.extend(crate::consts::name_case_error(c));
554 errors.extend(crate::consts::variant_conflict_error(
555 c,
556 &input.types,
557 &input.unselected_types,
558 ));
559 if let Some(err) = crate::consts::static_error(c, &input.consts, &input.types) {
560 errors.push(err);
561 return;
562 }
563 let Some((field_ty, result, local_errors)) = type_static_initialiser(
564 &c.init, &c.ty, input, expr_types, callees, refs, hints, locals, tys,
565 ) else {
566 return; };
568 if !local_errors.is_empty() {
569 errors.extend(local_errors);
570 return;
571 }
572 let Some(got) = result else { return };
573 if !compatible(got, field_ty, tys) {
574 errors.push(
575 CompileError::new(
576 "bynk.resolve.bad_const_initialiser",
577 c.init.span,
578 format!(
579 "constant `{}` is declared `{}`, but its initialiser is a `{}`",
580 c.name.name,
581 field_ty.display(tys),
582 got.display(tys),
583 ),
584 )
585 .with_label(c.ty.span(), "declared type"),
586 );
587 }
588}
589
590#[allow(clippy::too_many_arguments)]
593pub fn check_state_initialiser(
594 init: &Expr,
595 field_type: &TypeRef,
596 input: &ResolvedCommons,
597 tys: &Types,
598 expr_types: &mut HashMap<ExprId, TypedExpr>,
599 callees: &mut HashMap<ExprId, Callee>,
600 errors: &mut Vec<CompileError>,
601 refs: &mut RefSink,
602 hints: &mut HintSink,
603 locals: &mut LocalsSink,
604) {
605 check_static_initialiser(
606 init,
607 field_type,
608 input,
609 expr_types,
610 callees,
611 errors,
612 refs,
613 hints,
614 locals,
615 "bynk.agents.bad_state_initialiser",
616 "state field initialiser",
617 tys,
618 );
619}
620
621#[allow(clippy::too_many_arguments)]
639pub fn check_event_field_default(
640 init: &Expr,
641 field_type: &TypeRef,
642 subject: &str,
645 input: &ResolvedCommons,
646 tys: &Types,
647 expr_types: &mut HashMap<ExprId, TypedExpr>,
648 callees: &mut HashMap<ExprId, Callee>,
649 errors: &mut Vec<CompileError>,
650 refs: &mut RefSink,
651 hints: &mut HintSink,
652 locals: &mut LocalsSink,
653) {
654 check_static_initialiser(
655 init,
656 field_type,
657 input,
658 expr_types,
659 callees,
660 errors,
661 refs,
662 hints,
663 locals,
664 "bynk.types.bad_field_default",
665 subject,
666 tys,
667 );
668 if let ExprKind::MethodCall {
673 receiver,
674 method,
675 args,
676 ..
677 } = &init.kind
678 && let ExprKind::Ident(type_name) = &receiver.kind
679 && method.name == "unsafe"
680 && let [lit_expr] = args.as_slice()
681 && let Some(decl) = input.types.get(&type_name.name)
682 && matches!(decl.body, TypeBody::Opaque { .. })
683 && let Some(refinement) = refinements::type_decl_refinement(decl)
684 && let Some(lit) = refinements::const_literal(lit_expr)
685 && let Some(failed) = refinements::first_failed_predicate(refinement, &lit)
686 {
687 errors.push(
688 CompileError::new(
689 "bynk.types.bad_field_default",
690 lit_expr.span,
691 format!(
692 "`{}.unsafe(...)` bypasses its own refinement, but a {subject} \
693 must be a value the wire could actually carry — this literal fails `{}`",
694 type_name.name,
695 failed.name(),
696 ),
697 )
698 .with_note(
699 "a default is spliced into the same codec that validates a real wire value on \
700 receipt, so a refinement-violating `.unsafe(lit)` default would compile cleanly \
701 and then fail at runtime the first time an old event actually triggers it",
702 ),
703 );
704 }
705}
706
707pub(super) fn refuse_experimental(path: &str, span: Span, ctx: &mut Ctx) {
710 if let Some(err) = ctx.input.stability.policy.check(path, span) {
711 ctx.errors.push(err);
712 }
713}
714
715pub(crate) fn refuse_experimental_import(name: &Ident, ctx: &mut Ctx) {
719 if let Some(path) = ctx.input.stability.blocked_imports.get(&name.name).cloned() {
720 refuse_experimental(&path, name.span, ctx);
721 }
722}
723
724pub const BYNK_LIST_DEPRECATED: &[(&str, &str)] = &[
729 ("reverse", "xs.reverse()"),
730 ("map", "xs.map(f)"),
731 ("filter", "xs.filter(p)"),
732 ("find", "xs.find(p)"),
733 ("any", "xs.any(p)"),
734 ("all", "xs.all(p)"),
735 ("traverse", "xs.traverse(f)"),
736 ("sort", "xs.sort()"),
737 ("min", "xs.min()"),
738 ("max", "xs.max()"),
739];
740
741fn warn_bynk_list_deprecation(name: &Ident, args: &[Expr], call_span: Span, ctx: &mut Ctx) {
746 let module = ctx.input.imported_from.get(&name.name).map(String::as_str);
747 if matches!(module, Some("bynk.map" | "bynk.set")) {
749 return super::collections::warn_deprecated_collection_fn(name, args, call_span, ctx);
750 }
751 if module != Some("bynk.list") {
752 return;
753 }
754 let Some(&(_, method_form)) = BYNK_LIST_DEPRECATED
756 .iter()
757 .find(|(f, _)| *f == name.name.as_str())
758 else {
759 return;
760 };
761 let mut err = CompileError::new(
762 "bynk.list.deprecated_function",
763 name.span,
764 format!(
765 "`bynk.list.{}` is deprecated — use the `List` method form `{method_form}`",
766 name.name
767 ),
768 )
769 .with_note(
770 "the `bynk.list.*` free functions are superseded by the method-chain vocabulary (ADR 0116); the method form reads left-to-right and chains",
771 );
772 let keyless = matches!(name.name.as_str(), "reverse" | "sort" | "min" | "max");
775 let edits = match (keyless, args.len()) {
776 (true, 1) => Some(vec![
778 (
779 Span::new(name.span.start, args[0].span.start),
780 String::new(),
781 ),
782 (
783 Span::new(args[0].span.end, call_span.end),
784 format!(".{}()", name.name),
785 ),
786 ]),
787 (false, 2) => Some(vec![
789 (
790 Span::new(name.span.start, args[0].span.start),
791 String::new(),
792 ),
793 (
794 Span::new(args[0].span.end, args[1].span.start),
795 format!(".{}(", name.name),
796 ),
797 ]),
798 _ => None,
799 };
800 if let Some(edits) = edits {
801 err = err.with_suggestion(
802 format!("rewrite to the `List` method form `{method_form}`"),
803 edits,
804 Applicability::MachineApplicable,
805 );
806 }
807 ctx.errors.push(err);
808}
809
810pub(crate) fn require_callee_given(name: &Ident, callee: &FnDecl, ctx: &mut Ctx) {
817 if callee.given.is_empty() {
822 return;
823 }
824 if ctx.input.imported_fn_names.contains(&callee.name.display())
825 || given_fn_refusal(callee, ctx.input.is_context).is_some()
826 {
827 return;
828 }
829 let mut missing: Vec<String> = Vec::new();
830 for c in &callee.given {
831 let key = c.key().to_string();
832 if ctx.caps.given_remaining.contains(&key) {
835 ctx.caps.given_used.insert(key);
836 } else if !missing.contains(&c.display_name()) {
837 missing.push(c.display_name());
838 }
839 }
840 if missing.is_empty() || ctx.in_test_body {
841 return;
842 }
843 let list = missing.join(", ");
844 let mut err = CompileError::new(
845 "bynk.given.missing_for_call",
846 name.span,
847 format!(
848 "`{}` needs `given {list}`, which the enclosing body does not declare",
849 name.name
850 ),
851 )
852 .with_label(
853 callee.name.ident().span,
854 format!(
855 "`{}` declares `given {}`",
856 name.name,
857 callee
858 .given
859 .iter()
860 .map(|c| c.display_name())
861 .collect::<Vec<_>>()
862 .join(", ")
863 ),
864 )
865 .with_note(if ctx.test_values {
866 "a suite helper has no capabilities of its own to pass on: call it from a `case`, which gets the target's capabilities as its handlers do, or take the operation as a function parameter".to_string()
869 } else if ctx.caps.given_anchor.is_none() && ctx.caps.given_entries.is_empty() {
870 "this body cannot declare `given`: take the operation as a function parameter, or call it from a handler or a context function that declares `given`".to_string()
872 } else {
873 format!(
874 "a capability never appears in a body without appearing in the signature of every handler and function on the path to it: add `{list}` to the caller's `given` clause"
875 )
876 });
877 if !ctx.test_values
878 && let Some((span, insert)) =
879 given_insertion_edit(&ctx.caps.given_entries, ctx.caps.given_anchor, &list)
880 {
881 err = err.with_suggestion(
882 format!("add `{list}` to the `given` clause"),
883 vec![(span, insert)],
884 Applicability::MachineApplicable,
885 );
886 }
887 ctx.errors.push(err);
888}
889
890pub(crate) fn check_call(
891 name: &Ident,
892 type_args: &[TypeRef],
893 args: &[Expr],
894 span: Span,
895 expected: Option<TyId>,
898 expr_id: ExprId,
901 ctx: &mut Ctx,
902) -> Option<TyId> {
903 let tys = ctx.tys;
904 if let Some(fn_decl) = ctx.input.fns.get(&name.name) {
905 ctx.refs.record(name.span, SymbolKind::Fn, &name.name);
906 let fn_decl = Arc::clone(fn_decl);
907 ctx.callees
908 .insert(expr_id, Callee::Fn(Arc::clone(&fn_decl), Vec::new()));
909 warn_bynk_list_deprecation(name, args, span, ctx);
910 refuse_experimental_import(name, ctx);
911 require_callee_given(name, &fn_decl, ctx);
912 let ret = check_call_against_fn(name, &fn_decl, type_args, args, expected, ctx);
913 if let Some(witnesses) = ctx.last_witness.take() {
915 ctx.callees
916 .insert(expr_id, Callee::Fn(Arc::clone(&fn_decl), witnesses));
917 }
918 return ret;
919 }
920 if name.name == "TestConnection" {
923 return check_test_connection_new(type_args, args, span, expr_id, ctx);
924 }
925 if !type_args.is_empty() {
927 ctx.errors.push(CompileError::new(
928 "bynk.generics.type_arg_mismatch",
929 span,
930 format!(
931 "`{}` is not a generic function — it takes no type arguments",
932 name.name
933 ),
934 ));
935 for a in args {
936 let _ = type_of(a, None, ctx);
937 }
938 return None;
939 }
940 let owners: Vec<&Arc<TypeDecl>> = crate::resolver::bare_variant_owners(
944 &name.name,
945 &ctx.input.types,
946 &ctx.input.unselected_types,
947 );
948 let left_out = left_out_variant_owner(
950 &name.name,
951 &ctx.input.types,
952 &ctx.input.unselected_types,
953 expected,
954 tys,
955 );
956 if let Some(sum) = left_out.or_else(|| variant_owner(&owners, expected, tys)) {
957 ctx.callees.insert(
958 expr_id,
959 Callee::Ctor {
960 sum: Arc::clone(sum),
961 tag: name.name.clone(),
962 },
963 );
964 return check_variant_construction(sum, &name.name, args, span, expected, ctx);
965 }
966 if let Some(agent) = ctx.input.agents.get(&name.name).cloned() {
970 ctx.refs.record(name.span, SymbolKind::Agent, &name.name);
971 ctx.callees
972 .insert(expr_id, Callee::AgentInit(name.name.clone()));
973 let key_ty = resolve_type_ref(&agent.key_type, &ctx.input.types, tys);
974 if args.len() != 1 {
975 let mut err = CompileError::new(
976 "bynk.agent.construction_arity",
977 span,
978 format!(
979 "agent `{}` is constructed with one key argument, but {} were given",
980 name.name,
981 args.len()
982 ),
983 );
984 if let Some(s) = ctx.input.shadowed_imports.get(&name.name) {
987 err = err.with_note(format!(
988 "this unit's agent `{}` hides the {} of that name from `{}`; rename one to use the {}",
989 name.name, s.imported, s.unit, s.imported
990 ));
991 }
992 ctx.errors.push(err);
993 for a in args {
994 let _ = type_of(a, None, ctx);
995 }
996 return None;
997 }
998 let arg_ty = type_of(&args[0], key_ty, ctx);
999 if let (Some(a), Some(k)) = (arg_ty, key_ty)
1000 && !compatible(a, k, tys)
1001 {
1002 ctx.errors.push(CompileError::new(
1003 "bynk.agent.key_mismatch",
1004 args[0].span,
1005 format!(
1006 "agent `{}` key is `{}`, but a value of type `{}` was given",
1007 name.name,
1008 k.display(tys),
1009 a.display(tys)
1010 ),
1011 ));
1012 }
1013 return Some(tys.intern(Ty::Named {
1014 name: name.name.clone(),
1015 kind: NamedKind::Record,
1016 args: Vec::new(),
1017 }));
1018 }
1019 if let Some(ty) = ctx.lookup(&name.name) {
1025 return match &*tys.get(ty) {
1026 Ty::Fn { params, ret } => {
1027 ctx.callees
1028 .insert(expr_id, Callee::Value(name.name.clone()));
1029 check_value_application(name, params, *ret, args, span, ctx)
1030 }
1031 _ => {
1032 ctx.errors.push(
1035 CompileError::new(
1036 "bynk.resolve.param_as_function",
1037 span,
1038 format!(
1039 "`{}` has type `{}` and is not callable",
1040 name.name,
1041 ty.display(tys)
1042 ),
1043 )
1044 .with_note("only values of function type can be applied"),
1045 );
1046 for a in args {
1047 let _ = type_of(a, None, ctx);
1048 }
1049 None
1050 }
1051 };
1052 }
1053 if let Some(kind) = crate::builtin_names::faults::kind_of(&name.name) {
1056 return check_fault_call(name, kind, type_args, args, span, expr_id, ctx);
1057 }
1058 for a in args {
1065 let _ = type_of(a, None, ctx);
1066 }
1067 if owners.len() > 1 {
1068 ctx.errors.push(ambiguous_variant_error(
1069 &name.name, name.span, &owners, true,
1070 ));
1071 return None;
1072 }
1073 if let Some(err) = ctx.input.shadowed_import_error(&name.name, name.span) {
1076 ctx.errors.push(err);
1077 return None;
1078 }
1079 if ctx.input.types.contains_key(&name.name) {
1080 ctx.errors.push(CompileError::new(
1081 "bynk.resolve.type_as_function",
1082 span,
1083 format!(
1084 "`{}` is a type, not a function — use `{}.of(value)` or `{} {{ ... }}` instead",
1085 name.name, name.name, name.name
1086 ),
1087 ));
1088 return None;
1089 }
1090 ctx.errors.push(
1091 CompileError::new(
1092 "bynk.resolve.unknown_function",
1093 span,
1094 format!("unknown function `{}`", name.name),
1095 )
1096 .with_note(crate::resolver::unknown_function_note(&name.name)),
1097 );
1098 None
1099}
1100
1101fn check_test_connection_new(
1105 type_args: &[TypeRef],
1106 args: &[Expr],
1107 span: Span,
1108 expr_id: ExprId,
1109 ctx: &mut Ctx,
1110) -> Option<TyId> {
1111 let tys = ctx.tys;
1112 for a in args {
1113 let _ = type_of(a, None, ctx);
1114 }
1115 if type_args.len() != 1 || !args.is_empty() {
1116 ctx.errors.push(CompileError::new(
1117 "bynk.generics.type_arg_mismatch",
1118 span,
1119 "`TestConnection[F]()` takes the service's `out` frame type as its one type argument and no value arguments",
1120 ));
1121 return None;
1122 }
1123 let frame = resolve_type_ref(&type_args[0], &ctx.input.types, tys)?;
1124 ctx.callees.insert(
1125 expr_id,
1126 Callee::intrinsic(StaticOp::TestConnection(TestConnectionStatic::New)),
1127 );
1128 Some(tys.intern(Ty::TestConnection(frame)))
1129}
1130
1131fn check_fault_call(
1136 name: &Ident,
1137 kind: &'static str,
1138 type_args: &[TypeRef],
1139 args: &[Expr],
1140 span: Span,
1141 expr_id: ExprId,
1142 ctx: &mut Ctx,
1143) -> Option<TyId> {
1144 let tys = ctx.tys;
1145 ctx.callees.insert(expr_id, Callee::Fault { kind });
1146 if !type_args.is_empty() {
1147 ctx.errors.push(CompileError::new(
1148 "bynk.generics.type_arg_mismatch",
1149 span,
1150 format!(
1151 "`{}` is not a generic function — it takes no type arguments",
1152 name.name
1153 ),
1154 ));
1155 }
1156 if args.len() != 1 {
1157 ctx.errors.push(CompileError::new(
1158 "bynk.types.call_arity",
1159 span,
1160 format!(
1161 "`{}` takes 1 argument (a message), but {} were given",
1162 name.name,
1163 args.len()
1164 ),
1165 ));
1166 for a in args {
1167 let _ = type_of(a, None, ctx);
1168 }
1169 } else {
1170 let string = tys.intern(Ty::Base(BaseType::String));
1171 if let Some(a) = type_of(&args[0], Some(string), ctx)
1172 && !compatible(a, string, tys)
1173 {
1174 ctx.errors.push(CompileError::new(
1175 "bynk.types.argument_mismatch",
1176 args[0].span,
1177 format!(
1178 "argument has type `{}`, but `{}` expects `String`",
1179 a.display(tys),
1180 name.name
1181 ),
1182 ));
1183 }
1184 }
1185 if name.name == crate::builtin_names::faults::TODO {
1186 ctx.errors.push(
1187 CompileError::new(
1188 "bynk.fault.todo",
1189 span,
1190 "`todo` marks unfinished code and faults when it runs",
1191 )
1192 .with_note("replace it with the implementation, or use `unreachable` for a case that cannot happen"),
1193 );
1194 }
1195 Some(tys.intern(Ty::Never))
1196}
1197
1198fn check_value_application(
1199 name: &Ident,
1200 params: &[TyId],
1201 ret: TyId,
1202 args: &[Expr],
1203 span: Span,
1204 ctx: &mut Ctx,
1205) -> Option<TyId> {
1206 let tys = ctx.tys;
1207 if ret.is_effect(tys) && !ctx.effectful {
1208 ctx.errors.push(
1209 CompileError::new(
1210 "bynk.effect.fn_value_in_pure_context",
1211 span,
1212 format!(
1213 "`{}` is an effectful function (`{}`) and cannot be called in a pure context",
1214 name.name,
1215 Ty::Fn {
1216 params: params.to_vec(),
1217 ret,
1218 }
1219 .display(tys)
1220 ),
1221 )
1222 .with_note(
1223 "effectful function values may only be called where the enclosing body is effectful (its return type is an Effect)",
1224 ),
1225 );
1226 }
1227 if params.len() != args.len() {
1228 ctx.errors.push(CompileError::new(
1229 "bynk.types.call_arity",
1230 span,
1231 format!(
1232 "`{}` takes {} argument(s), but {} were given",
1233 name.name,
1234 params.len(),
1235 args.len()
1236 ),
1237 ));
1238 for a in args {
1239 let _ = type_of(a, None, ctx);
1240 }
1241 return None;
1242 }
1243 for (arg, param_ty) in args.iter().zip(params) {
1244 let arg_ty = type_of(arg, Some(*param_ty), ctx);
1245 if let Some(a) = arg_ty
1246 && !compatible(a, *param_ty, tys)
1247 {
1248 let err = CompileError::new(
1249 "bynk.types.argument_mismatch",
1250 arg.span,
1251 format!(
1252 "argument has type `{}`, but `{}` expects `{}`",
1253 a.display(tys),
1254 name.name,
1255 param_ty.display(tys)
1256 ),
1257 );
1258 ctx.errors.push(with_of_hint(err, a, *param_ty, ctx));
1259 }
1260 }
1261 Some(ret)
1262}
1263
1264fn ground_from_expected(
1275 ret_pattern: TyId,
1276 expected: Option<TyId>,
1277 names: &[String],
1278 subst: &mut HashMap<String, TyId>,
1279 ctx: &Ctx,
1280) {
1281 let tys = ctx.tys;
1282 let Some(expected) = expected else {
1283 return;
1284 };
1285 if names.iter().all(|n| subst.contains_key(n))
1286 || matches!(&*tys.get(expected), Ty::Error | Ty::Never)
1287 || contains_flexible_var(expected, &ctx.type_vars, tys)
1288 {
1289 return;
1290 }
1291 let mut scratch: HashMap<String, TyId> = HashMap::new();
1292 if !unify(ret_pattern, expected, &mut scratch, tys) {
1293 return;
1294 }
1295 for n in names {
1296 if !subst.contains_key(n)
1297 && let Some(t) = scratch.get(n)
1298 {
1299 subst.insert(n.clone(), *t);
1300 }
1301 }
1302}
1303
1304fn check_generic_call(
1315 name: &Ident,
1316 fn_decl: &FnDecl,
1317 type_args: &[TypeRef],
1318 args: &[Expr],
1319 expected: Option<TyId>,
1320 ctx: &mut Ctx,
1321) -> Option<TyId> {
1322 let tys = ctx.tys;
1323 let vars: HashSet<String> = fn_decl
1324 .type_params
1325 .iter()
1326 .map(|tp| tp.name.name.clone())
1327 .collect();
1328 if fn_decl.params.len() != args.len() {
1329 ctx.errors.push(
1332 CompileError::new(
1333 "bynk.resolve.arity_mismatch",
1334 name.span,
1335 format!(
1336 "function `{}` expects {} argument(s), but {} were given",
1337 name.name,
1338 fn_decl.params.len(),
1339 args.len()
1340 ),
1341 )
1342 .with_label(fn_decl.name.ident().span, "function declared here"),
1343 );
1344 for a in args {
1345 let _ = type_of(a, None, ctx);
1346 }
1347 return None;
1348 }
1349 let var_params: Vec<Option<TyId>> = fn_decl
1350 .params
1351 .iter()
1352 .map(|p| resolve_type_ref_in(&p.type_ref, &ctx.input.types, &vars, tys))
1353 .collect();
1354 let ret_pattern = resolve_type_ref_in(&fn_decl.return_type, &ctx.input.types, &vars, tys)?;
1355
1356 let mut subst: HashMap<String, TyId> = HashMap::new();
1357 if !type_args.is_empty() {
1358 if type_args.len() != fn_decl.type_params.len() {
1359 ctx.errors.push(CompileError::new(
1360 "bynk.generics.type_arg_mismatch",
1361 name.span,
1362 format!(
1363 "`{}` takes {} type argument(s), but {} were given",
1364 name.name,
1365 fn_decl.type_params.len(),
1366 type_args.len()
1367 ),
1368 ));
1369 return None;
1370 }
1371 for (tp, ta) in fn_decl.type_params.iter().zip(type_args) {
1372 let ty = resolve_expr_type_ref(ta, ctx)?;
1378 subst.insert(tp.name.name.clone(), ty);
1379 }
1380 }
1381
1382 let mut arg_tys: Vec<Option<TyId>> = vec![None; args.len()];
1383 for (i, arg) in args.iter().enumerate() {
1385 if matches!(arg.kind, ExprKind::Lambda(_)) {
1386 continue;
1387 }
1388 let expected = var_params[i].map(|p| substitute(p, &subst, tys));
1389 let ty = type_of(arg, expected, ctx);
1390 if let (Some(pattern), Some(actual)) = (var_params[i], ty)
1391 && !unify(pattern, actual, &mut subst, tys)
1392 {
1393 ctx.errors.push(CompileError::new(
1394 "bynk.generics.type_arg_mismatch",
1395 arg.span,
1396 format!(
1397 "argument {} infers a type for `{}`'s type parameter that conflicts with an earlier argument — annotate with `{}[T](…)`",
1398 i + 1,
1399 name.name,
1400 name.name
1401 ),
1402 ));
1403 return None;
1404 }
1405 arg_tys[i] = ty;
1406 }
1407 let own: Vec<String> = fn_decl
1410 .type_params
1411 .iter()
1412 .map(|tp| tp.name.name.clone())
1413 .collect();
1414 ground_from_expected(ret_pattern, expected, &own, &mut subst, ctx);
1415 for (i, arg) in args.iter().enumerate() {
1417 if !matches!(arg.kind, ExprKind::Lambda(_)) {
1418 continue;
1419 }
1420 let expected = var_params[i].map(|p| substitute(p, &subst, tys));
1421 let params_unconstrained = expected.is_some_and(|e| {
1422 matches!(&*tys.get(e), Ty::Fn { params, .. }
1423 if params.iter().any(|p| contains_var(*p, tys)))
1424 });
1425 let fully_annotated = matches!(
1426 &arg.kind,
1427 ExprKind::Lambda(l) if l.params.iter().all(|p| lambda_param_is_typed(p, ctx))
1428 );
1429 if params_unconstrained && !fully_annotated {
1430 ctx.errors.push(
1431 CompileError::new(
1432 "bynk.generics.uninferable_type_arg",
1433 arg.span,
1434 format!(
1435 "the lambda's parameter types depend on `{}`'s type parameters, which the other arguments do not determine",
1436 name.name
1437 ),
1438 )
1439 .with_note("annotate the lambda's parameters, or give explicit type arguments: `name[T](…)`"),
1440 );
1441 return None;
1442 }
1443 let ty = if params_unconstrained {
1446 type_of(arg, None, ctx)
1447 } else {
1448 type_of(arg, expected, ctx)
1449 };
1450 if let (Some(pattern), Some(actual)) = (var_params[i], ty)
1451 && !unify(pattern, actual, &mut subst, tys)
1452 {
1453 ctx.errors.push(CompileError::new(
1454 "bynk.generics.type_arg_mismatch",
1455 arg.span,
1456 format!(
1457 "the lambda's type conflicts with `{}`'s inferred type arguments",
1458 name.name
1459 ),
1460 ));
1461 return None;
1462 }
1463 arg_tys[i] = ty;
1464 }
1465 for tp in &fn_decl.type_params {
1467 if !subst.contains_key(&tp.name.name) {
1468 ctx.errors.push(
1469 CompileError::new(
1470 "bynk.generics.uninferable_type_arg",
1471 name.span,
1472 format!(
1473 "type parameter `{}` of `{}` is neither inferable from the arguments nor given explicitly",
1474 tp.name.name, name.name
1475 ),
1476 )
1477 .with_label(tp.span, "declared here")
1478 .with_note("give explicit type arguments: `name[T](…)`"),
1479 );
1480 return None;
1481 }
1482 }
1483 let mut ok = true;
1485 for (i, (pattern, arg)) in var_params.iter().zip(args).enumerate() {
1486 record_param_hint(ctx.hints, &fn_decl.params[i].name.name, arg);
1487 let (Some(pattern), Some(arg_ty)) = (pattern, arg_tys[i].as_ref()) else {
1488 continue;
1489 };
1490 let ground = substitute(*pattern, &subst, tys);
1491 if !compatible(*arg_ty, ground, tys) {
1492 let err = CompileError::new(
1493 "bynk.types.argument_mismatch",
1494 arg.span,
1495 format!(
1496 "argument {} to `{}` has type `{}`, but `{}` is expected",
1497 i + 1,
1498 name.name,
1499 arg_ty.display(tys),
1500 ground.display(tys)
1501 ),
1502 );
1503 ctx.errors.push(with_of_hint(err, *arg_ty, ground, ctx));
1504 ok = false;
1505 }
1506 }
1507 if !ok {
1508 return None;
1509 }
1510 let compared = match ctx.input.fns.get(&name.name) {
1516 Some(decl) if std::ptr::eq(decl.as_ref(), fn_decl) => {
1517 super::equality::compared_type_params(decl, ctx)
1518 }
1519 _ => Default::default(),
1520 };
1521 let ord_names = super::ordering::witness_params(fn_decl, &ctx.input.types);
1522 let key_names = super::keying::key_params(fn_decl, &ctx.input.types);
1523 let eq_params: Vec<(String, Option<Span>)> = fn_decl
1524 .type_params
1525 .iter()
1526 .filter(|tp| super::equality::has_eq(&tp.bounds) || compared.contains(&tp.name.name))
1527 .filter(|tp| !ord_names.contains(&tp.name.name) && !key_names.contains(&tp.name.name))
1530 .map(|tp| (tp.name.name.clone(), Some(tp.span)))
1531 .collect();
1532 if !super::equality::check_declared_eq_args(&name.name, name.span, &eq_params, &subst, ctx) {
1533 return None;
1534 }
1535 let witnesses = super::codable::check_declared_witness_args(
1538 &name.name,
1539 name.span,
1540 &super::codable::witness_list(fn_decl, &ctx.input.types),
1541 &subst,
1542 ctx,
1543 )?;
1544 if !super::keying::check_declared_key_args(&name.name, name.span, &key_names, &subst, ctx) {
1547 return None;
1548 }
1549 if type_args.is_empty() && !fn_decl.type_params.is_empty() {
1554 let rendered: Option<Vec<String>> = fn_decl
1555 .type_params
1556 .iter()
1557 .map(|tp| subst.get(&tp.name.name).map(|t| t.display(tys)))
1558 .collect();
1559 if let Some(parts) = rendered {
1560 ctx.hints
1561 .record(name.span, format!("[{}]", parts.join(", ")));
1562 }
1563 }
1564 if !witnesses.is_empty() {
1565 ctx.last_witness = Some(witnesses);
1566 }
1567 let ret = substitute(ret_pattern, &subst, tys);
1568 Some(ret)
1573}
1574
1575fn check_call_against_fn(
1576 name: &Ident,
1577 fn_decl: &FnDecl,
1578 type_args: &[TypeRef],
1579 args: &[Expr],
1580 expected: Option<TyId>,
1581 ctx: &mut Ctx,
1582) -> Option<TyId> {
1583 let tys = ctx.tys;
1584 if !fn_decl.type_params.is_empty() {
1588 return check_generic_call(name, fn_decl, type_args, args, expected, ctx);
1589 }
1590 if !type_args.is_empty() {
1591 ctx.errors.push(CompileError::new(
1592 "bynk.generics.type_arg_mismatch",
1593 name.span,
1594 format!(
1595 "`{}` is not a generic function — it takes no type arguments",
1596 name.name
1597 ),
1598 ));
1599 for a in args {
1600 let _ = type_of(a, None, ctx);
1601 }
1602 return None;
1603 }
1604 if fn_decl.params.len() != args.len() {
1605 ctx.errors.push(
1609 CompileError::new(
1610 "bynk.resolve.arity_mismatch",
1611 name.span,
1612 format!(
1613 "function `{}` expects {} argument(s), but {} were given",
1614 name.name,
1615 fn_decl.params.len(),
1616 args.len()
1617 ),
1618 )
1619 .with_label(fn_decl.name.ident().span, "function declared here"),
1620 );
1621 for a in args {
1622 let _ = type_of(a, None, ctx);
1623 }
1624 return None;
1625 }
1626 let resolved_params: Vec<(Option<TyId>, &Param)> = fn_decl
1627 .params
1628 .iter()
1629 .map(|p| (resolve_type_ref(&p.type_ref, &ctx.input.types, tys), p))
1630 .collect();
1631 let mut ok = true;
1632 for (i, ((param_ty, param), arg)) in resolved_params.iter().zip(args.iter()).enumerate() {
1633 record_param_hint(ctx.hints, ¶m.name.name, arg);
1634 let arg_ty = type_of(arg, *param_ty, ctx);
1635 let (Some(arg_ty), Some(param_ty)) = (arg_ty, *param_ty) else {
1636 ok = false;
1637 continue;
1638 };
1639 if !compatible(arg_ty, param_ty, tys) {
1640 let err = CompileError::new(
1641 "bynk.types.argument_mismatch",
1642 arg.span,
1643 format!(
1644 "argument {} to `{}` has type `{}`, but parameter `{}` expects `{}`",
1645 i + 1,
1646 name.name,
1647 arg_ty.display(tys),
1648 param.name.name,
1649 param_ty.display(tys)
1650 ),
1651 )
1652 .with_label(param.span, "parameter declared here");
1653 ctx.errors.push(with_of_hint(err, arg_ty, param_ty, ctx));
1654 ok = false;
1655 }
1656 }
1657 if !ok {
1658 return None;
1659 }
1660 resolve_type_ref(&fn_decl.return_type, &ctx.input.types, tys)
1661}
1662
1663fn infer_op_type_args(
1668 op: &CapabilityOpInfo,
1669 args: &[Expr],
1670 ctx: &mut Ctx,
1671) -> (Option<HashMap<String, TyId>>, Vec<Option<TyId>>) {
1672 let tys = ctx.tys;
1673 let mut subst: HashMap<String, TyId> = HashMap::new();
1674 let mut typed = Vec::with_capacity(args.len());
1675 let mut ok = true;
1676 for (pattern, arg) in op.params.iter().zip(args) {
1677 if !contains_var(*pattern, tys) {
1681 typed.push(type_of(arg, Some(*pattern), ctx));
1682 continue;
1683 }
1684 let t = type_of(arg, None, ctx);
1685 match t {
1686 Some(t) => ok &= unify(*pattern, t, &mut subst, tys),
1687 None => ok = false,
1688 }
1689 typed.push(t);
1690 }
1691 let complete = ok && op.type_params.iter().all(|tp| subst.contains_key(tp));
1692 (complete.then_some(subst), typed)
1693}
1694
1695pub(crate) fn check_arg(arg: &Expr, expected: TyId, what: &str, ctx: &mut Ctx) {
1698 let tys = ctx.tys;
1699 let Some(actual) = type_of(arg, Some(expected), ctx) else {
1700 return;
1701 };
1702 if !compatible(actual, expected, tys) {
1703 ctx.errors.push(CompileError::new(
1704 "bynk.types.type_mismatch",
1705 arg.span,
1706 format!(
1707 "{what} has type `{}`, but `{}` is required",
1708 actual.display(tys),
1709 expected.display(tys)
1710 ),
1711 ));
1712 }
1713}
1714
1715fn local_first_party(cap: &str, ctx: &Ctx) -> Option<crate::firstparty::FirstPartyCap> {
1718 crate::firstparty::resolve(
1719 cap,
1720 &ctx.input.commons.name.joined(),
1721 &ctx.input.cross_context.flattened_caps,
1722 )
1723}
1724
1725fn cross_first_party(consumed: &str, cap: &str) -> Option<crate::firstparty::FirstPartyCap> {
1728 crate::firstparty::resolve(cap, consumed, &HashMap::new())
1729}
1730
1731fn record_capability_ref(span: Span, name: &str, ctx: &mut Ctx) {
1736 if let Some(unit) = ctx.input.cross_context.flattened_caps.get(name) {
1737 ctx.refs
1738 .record_in_unit(span, SymbolKind::Capability, name, unit);
1739 } else {
1740 ctx.refs.record(span, SymbolKind::Capability, name);
1741 }
1742}
1743
1744fn of_result_ty(decl: &Arc<TypeDecl>, base: BaseType, tys: &Types) -> TyId {
1750 if bynk_syntax::ast::of_is_total(
1751 base,
1752 type_decl_refinement(decl),
1753 matches!(decl.body, TypeBody::Opaque { .. }),
1754 ) {
1755 return named_ty(decl, tys);
1756 }
1757 let named = named_ty(decl, tys);
1758 let err = tys.intern(Ty::ValidationError);
1759 tys.intern(Ty::Result(named, err))
1760}
1761
1762#[allow(clippy::too_many_arguments)]
1763pub(crate) fn check_static_call(
1764 type_name: &Ident,
1765 method: &Ident,
1766 type_args: &[TypeRef],
1772 args: &[Expr],
1773 span: Span,
1774 expected: Option<TyId>,
1777 expr_id: ExprId,
1780 ctx: &mut Ctx,
1781) -> Option<TyId> {
1782 let tys = ctx.tys;
1783 if ctx.caps.declared_capabilities.contains_key(&type_name.name)
1787 && !ctx.caps.capabilities.contains_key(&type_name.name)
1788 {
1789 record_capability_ref(type_name.span, &type_name.name, ctx);
1790 ctx.callees.insert(
1791 expr_id,
1792 Callee::Capability {
1793 cap: type_name.name.clone(),
1794 op: method.name.clone(),
1795 wire: None,
1796 first_party: local_first_party(&type_name.name, ctx),
1797 event: None,
1798 },
1799 );
1800 let mut err = CompileError::new(
1801 "bynk.given.undeclared_capability",
1802 type_name.span,
1803 format!(
1804 "capability `{}` is used but not listed in the handler's `given` clause",
1805 type_name.name
1806 ),
1807 )
1808 .with_note(format!(
1809 "add `{}` to the handler's `given` clause so the dependency surface is visible at the declaration site",
1810 type_name.name
1811 ));
1812 if let Some((span, insert)) = given_insertion_edit(
1814 &ctx.caps.given_entries,
1815 ctx.caps.given_anchor,
1816 &type_name.name,
1817 ) {
1818 err = err.with_suggestion(
1819 format!("add `{}` to the `given` clause", type_name.name),
1820 vec![(span, insert)],
1821 Applicability::MachineApplicable,
1822 );
1823 }
1824 ctx.errors.push(err);
1825 record_requirement(
1830 ctx,
1831 &type_name.name,
1832 span,
1833 RequirementSource::DirectCall {
1834 op: method.name.clone(),
1835 },
1836 false,
1837 );
1838 for a in args {
1839 let _ = type_of(a, None, ctx);
1840 }
1841 return None;
1842 }
1843 if let Some(cap) = ctx.caps.capabilities.get(&type_name.name).cloned() {
1844 record_capability_ref(type_name.span, &type_name.name, ctx);
1845 if let Some(unit) = ctx
1847 .input
1848 .cross_context
1849 .flattened_caps
1850 .get(&type_name.name)
1851 .cloned()
1852 {
1853 refuse_experimental(
1854 &format!("{unit}.{}.{}", type_name.name, method.name),
1855 method.span,
1856 ctx,
1857 );
1858 }
1859 ctx.callees.insert(
1860 expr_id,
1861 Callee::Capability {
1862 cap: type_name.name.clone(),
1863 op: method.name.clone(),
1864 wire: None,
1865 first_party: local_first_party(&type_name.name, ctx),
1866 event: None,
1867 },
1868 );
1869 if !ctx.effectful {
1870 ctx.errors.push(
1871 CompileError::new(
1872 "bynk.effect.capability_in_pure_context",
1873 span,
1874 format!(
1875 "capability `{}` can only be called inside an effectful body (one returning `Effect[T]`)",
1876 type_name.name
1877 ),
1878 ),
1879 );
1880 }
1881 ctx.caps.given_used.insert(type_name.name.clone());
1882 record_requirement(
1886 ctx,
1887 &type_name.name,
1888 span,
1889 RequirementSource::DirectCall {
1890 op: method.name.clone(),
1891 },
1892 true,
1893 );
1894 if d1::is_typed_read(cap.derived_from.as_ref(), &method.name) {
1897 return d1::check_typed_read(
1898 cap.derived_from.as_ref(),
1899 &type_name.name,
1900 method,
1901 type_args,
1902 args,
1903 span,
1904 expr_id,
1905 ctx,
1906 );
1907 }
1908 let Some(op) = cap.ops.iter().find(|o| o.name == method.name) else {
1909 ctx.errors.push(CompileError::new(
1910 "bynk.capability.unknown_operation",
1911 method.span,
1912 format!(
1913 "capability `{}` has no operation named `{}`",
1914 type_name.name, method.name
1915 ),
1916 ));
1917 for a in args {
1918 let _ = type_of(a, None, ctx);
1919 }
1920 return None;
1921 };
1922 match &cap.derived_from {
1928 Some((unit, base)) => {
1929 refuse_experimental(&format!("{unit}.{base}.{}", method.name), method.span, ctx);
1930 ctx.refs.record_in_unit(
1931 method.span,
1932 SymbolKind::CapabilityOp,
1933 &format!("{base}.{}", method.name),
1934 unit,
1935 );
1936 }
1937 None => ctx.refs.record(
1938 method.span,
1939 SymbolKind::CapabilityOp,
1940 &format!("{}.{}", type_name.name, method.name),
1941 ),
1942 }
1943 if let Some((unit, name, in_param)) = &op.boundary_conflict {
1947 let err = rebranded_return_mismatch(
1948 &format!("{}.{}", type_name.name, method.name),
1949 name,
1950 unit,
1951 *in_param,
1952 span,
1953 ctx,
1954 );
1955 ctx.errors.push(err);
1956 for a in args {
1957 let _ = type_of(a, None, ctx);
1958 }
1959 return None;
1960 }
1961 d1::check_sql_argument(
1963 cap.derived_from.as_ref(),
1964 &type_name.name,
1965 &method.name,
1966 args,
1967 ctx,
1968 );
1969 if op.params.len() != args.len() {
1970 ctx.errors.push(CompileError::new(
1971 "bynk.capability.op_arity",
1972 span,
1973 format!(
1974 "capability operation `{}.{}` expects {} argument(s), but {} were given",
1975 type_name.name,
1976 method.name,
1977 op.params.len(),
1978 args.len()
1979 ),
1980 ));
1981 for a in args {
1982 let _ = type_of(a, None, ctx);
1983 }
1984 return None;
1985 }
1986 let op_clone = op.clone();
1987 let mut subst: HashMap<String, TyId> = HashMap::new();
1991 let mut arg_tys: Option<Vec<Option<TyId>>> = None;
1994 if type_args.is_empty()
1995 && (!op_clone.codable_params.is_empty() || !op_clone.type_params.is_empty())
1996 {
1997 let (inferred, typed) = infer_op_type_args(&op_clone, args, ctx);
1998 arg_tys = Some(typed);
1999 if let Some(found) = inferred {
2000 subst = found;
2001 }
2002 }
2003 if !op_clone.type_params.is_empty() || !type_args.is_empty() {
2004 if type_args.is_empty() && subst.len() < op_clone.type_params.len() {
2005 ctx.errors.push(
2006 CompileError::new(
2007 "bynk.generics.uninferable_type_arg",
2008 span,
2009 format!(
2010 "capability operation `{}.{}` takes a type parameter, but none of its arguments determine it",
2011 type_name.name, method.name
2012 ),
2013 )
2014 .with_note(format!(
2015 "give it explicitly: `{}.{}[T](…)`",
2016 type_name.name, method.name
2017 )),
2018 );
2019 if arg_tys.is_none() {
2020 for a in args {
2021 let _ = type_of(a, None, ctx);
2022 }
2023 }
2024 return None;
2025 }
2026 if !type_args.is_empty() && type_args.len() != op_clone.type_params.len() {
2027 ctx.errors.push(CompileError::new(
2028 "bynk.generics.type_arg_mismatch",
2029 span,
2030 format!(
2031 "capability operation `{}.{}` takes {} type argument(s), but {} were given",
2032 type_name.name,
2033 method.name,
2034 op_clone.type_params.len(),
2035 type_args.len()
2036 ),
2037 ));
2038 for a in args {
2039 let _ = type_of(a, None, ctx);
2040 }
2041 return None;
2042 }
2043 if type_args.is_empty() {
2045 for ty in op_clone.type_params.iter().filter_map(|tp| subst.get(tp)) {
2046 super::events_emit::check_emit_owner(
2047 local_first_party(&type_name.name, ctx),
2048 &method.name,
2049 (*ty, span, expr_id),
2050 ctx,
2051 );
2052 }
2053 }
2054 for (tp, ta) in op_clone.type_params.iter().zip(type_args) {
2055 let ty = resolve_expr_type_ref(ta, ctx)?;
2056 super::events_emit::check_emit_owner(
2057 local_first_party(&type_name.name, ctx),
2058 &method.name,
2059 (ty, ta.span(), expr_id),
2060 ctx,
2061 );
2062 subst.insert(tp.clone(), ty);
2063 }
2064 }
2065 if !check_op_codable_args(
2068 &format!("{}.{}", type_name.name, method.name),
2069 span,
2070 &op_clone.codable_params,
2071 &subst,
2072 ctx,
2073 ) {
2074 if arg_tys.is_none() {
2075 for a in args {
2076 let _ = type_of(a, None, ctx);
2077 }
2078 }
2079 return None;
2080 }
2081 if !record_capability_wire(
2082 &op_clone,
2083 (&type_name.name, &method.name),
2084 span,
2085 expr_id,
2086 &subst,
2087 arg_tys.is_none().then_some(args),
2088 ctx,
2089 ) {
2090 return None;
2091 }
2092 for (i, (param_ty, arg)) in op_clone.params.iter().zip(args.iter()).enumerate() {
2093 let param_ty = substitute(*param_ty, &subst, tys);
2094 let arg_ty = match &arg_tys {
2095 Some(cached) => cached[i],
2096 None => type_of(arg, Some(param_ty), ctx),
2097 };
2098 if let Some(actual) = arg_ty
2099 && !compatible(actual, param_ty, tys)
2100 {
2101 ctx.errors.push(CompileError::new(
2102 "bynk.types.argument_mismatch",
2103 arg.span,
2104 format!(
2105 "argument {} to capability `{}.{}` has type `{}`, but parameter expects `{}`",
2106 i + 1,
2107 type_name.name,
2108 method.name,
2109 actual.display(tys),
2110 param_ty.display(tys)
2111 ),
2112 ));
2113 }
2114 }
2115 return Some(substitute(op_clone.return_ty, &subst, tys));
2116 }
2117 let decl = ctx.input.types.get(&type_name.name)?;
2118 ctx.refs
2119 .record(type_name.span, SymbolKind::Type, &type_name.name);
2120
2121 if let Some(method_decl) = ctx
2125 .input
2126 .methods
2127 .get(&type_name.name)
2128 .and_then(|table| table.statics.get(&method.name))
2129 {
2130 ctx.callees
2131 .insert(expr_id, Callee::Static(Arc::clone(method_decl), Vec::new()));
2132 if !decl.type_params.is_empty() {
2135 let type_params: Vec<String> = decl
2136 .type_params
2137 .iter()
2138 .map(|p| p.name.name.clone())
2139 .collect();
2140 let ret = check_generic_method_call(
2141 &type_name.name,
2142 &type_params,
2143 None,
2144 method_decl,
2145 method,
2146 type_args,
2147 args,
2148 expected,
2149 ctx,
2150 );
2151 if let Some(witnesses) = ctx.last_witness.take() {
2152 ctx.callees
2153 .insert(expr_id, Callee::Static(Arc::clone(method_decl), witnesses));
2154 }
2155 return ret;
2156 }
2157 return check_method_args(method_decl, args, ctx, type_name, method);
2158 }
2159
2160 if method.name == OF
2162 && let Some(base) = type_decl_base(decl)
2163 {
2164 ctx.callees
2165 .insert(expr_id, Callee::Refine(Arc::clone(decl)));
2166 if args.len() != 1 {
2167 ctx.errors.push(CompileError::new(
2168 "bynk.types.constructor_arity",
2169 span,
2170 format!(
2171 "constructor `{}.of` expects 1 argument, but {} were given",
2172 type_name.name,
2173 args.len()
2174 ),
2175 ));
2176 return None;
2177 }
2178 let arg = &args[0];
2179 let expected = tys.intern(Ty::Base(base));
2180 let arg_ty = type_of(arg, Some(expected), ctx)?;
2181 if !compatible(arg_ty, expected, tys) {
2182 ctx.errors.push(CompileError::new(
2183 "bynk.types.constructor_base_mismatch",
2184 arg.span,
2185 format!(
2186 "constructor `{}.of` expects a `{}` argument, but got `{}`",
2187 type_name.name,
2188 base.name(),
2189 arg_ty.display(tys)
2190 ),
2191 ));
2192 return None;
2193 }
2194 return Some(of_result_ty(decl, base, tys));
2195 }
2196
2197 if method.name == UNSAFE
2200 && let TypeBody::Opaque { base, .. } = &decl.body
2201 {
2202 ctx.callees
2203 .insert(expr_id, Callee::Unsafe(Arc::clone(decl)));
2204 if !ctx.input.is_local_type(&decl.name.name) {
2205 ctx.errors.push(
2206 CompileError::new(
2207 "bynk.types.opaque_unsafe_outside",
2208 method.span,
2209 format!(
2210 "`{}.unsafe(...)` is only available within the commons that defines the opaque type `{}`",
2211 type_name.name, type_name.name
2212 ),
2213 )
2214 .with_note(
2215 "outside the defining commons, opaque values are constructed via `T.of(value)`",
2216 ),
2217 );
2218 return None;
2219 }
2220 if args.len() != 1 {
2221 ctx.errors.push(CompileError::new(
2222 "bynk.types.constructor_arity",
2223 span,
2224 format!(
2225 "`{}.unsafe` expects 1 argument, but {} were given",
2226 type_name.name,
2227 args.len()
2228 ),
2229 ));
2230 return None;
2231 }
2232 let arg = &args[0];
2233 let expected = tys.intern(Ty::Base(*base));
2234 let arg_ty = type_of(arg, Some(expected), ctx)?;
2235 if !compatible(arg_ty, expected, tys) {
2236 ctx.errors.push(CompileError::new(
2237 "bynk.types.constructor_base_mismatch",
2238 arg.span,
2239 format!(
2240 "`{}.unsafe` expects a `{}` argument, but got `{}`",
2241 type_name.name,
2242 base.name(),
2243 arg_ty.display(tys)
2244 ),
2245 ));
2246 return None;
2247 }
2248 return Some(named_ty(decl, tys));
2249 }
2250
2251 if let TypeBody::Sum(_) = &decl.body {
2253 ctx.callees.insert(
2254 expr_id,
2255 Callee::Ctor {
2256 sum: Arc::clone(decl),
2257 tag: method.name.clone(),
2258 },
2259 );
2260 return check_variant_construction(decl, &method.name, args, span, expected, ctx);
2261 }
2262
2263 ctx.errors.push(
2264 CompileError::new(
2265 "bynk.types.unknown_static_member",
2266 method.span,
2267 format!(
2268 "type `{}` has no static method or variant named `{}`",
2269 type_name.name, method.name
2270 ),
2271 )
2272 .with_note("type declared here"),
2275 );
2276 None
2277}
2278
2279fn check_method_args(
2280 method_decl: &FnDecl,
2281 args: &[Expr],
2282 ctx: &mut Ctx,
2283 type_name: &Ident,
2284 method: &Ident,
2285) -> Option<TyId> {
2286 let tys = ctx.tys;
2287 if method_decl.params.len() != args.len() {
2288 ctx.errors.push(
2289 CompileError::new(
2290 "bynk.types.method_arity",
2291 method.span,
2292 format!(
2293 "static method `{}.{}` expects {} argument(s), but {} were given",
2294 type_name.name,
2295 method.name,
2296 method_decl.params.len(),
2297 args.len()
2298 ),
2299 )
2300 .with_label(method_decl.name.ident().span, "method declared here"),
2301 );
2302 for a in args {
2303 let _ = type_of(a, None, ctx);
2304 }
2305 return None;
2306 }
2307 let mut ok = true;
2308 for (i, (param, arg)) in method_decl.params.iter().zip(args.iter()).enumerate() {
2309 record_param_hint(ctx.hints, ¶m.name.name, arg);
2310 let expected = resolve_type_ref(¶m.type_ref, &ctx.input.types, tys);
2311 let actual = type_of(arg, expected, ctx);
2312 let (Some(actual), Some(expected)) = (actual, expected) else {
2313 ok = false;
2314 continue;
2315 };
2316 if !compatible(actual, expected, tys) {
2317 let err = CompileError::new(
2318 "bynk.types.argument_mismatch",
2319 arg.span,
2320 format!(
2321 "argument {} to `{}.{}` has type `{}`, but parameter `{}` expects `{}`",
2322 i + 1,
2323 type_name.name,
2324 method.name,
2325 actual.display(tys),
2326 param.name.name,
2327 expected.display(tys)
2328 ),
2329 );
2330 ctx.errors.push(with_of_hint(err, actual, expected, ctx));
2331 ok = false;
2332 }
2333 }
2334 if !ok {
2335 return None;
2336 }
2337 resolve_type_ref(&method_decl.return_type, &ctx.input.types, tys)
2338}
2339
2340pub(crate) fn check_store_map_op(
2348 method: &Ident,
2349 args: &[Expr],
2350 k: TyId,
2351 v: TyId,
2352 span: Span,
2353 ctx: &mut Ctx,
2354) -> Option<TyId> {
2355 let tys = ctx.tys;
2356 let vfn = || Ty::Fn {
2357 params: vec![v],
2358 ret: v,
2359 };
2360 if v.is_held(tys) && matches!(method.name.as_str(), "update" | "upsert") {
2367 ctx.errors.push(
2368 CompileError::new(
2369 "bynk.held.unsupported_map_op",
2370 method.span,
2371 format!(
2372 "a held `Map[K, Connection]` has no `{}` operation — a held resource cannot be transformed by a `(Connection) -> Connection` function",
2373 method.name
2374 ),
2375 )
2376 .with_note(
2377 "held connections are stored and resolved by identity; use `put`/`get`/`remove`",
2378 ),
2379 );
2380 for a in args {
2381 type_of(a, None, ctx);
2382 }
2383 return None;
2384 }
2385 let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2386 "put" => (vec![k, v], tys.intern(Ty::Unit)),
2387 "get" => (vec![k], tys.intern(Ty::Option(v))),
2388 "remove" => (vec![k], tys.intern(Ty::Unit)),
2389 "contains" => (vec![k], tys.intern(Ty::Base(BaseType::Bool))),
2390 "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2391 "update" => (vec![k, tys.intern(vfn())], tys.intern(Ty::Unit)),
2392 "upsert" => (vec![k, v, tys.intern(vfn())], tys.intern(Ty::Unit)),
2393 other => {
2394 ctx.errors.push(
2395 CompileError::new(
2396 "bynk.store.unknown_op",
2397 method.span,
2398 format!(
2399 "a `Map` store field has no operation `{other}` — expected `put`, `get`, \
2400 `update`, `upsert`, `remove`, `contains`, or `size`"
2401 ),
2402 )
2403 .with_note("storage-map ops are entry-level and effectful (await with `<-`)"),
2404 );
2405 for a in args {
2406 type_of(a, None, ctx);
2407 }
2408 return None;
2409 }
2410 };
2411 let effect = Ty::Effect(result);
2412 if args.len() != expected.len() {
2413 ctx.errors.push(CompileError::new(
2414 "bynk.types.call_arity",
2415 span,
2416 format!(
2417 "`Map.{}` takes {} argument(s), found {}",
2418 method.name,
2419 expected.len(),
2420 args.len()
2421 ),
2422 ));
2423 for a in args {
2424 type_of(a, None, ctx);
2425 }
2426 return Some(tys.intern(effect));
2427 }
2428 for (a, exp) in args.iter().zip(expected.iter()) {
2429 if let Some(at) = type_of(a, Some(*exp), ctx)
2430 && !compatible(at, *exp, tys)
2431 {
2432 ctx.errors.push(CompileError::new(
2433 "bynk.types.argument_mismatch",
2434 a.span,
2435 format!(
2436 "expected `{}`, found `{}`",
2437 exp.display(tys),
2438 at.display(tys)
2439 ),
2440 ));
2441 }
2442 }
2443 Some(tys.intern(effect))
2444}
2445
2446fn require_capability(
2454 site: Span,
2455 capability: &str,
2456 source: RequirementSource,
2457 ctx: &mut Ctx,
2458 code: &'static str,
2459 message: &str,
2460) {
2461 let covered = ctx.caps.capabilities.contains_key(capability);
2462 if covered {
2463 ctx.caps.given_used.insert(capability.to_string());
2464 } else {
2465 ctx.errors
2466 .push(CompileError::new(code, site, message).with_note(format!(
2467 "add `{capability}` to the handler's `given` clause"
2468 )));
2469 }
2470 record_requirement(ctx, capability, site, source, covered);
2471}
2472
2473fn record_requirement(
2478 ctx: &mut Ctx,
2479 capability: &str,
2480 site: Span,
2481 source: RequirementSource,
2482 covered: bool,
2483) {
2484 let materialize = if covered {
2485 None
2486 } else {
2487 given_insertion_edit(&ctx.caps.given_entries, ctx.caps.given_anchor, capability).map(
2488 |(edit_span, edit_text)| Materialize {
2489 anchor: ctx.caps.given_anchor.unwrap_or(ctx.return_ty_span),
2490 edit_span,
2491 edit_text,
2492 },
2493 )
2494 };
2495 ctx.requirements.record(Requirement {
2496 capability: capability.to_string(),
2497 site,
2498 source,
2499 covered,
2500 materialize,
2501 });
2502}
2503
2504pub(crate) fn check_store_cache_op(
2509 method: &Ident,
2510 args: &[Expr],
2511 k: TyId,
2512 v: TyId,
2513 span: Span,
2514 ctx: &mut Ctx,
2515) -> Option<TyId> {
2516 let tys = ctx.tys;
2517 let vfn = || Ty::Fn {
2518 params: vec![v],
2519 ret: v,
2520 };
2521 let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2522 "put" => (vec![k, v], tys.intern(Ty::Unit)),
2523 "get" => (vec![k], tys.intern(Ty::Option(v))),
2524 "remove" => (vec![k], tys.intern(Ty::Unit)),
2525 "contains" => (vec![k], tys.intern(Ty::Base(BaseType::Bool))),
2526 "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2527 "update" => (vec![k, tys.intern(vfn())], tys.intern(Ty::Unit)),
2528 "upsert" => (vec![k, v, tys.intern(vfn())], tys.intern(Ty::Unit)),
2529 other => {
2530 ctx.errors.push(
2531 CompileError::new(
2532 "bynk.store.unknown_op",
2533 method.span,
2534 format!(
2535 "a `Cache` store field has no operation `{other}` — expected `put`, \
2536 `get`, `update`, `upsert`, `remove`, `contains`, or `size`"
2537 ),
2538 )
2539 .with_note("storage-cache ops are entry-level and effectful (await with `<-`)"),
2540 );
2541 for a in args {
2542 type_of(a, None, ctx);
2543 }
2544 return None;
2545 }
2546 };
2547 if method.name != "remove" {
2549 require_capability(
2550 method.span,
2551 "Clock",
2552 RequirementSource::StoreOp {
2553 kind: StoreKind::Cache,
2554 op: method.name.clone(),
2555 },
2556 ctx,
2557 "bynk.store.cache_needs_clock",
2558 "a `Cache` operation applies TTL expiry, which reads the clock — the handler must declare `given Clock`",
2559 );
2560 }
2561 let effect = Ty::Effect(result);
2562 if args.len() != expected.len() {
2563 ctx.errors.push(CompileError::new(
2564 "bynk.types.call_arity",
2565 span,
2566 format!(
2567 "`Cache.{}` takes {} argument(s), found {}",
2568 method.name,
2569 expected.len(),
2570 args.len()
2571 ),
2572 ));
2573 for a in args {
2574 type_of(a, None, ctx);
2575 }
2576 return Some(tys.intern(effect));
2577 }
2578 for (a, exp) in args.iter().zip(expected.iter()) {
2579 if let Some(at) = type_of(a, Some(*exp), ctx)
2580 && !compatible(at, *exp, tys)
2581 {
2582 ctx.errors.push(CompileError::new(
2583 "bynk.types.argument_mismatch",
2584 a.span,
2585 format!(
2586 "expected `{}`, found `{}`",
2587 exp.display(tys),
2588 at.display(tys)
2589 ),
2590 ));
2591 }
2592 }
2593 Some(tys.intern(effect))
2594}
2595
2596pub(crate) fn check_store_log_op(
2604 method: &Ident,
2605 args: &[Expr],
2606 elem: TyId,
2607 span: Span,
2608 ctx: &mut Ctx,
2609) -> Option<TyId> {
2610 let tys = ctx.tys;
2611 let query = || Ty::Query(elem);
2612 let arity = |n: usize, ctx: &mut Ctx| {
2613 if args.len() != n {
2614 ctx.errors.push(CompileError::new(
2615 "bynk.types.call_arity",
2616 span,
2617 format!(
2618 "`Log.{}` takes {n} argument(s), found {}",
2619 method.name,
2620 args.len()
2621 ),
2622 ));
2623 for a in args {
2624 type_of(a, None, ctx);
2625 }
2626 return false;
2627 }
2628 true
2629 };
2630 let window_arg = |a: &Expr, what: &str, ctx: &mut Ctx| {
2631 if let Some(at) = type_of(a, Some(tys.intern(Ty::Base(BaseType::Instant))), ctx)
2632 && !compatible(at, tys.intern(Ty::Base(BaseType::Instant)), tys)
2633 {
2634 ctx.errors.push(CompileError::new(
2635 "bynk.types.argument_mismatch",
2636 a.span,
2637 format!("{what} expects `Instant`, found `{}`", at.display(tys)),
2638 ));
2639 }
2640 };
2641 match method.name.as_str() {
2642 "append" => {
2644 require_capability(
2645 method.span,
2646 "Clock",
2647 RequirementSource::StoreOp {
2648 kind: StoreKind::Log,
2649 op: method.name.clone(),
2650 },
2651 ctx,
2652 "bynk.store.log_needs_clock",
2653 "`Log.append` stamps the current time, which reads the clock — the handler must declare `given Clock`",
2654 );
2655 if !arity(1, ctx) {
2656 return Some(tys.intern(Ty::Effect(tys.intern(Ty::Unit))));
2657 }
2658 if let Some(at) = type_of(&args[0], Some(elem), ctx)
2659 && !compatible(at, elem, tys)
2660 {
2661 ctx.errors.push(CompileError::new(
2662 "bynk.types.argument_mismatch",
2663 args[0].span,
2664 format!(
2665 "expected `{}`, found `{}`",
2666 elem.display(tys),
2667 at.display(tys)
2668 ),
2669 ));
2670 }
2671 Some(tys.intern(Ty::Effect(tys.intern(Ty::Unit))))
2672 }
2673 "since" | "before" => {
2675 if !arity(1, ctx) {
2676 return Some(tys.intern(query()));
2677 }
2678 window_arg(&args[0], &format!("`Log.{}`", method.name), ctx);
2679 Some(tys.intern(query()))
2680 }
2681 "between" => {
2682 if !arity(2, ctx) {
2683 return Some(tys.intern(query()));
2684 }
2685 window_arg(&args[0], "`Log.between` start", ctx);
2686 window_arg(&args[1], "`Log.between` end", ctx);
2687 Some(tys.intern(query()))
2688 }
2689 "recent" => {
2690 if !arity(1, ctx) {
2691 return Some(tys.intern(query()));
2692 }
2693 check_arg(
2694 &args[0],
2695 tys.intern(Ty::Base(BaseType::Int)),
2696 "the `Log.recent` count",
2697 ctx,
2698 );
2699 Some(tys.intern(query()))
2700 }
2701 "reversed" => {
2702 if !arity(0, ctx) {
2703 return Some(tys.intern(query()));
2704 }
2705 Some(tys.intern(query()))
2706 }
2707 name if is_query_op(name) => {
2709 let r =
2710 check_query_kernel_method(method, QueryOp::from_name(name), args, elem, span, ctx);
2711 par::reject_store_write_in_closure(method, args, ctx);
2712 r
2713 }
2714 other => {
2715 ctx.errors.push(
2716 CompileError::new(
2717 "bynk.store.unknown_op",
2718 method.span,
2719 format!(
2720 "a `Log` store field has no operation `{other}` — `append`, the \
2721 time-window roots (`since`/`before`/`between`/`recent`/`reversed`), \
2722 and the query builders/terminals"
2723 ),
2724 )
2725 .with_note(
2726 "`Log` reads are lazy `Query[T]`; only `append` is effectful and writes",
2727 ),
2728 );
2729 for a in args {
2730 type_of(a, None, ctx);
2731 }
2732 None
2733 }
2734 }
2735}
2736
2737pub(crate) fn check_store_set_op(
2743 method: &Ident,
2744 args: &[Expr],
2745 t: TyId,
2746 span: Span,
2747 ctx: &mut Ctx,
2748) -> Option<TyId> {
2749 let tys = ctx.tys;
2750 let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2751 "add" => (vec![t], tys.intern(Ty::Unit)),
2752 "remove" => (vec![t], tys.intern(Ty::Unit)),
2753 "contains" => (vec![t], tys.intern(Ty::Base(BaseType::Bool))),
2754 "size" => (vec![], tys.intern(Ty::Base(BaseType::Int))),
2755 other => {
2756 ctx.errors.push(
2757 CompileError::new(
2758 "bynk.store.unknown_op",
2759 method.span,
2760 format!(
2761 "a `Set` store field has no operation `{other}` — expected `add`, \
2762 `remove`, `contains`, or `size`"
2763 ),
2764 )
2765 .with_note(
2766 "set algebra (`union`/`intersection`/`difference`) is not in this slice",
2767 ),
2768 );
2769 for a in args {
2770 type_of(a, None, ctx);
2771 }
2772 return None;
2773 }
2774 };
2775 let effect = Ty::Effect(result);
2776 if args.len() != expected.len() {
2777 ctx.errors.push(CompileError::new(
2778 "bynk.types.call_arity",
2779 span,
2780 format!(
2781 "`Set.{}` takes {} argument(s), found {}",
2782 method.name,
2783 expected.len(),
2784 args.len()
2785 ),
2786 ));
2787 for a in args {
2788 type_of(a, None, ctx);
2789 }
2790 return Some(tys.intern(effect));
2791 }
2792 for (a, exp) in args.iter().zip(expected.iter()) {
2793 if let Some(at) = type_of(a, Some(*exp), ctx)
2794 && !compatible(at, *exp, tys)
2795 {
2796 ctx.errors.push(CompileError::new(
2797 "bynk.types.argument_mismatch",
2798 a.span,
2799 format!(
2800 "expected `{}`, found `{}`",
2801 exp.display(tys),
2802 at.display(tys)
2803 ),
2804 ));
2805 }
2806 }
2807 Some(tys.intern(effect))
2808}
2809
2810pub(crate) fn check_store_cell_op(
2818 method: &Ident,
2819 args: &[Expr],
2820 t: TyId,
2821 span: Span,
2822 ctx: &mut Ctx,
2823) -> Option<TyId> {
2824 let tys = ctx.tys;
2825 let tfn = || Ty::Fn {
2826 params: vec![t],
2827 ret: t,
2828 };
2829 let (expected, result): (Vec<TyId>, TyId) = match method.name.as_str() {
2830 "update" => (vec![tys.intern(tfn())], tys.intern(Ty::Unit)),
2831 other => {
2832 ctx.errors.push(
2833 CompileError::new(
2834 "bynk.store.unknown_op",
2835 method.span,
2836 format!("a `Cell` store field has no operation `{other}` — expected `update`"),
2837 )
2838 .with_note(
2839 "a cell is read by its bare name and written with `:=`; `update` is the only \
2840 method-shaped op",
2841 ),
2842 );
2843 for a in args {
2844 type_of(a, None, ctx);
2845 }
2846 return None;
2847 }
2848 };
2849 let effect = Ty::Effect(result);
2850 if args.len() != expected.len() {
2851 ctx.errors.push(CompileError::new(
2852 "bynk.types.call_arity",
2853 span,
2854 format!(
2855 "`Cell.{}` takes {} argument(s), found {}",
2856 method.name,
2857 expected.len(),
2858 args.len()
2859 ),
2860 ));
2861 for a in args {
2862 type_of(a, None, ctx);
2863 }
2864 return Some(tys.intern(effect));
2865 }
2866 for (a, exp) in args.iter().zip(expected.iter()) {
2867 if let Some(at) = type_of(a, Some(*exp), ctx)
2868 && !compatible(at, *exp, tys)
2869 {
2870 ctx.errors.push(CompileError::new(
2871 "bynk.types.argument_mismatch",
2872 a.span,
2873 format!(
2874 "expected `{}`, found `{}`",
2875 exp.display(tys),
2876 at.display(tys)
2877 ),
2878 ));
2879 }
2880 }
2881 Some(tys.intern(effect))
2882}
2883
2884fn receiver_is_generic_static(receiver: &Expr, method: &Ident, ctx: &Ctx) -> bool {
2889 let ExprKind::Ident(id) = &receiver.kind else {
2890 return false;
2891 };
2892 ctx.lookup(id.name.as_str()).is_none()
2893 && ctx
2894 .input
2895 .types
2896 .get(&id.name)
2897 .is_some_and(|d| !d.type_params.is_empty())
2898 && ctx
2899 .input
2900 .methods
2901 .get(&id.name)
2902 .is_some_and(|t| t.statics.contains_key(&method.name))
2903}
2904
2905fn receiver_has_generic_instance_method(recv_ty: TyId, method: &Ident, ctx: &Ctx) -> bool {
2910 let Ty::Named { name, .. } = &*ctx.tys.get(recv_ty) else {
2911 return false;
2912 };
2913 ctx.input
2914 .methods
2915 .get(name)
2916 .and_then(|t| t.instance.get(&method.name))
2917 .is_some_and(|m| !m.type_params.is_empty())
2918}
2919
2920fn reject_method_type_args(method: &Ident, args: &[Expr], span: Span, ctx: &mut Ctx) {
2921 ctx.errors.push(CompileError::new(
2922 "bynk.generics.type_arg_mismatch",
2923 span,
2924 format!(
2925 "`{}` does not take explicit type arguments — only a generic method with type parameters of its own does",
2926 method.name
2927 ),
2928 ));
2929 for a in args {
2930 let _ = type_of(a, None, ctx);
2931 }
2932}
2933
2934fn record_kernel(
2940 ctx: &mut Ctx,
2941 expr_id: ExprId,
2942 recv: TyId,
2943 op: Option<KernelOp>,
2944 method: &Ident,
2945 result: Option<TyId>,
2946) -> Option<TyId> {
2947 match op {
2948 Some(op) => {
2949 ctx.callees.insert(expr_id, Callee::Kernel { recv, op });
2950 }
2951 None => debug_assert!(
2954 result.is_none(),
2955 "bynk internal error (#3164): kernel method `{}` was accepted but has no `KernelOp`",
2956 method.name
2957 ),
2958 }
2959 result
2960}
2961
2962fn check_request_cookies_call(
2965 method: &Ident,
2966 recv_ty: TyId,
2967 args: &[Expr],
2968 span: Span,
2969 expr_id: ExprId,
2970 ctx: &mut Ctx,
2971) -> Option<TyId> {
2972 let kop = RequestCookiesOp::from_name(&method.name);
2973 let r = check_request_cookies_method(method, kop, args, span, ctx);
2974 record_kernel(
2975 ctx,
2976 expr_id,
2977 recv_ty,
2978 kop.map(KernelOp::RequestCookies),
2979 method,
2980 r,
2981 )
2982}
2983
2984fn check_request_cookies_static_call(
2986 method: &Ident,
2987 args: &[Expr],
2988 span: Span,
2989 expr_id: ExprId,
2990 ctx: &mut Ctx,
2991) -> Option<TyId> {
2992 if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestCookies, &method.name) {
2993 ctx.callees.insert(expr_id, Callee::intrinsic(op));
2994 }
2995 check_request_cookies_static(method, args, span, ctx)
2996}
2997
2998fn receiver_names_capability(receiver: &Expr, ctx: &Ctx) -> bool {
3001 matches!(&receiver.kind, ExprKind::Ident(id)
3002 if ctx.caps.capabilities.contains_key(&id.name)
3003 || ctx.caps.declared_capabilities.contains_key(&id.name))
3004 || flatten_ident_chain(receiver).is_some_and(|chain| {
3005 ctx.input
3006 .cross_context
3007 .resolve_cross_capability(&chain)
3008 .is_some()
3009 })
3010}
3011
3012#[allow(clippy::too_many_arguments)]
3013pub(crate) fn check_method_call(
3014 receiver: &Expr,
3015 method: &Ident,
3016 type_args: &[TypeRef],
3017 args: &[Expr],
3018 span: Span,
3019 expected: Option<TyId>,
3020 expr_id: ExprId,
3022 ctx: &mut Ctx,
3023) -> Option<TyId> {
3024 let tys = ctx.tys;
3025 let receiver_is_capability = receiver_names_capability(receiver, ctx);
3041 let value_receiver = ctx.lookup_root_ident(receiver).is_some()
3045 || ctx.root_ident_is_store_field(receiver)
3046 || flatten_ident_chain(receiver).is_none();
3047 let type_args_pending = !type_args.is_empty()
3048 && !matches!(&receiver.kind, ExprKind::Ident(id) if (id.name == JSON || id.name == YAML || id.name == FORM)
3049 && !ctx.input.types.contains_key(id.name.as_str()))
3050 && !receiver_is_capability
3051 && !receiver_is_generic_static(receiver, method, ctx);
3052 if type_args_pending && !value_receiver {
3053 reject_method_type_args(method, args, span, ctx);
3054 return None;
3055 }
3056 if let Some(r) = super::peek::check_peek_call(
3057 receiver, method, type_args, args, span, expected, expr_id, ctx,
3058 ) {
3059 return r;
3060 }
3061 if let Some(r) = super::kernels::check_cookie_call(receiver, method, args, span, expr_id, ctx) {
3062 return r;
3063 }
3064 if let ExprKind::Ident(id) = &receiver.kind
3075 && ctx.lookup(id.name.as_str()).is_none()
3076 && let Some(sig) = ctx.test_services.get(&id.name).cloned()
3077 {
3078 if let Some(unit) = ctx.input.cross_context.self_context.clone() {
3079 ctx.refs
3080 .record_in_unit(id.span, SymbolKind::Service, &id.name, &unit);
3081 }
3082 return check_test_service_address(&sig, id, method, args, expr_id, ctx);
3083 }
3084 if ctx.lookup_root_ident(receiver).is_none() && !ctx.root_ident_is_store_field(receiver) {
3091 if let Some(chain) = flatten_ident_chain(receiver)
3095 && let Some((consumed, cap)) = ctx.input.cross_context.resolve_cross_capability(&chain)
3096 {
3097 if let ExprKind::FieldAccess { field, .. } = &receiver.kind {
3100 ctx.refs
3101 .record_in_unit(field.span, SymbolKind::Capability, &cap, &consumed);
3102 }
3103 return check_cross_context_capability_call(
3104 receiver, &consumed, &cap, method, type_args, args, span, expr_id, ctx,
3105 );
3106 }
3107 if let Some(consumed) = cross_context_prefix(receiver, ctx) {
3108 return check_cross_context_call(receiver, &consumed, method, args, span, expr_id, ctx);
3109 }
3110 if let ExprKind::FieldAccess { .. } = &receiver.kind
3122 && !ctx.root_ident_is_asset(receiver)
3123 && let Some(chain) = flatten_ident_chain(receiver)
3124 && chain.contains('.')
3125 {
3126 let info = &ctx.input.cross_context;
3127 let in_context = info.self_context.is_some();
3128 if in_context && info.resolve_prefix(&chain).is_none() {
3129 ctx.errors.push(
3130 CompileError::new(
3131 "bynk.resolve.unconsumed_context",
3132 receiver.span,
3133 format!(
3134 "`{chain}.{}` looks like a cross-context service call, but `{chain}` is not in this context's `consumes` clauses",
3135 method.name
3136 ),
3137 )
3138 .with_note(
3139 "add a `consumes {chain}` clause at the top of the context, or use an alias and call it through the alias",
3140 ),
3141 );
3142 for a in args {
3143 let _ = type_of(a, None, ctx);
3144 }
3145 return None;
3146 }
3147 }
3148 }
3149 if let ExprKind::Ident(id) = &receiver.kind
3153 && ctx.lookup(id.name.as_str()).is_none()
3154 && (ctx.caps.capabilities.contains_key(&id.name)
3155 || ctx.caps.declared_capabilities.contains_key(&id.name))
3156 {
3157 return check_static_call(id, method, type_args, args, span, expected, expr_id, ctx);
3158 }
3159 if let ExprKind::Ident(id) = &receiver.kind
3165 && ctx.lookup(id.name.as_str()).is_none()
3166 && ctx.input.types.contains_key(&id.name)
3167 {
3168 return check_static_call(id, method, type_args, args, span, expected, expr_id, ctx);
3169 }
3170 if let ExprKind::Ident(id) = &receiver.kind
3174 && ctx.lookup(id.name.as_str()).is_none()
3175 && !ctx.input.types.contains_key(&id.name)
3176 && (id.name == LIST || id.name == MAP || id.name == SET)
3177 {
3178 let ns = if id.name == LIST {
3179 IntrinsicNs::List
3180 } else if id.name == MAP {
3181 IntrinsicNs::Map
3182 } else {
3183 IntrinsicNs::Set
3184 };
3185 if let Some(op) = StaticOp::resolve(ns, &method.name) {
3186 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3187 }
3188 return check_collection_static(id, method, args, span, expected, ctx);
3189 }
3190 if let ExprKind::Ident(id) = &receiver.kind
3194 && (id.name == INT || id.name == FLOAT)
3195 {
3196 let ns = if id.name == INT {
3197 IntrinsicNs::Int
3198 } else {
3199 IntrinsicNs::Float
3200 };
3201 if let Some(op) = StaticOp::resolve(ns, &method.name) {
3202 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3203 }
3204 return check_numeric_parse_static(id, method, args, span, ctx);
3205 }
3206 if let ExprKind::Ident(id) = &receiver.kind
3208 && id.name == DECIMAL
3209 && ctx.lookup(DECIMAL).is_none()
3210 && !ctx.input.types.contains_key(DECIMAL)
3211 {
3212 if let Some(op) = StaticOp::resolve(IntrinsicNs::Decimal, &method.name) {
3213 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3214 }
3215 return check_decimal_static(method, args, span, ctx);
3216 }
3217 if let ExprKind::Ident(id) = &receiver.kind
3220 && id.name == DURATION
3221 && ctx.lookup(DURATION).is_none()
3222 && !ctx.input.types.contains_key(DURATION)
3223 {
3224 if let Some(op) = StaticOp::resolve(IntrinsicNs::Duration, &method.name) {
3225 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3226 }
3227 return check_duration_static(method, args, span, ctx);
3228 }
3229 if let ExprKind::Ident(id) = &receiver.kind
3231 && id.name == INSTANT
3232 && ctx.lookup(INSTANT).is_none()
3233 && !ctx.input.types.contains_key(INSTANT)
3234 {
3235 if let Some(op) = StaticOp::resolve(IntrinsicNs::Instant, &method.name) {
3236 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3237 }
3238 return check_instant_static(method, args, span, ctx);
3239 }
3240 if let ExprKind::Ident(id) = &receiver.kind
3243 && id.name == BYTES
3244 && ctx.lookup(BYTES).is_none()
3245 && !ctx.input.types.contains_key(BYTES)
3246 {
3247 if let Some(op) = StaticOp::resolve(IntrinsicNs::Bytes, &method.name) {
3248 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3249 }
3250 return check_bytes_static(method, args, span, ctx);
3251 }
3252 if let ExprKind::Ident(id) = &receiver.kind
3255 && id.name == TOKEN_CLAIMS
3256 && ctx.lookup(TOKEN_CLAIMS).is_none()
3257 && !ctx.input.types.contains_key(TOKEN_CLAIMS)
3258 {
3259 if let Some(op) = StaticOp::resolve(IntrinsicNs::TokenClaims, &method.name) {
3260 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3261 }
3262 return check_token_claims_static(method, args, span, ctx);
3263 }
3264 if let ExprKind::Ident(id) = &receiver.kind
3267 && id.name == REQUEST_HEADERS
3268 && ctx.lookup(REQUEST_HEADERS).is_none()
3269 && !ctx.input.types.contains_key(REQUEST_HEADERS)
3270 {
3271 if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestHeaders, &method.name) {
3272 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3273 }
3274 return check_request_headers_static(method, args, span, ctx);
3275 }
3276 if let ExprKind::Ident(id) = &receiver.kind
3279 && id.name == REQUEST_QUERY
3280 && ctx.lookup(REQUEST_QUERY).is_none()
3281 && !ctx.input.types.contains_key(REQUEST_QUERY)
3282 {
3283 if let Some(op) = StaticOp::resolve(IntrinsicNs::RequestQuery, &method.name) {
3284 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3285 }
3286 return check_request_query_static(method, args, span, ctx);
3287 }
3288 if let ExprKind::Ident(id) = &receiver.kind
3291 && id.name == REQUEST_COOKIES
3292 && ctx.lookup(REQUEST_COOKIES).is_none()
3293 && !ctx.input.types.contains_key(REQUEST_COOKIES)
3294 {
3295 return check_request_cookies_static_call(method, args, span, expr_id, ctx);
3296 }
3297 if let ExprKind::Ident(id) = &receiver.kind
3299 && id.name == JSON
3300 && ctx.lookup(JSON).is_none()
3301 && !ctx.input.types.contains_key(JSON)
3302 {
3303 if let Some(op) = StaticOp::resolve(IntrinsicNs::Json, &method.name) {
3304 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3305 }
3306 return check_json_static(JSON, method, type_args, args, span, expected, ctx);
3307 }
3308 if let ExprKind::Ident(id) = &receiver.kind
3310 && id.name == YAML
3311 && ctx.lookup(YAML).is_none()
3312 && !ctx.input.types.contains_key(YAML)
3313 {
3314 if let Some(op) = StaticOp::resolve(IntrinsicNs::Yaml, &method.name) {
3315 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3316 }
3317 return check_json_static(YAML, method, type_args, args, span, expected, ctx);
3318 }
3319 if let ExprKind::Ident(id) = &receiver.kind
3321 && id.name == FORM
3322 && ctx.lookup(FORM).is_none()
3323 && !ctx.input.types.contains_key(FORM)
3324 {
3325 if let Some(op) = StaticOp::resolve(IntrinsicNs::Form, &method.name) {
3326 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3327 }
3328 return check_json_static(FORM, method, type_args, args, span, expected, ctx);
3329 }
3330 if let ExprKind::Ident(id) = &receiver.kind
3332 && id.name == STREAM
3333 && ctx.lookup(STREAM).is_none()
3334 && !ctx.input.types.contains_key(STREAM)
3335 {
3336 if let Some(op) = StaticOp::resolve(IntrinsicNs::Stream, &method.name) {
3337 ctx.callees.insert(expr_id, Callee::intrinsic(op));
3338 }
3339 return check_stream_static(method, args, span, ctx);
3340 }
3341 let recv_expected = match (expected, method.name.as_str()) {
3346 (Some(t), "insert") => peel_to_map(t, tys)
3347 .map(|(k, v)| tys.intern(Ty::Map(k, v)))
3348 .or_else(|| peel_to_set(t, tys).map(|e| tys.intern(Ty::Set(e)))),
3349 (Some(t), "remove") => peel_to_set(t, tys).map(|e| tys.intern(Ty::Set(e))),
3350 (Some(t), "prepend" | "append" | "concat") => {
3351 peel_to_list(t, tys).map(|e| tys.intern(Ty::List(e)))
3352 }
3353 _ => None,
3354 };
3355 let recv_ty = type_of(receiver, recv_expected, ctx)?;
3356 if type_args_pending && !receiver_has_generic_instance_method(recv_ty, method, ctx) {
3357 reject_method_type_args(method, args, span, ctx);
3358 return None;
3359 }
3360 match &*tys.get(recv_ty) {
3365 Ty::List(elem) => {
3366 let kop = ListOp::from_name(&method.name);
3367 let r = check_list_kernel_method(method, kop, args, *elem, span, ctx);
3368 par::reject_store_write_in_closure(method, args, ctx);
3369 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::List), method, r);
3370 }
3371 Ty::Query(elem) => {
3373 let kop = QueryOp::from_name(&method.name);
3374 let r = check_query_kernel_method(method, kop, args, *elem, span, ctx);
3375 par::reject_store_write_in_closure(method, args, ctx);
3376 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Query), method, r);
3377 }
3378 Ty::Stream(elem) => {
3380 let kop = StreamOp::from_name(&method.name);
3381 let r = check_stream_kernel_method(method, kop, args, *elem, span, ctx);
3382 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Stream), method, r);
3383 }
3384 Ty::Connection(frame) => {
3388 let kop = ConnectionOp::from_name(&method.name);
3389 let r = check_connection_method(method, kop, args, *frame, span, ctx);
3390 return record_kernel(
3391 ctx,
3392 expr_id,
3393 recv_ty,
3394 kop.map(KernelOp::Connection),
3395 method,
3396 r,
3397 );
3398 }
3399 Ty::TestConnection(frame) => {
3401 let kop = TestConnectionOp::from_name(&method.name);
3402 let r = check_test_connection_method(method, kop, args, *frame, span, ctx);
3403 return record_kernel(
3404 ctx,
3405 expr_id,
3406 recv_ty,
3407 kop.map(KernelOp::TestConnection),
3408 method,
3409 r,
3410 );
3411 }
3412 Ty::Map(key, val) => {
3413 let kop = MapOp::from_name(&method.name);
3414 let r = check_map_kernel_method(method, kop, args, *key, *val, span, ctx);
3415 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Map), method, r);
3416 }
3417 Ty::Set(elem) => {
3419 let kop = SetOp::from_name(&method.name);
3420 let r = check_set_kernel_method(method, kop, args, *elem, span, ctx);
3421 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Set), method, r);
3422 }
3423 Ty::Base(base @ (BaseType::Int | BaseType::Float)) => {
3431 let op = match *base {
3432 BaseType::Int => IntOp::from_name(&method.name).map(KernelOp::Int),
3433 _ => FloatOp::from_name(&method.name).map(KernelOp::Float),
3434 };
3435 let r = check_numeric_kernel_method(method, op, args, *base, span, ctx);
3436 return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3437 }
3438 Ty::Base(BaseType::Duration) => {
3440 let kop = DurationOp::from_name(&method.name);
3441 let r = check_duration_kernel_method(method, kop, args, span, ctx);
3442 return record_kernel(
3443 ctx,
3444 expr_id,
3445 recv_ty,
3446 kop.map(KernelOp::Duration),
3447 method,
3448 r,
3449 );
3450 }
3451 Ty::Base(BaseType::Instant) => {
3453 let kop = InstantOp::from_name(&method.name);
3454 let r = check_instant_kernel_method(method, kop, args, span, ctx);
3455 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Instant), method, r);
3456 }
3457 Ty::RequestHeaders => {
3460 let kop = RequestHeadersOp::from_name(&method.name);
3461 let r = check_request_headers_method(method, kop, args, span, ctx);
3462 return record_kernel(
3463 ctx,
3464 expr_id,
3465 recv_ty,
3466 kop.map(KernelOp::RequestHeaders),
3467 method,
3468 r,
3469 );
3470 }
3471 Ty::HttpResult(_) => {
3473 let kop = HttpResultOp::from_name(&method.name);
3474 let r = check_http_result_method(method, kop, recv_ty, args, span, ctx);
3475 return record_kernel(
3476 ctx,
3477 expr_id,
3478 recv_ty,
3479 kop.map(KernelOp::HttpResult),
3480 method,
3481 r,
3482 );
3483 }
3484 Ty::RequestQuery => {
3486 let kop = RequestQueryOp::from_name(&method.name);
3487 let r = check_request_query_method(method, kop, args, span, ctx);
3488 return record_kernel(
3489 ctx,
3490 expr_id,
3491 recv_ty,
3492 kop.map(KernelOp::RequestQuery),
3493 method,
3494 r,
3495 );
3496 }
3497 Ty::RequestCookies => {
3499 return check_request_cookies_call(method, recv_ty, args, span, expr_id, ctx);
3500 }
3501 Ty::TokenClaims => {
3503 let kop = TokenClaimsOp::from_name(&method.name);
3504 let r = check_token_claims_method(method, kop, args, span, ctx);
3505 return record_kernel(
3506 ctx,
3507 expr_id,
3508 recv_ty,
3509 kop.map(KernelOp::TokenClaims),
3510 method,
3511 r,
3512 );
3513 }
3514 Ty::Base(BaseType::Bytes) => {
3516 let kop = BytesOp::from_name(&method.name);
3517 let r = check_bytes_kernel_method(method, kop, args, span, ctx);
3518 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Bytes), method, r);
3519 }
3520 Ty::Base(BaseType::Decimal) => {
3522 let kop = DecimalOp::from_name(&method.name);
3523 let r = check_decimal_kernel_method(method, kop, args, span, ctx);
3524 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Decimal), method, r);
3525 }
3526 Ty::Base(BaseType::String) => {
3528 let kop = StringOp::from_name(&method.name);
3529 let r = check_string_kernel_method(method, kop, args, span, ctx);
3530 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::String), method, r);
3531 }
3532 Ty::Option(inner) => {
3534 let kop = OptionOp::from_name(&method.name);
3535 let r = check_option_kernel_method(method, kop, args, *inner, span, ctx);
3536 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Option), method, r);
3537 }
3538 Ty::Result(ok, err) => {
3539 let kop = ResultOp::from_name(&method.name);
3540 let r = check_result_kernel_method(method, kop, args, *ok, *err, span, ctx);
3541 return record_kernel(ctx, expr_id, recv_ty, kop.map(KernelOp::Result), method, r);
3542 }
3543 Ty::Effect(inner) => {
3548 if matches!(method.name.as_str(), "within" | "race" | "detach") {
3553 let op = EffectOp::from_name(&method.name).map(KernelOp::Effect);
3554 let r = check_effect_method(method, receiver, args, *inner, span, ctx);
3555 return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3556 }
3557 if let Ty::Result(ok, err) = &*tys.get(*inner) {
3558 let kop = EffectResultOp::from_name(&method.name);
3559 let r = check_effect_result_kernel_method(method, kop, args, *ok, *err, span, ctx);
3560 return record_kernel(
3561 ctx,
3562 expr_id,
3563 recv_ty,
3564 kop.map(KernelOp::EffectResult),
3565 method,
3566 r,
3567 );
3568 }
3569 }
3570 _ => {}
3571 }
3572 let type_name = match &*tys.get(recv_ty) {
3574 Ty::Named { name, .. } => name.clone(),
3575 _ => {
3576 ctx.errors.push(CompileError::new(
3577 "bynk.types.method_on_non_named_type",
3578 method.span,
3579 format!(
3580 "type `{}` has no methods — only user-declared types support method calls",
3581 recv_ty.display(tys)
3582 ),
3583 ));
3584 return None;
3585 }
3586 };
3587 if let Some(agent) = ctx.input.agents.get(&type_name).cloned() {
3591 let Some(handler) = agent.handlers.iter().find(|h| {
3592 h.method_name
3593 .as_ref()
3594 .is_some_and(|n| n.name == method.name)
3595 }) else {
3596 ctx.errors.push(CompileError::new(
3597 "bynk.agent.handler_not_found",
3598 method.span,
3599 format!(
3600 "agent `{}` has no handler named `{}`",
3601 type_name, method.name
3602 ),
3603 ));
3604 for a in args {
3605 let _ = type_of(a, None, ctx);
3606 }
3607 return None;
3608 };
3609 ctx.callees.insert(
3610 expr_id,
3611 Callee::Agent {
3612 agent: type_name.clone(),
3613 handler: method.name.clone(),
3614 },
3615 );
3616 ctx.refs.record(
3621 method.span,
3622 SymbolKind::Handler,
3623 &format!("{type_name}.{}", method.name),
3624 );
3625 if handler.params.len() != args.len() {
3626 ctx.errors.push(CompileError::new(
3627 "bynk.agent.handler_arity",
3628 method.span,
3629 format!(
3630 "agent handler `{}.{}` expects {} argument(s), but {} were given",
3631 type_name,
3632 method.name,
3633 handler.params.len(),
3634 args.len()
3635 ),
3636 ));
3637 for a in args {
3638 let _ = type_of(a, None, ctx);
3639 }
3640 return None;
3641 }
3642 for (p, arg) in handler.params.iter().zip(args.iter()) {
3643 let pty = resolve_type_ref(&p.type_ref, &ctx.input.types, tys);
3644 let arg_ty = type_of(arg, pty, ctx);
3645 if let (Some(a), Some(p_ty)) = (arg_ty, pty.as_ref())
3646 && !compatible(a, *p_ty, tys)
3647 {
3648 ctx.errors.push(CompileError::new(
3649 "bynk.types.argument_mismatch",
3650 arg.span,
3651 format!(
3652 "argument has type `{}`, but `{}.{}` expects `{}`",
3653 a.display(tys),
3654 type_name,
3655 method.name,
3656 p_ty.display(tys)
3657 ),
3658 ));
3659 }
3660 }
3661 return resolve_type_ref(&handler.return_type, &ctx.input.types, tys);
3662 }
3663 let table = ctx
3664 .input
3665 .methods
3666 .get(&type_name)
3667 .cloned()
3668 .unwrap_or_default();
3669 let Some(method_decl) = table.instance.get(&method.name).cloned() else {
3670 if let Ty::Named {
3680 kind: NamedKind::Refined(base),
3681 ..
3682 } = &*tys.get(recv_ty)
3683 {
3684 let op = KernelOp::for_base(*base, &method.name);
3685 let r = match base {
3686 BaseType::Int | BaseType::Float => {
3687 check_numeric_kernel_method(method, op, args, *base, span, ctx)
3688 }
3689 BaseType::String => check_string_kernel_method(
3690 method,
3691 StringOp::from_name(&method.name),
3692 args,
3693 span,
3694 ctx,
3695 ),
3696 BaseType::Duration => check_duration_kernel_method(
3697 method,
3698 DurationOp::from_name(&method.name),
3699 args,
3700 span,
3701 ctx,
3702 ),
3703 BaseType::Instant => check_instant_kernel_method(
3704 method,
3705 InstantOp::from_name(&method.name),
3706 args,
3707 span,
3708 ctx,
3709 ),
3710 BaseType::Bytes => check_bytes_kernel_method(
3711 method,
3712 BytesOp::from_name(&method.name),
3713 args,
3714 span,
3715 ctx,
3716 ),
3717 BaseType::Decimal => check_decimal_kernel_method(
3718 method,
3719 DecimalOp::from_name(&method.name),
3720 args,
3721 span,
3722 ctx,
3723 ),
3724 BaseType::Bool => None,
3726 };
3727 if !matches!(base, BaseType::Bool) {
3728 return record_kernel(ctx, expr_id, recv_ty, op, method, r);
3729 }
3730 }
3731 ctx.errors.push(CompileError::new(
3732 "bynk.types.method_not_found",
3733 method.span,
3734 format!(
3735 "type `{}` has no instance method named `{}`",
3736 type_name, method.name
3737 ),
3738 ));
3739 return None;
3740 };
3741 ctx.refs.record(
3746 method.span,
3747 SymbolKind::Method,
3748 &format!("{type_name}.{}", method.name),
3749 );
3750 ctx.callees.insert(
3751 expr_id,
3752 Callee::Method(Arc::clone(&method_decl), Vec::new()),
3753 );
3754 let recv_type_params: Vec<String> = ctx
3762 .input
3763 .types
3764 .get(&type_name)
3765 .map(|d| d.type_params.iter().map(|p| p.name.name.clone()).collect())
3766 .unwrap_or_default();
3767 if !recv_type_params.is_empty() || !method_decl.type_params.is_empty() {
3768 let ret = check_generic_method_call(
3769 &type_name,
3770 &recv_type_params,
3771 Some(recv_ty),
3772 &method_decl,
3773 method,
3774 type_args,
3775 args,
3776 expected,
3777 ctx,
3778 );
3779 if let Some(witnesses) = ctx.last_witness.take() {
3781 ctx.callees
3782 .insert(expr_id, Callee::Method(Arc::clone(&method_decl), witnesses));
3783 }
3784 return ret;
3785 }
3786 if method_decl.params.len() != args.len() {
3788 ctx.errors.push(
3789 CompileError::new(
3790 "bynk.types.method_arity",
3791 method.span,
3792 format!(
3793 "method `{}.{}` expects {} argument(s), but {} were given",
3794 type_name,
3795 method.name,
3796 method_decl.params.len(),
3797 args.len()
3798 ),
3799 )
3800 .with_label(method_decl.name.ident().span, "method declared here"),
3801 );
3802 for a in args {
3803 let _ = type_of(a, None, ctx);
3804 }
3805 return None;
3806 }
3807 let mut ok = true;
3808 for (i, (param, arg)) in method_decl.params.iter().zip(args.iter()).enumerate() {
3809 record_param_hint(ctx.hints, ¶m.name.name, arg);
3810 let expected = resolve_type_ref(¶m.type_ref, &ctx.input.types, tys);
3811 let actual = type_of(arg, expected, ctx);
3812 let (Some(actual), Some(expected)) = (actual, expected) else {
3813 ok = false;
3814 continue;
3815 };
3816 if !compatible(actual, expected, tys) {
3817 ctx.errors.push(CompileError::new(
3818 "bynk.types.argument_mismatch",
3819 arg.span,
3820 format!(
3821 "argument {} to `{}.{}` has type `{}`, but parameter `{}` expects `{}`",
3822 i + 1,
3823 type_name,
3824 method.name,
3825 actual.display(tys),
3826 param.name.name,
3827 expected.display(tys)
3828 ),
3829 ));
3830 ok = false;
3831 }
3832 }
3833 let _ = span;
3834 if !ok {
3835 return None;
3836 }
3837 resolve_type_ref(&method_decl.return_type, &ctx.input.types, tys)
3838}
3839
3840#[allow(clippy::too_many_arguments)]
3855fn check_generic_method_call(
3856 type_name: &str,
3857 recv_type_params: &[String],
3858 recv_ty: Option<TyId>,
3859 method_decl: &FnDecl,
3860 method: &Ident,
3861 type_args: &[TypeRef],
3862 args: &[Expr],
3863 call_expected: Option<TyId>,
3864 ctx: &mut Ctx,
3865) -> Option<TyId> {
3866 let tys = ctx.tys;
3867 let is_static = recv_ty.is_none();
3868 let what = if is_static { "static method" } else { "method" };
3869 let mut vars: HashSet<String> = recv_type_params.iter().cloned().collect();
3871 for tp in &method_decl.type_params {
3872 vars.insert(tp.name.name.clone());
3873 }
3874 if method_decl.params.len() != args.len() {
3876 ctx.errors.push(
3877 CompileError::new(
3878 "bynk.types.method_arity",
3879 method.span,
3880 format!(
3881 "{what} `{}.{}` expects {} argument(s), but {} were given",
3882 type_name,
3883 method.name,
3884 method_decl.params.len(),
3885 args.len()
3886 ),
3887 )
3888 .with_label(method_decl.name.ident().span, "method declared here"),
3889 );
3890 for a in args {
3891 let _ = type_of(a, None, ctx);
3892 }
3893 return None;
3894 }
3895 let mut subst: HashMap<String, TyId> = HashMap::new();
3902 if let Some(recv_ty) = recv_ty
3903 && let Ty::Named {
3904 args: recv_args, ..
3905 } = &*tys.get(recv_ty)
3906 && recv_args.len() == recv_type_params.len()
3907 {
3908 for (name, arg) in recv_type_params.iter().zip(recv_args.iter()) {
3909 subst.insert(name.clone(), *arg);
3910 }
3911 }
3912 let mut all_params: Vec<String> = Vec::new();
3915 if is_static {
3916 all_params.extend(recv_type_params.iter().cloned());
3917 }
3918 all_params.extend(
3919 method_decl
3920 .type_params
3921 .iter()
3922 .map(|tp| tp.name.name.clone()),
3923 );
3924 if !type_args.is_empty() {
3925 if type_args.len() != all_params.len() {
3926 ctx.errors.push(CompileError::new(
3927 "bynk.generics.type_arg_mismatch",
3928 method.span,
3929 format!(
3930 "`{}.{}` takes {} type argument(s), but {} were given",
3931 type_name,
3932 method.name,
3933 all_params.len(),
3934 type_args.len()
3935 ),
3936 ));
3937 for a in args {
3938 let _ = type_of(a, None, ctx);
3939 }
3940 return None;
3941 }
3942 for (name, ta) in all_params.iter().zip(type_args) {
3943 let Some(ty) = resolve_expr_type_ref(ta, ctx) else {
3944 for a in args {
3946 let _ = type_of(a, None, ctx);
3947 }
3948 return None;
3949 };
3950 subst.insert(name.clone(), ty);
3951 }
3952 }
3953 let var_params: Vec<Option<TyId>> = method_decl
3956 .params
3957 .iter()
3958 .map(|p| resolve_type_ref_in(&p.type_ref, &ctx.input.types, &vars, tys))
3959 .collect();
3960 let ret_pattern = resolve_type_ref_in(&method_decl.return_type, &ctx.input.types, &vars, tys)?;
3961
3962 let mut arg_tys: Vec<Option<TyId>> = vec![None; args.len()];
3963 for (i, arg) in args.iter().enumerate() {
3965 if matches!(arg.kind, ExprKind::Lambda(_)) {
3966 continue;
3967 }
3968 let expected = var_params[i].map(|p| substitute(p, &subst, tys));
3969 let ty = type_of(arg, expected, ctx);
3970 if let (Some(pattern), Some(actual)) = (var_params[i], ty)
3971 && !unify(pattern, actual, &mut subst, tys)
3972 {
3973 ctx.errors.push(CompileError::new(
3974 "bynk.generics.type_arg_mismatch",
3975 arg.span,
3976 format!(
3977 "argument {} infers a type for `{}.{}`'s type parameter that conflicts with an earlier argument or the receiver",
3978 i + 1,
3979 type_name,
3980 method.name
3981 ),
3982 ));
3983 return None;
3984 }
3985 arg_tys[i] = ty;
3986 }
3987 ground_from_expected(ret_pattern, call_expected, &all_params, &mut subst, ctx);
3990 for (i, arg) in args.iter().enumerate() {
3992 if !matches!(arg.kind, ExprKind::Lambda(_)) {
3993 continue;
3994 }
3995 let expected = var_params[i].map(|p| substitute(p, &subst, tys));
3996 let params_unconstrained = expected.is_some_and(|e| {
3997 matches!(&*tys.get(e), Ty::Fn { params, .. }
3998 if params.iter().any(|p| contains_var(*p, tys)))
3999 });
4000 let fully_annotated = matches!(
4001 &arg.kind,
4002 ExprKind::Lambda(l) if l.params.iter().all(|p| lambda_param_is_typed(p, ctx))
4003 );
4004 if params_unconstrained && !fully_annotated {
4005 ctx.errors.push(
4006 CompileError::new(
4007 "bynk.generics.uninferable_type_arg",
4008 arg.span,
4009 format!(
4010 "the lambda's parameter types depend on `{}.{}`'s type parameters, which the receiver and other arguments do not determine",
4011 type_name, method.name
4012 ),
4013 )
4014 .with_note("annotate the lambda's parameters"),
4015 );
4016 return None;
4017 }
4018 let ty = if params_unconstrained {
4019 type_of(arg, None, ctx)
4020 } else {
4021 type_of(arg, expected, ctx)
4022 };
4023 if let (Some(pattern), Some(actual)) = (var_params[i], ty)
4024 && !unify(pattern, actual, &mut subst, tys)
4025 {
4026 ctx.errors.push(CompileError::new(
4027 "bynk.generics.type_arg_mismatch",
4028 arg.span,
4029 format!(
4030 "the lambda's type conflicts with `{}.{}`'s inferred type arguments",
4031 type_name, method.name
4032 ),
4033 ));
4034 return None;
4035 }
4036 arg_tys[i] = ty;
4037 }
4038 for name in &all_params {
4042 if !subst.contains_key(name) {
4043 let mut err = CompileError::new(
4044 "bynk.generics.uninferable_type_arg",
4045 method.span,
4046 if is_static {
4047 format!(
4048 "type parameter `{name}` of `{}.{}` is neither inferable from the arguments nor given explicitly",
4049 type_name, method.name
4050 )
4051 } else {
4052 format!(
4053 "type parameter `{name}` of `{}.{}` is not inferable from the receiver or the arguments",
4054 type_name, method.name
4055 )
4056 },
4057 );
4058 if let Some(tp) = method_decl
4059 .type_params
4060 .iter()
4061 .find(|tp| &tp.name.name == name)
4062 {
4063 err = err.with_label(tp.span, "declared here");
4064 }
4065 if is_static {
4066 err = err.with_note(
4067 "annotate the binding, or give explicit type arguments: `Type.method[T](…)`",
4068 );
4069 }
4070 ctx.errors.push(err);
4071 return None;
4072 }
4073 }
4074 let mut ok = true;
4076 for (i, (pattern, arg)) in var_params.iter().zip(args).enumerate() {
4077 record_param_hint(ctx.hints, &method_decl.params[i].name.name, arg);
4078 let (Some(pattern), Some(arg_ty)) = (pattern, arg_tys[i].as_ref()) else {
4079 continue;
4080 };
4081 let ground = substitute(*pattern, &subst, tys);
4082 if !compatible(*arg_ty, ground, tys) {
4083 ctx.errors.push(CompileError::new(
4084 "bynk.types.argument_mismatch",
4085 arg.span,
4086 format!(
4087 "argument {} to `{}.{}` has type `{}`, but `{}` is expected",
4088 i + 1,
4089 type_name,
4090 method.name,
4091 arg_ty.display(tys),
4092 ground.display(tys)
4093 ),
4094 ));
4095 ok = false;
4096 }
4097 }
4098 if !ok {
4099 return None;
4100 }
4101 let decl = ctx.input.methods.get(type_name).and_then(|t| {
4105 t.instance
4106 .get(&method.name)
4107 .or_else(|| t.statics.get(&method.name))
4108 .cloned()
4109 });
4110 let compared = match &decl {
4111 Some(decl) if std::ptr::eq(decl.as_ref(), method_decl) => {
4112 super::equality::compared_type_params(decl, ctx)
4113 }
4114 _ => Default::default(),
4115 };
4116 let recv_decl = ctx.input.types.get(type_name);
4117 let declared_eq = |name: &str| {
4118 recv_decl.is_some_and(|d| {
4121 d.type_params
4122 .iter()
4123 .any(|tp| tp.name.name == name && super::equality::has_eq(&tp.bounds))
4124 }) || method_decl
4125 .type_params
4126 .iter()
4127 .any(|tp| tp.name.name == name && super::equality::has_eq(&tp.bounds))
4128 || method_decl
4129 .where_bounds
4130 .iter()
4131 .any(|wb| wb.param.name == name && super::equality::has_eq(&wb.bounds))
4132 };
4133 let mut eq_params: Vec<(String, Option<Span>)> = method_decl
4134 .type_params
4135 .iter()
4136 .map(|tp| (tp.name.name.clone(), Some(tp.span)))
4137 .collect();
4138 eq_params.extend(recv_type_params.iter().map(|p| (p.clone(), None)));
4139 let ord_params = super::ordering::witness_params(method_decl, &ctx.input.types);
4140 let key_params = super::keying::key_params(method_decl, &ctx.input.types);
4141 eq_params.retain(|(p, _)| {
4142 (declared_eq(p) || compared.contains(p))
4143 && !ord_params.iter().any(|o| o == p)
4144 && !key_params.iter().any(|k| k == p)
4145 });
4146 let callee = format!("{type_name}.{}", method.name);
4147 if !super::equality::check_declared_eq_args(&callee, method.span, &eq_params, &subst, ctx) {
4148 return None;
4149 }
4150 let witnesses = super::codable::check_declared_witness_args(
4151 &callee,
4152 method.span,
4153 &super::codable::witness_list(method_decl, &ctx.input.types),
4154 &subst,
4155 ctx,
4156 )?;
4157 if !super::keying::check_declared_key_args(&callee, method.span, &key_params, &subst, ctx) {
4158 return None;
4159 }
4160 if !witnesses.is_empty() {
4161 ctx.last_witness = Some(witnesses);
4162 }
4163 if !all_params.is_empty() && type_args.is_empty() {
4167 let rendered: Option<Vec<String>> = all_params
4168 .iter()
4169 .map(|n| subst.get(n).map(|t| t.display(tys)))
4170 .collect();
4171 if let Some(parts) = rendered {
4172 ctx.hints
4173 .record(method.span, format!("[{}]", parts.join(", ")));
4174 }
4175 }
4176 Some(substitute(ret_pattern, &subst, tys))
4177}
4178
4179fn check_test_service_address(
4197 sig: &TestServiceSig,
4198 id: &Ident,
4199 method: &Ident,
4200 args: &[Expr],
4201 expr_id: ExprId,
4203 ctx: &mut Ctx,
4204) -> Option<TyId> {
4205 use bynk_syntax::ast::{ExprKind as EK, HandlerKind};
4206
4207 if method.name == "call" {
4209 ctx.callees.insert(
4210 expr_id,
4211 Callee::TestService {
4212 service: id.name.clone(),
4213 address: HandlerAddress::Call,
4214 extra_headers: false,
4215 },
4216 );
4217 let Some(handler) = sig.call_handler() else {
4218 let message = match &sig.protocol {
4219 Some(protocol) => format!(
4220 "`{}` is a `from {protocol}` service and has no `on call` handler to invoke",
4221 id.name
4222 ),
4223 None => format!("service `{}` has no `on call` handler to invoke", id.name),
4224 };
4225 ctx.errors.push(
4226 CompileError::new("bynk.test.service_no_call_handler", method.span, message)
4227 .with_note(
4228 "call an `on call` service with `svc.call(...)`, an http route with `svc.GET(\"/path\")`, cron with `svc.schedule(\"…\")`, or a queue with `svc.message(m)`",
4229 ),
4230 );
4231 for a in args {
4232 let _ = type_of(a, None, ctx);
4233 }
4234 return None;
4235 };
4236 let params = handler.params.clone();
4237 check_address_args(&id.name, "call", ¶ms, args, method.span, ctx);
4238 return handler_outcome(handler, ctx);
4239 }
4240
4241 if sig.ws_frames.is_some() && matches!(method.name.as_str(), "open" | "message" | "close") {
4244 return check_ws_address(sig, id, method, args, expr_id, ctx);
4245 }
4246
4247 if bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some() {
4252 ctx.callees.insert(
4253 expr_id,
4254 Callee::TestService {
4255 service: id.name.clone(),
4256 address: http_address(method, None),
4257 extra_headers: false,
4258 },
4259 );
4260 if let Some(first) = args.first()
4265 && !matches!(first.kind, EK::StrLit(_))
4266 && is_asset_value(first, ctx)
4267 {
4268 let _ = type_of(first, None, ctx);
4269 if sig.protocol.as_deref() != Some("http") {
4272 ctx.errors.push(
4273 CompileError::new(
4274 "bynk.test.service_bad_address",
4275 method.span,
4276 format!(
4277 "`{}` is not a `from http` service, so it cannot fetch an asset",
4278 id.name
4279 ),
4280 )
4281 .with_note("fetch an asset through one of the target's `from http` services: `api.GET(asset)`"),
4282 );
4283 for a in &args[1..] {
4286 let _ = type_of(a, None, ctx);
4287 }
4288 return None;
4289 }
4290 if method.name != "GET" {
4291 ctx.errors.push(
4292 CompileError::new(
4293 "bynk.test.asset_address_method",
4294 method.span,
4295 format!(
4296 "an asset is fetched with `{}.GET(asset)`, not `{}`",
4297 id.name, method.name
4298 ),
4299 )
4300 .with_note(
4301 "the platform serves an asset to `GET` and answers every other method with `405`",
4302 ),
4303 );
4304 }
4305 if args.len() > 1 {
4306 ctx.errors.push(CompileError::new(
4307 "bynk.test.service_call_arity",
4308 args[1].span,
4309 format!(
4310 "`{}.{}(asset)` takes the asset alone; remove the other arguments",
4311 id.name, method.name
4312 ),
4313 ));
4314 for a in &args[1..] {
4315 let _ = type_of(a, None, ctx);
4316 }
4317 }
4318 ctx.callees.insert(
4319 expr_id,
4320 Callee::TestAssetFetch {
4321 service: id.name.clone(),
4322 },
4323 );
4324 let unit = ctx.tys.intern(Ty::Unit);
4326 return Some(effect_of(ctx.tys.intern(Ty::HttpResult(unit)), ctx));
4327 }
4328 let Some(EK::StrLit(path)) = args.first().map(|a| &a.kind) else {
4329 ctx.errors.push(
4330 CompileError::new(
4331 "bynk.test.service_bad_address",
4332 method.span,
4333 format!(
4334 "`{}.{}` addresses an http route, so its first argument must be the route pattern string (e.g. `\"/todos\"`)",
4335 id.name, method.name
4336 ),
4337 ),
4338 );
4339 for a in args {
4340 let _ = type_of(a, None, ctx);
4341 }
4342 return None;
4343 };
4344 ctx.callees.insert(
4349 expr_id,
4350 Callee::TestService {
4351 service: id.name.clone(),
4352 address: http_address(method, Some(path)),
4353 extra_headers: false,
4354 },
4355 );
4356 let matched = sig.handlers.iter().find(|h| {
4357 matches!(&h.kind, HandlerKind::Http { method: m, path: p } if m.as_str() == method.name && p == path)
4358 });
4359 let Some(handler) = matched else {
4360 let path_declared = sig
4368 .handlers
4369 .iter()
4370 .any(|h| matches!(&h.kind, HandlerKind::Http { path: p, .. } if p == path));
4371 if path_declared {
4372 let _ = type_of(&args[0], None, ctx);
4373 if args.len() > 1 {
4377 ctx.errors.push(
4378 CompileError::new(
4379 "bynk.test.service_call_arity",
4380 method.span,
4381 format!(
4382 "`{}.{}(\"{}\")` is a wrong-method `405` test and takes only the route path, but {} argument(s) were given",
4383 id.name,
4384 method.name,
4385 path,
4386 args.len() - 1
4387 ),
4388 )
4389 .with_note("a wrong-method call reaches no handler, so it passes no body or params"),
4390 );
4391 for a in &args[1..] {
4392 let _ = type_of(a, None, ctx);
4393 }
4394 }
4395 let unit = ctx.tys.intern(Ty::Unit);
4396 return Some(effect_of(ctx.tys.intern(Ty::HttpOutcome(unit)), ctx));
4397 }
4398 ctx.errors.push(
4399 CompileError::new(
4400 "bynk.test.service_unknown_route",
4401 method.span,
4402 format!(
4403 "`{}` declares no route at `\"{}\"` (no handler for any method)",
4404 id.name, path
4405 ),
4406 )
4407 .with_note("the path must match a declared route; drive a wrong method against an existing path to test the `405` fall-through"),
4408 );
4409 for a in args {
4410 let _ = type_of(a, None, ctx);
4411 }
4412 return None;
4413 };
4414 let params = handler.params.clone();
4415 let _ = type_of(&args[0], None, ctx);
4417 let mut positional = &args[1..];
4418 let declares_headers = params.iter().any(|p| {
4424 p.name.name == "headers"
4425 && matches!(p.type_ref, bynk_syntax::ast::TypeRef::RequestHeaders(_))
4426 });
4427 let trailing = if positional.len() == params.len() + 1
4428 && let Some((last, rest)) = positional.split_last()
4429 && !matches!(last.kind, EK::Wire(_))
4430 {
4431 let is_headers = type_of(last, None, ctx)
4432 .is_some_and(|t| matches!(&*ctx.tys.get(t), Ty::RequestHeaders));
4433 Some((last, rest, is_headers))
4434 } else {
4435 None
4436 };
4437 match trailing {
4438 Some((last, rest, true)) if !declares_headers => {
4439 positional = rest;
4440 check_extra_headers_authorization(last, ctx);
4441 ctx.callees.insert(
4442 expr_id,
4443 Callee::TestService {
4444 service: id.name.clone(),
4445 address: http_address(method, Some(path)),
4446 extra_headers: true,
4447 },
4448 );
4449 check_address_args(
4450 &id.name,
4451 &method.name,
4452 ¶ms,
4453 positional,
4454 method.span,
4455 ctx,
4456 );
4457 }
4458 Some((_, rest, is_headers)) => {
4459 let mut err = CompileError::new(
4462 "bynk.test.service_call_arity",
4463 method.span,
4464 format!(
4465 "`{}.{}` expects {} argument(s), but {} were given",
4466 id.name,
4467 method.name,
4468 params.len(),
4469 positional.len()
4470 ),
4471 );
4472 err = if is_headers {
4473 err.with_note("the route already declares `headers: RequestHeaders`, so that argument is its request headers; a second `RequestHeaders` cannot be sent")
4474 } else {
4475 err.with_note("handler declared here")
4476 };
4477 ctx.errors.push(err);
4478 for a in rest {
4479 let _ = type_of(a, None, ctx);
4480 }
4481 }
4482 None => check_address_args(
4483 &id.name,
4484 &method.name,
4485 ¶ms,
4486 positional,
4487 method.span,
4488 ctx,
4489 ),
4490 }
4491 let outcome = handler_outcome(handler, ctx);
4495 if args[1..].iter().any(|a| matches!(a.kind, EK::Wire(_))) {
4496 return outcome.map(|t| wire_outcome(t, ctx));
4497 }
4498 return outcome;
4499 }
4500
4501 if method.name == "schedule" {
4503 ctx.callees.insert(
4504 expr_id,
4505 Callee::TestService {
4506 service: id.name.clone(),
4507 address: HandlerAddress::Schedule { expr: None },
4508 extra_headers: false,
4509 },
4510 );
4511 let Some(EK::StrLit(expr)) = args.first().map(|a| &a.kind) else {
4512 ctx.errors.push(CompileError::new(
4513 "bynk.test.service_bad_address",
4514 method.span,
4515 format!(
4516 "`{}.schedule` addresses a cron handler, so its first argument must be the schedule string",
4517 id.name
4518 ),
4519 ));
4520 for a in args {
4521 let _ = type_of(a, None, ctx);
4522 }
4523 return None;
4524 };
4525 ctx.callees.insert(
4528 expr_id,
4529 Callee::TestService {
4530 service: id.name.clone(),
4531 address: HandlerAddress::schedule(expr),
4532 extra_headers: false,
4533 },
4534 );
4535 let matched = sig
4536 .handlers
4537 .iter()
4538 .find(|h| matches!(&h.kind, HandlerKind::Cron { expr: e } if e == expr));
4539 let Some(handler) = matched else {
4540 ctx.errors.push(CompileError::new(
4541 "bynk.test.service_unknown_route",
4542 method.span,
4543 format!(
4544 "`{}` declares no `on schedule(\"{}\")` handler",
4545 id.name, expr
4546 ),
4547 ));
4548 for a in args {
4549 let _ = type_of(a, None, ctx);
4550 }
4551 return None;
4552 };
4553 let params = handler.params.clone();
4554 let _ = type_of(&args[0], None, ctx);
4555 check_address_args(&id.name, "schedule", ¶ms, &args[1..], method.span, ctx);
4556 return handler_outcome(handler, ctx);
4557 }
4558
4559 if method.name == "message" {
4561 ctx.callees.insert(
4562 expr_id,
4563 Callee::TestService {
4564 service: id.name.clone(),
4565 address: HandlerAddress::Message,
4566 extra_headers: false,
4567 },
4568 );
4569 let matched = sig
4570 .handlers
4571 .iter()
4572 .find(|h| matches!(&h.kind, HandlerKind::Message));
4573 let Some(handler) = matched else {
4574 ctx.errors.push(CompileError::new(
4575 "bynk.test.service_unknown_route",
4576 method.span,
4577 format!("`{}` declares no `on message(...)` handler", id.name),
4578 ));
4579 for a in args {
4580 let _ = type_of(a, None, ctx);
4581 }
4582 return None;
4583 };
4584 let params = handler.params.clone();
4585 check_address_args(&id.name, "message", ¶ms, args, method.span, ctx);
4586 return handler_outcome(handler, ctx);
4587 }
4588
4589 if method.name == "event"
4592 && let Some(handler) = sig
4593 .handlers
4594 .iter()
4595 .find(|h| matches!(&h.kind, HandlerKind::Event))
4596 {
4597 ctx.callees.insert(
4598 expr_id,
4599 Callee::TestService {
4600 service: id.name.clone(),
4601 address: HandlerAddress::Event,
4602 extra_headers: false,
4603 },
4604 );
4605 let handler = handler.clone();
4606 check_event_address(sig, id, &handler, args, method.span, ctx);
4607 return handler_outcome(&handler, ctx);
4608 }
4609
4610 let proto = sig.protocol.as_deref().unwrap_or("call");
4612 let mut err = CompileError::new(
4613 "bynk.test.service_bad_address",
4614 method.span,
4615 format!(
4616 "`{}.{}` is not a way to address a `from {proto}` service in a test body",
4617 id.name, method.name
4618 ),
4619 );
4620 if method.name == "event" {
4621 err = err.with_note(
4622 "only a `from Events(E)` service is addressed with `svc.event(e)`; it delivers one event to the service's `on event` handler",
4623 );
4624 }
4625 ctx.errors.push(err);
4626 for a in args {
4627 let _ = type_of(a, None, ctx);
4628 }
4629 None
4630}
4631
4632fn check_ws_address(
4640 sig: &TestServiceSig,
4641 id: &Ident,
4642 method: &Ident,
4643 args: &[Expr],
4644 expr_id: ExprId,
4645 ctx: &mut Ctx,
4646) -> Option<TyId> {
4647 use bynk_syntax::ast::HandlerKind;
4648 let tys = ctx.tys;
4649 let which = method.name.as_str();
4650 let (in_ref, out_ref) = sig.ws_frames.clone()?;
4651 let handler = sig
4652 .handlers
4653 .iter()
4654 .find(|h| {
4655 matches!(
4656 (which, &h.kind),
4657 ("open", HandlerKind::Open)
4658 | ("message", HandlerKind::Message)
4659 | ("close", HandlerKind::Close)
4660 )
4661 })
4662 .cloned();
4663 let service = id.name.clone();
4664 ctx.callees.insert(
4665 expr_id,
4666 Callee::TestService {
4667 service: service.clone(),
4668 address: HandlerAddress::Ws(match which {
4669 "open" => WsAddress::Open,
4670 "message" => WsAddress::Message { frame: None },
4671 _ => WsAddress::Close { params: None },
4672 }),
4673 extra_headers: false,
4674 },
4675 );
4676 let Some(handler) = handler else {
4677 ctx.errors.push(CompileError::new(
4678 "bynk.test.service_unknown_route",
4679 method.span,
4680 format!("`{service}` declares no `on {which}` handler"),
4681 ));
4682 for a in args {
4683 let _ = type_of(a, None, ctx);
4684 }
4685 return None;
4686 };
4687 let out_ty = resolve_type_ref(&out_ref, &ctx.input.types, tys)?;
4688 let in_ty = resolve_type_ref(&in_ref, &ctx.input.types, tys)?;
4689 let tc_ty = tys.intern(Ty::TestConnection(out_ty));
4690 let Some(first) = args.first() else {
4691 ctx.errors.push(
4692 CompileError::new(
4693 "bynk.test.service_call_arity",
4694 method.span,
4695 format!(
4696 "`{service}.{which}` takes the case's `TestConnection` as its first argument"
4697 ),
4698 )
4699 .with_note(format!(
4700 "build one with `TestConnection[{}]()`",
4701 out_ty.display(tys)
4702 )),
4703 );
4704 return None;
4705 };
4706 check_arg(
4707 first,
4708 tc_ty,
4709 &format!("the connection of `{service}.{which}`"),
4710 ctx,
4711 );
4712 let rest = &args[1..];
4713 match which {
4714 "open" => {
4715 let params = handler.params.clone();
4716 check_address_args(&service, "open", ¶ms, rest, method.span, ctx);
4717 }
4718 "message" => {
4719 let frame_idx = handler
4720 .params
4721 .iter()
4722 .position(|p| resolve_type_ref(&p.type_ref, &ctx.input.types, tys) == Some(in_ty))
4723 .unwrap_or(0);
4724 ctx.callees.insert(
4725 expr_id,
4726 Callee::TestService {
4727 service: service.clone(),
4728 address: HandlerAddress::ws_message(frame_idx, handler.params.len()),
4729 extra_headers: false,
4730 },
4731 );
4732 if rest.len() != 1 {
4733 ctx.errors.push(
4734 CompileError::new(
4735 "bynk.test.service_call_arity",
4736 method.span,
4737 format!(
4738 "`{service}.message` takes the connection and one inbound frame, but {} argument(s) were given",
4739 args.len()
4740 ),
4741 )
4742 .with_note("the route values were given at `open`; the connection remembers them"),
4743 );
4744 for a in rest {
4745 let _ = type_of(a, None, ctx);
4746 }
4747 } else {
4748 check_arg(
4749 &rest[0],
4750 in_ty,
4751 &format!("the frame of `{service}.message`"),
4752 ctx,
4753 );
4754 }
4755 }
4756 _ => {
4757 ctx.callees.insert(
4758 expr_id,
4759 Callee::TestService {
4760 service: service.clone(),
4761 address: HandlerAddress::ws_close(handler.params.len()),
4762 extra_headers: false,
4763 },
4764 );
4765 if !rest.is_empty() {
4766 ctx.errors.push(CompileError::new(
4767 "bynk.test.service_call_arity",
4768 method.span,
4769 format!(
4770 "`{service}.close` takes only the connection, but {} argument(s) were given",
4771 args.len()
4772 ),
4773 ));
4774 for a in rest {
4775 let _ = type_of(a, None, ctx);
4776 }
4777 }
4778 }
4779 }
4780 handler_outcome(&handler, ctx)
4781}
4782
4783fn handler_outcome(handler: &TestHandler, ctx: &mut Ctx) -> Option<TyId> {
4787 resolve_type_ref(&handler.return_type, &ctx.input.types, ctx.tys)
4788}
4789
4790fn effect_of(ty: TyId, ctx: &Ctx) -> TyId {
4792 ctx.tys.intern(Ty::Effect(ty))
4793}
4794
4795fn wire_outcome(outcome: TyId, ctx: &Ctx) -> TyId {
4798 let tys = ctx.tys;
4799 let inner = match &*tys.get(outcome) {
4800 Ty::Effect(t) => *t,
4801 _ => outcome,
4802 };
4803 let t = match &*tys.get(inner) {
4804 Ty::HttpResult(t) => *t,
4805 _ => return outcome,
4806 };
4807 tys.intern(Ty::Effect(tys.intern(Ty::HttpOutcome(t))))
4808}
4809
4810fn with_open_sum_note(err: CompileError, handler: &TestHandler, ctx: &Ctx) -> CompileError {
4817 let open = handler
4818 .by_clause
4819 .as_ref()
4820 .is_some_and(|by| by.is_sum() && crate::actors::sum_has_open_member(by, &ctx.test_actors));
4821 if open {
4822 err.with_note(
4823 "this actor sum admits an open member (`Visitor`): a request with a missing or bad credential resolves as it, so the seam never answers `401`",
4824 )
4825 } else {
4826 err
4827 }
4828}
4829
4830fn http_address(method: &Ident, path: Option<&str>) -> HandlerAddress {
4832 HandlerAddress::Http {
4833 verb: bynk_syntax::ast::HttpMethod::from_ident(&method.name).expect("the branch's guard"),
4834 path: path.map(str::to_string),
4835 }
4836}
4837
4838pub(crate) fn record_principal(
4842 p: &bynk_syntax::ast::CallSiteActor,
4843 ctx: &mut Ctx,
4844) -> CallSitePrincipal {
4845 let kind = CallSitePrincipal::of(&p.actor.name);
4846 ctx.callees.insert(p.id, Callee::Principal(kind.clone()));
4847 kind
4848}
4849
4850struct OidcOnlyPrincipal {
4853 code: &'static str,
4855 sends: &'static str,
4857 why_not_elsewhere: &'static str,
4860}
4861
4862fn oidc_only_principal(bad: BadCredential) -> Option<OidcOnlyPrincipal> {
4864 let (code, sends, why_not_elsewhere) = match bad {
4865 BadCredential::WrongIssuer => (
4866 "bynk.test.wrong_issuer_needs_oidc_route",
4867 "a token for another issuer",
4868 "; a `Bearer` token has no issuer to check",
4869 ),
4870 BadCredential::WrongAudience => (
4871 "bynk.test.wrong_audience_needs_oidc_route",
4872 "a token for another audience",
4873 "; a `Bearer` token has no audience to check",
4874 ),
4875 BadCredential::WrongAlgorithm => (
4876 "bynk.test.wrong_algorithm_needs_oidc_route",
4877 "tokens signed under a refused algorithm (`alg: none`, and `HS256` keyed with the public key)",
4878 "; only an `Oidc` seam is driven with these tokens",
4879 ),
4880 BadCredential::NoSubject => (
4881 "bynk.test.no_subject_needs_oidc_route",
4882 "tokens with an empty and with a missing `sub`",
4883 "; only an `Oidc` seam is driven with these tokens",
4884 ),
4885 BadCredential::Forged | BadCredential::Stale | BadCredential::Expired => return None,
4886 };
4887 Some(OidcOnlyPrincipal {
4888 code,
4889 sends,
4890 why_not_elsewhere,
4891 })
4892}
4893
4894fn check_principal_claims(p: &bynk_syntax::ast::CallSiteActor, ctx: &mut Ctx) {
4897 let tys = ctx.tys;
4898 if let Some(claims) = &p.claims {
4899 let want = tys.intern(Ty::TokenClaims);
4900 check_arg(claims, want, "the principal's claims", ctx);
4901 let oidc = ctx.test_actors.get(&p.actor.name).is_some_and(|decl| {
4902 decl.auth
4903 .as_ref()
4904 .is_some_and(|a| a.name.as_str() == "Oidc")
4905 });
4906 if !oidc {
4907 ctx.errors.push(
4908 CompileError::new(
4909 "bynk.test.principal_claims_not_oidc",
4910 claims.span,
4911 format!(
4912 "`{}` isn't an `Oidc` actor, so its handlers read no token claims",
4913 p.actor.name
4914 ),
4915 )
4916 .with_note("claims are passed as `by Workload(\"id\", TokenClaims.of([\"name: value\"]))` for an `Oidc` actor"),
4917 );
4918 }
4919 }
4920}
4921
4922pub(crate) fn nobody_outcome(value: &Expr, ty: TyId, ctx: &Ctx) -> TyId {
4923 let is_http_address = matches!(
4924 ctx.callees.get(&value.id),
4925 Some(Callee::TestService {
4926 address: HandlerAddress::Http { .. },
4927 ..
4928 })
4929 );
4930 if is_http_address {
4931 wire_outcome(ty, ctx)
4932 } else {
4933 ty
4934 }
4935}
4936
4937enum ActorIdentity {
4939 Typed(TyId),
4940 CallerString,
4941 Unit,
4942 Unknown,
4943}
4944
4945fn resolve_actor_identity(name: &str, ctx: &Ctx) -> ActorIdentity {
4947 let tys = ctx.tys;
4948 use crate::actors::{Identity, prelude_actor};
4949 if let Some(decl) = ctx.test_actors.get(name) {
4950 if crate::actors::caller_refinement(decl, &ctx.test_actors).is_some() {
4952 return ActorIdentity::CallerString;
4953 }
4954 let decl = match &decl.refinement {
4961 Some(r) => match ctx.test_actors.get(&r.base.name) {
4962 Some(base) if base.refinement.is_none() => base,
4963 _ => return ActorIdentity::Unknown,
4964 },
4965 None => decl,
4966 };
4967 return match &decl.identity {
4968 Some(t) => match resolve_type_ref(t, &ctx.input.types, tys) {
4969 Some(ty) => ActorIdentity::Typed(ty),
4970 None => ActorIdentity::Unit,
4971 },
4972 None => ActorIdentity::Unit,
4973 };
4974 }
4975 match prelude_actor(name) {
4976 Some(c) => match c.identity {
4977 Identity::Unit => ActorIdentity::Unit,
4978 Identity::CallerId => ActorIdentity::CallerString,
4979 Identity::Declared(_) => ActorIdentity::Unit,
4980 },
4981 None => ActorIdentity::Unknown,
4982 }
4983}
4984
4985fn handler_actor_name(handler: &TestHandler, protocol: Option<&str>) -> Option<String> {
4989 if let Some(by) = &handler.by_clause {
4990 return Some(by.primary().name.clone());
4991 }
4992 match protocol {
4993 None => Some("Caller".to_string()),
4994 Some("cron") => Some("Scheduler".to_string()),
4995 Some("queue") => Some("Producer".to_string()),
4996 _ => None,
4997 }
4998}
4999
5000fn is_asset_value(e: &Expr, ctx: &Ctx) -> bool {
5004 match &e.kind {
5005 ExprKind::Ident(id) => ctx
5006 .lookup(id.name.as_str())
5007 .map(|t| matches!(&*ctx.tys.get(t), Ty::Asset))
5008 .unwrap_or_else(|| ctx.input.assets.contains_key(&id.name)),
5009 _ => false,
5010 }
5011}
5012
5013fn resolve_test_address<'a>(
5016 sig: &'a TestServiceSig,
5017 method: &str,
5018 args: &[Expr],
5019) -> Option<&'a TestHandler> {
5020 use bynk_syntax::ast::{ExprKind as EK, HandlerKind, HttpMethod};
5021 if method == "call" {
5022 return sig.call_handler();
5023 }
5024 if HttpMethod::from_ident(method).is_some() {
5025 let EK::StrLit(path) = &args.first()?.kind else {
5026 return None;
5027 };
5028 return sig.handlers.iter().find(|h| {
5029 matches!(&h.kind, HandlerKind::Http { method: m, path: p } if m.as_str() == method && p == path)
5030 });
5031 }
5032 if method == "schedule" {
5033 let EK::StrLit(expr) = &args.first()?.kind else {
5034 return None;
5035 };
5036 return sig
5037 .handlers
5038 .iter()
5039 .find(|h| matches!(&h.kind, HandlerKind::Cron { expr: e } if e == expr));
5040 }
5041 if method == "message" {
5042 return sig
5043 .handlers
5044 .iter()
5045 .find(|h| matches!(&h.kind, HandlerKind::Message));
5046 }
5047 if method == "open" && sig.ws_frames.is_some() {
5049 return sig
5050 .handlers
5051 .iter()
5052 .find(|h| matches!(&h.kind, HandlerKind::Open));
5053 }
5054 if method == "event" {
5056 return sig
5057 .handlers
5058 .iter()
5059 .find(|h| matches!(&h.kind, HandlerKind::Event));
5060 }
5061 None
5062}
5063
5064pub(crate) fn check_effect_let_principal(
5071 value: &Expr,
5072 principal: Option<&bynk_syntax::ast::CallSiteActor>,
5073 ctx: &mut Ctx,
5074) {
5075 let tys = ctx.tys;
5076 let kind = principal.map(|p| record_principal(p, ctx));
5078 if let Some(p) = principal {
5079 check_principal_claims(p, ctx);
5080 }
5081 let ExprKind::MethodCall {
5082 receiver,
5083 method,
5084 args,
5085 ..
5086 } = &value.kind
5087 else {
5088 if let Some(p) = principal {
5089 report_principal_actor(p, ctx);
5090 }
5091 return;
5092 };
5093 let ExprKind::Ident(id) = &receiver.kind else {
5094 if let Some(p) = principal {
5095 report_principal_actor(p, ctx);
5096 }
5097 return;
5098 };
5099 let Some(sig) = ctx.test_services.get(&id.name).cloned() else {
5100 if let Some(p) = principal {
5101 report_principal_actor(p, ctx);
5102 }
5103 return;
5104 };
5105 if sig.ws_frames.is_some() && matches!(method.name.as_str(), "message" | "close") {
5108 if let Some(p) = principal {
5109 ctx.errors.push(
5110 CompileError::new(
5111 "bynk.test.ws_lifecycle_by",
5112 p.span,
5113 format!(
5114 "`{}.{}` takes no `by`: the connection's principal was given at `open`",
5115 id.name, method.name
5116 ),
5117 )
5118 .with_note("open a new `TestConnection` to act as a different principal"),
5119 );
5120 if let Some(idv) = &p.identity {
5121 let _ = type_of(idv, None, ctx);
5122 }
5123 }
5124 return;
5125 }
5126 let Some(handler) = resolve_test_address(&sig, &method.name, args).cloned() else {
5127 if let Some(p) = principal
5128 && args.first().is_some_and(|a| is_asset_value(a, ctx))
5129 {
5130 ctx.errors.push(
5133 CompileError::new(
5134 "bynk.test.principal_on_asset",
5135 p.span,
5136 format!(
5137 "an asset is public and served before the Worker runs, so `by {}` is meaningless",
5138 p.actor.name
5139 ),
5140 )
5141 .with_note("drop the `by` clause on an asset fetch"),
5142 );
5143 if let Some(id) = &p.identity {
5144 let _ = type_of(id, None, ctx);
5145 }
5146 return;
5147 }
5148 if let Some(p) = principal {
5149 let wrong_method = bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some()
5155 && matches!(args.first().map(|a| &a.kind), Some(bynk_syntax::ast::ExprKind::StrLit(path))
5156 if sig.handlers.iter().any(|h| matches!(&h.kind, bynk_syntax::ast::HandlerKind::Http { path: p, .. } if p == path)));
5157 if wrong_method {
5158 ctx.errors.push(
5159 CompileError::new(
5160 "bynk.test.principal_on_wrong_method",
5161 p.span,
5162 format!(
5163 "a wrong-method `405` test reaches no handler, so `by {}` is meaningless",
5164 p.actor.name
5165 ),
5166 )
5167 .with_note("drop the `by` clause on a wrong-method call"),
5168 );
5169 if let Some(id) = &p.identity {
5170 let _ = type_of(id, None, ctx);
5171 }
5172 } else {
5173 report_principal_actor(p, ctx);
5174 }
5175 }
5176 return;
5177 };
5178
5179 if let Some(p) = principal
5187 && kind == Some(CallSitePrincipal::Nobody)
5188 {
5189 let secured = handler
5198 .by_clause
5199 .as_ref()
5200 .is_some_and(|by| crate::actors::route_is_secured(by, &ctx.test_actors));
5201 if !secured {
5202 let err = CompileError::new(
5203 "bynk.test.nobody_needs_secured_route",
5204 p.span,
5205 "`by Nobody` drives the auth seam to a `401`, but this handler's route has no seam that refuses a missing credential",
5206 )
5207 .with_note(
5208 "use `by Nobody` only on a route guarded by a `Bearer`, `Oidc` or `Signature` actor; a public (`Visitor`) route has no seam to test",
5209 );
5210 ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5211 }
5212 if let Some(idv) = &p.identity {
5213 ctx.errors.push(CompileError::new(
5214 "bynk.test.actor_no_identity",
5215 p.span,
5216 "`Nobody` presents no credential, so it takes no identity — write `by Nobody`",
5217 ));
5218 let _ = type_of(idv, None, ctx);
5219 }
5220 return;
5221 }
5222
5223 if let Some(p) = principal
5231 && let Some(CallSitePrincipal::BadCredential(bad)) = kind
5232 {
5233 let name = p.actor.name.as_str();
5234 let by = handler.by_clause.as_ref();
5235 let sig_seam =
5236 by.and_then(|by| crate::actors::signature_seam_of_route(by, &ctx.test_actors));
5237 let bearer =
5238 by.is_some_and(|by| crate::actors::route_refuses_bad_token(by, &ctx.test_actors));
5239 let oidc = by.is_some_and(|by| crate::actors::by_clause_is_oidc(by, &ctx.test_actors));
5241 match (bad, sig_seam) {
5242 (BadCredential::Expired, _) if !bearer && !oidc => {
5243 let err = CompileError::new(
5244 "bynk.test.expired_needs_bearer_route",
5245 p.span,
5246 "`by Expired` sends an expired token to a `Bearer` or `Oidc` seam, but this handler's route has no such seam that refuses one",
5247 )
5248 .with_note(
5249 "use `by Expired` on a route guarded by a `Bearer` or `Oidc` actor; on a `Signature` route, `by Stale` sends a stale signature",
5250 );
5251 ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5252 }
5253 (BadCredential::Expired, _) => {}
5254 (n, _) if !oidc && oidc_only_principal(n).is_some() => {
5255 let kind = oidc_only_principal(n).expect("matched above");
5256 ctx.errors.push(
5257 CompileError::new(
5258 kind.code,
5259 p.span,
5260 format!(
5261 "`by {name}` sends {} to an `Oidc` seam, but this handler's route has no `Oidc` seam that checks it",
5262 kind.sends
5263 ),
5264 )
5265 .with_note(format!(
5266 "use `by {name}` on a route guarded by an `Oidc` actor{}",
5267 kind.why_not_elsewhere
5268 )),
5269 );
5270 }
5271 (n, _) if oidc_only_principal(n).is_some() => {}
5272 (BadCredential::Forged | BadCredential::Stale, None)
5273 if !(bad == BadCredential::Forged && (bearer || oidc)) =>
5274 {
5275 let err = CompileError::new(
5276 "bynk.test.forged_needs_signature_route",
5277 p.span,
5278 if bad == BadCredential::Forged {
5279 "`by Forged` sends a bad credential to a `Signature`, `Bearer` or `Oidc` seam, but this handler's route has none of these seams to refuse one".to_string()
5280 } else {
5281 "`by Stale` sends a stale signature to a `Signature` seam, but this handler's route has no `Signature` seam that refuses one".to_string()
5282 },
5283 )
5284 .with_note(
5285 "use `by Forged` on a route guarded by a `Signature`, `Bearer` or `Oidc` actor, and `by Stale` on a `Signature` one; `by Nobody` drives any of them to a `401`",
5286 );
5287 ctx.errors.push(with_open_sum_note(err, &handler, ctx));
5288 }
5289 (BadCredential::Stale, Some(seam))
5290 if seam.timestamp_header.is_none() || seam.tolerance_secs.is_none() =>
5291 {
5292 ctx.errors.push(
5293 CompileError::new(
5294 "bynk.test.stale_needs_timestamp",
5295 p.span,
5296 "`by Stale` signs in the past, but this route's `Signature` actor declares no `timestamp` header and `tolerance` for the seam to refuse it by",
5297 )
5298 .with_note(
5299 "declare `timestamp = \"<Header>\"` and `tolerance = <seconds>` on the actor, or test the seam with `by Forged`",
5300 ),
5301 );
5302 }
5303 _ => {}
5304 }
5305 if let Some(idv) = &p.identity {
5306 ctx.errors.push(CompileError::new(
5307 "bynk.test.actor_no_identity",
5308 p.span,
5309 format!("`{name}` presents a bad credential, not an identity, so it takes none — write `by {name}`"),
5310 ));
5311 let _ = type_of(idv, None, ctx);
5312 }
5313 return;
5314 }
5315
5316 if let Some(p) = principal {
5317 check_principal_admitted(&handler, p, ctx);
5318 }
5319
5320 if let Some(by) = handler.by_clause.as_ref().filter(|by| by.is_sum()) {
5323 check_sum_principal(by, principal, value.span, ctx);
5324 return;
5325 }
5326
5327 let required = handler_actor_name(&handler, sig.protocol.as_deref())
5328 .map(|actor| resolve_actor_identity(&actor, ctx));
5329
5330 match (required, principal) {
5331 (Some(ActorIdentity::Typed(ty)), principal) => match principal {
5332 Some(p) => match resolve_actor_identity(&p.actor.name, ctx) {
5333 ActorIdentity::Unknown => report_principal_actor(p, ctx),
5334 ActorIdentity::Unit | ActorIdentity::CallerString => {
5335 ctx.errors.push(CompileError::new(
5336 "bynk.test.principal_identity_mismatch",
5337 p.span,
5338 format!(
5339 "this handler runs as an actor carrying `{}`, but `by {}` supplies no matching identity",
5340 ty.display(tys),
5341 p.actor.name
5342 ),
5343 ));
5344 if let Some(idv) = &p.identity {
5345 let _ = type_of(idv, None, ctx);
5346 }
5347 }
5348 ActorIdentity::Typed(_) => match &p.identity {
5349 Some(idv) => {
5350 let got = type_of(idv, Some(ty), ctx);
5351 if let Some(g) = got
5352 && !compatible(g, ty, tys)
5353 {
5354 ctx.errors.push(CompileError::new(
5355 "bynk.types.argument_mismatch",
5356 idv.span,
5357 format!(
5358 "identity has type `{}`, but the handler expects `{}`",
5359 g.display(tys),
5360 ty.display(tys)
5361 ),
5362 ));
5363 }
5364 }
5365 None => ctx.errors.push(CompileError::new(
5366 "bynk.test.actor_identity_required",
5367 p.span,
5368 format!(
5369 "actor `{}` carries an identity, so write `by {}(...)`",
5370 p.actor.name, p.actor.name
5371 ),
5372 )),
5373 },
5374 },
5375 None => ctx.errors.push(
5376 CompileError::new(
5377 "bynk.test.principal_required",
5378 value.span,
5379 format!(
5380 "this handler runs as a verified actor carrying `{}`; the case must act as it with `by <Actor>(<identity>)`",
5381 ty.display(tys)
5382 ),
5383 )
5384 .with_note("append a call-site actor, e.g. `... by User(\"alice\")`"),
5385 ),
5386 },
5387 (Some(ActorIdentity::CallerString), principal) if handler_binds_caller(&handler, ctx) => {
5392 match principal {
5393 None => ctx.errors.push(
5394 CompileError::new(
5395 "bynk.test.actor_identity_required",
5396 value.span,
5397 "this handler binds its caller's identity (`by <binder>: Caller`), so the case must name the calling context with `by Caller(\"...\")`",
5398 )
5399 .with_note("append a call-site actor, e.g. `... by Caller(\"orders\")`"),
5400 ),
5401 Some(p) => match resolve_actor_identity(&p.actor.name, ctx) {
5402 ActorIdentity::CallerString if p.identity.is_none() => {
5403 ctx.errors.push(CompileError::new(
5404 "bynk.test.actor_identity_required",
5405 p.span,
5406 format!(
5407 "this handler binds its caller's identity, so write `by {}(\"...\")` naming the calling context",
5408 p.actor.name
5409 ),
5410 ))
5411 }
5412 ActorIdentity::Unit => {
5413 ctx.errors.push(CompileError::new(
5414 "bynk.test.principal_identity_mismatch",
5415 p.span,
5416 format!(
5417 "this handler binds its caller's identity, but `by {}` supplies none — write `by Caller(\"...\")`",
5418 p.actor.name
5419 ),
5420 ));
5421 if let Some(idv) = &p.identity {
5422 let _ = type_of(idv, None, ctx);
5423 }
5424 }
5425 _ => report_principal_actor(p, ctx),
5426 },
5427 }
5428 }
5429 (_, Some(p)) => report_principal_actor(p, ctx),
5430 (_, None) => {}
5431 }
5432}
5433
5434fn check_sum_principal(
5441 by: &bynk_syntax::ast::ByClause,
5442 principal: Option<&bynk_syntax::ast::CallSiteActor>,
5443 value_span: Span,
5444 ctx: &mut Ctx,
5445) {
5446 let members = format!(
5447 "`{}`",
5448 by.actors
5449 .iter()
5450 .map(|a| a.name.as_str())
5451 .collect::<Vec<_>>()
5452 .join(" | ")
5453 );
5454 let Some(p) = principal else {
5455 ctx.errors.push(
5456 CompileError::new(
5457 "bynk.test.principal_required",
5458 value_span,
5459 format!(
5460 "this handler runs as one of the actors {members}; the case must act as one with `by <Actor>`"
5461 ),
5462 )
5463 .with_note(format!(
5464 "append a call-site actor naming a member, e.g. `... by {}`",
5465 sum_member_example(&by.actors[0].name, ctx)
5466 )),
5467 );
5468 return;
5469 };
5470 let name = &p.actor.name;
5471 if !by.actors.iter().any(|a| &a.name == name) {
5472 if matches!(resolve_actor_identity(name, ctx), ActorIdentity::Unknown) {
5473 report_principal_actor(p, ctx);
5474 return;
5475 }
5476 ctx.errors.push(
5477 CompileError::new(
5478 "bynk.test.principal_identity_mismatch",
5479 p.span,
5480 format!(
5481 "this handler runs as one of the actors {members}, but `by {name}` names none of them"
5482 ),
5483 )
5484 .with_note("act as a member of the handler's `by` sum"),
5485 );
5486 if let Some(idv) = &p.identity {
5487 let _ = type_of(idv, None, ctx);
5488 }
5489 return;
5490 }
5491 match resolve_actor_identity(name, ctx) {
5492 ActorIdentity::CallerString if p.identity.is_none() => ctx.errors.push(CompileError::new(
5495 "bynk.test.actor_identity_required",
5496 p.span,
5497 format!(
5498 "the `{name}` arm carries the calling context's name, so write `by {name}(\"...\")`"
5499 ),
5500 )),
5501 _ => report_principal_actor(p, ctx),
5502 }
5503}
5504
5505fn sum_member_example(name: &str, ctx: &Ctx) -> String {
5507 match resolve_actor_identity(name, ctx) {
5508 ActorIdentity::Typed(_) | ActorIdentity::CallerString => format!("{name}(...)"),
5509 ActorIdentity::Unit | ActorIdentity::Unknown => name.to_string(),
5510 }
5511}
5512
5513fn handler_binds_caller(handler: &TestHandler, ctx: &Ctx) -> bool {
5520 use crate::actors::{Identity, prelude_actor};
5521 let Some(by) = &handler.by_clause else {
5522 return false;
5523 };
5524 let Some(binder) = &by.binder else {
5525 return false;
5526 };
5527 let name = &by.primary().name;
5528 matches!(handler.kind, bynk_syntax::ast::HandlerKind::Call)
5529 && !by.is_sum()
5530 && (!ctx.test_actors.contains_key(name)
5531 && prelude_actor(name).map(|c| c.identity) == Some(Identity::CallerId)
5532 || ctx.test_actors.get(name).is_some_and(|d| {
5534 crate::actors::caller_refinement(d, &ctx.test_actors).is_some()
5535 }))
5536 && !handler.params.iter().any(|p| p.name.name == binder.name)
5537}
5538
5539fn check_principal_admitted(
5544 handler: &TestHandler,
5545 p: &bynk_syntax::ast::CallSiteActor,
5546 ctx: &mut Ctx,
5547) {
5548 let Some(idv) = &p.identity else {
5549 return;
5550 };
5551 let ExprKind::StrLit(context) = &idv.kind else {
5552 return;
5553 };
5554 let mut names = vec![p.actor.name.clone()];
5555 if let Some(by) = handler.by_clause.as_ref().filter(|by| !by.is_sum()) {
5556 names.push(by.primary().name.clone());
5557 }
5558 names.dedup();
5559 for name in names {
5560 let Some(pred) = ctx
5561 .test_actors
5562 .get(&name)
5563 .and_then(|d| crate::actors::caller_refinement(d, &ctx.test_actors))
5564 else {
5565 continue;
5566 };
5567 if !pred.admits(context) {
5568 ctx.errors.push(
5569 CompileError::new(
5570 "bynk.actor.caller_not_admitted",
5571 idv.span,
5572 format!("`{name}` does not admit calls from `{context}`"),
5573 )
5574 .with_note(format!(
5575 "the actor is `Caller` refined by `IsContext(…)`, which names the contexts that may call; this case names `{context}`"
5576 )),
5577 );
5578 return;
5579 }
5580 }
5581}
5582
5583fn report_principal_actor(p: &bynk_syntax::ast::CallSiteActor, ctx: &mut Ctx) {
5585 let tys = ctx.tys;
5586 let name = &p.actor.name;
5587 let kind = record_principal(p, ctx);
5588 match resolve_actor_identity(name, ctx) {
5589 ActorIdentity::Unknown if ctx.test_actors.contains_key(name) => {
5594 if let Some(id) = &p.identity {
5595 let _ = type_of(id, None, ctx);
5596 }
5597 }
5598 ActorIdentity::Unknown if matches!(kind, CallSitePrincipal::BadCredential(_)) => {
5602 let CallSitePrincipal::BadCredential(bad) = kind else {
5603 unreachable!("matched above")
5604 };
5605 let err = if bad == BadCredential::Expired {
5606 CompileError::new(
5607 "bynk.test.expired_needs_bearer_route",
5608 p.span,
5609 "`by Expired` sends an expired token to a `Bearer` or `Oidc` seam, but this address reaches no `Bearer`- or `Oidc`-secured http route",
5610 )
5611 .with_note("use `by Expired` on an http route guarded by a `Bearer` or `Oidc` actor")
5612 } else if let Some(kind) = oidc_only_principal(bad) {
5613 CompileError::new(
5614 kind.code,
5615 p.span,
5616 format!("`by {name}` sends {} to an `Oidc` seam, but this address reaches no `Oidc`-secured http route", kind.sends),
5617 )
5618 .with_note(format!("use `by {name}` on an http route guarded by an `Oidc` actor"))
5619 } else {
5620 CompileError::new(
5621 "bynk.test.forged_needs_signature_route",
5622 p.span,
5623 format!("`by {name}` sends a bad credential to a `Signature`, `Bearer` or `Oidc` seam, but this address reaches no `Signature`-, `Bearer`- or `Oidc`-secured http route"),
5624 )
5625 .with_note("use `by Forged` on an http route guarded by a `Signature`, `Bearer` or `Oidc` actor, and `by Stale` on a `Signature` one")
5626 };
5627 ctx.errors.push(err);
5628 if let Some(id) = &p.identity {
5629 let _ = type_of(id, None, ctx);
5630 }
5631 }
5632 ActorIdentity::Unknown => {
5633 ctx.errors.push(
5634 CompileError::new(
5635 "bynk.test.unknown_actor",
5636 p.actor.span,
5637 format!("`{name}` is not an actor of the target context or a prelude actor"),
5638 )
5639 .with_note("name an `actor` the target declares, or a prelude actor (`Visitor`, `Caller`, …)"),
5640 );
5641 if let Some(id) = &p.identity {
5642 let _ = type_of(id, None, ctx);
5643 }
5644 }
5645 ActorIdentity::Typed(ty) => match &p.identity {
5646 Some(id) => {
5647 let got = type_of(id, Some(ty), ctx);
5648 if let Some(g) = got
5649 && !compatible(g, ty, tys)
5650 {
5651 ctx.errors.push(CompileError::new(
5652 "bynk.types.argument_mismatch",
5653 id.span,
5654 format!(
5655 "identity has type `{}`, but actor `{name}` expects `{}`",
5656 g.display(tys),
5657 ty.display(tys)
5658 ),
5659 ));
5660 }
5661 }
5662 None => ctx.errors.push(CompileError::new(
5663 "bynk.test.actor_identity_required",
5664 p.span,
5665 format!("actor `{name}` carries an identity, so `by {name}(...)` needs an identity value"),
5666 )),
5667 },
5668 ActorIdentity::CallerString => {
5669 if let Some(id) = &p.identity {
5670 let _ = type_of(id, None, ctx);
5671 }
5672 }
5673 ActorIdentity::Unit => {
5674 if let Some(id) = &p.identity {
5675 let _ = type_of(id, None, ctx);
5676 ctx.errors.push(CompileError::new(
5677 "bynk.test.actor_no_identity",
5678 p.span,
5679 format!("actor `{name}` has no identity, so write `by {name}` with no argument"),
5680 ));
5681 }
5682 }
5683 }
5684}
5685
5686fn check_extra_headers_authorization(arg: &Expr, ctx: &mut Ctx) {
5692 ctx.errors.extend(extra_headers_authorization_errors(arg));
5693}
5694
5695pub(crate) fn extra_headers_authorization_errors(arg: &Expr) -> Vec<CompileError> {
5699 use bynk_syntax::ast::ExprKind as EK;
5700 let mut errors = Vec::new();
5701 let EK::MethodCall {
5702 receiver,
5703 method,
5704 args,
5705 ..
5706 } = &arg.kind
5707 else {
5708 return errors;
5709 };
5710 let (EK::Ident(r), "of", Some(EK::ListLit(lines, ..))) = (
5711 &receiver.kind,
5712 method.name.as_str(),
5713 args.first().map(|a| &a.kind),
5714 ) else {
5715 return errors;
5716 };
5717 if r.name != REQUEST_HEADERS {
5718 return errors;
5719 }
5720 for line in lines {
5721 if let EK::StrLit(text) = &line.kind
5722 && text
5723 .split_once(':')
5724 .is_some_and(|(n, _)| n.trim().eq_ignore_ascii_case("authorization"))
5725 {
5726 errors.push(
5727 CompileError::new(
5728 "bynk.test.extra_headers_authorization",
5729 line.span,
5730 "`Authorization` cannot be sent as an extra request header",
5731 )
5732 .with_note("the case's `by <Actor>` owns the credential the driver sends; choose the actor instead"),
5733 );
5734 }
5735 }
5736 errors
5737}
5738
5739fn is_wire(e: &Expr) -> bool {
5744 matches!(e.kind, bynk_syntax::ast::ExprKind::Wire(_))
5745}
5746
5747fn type_wire_inner(e: &Expr, ctx: &mut Ctx) {
5750 if let bynk_syntax::ast::ExprKind::Wire(inner) = &e.kind {
5751 let string = ctx.tys.intern(Ty::Base(BaseType::String));
5752 let _ = type_of(inner, Some(string), ctx);
5753 }
5754}
5755
5756fn reject_wire_args(svc: &str, addr: &str, args: &[Expr], ctx: &mut Ctx) {
5757 for a in args {
5758 if is_wire(a) {
5759 ctx.errors.push(
5760 CompileError::new(
5761 "bynk.test.wire_http_only",
5762 a.span,
5763 format!("`Wire(...)` cannot be passed to `{svc}.{addr}`"),
5764 )
5765 .with_note(
5766 "`Wire` drives an http body or path segment; pass a queue message, cron tick or event as a typed value",
5767 ),
5768 );
5769 }
5770 }
5771}
5772
5773fn check_address_args(
5777 svc: &str,
5778 addr: &str,
5779 params: &[bynk_syntax::ast::Param],
5780 positional: &[Expr],
5781 err_span: Span,
5782 ctx: &mut Ctx,
5783) {
5784 let tys = ctx.tys;
5785 if addr == "call" || addr == "schedule" || addr == "message" {
5786 reject_wire_args(svc, addr, positional, ctx);
5787 }
5788 if params.len() != positional.len() {
5789 ctx.errors.push(
5790 CompileError::new(
5791 "bynk.test.service_call_arity",
5792 err_span,
5793 format!(
5794 "`{svc}.{addr}` expects {} argument(s), but {} were given",
5795 params.len(),
5796 positional.len()
5797 ),
5798 )
5799 .with_note("handler declared here"),
5802 );
5803 for a in positional {
5804 if is_wire(a) {
5805 type_wire_inner(a, ctx);
5806 } else {
5807 let _ = type_of(a, None, ctx);
5808 }
5809 }
5810 return;
5811 }
5812 for (i, (param, arg)) in params.iter().zip(positional.iter()).enumerate() {
5813 record_param_hint(ctx.hints, ¶m.name.name, arg);
5814 if let bynk_syntax::ast::ExprKind::Wire(inner) = &arg.kind {
5822 let _ = type_of(inner, Some(tys.intern(Ty::Base(BaseType::String))), ctx);
5823 continue;
5824 }
5825 let expected = resolve_type_ref(¶m.type_ref, &ctx.input.types, tys);
5826 let arg_ty = type_of(arg, expected, ctx);
5827 if let (Some(a), Some(p)) = (arg_ty, expected)
5828 && !compatible(a, p, tys)
5829 {
5830 ctx.errors.push(CompileError::new(
5831 "bynk.types.argument_mismatch",
5832 arg.span,
5833 format!(
5834 "argument {} has type `{}`, but `{svc}.{addr}` expects `{}` for `{}`",
5835 i + 1,
5836 a.display(tys),
5837 p.display(tys),
5838 param.name.name
5839 ),
5840 ));
5841 }
5842 }
5843}
5844
5845fn check_event_address(
5851 sig: &TestServiceSig,
5852 id: &Ident,
5853 handler: &TestHandler,
5854 args: &[Expr],
5855 err_span: Span,
5856 ctx: &mut Ctx,
5857) {
5858 let tys = ctx.tys;
5859 let svc = &id.name;
5860 reject_wire_args(svc, "event", args, ctx);
5861 if args.is_empty() || args.len() > 2 {
5862 ctx.errors.push(
5863 CompileError::new(
5864 "bynk.test.service_call_arity",
5865 err_span,
5866 format!(
5867 "`{svc}.event` takes the event and, optionally, an `EventEnvelope`, but {} argument(s) were given",
5868 args.len()
5869 ),
5870 )
5871 .with_note("deliver an event with `svc.event(e)`, or `svc.event(e, env)` to choose its envelope"),
5872 );
5873 for a in args {
5874 if is_wire(a) {
5875 type_wire_inner(a, ctx);
5876 } else {
5877 let _ = type_of(a, None, ctx);
5878 }
5879 }
5880 return;
5881 }
5882 if args.len() == 1
5885 && let Some(Err(candidates)) = &sig.event_publisher
5886 {
5887 let found = if candidates.is_empty() {
5888 "no context the target declares or consumes declares it".to_string()
5889 } else {
5890 format!(
5891 "it is declared by {}",
5892 candidates
5893 .iter()
5894 .map(|c| format!("`{c}`"))
5895 .collect::<Vec<_>>()
5896 .join(", ")
5897 )
5898 };
5899 ctx.errors.push(
5900 CompileError::new(
5901 "bynk.test.event_publisher_ambiguous",
5902 err_span,
5903 format!("`{svc}.event(e)` has no single publisher to name in its default envelope: {found}"),
5904 )
5905 .with_note("pass the envelope yourself: `svc.event(e, env)`"),
5906 );
5907 }
5908 let payload = &args[0];
5909 type_wire_inner(payload, ctx);
5910 if !is_wire(payload) {
5911 let expected = handler
5912 .params
5913 .first()
5914 .and_then(|p| resolve_type_ref(&p.type_ref, &ctx.input.types, tys));
5915 let arg_ty = type_of(payload, expected, ctx);
5916 if let (Some(a), Some(p)) = (arg_ty, expected)
5917 && !compatible(a, p, tys)
5918 {
5919 let other_event = match &*tys.get(a) {
5920 Ty::Named { name, .. } if sig.known_events.contains(name) => Some(name.clone()),
5921 _ => None,
5922 };
5923 let err = match other_event {
5924 Some(other) => CompileError::new(
5925 "bynk.test.event_not_subscribed",
5926 payload.span,
5927 format!(
5928 "`{svc}` subscribes to `{}`, not `{other}`",
5929 p.display(tys)
5930 ),
5931 )
5932 .with_note(
5933 "an event address delivers only the event the service's `from Events(E)` header names",
5934 ),
5935 None => CompileError::new(
5936 "bynk.types.argument_mismatch",
5937 payload.span,
5938 format!(
5939 "argument 1 has type `{}`, but `{svc}.event` expects the event it subscribes to, `{}`",
5940 a.display(tys),
5941 p.display(tys)
5942 ),
5943 ),
5944 };
5945 ctx.errors.push(err);
5946 }
5947 }
5948 let Some(envelope) = args.get(1) else {
5949 return;
5950 };
5951 if is_wire(envelope) {
5952 type_wire_inner(envelope, ctx);
5953 return;
5954 }
5955 let envelope_ref = TypeRef::Named(Ident {
5956 name: "EventEnvelope".to_string(),
5957 span: envelope.span,
5958 });
5959 let expected = resolve_type_ref(&envelope_ref, &ctx.input.types, tys);
5960 let env_ty = type_of(envelope, expected, ctx);
5961 let Some(a) = env_ty else {
5962 return;
5963 };
5964 let mismatch = match expected {
5967 Some(p) => !compatible(a, p, tys),
5968 None => true,
5969 };
5970 if mismatch {
5971 let mut err = CompileError::new(
5972 "bynk.types.argument_mismatch",
5973 envelope.span,
5974 format!(
5975 "argument 2 has type `{}`, but `{svc}.event` expects an `EventEnvelope`",
5976 a.display(tys)
5977 ),
5978 );
5979 if expected.is_none() {
5980 err = err.with_note(
5981 "`EventEnvelope` comes from `bynk`; the suite's target must `consumes bynk` to build one",
5982 );
5983 }
5984 ctx.errors.push(err);
5985 }
5986}
5987
5988fn cross_context_prefix(receiver: &Expr, ctx: &Ctx) -> Option<String> {
5993 let info = &ctx.input.cross_context;
5994 if info.consumed_contexts.is_empty() && info.aliases.is_empty() {
5995 return None;
5996 }
5997 let candidate = flatten_ident_chain(receiver)?;
6002 let head = candidate.split('.').next().unwrap_or("");
6003 if ctx.lookup(head).is_some() {
6005 return None;
6006 }
6007 if ctx.caps.capabilities.contains_key(head) || ctx.caps.declared_capabilities.contains_key(head)
6008 {
6009 return None;
6010 }
6011 info.resolve_prefix(candidate.as_str())
6015}
6016
6017fn flatten_ident_chain(expr: &Expr) -> Option<String> {
6020 match &expr.kind {
6021 ExprKind::Ident(id) => Some(id.name.clone()),
6022 ExprKind::FieldAccess { receiver, field } => {
6023 let head = flatten_ident_chain(receiver)?;
6024 Some(format!("{head}.{}", field.name))
6025 }
6026 _ => None,
6027 }
6028}
6029
6030#[allow(clippy::too_many_arguments)]
6038fn check_cross_context_capability_call(
6039 receiver: &Expr,
6040 consumed: &str,
6041 cap: &str,
6042 method: &Ident,
6043 type_args: &[TypeRef],
6046 args: &[Expr],
6047 span: Span,
6048 expr_id: ExprId,
6050 ctx: &mut Ctx,
6051) -> Option<TyId> {
6052 let tys = ctx.tys;
6053 refuse_experimental(
6055 &format!("{consumed}.{cap}.{}", method.name),
6056 method.span,
6057 ctx,
6058 );
6059 ctx.callees.insert(
6060 expr_id,
6061 Callee::CrossCap {
6062 unit: consumed.to_string(),
6063 cap: cap.to_string(),
6064 op: method.name.clone(),
6065 wire: None,
6066 first_party: cross_first_party(consumed, cap),
6067 },
6068 );
6069 if !ctx.effectful {
6071 ctx.errors.push(CompileError::new(
6072 "bynk.effect.capability_in_pure_context",
6073 method.span,
6074 format!(
6075 "capability `{consumed}.{cap}` can only be called inside an effectful body (one returning `Effect[T]`)"
6076 ),
6077 ));
6078 }
6079 if !ctx.caps.given_remaining.contains(cap) {
6082 let mut err = CompileError::new(
6083 "bynk.given.undeclared_capability",
6084 receiver.span,
6085 format!("capability `{consumed}.{cap}` is used but not listed in the `given` clause"),
6086 )
6087 .with_note(format!(
6088 "add `{consumed}.{cap}` to the handler's `given` clause so the dependency surface is visible at the declaration site"
6089 ));
6090 if let Some((span, insert)) = given_insertion_edit(
6093 &ctx.caps.given_entries,
6094 ctx.caps.given_anchor,
6095 &format!("{consumed}.{cap}"),
6096 ) {
6097 err = err.with_suggestion(
6098 format!("add `{consumed}.{cap}` to the `given` clause"),
6099 vec![(span, insert)],
6100 Applicability::MachineApplicable,
6101 );
6102 }
6103 ctx.errors.push(err);
6104 for a in args {
6105 let _ = type_of(a, None, ctx);
6106 }
6107 return None;
6108 }
6109 ctx.caps.given_used.insert(cap.to_string());
6110
6111 let info = &ctx.input.cross_context;
6112 let op = info
6113 .consumed_capabilities
6114 .get(consumed)
6115 .and_then(|caps| caps.get(cap))
6116 .and_then(|c| c.ops.iter().find(|o| o.name == method.name))
6117 .cloned();
6118 let Some(op) = op else {
6119 ctx.errors.push(CompileError::new(
6120 "bynk.capability.unknown_operation",
6121 method.span,
6122 format!(
6123 "capability `{consumed}.{cap}` has no operation named `{}`",
6124 method.name
6125 ),
6126 ));
6127 for a in args {
6128 let _ = type_of(a, None, ctx);
6129 }
6130 return None;
6131 };
6132 ctx.refs.record_in_unit(
6136 method.span,
6137 SymbolKind::CapabilityOp,
6138 &format!("{cap}.{}", method.name),
6139 consumed,
6140 );
6141 if op.params.len() != args.len() {
6142 ctx.errors.push(CompileError::new(
6143 "bynk.capability.op_arity",
6144 method.span,
6145 format!(
6146 "capability operation `{consumed}.{cap}.{}` expects {} argument(s), but {} were given",
6147 method.name,
6148 op.params.len(),
6149 args.len()
6150 ),
6151 ));
6152 for a in args {
6153 let _ = type_of(a, None, ctx);
6154 }
6155 return None;
6156 }
6157
6158 let consumed_types = info
6160 .consumed_types
6161 .get(consumed)
6162 .cloned()
6163 .unwrap_or_default();
6164 let vars: HashSet<String> = op.type_params.iter().cloned().collect();
6171 let mut subst: HashMap<String, TyId> = HashMap::new();
6172 if !op.type_params.is_empty() || !type_args.is_empty() {
6173 if type_args.is_empty() {
6174 ctx.errors.push(
6175 CompileError::new(
6176 "bynk.generics.uninferable_type_arg",
6177 method.span,
6178 format!(
6179 "capability operation `{consumed}.{cap}.{}` takes a type parameter, but none of its arguments determine it",
6180 method.name
6181 ),
6182 )
6183 .with_note(format!(
6184 "a qualified cross-context call takes its type arguments explicitly: `{consumed}.{cap}.{}[T](…)`",
6185 method.name
6186 )),
6187 );
6188 for a in args {
6189 let _ = type_of(a, None, ctx);
6190 }
6191 return None;
6192 }
6193 if type_args.len() != op.type_params.len() {
6194 ctx.errors.push(CompileError::new(
6195 "bynk.generics.type_arg_mismatch",
6196 method.span,
6197 format!(
6198 "capability operation `{consumed}.{cap}.{}` takes {} type argument(s), but {} were given",
6199 method.name,
6200 op.type_params.len(),
6201 type_args.len()
6202 ),
6203 ));
6204 for a in args {
6205 let _ = type_of(a, None, ctx);
6206 }
6207 return None;
6208 }
6209 for (tp, ta) in op.type_params.iter().zip(type_args) {
6210 let ty = resolve_expr_type_ref(ta, ctx)?;
6211 subst.insert(tp.clone(), ty);
6212 }
6213 }
6214 if !op.codable_params.is_empty() {
6217 if !check_op_codable_args(
6218 &format!("{consumed}.{cap}.{}", method.name),
6219 method.span,
6220 &op.codable_params,
6221 &subst,
6222 ctx,
6223 ) {
6224 for a in args {
6225 let _ = type_of(a, None, ctx);
6226 }
6227 return None;
6228 }
6229 let patterns: Vec<TyId> = op
6230 .params
6231 .iter()
6232 .map(|(_, tr)| {
6233 resolve_type_ref_in(tr, &consumed_types, &vars, tys).unwrap_or(tys.intern(Ty::Unit))
6234 })
6235 .collect();
6236 let ret_pattern = resolve_type_ref_in(&op.return_type, &consumed_types, &vars, tys)
6237 .unwrap_or(tys.intern(Ty::Unit));
6238 if let Some(wire) = op_encoding(
6239 &op.type_params,
6240 &op.codable_params,
6241 &patterns,
6242 ret_pattern,
6243 op.reply_policy,
6244 &subst,
6245 tys,
6246 ) {
6247 if !check_reply_codable(
6248 &format!("{consumed}.{cap}.{}", method.name),
6249 method.span,
6250 &op.codable_params,
6251 &wire,
6252 ctx,
6253 ) {
6254 for a in args {
6255 let _ = type_of(a, None, ctx);
6256 }
6257 return None;
6258 }
6259 ctx.callees.insert(
6260 expr_id,
6261 Callee::CrossCap {
6262 unit: consumed.to_string(),
6263 cap: cap.to_string(),
6264 op: method.name.clone(),
6265 wire: Some(wire),
6266 first_party: cross_first_party(consumed, cap),
6267 },
6268 );
6269 }
6270 }
6271 let (caller_types, ambiguous) = projected_types(&ctx.input.types, &info.consumed_types, tys);
6274 let mut all_ok = true;
6275 for (i, ((pname, ptype_ref), arg)) in op.params.iter().zip(args.iter()).enumerate() {
6276 record_param_hint(ctx.hints, pname, arg);
6277 let param_ty = resolve_type_ref_in(ptype_ref, &consumed_types, &vars, tys)
6278 .unwrap_or(tys.intern(Ty::Unit));
6279 let param_ty = substitute(param_ty, &subst, tys);
6280 let (arg_ty, crosses) =
6282 type_cross_context_arg(arg, param_ty, &caller_types, &consumed_types, consumed, ctx);
6283 let Some(arg_ty) = arg_ty else {
6284 all_ok = false;
6285 continue;
6286 };
6287 if !crosses {
6288 let mut err = CompileError::new(
6289 "bynk.boundary.structural_mismatch",
6290 arg.span,
6291 format!(
6292 "cross-context argument {} to `{consumed}.{cap}.{}` has type `{}`, but parameter `{pname}` expects `{}`",
6293 i + 1,
6294 method.name,
6295 arg_ty.display(tys),
6296 param_ty.display(tys),
6297 ),
6298 );
6299 if let Some(note) = ambiguous_projection_note(arg_ty, &ambiguous, tys) {
6300 err = err.with_note(note);
6301 }
6302 ctx.errors.push(err);
6303 all_ok = false;
6304 }
6305 }
6306 if !all_ok {
6307 return None;
6308 }
6309 let raw_ret = resolve_type_ref_in(&op.return_type, &consumed_types, &vars, tys)
6310 .unwrap_or(tys.intern(Ty::Unit));
6311 let raw_ret = substitute(raw_ret, &subst, tys);
6312 let rebrand_types = rebrand_table(&ctx.input.types, &consumed_types);
6313 if let Some(name) =
6314 rebrand_conflict(raw_ret, &consumed_types, &rebrand_types, &caller_types, tys)
6315 {
6316 ctx.errors.push(rebranded_return_mismatch(
6317 &format!("{consumed}.{cap}.{}", method.name),
6318 &name,
6319 consumed,
6320 false,
6321 span,
6322 ctx,
6323 ));
6324 return None;
6325 }
6326 Some(rebrand_return_type(raw_ret, &rebrand_types, tys))
6327}
6328
6329fn rebranded_return_mismatch(
6333 callee: &str,
6334 name: &str,
6335 consumed: &str,
6336 in_param: bool,
6337 span: Span,
6338 ctx: &Ctx,
6339) -> CompileError {
6340 let caller = ctx
6341 .input
6342 .cross_context
6343 .self_context
6344 .as_deref()
6345 .unwrap_or("?");
6346 CompileError::new(
6347 "bynk.boundary.structural_mismatch",
6348 span,
6349 format!(
6350 "cross-context call `{callee}` {} `{consumed}`'s type `{name}`, but `{name}` in \
6351 `{caller}` is a different type",
6352 if in_param {
6353 "takes as a parameter"
6354 } else {
6355 "returns"
6356 }
6357 ),
6358 )
6359 .with_note(
6360 "a value crossing the boundary takes the receiving context's type of the same name, so \
6361 the two must be structurally compatible; rename one of them",
6362 )
6363}
6364
6365fn type_cross_context_arg(
6388 arg: &Expr,
6389 param_ty: TyId,
6390 caller_types: &HashMap<String, Arc<TypeDecl>>,
6391 consumed_types: &HashMap<String, Arc<TypeDecl>>,
6392 consumed: &str,
6393 ctx: &mut Ctx,
6394) -> (Option<TyId>, bool) {
6395 let tys = ctx.tys;
6396 let mut found = CrossingPositions::default();
6397 collect_crossing_positions(arg, param_ty, caller_types, consumed_types, tys, &mut found);
6398 let CrossingPositions {
6399 literals,
6400 mut leaves,
6401 bindings,
6402 } = found;
6403 for (lit, pos) in literals {
6404 let before = ctx.errors.len();
6405 match admit_refined_literal_in(lit, Some(pos), consumed_types, ctx) {
6406 Some(ty) => {
6407 for err in &mut ctx.errors[before..] {
6408 err.notes.push(format!(
6409 "`{}` is the type at this position of the parameter, as `{consumed}` declares it",
6410 ty.display(tys)
6411 ));
6412 }
6413 ctx.admitted_literals.insert(lit.id, ty);
6414 }
6415 None => leaves.push((lit, pos)),
6417 }
6418 }
6419 let arg_ty = type_of(arg, Some(param_ty), ctx);
6420 let Some(ty) = arg_ty else {
6421 return (None, false);
6422 };
6423 let whole = || structurally_compatible(ty, param_ty, caller_types, consumed_types, tys);
6424 let leaves_cross = leaves.iter().all(|(leaf, pos)| {
6425 match ctx.expr_types.get(&leaf.id) {
6428 Some(t) => structurally_compatible(t.ty, *pos, caller_types, consumed_types, tys),
6429 None => whole(),
6430 }
6431 });
6432 let bindings_cross = bindings.iter().all(|(name, pos)| match ctx.lookup(name) {
6433 Some(t) => structurally_compatible(t, *pos, caller_types, consumed_types, tys),
6434 None => whole(),
6435 });
6436 (arg_ty, leaves_cross && bindings_cross)
6437}
6438
6439#[derive(Default)]
6443struct CrossingPositions<'e> {
6444 literals: Vec<(&'e Expr, TyId)>,
6446 leaves: Vec<(&'e Expr, TyId)>,
6448 bindings: Vec<(&'e str, TyId)>,
6450}
6451
6452fn collect_crossing_positions<'e>(
6462 e: &'e Expr,
6463 pos: TyId,
6464 caller_types: &HashMap<String, Arc<TypeDecl>>,
6465 consumed_types: &HashMap<String, Arc<TypeDecl>>,
6466 tys: &Types,
6467 found: &mut CrossingPositions<'e>,
6468) {
6469 let node = tys.get(pos);
6470 let walk = |inner: &'e Expr, at: TyId, found: &mut CrossingPositions<'e>| {
6471 collect_crossing_positions(inner, at, caller_types, consumed_types, tys, found)
6472 };
6473 if const_literal(e).is_some()
6475 && matches!(
6476 &*node,
6477 Ty::Named {
6478 kind: NamedKind::Refined(_),
6479 ..
6480 }
6481 )
6482 {
6483 return found.literals.push((e, pos));
6484 }
6485 match (&e.kind, &*node) {
6486 (ExprKind::Paren(inner), _) => walk(inner, pos, found),
6487 (ExprKind::None, Ty::Option(_)) => {}
6489 (ExprKind::ListLit(items, ..), Ty::List(_)) if items.is_empty() => {}
6490 (
6492 ExprKind::MethodCall {
6493 receiver,
6494 method,
6495 type_args,
6496 args,
6497 ..
6498 },
6499 Ty::List(_) | Ty::Map(..) | Ty::Set(_),
6500 ) if method.name == "empty"
6501 && type_args.is_empty()
6502 && args.is_empty()
6503 && matches!(
6504 &receiver.kind,
6505 ExprKind::Ident(id)
6506 if id.name == match &*node {
6507 Ty::List(_) => "List",
6508 Ty::Set(_) => "Set",
6509 _ => "Map",
6510 }
6511 ) => {}
6512 (ExprKind::Some(inner), Ty::Option(t)) => walk(inner, *t, found),
6513 (ExprKind::Ok(inner), Ty::Result(t, _)) => walk(inner, *t, found),
6514 (ExprKind::Err(inner), Ty::Result(_, t)) => walk(inner, *t, found),
6515 (ExprKind::ListLit(items, ..), Ty::List(t)) => {
6516 for item in items {
6517 walk(item, *t, found);
6518 }
6519 }
6520 (
6521 ExprKind::RecordConstruction {
6522 type_name, fields, ..
6523 },
6524 Ty::Named {
6525 name,
6526 kind: NamedKind::Record,
6527 args,
6528 },
6529 ) if type_name.name == *name => {
6530 let Some(field_positions) =
6531 record_field_positions(name, args, fields, caller_types, consumed_types, tys)
6532 else {
6533 return found.leaves.push((e, pos));
6534 };
6535 for (f, field_ty) in field_positions {
6536 match &f.value {
6537 Some(value) => walk(value, field_ty, found),
6538 None => found.bindings.push((f.name.name.as_str(), field_ty)),
6540 }
6541 }
6542 }
6543 _ => found.leaves.push((e, pos)),
6544 }
6545}
6546
6547fn record_field_positions<'f>(
6554 name: &str,
6555 args: &[TyId],
6556 fields: &'f [FieldInit],
6557 caller_types: &HashMap<String, Arc<TypeDecl>>,
6558 consumed_types: &HashMap<String, Arc<TypeDecl>>,
6559 tys: &Types,
6560) -> Option<Vec<(&'f FieldInit, TyId)>> {
6561 let decl = consumed_types.get(name)?;
6562 if !caller_types.get(name).is_some_and(|c| Arc::ptr_eq(c, decl)) {
6563 return None;
6564 }
6565 let TypeBody::Record(record) = &decl.body else {
6566 return None;
6567 };
6568 if decl.type_params.len() != args.len() {
6569 return None;
6570 }
6571 let vars: HashSet<String> = decl
6572 .type_params
6573 .iter()
6574 .map(|p| p.name.name.clone())
6575 .collect();
6576 let subst: HashMap<String, TyId> = decl
6577 .type_params
6578 .iter()
6579 .map(|p| p.name.name.clone())
6580 .zip(args.iter().copied())
6581 .collect();
6582 fields
6583 .iter()
6584 .map(|f| {
6585 let declared = record.fields.iter().find(|d| d.name.name == f.name.name)?;
6586 let ty = resolve_type_ref_in(&declared.type_ref, consumed_types, &vars, tys)?;
6587 Some((f, substitute(ty, &subst, tys)))
6588 })
6589 .collect()
6590}
6591
6592fn check_signature_owners_consumed(
6598 consumed: &str,
6599 service: &crate::resolver::CrossContextService,
6600 method: &Ident,
6601 ctx: &mut Ctx,
6602) -> bool {
6603 let info = &ctx.input.cross_context;
6604 let Some(owners) = info.consumed_type_owners.get(consumed) else {
6605 return false;
6606 };
6607 let types = info.consumed_types.get(consumed);
6608 let mut seen: HashSet<String> = HashSet::new();
6609 let mut stack: Vec<String> = Vec::new();
6610 let vars = HashSet::new();
6611 for (_, t) in &service.params {
6612 crate::project_model::type_ref_names(t, &vars, &mut stack);
6613 }
6614 crate::project_model::type_ref_names(&service.return_type, &vars, &mut stack);
6615 let mut missing: std::collections::BTreeMap<String, String> = Default::default();
6616 while let Some(n) = stack.pop() {
6617 if !seen.insert(n.clone()) {
6618 continue;
6619 }
6620 if let Some(owner) = owners.get(&n)
6621 && info.self_context.as_deref() != Some(owner.as_str())
6622 && !info.consumed_contexts.contains(owner)
6623 {
6624 let declared = n
6627 .strip_prefix(&format!("{}__", owner.replace('.', "_")))
6628 .unwrap_or(&n)
6629 .to_string();
6630 missing.entry(owner.clone()).or_insert(declared);
6631 }
6632 if let Some(d) = types.and_then(|t| t.get(&n)) {
6633 stack.extend(crate::project_model::type_decl_ref_names(d));
6634 }
6635 }
6636 let refused = !missing.is_empty();
6637 for (owner, ty) in missing {
6638 ctx.errors.push(
6639 CompileError::new(
6640 "bynk.consumes.signature_type_unconsumed",
6641 method.span,
6642 format!(
6643 "`{consumed}.{}` takes or returns `{ty}`, declared in `{owner}`, but this context does not consume `{owner}`",
6644 method.name
6645 ),
6646 )
6647 .with_note(format!(
6648 "add `consumes {owner}`: a value of `{ty}` crosses this call as `{owner}`'s type"
6649 )),
6650 );
6651 }
6652 refused
6653}
6654
6655fn check_cross_context_call(
6656 receiver: &Expr,
6657 consumed: &str,
6658 method: &Ident,
6659 args: &[Expr],
6660 span: Span,
6661 expr_id: ExprId,
6663 ctx: &mut Ctx,
6664) -> Option<TyId> {
6665 let tys = ctx.tys;
6666 ctx.callees.insert(
6667 expr_id,
6668 Callee::Cross {
6669 unit: consumed.to_string(),
6670 service: method.name.clone(),
6671 },
6672 );
6673 if !ctx.effectful {
6676 ctx.errors.push(
6677 CompileError::new(
6678 "bynk.effect.cross_context_in_pure_context",
6679 method.span,
6680 format!(
6681 "cross-context service call `{}.{}` can only be made inside an effectful body (one returning `Effect[T]`)",
6682 consumed, method.name
6683 ),
6684 )
6685 .with_label(receiver.span, "consumed context prefix"),
6686 );
6687 }
6688 let info = &ctx.input.cross_context;
6689 let Some(svcs) = info.consumed_services.get(consumed) else {
6690 ctx.errors.push(
6691 CompileError::new(
6692 "bynk.consumes.unknown_context",
6693 receiver.span,
6694 format!("context `{consumed}` is not in scope here"),
6695 )
6696 .with_note(
6697 "add a `consumes` clause for the target context at the top of the consuming context",
6698 ),
6699 );
6700 for a in args {
6701 let _ = type_of(a, None, ctx);
6702 }
6703 return None;
6704 };
6705 let Some(service) = svcs.get(&method.name).cloned() else {
6706 ctx.errors.push(
6707 CompileError::new(
6708 "bynk.consumes.unknown_service",
6709 method.span,
6710 format!(
6711 "context `{consumed}` has no service named `{}`",
6712 method.name
6713 ),
6714 )
6715 .with_note(
6716 "cross-context calls require an `on call` service handler in the consumed context",
6717 ),
6718 );
6719 for a in args {
6720 let _ = type_of(a, None, ctx);
6721 }
6722 return None;
6723 };
6724 ctx.refs
6725 .record_in_unit(method.span, SymbolKind::Service, &method.name, consumed);
6726 ctx.refs.record_in_unit(
6730 method.span,
6731 SymbolKind::Handler,
6732 &format!("{}.call", method.name),
6733 consumed,
6734 );
6735 let unconsumed = check_signature_owners_consumed(consumed, &service, method, ctx);
6737
6738 if service.params.len() != args.len() {
6739 ctx.errors.push(
6740 CompileError::new(
6741 "bynk.consumes.service_arity",
6742 method.span,
6743 format!(
6744 "cross-context service `{consumed}.{}` expects {} argument(s), but {} were given",
6745 method.name,
6746 service.params.len(),
6747 args.len()
6748 ),
6749 )
6750 .with_note("service declared here"),
6756 );
6757 for a in args {
6758 let _ = type_of(a, None, ctx);
6759 }
6760 return None;
6761 }
6762
6763 let consumed_types = info
6765 .consumed_types
6766 .get(consumed)
6767 .cloned()
6768 .unwrap_or_default();
6769
6770 let (caller_types, ambiguous) = projected_types(&ctx.input.types, &info.consumed_types, tys);
6773
6774 let mut all_ok = true;
6776 for (i, ((pname, ptype_ref), arg)) in service.params.iter().zip(args.iter()).enumerate() {
6777 record_param_hint(ctx.hints, pname, arg);
6778 let param_ty =
6779 resolve_type_ref(ptype_ref, &consumed_types, tys).unwrap_or(tys.intern(Ty::Unit));
6780 let (arg_ty, crosses) =
6783 type_cross_context_arg(arg, param_ty, &caller_types, &consumed_types, consumed, ctx);
6784 let Some(arg_ty) = arg_ty else {
6785 all_ok = false;
6786 continue;
6787 };
6788 if !crosses && !unconsumed {
6789 let mut err = CompileError::new(
6790 "bynk.boundary.structural_mismatch",
6791 arg.span,
6792 format!(
6793 "cross-context argument {} to `{consumed}.{}` has type `{}` in `{}`, but parameter `{pname}` expects `{}` in `{}`",
6794 i + 1,
6795 method.name,
6796 arg_ty.display(tys),
6797 ctx.input
6798 .cross_context
6799 .self_context
6800 .as_deref()
6801 .unwrap_or("?"),
6802 param_ty.display(tys),
6803 consumed,
6804 ),
6805 )
6806 .with_note("service declared here")
6808 .with_note(
6809 "values crossing a context boundary must have structurally compatible types (same commons-derived type, or identical record/sum shape)",
6810 );
6811 if let Some(note) = ambiguous_projection_note(arg_ty, &ambiguous, tys) {
6812 err = err.with_note(note);
6813 }
6814 ctx.errors.push(err);
6815 all_ok = false;
6816 }
6817 }
6818 if !all_ok {
6819 return None;
6820 }
6821
6822 let raw_ret = resolve_type_ref(&service.return_type, &consumed_types, tys)
6826 .unwrap_or(tys.intern(Ty::Unit));
6827 let rebrand_types = rebrand_table(&ctx.input.types, &consumed_types);
6828 if let Some(name) =
6829 rebrand_conflict(raw_ret, &consumed_types, &rebrand_types, &caller_types, tys)
6830 {
6831 ctx.errors.push(rebranded_return_mismatch(
6832 &format!("{consumed}.{}", method.name),
6833 &name,
6834 consumed,
6835 false,
6836 span,
6837 ctx,
6838 ));
6839 return None;
6840 }
6841 Some(rebrand_return_type(raw_ret, &rebrand_types, tys))
6842}
6843
6844pub(crate) fn with_of_hint(
6850 err: CompileError,
6851 actual: TyId,
6852 expected: TyId,
6853 ctx: &Ctx,
6854) -> CompileError {
6855 let Ty::Base(base) = *ctx.tys.get(actual) else {
6856 return err;
6857 };
6858 let ty = ctx.tys.get(expected);
6859 let Ty::Named {
6860 name,
6861 kind: NamedKind::Refined(b) | NamedKind::Opaque(b),
6862 args,
6863 } = &*ty
6864 else {
6865 return err;
6866 };
6867 if *b != base
6868 || !args.is_empty()
6869 || !(ctx.input.is_local_type(name) || ctx.input.is_uses_commons_type(name))
6870 {
6871 return err;
6872 }
6873 err.with_note(format!(
6874 "to make a `{name}` from a `{}`, use `{name}.of(value)`, which checks the value and returns a `Result`",
6875 base.name()
6876 ))
6877}
6878
6879fn reply_codable_or_type_args(
6883 op: &str,
6884 span: Span,
6885 codable: &[String],
6886 wire: &super::codable::CapEncoding,
6887 untyped: Option<&[Expr]>,
6888 ctx: &mut Ctx,
6889) -> bool {
6890 if check_reply_codable(op, span, codable, wire, ctx) {
6891 return true;
6892 }
6893 for a in untyped.unwrap_or_default() {
6894 let _ = type_of(a, None, ctx);
6895 }
6896 false
6897}
6898
6899fn record_capability_wire(
6903 op: &CapabilityOpInfo,
6904 (cap, name): (&str, &str),
6905 span: Span,
6906 expr_id: ExprId,
6907 subst: &HashMap<String, TyId>,
6908 untyped: Option<&[Expr]>,
6909 ctx: &mut Ctx,
6910) -> bool {
6911 let Some(wire) = op_encoding(
6912 &op.type_params,
6913 &op.codable_params,
6914 &op.params,
6915 op.return_ty,
6916 op.reply_policy,
6917 subst,
6918 ctx.tys,
6919 ) else {
6920 return true;
6921 };
6922 if !reply_codable_or_type_args(
6923 &format!("{cap}.{name}"),
6924 span,
6925 &op.codable_params,
6926 &wire,
6927 untyped,
6928 ctx,
6929 ) {
6930 return false;
6931 }
6932 ctx.callees.insert(
6933 expr_id,
6934 Callee::Capability {
6935 cap: cap.to_string(),
6936 op: name.to_string(),
6937 wire: Some(wire),
6938 first_party: local_first_party(cap, ctx),
6939 event: None,
6940 },
6941 );
6942 true
6943}
6944
6945#[cfg(test)]
6946mod tests {
6947 use crate::testkit::analyse;
6948
6949 fn commons(body: &str) -> crate::testkit::Analysed {
6951 analyse(&[("demo.bynk", &format!("commons demo\n\n{body}"))])
6952 }
6953
6954 fn context(body: &str) -> crate::testkit::Analysed {
6956 analyse(&[("demo.bynk", &format!("context demo\n\n{body}"))])
6957 }
6958
6959 const CLOCK: &str = "capability Clock {\n fn now() -> Effect[Int]\n}\n\n\
6960 provides Clock = FixedClock {\n fn now() -> Effect[Int] {\n Effect.pure(0)\n }\n}\n";
6961
6962 #[test]
6963 fn a_call_to_a_declared_fn_has_its_return_type() {
6964 let a = commons("fn double(x: Int) -> Int { x * 2 }\n\nfn four() -> Int { double(2) }\n");
6965 a.assert_clean();
6966 assert_eq!(a.type_at("demo.bynk", "double(2)"), "Int");
6967 }
6968
6969 #[test]
6970 fn an_argument_of_the_wrong_type_is_a_mismatch() {
6971 let a = commons(
6972 "fn double(x: Int) -> Int { x * 2 }\n\nfn bad(s: String) -> Int { double(s) }\n",
6973 );
6974 a.assert_reports("bynk.types.argument_mismatch");
6975 }
6976
6977 #[test]
6978 fn a_fn_called_with_too_many_arguments_is_an_arity_error() {
6979 let a = commons("fn double(x: Int) -> Int { x * 2 }\n\nfn bad() -> Int { double(1, 2) }\n");
6980 a.assert_reports("bynk.resolve.arity_mismatch");
6981 }
6982
6983 #[test]
6984 fn a_fn_value_called_with_too_many_arguments_is_a_call_arity_error() {
6985 let a = commons("fn f(g: (Int) -> Int) -> Int { g(1, 2) }\n");
6986 a.assert_reports("bynk.types.call_arity");
6987 }
6988
6989 #[test]
6990 fn a_fn_value_call_has_the_value_s_return_type() {
6991 let a = commons("fn f(g: (Int) -> String) -> String { g(1) }\n");
6992 a.assert_clean();
6993 assert_eq!(a.type_at("demo.bynk", "g(1)"), "String");
6994 }
6995
6996 #[test]
6997 fn a_generic_call_infers_its_type_argument_from_the_argument() {
6998 let a = commons("fn id[A](x: A) -> A { x }\n\nfn s() -> String { id(\"s\") }\n");
6999 a.assert_clean();
7000 assert_eq!(a.type_at("demo.bynk", "id(\"s\")"), "String");
7001 }
7002
7003 #[test]
7004 fn a_list_literal_argument_infers_the_type_argument() {
7005 let a = commons(
7006 "fn size[T](xs: List[T]) -> Int { 0 }\n\n\
7007 fn s() -> Int { size([1, 2]) }\n\n\
7008 fn n() -> Int { size([[1], [2, 3]]) }\n",
7009 );
7010 a.assert_clean();
7011 }
7012
7013 #[test]
7014 fn a_list_literal_argument_grounds_a_later_lambda() {
7015 let a = commons(
7016 "fn count_by[T](xs: List[T], f: (T) -> Int) -> Int { 0 }\n\n\
7017 fn s() -> Int { count_by([\"ant\", \"bee\"], (w) => w.length()) }\n",
7018 );
7019 a.assert_clean();
7020 }
7021
7022 #[test]
7023 fn list_literals_binding_one_type_argument_two_ways_still_conflict() {
7024 let a = commons(
7025 "fn size2[T](a: List[T], b: List[T]) -> Int { 0 }\n\n\
7026 fn bad() -> Int { size2([1], [\"x\"]) }\n",
7027 );
7028 a.assert_reports("bynk.types.list_element_mismatch");
7029 }
7030
7031 #[test]
7032 fn a_list_literal_with_mixed_elements_is_still_a_mismatch_in_a_generic_call() {
7033 let a = commons(
7034 "fn size[T](xs: List[T]) -> Int { 0 }\n\n\
7035 fn bad() -> Int { size([1, \"x\"]) }\n",
7036 );
7037 a.assert_reports("bynk.types.list_element_mismatch");
7038 }
7039
7040 #[test]
7041 fn a_some_argument_infers_the_type_argument() {
7042 let a = commons(
7043 "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7044 fn one[T](x: Option[T]) -> Int { 0 }\n\n\
7045 fn s() -> Int { size([None, Some(1)]) }\n\n\
7046 fn t() -> Int { one(Some(\"a\")) }\n",
7047 );
7048 a.assert_clean();
7049 }
7050
7051 #[test]
7052 fn ok_and_err_arguments_infer_the_type_arguments() {
7053 let a = commons(
7054 "fn okay[T](x: Result[T, String]) -> Int { 0 }\n\n\
7055 fn bad[E](x: Result[Int, E]) -> Int { 0 }\n\n\
7056 fn s() -> Int { okay(Ok(1)) }\n\n\
7057 fn t() -> Int { bad(Err(\"x\")) }\n",
7058 );
7059 a.assert_clean();
7060 }
7061
7062 #[test]
7063 fn a_mixed_some_list_in_a_generic_call_still_reports() {
7064 let a = commons(
7065 "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7066 fn bad() -> Int { size([None, Some(1), Some(\"a\")]) }\n",
7067 );
7068 a.assert_reports("bynk.types.some_value_mismatch");
7069 }
7070
7071 #[test]
7072 fn an_all_deferred_list_does_not_come_back_untyped() {
7073 let a = commons(
7074 "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7075 fn s() -> Int { size([None]) }\n",
7076 );
7077 let b = commons(
7078 "fn size[T](xs: List[Option[T]]) -> Int { 0 }\n\n\
7079 fn s() -> Int { size([]) }\n",
7080 );
7081 a.assert_clean();
7084 b.assert_clean();
7085 }
7086
7087 #[test]
7088 fn an_http_result_ok_argument_infers_the_type_argument() {
7089 let a = commons(
7090 "fn h[T](x: HttpResult[T]) -> Int { 0 }\n\n\
7091 fn s() -> Int { h(Ok(1)) }\n",
7092 );
7093 a.assert_clean();
7094 }
7095
7096 #[test]
7097 fn a_context_typed_payload_inside_some_ok_and_err_keeps_its_context() {
7098 let a = commons(
7099 "fn one[T](x: Option[Option[T]]) -> Int { 0 }\n\n\
7100 fn two[T](x: Option[List[T]]) -> Int { 0 }\n\n\
7101 fn three[T](x: Result[Option[T], String]) -> Int { 0 }\n\n\
7102 fn four[T](x: Result[Int, Option[T]]) -> Int { 0 }\n\n\
7103 fn s() -> Int { one(Some(None)) }\n\n\
7104 fn t() -> Int { two(Some([])) }\n\n\
7105 fn u() -> Int { three(Ok(None)) }\n\n\
7106 fn v() -> Int { four(Err(None)) }\n",
7107 );
7108 a.assert_clean();
7109 }
7110
7111 #[test]
7112 fn a_lambda_payload_inside_some_and_ok_keeps_its_parameter_types() {
7113 let a = commons(
7114 "fn ap[T](f: Option[(Int) -> T]) -> Int { 0 }\n\n\
7115 fn bp[T](f: Result[(Int) -> T, String]) -> Int { 0 }\n\n\
7116 fn s() -> Int { ap(Some((x) => x + 1)) }\n\n\
7117 fn t() -> Int { bp(Ok((x) => x + 1)) }\n",
7118 );
7119 a.assert_clean();
7120 }
7121
7122 #[test]
7123 fn mixed_deferred_ok_and_err_elements_infer_both_type_arguments() {
7124 let a = commons(
7125 "fn size[T, E](xs: List[Result[T, E]]) -> Int { 0 }\n\n\
7126 fn s() -> Int { size([Ok(1), Err(\"x\")]) }\n\n\
7127 fn t() -> Int { size([Err(\"x\"), Ok(1)]) }\n",
7128 );
7129 a.assert_clean();
7130 }
7131
7132 #[test]
7133 fn mixed_deferred_result_elements_that_disagree_still_report() {
7134 for list in [
7135 "[Ok(1), Err(\"x\"), Err(2)]",
7136 "[Err(\"x\"), Ok(1), Ok(\"a\")]",
7137 ] {
7138 let a = commons(&format!(
7139 "fn size[T, E](xs: List[Result[T, E]]) -> Int {{ 0 }}\n\n\
7140 fn bad() -> Int {{ size({list}) }}\n"
7141 ));
7142 assert!(
7145 a.categories().iter().any(|c| matches!(
7146 *c,
7147 "bynk.types.list_element_mismatch"
7148 | "bynk.types.err_value_mismatch"
7149 | "bynk.types.ok_value_mismatch"
7150 )),
7151 "{list} should report, got {:?}",
7152 a.categories()
7153 );
7154 }
7155 }
7156
7157 #[test]
7158 fn mixed_deferred_elements_solve_the_type_arguments_they_supply() {
7159 let a = commons(
7160 "fn first_err[T, E](xs: List[Result[T, E]]) -> Option[E] { None }\n\n\
7161 fn s() -> Option[String] { first_err([Ok(1), Err(\"x\")]) }\n",
7162 );
7163 a.assert_clean();
7164 }
7165
7166 #[test]
7167 fn deferred_siblings_merge_through_fn_and_effect_types_in_either_order() {
7168 for list in [
7169 "[Err(\"x\"), Ok((x) => x + 1)]",
7170 "[Ok((x) => x + 1), Err(\"x\")]",
7171 ] {
7172 let a = commons(&format!(
7173 "fn size[T, E](xs: List[Result[(Int) -> T, E]]) -> Int {{ 0 }}\n\n\
7174 fn s() -> Int {{ size({list}) }}\n"
7175 ));
7176 a.assert_clean();
7177 }
7178 }
7179
7180 #[test]
7181 fn deferred_siblings_merge_through_nested_effect_types() {
7182 let a = commons(
7183 "fn size[T](xs: List[Option[Effect[T]]]) -> Int { 0 }\n\n\
7184 fn s(e: Effect[Int]) -> Int { size([None, Some(e)]) }\n\n\
7185 fn t(e: Effect[Int]) -> Int { size([Some(e), None]) }\n",
7186 );
7187 a.assert_clean();
7188 }
7189
7190 #[test]
7191 fn deferred_fn_siblings_that_disagree_still_report() {
7192 let a = commons(
7193 "fn size[T, E](xs: List[Result[(Int) -> T, E]]) -> Int { 0 }\n\n\
7194 fn bad() -> Int { size([Ok((x) => x + 1), Ok((x) => \"s\")]) }\n",
7195 );
7196 a.assert_reports("bynk.types.lambda_mismatch");
7197 }
7198
7199 #[test]
7200 fn deferred_effect_siblings_that_disagree_still_report() {
7201 let a = commons(
7202 "fn size[T](xs: List[Option[Effect[T]]]) -> Int { 0 }\n\n\
7203 fn bad(a: Effect[Int], b: Effect[String]) -> Int { size([None, Some(a), Some(b)]) }\n",
7204 );
7205 a.assert_reports("bynk.types.some_value_mismatch");
7206 }
7207
7208 #[test]
7209 fn a_concrete_some_mismatch_still_reports() {
7210 let a = commons("fn f() -> Int { let x: Option[Int] = Some(\"a\")\n 0 }\n");
7211 a.assert_reports("bynk.types.some_value_mismatch");
7212 }
7213
7214 #[test]
7215 fn a_some_argument_conflicting_with_a_bound_type_argument_still_reports() {
7216 let a = commons(
7217 "fn two[T](a: Option[T], b: Option[T]) -> Int { 0 }\n\n\
7218 fn bad() -> Int { two(Some(1), Some(\"x\")) }\n",
7219 );
7220 a.assert_reports("bynk.types.some_value_mismatch");
7221 }
7222
7223 #[test]
7224 fn a_generic_call_binding_one_type_argument_two_ways_is_a_conflict() {
7225 let a =
7226 commons("fn both[A](x: A, y: A) -> A { x }\n\nfn bad() -> Int { both(1, \"two\") }\n");
7227 a.assert_reports("bynk.generics.type_arg_mismatch");
7228 }
7229
7230 #[test]
7231 fn a_type_argument_no_parameter_mentions_is_uninferable() {
7232 let a = commons(
7233 "fn first_of[A](x: Int) -> A { identity_helper(x) }\n\n\
7234 fn identity_helper[A](x: A) -> A { x }\n\n\
7235 fn misuse() -> Int { let y = first_of(5)\n 0 }\n",
7236 );
7237 a.assert_reports("bynk.generics.uninferable_type_arg");
7238 }
7239
7240 #[test]
7241 fn calling_an_undeclared_name_is_an_unknown_function() {
7242 let a = commons("fn bad() -> Int { nope(1) }\n");
7243 a.assert_reports("bynk.resolve.unknown_function");
7244 }
7245
7246 #[test]
7247 fn calling_a_record_type_like_a_function_is_rejected() {
7248 let a = commons("type P = { a: Int }\n\nfn f() -> P { P(1) }\n");
7249 a.assert_reports("bynk.resolve.type_as_function");
7250 }
7251
7252 #[test]
7253 fn a_capability_op_call_has_the_op_s_return_type() {
7254 let a = context(&format!(
7255 "{CLOCK}\nservice probe {{\n on call() -> Effect[Int] by Caller given Clock {{\n Clock.now()\n }}\n}}\n"
7256 ));
7257 a.assert_clean();
7258 assert_eq!(a.type_at("demo.bynk", "Clock.now()"), "Effect[Int]");
7259 }
7260
7261 #[test]
7262 fn a_capability_op_called_with_an_extra_argument_is_an_arity_error() {
7263 let a = context(&format!(
7264 "{CLOCK}\nservice probe {{\n on call() -> Effect[Int] by Caller given Clock {{\n Clock.now(1)\n }}\n}}\n"
7265 ));
7266 a.assert_reports("bynk.capability.op_arity");
7267 }
7268
7269 #[test]
7270 fn a_capability_called_inside_a_pure_lambda_is_rejected() {
7271 let a = context(&format!(
7272 "{CLOCK}\nservice probe {{\n on call() -> Effect[Int] by Caller given Clock {{\n \
7273 let f: (Int) -> Int = (n) => Clock.now()\n Effect.pure(1)\n }}\n}}\n"
7274 ));
7275 a.assert_reports("bynk.effect.capability_in_pure_context");
7276 }
7277
7278 #[test]
7279 fn an_unknown_cell_op_is_rejected() {
7280 let a = context(
7281 "agent Counter {\n key id: String\n store n: Cell[Int] = 0\n\n \
7282 on call bad() -> Effect[()] {\n let _ <- n.foo()\n Effect.pure(())\n }\n}\n",
7283 );
7284 a.assert_reports("bynk.store.unknown_op");
7285 }
7286
7287 #[test]
7288 fn a_cell_update_is_an_effect_of_unit() {
7289 let a = context(
7290 "agent Counter {\n key id: String\n store n: Cell[Int] = 0\n\n \
7291 on call bump() -> Effect[()] {\n n.update((c) => c + 1)\n }\n}\n",
7292 );
7293 a.assert_clean();
7294 assert_eq!(
7295 a.type_at("demo.bynk", "n.update((c) => c + 1)"),
7296 "Effect[()]"
7297 );
7298 }
7299
7300 #[test]
7301 fn a_cell_update_whose_function_returns_another_type_is_a_mismatch() {
7302 let a = context(
7303 "agent Counter {\n key id: String\n store n: Cell[Int] = 0\n\n \
7304 on call bad() -> Effect[()] {\n n.update((c) => \"x\")\n }\n}\n",
7305 );
7306 a.assert_reports("bynk.types.lambda_mismatch");
7307 }
7308
7309 #[test]
7310 fn a_cell_update_with_no_function_is_a_call_arity_error() {
7311 let a = context(
7312 "agent Counter {\n key id: String\n store n: Cell[Int] = 0\n\n \
7313 on call bad() -> Effect[()] {\n n.update()\n }\n}\n",
7314 );
7315 a.assert_reports("bynk.types.call_arity");
7316 }
7317
7318 const SHOP: &str = "context shop\n\nexports capability { Store }\n\n\
7322 type Amount = { cents: Int }\n\ntype Box = { a: Amount }\n\n\
7323 capability Store {\n fn get() -> Effect[Box]\n fn put(b: Box) -> Effect[Int]\n}\n\n\
7324 provides Store = Shelf {\n fn get() -> Effect[Box] {\n Effect.pure(Box { a: Amount { cents: 1 } })\n }\n\n \
7325 fn put(b: Box) -> Effect[Int] {\n Effect.pure(b.a.cents)\n }\n}\n\n\
7326 service quote {\n on call() -> Effect[Box] by Caller {\n Effect.pure(Box { a: Amount { cents: 1 } })\n }\n}\n\n\
7327 service take {\n on call(b: Box) -> Effect[Int] by Caller {\n Effect.pure(b.a.cents)\n }\n}\n";
7328
7329 fn till(decls: &str, body: &str) -> String {
7332 let given = if body.contains("Store") {
7333 " given shop.Store"
7334 } else {
7335 ""
7336 };
7337 format!(
7338 "context till\n\nconsumes shop\n\n{decls}service total {{\n \
7339 on call() -> Effect[Int] by Caller{given} {{\n{body}\n }}\n}}\n"
7340 )
7341 }
7342
7343 fn label_provider(max: u32) -> String {
7347 format!(
7348 "context shop\n\ntype Label = String where MaxLength({max})\n\n\
7349 service label {{\n on call() -> Effect[Result[Label, Int]] by Caller {{\n Effect.pure(Ok(\"a\"))\n }}\n}}\n"
7350 )
7351 }
7352
7353 #[test]
7354 fn a_stronger_returned_refinement_is_admitted_by_the_callers_same_named_type() {
7355 let a = analyse(&[
7356 ("shop.bynk", &label_provider(4)),
7357 (
7358 "till.bynk",
7359 &till(
7360 "type Label = String where MaxLength(8)\n\n",
7361 " let l <- shop.label()\n Effect.pure(0)",
7362 ),
7363 ),
7364 ]);
7365 a.assert_clean();
7366 }
7367
7368 #[test]
7369 fn a_weaker_returned_refinement_is_rejected_by_the_callers_same_named_type() {
7370 let a = analyse(&[
7371 ("shop.bynk", &label_provider(8)),
7372 (
7373 "till.bynk",
7374 &till(
7375 "type Label = String where MaxLength(4)\n\n",
7376 " let l <- shop.label()\n Effect.pure(0)",
7377 ),
7378 ),
7379 ]);
7380 a.assert_reports("bynk.boundary.structural_mismatch");
7381 }
7382
7383 fn opaque_provider(max: u32) -> String {
7389 format!(
7390 "context shop\n\ntype Tag = opaque String where MaxLength({max})\n\n\
7391 service check {{\n on call(t: Tag) -> Effect[Int] by Caller {{\n Effect.pure(0)\n }}\n}}\n"
7392 )
7393 }
7394
7395 fn opaque_till(max: u32) -> String {
7396 format!(
7397 "context till\n\nconsumes shop\n\ntype Tag = opaque String where MaxLength({max})\n\n\
7398 service total {{\n on call(t: Tag) -> Effect[Int] by Caller {{\n shop.check(t)\n }}\n}}\n"
7399 )
7400 }
7401
7402 #[test]
7403 fn a_stronger_opaque_sender_is_admitted_and_a_weaker_one_rejected() {
7404 analyse(&[
7405 ("shop.bynk", &opaque_provider(8)),
7406 ("till.bynk", &opaque_till(4)),
7407 ])
7408 .assert_clean();
7409 analyse(&[
7410 ("shop.bynk", &opaque_provider(4)),
7411 ("till.bynk", &opaque_till(8)),
7412 ])
7413 .assert_reports("bynk.boundary.structural_mismatch");
7414 }
7415
7416 #[test]
7421 fn equivalent_refinements_of_one_name_do_not_make_it_ambiguous() {
7422 let owner = "context shop\n\ntype Label = Int where Positive\n\n\
7423 service make {\n on call() -> Effect[Result[Label, Int]] by Caller {\n Effect.pure(Ok(1))\n }\n}\n\n\
7424 service take {\n on call(l: Label) -> Effect[Int] by Caller {\n Effect.pure(0)\n }\n}\n";
7425 let other = "context other\n\ntype Label = Int where Positive && NonNegative\n\n\
7426 service peek {\n on call() -> Effect[Int] by Caller {\n Effect.pure(0)\n }\n}\n";
7427 let till = "context till\n\nconsumes shop\n\nconsumes other\n\n\
7428 service total {\n on call() -> Effect[Int] by Caller {\n \
7429 let r <- shop.make()\n match r {\n Ok(l) => shop.take(l)\n Err(_) => Effect.pure(0)\n }\n }\n}\n";
7430 analyse(&[
7431 ("shop.bynk", owner),
7432 ("other.bynk", other),
7433 ("till.bynk", till),
7434 ])
7435 .assert_clean();
7436 }
7437
7438 #[test]
7439 fn an_unexported_value_passes_back_to_its_service() {
7440 let a = analyse(&[
7441 ("shop.bynk", SHOP),
7442 (
7443 "till.bynk",
7444 &till("", " let b <- shop.quote()\n shop.take(b)"),
7445 ),
7446 ]);
7447 a.assert_clean();
7448 }
7449
7450 #[test]
7451 fn an_unexported_value_passes_back_to_its_capability() {
7452 let a = analyse(&[
7453 ("shop.bynk", SHOP),
7454 (
7455 "till.bynk",
7456 &till("", " let b <- shop.Store.get()\n shop.Store.put(b)"),
7457 ),
7458 ]);
7459 a.assert_clean();
7460 }
7461
7462 #[test]
7463 fn a_caller_type_of_another_shape_cannot_receive_a_service_return() {
7464 let a = analyse(&[
7465 ("shop.bynk", SHOP),
7466 (
7467 "till.bynk",
7468 &till(
7469 "type Box = { label: String }\n\n",
7470 " let b <- shop.quote()\n Effect.pure(1)",
7471 ),
7472 ),
7473 ]);
7474 a.assert_reports("bynk.boundary.structural_mismatch");
7475 }
7476
7477 #[test]
7478 fn a_caller_type_of_another_shape_cannot_receive_a_capability_return() {
7479 let a = analyse(&[
7480 ("shop.bynk", SHOP),
7481 (
7482 "till.bynk",
7483 &till(
7484 "type Box = { label: String }\n\n",
7485 " let b <- shop.Store.get()\n Effect.pure(1)",
7486 ),
7487 ),
7488 ]);
7489 a.assert_reports("bynk.boundary.structural_mismatch");
7490 }
7491
7492 #[test]
7493 fn a_caller_type_of_the_same_shape_receives_a_return() {
7494 let a = analyse(&[
7495 ("shop.bynk", SHOP),
7496 (
7497 "till.bynk",
7498 &till(
7499 "type Coins = { cents: Int }\n\ntype Box = { a: Coins }\n\n",
7500 " let b <- shop.quote()\n let c <- shop.Store.get()\n \
7501 Effect.pure(b.a.cents + c.a.cents)",
7502 ),
7503 ),
7504 ]);
7505 a.assert_clean();
7506 }
7507
7508 #[test]
7509 fn an_ambiguous_unexported_name_explains_its_rejection() {
7510 let other = "context depot\n\ntype Box = { label: String }\n\n\
7511 service quote {\n on call() -> Effect[Box] by Caller {\n Effect.pure(Box { label: \"x\" })\n }\n}\n";
7512 let a = analyse(&[
7513 ("shop.bynk", SHOP),
7514 ("depot.bynk", other),
7515 (
7516 "till.bynk",
7517 "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7518 service total {\n on call() -> Effect[Int] by Caller {\n \
7519 let b <- shop.quote()\n shop.take(b)\n }\n}\n",
7520 ),
7521 ]);
7522 let err = a
7523 .analysis
7524 .errors
7525 .iter()
7526 .find(|e| e.error.category == "bynk.boundary.structural_mismatch")
7527 .expect("the argument is rejected");
7528 assert!(
7529 err.error
7530 .notes
7531 .iter()
7532 .any(|n| n.contains("more than one consumed context declares a type `Box`")),
7533 "{:?}",
7534 err.error.notes
7535 );
7536 }
7537
7538 #[test]
7539 fn a_return_the_caller_does_not_rebrand_is_not_checked_against_a_projection() {
7540 let pair = |name: &str, svc: &str| {
7546 format!(
7547 "context {name}\n\ntype Amount = {{ cents: Int }}\n\ntype Box = {{ a: Amount }}\n\n{svc}"
7548 )
7549 };
7550 let shop = pair(
7551 "shop",
7552 "service quote {\n on call() -> Effect[Box] by Caller {\n Effect.pure(Box { a: Amount { cents: 1 } })\n }\n}\n",
7553 );
7554 let depot = pair(
7555 "depot",
7556 "service store {\n on call(b: Box) -> Effect[Int] by Caller {\n Effect.pure(b.a.cents)\n }\n}\n",
7557 );
7558 let a = analyse(&[
7559 ("shop.bynk", &shop),
7560 ("depot.bynk", &depot),
7561 (
7562 "till.bynk",
7563 "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7564 type Amount = { dollars: Int }\n\n\
7565 fn mine() -> Amount {\n Amount { dollars: 1 }\n}\n\n\
7566 service total {\n on call() -> Effect[Int] by Caller {\n \
7567 let b <- shop.quote()\n Effect.pure(1)\n }\n}\n",
7568 ),
7569 ]);
7570 a.assert_clean();
7571 }
7572
7573 fn caller_box_differs_inside(ret: &str, value: &str) {
7577 let shop = format!(
7578 "context shop\n\ntype Box = {{ a: Int }}\n\n\
7579 service quote {{\n on call() -> Effect[{ret}] by Caller {{\n Effect.pure({value})\n }}\n}}\n"
7580 );
7581 let a = analyse(&[
7582 ("shop.bynk", &shop),
7583 (
7584 "till.bynk",
7585 "context till\n\nconsumes shop\n\ntype Box = { label: String }\n\n\
7586 service total {\n on call() -> Effect[Int] by Caller {\n \
7587 let b <- shop.quote()\n Effect.pure(1)\n }\n}\n",
7588 ),
7589 ]);
7590 a.assert_reports("bynk.boundary.structural_mismatch");
7591 }
7592
7593 #[test]
7594 fn a_differing_caller_type_is_found_in_a_result() {
7595 caller_box_differs_inside("Result[Box, String]", "Ok(Box { a: 1 })");
7596 }
7597
7598 #[test]
7599 fn a_differing_caller_type_is_found_in_a_map_value() {
7600 caller_box_differs_inside("Map[String, Box]", "Map.empty()");
7601 }
7602
7603 #[test]
7604 fn a_differing_caller_type_is_found_in_an_option() {
7605 caller_box_differs_inside("Option[Box]", "None");
7606 }
7607
7608 #[test]
7609 fn a_differing_caller_type_is_found_in_a_list() {
7610 caller_box_differs_inside("List[Box]", "[]");
7611 }
7612
7613 #[test]
7614 fn a_differing_caller_type_is_found_in_an_http_result() {
7615 caller_box_differs_inside("HttpResult[Box]", "Ok(Box { a: 1 })");
7616 }
7617
7618 #[test]
7619 fn agreeing_declarations_project_in_context_name_order() {
7620 let a = analyse(&[
7626 (
7627 "shop.bynk",
7628 "context shop\n\ntype Amount = { cents: Int }\n\ntype Box = { a: Amount }\n\n\
7629 service quote {\n on call() -> Effect[Box] by Caller {\n \
7630 Effect.pure(Box { a: Amount { cents: 1 } })\n }\n}\n",
7631 ),
7632 (
7633 "depot.bynk",
7634 "context depot\n\ntype Coins = { cents: Int }\n\ntype Box = { a: Coins }\n\n\
7635 service store {\n on call(b: Box) -> Effect[Int] by Caller {\n Effect.pure(b.a.cents)\n }\n}\n",
7636 ),
7637 (
7638 "till.bynk",
7639 "context till\n\nconsumes shop\n\nconsumes depot\n\n\
7640 type Amount = { dollars: Int }\n\n\
7641 fn mine() -> Amount {\n Amount { dollars: 1 }\n}\n\n\
7642 service total {\n on call() -> Effect[Int] by Caller {\n \
7643 let b <- shop.quote()\n depot.store(b)\n }\n}\n",
7644 ),
7645 ]);
7646 a.assert_clean();
7647 }
7648}