1use std::collections::{BTreeMap, HashMap, HashSet};
57use std::path::PathBuf;
58use std::sync::Arc;
59
60use crate::actors::CallSitePrincipal;
61use crate::checker::{self, Types};
62use crate::context_checks::{build_capability_op_info, ts_type_ref_display};
63use crate::hints::HintSink;
64use crate::index::{RefSink, SymbolKind};
65use crate::locals::LocalsSink;
66use crate::requirements::RequirementSink;
67use crate::resolver::{self, MethodTable as ResolverMethodTable, ResolvedCommons};
68use crate::symbols::{UnitTable, build_cross_context_info};
69use bynk_project::ParsedFile;
70use bynk_project::UnitKind;
71use bynk_project::discovery::{case_effective_tier, suite_effective_tier_is_system};
72use bynk_syntax::ast::*;
73use bynk_syntax::error::CompileError;
74use bynk_syntax::span::Span;
75
76#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum StubScope {
82 Every,
84 Case(String),
87 Suite(usize),
91}
92
93pub fn suite_ordinal(i: usize, indices: &[usize], parsed: &[ParsedFile]) -> Option<usize> {
98 indices
99 .iter()
100 .filter(|&&j| parsed[j].test().is_some())
101 .position(|&j| j == i)
102}
103
104#[derive(Debug, Clone)]
110pub struct ResolvedStub {
111 pub cap: String,
113 pub cap_decl: CapabilityDecl,
115 pub service_context: Option<String>,
121 pub clauses: Vec<StubClause>,
124 pub clause_scopes: Vec<StubScope>,
126 pub clause_fixtures: Vec<Vec<FixtureDecl>>,
129 pub clause_fns: Vec<Vec<FnDecl>>,
132 pub clause_types: Vec<Vec<TypeDecl>>,
135 pub clause_consts: Vec<Vec<ConstDecl>>,
136 pub identity_path: PathBuf,
144}
145
146#[allow(clippy::too_many_arguments)]
161pub fn phase_test_bodies(
162 test_groups: &BTreeMap<String, Vec<usize>>,
163 parsed: &[ParsedFile],
164 kinds: &BTreeMap<String, UnitKind>,
165 unit_tables: &HashMap<String, UnitTable>,
166 exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
167 unit_consumes: &HashMap<String, Vec<String>>,
168 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
169 unit_uses: &HashMap<String, Vec<String>>,
170 broken: &crate::project_model::BrokenDeclNames,
174 errors: &mut Vec<CompileError>,
175 refs: &mut RefSink,
176 locals: &mut LocalsSink,
177 tys: &Arc<Types>,
178 d1_sql: Option<&crate::d1_sql::D1Sql>,
181) -> HashMap<String, HashMap<String, ResolvedStub>> {
182 let mut ready: HashMap<String, HashMap<String, ResolvedStub>> = HashMap::new();
183
184 let mut sorted_targets: Vec<&String> = test_groups.keys().collect();
185 sorted_targets.sort();
186
187 for target_name in sorted_targets {
188 let indices = test_groups.get(target_name).unwrap();
189 let target_kind = match kinds.get(target_name) {
191 Some(k) => *k,
192 None => {
193 let span = first_test_target_span(indices, parsed);
194 errors.push(
195 CompileError::new(
196 "bynk.suite.unknown_target",
197 span,
198 format!(
199 "test target `{target_name}` is not a declared commons or context in this project",
200 ),
201 )
202 .with_note(
203 "the target of a `test` declaration must be a commons or context declared elsewhere in the project",
204 ),
205 );
206 continue;
207 }
208 };
209
210 let mut seen_cases: HashMap<String, Span> = HashMap::new();
212 let mut had_dup = false;
213 for &i in indices {
214 if let Some(t) = parsed[i].test() {
215 for case in &t.cases {
216 if let Some(prev) = seen_cases.get(&case.name) {
217 had_dup = true;
218 errors.push(
219 CompileError::new(
220 "bynk.suite.duplicate_case_name",
221 case.name_span,
222 format!(
223 "test case `\"{}\"` is declared more than once in tests targeting `{target_name}`",
224 case.name
225 ),
226 )
227 .with_label(*prev, "previously declared here"),
228 );
229 } else {
230 seen_cases.insert(case.name.clone(), case.name_span);
231 }
232 }
233 }
234 }
235
236 for &i in indices {
238 if let Some(t) = parsed[i].test() {
239 crate::test_env::check_env_clauses(t, errors);
240 }
241 }
242
243 let target_stubs = resolve_stubs(
252 target_name,
253 target_kind,
254 indices,
255 parsed,
256 unit_tables,
257 unit_consumes,
258 unit_consumes_aliases,
259 errors,
260 );
261
262 if had_dup {
263 continue;
265 }
266
267 let bodies_errs = check_test_bodies(
271 target_name,
272 target_kind,
273 indices,
274 parsed,
275 &target_stubs,
276 unit_tables,
277 exports_visibility,
278 unit_consumes,
279 unit_consumes_aliases,
280 unit_uses,
281 refs,
282 locals,
283 tys,
284 d1_sql,
285 );
286 let bodies_errs = match unit_tables.get(target_name) {
290 Some(local) => {
291 let mut used: Vec<String> = unit_uses.get(target_name).cloned().unwrap_or_default();
292 for &i in indices {
293 for u in parsed[i].uses() {
294 let q = u.target.joined();
295 if !used.contains(&q) {
296 used.push(q);
297 }
298 }
299 }
300 let private = resolver::private_imports_in(
301 local,
302 used.iter()
303 .filter_map(|t| unit_tables.get(t).map(|u| (t, u))),
304 );
305 resolver::rewrite_private_references(bodies_errs, &private)
306 }
307 None => bodies_errs,
308 };
309 let visible_broken = visible_broken_names(
315 std::slice::from_ref(target_name),
316 indices,
317 parsed,
318 unit_uses,
319 unit_consumes,
320 broken,
321 );
322 let bodies_failed = !bodies_errs.is_empty();
323 errors.extend(resolver::split_broken_decl_echoes(bodies_errs, &visible_broken).0);
324
325 if bodies_failed {
326 continue;
327 }
328
329 ready.insert(target_name.clone(), target_stubs);
330 }
331
332 ready
333}
334
335#[allow(clippy::too_many_arguments)]
342fn resolve_stubs(
343 target_name: &str,
344 target_kind: UnitKind,
345 indices: &[usize],
346 parsed: &[ParsedFile],
347 unit_tables: &HashMap<String, UnitTable>,
348 unit_consumes: &HashMap<String, Vec<String>>,
349 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
350 errors: &mut Vec<CompileError>,
351) -> HashMap<String, ResolvedStub> {
352 let target_table = unit_tables.get(target_name);
353 let target_consumed = unit_consumes.get(target_name).cloned().unwrap_or_default();
354
355 type Collected = (
359 StubClause,
360 StubScope,
361 PathBuf,
362 Vec<FixtureDecl>,
363 Vec<FnDecl>,
364 Vec<TypeDecl>,
365 Vec<ConstDecl>,
366 );
367 let mut collected: Vec<Collected> = Vec::new();
368 for &i in indices {
369 let Some(t) = parsed[i].test() else { continue };
370 for case in &t.cases {
371 for pc in &case.stubs {
372 collected.push((
373 pc.clone(),
374 StubScope::Case(case.name.clone()),
375 parsed[i].identity_path(),
376 t.fixtures.clone(),
377 t.fns.clone(),
378 t.types.clone(),
379 t.consts.clone(),
380 ));
381 }
382 }
383 }
384 let suites = indices
388 .iter()
389 .filter(|&&i| parsed[i].test().is_some())
390 .count();
391 for &i in indices {
392 let Some(t) = parsed[i].test() else { continue };
393 let scope = match suite_ordinal(i, indices, parsed) {
394 Some(n) if suites > 1 => StubScope::Suite(n),
395 _ => StubScope::Every,
396 };
397 for pc in &t.stubs {
398 collected.push((
399 pc.clone(),
400 scope.clone(),
401 parsed[i].identity_path(),
402 t.fixtures.clone(),
403 t.fns.clone(),
404 t.types.clone(),
405 t.consts.clone(),
406 ));
407 }
408 }
409
410 let resolve_cap = |name: &str| -> Option<CapabilityDecl> {
414 target_table
415 .and_then(|t| t.capabilities.get(name).cloned())
416 .or_else(|| {
417 target_consumed.iter().find_map(|q| {
418 unit_tables
419 .get(q)
420 .and_then(|t| t.capabilities.get(name).cloned())
421 })
422 })
423 };
424
425 let mut out: HashMap<String, ResolvedStub> = HashMap::new();
426 for (pc, scope, identity_path, fixtures, fns, types, consts) in collected {
427 let cap_name = pc.capability.name.clone();
428 let consumed_ctx = resolve_cap(&cap_name).is_none().then(|| {
431 unit_consumes_aliases
432 .get(target_name)
433 .and_then(|a| a.get(&cap_name).cloned())
434 .or_else(|| target_consumed.iter().find(|q| **q == cap_name).cloned())
435 });
436 if let Some(Some(ctx)) = consumed_ctx {
437 resolve_service_stub(
438 &ctx,
439 &cap_name,
440 pc,
441 scope,
442 identity_path,
443 fixtures,
444 fns,
445 types,
446 consts,
447 unit_tables,
448 &mut out,
449 errors,
450 );
451 continue;
452 }
453 let Some(cap_decl) = resolve_cap(&cap_name) else {
454 let note = if target_kind == UnitKind::Commons {
457 "commons have no capability seams — `stub` overrides a capability the target context declares or consumes"
458 } else {
459 "a `stub` clause names a capability the target context declares or reaches through a consumed context"
460 };
461 errors.push(
462 CompileError::new(
463 "bynk.stub.not_a_seam",
464 pc.capability.span,
465 format!("`{cap_name}` is not a capability seam of `{target_name}`",),
466 )
467 .with_note(note),
468 );
469 continue;
470 };
471 let Some(op_decl) = cap_decl.ops.iter().find(|o| o.name.name == pc.method.name) else {
472 errors.push(CompileError::new(
473 "bynk.stub.unknown_op",
474 pc.method.span,
475 format!(
476 "`{}` is not an operation of capability `{cap_name}`",
477 pc.method.name
478 ),
479 ));
480 continue;
481 };
482 if !op_decl.type_params.is_empty() {
490 errors.push(
491 CompileError::new(
492 "bynk.stub.generic_op",
493 pc.method.span,
494 format!(
495 "`{cap_name}.{}` declares its own type parameter — a generic capability operation cannot be stubbed at v1",
496 pc.method.name
497 ),
498 )
499 .with_note(
500 "test through the capability's real (external) provider instead, or restructure the test to avoid stubbing this operation",
501 ),
502 );
503 continue;
504 }
505 if let StubRhs::ReturnsEach(outcomes, span) = &pc.rhs
506 && outcomes.is_empty()
507 {
508 errors.push(CompileError::new(
509 "bynk.stub.bad_sequence",
510 *span,
511 format!(
512 "`stub {cap_name}.{} returns each []` has no outcomes — a sequence needs at least one",
513 pc.method.name
514 ),
515 ));
516 continue;
517 }
518 let entry = out.entry(cap_name.clone()).or_insert_with(|| ResolvedStub {
519 cap: cap_name.clone(),
520 cap_decl: cap_decl.clone(),
521 service_context: None,
522 clauses: Vec::new(),
523 clause_scopes: Vec::new(),
524 clause_fixtures: Vec::new(),
525 clause_fns: Vec::new(),
526 clause_types: Vec::new(),
527 clause_consts: Vec::new(),
528 identity_path: identity_path.clone(),
529 });
530 entry.clauses.push(pc);
531 entry.clause_scopes.push(scope);
532 entry.clause_fixtures.push(fixtures);
533 entry.clause_fns.push(fns);
534 entry.clause_types.push(types);
535 entry.clause_consts.push(consts);
536 }
537 out
538}
539
540#[allow(clippy::too_many_arguments)]
545fn resolve_service_stub(
546 ctx: &str,
547 seam: &str,
548 pc: StubClause,
549 scope: StubScope,
550 identity_path: PathBuf,
551 fixtures: Vec<FixtureDecl>,
552 fns: Vec<FnDecl>,
553 types: Vec<TypeDecl>,
554 consts: Vec<ConstDecl>,
555 unit_tables: &HashMap<String, UnitTable>,
556 out: &mut HashMap<String, ResolvedStub>,
557 errors: &mut Vec<CompileError>,
558) {
559 let handler = unit_tables
560 .get(ctx)
561 .and_then(|t| t.services.get(&pc.method.name))
562 .and_then(|s| s.handlers.iter().find(|h| h.kind == HandlerKind::Call));
563 let Some(handler) = handler else {
564 errors.push(
565 CompileError::new(
566 "bynk.stub.unknown_op",
567 pc.method.span,
568 format!("`{}` is not a service of `{ctx}`", pc.method.name),
569 )
570 .with_note("a `stub` on a consumed context names one of its services"),
571 );
572 return;
573 };
574 if let StubRhs::ReturnsEach(outcomes, span) = &pc.rhs
575 && outcomes.is_empty()
576 {
577 errors.push(CompileError::new(
578 "bynk.stub.bad_sequence",
579 *span,
580 format!(
581 "`stub {seam}.{} returns each []` has no outcomes — a sequence needs at least one",
582 pc.method.name
583 ),
584 ));
585 return;
586 }
587 let op = CapabilityOp {
588 name: pc.method.clone(),
589 type_params: Vec::new(),
590 params: handler.params.clone(),
591 return_type: handler.return_type.clone(),
592 annotations: Vec::new(),
593 documentation: None,
594 span: handler.span,
595 trivia: Default::default(),
596 };
597 let entry = out.entry(seam.to_string()).or_insert_with(|| ResolvedStub {
598 cap: seam.to_string(),
599 cap_decl: CapabilityDecl {
600 name: pc.capability.clone(),
601 ops: Vec::new(),
602 derived: None,
603 documentation: None,
604 span: pc.capability.span,
605 trailing_comments: Vec::new(),
606 trivia: Default::default(),
607 },
608 service_context: Some(ctx.to_string()),
609 clauses: Vec::new(),
610 clause_scopes: Vec::new(),
611 clause_fixtures: Vec::new(),
612 clause_fns: Vec::new(),
613 clause_types: Vec::new(),
614 clause_consts: Vec::new(),
615 identity_path: identity_path.clone(),
616 });
617 if !entry
618 .cap_decl
619 .ops
620 .iter()
621 .any(|o| o.name.name == op.name.name)
622 {
623 entry.cap_decl.ops.push(op);
624 }
625 entry.clauses.push(pc);
626 entry.clause_scopes.push(scope);
627 entry.clause_fixtures.push(fixtures);
628 entry.clause_fns.push(fns);
629 entry.clause_types.push(types);
630 entry.clause_consts.push(consts);
631}
632
633pub fn infer_participants(
642 target: &str,
643 unit_consumes: &HashMap<String, Vec<String>>,
644 kinds: &BTreeMap<String, UnitKind>,
645) -> Vec<String> {
646 let mut seen: HashSet<String> = HashSet::new();
647 let mut order: Vec<String> = Vec::new();
648 let mut queue: Vec<String> = vec![target.to_string()];
649 seen.insert(target.to_string());
650 let mut head = 0;
651 while head < queue.len() {
652 let node = queue[head].clone();
653 head += 1;
654 order.push(node.clone());
655 if let Some(deps) = unit_consumes.get(&node) {
656 for d in deps {
657 if seen.insert(d.clone()) {
658 queue.push(d.clone());
659 }
660 }
661 }
662 }
663 order.retain(|u| kinds.get(u) == Some(&UnitKind::Context));
664 order
665}
666
667pub fn infer_harness_participants(
676 target: &str,
677 unit_consumes: &HashMap<String, Vec<String>>,
678 kinds: &BTreeMap<String, UnitKind>,
679 event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
680) -> Vec<String> {
681 let mut seen: HashSet<String> = HashSet::new();
682 let mut order: Vec<String> = Vec::new();
683 let mut queue: Vec<String> = vec![target.to_string()];
684 seen.insert(target.to_string());
685 let mut head = 0;
686 while head < queue.len() {
687 let node = queue[head].clone();
688 head += 1;
689 order.push(node.clone());
690 let consumed = unit_consumes.get(&node).into_iter().flatten();
691 let subscribers = event_subscribers
692 .iter()
693 .filter(|((owner, _), _)| *owner == node)
694 .flat_map(|(_, subs)| subs.iter().map(|(ctx, _)| ctx));
695 for next in consumed.chain(subscribers) {
696 if seen.insert(next.clone()) {
697 queue.push(next.clone());
698 }
699 }
700 }
701 order.retain(|u| kinds.get(u) == Some(&UnitKind::Context));
702 order
703}
704
705#[allow(clippy::too_many_arguments)]
725pub fn phase_integration_bodies(
726 integration_groups: &BTreeMap<String, Vec<usize>>,
727 parsed: &[ParsedFile],
728 kinds: &BTreeMap<String, UnitKind>,
729 unit_tables: &HashMap<String, UnitTable>,
730 unit_consumes: &HashMap<String, Vec<String>>,
731 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
732 unit_uses: &HashMap<String, Vec<String>>,
733 broken: &crate::project_model::BrokenDeclNames,
735 errors: &mut Vec<CompileError>,
736 refs: &mut RefSink,
737 tys: &Arc<Types>,
738 d1_sql: Option<&crate::d1_sql::D1Sql>,
740) -> HashMap<String, resolver::CrossContextInfo> {
741 let mut ready: HashMap<String, resolver::CrossContextInfo> = HashMap::new();
742
743 let mut sorted: Vec<&String> = integration_groups.keys().collect();
744 sorted.sort();
745
746 for group_name in sorted {
747 let indices = integration_groups.get(group_name).unwrap();
748 let first = indices[0];
749 let Some(decl) = parsed[first].integration() else {
750 continue;
751 };
752 let suite_target = decl.target.joined();
756 let participants = infer_participants(&suite_target, unit_consumes, kinds);
757
758 let mut bad = false;
759
760 let has_serialisation_edge = unit_tables
769 .get(&suite_target)
770 .is_some_and(has_serialisation_edge);
771 if participants.len() < 2 && !has_serialisation_edge {
772 errors.push(
773 CompileError::new(
774 "bynk.tier.system_needs_wire",
775 decl.target.span,
776 format!(
777 "`system`-tier suite for `{suite_target}` has no serialisation edge — the target consumes no other context and exposes no `http`, `queue` or `email` service",
778 ),
779 )
780 .with_note(
781 "a `system` case crosses a real serialise → JSON → deserialise boundary; this target has none to cross, so `unit` already covers it",
782 ),
783 );
784 bad = true;
785 }
786
787 let mut seen_cases: HashMap<String, Span> = HashMap::new();
789 for &i in indices {
790 let Some(d) = parsed[i].integration() else {
791 continue;
792 };
793 for case in &d.cases {
794 if let Some(prev) = seen_cases.get(&case.name) {
795 errors.push(
796 CompileError::new(
797 "bynk.suite.duplicate_case_name",
798 case.name_span,
799 format!(
800 "test case `\"{}\"` is declared more than once in tests targeting `{suite_target}`",
801 case.name
802 ),
803 )
804 .with_label(*prev, "previously declared here"),
805 );
806 bad = true;
807 } else {
808 seen_cases.insert(case.name.clone(), case.name_span);
809 }
810 }
811 }
812
813 for &i in indices {
815 if let Some(d) = parsed[i].integration() {
816 crate::test_env::check_env_clauses(d, errors);
817 }
818 }
819
820 for &i in indices {
830 let Some(d) = parsed[i].integration() else {
831 continue;
832 };
833 let suite_is_system = d.tier == Some(bynk_syntax::ast::TestTier::System);
834 let has_lower = d
835 .cases
836 .iter()
837 .any(|c| case_effective_tier(c, d) != bynk_syntax::ast::TestTier::System);
838 if !has_lower {
839 continue;
840 }
841 for case in &d.cases {
842 let tier = case_effective_tier(case, d);
843 let flagged = if suite_is_system {
846 tier != bynk_syntax::ast::TestTier::System
847 } else {
848 case.tier == Some(bynk_syntax::ast::TestTier::System)
849 };
850 if !flagged {
851 continue;
852 }
853 let (message, advice) = if suite_is_system {
854 (
855 format!(
856 "case `\"{}\"` is `{}`-tier, but its suite is `as system`",
857 case.name,
858 tier.as_str()
859 ),
860 format!(
861 "move this case into a separate `suite {suite_target}` without `as system`"
862 ),
863 )
864 } else {
865 (
866 format!(
867 "case `\"{}\"` is `as system`, but other cases in its suite run below `system`",
868 case.name
869 ),
870 format!(
871 "move this case into its own `suite {suite_target} as system {{ … }}`, addressing services by context path (`{suite_target}.<service>(…)`)"
872 ),
873 )
874 };
875 errors.push(
876 CompileError::new("bynk.tier.mixed_system_suite", case.name_span, message)
877 .with_note(format!(
878 "a `system` case runs against deployed Workers, so its suite holds `system` cases only; {advice}"
879 )),
880 );
881 }
882 }
883
884 refuse_stubs_at_system(indices, parsed, &suite_target, errors);
886
887 if bad {
888 continue;
889 }
890
891 let harness_name = group_name.clone();
893 let mut uses_targets: Vec<String> = Vec::new();
894 for &i in indices {
895 if let Some(d) = parsed[i].integration() {
896 for u in &d.uses {
897 let q = u.target.joined();
898 if !uses_targets.contains(&q) {
899 uses_targets.push(q);
900 }
901 }
902 }
903 }
904 let mut harness_consumes = unit_consumes.clone();
908 harness_consumes.insert(harness_name.clone(), participants.clone());
909 let mut harness_uses = unit_uses.clone();
916 let entry = harness_uses.entry(harness_name.clone()).or_default();
917 for u in &uses_targets {
918 if !entry.contains(u) {
919 entry.push(u.clone());
920 }
921 }
922 let cross_context = build_cross_context_info(
923 &harness_name,
924 &harness_consumes,
925 unit_consumes_aliases,
926 &harness_uses,
927 unit_tables,
928 );
929
930 let mut body_errs: Vec<CompileError> = Vec::new();
932 let view = integration_view(&uses_targets, &participants, unit_tables, unit_uses);
935 for c in &view.conflicts {
941 let span = indices
942 .iter()
943 .filter_map(|&i| parsed[i].integration())
944 .flat_map(|d| &d.uses)
945 .find(|u| u.target.joined() == c.via)
946 .map(|u| u.target.span)
947 .unwrap_or(decl.target.span);
948 let names = c
949 .bound
950 .as_ref()
951 .map(|b| format!("`{b}`'s type"))
952 .unwrap_or_else(|| "another declaration".to_string());
953 body_errs.push(view_conflict_error(c, span, &names));
954 }
955 let mut harness_resolution = uses_targets.clone();
958 harness_resolution.extend(participants.iter().cloned());
959 refs.declare_namespace(&harness_name, harness_resolution);
960 for &i in indices {
961 let Some(d) = parsed[i].integration() else {
962 continue;
963 };
964 let namespace = if SuiteItems::of(d).is_empty() {
967 harness_name.clone()
968 } else {
969 let ns = suite_helper_namespace(&harness_name, &parsed[i].identity_path());
970 let mut resolution = uses_targets.clone();
971 resolution.extend(participants.iter().cloned());
972 refs.declare_namespace(&ns, resolution);
973 ns
974 };
975 refs.enter_file(
976 &parsed[i].identity_path(),
977 &namespace,
978 parsed[i].is_synthetic(),
979 );
980 body_errs.extend(resolver::check_hidden_type_names_in_suite(
983 d,
984 None,
985 &view.hidden,
986 ));
987 let mut helper_view = integration_resolved(&view, &cross_context, SuiteItems::NONE);
989 check_suite_fixtures_in(
990 d,
991 &helper_view,
992 participants.first().and_then(|p| unit_tables.get(p)),
993 &mut body_errs,
994 );
995 add_suite_fns(
996 &mut helper_view,
997 SuiteItems {
998 fns: &[],
999 fixtures: &d.fixtures,
1000 types: &[],
1001 consts: &[],
1002 },
1003 );
1004 check_suite_decls(
1005 &d.types,
1006 &d.consts,
1007 &mut helper_view,
1008 participants.first().and_then(|p| unit_tables.get(p)),
1009 &mut body_errs,
1010 refs,
1011 &mut LocalsSink::new(),
1012 tys,
1013 );
1014 check_suite_fns(
1015 &d.fns,
1016 &mut helper_view,
1017 participants.first().and_then(|p| unit_tables.get(p)),
1018 &mut body_errs,
1019 refs,
1020 &mut LocalsSink::new(),
1021 tys,
1022 );
1023 let suite_has_system = d.tier == Some(bynk_syntax::ast::TestTier::System)
1029 || d.cases
1030 .iter()
1031 .any(|c| case_effective_tier(c, d) == bynk_syntax::ast::TestTier::System);
1032 for case in &d.cases {
1033 let unchecked = suite_has_system
1034 && case_effective_tier(case, d) != bynk_syntax::ast::TestTier::System;
1035 let case_callees = if unchecked {
1038 Default::default()
1039 } else {
1040 let body = IntegrationBody {
1041 participants: &participants,
1042 view: &view,
1043 suite: d,
1044 case,
1045 cross_context: &cross_context,
1046 unit_tables,
1047 };
1048 check_integration_body(
1049 &body,
1050 d1_sql,
1051 parsed[first].source(),
1052 &mut body_errs,
1053 refs,
1054 tys,
1055 )
1056 };
1057 check_faults_tier(case, case_effective_tier(case, d), &mut body_errs);
1058 check_snapshot_placement(case, true, &mut body_errs);
1059 check_event_address_tier(
1060 case,
1061 case_effective_tier(case, d),
1062 &case_callees,
1063 &mut body_errs,
1064 );
1065 check_ws_address_tier(
1066 case,
1067 case_effective_tier(case, d),
1068 &case_callees,
1069 &mut body_errs,
1070 );
1071 check_call_address_tier(
1072 case,
1073 case_effective_tier(case, d),
1074 &case_callees,
1075 &mut body_errs,
1076 );
1077 check_extra_headers_tier(
1078 case,
1079 case_effective_tier(case, d),
1080 &case_callees,
1081 &mut body_errs,
1082 );
1083 check_extra_headers_let(case, &case_callees, &mut body_errs);
1084 if case_effective_tier(case, d) == bynk_syntax::ast::TestTier::System {
1085 check_system_claims_literal(case, &mut body_errs);
1086 }
1087 check_wire_tier(case, case_effective_tier(case, d), &mut body_errs);
1092 if !matches!(
1096 case_effective_tier(case, d),
1097 bynk_syntax::ast::TestTier::System
1098 ) && block_uses_nobody(&case.body)
1099 {
1100 body_errs.push(CompileError::new(
1101 "bynk.test.credential_needs_system",
1102 case.name_span,
1103 format!(
1104 "case `\"{}\"` drives `by Nobody` but is not a `system`-tier case",
1105 case.name
1106 ),
1107 ).with_note(
1108 "`by Nobody` presents no credential to the real auth seam (the 401 path), which exists only at `system`; promote the case with `as system`, or supply `by <Actor>(<identity>)`",
1109 ));
1110 }
1111 check_bad_signature_tier(case, case_effective_tier(case, d), &mut body_errs);
1112 }
1113 }
1114 let visible_broken = visible_broken_names(
1117 &participants,
1118 indices,
1119 parsed,
1120 unit_uses,
1121 unit_consumes,
1122 broken,
1123 );
1124 let bodies_failed = !body_errs.is_empty();
1125 errors.extend(resolver::split_broken_decl_echoes(body_errs, &visible_broken).0);
1126 if bodies_failed {
1127 continue;
1128 }
1129
1130 ready.insert(group_name.clone(), cross_context);
1131 }
1132
1133 ready
1134}
1135
1136fn refuse_stubs_at_system(
1143 indices: &[usize],
1144 parsed: &[ParsedFile],
1145 suite_target: &str,
1146 errors: &mut Vec<CompileError>,
1147) {
1148 for &i in indices {
1149 let Some(d) = parsed[i].integration() else {
1150 continue;
1151 };
1152 let system = bynk_syntax::ast::TestTier::System;
1153 let suite_stubs = d
1154 .stubs
1155 .iter()
1156 .filter(|_| suite_effective_tier_is_system(d))
1157 .map(|s| (s, "suite"));
1158 let case_stubs = d
1159 .cases
1160 .iter()
1161 .filter(|c| case_effective_tier(c, d) == system)
1162 .flat_map(|c| c.stubs.iter().map(|s| (s, "case")));
1163 for (stub, scope) in suite_stubs.chain(case_stubs) {
1164 errors.push(
1165 CompileError::new(
1166 "bynk.stub.at_system",
1167 stub.span,
1168 format!(
1169 "`stub {}.{}` is in a `system`-tier {scope}, where a `stub` has no effect",
1170 stub.capability.name, stub.method.name
1171 ),
1172 )
1173 .with_note(
1174 "a `system` case runs each context as the Worker it deploys as, which builds its own capability providers; no seam can be overridden there",
1175 )
1176 .with_note(format!(
1177 "move the case into a `suite {suite_target}` below `system` (`unit`, or `as integration`), where a `stub` overrides the seam"
1178 )),
1179 );
1180 }
1181 }
1182}
1183
1184struct IntegrationBody<'a> {
1186 participants: &'a [String],
1187 view: &'a SuiteView,
1188 suite: &'a SuiteDecl,
1189 case: &'a Case,
1190 cross_context: &'a resolver::CrossContextInfo,
1191 unit_tables: &'a HashMap<String, UnitTable>,
1192}
1193
1194fn check_integration_body(
1198 body: &IntegrationBody<'_>,
1199 d1_sql: Option<&crate::d1_sql::D1Sql>,
1200 source: &str,
1201 errors: &mut Vec<CompileError>,
1202 refs: &mut RefSink,
1203 tys: &Arc<Types>,
1204) -> HashMap<ExprId, checker::Callee> {
1205 let callees = typecheck_integration_case_body(
1206 body.participants,
1207 body.view,
1208 SuiteItems::of(body.suite),
1209 body.case,
1210 body.cross_context,
1211 body.unit_tables,
1212 errors,
1213 refs,
1214 tys,
1215 )
1216 .1;
1217 if let Some(d1_sql) = d1_sql {
1218 errors.extend(d1_sql.check_peek_sites(body.unit_tables, &callees, Some(source)));
1219 }
1220 callees
1221}
1222
1223fn visible_broken_names(
1230 roots: &[String],
1231 suite_files: &[usize],
1232 parsed: &[ParsedFile],
1233 unit_uses: &HashMap<String, Vec<String>>,
1234 unit_consumes: &HashMap<String, Vec<String>>,
1235 broken: &crate::project_model::BrokenDeclNames,
1236) -> Vec<String> {
1237 let suite_uses: Vec<String> = suite_files
1238 .iter()
1239 .flat_map(|&i| parsed[i].uses())
1240 .map(|u| u.target.joined())
1241 .collect();
1242 roots
1243 .iter()
1244 .chain(
1245 roots
1246 .iter()
1247 .flat_map(|r| unit_uses.get(r).into_iter().chain(unit_consumes.get(r)))
1248 .flatten(),
1249 )
1250 .chain(suite_uses.iter())
1251 .filter_map(|u| broken.get(u))
1252 .flatten()
1253 .cloned()
1254 .collect()
1255}
1256
1257fn has_serialisation_edge(target: &UnitTable) -> bool {
1267 target.services.values().any(|s| {
1268 matches!(
1269 s.protocol,
1270 bynk_syntax::ast::ServiceProtocol::Http
1271 | bynk_syntax::ast::ServiceProtocol::Queue { .. }
1272 | bynk_syntax::ast::ServiceProtocol::Email { .. }
1273 )
1274 })
1275}
1276
1277#[allow(clippy::too_many_arguments)]
1289pub fn typecheck_integration_case_body(
1290 participants: &[String],
1291 view: &SuiteView,
1292 suite_fns: SuiteItems<'_>,
1294 case: &Case,
1295 cross_context: &resolver::CrossContextInfo,
1296 unit_tables: &HashMap<String, UnitTable>,
1297 errors: &mut Vec<CompileError>,
1298 refs: &mut RefSink,
1299 tys: &Arc<Types>,
1300) -> (
1301 HashMap<ExprId, checker::TypedExpr>,
1302 HashMap<ExprId, checker::Callee>,
1303) {
1304 let resolved = integration_resolved(view, cross_context, suite_fns);
1305
1306 let unit_span = case.span;
1307 let synthetic_return = TypeRef::Effect(
1308 Box::new(TypeRef::Result(
1309 Box::new(TypeRef::Unit(unit_span)),
1310 Box::new(TypeRef::ValidationError(unit_span)),
1311 unit_span,
1312 )),
1313 unit_span,
1314 );
1315 let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
1316 let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
1317 let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
1318 let mut no_hints = HintSink::new();
1320 let mut no_locals = LocalsSink::new();
1321 let mut no_requirements = RequirementSink::new();
1323 let _ = checker::check_body(
1324 &resolved,
1325 &case.body,
1326 return_ty,
1327 case.span,
1328 HashMap::new(),
1329 checker::CapabilityCtx {
1330 peek_env: Some(Arc::new(peek_env(
1332 participants,
1333 unit_tables,
1334 &resolved,
1335 tys,
1336 ))),
1337 ..Default::default()
1338 },
1339 target_test_services(
1343 participants.first().map(String::as_str),
1344 unit_tables,
1345 &cross_context.consumed_contexts,
1346 ),
1347 target_test_actors(participants.first().and_then(|t| unit_tables.get(t))),
1348 None,
1349 checker::CheckSinks {
1350 tys,
1351 expr_types: &mut expr_types,
1352 errors,
1353 refs,
1354 hints: &mut no_hints,
1355 locals: &mut no_locals,
1356 requirements: &mut no_requirements,
1357 callees: &mut callees,
1358 },
1359 );
1360 (expr_types, callees)
1361}
1362
1363fn peek_env(
1365 participants: &[String],
1366 unit_tables: &HashMap<String, UnitTable>,
1367 resolved: &ResolvedCommons,
1368 tys: &Arc<Types>,
1369) -> checker::peek::PeekEnv {
1370 let mut env = checker::peek::PeekEnv::default();
1371 for p in participants {
1372 let Some(table) = unit_tables.get(p) else {
1373 continue;
1374 };
1375 let caps = table
1376 .capabilities
1377 .iter()
1378 .map(|(name, decl)| {
1379 let ops = decl
1380 .ops
1381 .iter()
1382 .map(|op| build_capability_op_info(op, &resolved.types, tys))
1383 .collect();
1384 let info = checker::CapabilityInfo {
1385 name: name.clone(),
1386 ops,
1387 derived_from: crate::context_checks::derived_from(
1388 decl,
1389 &resolved.cross_context.flattened_caps,
1390 ),
1391 };
1392 let binding = table.derived.get(name).map(|d| d.binding.clone());
1393 (name.clone(), checker::peek::PeekCap { info, binding })
1394 })
1395 .collect();
1396 env.participants.insert(p.clone(), caps);
1397 }
1398 env
1399}
1400
1401pub fn integration_resolved(
1405 view: &SuiteView,
1406 cross_context: &resolver::CrossContextInfo,
1407 suite_fns: SuiteItems<'_>,
1408) -> ResolvedCommons {
1409 let SuiteView {
1410 types,
1411 fns,
1412 methods,
1413 ..
1414 } = view.clone();
1415
1416 let synthetic_commons = Commons {
1417 name: QualifiedName {
1418 parts: vec![Ident {
1419 name: "integration".to_string(),
1420 span: Span::default(),
1421 }],
1422 span: Span::default(),
1423 },
1424 items: Vec::new(),
1425 uses: Vec::new(),
1426 documentation: None,
1427 form: CommonsForm::Brace,
1428 span: Span::default(),
1429 trivia: Trivia::default(),
1430 trailing_comments: Vec::new(),
1431 };
1432 let no_local_types = HashMap::new();
1437 let no_local_events = HashMap::new();
1438 let mut resolved = ResolvedCommons::new(
1439 Arc::new(synthetic_commons),
1440 types,
1441 &no_local_types,
1442 fns,
1443 methods,
1444 HashMap::new(),
1445 &no_local_events,
1446 cross_context.clone(),
1447 HashMap::new(),
1448 false,
1450 HashSet::new(),
1451 )
1452 .with_assets(view.assets.clone())
1454 .with_embeds(view.embeds.clone())
1455 .with_consts(view.consts.clone());
1456 add_suite_fns(&mut resolved, suite_fns);
1457 resolved
1458}
1459
1460#[derive(Clone, Copy)]
1463pub struct SuiteItems<'a> {
1464 pub fns: &'a [FnDecl],
1465 pub fixtures: &'a [FixtureDecl],
1466 pub types: &'a [TypeDecl],
1468 pub consts: &'a [ConstDecl],
1469}
1470
1471impl<'a> SuiteItems<'a> {
1472 pub const NONE: SuiteItems<'static> = SuiteItems {
1473 fns: &[],
1474 fixtures: &[],
1475 types: &[],
1476 consts: &[],
1477 };
1478
1479 pub fn of(suite: &'a SuiteDecl) -> Self {
1480 SuiteItems {
1481 fns: &suite.fns,
1482 fixtures: &suite.fixtures,
1483 types: &suite.types,
1484 consts: &suite.consts,
1485 }
1486 }
1487
1488 pub fn is_empty(&self) -> bool {
1489 self.fns.is_empty()
1490 && self.fixtures.is_empty()
1491 && self.types.is_empty()
1492 && self.consts.is_empty()
1493 }
1494}
1495
1496fn fixture_as_embed(f: &FixtureDecl) -> EmbedDecl {
1499 EmbedDecl {
1500 name: f.name.clone(),
1501 path: f.path.clone(),
1502 path_span: f.path_span,
1503 documentation: f.documentation.clone(),
1504 private: None,
1505 span: f.span,
1506 trivia: f.trivia.clone(),
1507 }
1508}
1509
1510pub fn add_suite_fns(resolved: &mut ResolvedCommons, items: SuiteItems<'_>) {
1514 for t in items.types {
1516 if resolved.unselected_types.remove(&t.name.name) {
1519 resolved
1520 .types
1521 .insert(t.name.name.clone(), Arc::new(t.clone()));
1522 } else {
1523 resolved
1524 .types
1525 .entry(t.name.name.clone())
1526 .or_insert_with(|| Arc::new(t.clone()));
1527 }
1528 resolved.local_type_names.insert(t.name.name.clone());
1529 }
1530 for c in items.consts {
1531 resolved
1532 .consts
1533 .entry(c.name.name.clone())
1534 .or_insert_with(|| c.clone());
1535 }
1536 for f in items.fixtures {
1537 resolved
1538 .embeds
1539 .entry(f.name.name.clone())
1540 .or_insert_with(|| fixture_as_embed(f));
1541 }
1542 for f in items.fns {
1543 if let FnName::Free(name) = &f.name {
1544 resolved
1545 .fns
1546 .entry(name.name.clone())
1547 .or_insert_with(|| Arc::new(f.clone()));
1548 }
1549 }
1550}
1551
1552pub fn suite_helper_namespace(target: &str, file: &std::path::Path) -> String {
1555 format!("{target}#helpers:{}", file.display())
1556}
1557
1558pub fn check_suite_fixtures_in(
1561 suite: &SuiteDecl,
1562 resolved: &ResolvedCommons,
1563 target: Option<&UnitTable>,
1564 errors: &mut Vec<CompileError>,
1565) {
1566 if suite.fixtures.is_empty() {
1567 return;
1568 }
1569 let taken = bound_value_names(resolved, target);
1570 crate::fixtures::check_suite_fixtures(suite, &taken, errors);
1571}
1572
1573pub fn add_suite_fns_to_typed(typed: &mut checker::TypedCommons, suite_fns: &[FnDecl]) {
1575 for f in suite_fns {
1576 if let FnName::Free(name) = &f.name {
1577 typed
1578 .fns
1579 .entry(name.name.clone())
1580 .or_insert_with(|| Arc::new(f.clone()));
1581 }
1582 }
1583}
1584
1585fn bound_value_names(resolved: &ResolvedCommons, target: Option<&UnitTable>) -> HashSet<String> {
1588 let mut names: HashSet<String> = HashSet::new();
1589 names.extend(resolved.fns.keys().cloned());
1590 names.extend(
1592 resolved
1593 .types
1594 .keys()
1595 .filter(|n| !resolved.unselected_types.contains(*n))
1596 .cloned(),
1597 );
1598 names.extend(resolved.consts.keys().cloned());
1599 names.extend(resolved.embeds.keys().cloned());
1600 names.extend(resolved.assets.keys().cloned());
1601 names.insert("deps".to_string());
1603 if let Some(t) = target {
1604 names.extend(t.services.keys().cloned());
1605 names.extend(t.agents.keys().cloned());
1606 }
1607 names
1608}
1609
1610#[allow(clippy::too_many_arguments)]
1618pub fn check_suite_decls(
1619 types: &[TypeDecl],
1620 consts: &[ConstDecl],
1621 resolved: &mut ResolvedCommons,
1622 target: Option<&UnitTable>,
1623 errors: &mut Vec<CompileError>,
1624 refs: &mut RefSink,
1625 locals: &mut LocalsSink,
1626 tys: &Arc<Types>,
1627) -> (
1628 HashMap<ExprId, checker::TypedExpr>,
1629 HashMap<ExprId, checker::Callee>,
1630) {
1631 if types.is_empty() && consts.is_empty() {
1632 return Default::default();
1633 }
1634 let mut taken = bound_value_names(resolved, target);
1635 for t in resolved.types.values() {
1636 if let TypeBody::Sum(s) = &t.body
1637 && !resolved.unselected_types.contains(&t.name.name)
1638 {
1639 taken.extend(s.variants.iter().map(|v| v.name.name.clone()));
1640 }
1641 }
1642 let mut seen: HashSet<String> = HashSet::new();
1643 let mut ok_types: Vec<TypeDecl> = Vec::new();
1644 let mut ok_consts: Vec<ConstDecl> = Vec::new();
1645 let mut verdict = |name: &Ident,
1646 kind: &str,
1647 dup: &'static str,
1648 clash: &'static str,
1649 errors: &mut Vec<CompileError>|
1650 -> bool {
1651 if !seen.insert(name.name.clone()) {
1652 errors.push(CompileError::new(
1653 dup,
1654 name.span,
1655 format!("this suite declares `{}` twice", name.name),
1656 ));
1657 return false;
1658 }
1659 if taken.contains(&name.name) || name.name.starts_with("__") {
1660 errors.push(
1661 CompileError::new(
1662 clash,
1663 name.span,
1664 format!(
1665 "the suite {kind} `{}` has the name of a declaration already in scope in its cases",
1666 name.name
1667 ),
1668 )
1669 .with_note("rename it; a suite `type` or `const` does not shadow the target's or an imported name"),
1670 );
1671 return false;
1672 }
1673 true
1674 };
1675 for t in types {
1676 if !t.type_params.is_empty() {
1677 errors.push(
1678 CompileError::new(
1679 "bynk.suite.type_generic",
1680 t.name.span,
1681 format!("the suite type `{}` is generic", t.name.name),
1682 )
1683 .with_note("a suite type is a plain, non-generic shape; declare a generic type in the target or a `commons`"),
1684 );
1685 continue;
1686 }
1687 if verdict(
1688 &t.name,
1689 "type",
1690 "bynk.suite.duplicate_type",
1691 "bynk.suite.type_name_clash",
1692 errors,
1693 ) {
1694 ok_types.push(t.clone());
1695 }
1696 }
1697 for c in consts {
1698 if verdict(
1699 &c.name,
1700 "const",
1701 "bynk.suite.duplicate_const",
1702 "bynk.suite.const_name_clash",
1703 errors,
1704 ) {
1705 ok_consts.push(c.clone());
1706 }
1707 }
1708 let item_names: HashSet<&str> = ok_types
1712 .iter()
1713 .map(|t| t.name.name.as_str())
1714 .chain(ok_consts.iter().map(|c| c.name.name.as_str()))
1715 .collect();
1716 let mut variant_seen: HashSet<&str> = HashSet::new();
1717 for t in &ok_types {
1718 let TypeBody::Sum(sum) = &t.body else {
1719 continue;
1720 };
1721 for v in &sum.variants {
1722 let name = v.name.name.as_str();
1723 if taken.contains(name) || item_names.contains(name) || !variant_seen.insert(name) {
1724 errors.push(
1725 CompileError::new(
1726 "bynk.suite.type_name_clash",
1727 v.name.span,
1728 format!(
1729 "the variant `{name}` of the suite type `{}` has the name of another value in scope in the suite's cases",
1730 t.name.name
1731 ),
1732 )
1733 .with_note("rename the variant; a bare variant name would read as either value"),
1734 );
1735 }
1736 }
1737 }
1738 add_suite_fns(
1739 resolved,
1740 SuiteItems {
1741 fns: &[],
1742 fixtures: &[],
1743 types: &ok_types,
1744 consts: &ok_consts,
1745 },
1746 );
1747 let probe_items: Vec<CommonsItem> = ok_types
1751 .iter()
1752 .cloned()
1753 .map(CommonsItem::Type)
1754 .chain(ok_consts.iter().cloned().map(CommonsItem::Const))
1755 .collect();
1756 let saved = std::mem::replace(&mut Arc::make_mut(&mut resolved.commons).items, probe_items);
1757 let resolution = resolver::resolve_file_record(resolved, refs);
1758 Arc::make_mut(&mut resolved.commons).items = saved;
1759 if let Err(errs) = resolution {
1760 errors.extend(errs);
1761 return Default::default();
1762 }
1763 checker::check_suite_decls(&ok_types, &ok_consts, resolved, tys, errors, refs, locals)
1764}
1765
1766#[allow(clippy::too_many_arguments)]
1773pub fn check_suite_fns(
1774 suite_fns: &[FnDecl],
1775 resolved: &mut ResolvedCommons,
1776 target: Option<&UnitTable>,
1777 errors: &mut Vec<CompileError>,
1778 refs: &mut RefSink,
1779 locals: &mut LocalsSink,
1780 tys: &Arc<Types>,
1781) -> (
1782 HashMap<ExprId, checker::TypedExpr>,
1783 HashMap<ExprId, checker::Callee>,
1784) {
1785 let mut expr_types = HashMap::new();
1786 let mut callees = HashMap::new();
1787 if suite_fns.is_empty() {
1788 return (expr_types, callees);
1789 }
1790 let taken = bound_value_names(resolved, target);
1791 add_suite_fns(
1792 resolved,
1793 SuiteItems {
1794 fns: suite_fns,
1795 fixtures: &[],
1796 types: &[],
1797 consts: &[],
1798 },
1799 );
1800 let resolved = &*resolved;
1801 let mut seen: HashSet<&str> = HashSet::new();
1802 for f in suite_fns {
1803 let FnName::Free(name) = &f.name else {
1804 errors.push(
1805 CompileError::new(
1806 "bynk.suite.fn_method",
1807 f.span,
1808 format!(
1809 "a suite helper must be a free function, but `{}` is a method",
1810 f.name.display()
1811 ),
1812 )
1813 .with_note("declare the method in the target or a `commons`; a suite `fn` is a plain helper its cases call by name"),
1814 );
1815 continue;
1816 };
1817 if !seen.insert(name.name.as_str()) {
1818 errors.push(CompileError::new(
1819 "bynk.suite.duplicate_fn",
1820 name.span,
1821 format!("this suite declares the helper `{}` twice", name.name),
1822 ));
1823 continue;
1824 }
1825 if taken.contains(&name.name) || name.name.starts_with("__") {
1826 errors.push(
1827 CompileError::new(
1828 "bynk.suite.fn_name_clash",
1829 name.span,
1830 format!(
1831 "the suite helper `{}` has the name of a declaration already in scope in its cases",
1832 name.name
1833 ),
1834 )
1835 .with_note("rename the helper; a suite `fn` does not shadow the target's or an imported name"),
1836 );
1837 continue;
1838 }
1839 if matches!(f.return_type, TypeRef::Effect(..)) {
1840 errors.push(
1841 CompileError::new(
1842 "bynk.suite.fn_effectful",
1843 f.return_type.span(),
1844 format!("the suite helper `{}` returns an `Effect`", name.name),
1845 )
1846 .with_note("a suite helper is a pure function; build the value in the helper and run the effect in the `case`"),
1847 );
1848 continue;
1849 }
1850 refs.set_owner(f.name.display());
1851 checker::check_suite_fn(
1852 f,
1853 resolved,
1854 &mut expr_types,
1855 &mut callees,
1856 errors,
1857 refs,
1858 &mut HintSink::new(),
1859 locals,
1860 &mut RequirementSink::new(),
1861 tys,
1862 );
1863 refs.clear_owner();
1864 }
1865 (expr_types, callees)
1866}
1867
1868fn view_conflict_error(
1872 c: &crate::project_model::ViewConflict,
1873 span: Span,
1874 names: &str,
1875) -> CompileError {
1876 CompileError::new(
1877 "bynk.uses.name_conflict",
1878 span,
1879 format!(
1880 "`{via}` brings in declarations that use type `{t}` from `{owner}`, but `{t}` in \
1881 this suite names {names}",
1882 via = c.via,
1883 t = c.name,
1884 owner = c.owner,
1885 ),
1886 )
1887 .with_note(
1888 "rename one of the two types; the imported declarations cannot be checked against a \
1889 different type of the same name",
1890 )
1891}
1892
1893fn first_test_target_span(indices: &[usize], parsed: &[ParsedFile]) -> Span {
1894 indices
1895 .first()
1896 .and_then(|&i| parsed[i].test().map(|t| t.target.span))
1897 .unwrap_or_default()
1898}
1899
1900#[allow(clippy::too_many_arguments)]
1905fn check_test_bodies(
1906 target_name: &str,
1907 target_kind: UnitKind,
1908 indices: &[usize],
1909 parsed: &[ParsedFile],
1910 stubs: &HashMap<String, ResolvedStub>,
1911 unit_tables: &HashMap<String, UnitTable>,
1912 exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
1913 unit_consumes: &HashMap<String, Vec<String>>,
1914 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
1915 unit_uses: &HashMap<String, Vec<String>>,
1916 refs: &mut RefSink,
1917 locals: &mut LocalsSink,
1918 tys: &Arc<Types>,
1919 d1_sql: Option<&crate::d1_sql::D1Sql>,
1920) -> Vec<CompileError> {
1921 let mut errors = Vec::new();
1922
1923 let privileged = build_privileged_resolved(
1926 target_name,
1927 unit_tables,
1928 unit_uses,
1929 unit_consumes,
1930 unit_consumes_aliases,
1931 );
1932
1933 if !stubs.is_empty()
1938 && let Some((resolved, _)) = &privileged
1939 {
1940 for rp in stubs.values() {
1941 refs.enter_file(&rp.identity_path, target_name, false);
1942 for (clause_idx, clause) in rp.clauses.iter().enumerate() {
1943 let Some(op) = rp
1944 .cap_decl
1945 .ops
1946 .iter()
1947 .find(|o| o.name.name == clause.method.name)
1948 else {
1949 continue;
1950 };
1951 let clause_view = if rp.clause_fixtures[clause_idx].is_empty()
1954 && rp.clause_fns[clause_idx].is_empty()
1955 && rp.clause_types[clause_idx].is_empty()
1956 && rp.clause_consts[clause_idx].is_empty()
1957 {
1958 None
1959 } else {
1960 build_privileged_resolved(
1961 target_name,
1962 unit_tables,
1963 unit_uses,
1964 unit_consumes,
1965 unit_consumes_aliases,
1966 )
1967 .map(|(mut view, _)| {
1968 add_suite_fns(
1969 &mut view,
1970 SuiteItems {
1971 fns: &rp.clause_fns[clause_idx],
1972 fixtures: &rp.clause_fixtures[clause_idx],
1973 types: &rp.clause_types[clause_idx],
1974 consts: &rp.clause_consts[clause_idx],
1975 },
1976 );
1977 view
1978 })
1979 };
1980 let resolved = clause_view.as_ref().unwrap_or(resolved);
1981 let check_value = |e: &Expr, errors: &mut Vec<CompileError>| {
1982 let errs = stub_value_errors(e, op, resolved, tys);
1983 if errs.is_empty() {
1984 return;
1985 }
1986 let unresolved = stub_name_errors(errs);
1987 if !unresolved.is_empty() {
1988 errors.extend(unresolved);
1989 } else {
1990 errors.push(CompileError::new(
1991 "bynk.stub.rhs_type",
1992 e.span,
1993 format!(
1994 "the value provided for `{}.{}` does not match the operation's declared return type `{}`",
1995 rp.cap,
1996 op.name.name,
1997 ts_type_ref_display(&op.return_type),
1998 ),
1999 ));
2000 }
2001 };
2002 match &clause.rhs {
2003 StubRhs::Returns(e) => check_value(e, &mut errors),
2004 StubRhs::ReturnsEach(outcomes, _) => {
2005 for o in outcomes {
2006 if let SeqOutcome::Value(e) = o {
2007 check_value(e, &mut errors);
2008 }
2009 }
2010 }
2011 StubRhs::Fails(_) | StubRhs::Never(_) => {}
2012 }
2013 if let Some(after) = &clause.after
2015 && !stub_after_typechecks(after, resolved, tys)
2016 {
2017 errors.push(CompileError::new(
2018 "bynk.stub.after_type",
2019 after.span,
2020 format!(
2021 "`after` in a `stub` for `{}.{}` takes a `Duration`, such as `3.seconds`",
2022 rp.cap, op.name.name
2023 ),
2024 ));
2025 }
2026 }
2027 }
2028 }
2029
2030 let crossing = CrossingServices::of(
2033 target_name,
2034 unit_tables,
2035 unit_consumes,
2036 unit_consumes_aliases,
2037 );
2038
2039 let target_shadowed = privileged
2044 .as_ref()
2045 .map(|(r, _)| (r.shadowed_imports.clone(), r.types.clone()))
2046 .unwrap_or_default();
2047 let reach = privileged.map(|(_, r)| r).unwrap_or_default();
2048 let hidden = reach.hidden;
2049
2050 for c in &reach.conflicts {
2056 let Some(bound) = &c.bound else {
2057 continue;
2058 };
2059 let consumed = unit_consumes
2060 .get(target_name)
2061 .is_some_and(|cs| cs.contains(bound));
2062 let exported = exports_visibility
2063 .get(bound)
2064 .is_some_and(|e| e.contains_key(&c.name));
2065 if consumed && !exported {
2066 errors.push(view_conflict_error(
2067 c,
2068 first_test_target_span(indices, parsed),
2069 &format!("`{bound}`'s unexported type"),
2070 ));
2071 }
2072 }
2073
2074 for &i in indices {
2077 let Some(test_decl) = parsed[i].test() else {
2078 continue;
2079 };
2080 let maps = (unit_tables, unit_uses, unit_consumes, unit_consumes_aliases);
2081 errors.extend(suite_naming_errors(
2082 test_decl,
2083 &parsed[i],
2084 target_name,
2085 maps,
2086 (&hidden, &target_shadowed),
2087 ));
2088 let namespace = if SuiteItems::of(test_decl).is_empty() {
2094 target_name.to_string()
2095 } else {
2096 let ns = suite_helper_namespace(target_name, &parsed[i].identity_path());
2097 let mut resolution = vec![target_name.to_string()];
2098 resolution.extend(unit_uses.get(target_name).into_iter().flatten().cloned());
2099 resolution.extend(
2100 unit_consumes
2101 .get(target_name)
2102 .into_iter()
2103 .flatten()
2104 .cloned(),
2105 );
2106 refs.declare_namespace(&ns, resolution);
2107 ns
2108 };
2109 refs.enter_file(
2110 &parsed[i].identity_path(),
2111 &namespace,
2112 parsed[i].is_synthetic(),
2113 );
2114 locals.enter_file(&parsed[i].identity_path(), parsed[i].is_synthetic());
2116 if !SuiteItems::of(test_decl).is_empty()
2119 && let Some((mut helper_view, _)) = build_privileged_resolved(
2120 target_name,
2121 unit_tables,
2122 unit_uses,
2123 unit_consumes,
2124 unit_consumes_aliases,
2125 )
2126 {
2127 register_call_record_types(&mut helper_view, target_name, unit_tables);
2128 check_suite_fixtures_in(
2129 test_decl,
2130 &helper_view,
2131 unit_tables.get(target_name),
2132 &mut errors,
2133 );
2134 add_suite_fns(
2135 &mut helper_view,
2136 SuiteItems {
2137 fns: &[],
2138 fixtures: &test_decl.fixtures,
2139 types: &[],
2140 consts: &[],
2141 },
2142 );
2143 check_suite_decls(
2144 &test_decl.types,
2145 &test_decl.consts,
2146 &mut helper_view,
2147 unit_tables.get(target_name),
2148 &mut errors,
2149 refs,
2150 locals,
2151 tys,
2152 );
2153 check_suite_fns(
2154 &test_decl.fns,
2155 &mut helper_view,
2156 unit_tables.get(target_name),
2157 &mut errors,
2158 refs,
2159 locals,
2160 tys,
2161 );
2162 }
2163 for case in &test_decl.cases {
2164 let case_callees = check_test_case_body(
2165 target_name,
2166 target_kind,
2167 SuiteItems::of(test_decl),
2168 case,
2169 unit_tables,
2170 unit_uses,
2171 unit_consumes,
2172 unit_consumes_aliases,
2173 &mut errors,
2174 refs,
2175 locals,
2176 tys,
2177 );
2178 check_d1_sql_sites(
2179 d1_sql,
2180 target_name,
2181 unit_tables,
2182 &case_callees,
2183 parsed[i].source(),
2184 &mut errors,
2185 );
2186 let tier = case_effective_tier(case, test_decl);
2187 check_extra_headers_tier(case, tier, &case_callees, &mut errors);
2188 check_extra_headers_let(case, &case_callees, &mut errors);
2189 check_faults_tier(case, tier, &mut errors);
2190 check_snapshot_placement(
2191 case,
2192 tier == bynk_syntax::ast::TestTier::System,
2193 &mut errors,
2194 );
2195 check_bad_signature_tier(case, tier, &mut errors);
2196 check_wire_tier(case, tier, &mut errors);
2197 if tier != bynk_syntax::ast::TestTier::System {
2198 crossing.check_case_stubbed(stubs, target_name, case, tier, &mut errors);
2199 }
2200 }
2201 for prop in &test_decl.properties {
2208 check_property_body(
2209 target_name,
2210 target_kind,
2211 SuiteItems::of(test_decl),
2212 prop,
2213 unit_tables,
2214 unit_uses,
2215 unit_consumes,
2216 unit_consumes_aliases,
2217 &mut errors,
2218 refs,
2219 locals,
2220 tys,
2221 d1_sql,
2222 parsed[i].source(),
2223 );
2224 crossing.check_property_stubbed(stubs, target_name, prop, &mut errors);
2225 check_advance_in_property(prop, &mut errors);
2226 check_snapshot_in_property(prop, &mut errors);
2227 }
2228 }
2229
2230 errors
2231}
2232
2233pub fn snapshot_expects(block: &Block) -> Vec<&bynk_syntax::ast::ExpectStmt> {
2236 blocks_deep(block)
2237 .into_iter()
2238 .flat_map(flat_statements)
2239 .filter_map(|s| match s {
2240 Statement::Expect(e) if e.snapshot.is_some() => Some(e),
2241 _ => None,
2242 })
2243 .collect()
2244}
2245
2246fn check_snapshot_placement(case: &Case, no_store: bool, errors: &mut Vec<CompileError>) {
2251 let mut seen: HashSet<&str> = HashSet::new();
2252 for e in snapshot_expects(&case.body) {
2253 let clause = e.snapshot.as_ref().expect("snapshot_expects filters");
2254 if no_store {
2255 errors.push(
2256 CompileError::new(
2257 "bynk.test.snapshot_needs_unit_suite",
2258 clause.span,
2259 "a snapshot is not available in a `system`-tier case or an integration or system suite",
2260 )
2261 .with_note(
2262 "snapshots are stored per unit suite file; take the snapshot in a unit-tier `case` of a suite that targets a unit",
2263 ),
2264 );
2265 } else if !seen.insert(clause.name.as_str()) {
2266 errors.push(
2267 CompileError::new(
2268 "bynk.test.snapshot_duplicate_name",
2269 clause.name_span,
2270 format!(
2271 "case `\"{}\"` already has a snapshot named `\"{}\"`",
2272 case.name, clause.name
2273 ),
2274 )
2275 .with_note("a snapshot is keyed by its case and name, so give each `matches snapshot` in a case its own name"),
2276 );
2277 }
2278 }
2279}
2280
2281fn check_snapshot_in_property(
2284 prop: &bynk_syntax::ast::PropertyDecl,
2285 errors: &mut Vec<CompileError>,
2286) {
2287 for e in snapshot_expects(&prop.forall.body) {
2288 let clause = e.snapshot.as_ref().expect("snapshot_expects filters");
2289 errors.push(
2290 CompileError::new(
2291 "bynk.test.snapshot_in_property",
2292 clause.span,
2293 "a snapshot can only be taken in a `case`, not in a `property`",
2294 )
2295 .with_note("a property runs its body for many generated inputs; snapshot a fixed value in a `case`"),
2296 );
2297 }
2298}
2299
2300fn check_advance_in_property(
2305 prop: &bynk_syntax::ast::PropertyDecl,
2306 errors: &mut Vec<CompileError>,
2307) {
2308 fn collect(b: &Block, out: &mut Vec<Span>) {
2309 for s in &b.statements {
2310 if let Statement::Advance(a) = s {
2311 out.push(a.keyword.merge(a.cap.span));
2312 }
2313 }
2314 let mut exprs = Vec::new();
2315 for s in &b.statements {
2316 bynk_syntax::ast::statement_exprs(s, &mut exprs);
2317 }
2318 exprs.push(&b.tail);
2319 for e in exprs {
2320 walk(e, out);
2321 }
2322 }
2323 fn walk(e: &Expr, out: &mut Vec<Span>) {
2326 match &e.kind {
2327 ExprKind::Block(inner) => collect(inner, out),
2328 ExprKind::If {
2329 cond,
2330 then_block,
2331 else_block,
2332 } => {
2333 walk(cond, out);
2334 collect(then_block, out);
2335 collect(else_block, out);
2336 }
2337 ExprKind::Match { discriminant, arms } => {
2338 walk(discriminant, out);
2339 for arm in arms {
2340 if let Some(g) = &arm.guard {
2341 walk(g, out);
2342 }
2343 match &arm.body {
2344 bynk_syntax::ast::MatchBody::Block(b) => collect(b, out),
2345 bynk_syntax::ast::MatchBody::Expr(x) => walk(x, out),
2346 }
2347 }
2348 }
2349 _ => {
2350 for c in bynk_syntax::ast::expr_children(e) {
2351 walk(c, out);
2352 }
2353 }
2354 }
2355 }
2356 let mut spans = Vec::new();
2357 collect(&prop.forall.body, &mut spans);
2358 for span in spans {
2359 errors.push(
2360 CompileError::new(
2361 "bynk.test.advance_outside_case",
2362 span,
2363 format!(
2364 "`advance` is only valid inside a `case` body, but this is in property `\"{}\"`",
2365 prop.name
2366 ),
2367 )
2368 .with_note(
2369 "a property runs its body once per generated input, with no clock of its own; move the time-dependent check into a `case`",
2370 ),
2371 );
2372 }
2373}
2374
2375pub fn value_block(e: &Expr) -> Block {
2385 Block {
2386 statements: Vec::new(),
2387 tail: Box::new(e.clone()),
2388 span: e.span,
2389 tail_leading_comments: Vec::new(),
2390 implicit_tail: false,
2391 }
2392}
2393
2394fn stub_name_errors(errs: Vec<CompileError>) -> Vec<CompileError> {
2398 errs.into_iter()
2399 .filter(|e| {
2400 matches!(
2401 e.category,
2402 "bynk.resolve.unknown_name"
2403 | "bynk.resolve.unknown_function"
2404 | "bynk.resolve.ambiguous_variant"
2405 )
2406 })
2407 .collect()
2408}
2409
2410fn stub_value_errors(
2415 e: &Expr,
2416 op: &CapabilityOp,
2417 resolved: &ResolvedCommons,
2418 tys: &Arc<Types>,
2419) -> Vec<CompileError> {
2420 value_errors(e, &op.return_type, &op.params, resolved, tys)
2421}
2422
2423pub fn stub_after_typechecks(e: &Expr, resolved: &ResolvedCommons, tys: &Arc<Types>) -> bool {
2425 let duration = TypeRef::Effect(Box::new(TypeRef::Base(BaseType::Duration, e.span)), e.span);
2426 value_errors(e, &duration, &[], resolved, tys).is_empty()
2427}
2428
2429fn value_errors(
2430 e: &Expr,
2431 return_type: &TypeRef,
2432 params: &[Param],
2433 resolved: &ResolvedCommons,
2434 tys: &Arc<Types>,
2435) -> Vec<CompileError> {
2436 let block = value_block(e);
2437 let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
2438 let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
2439 let mut errs: Vec<CompileError> = Vec::new();
2440 checker::check_handler_body(
2441 resolved,
2442 checker::HandlerBodyCheck::new(&block, return_type, params, &[]),
2443 checker::CheckSinks {
2444 tys,
2445 expr_types: &mut expr_types,
2446 errors: &mut errs,
2447 refs: &mut RefSink::new(),
2448 hints: &mut HintSink::new(),
2449 locals: &mut LocalsSink::new(),
2450 requirements: &mut RequirementSink::new(),
2451 callees: &mut callees,
2452 },
2453 );
2454 errs
2455}
2456
2457fn block_uses_wire(block: &Block) -> bool {
2461 fn contains_wire(e: &Expr) -> bool {
2468 matches!(e.kind, ExprKind::Wire(_))
2469 || bynk_syntax::ast::expr_children(e)
2470 .into_iter()
2471 .any(contains_wire)
2472 }
2473 let mut exprs = Vec::new();
2476 for s in &block.statements {
2477 bynk_syntax::ast::statement_exprs(s, &mut exprs);
2478 }
2479 exprs.into_iter().any(contains_wire) || contains_wire(&block.tail)
2480}
2481
2482type CrossCall = (String, String);
2484
2485type AgentHandler = (String, String);
2487
2488fn stubbed_services(
2492 stubs: &HashMap<String, ResolvedStub>,
2493 case: Option<&str>,
2494) -> HashSet<CrossCall> {
2495 let mut out = HashSet::new();
2496 for rp in stubs.values() {
2497 let Some(ctx) = &rp.service_context else {
2498 continue;
2499 };
2500 for (clause, scope) in rp.clauses.iter().zip(&rp.clause_scopes) {
2501 let applies = match scope {
2502 StubScope::Case(name) => case == Some(name.as_str()),
2503 _ => true,
2504 };
2505 if applies {
2506 out.insert((ctx.clone(), clause.method.name.clone()));
2507 }
2508 }
2509 }
2510 out
2511}
2512
2513struct CrossingServices<'a> {
2533 services: HashMap<String, CrossCall>,
2535 agents: HashMap<AgentHandler, CrossCall>,
2537 table: Option<&'a UnitTable>,
2539 consumed: &'a [String],
2541 aliases: Option<&'a HashMap<String, String>>,
2542 unit_tables: &'a HashMap<String, UnitTable>,
2543 stubbed: HashSet<CrossCall>,
2546 consumes: &'a HashMap<String, Vec<String>>,
2548 all_aliases: &'a HashMap<String, HashMap<String, String>>,
2549}
2550
2551impl<'a> CrossingServices<'a> {
2552 fn of(
2553 target_name: &str,
2554 unit_tables: &'a HashMap<String, UnitTable>,
2555 unit_consumes: &'a HashMap<String, Vec<String>>,
2556 unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
2557 ) -> Self {
2558 Self::of_stubbed(
2559 target_name,
2560 unit_tables,
2561 unit_consumes,
2562 unit_consumes_aliases,
2563 HashSet::new(),
2564 )
2565 }
2566
2567 fn of_stubbed(
2570 target_name: &str,
2571 unit_tables: &'a HashMap<String, UnitTable>,
2572 unit_consumes: &'a HashMap<String, Vec<String>>,
2573 unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
2574 stubbed: HashSet<CrossCall>,
2575 ) -> Self {
2576 let mut this = CrossingServices {
2577 services: HashMap::new(),
2578 agents: HashMap::new(),
2579 table: unit_tables.get(target_name),
2580 consumed: unit_consumes
2581 .get(target_name)
2582 .map(Vec::as_slice)
2583 .unwrap_or(&[]),
2584 aliases: unit_consumes_aliases.get(target_name),
2585 unit_tables,
2586 consumes: unit_consumes,
2587 all_aliases: unit_consumes_aliases,
2588 stubbed,
2589 };
2590 let Some(table) = this.table else {
2591 return this;
2592 };
2593 if this.consumed.is_empty() {
2594 return this;
2595 }
2596 let mut agent_edges: HashMap<AgentHandler, Vec<AgentHandler>> = HashMap::new();
2599 for (agent, decl) in &table.agents {
2600 for h in &decl.handlers {
2601 let Some(method) = &h.method_name else {
2602 continue;
2603 };
2604 let key = (agent.clone(), method.name.clone());
2605 let (hit, edges) = this.scan(&h.body);
2606 if let Some(hit) = hit {
2607 this.agents.insert(key.clone(), hit);
2608 }
2609 agent_edges.insert(key, edges);
2610 }
2611 }
2612 loop {
2613 let mut changed = false;
2614 for (key, edges) in &agent_edges {
2615 if this.agents.contains_key(key) {
2616 continue;
2617 }
2618 if let Some(hit) = edges.iter().find_map(|e| this.agents.get(e).cloned()) {
2619 this.agents.insert(key.clone(), hit);
2620 changed = true;
2621 }
2622 }
2623 if !changed {
2624 break;
2625 }
2626 }
2627 for (name, decl) in &table.services {
2628 for h in &decl.handlers {
2629 let (hit, edges) = this.scan(&h.body);
2630 let reached =
2631 hit.or_else(|| edges.iter().find_map(|e| this.agents.get(e).cloned()));
2632 if let Some(reached) = reached {
2633 this.services.entry(name.clone()).or_insert(reached);
2634 }
2635 }
2636 }
2637 this
2638 }
2639
2640 fn resolve(&self, chain: &str) -> Option<&String> {
2642 self.aliases
2643 .and_then(|a| a.get(chain))
2644 .or_else(|| self.consumed.iter().find(|c| *c == chain))
2645 }
2646
2647 fn cross_call(&self, e: &Expr) -> Option<CrossCall> {
2649 let ExprKind::MethodCall {
2650 receiver, method, ..
2651 } = &e.kind
2652 else {
2653 return None;
2654 };
2655 let ctx = self.resolve(&receiver_chain(receiver)?)?;
2656 let callee = self.unit_tables.get(ctx)?;
2657 callee
2658 .services
2659 .contains_key(&method.name)
2660 .then(|| (ctx.clone(), method.name.clone()))
2661 }
2662
2663 fn dispatch(&self, e: &Expr, bound: &HashMap<String, String>) -> Option<AgentHandler> {
2666 let table = self.table?;
2667 let ExprKind::MethodCall {
2668 receiver, method, ..
2669 } = &e.kind
2670 else {
2671 return None;
2672 };
2673 let agent = match &receiver.kind {
2674 ExprKind::Call { name, .. } if table.agents.contains_key(&name.name) => {
2675 name.name.clone()
2676 }
2677 ExprKind::Ident(x) => bound.get(&x.name)?.clone(),
2678 _ => return None,
2679 };
2680 Some((agent, method.name.clone()))
2681 }
2682
2683 fn scan(&self, block: &Block) -> (Option<CrossCall>, Vec<AgentHandler>) {
2686 let bound = self.agent_bindings(block);
2687 let mut hit = None;
2688 let mut edges = Vec::new();
2689 for e in exprs_in_order(block) {
2690 if hit.is_none() {
2691 hit = self.cross_call(e).filter(|c| !self.stubbed.contains(c));
2692 }
2693 if let Some(edge) = self.dispatch(e, &bound) {
2694 edges.push(edge);
2695 }
2696 }
2697 (hit, edges)
2698 }
2699
2700 fn agent_bindings(&self, block: &Block) -> HashMap<String, String> {
2703 let mut bound = HashMap::new();
2704 let Some(table) = self.table else {
2705 return bound;
2706 };
2707 for b in blocks_deep(block) {
2708 for s in flat_statements(b) {
2709 if let Statement::Let(l) | Statement::EffectLet(l) = s
2710 && let ExprKind::Call { name, .. } = &l.value.kind
2711 && table.agents.contains_key(&name.name)
2712 {
2713 bound.insert(l.name.name.clone(), name.name.clone());
2714 }
2715 }
2716 }
2717 bound
2718 }
2719
2720 fn check_block(
2726 &self,
2727 target_name: &str,
2728 subject: &str,
2729 below: &str,
2730 body: &Block,
2731 errors: &mut Vec<CompileError>,
2732 ) {
2733 if self.consumed.is_empty() {
2734 return;
2735 }
2736 let bound = self.agent_bindings(body);
2737 let shadowed: HashSet<String> = blocks_deep(body)
2739 .into_iter()
2740 .flat_map(flat_statements)
2741 .filter_map(|s| match s {
2742 Statement::Let(l) | Statement::EffectLet(l) => Some(l.name.name.clone()),
2743 _ => None,
2744 })
2745 .collect();
2746 for e in exprs_in_order(body) {
2747 let ExprKind::MethodCall {
2748 receiver,
2749 method,
2750 args,
2751 ..
2752 } = &e.kind
2753 else {
2754 continue;
2755 };
2756 if bynk_syntax::ast::HttpMethod::from_ident(&method.name).is_some()
2761 && args
2762 .first()
2763 .is_some_and(|a| !matches!(a.kind, ExprKind::StrLit(_)))
2764 {
2765 continue;
2766 }
2767 let through = match &receiver.kind {
2768 ExprKind::Ident(svc) if !shadowed.contains(&svc.name) => self
2770 .services
2771 .get(&svc.name)
2772 .map(|reached| (format!("`{}`", svc.name), Some(svc.name.clone()), reached)),
2773 _ => None,
2774 };
2775 let through = through.or_else(|| {
2776 let (agent, handler) = self.dispatch(e, &bound)?;
2777 let reached = self.agents.get(&(agent.clone(), handler.clone()))?;
2778 Some((format!("`{agent}.{handler}`"), None, reached))
2779 });
2780 let message = match through {
2781 Some((via, _, (ctx, svc))) => {
2782 format!(
2783 "{subject} calls {via}, which calls `{ctx}.{svc}` in another context, but {below}"
2784 )
2785 }
2786 None => match self.cross_call(e) {
2787 Some((ctx, svc)) => {
2788 format!("{subject} calls `{ctx}.{svc}` in another context, but {below}")
2789 }
2790 None => continue,
2791 },
2792 };
2793 let service = match &receiver.kind {
2794 ExprKind::Ident(svc) if self.services.contains_key(&svc.name) => {
2795 Some(svc.name.clone())
2796 }
2797 _ => None,
2798 };
2799 let promote = match service {
2800 Some(s) => format!(
2801 "move it into a `system` suite (`suite {target_name} as system {{ … }}`), where the service is addressed by its context path (`{target_name}.{s}(…)`)"
2802 ),
2803 None => format!(
2804 "move it into a `system` suite (`suite {target_name} as system {{ … }}`) and drive it through one of `{target_name}`'s services (`{target_name}.<service>(…)`), which reaches the other context over the real wire"
2805 ),
2806 };
2807 errors.push(
2808 CompileError::new("bynk.tier.cross_context_needs_system", e.span, message)
2809 .with_note(format!(
2810 "below `system` a test runs in-process, with no other context stood up to call; stub the service (`stub <context>.<service>(…) returns …`) to substitute it, or {promote}"
2811 )),
2812 );
2813 }
2814 }
2815
2816 fn with_stubs(
2818 &self,
2819 target_name: &str,
2820 stubs: &HashMap<String, ResolvedStub>,
2821 case: Option<&str>,
2822 ) -> Option<CrossingServices<'a>> {
2823 let stubbed = stubbed_services(stubs, case);
2824 (!stubbed.is_empty()).then(|| {
2825 Self::of_stubbed(
2826 target_name,
2827 self.unit_tables,
2828 self.consumes,
2829 self.all_aliases,
2830 stubbed,
2831 )
2832 })
2833 }
2834
2835 fn check_case_stubbed(
2837 &self,
2838 stubs: &HashMap<String, ResolvedStub>,
2839 target_name: &str,
2840 case: &Case,
2841 tier: TestTier,
2842 errors: &mut Vec<CompileError>,
2843 ) {
2844 let gate = self.with_stubs(target_name, stubs, Some(&case.name));
2845 gate.as_ref()
2846 .unwrap_or(self)
2847 .check_case(target_name, case, tier, errors);
2848 }
2849
2850 fn check_property_stubbed(
2852 &self,
2853 stubs: &HashMap<String, ResolvedStub>,
2854 target_name: &str,
2855 prop: &PropertyDecl,
2856 errors: &mut Vec<CompileError>,
2857 ) {
2858 let gate = self.with_stubs(target_name, stubs, None);
2859 gate.as_ref()
2860 .unwrap_or(self)
2861 .check_property(target_name, prop, errors);
2862 }
2863
2864 fn check_case(
2866 &self,
2867 target_name: &str,
2868 case: &Case,
2869 tier: TestTier,
2870 errors: &mut Vec<CompileError>,
2871 ) {
2872 let tier = tier.as_str();
2873 let article = if tier == "integration" { "an" } else { "a" };
2875 self.check_block(
2876 target_name,
2877 &format!("case `\"{}\"`", case.name),
2878 &format!("it is {article} `{tier}`-tier case"),
2879 &case.body,
2880 errors,
2881 );
2882 }
2883
2884 fn check_property(
2886 &self,
2887 target_name: &str,
2888 prop: &PropertyDecl,
2889 errors: &mut Vec<CompileError>,
2890 ) {
2891 self.check_block(
2892 target_name,
2893 &format!("property `\"{}\"`", prop.name),
2894 "a property runs in-process (it generates, and has no `system` tier)",
2895 &prop.forall.body,
2896 errors,
2897 );
2898 }
2899}
2900
2901fn receiver_chain(e: &Expr) -> Option<String> {
2904 match &e.kind {
2905 ExprKind::Ident(id) => Some(id.name.clone()),
2906 ExprKind::FieldAccess { receiver, field } => {
2907 Some(format!("{}.{}", receiver_chain(receiver)?, field.name))
2908 }
2909 _ => None,
2910 }
2911}
2912
2913fn exprs_in_order(block: &Block) -> Vec<&Expr> {
2917 let mut roots: Vec<&Expr> = Vec::new();
2918 for s in &block.statements {
2919 bynk_syntax::ast::statement_exprs(s, &mut roots);
2920 }
2921 roots.push(&block.tail);
2922 let mut stack: Vec<&Expr> = roots.into_iter().rev().collect();
2924 let mut out = Vec::new();
2925 while let Some(e) = stack.pop() {
2926 out.push(e);
2927 stack.extend(bynk_syntax::ast::expr_children(e).into_iter().rev());
2928 }
2929 out
2930}
2931
2932fn flat_statements(block: &Block) -> Vec<&Statement> {
2936 fn push<'a>(s: &'a Statement, out: &mut Vec<&'a Statement>) {
2937 match s {
2938 Statement::Par(p) => p.statements.iter().for_each(|inner| push(inner, out)),
2939 other => out.push(other),
2940 }
2941 }
2942 let mut out = Vec::new();
2943 block.statements.iter().for_each(|s| push(s, &mut out));
2944 out
2945}
2946
2947fn blocks_deep(block: &Block) -> Vec<&Block> {
2950 let mut out = vec![block];
2951 for e in exprs_in_order(block) {
2952 match &e.kind {
2953 ExprKind::Block(b) => out.push(b),
2954 ExprKind::If {
2955 then_block,
2956 else_block,
2957 ..
2958 } => {
2959 out.push(then_block);
2960 out.push(else_block);
2961 }
2962 ExprKind::Match { arms, .. } => {
2963 for arm in arms {
2964 if let MatchBody::Block(b) = &arm.body {
2965 out.push(b);
2966 }
2967 }
2968 }
2969 _ => {}
2970 }
2971 }
2972 out
2973}
2974
2975fn block_uses_faults(block: &Block) -> bool {
2981 !faults_claims(block).is_empty()
2982}
2983
2984fn faults_claims(block: &Block) -> Vec<&bynk_syntax::ast::FaultsExpr> {
2987 fn collect<'a>(e: &'a Expr, out: &mut Vec<&'a bynk_syntax::ast::FaultsExpr>) {
2988 if let ExprKind::Faults(f) = &e.kind {
2989 out.push(f);
2990 }
2991 for c in bynk_syntax::ast::expr_children(e) {
2992 collect(c, out);
2993 }
2994 }
2995 let mut exprs = Vec::new();
2996 for s in &block.statements {
2997 bynk_syntax::ast::statement_exprs(s, &mut exprs);
2998 }
2999 exprs.push(&block.tail);
3000 let mut out = Vec::new();
3001 for e in exprs {
3002 collect(e, &mut out);
3003 }
3004 out
3005}
3006
3007fn check_event_address_tier(
3014 case: &Case,
3015 tier: bynk_syntax::ast::TestTier,
3016 callees: &HashMap<ExprId, checker::Callee>,
3017 errors: &mut Vec<CompileError>,
3018) {
3019 if tier != bynk_syntax::ast::TestTier::System {
3020 return;
3021 }
3022 let mut services: Vec<&str> = callees
3023 .values()
3024 .filter_map(|c| match c {
3025 checker::Callee::TestService {
3026 service,
3027 address: checker::HandlerAddress::Event,
3028 ..
3029 } => Some(service.as_str()),
3030 _ => None,
3031 })
3032 .collect();
3033 services.sort_unstable();
3034 services.dedup();
3035 for service in services {
3036 errors.push(
3037 CompileError::new(
3038 "bynk.test.event_needs_in_process",
3039 case.name_span,
3040 format!(
3041 "case `\"{}\"` delivers an event with `{service}.event(…)`, but is a `system`-tier case",
3042 case.name
3043 ),
3044 )
3045 .with_note(
3046 "at `system` an event reaches a subscriber only through its publisher's fan-out; drive the handler that emits it, or deliver the event at `unit` or `integration`",
3047 ),
3048 );
3049 }
3050}
3051
3052fn check_ws_address_tier(
3056 case: &Case,
3057 tier: bynk_syntax::ast::TestTier,
3058 callees: &HashMap<ExprId, checker::Callee>,
3059 errors: &mut Vec<CompileError>,
3060) {
3061 if tier != bynk_syntax::ast::TestTier::System {
3062 return;
3063 }
3064 let mut services: Vec<&str> = callees
3065 .values()
3066 .filter_map(|c| match c {
3067 checker::Callee::TestService {
3068 service,
3069 address: checker::HandlerAddress::Ws(_),
3070 ..
3071 } => Some(service.as_str()),
3072 _ => None,
3073 })
3074 .collect();
3075 services.sort_unstable();
3076 services.dedup();
3077 for service in services {
3078 errors.push(
3079 CompileError::new(
3080 "bynk.test.ws_needs_in_process",
3081 case.name_span,
3082 format!(
3083 "case `\"{}\"` drives the WebSocket service `{service}` by address, but is a `system`-tier case",
3084 case.name
3085 ),
3086 )
3087 .with_note(
3088 "a deployed WebSocket is a real upgrade through the Worker and a Durable Object, which a `system` case does not drive; drive the service at `unit` or `integration`",
3089 ),
3090 );
3091 }
3092}
3093
3094fn check_extra_headers_tier(
3099 case: &Case,
3100 tier: bynk_syntax::ast::TestTier,
3101 callees: &HashMap<ExprId, checker::Callee>,
3102 errors: &mut Vec<CompileError>,
3103) {
3104 if tier == bynk_syntax::ast::TestTier::System {
3105 return;
3106 }
3107 for e in exprs_in_order(&case.body) {
3108 let Some(checker::Callee::TestService {
3109 address,
3110 extra_headers: true,
3111 ..
3112 }) = callees.get(&e.id)
3113 else {
3114 continue;
3115 };
3116 let address = address.describe();
3117 errors.push(
3118 CompileError::new(
3119 "bynk.test.service_call_arity",
3120 e.span,
3121 format!(
3122 "case `\"{}\"` sends extra request headers to `{address}`, which declares no `headers:` parameter, but is a `{}`-tier case",
3123 case.name,
3124 tier.as_str()
3125 ),
3126 )
3127 .with_note(
3128 "extra request headers can only be sent in a `system` case; at lower tiers the route sees only its declared parameters",
3129 ),
3130 );
3131 }
3132}
3133
3134fn check_extra_headers_let(
3139 case: &Case,
3140 callees: &HashMap<ExprId, checker::Callee>,
3141 errors: &mut Vec<CompileError>,
3142) {
3143 use bynk_syntax::ast::ExprKind;
3144 for e in exprs_in_order(&case.body) {
3145 if !matches!(
3146 callees.get(&e.id),
3147 Some(checker::Callee::TestService {
3148 extra_headers: true,
3149 ..
3150 })
3151 ) {
3152 continue;
3153 }
3154 let ExprKind::MethodCall { args, .. } = &e.kind else {
3155 continue;
3156 };
3157 let Some(ExprKind::Ident(name)) = args.last().map(|a| &a.kind) else {
3158 continue;
3159 };
3160 let init = flat_statements(&case.body)
3162 .into_iter()
3163 .filter_map(|s| match s {
3164 Statement::Let(l) | Statement::EffectLet(l) if l.name.name == name.name => {
3165 Some(&l.value)
3166 }
3167 _ => None,
3168 })
3169 .take_while(|v| v.span.start < e.span.start)
3170 .last();
3171 if let Some(init) = init {
3172 errors.extend(checker::extra_headers_authorization_errors(init));
3173 }
3174 }
3175}
3176
3177fn check_call_address_tier(
3184 case: &Case,
3185 tier: bynk_syntax::ast::TestTier,
3186 callees: &HashMap<ExprId, checker::Callee>,
3187 errors: &mut Vec<CompileError>,
3188) {
3189 if tier != bynk_syntax::ast::TestTier::System {
3190 return;
3191 }
3192 let mut services: Vec<&str> = callees
3193 .values()
3194 .filter_map(|c| match c {
3195 checker::Callee::TestService {
3196 service,
3197 address: checker::HandlerAddress::Call,
3198 ..
3199 } => Some(service.as_str()),
3200 _ => None,
3201 })
3202 .collect();
3203 services.sort_unstable();
3204 services.dedup();
3205 for service in services {
3206 errors.push(
3207 CompileError::new(
3208 "bynk.test.call_needs_in_process",
3209 case.name_span,
3210 format!(
3211 "case `\"{}\"` calls the `on call` service `{service}` with `{service}.call(…)`, but is a `system`-tier case",
3212 case.name
3213 ),
3214 )
3215 .with_note(
3216 "an `on call` service is internal to a deployment and has no public route for a `system` case to drive; drive an `http` route that reaches it, or call it at `unit` or `integration`",
3217 ),
3218 );
3219 }
3220}
3221
3222pub fn remote_unsupported(
3242 case: &Case,
3243 callees: &HashMap<ExprId, checker::Callee>,
3244) -> Option<CompileError> {
3245 use checker::Callee;
3246 let callee_list: Vec<&Callee> = callees.values().collect();
3247 let refusal = |code: &'static str, what: String, note: &str| {
3248 Some(
3249 CompileError::new(
3250 code,
3251 case.name_span,
3252 format!(
3253 "case `\"{}\"` {what}, which a run against a real runtime can't honour",
3254 case.name
3255 ),
3256 )
3257 .with_note(note.to_string())
3258 .with_note(
3259 "run it in process (`bynk test` without `--against`), or pass `--skip-unsupported` to skip it with this reason",
3260 ),
3261 )
3262 };
3263 let named = |pick: &dyn Fn(&Callee) -> Option<String>| -> Option<String> {
3265 let mut names: Vec<String> = callee_list.iter().filter_map(|c| pick(c)).collect();
3266 names.sort();
3267 names.into_iter().next()
3268 };
3269 if let Some(svc) = named(&|c| match c {
3270 Callee::Cross { unit, service } => Some(format!("{unit}.{service}")),
3271 Callee::TestService {
3272 service,
3273 address: checker::HandlerAddress::Call,
3274 ..
3275 } => Some(service.clone()),
3276 _ => None,
3277 }) {
3278 return refusal(
3279 "bynk.test.remote_unsupported_call",
3280 format!("addresses the `on call` service `{svc}`"),
3281 "an `on call` service is internal to a deployment, and each call is signed for one caller; drive it through an `http` route",
3282 );
3283 }
3284 if block_has_advance(&case.body) {
3285 return refusal(
3286 "bynk.test.remote_unsupported_advance",
3287 "moves the harness clock with `advance Clock`".to_string(),
3288 "a deployed Worker reads wall-clock time, which the test can't move",
3289 );
3290 }
3291 for (address, code, what) in [
3292 (
3293 "schedule",
3294 "bynk.test.remote_unsupported_schedule",
3295 "runs a cron handler",
3296 ),
3297 (
3298 "message",
3299 "bynk.test.remote_unsupported_queue",
3300 "delivers a queue message",
3301 ),
3302 ] {
3303 if let Some(svc) = named(&|c| match c {
3304 Callee::TestService {
3305 service,
3306 address: checker::HandlerAddress::Schedule { .. },
3307 ..
3308 } if address == "schedule" => Some(service.clone()),
3309 Callee::TestService {
3310 service,
3311 address: checker::HandlerAddress::Message,
3312 ..
3313 } if address == "message" => Some(service.clone()),
3314 _ => None,
3315 }) {
3316 return refusal(
3317 code,
3318 format!("{what} with `{svc}.{address}(…)`"),
3319 "a deployment exposes no public wire to that handler; only its `http` routes are reachable",
3320 );
3321 }
3322 }
3323 if callee_list
3326 .iter()
3327 .any(|c| matches!(c, Callee::D1Peek { .. }))
3328 {
3329 return refusal(
3330 "bynk.test.remote_unsupported_peek",
3331 "reads a participant's database with `D1.peek`".to_string(),
3332 "a deployment has no in-process test database, and reaching a deployed D1 would make a test run touch real data",
3333 );
3334 }
3335 if let Some(svc) = named(&|c| match c {
3336 Callee::TestAssetFetch { service } => Some(service.clone()),
3337 _ => None,
3338 }) {
3339 return refusal(
3340 "bynk.test.remote_unsupported_asset",
3341 format!("fetches an asset with `{svc}.GET(…)`"),
3342 "an asset fetch is answered in process from the files the target ships, not by the deployment",
3343 );
3344 }
3345 None
3346}
3347
3348pub fn remote_clock_dependent(
3372 case: &Case,
3373 expr_types: &HashMap<ExprId, checker::TypedExpr>,
3374 tys: &Types,
3375) -> Option<CompileError> {
3376 struct Scan<'a> {
3377 expr_types: &'a HashMap<ExprId, checker::TypedExpr>,
3378 tys: &'a Types,
3379 constants: HashSet<String>,
3381 found: Option<Span>,
3382 }
3383 impl Scan<'_> {
3384 fn is_instant(&self, e: &Expr) -> bool {
3385 self.expr_types.get(&e.id).is_some_and(|t| {
3386 matches!(&*self.tys.get(t.ty), checker::Ty::Base(BaseType::Instant))
3387 })
3388 }
3389 fn constant(&self, e: &Expr) -> bool {
3390 match &e.kind {
3391 ExprKind::Ident(id) => {
3394 self.constants.contains(&id.name)
3395 || id.name.starts_with(|c: char| c.is_ascii_uppercase())
3396 }
3397 _ => expr_children(e).into_iter().all(|c| self.constant(c)),
3398 }
3399 }
3400 fn without(&mut self, names: Vec<String>, f: impl FnOnce(&mut Self)) {
3402 let saved = self.constants.clone();
3403 for n in &names {
3404 self.constants.remove(n);
3405 }
3406 f(self);
3407 self.constants = saved;
3408 }
3409 fn check(&mut self, pred: &Expr, span: Span) {
3413 if self.found.is_some() {
3414 return;
3415 }
3416 let mut binders = Vec::new();
3417 walk_expr_tree(pred, &mut |e: &Expr| binder_names(e, &mut binders));
3418 let saved = self.constants.clone();
3419 for n in &binders {
3420 self.constants.remove(n);
3421 }
3422 let mut hit = false;
3423 walk_expr_tree(pred, &mut |e: &Expr| {
3424 if let ExprKind::BinOp(
3425 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq,
3426 a,
3427 b,
3428 ) = &e.kind
3429 && [a, b]
3430 .into_iter()
3431 .any(|side| self.is_instant(side) && self.constant(side))
3432 {
3433 hit = true;
3434 }
3435 });
3436 self.constants = saved;
3437 if hit {
3438 self.found = Some(span);
3439 }
3440 }
3441 fn block(&mut self, b: &Block) {
3442 for stmt in &b.statements {
3443 match stmt {
3444 Statement::Let(l) => {
3445 if self.constant(&l.value) {
3446 self.constants.insert(l.name.name.clone());
3447 } else {
3448 self.constants.remove(&l.name.name);
3449 }
3450 }
3451 Statement::EffectLet(l) => {
3452 self.constants.remove(&l.name.name);
3453 }
3454 Statement::Expect(x) => self.check(&x.value, x.span),
3455 _ => {}
3456 }
3457 let mut exprs = Vec::new();
3458 statement_exprs(stmt, &mut exprs);
3459 for e in exprs {
3460 self.expr(e);
3461 }
3462 }
3463 self.expr(&b.tail);
3464 }
3465 fn expr(&mut self, e: &Expr) {
3467 match &e.kind {
3468 ExprKind::Block(b) => self.block(b),
3469 ExprKind::If {
3470 cond,
3471 then_block,
3472 else_block,
3473 } => {
3474 self.expr(cond);
3475 let mut names = Vec::new();
3476 walk_expr_tree(cond, &mut |e: &Expr| binder_names(e, &mut names));
3477 self.without(names, |scan| {
3478 scan.block(then_block);
3479 scan.block(else_block);
3480 });
3481 }
3482 ExprKind::Match { discriminant, arms } => {
3483 self.expr(discriminant);
3484 for arm in arms {
3485 let names = arm
3486 .pattern
3487 .bound_names()
3488 .into_iter()
3489 .map(|id| id.name.clone())
3490 .collect();
3491 self.without(names, |scan| {
3492 if let Some(guard) = &arm.guard {
3493 scan.expr(guard);
3494 }
3495 match &arm.body {
3496 MatchBody::Expr(body) => scan.expr(body),
3497 MatchBody::Block(b) => scan.block(b),
3498 }
3499 });
3500 }
3501 }
3502 ExprKind::Lambda(l) => {
3503 let names = l.params.iter().map(|p| p.name.name.clone()).collect();
3504 self.without(names, |scan| scan.expr(&l.body));
3505 }
3506 ExprKind::Expect(inner) => {
3507 self.check(inner, e.span);
3508 self.expr(inner);
3509 }
3510 _ => {
3511 for c in expr_children(e) {
3512 self.expr(c);
3513 }
3514 }
3515 }
3516 }
3517 }
3518 let mut scan = Scan {
3519 expr_types,
3520 tys,
3521 constants: HashSet::new(),
3522 found: None,
3523 };
3524 scan.block(&case.body);
3525 let span = scan.found?;
3526 Some(
3527 CompileError::new(
3528 "bynk.test.remote_clock_dependent",
3529 span,
3530 format!(
3531 "case `\"{}\"` compares an `Instant` that isn't derived from the run, which can pass in process and fail against a real runtime",
3532 case.name
3533 ),
3534 )
3535 .with_note(
3536 "in process the clock starts at the epoch; a real runtime's Workers read wall-clock time. Assert a relation between instants the run produced (`expires > created`) instead of an absolute instant",
3537 ),
3538 )
3539}
3540
3541fn binder_names(e: &Expr, out: &mut Vec<String>) {
3544 match &e.kind {
3545 ExprKind::Is { pattern, .. } => {
3546 out.extend(pattern.bound_names().into_iter().map(|id| id.name.clone()));
3547 }
3548 ExprKind::Lambda(l) => out.extend(l.params.iter().map(|p| p.name.name.clone())),
3549 ExprKind::Match { arms, .. } => {
3550 for arm in arms {
3551 out.extend(
3552 arm.pattern
3553 .bound_names()
3554 .into_iter()
3555 .map(|id| id.name.clone()),
3556 );
3557 }
3558 }
3559 _ => {}
3560 }
3561}
3562
3563fn walk_expr_tree(e: &Expr, f: &mut dyn FnMut(&Expr)) {
3567 f(e);
3568 for c in expr_children(e) {
3569 walk_expr_tree(c, f);
3570 }
3571}
3572
3573fn block_has_advance(block: &Block) -> bool {
3575 fn walk(e: &Expr) -> bool {
3576 match &e.kind {
3577 ExprKind::Block(b) => block_has_advance(b),
3578 ExprKind::If {
3579 cond,
3580 then_block,
3581 else_block,
3582 } => walk(cond) || block_has_advance(then_block) || block_has_advance(else_block),
3583 ExprKind::Match { discriminant, arms } => {
3584 walk(discriminant)
3585 || arms.iter().any(|a| {
3586 a.guard.as_ref().is_some_and(walk)
3587 || match &a.body {
3588 MatchBody::Block(b) => block_has_advance(b),
3589 MatchBody::Expr(x) => walk(x),
3590 }
3591 })
3592 }
3593 _ => expr_children(e).into_iter().any(walk),
3594 }
3595 }
3596 if block
3597 .statements
3598 .iter()
3599 .any(|s| matches!(s, Statement::Advance(_)))
3600 {
3601 return true;
3602 }
3603 let mut exprs = Vec::new();
3604 for s in &block.statements {
3605 statement_exprs(s, &mut exprs);
3606 }
3607 exprs.push(&block.tail);
3608 exprs.into_iter().any(walk)
3609}
3610
3611fn check_system_claims_literal(case: &Case, errors: &mut Vec<CompileError>) {
3618 for b in blocks_deep(&case.body) {
3619 for st in flat_statements(b) {
3620 let Statement::EffectLet(l) = st else {
3621 continue;
3622 };
3623 let Some(claims) = l.principal.as_ref().and_then(|p| p.claims.as_deref()) else {
3624 continue;
3625 };
3626 let literal = matches!(
3627 &claims.kind,
3628 ExprKind::MethodCall { receiver, method, args, .. }
3629 if method.name == "of"
3630 && args.len() == 1
3631 && matches!(&receiver.kind, ExprKind::Ident(id) if id.name == "TokenClaims")
3632 );
3633 if !literal {
3634 errors.push(
3635 CompileError::new(
3636 "bynk.test.system_claims_need_literal",
3637 claims.span,
3638 "a `system`-tier case mints the token's claims from the lines of a `TokenClaims.of([…])` written in the principal",
3639 )
3640 .with_note(
3641 "write `by Actor(\"id\", TokenClaims.of([\"name: value\"]))` here, or move the case to a suite `as integration`, where the handler reads the claims value as given",
3642 ),
3643 );
3644 }
3645 }
3646 }
3647}
3648
3649fn check_faults_tier(
3658 case: &Case,
3659 tier: bynk_syntax::ast::TestTier,
3660 errors: &mut Vec<CompileError>,
3661) {
3662 if tier != bynk_syntax::ast::TestTier::System {
3663 for p in faults_claims(&case.body)
3664 .into_iter()
3665 .filter_map(|f| f.principal.as_ref())
3666 .filter(|p| CallSitePrincipal::of(&p.actor.name).is_reserved())
3667 {
3668 let name = &p.actor.name;
3671 let what = if CallSitePrincipal::of(name) == CallSitePrincipal::Nobody {
3672 "the missing credential"
3673 } else {
3674 "the bad credential"
3675 };
3676 errors.push(
3677 CompileError::new(
3678 "bynk.test.faults_needs_in_process",
3679 p.span,
3680 format!("a fault claim cannot be driven `by {name}`: {what} is rejected only by the `system`-tier auth seam, where a fault is never a throw"),
3681 )
3682 .with_note(format!(
3683 "assert the rejection instead, in a `system` case: `let r <- <call> by {name}` then `expect r is Rejected(Unauthorized)`"
3684 )),
3685 );
3686 }
3687 return;
3688 }
3689 if block_uses_faults(&case.body) {
3690 errors.push(
3691 CompileError::new(
3692 "bynk.test.faults_needs_in_process",
3693 case.name_span,
3694 format!(
3695 "case `\"{}\"` claims a fault with `faults`, but is a `system`-tier case",
3696 case.name
3697 ),
3698 )
3699 .with_note(
3700 "at `system` a handler's fault reaches the case as an error response from the deployed Worker, not a throw; claim the fault at `unit` or `integration`, or assert the response at `system`",
3701 ),
3702 );
3703 }
3704}
3705
3706fn check_wire_tier(case: &Case, tier: bynk_syntax::ast::TestTier, errors: &mut Vec<CompileError>) {
3710 if tier == bynk_syntax::ast::TestTier::System || !block_uses_wire(&case.body) {
3711 return;
3712 }
3713 errors.push(CompileError::new(
3714 "bynk.test.wire_needs_system",
3715 case.name_span,
3716 format!(
3717 "case `\"{}\"` uses `Wire(...)` but is not a `system`-tier case",
3718 case.name
3719 ),
3720 ).with_note(
3721 "`Wire` hands raw, pre-validation input to the real boundary; promote the case with `as system`, or pass a typed argument",
3722 ));
3723}
3724
3725fn block_uses_nobody(block: &Block) -> bool {
3732 blocks_deep(block).into_iter().any(|b| {
3733 flat_statements(b).into_iter().any(|s| {
3734 matches!(s, Statement::EffectLet(l)
3735 if l.principal.as_ref().is_some_and(|p| CallSitePrincipal::of(&p.actor.name) == CallSitePrincipal::Nobody))
3736 })
3737 })
3738}
3739
3740fn check_bad_signature_tier(
3747 case: &Case,
3748 tier: bynk_syntax::ast::TestTier,
3749 errors: &mut Vec<CompileError>,
3750) {
3751 if tier == bynk_syntax::ast::TestTier::System {
3752 return;
3753 }
3754 let mut names: Vec<&str> = blocks_deep(&case.body)
3755 .into_iter()
3756 .flat_map(flat_statements)
3757 .filter_map(|s| match s {
3758 Statement::EffectLet(l) => {
3759 l.principal
3760 .as_ref()
3761 .map(|p| p.actor.name.as_str())
3762 .filter(|n| {
3763 matches!(
3764 CallSitePrincipal::of(n),
3765 CallSitePrincipal::BadCredential(_)
3766 )
3767 })
3768 }
3769 _ => None,
3770 })
3771 .collect();
3772 names.sort_unstable();
3773 names.dedup();
3774 for name in names {
3775 errors.push(
3776 CompileError::new(
3777 "bynk.test.forged_needs_system",
3778 case.name_span,
3779 format!(
3780 "case `\"{}\"` drives `by {name}` but is a `{}`-tier case",
3781 case.name,
3782 tier.as_str()
3783 ),
3784 )
3785 .with_note(format!(
3786 "`by {name}` sends a bad credential to the real `Signature` or `Bearer` seam, which only the `system` driver reaches; in process the seam is skipped. Move the case into a `suite … as system`"
3787 )),
3788 );
3789 }
3790}
3791
3792pub fn register_call_record_types(
3797 resolved: &mut ResolvedCommons,
3798 target_name: &str,
3799 unit_tables: &HashMap<String, UnitTable>,
3800) {
3801 let Some(table) = unit_tables.get(target_name) else {
3802 return;
3803 };
3804 let mut caps: Vec<(&String, &CapabilityDecl)> = table.capabilities.iter().collect();
3807 for (n, d) in flattened_platform_capabilities(unit_tables, resolved) {
3808 if !table.capabilities.contains_key(n) {
3809 caps.push((n, d));
3810 }
3811 }
3812 let service_seams = consumed_service_seam_decls(
3815 unit_tables,
3816 &resolved.cross_context.consumed_contexts,
3817 &resolved.cross_context.aliases,
3818 );
3819 for (n, d) in &service_seams {
3820 if !table.capabilities.contains_key(n) {
3821 caps.push((n, d));
3822 }
3823 }
3824 for (cap_name, decl) in caps {
3825 for op in &decl.ops {
3826 let fields: Vec<RecordField> = op
3827 .params
3828 .iter()
3829 .map(|p| RecordField {
3830 annotations: Vec::new(),
3831 documentation: None,
3832 trivia: Default::default(),
3833 name: p.name.clone(),
3834 type_ref: p.type_ref.clone(),
3835 refinement: None,
3836 init: None,
3837 span: p.span,
3838 })
3839 .collect();
3840 let name = checker::call_record_type_name(cap_name, &op.name.name);
3841 resolved.types.insert(
3842 name.clone(),
3843 Arc::new(TypeDecl {
3844 derives: Vec::new(),
3845 derives_kw: None,
3846 type_params: Vec::new(),
3847 name: Ident {
3848 name,
3849 span: op.name.span,
3850 },
3851 body: TypeBody::Record(RecordBody {
3852 trailing_comments: Default::default(),
3853 fields,
3854 span: op.name.span,
3855 }),
3856 documentation: None,
3857 span: op.name.span,
3858 trivia: Trivia::default(),
3859 private: None,
3860 }),
3861 );
3862 }
3863 }
3864}
3865
3866fn target_test_actors(table: Option<&UnitTable>) -> HashMap<String, bynk_syntax::ast::ActorDecl> {
3867 table.map(|t| t.actors.clone()).unwrap_or_default()
3868}
3869
3870pub fn event_publisher(
3877 target: &str,
3878 event: &str,
3879 unit_tables: &HashMap<String, UnitTable>,
3880 consumed: &[String],
3881) -> Result<String, Vec<String>> {
3882 if unit_tables
3883 .get(target)
3884 .is_some_and(|t| t.events.contains_key(event))
3885 {
3886 return Ok(target.to_string());
3887 }
3888 let mut owners: Vec<String> = consumed
3889 .iter()
3890 .filter(|c| c.as_str() != target)
3891 .filter(|c| {
3892 unit_tables
3893 .get(*c)
3894 .is_some_and(|t| t.events.contains_key(event))
3895 })
3896 .cloned()
3897 .collect();
3898 owners.sort();
3899 owners.dedup();
3900 match owners.as_slice() {
3901 [one] => Ok(one.clone()),
3902 _ => Err(owners),
3903 }
3904}
3905
3906fn target_test_services(
3907 target: Option<&str>,
3908 unit_tables: &HashMap<String, UnitTable>,
3909 consumed: &[String],
3910) -> HashMap<String, checker::TestServiceSig> {
3911 use bynk_syntax::ast::ServiceProtocol;
3912 let Some((target, t)) = target.and_then(|n| unit_tables.get(n).map(|t| (n, t))) else {
3913 return HashMap::new();
3914 };
3915 let scope_events: std::collections::BTreeSet<String> = std::iter::once(target)
3918 .chain(consumed.iter().map(String::as_str))
3919 .filter_map(|u| unit_tables.get(u))
3920 .flat_map(|u| u.events.keys().cloned())
3921 .collect();
3922 t.services
3923 .iter()
3924 .map(|(name, decl)| {
3925 let protocol = match &decl.protocol {
3926 ServiceProtocol::Call => None,
3927 ServiceProtocol::Http => Some("http".to_string()),
3928 ServiceProtocol::Cron => Some("cron".to_string()),
3929 ServiceProtocol::Queue { .. } => Some("queue".to_string()),
3930 ServiceProtocol::WebSocket { .. } => Some("websocket".to_string()),
3931 ServiceProtocol::Events { .. } => Some("events".to_string()),
3932 ServiceProtocol::Email { .. } => Some("email".to_string()),
3933 };
3934 let handlers = decl
3935 .handlers
3936 .iter()
3937 .map(|h| checker::TestHandler {
3938 kind: h.kind.clone(),
3939 params: h.params.clone(),
3940 by_clause: h.by_clause.clone(),
3941 return_type: h.return_type.clone(),
3942 span: h.span,
3943 })
3944 .collect();
3945 let (known_events, event_publisher) = match &decl.protocol {
3946 ServiceProtocol::Events {
3947 event_type: TypeRef::Named(e),
3948 ..
3949 } => (
3950 scope_events.clone(),
3951 Some(event_publisher(target, &e.name, unit_tables, consumed)),
3952 ),
3953 _ => (Default::default(), None),
3954 };
3955 let ws_frames = match &decl.protocol {
3956 ServiceProtocol::WebSocket {
3957 in_type, out_type, ..
3958 } => Some((in_type.clone(), out_type.clone())),
3959 _ => None,
3960 };
3961 (
3962 name.clone(),
3963 checker::TestServiceSig {
3964 protocol,
3965 handlers,
3966 known_events,
3967 event_publisher,
3968 ws_frames,
3969 },
3970 )
3971 })
3972 .collect()
3973}
3974
3975fn flattened_platform_capabilities<'a>(
3979 unit_tables: &'a HashMap<String, UnitTable>,
3980 resolved: &ResolvedCommons,
3981) -> Vec<(&'a String, &'a CapabilityDecl)> {
3982 let mut out: Vec<_> = resolved
3983 .cross_context
3984 .flattened_caps
3985 .iter()
3986 .filter_map(|(cap, owner)| {
3987 let t = unit_tables.get(owner)?;
3988 if t.kind != Some(UnitKind::Adapter) {
3989 return None;
3990 }
3991 t.capabilities.get_key_value(cap)
3992 })
3993 .collect();
3994 out.sort_by_key(|(cap, _)| cap.as_str());
3995 out
3996}
3997
3998fn add_consumed_adapter_capabilities(
4004 map: &mut HashMap<String, checker::CapabilityInfo>,
4005 unit_tables: &HashMap<String, UnitTable>,
4006 resolved: &ResolvedCommons,
4007 tys: &Arc<Types>,
4008) {
4009 for (name, decl) in flattened_platform_capabilities(unit_tables, resolved) {
4010 if map.contains_key(name) {
4011 continue;
4012 }
4013 let ops = decl
4014 .ops
4015 .iter()
4016 .map(|op| build_capability_op_info(op, &resolved.types, tys))
4017 .collect();
4018 map.insert(
4019 name.clone(),
4020 checker::CapabilityInfo {
4021 name: name.clone(),
4022 ops,
4023 derived_from: None,
4024 },
4025 );
4026 }
4027}
4028
4029pub fn consumed_service_seam_decls(
4036 unit_tables: &HashMap<String, UnitTable>,
4037 consumed: &[String],
4038 aliases: &HashMap<String, String>,
4039) -> std::collections::BTreeMap<String, CapabilityDecl> {
4040 let mut out = std::collections::BTreeMap::new();
4041 for ctx in consumed {
4042 let Some(table) = unit_tables.get(ctx) else {
4043 continue;
4044 };
4045 if table.kind == Some(UnitKind::Adapter) || table.services.is_empty() {
4046 continue;
4047 }
4048 let mut names: Vec<String> = aliases
4049 .iter()
4050 .filter(|(_, q)| *q == ctx)
4051 .map(|(alias, _)| alias.clone())
4052 .collect();
4053 if names.is_empty() {
4054 names.push(ctx.rsplit('.').next().unwrap_or(ctx).to_string());
4055 }
4056 let mut ops: Vec<CapabilityOp> = table
4057 .services
4058 .values()
4059 .filter_map(|svc| {
4060 let h = svc.handlers.iter().find(|h| h.kind == HandlerKind::Call)?;
4061 Some(CapabilityOp {
4062 name: svc.name.clone(),
4063 type_params: Vec::new(),
4064 params: h.params.clone(),
4065 return_type: h.return_type.clone(),
4066 annotations: Vec::new(),
4067 documentation: None,
4068 span: h.span,
4069 trivia: Default::default(),
4070 })
4071 })
4072 .collect();
4073 ops.sort_by(|a, b| a.name.name.cmp(&b.name.name));
4074 for name in names {
4075 out.entry(name.clone()).or_insert_with(|| CapabilityDecl {
4076 name: Ident {
4077 name: name.clone(),
4078 span: Span::default(),
4079 },
4080 ops: ops.clone(),
4081 derived: None,
4082 documentation: None,
4083 span: Span::default(),
4084 trailing_comments: Vec::new(),
4085 trivia: Default::default(),
4086 });
4087 }
4088 }
4089 out
4090}
4091
4092fn add_consumed_service_seams(
4095 map: &mut HashMap<String, checker::CapabilityInfo>,
4096 resolved: &ResolvedCommons,
4097 unit_tables: &HashMap<String, UnitTable>,
4098 tys: &Arc<Types>,
4099) {
4100 let cross = &resolved.cross_context;
4101 for (name, decl) in
4102 consumed_service_seam_decls(unit_tables, &cross.consumed_contexts, &cross.aliases)
4103 {
4104 let ops = decl
4105 .ops
4106 .iter()
4107 .map(|op| build_capability_op_info(op, &resolved.types, tys))
4108 .collect();
4109 map.entry(name.clone())
4110 .or_insert_with(|| checker::CapabilityInfo {
4111 name,
4112 ops,
4113 derived_from: None,
4114 });
4115 }
4116}
4117
4118#[allow(clippy::too_many_arguments)]
4131pub fn typecheck_case_body(
4132 target_name: &str,
4133 body: &Block,
4134 unit_span: Span,
4135 unit_tables: &HashMap<String, UnitTable>,
4136 resolved: &ResolvedCommons,
4137 errors: &mut Vec<CompileError>,
4138 refs: &mut RefSink,
4139 initial_scope: HashMap<String, checker::TyId>,
4142 tys: &Arc<Types>,
4143) -> (
4144 HashMap<ExprId, checker::TypedExpr>,
4145 HashMap<ExprId, checker::Callee>,
4146) {
4147 typecheck_case_body_recording(
4149 target_name,
4150 body,
4151 unit_span,
4152 unit_tables,
4153 resolved,
4154 errors,
4155 refs,
4156 &mut LocalsSink::new(),
4157 initial_scope,
4158 tys,
4159 )
4160}
4161
4162#[allow(clippy::too_many_arguments)]
4165fn typecheck_case_body_recording(
4166 target_name: &str,
4167 body: &Block,
4168 unit_span: Span,
4169 unit_tables: &HashMap<String, UnitTable>,
4170 resolved: &ResolvedCommons,
4171 errors: &mut Vec<CompileError>,
4172 refs: &mut RefSink,
4173 locals: &mut LocalsSink,
4174 initial_scope: HashMap<String, checker::TyId>,
4175 tys: &Arc<Types>,
4176) -> (
4177 HashMap<ExprId, checker::TypedExpr>,
4178 HashMap<ExprId, checker::Callee>,
4179) {
4180 let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
4181 let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
4182 let synthetic_return = TypeRef::Effect(
4186 Box::new(TypeRef::Result(
4187 Box::new(TypeRef::Unit(unit_span)),
4188 Box::new(TypeRef::ValidationError(unit_span)),
4189 unit_span,
4190 )),
4191 unit_span,
4192 );
4193
4194 let mut capability_info_map: HashMap<String, checker::CapabilityInfo> = HashMap::new();
4197 if let Some(table) = unit_tables.get(target_name) {
4198 for (name, decl) in &table.capabilities {
4199 let ops = decl
4200 .ops
4201 .iter()
4202 .map(|op| build_capability_op_info(op, &resolved.types, tys))
4203 .collect();
4204 capability_info_map.insert(
4205 name.clone(),
4206 checker::CapabilityInfo {
4207 name: name.clone(),
4208 ops,
4209 derived_from: crate::context_checks::derived_from(
4210 decl,
4211 &resolved.cross_context.flattened_caps,
4212 ),
4213 },
4214 );
4215 }
4216 }
4217 add_consumed_adapter_capabilities(&mut capability_info_map, unit_tables, resolved, tys);
4218 add_consumed_service_seams(&mut capability_info_map, resolved, unit_tables, tys);
4219
4220 let given_declared: Vec<String> = capability_info_map.keys().cloned().collect();
4224
4225 let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
4226 let return_ty_span = unit_span;
4227 let mut no_hints = HintSink::new();
4229 let mut no_requirements = RequirementSink::new();
4231 let _ = checker::check_body(
4232 resolved,
4233 body,
4234 return_ty,
4235 return_ty_span,
4236 initial_scope,
4237 checker::CapabilityCtx {
4238 capabilities: capability_info_map.clone(),
4239 declared_capabilities: capability_info_map,
4240 given_remaining: given_declared.iter().cloned().collect(),
4241 given_used: HashSet::new(),
4242 given_entries: Vec::new(),
4243 given_anchor: None,
4244 ..Default::default()
4245 },
4246 target_test_services(
4247 Some(target_name),
4248 unit_tables,
4249 &resolved.cross_context.consumed_contexts,
4250 ),
4251 target_test_actors(unit_tables.get(target_name)),
4252 None,
4253 checker::CheckSinks {
4254 tys,
4255 expr_types: &mut expr_types,
4256 errors,
4257 refs,
4258 hints: &mut no_hints,
4259 locals,
4260 requirements: &mut no_requirements,
4261 callees: &mut callees,
4262 },
4263 );
4264 #[cfg(test)]
4265 crate::testkit::note_callees(target_name, callees.iter());
4266 (expr_types, callees)
4267}
4268
4269fn check_d1_sql_sites(
4272 d1_sql: Option<&crate::d1_sql::D1Sql>,
4273 target_name: &str,
4274 unit_tables: &HashMap<String, UnitTable>,
4275 callees: &HashMap<ExprId, checker::Callee>,
4276 source: &str,
4278 errors: &mut Vec<CompileError>,
4279) {
4280 if let (Some(d1_sql), Some(table)) = (d1_sql, unit_tables.get(target_name)) {
4281 errors.extend(d1_sql.check_unit(target_name, table, callees, Some(source)));
4282 }
4283}
4284
4285#[allow(clippy::too_many_arguments)]
4286fn check_test_case_body(
4287 target_name: &str,
4288 target_kind: UnitKind,
4289 suite_fns: SuiteItems<'_>,
4290 case: &Case,
4291 unit_tables: &HashMap<String, UnitTable>,
4292 unit_uses: &HashMap<String, Vec<String>>,
4293 unit_consumes: &HashMap<String, Vec<String>>,
4294 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
4295 errors: &mut Vec<CompileError>,
4296 refs: &mut RefSink,
4297 locals: &mut LocalsSink,
4298 tys: &Arc<Types>,
4299) -> HashMap<ExprId, checker::Callee> {
4300 let Some((mut resolved, _)) = build_privileged_resolved(
4301 target_name,
4302 unit_tables,
4303 unit_uses,
4304 unit_consumes,
4305 unit_consumes_aliases,
4306 ) else {
4307 return HashMap::new();
4308 };
4309 register_call_record_types(&mut resolved, target_name, unit_tables);
4310 add_suite_fns(&mut resolved, suite_fns);
4311 let _ = target_kind;
4312 let (_, case_callees) = typecheck_case_body_recording(
4313 target_name,
4314 &case.body,
4315 case.span,
4316 unit_tables,
4317 &resolved,
4318 errors,
4319 refs,
4320 locals,
4321 HashMap::new(),
4322 tys,
4323 );
4324 check_restated_contract(&case.body, &resolved, errors);
4335 case_callees
4336}
4337
4338fn check_restated_contract(
4345 body: &Block,
4346 resolved: &ResolvedCommons,
4347 errors: &mut Vec<CompileError>,
4348) {
4349 let mut bound: HashMap<String, (&FnDecl, &[Expr])> = HashMap::new();
4352 for stmt in &body.statements {
4353 let (name, value) = match stmt {
4354 Statement::Let(l) | Statement::EffectLet(l) => (&l.name.name, &l.value),
4355 _ => continue,
4356 };
4357 if let ExprKind::Call {
4358 name: callee, args, ..
4359 } = &value.kind
4360 && let Some(f) = resolved.fns.get(&callee.name)
4361 && matches!(&f.name, FnName::Free(_))
4362 && !f.ensures.is_empty()
4363 && f.params.len() == args.len()
4364 {
4365 bound.insert(name.clone(), (f, args.as_slice()));
4366 }
4367 }
4368 if bound.is_empty() {
4369 return;
4370 }
4371 for stmt in &body.statements {
4372 let Statement::Expect(e) = stmt else { continue };
4373 for (result_name, (f, args)) in &bound {
4374 let result_ident = Expr {
4376 id: ExprId::SYNTHETIC,
4377 kind: ExprKind::Ident(Ident {
4378 name: result_name.clone(),
4379 span: e.span,
4380 }),
4381 span: e.span,
4382 };
4383 let mut subst: HashMap<&str, &Expr> = HashMap::new();
4384 subst.insert("result", &result_ident);
4385 for (p, a) in f.params.iter().zip(args.iter()) {
4386 subst.insert(p.name.name.as_str(), a);
4387 }
4388 for c in &f.ensures {
4389 if expr_alpha_eq_subst(&c.predicate, &e.value, &subst) {
4390 let FnName::Free(fname) = &f.name else {
4391 continue;
4392 };
4393 errors.push(
4394 CompileError::new(
4395 "bynk.contract.restated_by_test",
4396 e.span,
4397 format!(
4398 "this `expect` restates the `ensures {}` contract of `{}`, which is already checked at every call and by the runner",
4399 c.name.name, fname.name
4400 ),
4401 )
4402 .with_note(
4403 "a contract is checked everywhere for free — delete the restating test, or keep a `case` only for a specific witnessed value",
4404 ),
4405 );
4406 break;
4407 }
4408 }
4409 }
4410 }
4411}
4412
4413fn expr_alpha_eq_subst(pattern: &Expr, actual: &Expr, subst: &HashMap<&str, &Expr>) -> bool {
4419 if let ExprKind::Ident(id) = &pattern.kind
4420 && let Some(replacement) = subst.get(id.name.as_str())
4421 {
4422 return expr_struct_eq(replacement, actual);
4423 }
4424 match (&pattern.kind, &actual.kind) {
4425 (ExprKind::Ident(a), ExprKind::Ident(b)) => a.name == b.name,
4426 (ExprKind::IntLit { value: a, .. }, ExprKind::IntLit { value: b, .. }) => a == b,
4427 (ExprKind::BoolLit(a), ExprKind::BoolLit(b)) => a == b,
4428 (ExprKind::StrLit(a), ExprKind::StrLit(b)) => a == b,
4429 (ExprKind::Paren(a), _) => expr_alpha_eq_subst(a, actual, subst),
4430 (_, ExprKind::Paren(b)) => expr_alpha_eq_subst(pattern, b, subst),
4431 (ExprKind::BinOp(oa, la, ra), ExprKind::BinOp(ob, lb, rb)) => {
4432 oa == ob && expr_alpha_eq_subst(la, lb, subst) && expr_alpha_eq_subst(ra, rb, subst)
4433 }
4434 (ExprKind::UnaryOp(oa, a), ExprKind::UnaryOp(ob, b)) => {
4435 oa == ob && expr_alpha_eq_subst(a, b, subst)
4436 }
4437 (
4438 ExprKind::MethodCall {
4439 receiver: ra,
4440 method: ma,
4441 args: aa,
4442 ..
4443 },
4444 ExprKind::MethodCall {
4445 receiver: rb,
4446 method: mb,
4447 args: ab,
4448 ..
4449 },
4450 ) => {
4451 ma.name == mb.name
4452 && aa.len() == ab.len()
4453 && expr_alpha_eq_subst(ra, rb, subst)
4454 && aa
4455 .iter()
4456 .zip(ab.iter())
4457 .all(|(x, y)| expr_alpha_eq_subst(x, y, subst))
4458 }
4459 _ => false,
4460 }
4461}
4462
4463fn expr_struct_eq(a: &Expr, b: &Expr) -> bool {
4466 match (&a.kind, &b.kind) {
4467 (ExprKind::Ident(x), ExprKind::Ident(y)) => x.name == y.name,
4468 (ExprKind::IntLit { value: x, .. }, ExprKind::IntLit { value: y, .. }) => x == y,
4469 (ExprKind::BoolLit(x), ExprKind::BoolLit(y)) => x == y,
4470 (ExprKind::StrLit(x), ExprKind::StrLit(y)) => x == y,
4471 (ExprKind::Paren(x), _) => expr_struct_eq(x, b),
4472 (_, ExprKind::Paren(y)) => expr_struct_eq(a, y),
4473 (ExprKind::BinOp(oa, la, ra), ExprKind::BinOp(ob, lb, rb)) => {
4474 oa == ob && expr_struct_eq(la, lb) && expr_struct_eq(ra, rb)
4475 }
4476 (ExprKind::UnaryOp(oa, x), ExprKind::UnaryOp(ob, y)) => oa == ob && expr_struct_eq(x, y),
4477 (
4478 ExprKind::MethodCall {
4479 receiver: ra,
4480 method: ma,
4481 args: aa,
4482 ..
4483 },
4484 ExprKind::MethodCall {
4485 receiver: rb,
4486 method: mb,
4487 args: ab,
4488 ..
4489 },
4490 ) => {
4491 ma.name == mb.name
4492 && aa.len() == ab.len()
4493 && expr_struct_eq(ra, rb)
4494 && aa.iter().zip(ab.iter()).all(|(x, y)| expr_struct_eq(x, y))
4495 }
4496 _ => false,
4497 }
4498}
4499
4500pub const PROP_GEN_DEPTH: u32 = 12;
4503
4504pub fn prop_binding_generable(
4510 ty: checker::TyId,
4511 types: &HashMap<String, Arc<TypeDecl>>,
4512 depth: u32,
4513 tys: &Arc<Types>,
4514) -> bool {
4515 if depth == 0 {
4516 return false;
4517 }
4518 match &*tys.get(ty) {
4519 checker::Ty::Base(_) => true,
4520 checker::Ty::Named { name, .. } => {
4521 let Some(decl) = types.get(name) else {
4522 return false;
4523 };
4524 match &decl.body {
4525 TypeBody::Refined { refinement, .. } | TypeBody::Opaque { refinement, .. } => {
4526 !refinement_lacks_generator(refinement.as_ref())
4527 }
4528 TypeBody::Sum(s) => s.variants.first().is_some_and(|v| {
4529 v.payload.iter().all(|f| {
4530 checker::resolve_type_ref(&f.type_ref, types, tys)
4531 .is_some_and(|t| prop_binding_generable(t, types, depth - 1, tys))
4532 })
4533 }),
4534 TypeBody::Record(r) => r.fields.iter().all(|f| {
4535 !refinement_lacks_generator(f.refinement.as_ref())
4538 && checker::resolve_type_ref(&f.type_ref, types, tys)
4539 .is_some_and(|t| prop_binding_generable(t, types, depth - 1, tys))
4540 }),
4541 }
4542 }
4543 _ => false,
4544 }
4545}
4546
4547fn refinement_lacks_generator(refinement: Option<&Refinement>) -> bool {
4550 refinement.is_some_and(crate::checker::refinement_needs_pin)
4551}
4552
4553fn named_refinement<'a>(
4556 ty: checker::TyId,
4557 types: &'a HashMap<String, Arc<TypeDecl>>,
4558 tys: &Arc<Types>,
4559) -> Option<&'a Refinement> {
4560 let node = tys.get(ty);
4561 let checker::Ty::Named { name, .. } = &*node else {
4562 return None;
4563 };
4564 match &types.get(name)?.body {
4565 TypeBody::Refined { refinement, .. } | TypeBody::Opaque { refinement, .. } => {
4566 refinement.as_ref()
4567 }
4568 _ => None,
4569 }
4570}
4571
4572fn predicate_restates_refinement(pred: &Expr, bound_var: &str, refinement: &Refinement) -> bool {
4578 let ExprKind::BinOp(op, lhs, rhs) = &pred.kind else {
4579 return false;
4580 };
4581 let ExprKind::Ident(id) = &lhs.kind else {
4583 return false;
4584 };
4585 if id.name != bound_var {
4586 return false;
4587 }
4588 let ExprKind::IntLit { value: n, .. } = &rhs.kind else {
4589 return false;
4590 };
4591 let n = *n;
4592 let positive = refinement
4593 .predicates
4594 .iter()
4595 .any(|p| matches!(p.kind, PredKind::Positive));
4596 let non_negative = refinement
4597 .predicates
4598 .iter()
4599 .any(|p| matches!(p.kind, PredKind::NonNegative));
4600 match op {
4601 BinOp::Gt if n == 0 => positive,
4603 BinOp::GtEq if n == 1 => positive,
4604 BinOp::GtEq if n == 0 => non_negative,
4606 _ => false,
4607 }
4608}
4609
4610#[derive(Clone, Copy)]
4613enum HistoryRestate {
4614 Invariant,
4616 Transition,
4618}
4619
4620fn as_new_field<'a>(e: &'a Expr, s: &str) -> Option<&'a str> {
4623 let ExprKind::FieldAccess { receiver, field } = &e.kind else {
4624 return None;
4625 };
4626 let ExprKind::FieldAccess {
4627 receiver: inner,
4628 field: which,
4629 } = &receiver.kind
4630 else {
4631 return None;
4632 };
4633 let ExprKind::Ident(id) = &inner.kind else {
4634 return None;
4635 };
4636 (id.name == s && which.name == "new").then_some(field.name.as_str())
4637}
4638
4639fn as_step_root<'a>(e: &'a Expr, s: &str) -> Option<&'a str> {
4642 let ExprKind::FieldAccess { receiver, field } = &e.kind else {
4643 return None;
4644 };
4645 let ExprKind::Ident(id) = &receiver.kind else {
4646 return None;
4647 };
4648 (id.name == s && (field.name == "old" || field.name == "new")).then_some(field.name.as_str())
4649}
4650
4651fn history_pred_matches(body: &Expr, s: &str, decl: &Expr, mode: HistoryRestate) -> bool {
4656 match mode {
4658 HistoryRestate::Invariant => {
4659 if let (Some(f), ExprKind::Ident(id)) = (as_new_field(body, s), &decl.kind) {
4660 return f == id.name;
4661 }
4662 }
4663 HistoryRestate::Transition => {
4664 if let (Some(root), ExprKind::Ident(id)) = (as_step_root(body, s), &decl.kind) {
4665 return root == id.name;
4666 }
4667 }
4668 }
4669 match (&body.kind, &decl.kind) {
4670 (ExprKind::Paren(x), _) => history_pred_matches(x, s, decl, mode),
4671 (_, ExprKind::Paren(y)) => history_pred_matches(body, s, y, mode),
4672 (ExprKind::IntLit { value: x, .. }, ExprKind::IntLit { value: y, .. }) => x == y,
4673 (ExprKind::BoolLit(x), ExprKind::BoolLit(y)) => x == y,
4674 (ExprKind::StrLit(x), ExprKind::StrLit(y)) => x == y,
4675 (ExprKind::Ident(x), ExprKind::Ident(y)) => x.name == y.name,
4676 (ExprKind::None, ExprKind::None) => true,
4677 (ExprKind::Some(x), ExprKind::Some(y)) => history_pred_matches(x, s, y, mode),
4678 (ExprKind::UnaryOp(o1, x), ExprKind::UnaryOp(o2, y)) => {
4679 o1 == o2 && history_pred_matches(x, s, y, mode)
4680 }
4681 (
4684 ExprKind::Is {
4685 value: v1,
4686 pattern: p1,
4687 },
4688 ExprKind::Is {
4689 value: v2,
4690 pattern: p2,
4691 },
4692 ) => history_pattern_matches(p1, p2) && history_pred_matches(v1, s, v2, mode),
4693 (ExprKind::BinOp(o1, l1, r1), ExprKind::BinOp(o2, l2, r2)) => {
4694 o1 == o2
4695 && history_pred_matches(l1, s, l2, mode)
4696 && history_pred_matches(r1, s, r2, mode)
4697 }
4698 (
4699 ExprKind::FieldAccess {
4700 receiver: r1,
4701 field: f1,
4702 },
4703 ExprKind::FieldAccess {
4704 receiver: r2,
4705 field: f2,
4706 },
4707 ) => f1.name == f2.name && history_pred_matches(r1, s, r2, mode),
4708 (
4709 ExprKind::MethodCall {
4710 receiver: r1,
4711 method: m1,
4712 args: a1,
4713 ..
4714 },
4715 ExprKind::MethodCall {
4716 receiver: r2,
4717 method: m2,
4718 args: a2,
4719 ..
4720 },
4721 ) => {
4722 m1.name == m2.name
4723 && a1.len() == a2.len()
4724 && history_pred_matches(r1, s, r2, mode)
4725 && a1
4726 .iter()
4727 .zip(a2)
4728 .all(|(x, y)| history_pred_matches(x, s, y, mode))
4729 }
4730 (
4731 ExprKind::Call {
4732 name: n1, args: a1, ..
4733 },
4734 ExprKind::Call {
4735 name: n2, args: a2, ..
4736 },
4737 ) => {
4738 n1.name == n2.name
4739 && a1.len() == a2.len()
4740 && a1
4741 .iter()
4742 .zip(a2)
4743 .all(|(x, y)| history_pred_matches(x, s, y, mode))
4744 }
4745 _ => false,
4746 }
4747}
4748
4749fn history_pattern_matches(a: &Pattern, b: &Pattern) -> bool {
4754 match (a, b) {
4755 (Pattern::Literal { value: x, .. }, Pattern::Literal { value: y, .. }) => x == y,
4756 (
4757 Pattern::Variant {
4758 type_name: t1,
4759 variant: v1,
4760 bindings: b1,
4761 ..
4762 },
4763 Pattern::Variant {
4764 type_name: t2,
4765 variant: v2,
4766 bindings: b2,
4767 ..
4768 },
4769 ) => {
4770 b1.is_empty()
4771 && b2.is_empty()
4772 && v1.name == v2.name
4773 && t1.as_ref().map(|t| &t.name) == t2.as_ref().map(|t| &t.name)
4774 }
4775 _ => false,
4776 }
4777}
4778
4779fn history_restates_invariant(prop: &PropertyDecl, run_var: &str, agent: &AgentDecl) -> bool {
4786 let [stmt] = prop.forall.body.statements.as_slice() else {
4787 return false;
4788 };
4789 let Statement::Expect(e) = stmt else {
4790 return false;
4791 };
4792 let ExprKind::MethodCall {
4794 receiver,
4795 method,
4796 args,
4797 ..
4798 } = &e.value.kind
4799 else {
4800 return false;
4801 };
4802 if method.name != "all" && method.name != "any" {
4803 return false;
4804 }
4805 let ExprKind::Ident(recv) = &receiver.kind else {
4806 return false;
4807 };
4808 if recv.name != run_var {
4809 return false;
4810 }
4811 let [arg] = args.as_slice() else {
4812 return false;
4813 };
4814 let ExprKind::Lambda(lam) = &arg.kind else {
4815 return false;
4816 };
4817 let [param] = lam.params.as_slice() else {
4818 return false;
4819 };
4820 let s = ¶m.name.name;
4821 agent
4822 .invariants
4823 .iter()
4824 .any(|inv| history_pred_matches(&lam.body, s, &inv.predicate, HistoryRestate::Invariant))
4825 || agent
4826 .transitions
4827 .iter()
4828 .any(|tr| history_pred_matches(&lam.body, s, &tr.predicate, HistoryRestate::Transition))
4829}
4830
4831fn history_call_type_name(agent: &str) -> String {
4835 format!("__History_{agent}_Call")
4836}
4837fn history_step_type_name(agent: &str) -> String {
4838 format!("__History_{agent}_Step")
4839}
4840fn history_state_type_name(agent: &str) -> String {
4841 format!("__History_{agent}_State")
4842}
4843
4844pub fn history_variant_name(handler: &str) -> String {
4848 let mut chars = handler.chars();
4849 match chars.next() {
4850 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
4851 None => handler.to_string(),
4852 }
4853}
4854
4855pub fn history_handlers(agent: &AgentDecl) -> Vec<&Handler> {
4859 agent
4860 .handlers
4861 .iter()
4862 .filter(|h| matches!(h.kind, HandlerKind::Call) && h.method_name.is_some())
4863 .collect()
4864}
4865
4866pub fn check_history_binding(
4874 inner: &TypeRef,
4875 span: Span,
4876 resolved: &mut ResolvedCommons,
4877 refs: &mut RefSink,
4878 tys: &Arc<Types>,
4879) -> Result<checker::Ty, CompileError> {
4880 let TypeRef::Named(agent_id) = inner else {
4883 return Err(CompileError::new(
4884 "bynk.history.not_an_agent",
4885 span,
4886 format!(
4887 "`for all` cannot generate `History[{}]` — only an agent has handlers to sequence",
4888 ts_type_ref_display(inner)
4889 ),
4890 )
4891 .with_note("generate a driven call-history over an agent: `for all run: History[Agent]`"));
4892 };
4893 let Some(agent) = resolved.agents.get(&agent_id.name).cloned() else {
4894 return Err(CompileError::new(
4895 "bynk.history.not_an_agent",
4896 span,
4897 format!(
4898 "`for all run: History[{}]` names `{}`, which is not an agent in scope",
4899 agent_id.name, agent_id.name
4900 ),
4901 )
4902 .with_note(
4903 "only an agent (with handlers and reachable state) can be driven as a history",
4904 ));
4905 };
4906 refs.record(agent_id.span, SymbolKind::Type, &agent_id.name);
4907
4908 let handlers = history_handlers(&agent);
4909 for h in &handlers {
4913 for p in &h.params {
4914 let generable = checker::resolve_type_ref(&p.type_ref, &resolved.types, tys)
4915 .is_some_and(|t| prop_binding_generable(t, &resolved.types, PROP_GEN_DEPTH, tys));
4916 if !generable {
4917 return Err(CompileError::new(
4918 "bynk.history.not_generable",
4919 span,
4920 format!(
4921 "`History[{}]` cannot be driven — handler `{}`'s parameter `{}: {}` is not generable (e.g. a `Matches` refinement)",
4922 agent_id.name,
4923 h.method_name.as_ref().map(|m| m.name.as_str()).unwrap_or(""),
4924 p.name.name,
4925 ts_type_ref_display(&p.type_ref),
4926 ),
4927 )
4928 .with_note(
4929 "every handler parameter must be refinement-generable for the run to be seeded",
4930 ));
4931 }
4932 }
4933 }
4934
4935 let state_name = history_state_type_name(&agent_id.name);
4940 let call_name = history_call_type_name(&agent_id.name);
4941 let step_name = history_step_type_name(&agent_id.name);
4942
4943 let state_fields: Vec<RecordField> = agent
4946 .store_fields
4947 .iter()
4948 .filter(|f| f.kind.head.name == "Cell" && f.kind.args.len() == 1)
4949 .map(|f| RecordField {
4950 annotations: Vec::new(),
4951 documentation: None,
4952 trivia: Default::default(),
4953 name: f.name.clone(),
4954 type_ref: f.kind.args[0].clone(),
4955 refinement: None,
4956 init: None,
4957 span: f.span,
4958 })
4959 .collect();
4960 resolved.types.insert(
4961 state_name.clone(),
4962 Arc::new(TypeDecl {
4963 derives: Vec::new(),
4964 derives_kw: None,
4965 type_params: Vec::new(),
4966 name: Ident {
4967 name: state_name.clone(),
4968 span,
4969 },
4970 body: TypeBody::Record(RecordBody {
4971 trailing_comments: Default::default(),
4972 fields: state_fields,
4973 span,
4974 }),
4975 documentation: None,
4976 span,
4977 trivia: Trivia::default(),
4978 private: None,
4979 }),
4980 );
4981
4982 let variants: Vec<Variant> = handlers
4985 .iter()
4986 .map(|h| {
4987 let hname = h.method_name.as_ref().expect("call handler has a name");
4988 Variant {
4989 documentation: None,
4990 trivia: Default::default(),
4991 name: Ident {
4992 name: history_variant_name(&hname.name),
4993 span: hname.span,
4994 },
4995 payload: h
4996 .params
4997 .iter()
4998 .map(|p| VariantField {
4999 documentation: None,
5000 name: p.name.clone(),
5001 type_ref: p.type_ref.clone(),
5002 span: p.span,
5003 })
5004 .collect(),
5005 span: hname.span,
5006 }
5007 })
5008 .collect();
5009 resolved.types.insert(
5010 call_name.clone(),
5011 Arc::new(TypeDecl {
5012 derives: Vec::new(),
5013 derives_kw: None,
5014 type_params: Vec::new(),
5015 name: Ident {
5016 name: call_name.clone(),
5017 span,
5018 },
5019 body: TypeBody::Sum(SumBody {
5020 trailing_comments: Default::default(),
5021 variants,
5022 embeds: Vec::new(),
5023 span,
5024 }),
5025 documentation: None,
5026 span,
5027 trivia: Trivia::default(),
5028 private: None,
5029 }),
5030 );
5031
5032 let step_fields = vec![
5035 RecordField {
5036 annotations: Vec::new(),
5037 documentation: None,
5038 trivia: Default::default(),
5039 name: Ident {
5040 name: "call".to_string(),
5041 span,
5042 },
5043 type_ref: TypeRef::Named(Ident {
5044 name: call_name.clone(),
5045 span,
5046 }),
5047 refinement: None,
5048 init: None,
5049 span,
5050 },
5051 RecordField {
5052 annotations: Vec::new(),
5053 documentation: None,
5054 trivia: Default::default(),
5055 name: Ident {
5056 name: "accepted".to_string(),
5057 span,
5058 },
5059 type_ref: TypeRef::Base(BaseType::Bool, span),
5060 refinement: None,
5061 init: None,
5062 span,
5063 },
5064 RecordField {
5065 annotations: Vec::new(),
5066 documentation: None,
5067 trivia: Default::default(),
5068 name: Ident {
5069 name: "old".to_string(),
5070 span,
5071 },
5072 type_ref: TypeRef::Named(Ident {
5073 name: state_name.clone(),
5074 span,
5075 }),
5076 refinement: None,
5077 init: None,
5078 span,
5079 },
5080 RecordField {
5081 annotations: Vec::new(),
5082 documentation: None,
5083 trivia: Default::default(),
5084 name: Ident {
5085 name: "new".to_string(),
5086 span,
5087 },
5088 type_ref: TypeRef::Named(Ident {
5089 name: state_name.clone(),
5090 span,
5091 }),
5092 refinement: None,
5093 init: None,
5094 span,
5095 },
5096 ];
5097 resolved.types.insert(
5098 step_name.clone(),
5099 Arc::new(TypeDecl {
5100 derives: Vec::new(),
5101 derives_kw: None,
5102 type_params: Vec::new(),
5103 name: Ident {
5104 name: step_name.clone(),
5105 span,
5106 },
5107 body: TypeBody::Record(RecordBody {
5108 trailing_comments: Default::default(),
5109 fields: step_fields,
5110 span,
5111 }),
5112 documentation: None,
5113 span,
5114 trivia: Trivia::default(),
5115 private: None,
5116 }),
5117 );
5118
5119 Ok(checker::Ty::List(tys.intern(checker::Ty::Named {
5120 name: step_name,
5121 kind: checker::NamedKind::Record,
5122 args: Vec::new(),
5123 })))
5124}
5125
5126#[allow(clippy::too_many_arguments)]
5134fn check_property_body(
5135 target_name: &str,
5136 target_kind: UnitKind,
5137 suite_fns: SuiteItems<'_>,
5138 prop: &PropertyDecl,
5139 unit_tables: &HashMap<String, UnitTable>,
5140 unit_uses: &HashMap<String, Vec<String>>,
5141 unit_consumes: &HashMap<String, Vec<String>>,
5142 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5143 errors: &mut Vec<CompileError>,
5144 refs: &mut RefSink,
5145 locals: &mut LocalsSink,
5146 tys: &Arc<Types>,
5147 d1_sql: Option<&crate::d1_sql::D1Sql>,
5148 source: &str,
5149) {
5150 let Some((mut resolved, _)) = build_privileged_resolved(
5151 target_name,
5152 unit_tables,
5153 unit_uses,
5154 unit_consumes,
5155 unit_consumes_aliases,
5156 ) else {
5157 return;
5158 };
5159 register_call_record_types(&mut resolved, target_name, unit_tables);
5160 add_suite_fns(&mut resolved, suite_fns);
5161 let _ = target_kind;
5162
5163 let mut binding_scope: HashMap<String, checker::TyId> = HashMap::new();
5165 let mut binding_types: Vec<(String, Option<checker::TyId>)> = Vec::new();
5166 let mut history_binding: Option<(String, AgentDecl)> = None;
5169 for b in &prop.forall.bindings {
5170 if let TypeRef::History(inner, hspan) = &b.type_ref {
5173 match check_history_binding(inner, *hspan, &mut resolved, refs, tys) {
5174 Ok(step_ty) => {
5175 if let TypeRef::Named(agent_id) = &**inner
5176 && let Some(agent) = resolved.agents.get(&agent_id.name)
5177 {
5178 history_binding = Some((b.name.name.clone(), AgentDecl::clone(agent)));
5179 }
5180 binding_scope.insert(b.name.name.clone(), tys.intern(step_ty.clone()));
5181 binding_types.push((b.name.name.clone(), Some(tys.intern(step_ty))));
5182 }
5183 Err(err) => {
5184 errors.push(err);
5185 binding_types.push((b.name.name.clone(), None));
5186 binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5189 }
5190 }
5191 continue;
5192 }
5193 if let TypeRef::Named(id) = &b.type_ref
5196 && resolved.agents.contains_key(&id.name)
5197 {
5198 errors.push(
5199 CompileError::new(
5200 "bynk.val.agent_not_generable",
5201 b.type_ref.span(),
5202 format!(
5203 "`for all {}: {}` cannot generate an agent — a fabricated agent state need not be reachable",
5204 b.name.name, id.name
5205 ),
5206 )
5207 .with_note(
5208 "generate behaviour over an agent via handler sequences (the history rung), not fabricated states",
5209 ),
5210 );
5211 binding_types.push((b.name.name.clone(), None));
5212 binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5215 continue;
5216 }
5217 let ty = match checker::resolve_type_ref(&b.type_ref, &resolved.types, tys) {
5218 Some(t) => {
5219 record_type_refs_in_property(&b.type_ref, &resolved, refs);
5220 t
5221 }
5222 None => {
5223 errors.push(CompileError::new(
5224 "bynk.val.unknown_type",
5225 b.type_ref.span(),
5226 format!(
5227 "`for all {}: {}` names a type that does not resolve",
5228 b.name.name,
5229 ts_type_ref_display(&b.type_ref)
5230 ),
5231 ));
5232 binding_types.push((b.name.name.clone(), None));
5233 binding_scope.insert(b.name.name.clone(), tys.intern(checker::Ty::Error));
5236 continue;
5237 }
5238 };
5239 if !prop_binding_generable(ty, &resolved.types, PROP_GEN_DEPTH, tys) {
5240 errors.push(
5241 CompileError::new(
5242 "bynk.val.needs_pin",
5243 b.type_ref.span(),
5244 format!(
5245 "`for all {}: {}` cannot generate a value (e.g. a `Matches` refinement); a property cannot bind it",
5246 b.name.name,
5247 ts_type_ref_display(&b.type_ref)
5248 ),
5249 )
5250 .with_note("supply the witness in a `case` with a pinned `Val[T](...)` instead"),
5251 );
5252 }
5253 binding_scope.insert(b.name.name.clone(), ty);
5254 binding_types.push((b.name.name.clone(), Some(ty)));
5255 }
5256
5257 let mut expr_types: HashMap<ExprId, checker::TypedExpr> = HashMap::new();
5260 let mut callees: HashMap<ExprId, checker::Callee> = HashMap::new();
5261 let unit_span = prop.span;
5262 let synthetic_return = TypeRef::Effect(
5263 Box::new(TypeRef::Result(
5264 Box::new(TypeRef::Unit(unit_span)),
5265 Box::new(TypeRef::ValidationError(unit_span)),
5266 unit_span,
5267 )),
5268 unit_span,
5269 );
5270 let mut capability_info_map: HashMap<String, checker::CapabilityInfo> = HashMap::new();
5271 if let Some(table) = unit_tables.get(target_name) {
5272 for (name, decl) in &table.capabilities {
5273 let ops = decl
5274 .ops
5275 .iter()
5276 .map(|op| build_capability_op_info(op, &resolved.types, tys))
5277 .collect();
5278 capability_info_map.insert(
5279 name.clone(),
5280 checker::CapabilityInfo {
5281 name: name.clone(),
5282 ops,
5283 derived_from: crate::context_checks::derived_from(
5284 decl,
5285 &resolved.cross_context.flattened_caps,
5286 ),
5287 },
5288 );
5289 }
5290 }
5291 add_consumed_adapter_capabilities(&mut capability_info_map, unit_tables, &resolved, tys);
5292 add_consumed_service_seams(&mut capability_info_map, &resolved, unit_tables, tys);
5293 let given_declared: Vec<String> = capability_info_map.keys().cloned().collect();
5294 let return_ty = checker::resolve_type_ref(&synthetic_return, &resolved.types, tys).unwrap();
5295 let return_ty_span = prop.span;
5296 let mut no_hints = HintSink::new();
5297 let mut no_requirements = RequirementSink::new();
5298 let _ = checker::check_body(
5302 &resolved,
5303 &prop.forall.body,
5304 return_ty,
5305 return_ty_span,
5306 binding_scope,
5307 checker::CapabilityCtx {
5308 capabilities: capability_info_map.clone(),
5309 declared_capabilities: capability_info_map,
5310 given_remaining: given_declared.iter().cloned().collect(),
5311 given_used: HashSet::new(),
5312 given_entries: Vec::new(),
5313 given_anchor: None,
5314 ..Default::default()
5315 },
5316 target_test_services(
5317 Some(target_name),
5318 unit_tables,
5319 &resolved.cross_context.consumed_contexts,
5320 ),
5321 target_test_actors(unit_tables.get(target_name)),
5322 prop.forall.where_pred.as_ref(),
5323 checker::CheckSinks {
5324 tys,
5325 expr_types: &mut expr_types,
5326 errors,
5327 refs,
5328 hints: &mut no_hints,
5329 locals,
5330 requirements: &mut no_requirements,
5331 callees: &mut callees,
5332 },
5333 );
5334
5335 check_d1_sql_sites(d1_sql, target_name, unit_tables, &callees, source, errors);
5336
5337 if let [(var, Some(ty))] = binding_types.as_slice()
5340 && let Some(refinement) = named_refinement(*ty, &resolved.types, tys)
5341 && let [stmt] = prop.forall.body.statements.as_slice()
5342 && let Statement::Expect(e) = stmt
5343 && predicate_restates_refinement(&e.value, var, refinement)
5344 {
5345 errors.push(
5346 CompileError::new(
5347 "bynk.property.restates_refinement",
5348 prop.forall.body.span,
5349 format!(
5350 "property `{}` merely re-checks a refinement type `{}` already guarantees",
5351 prop.name,
5352 ty.display(tys)
5353 ),
5354 )
5355 .with_note(
5356 "a property earns its keep by asserting behaviour over valid inputs, not by restating the type's refinement",
5357 ),
5358 );
5359 }
5360
5361 if let Some((run_var, agent)) = &history_binding
5366 && history_restates_invariant(prop, run_var, agent)
5367 {
5368 errors.push(
5369 CompileError::new(
5370 "bynk.history.restates_invariant",
5371 prop.forall.body.span,
5372 format!(
5373 "history property `{}` merely re-checks a guarantee agent `{}`'s `invariant`/`transition` already enforces on every reached state",
5374 prop.name, agent.name.name
5375 ),
5376 )
5377 .with_note(
5378 "a history property earns its keep by asserting a cross-step protocol, not by restating a per-state invariant",
5379 ),
5380 );
5381 }
5382}
5383
5384fn record_type_refs_in_property(
5387 type_ref: &TypeRef,
5388 resolved: &ResolvedCommons,
5389 refs: &mut RefSink,
5390) {
5391 checker::record_type_refs(type_ref, &resolved.types, &HashSet::new(), refs);
5392}
5393
5394#[derive(Clone, Default)]
5400pub struct SuiteView {
5401 pub types: HashMap<String, Arc<TypeDecl>>,
5402 pub fns: HashMap<String, Arc<FnDecl>>,
5403 pub methods: HashMap<String, ResolverMethodTable>,
5404 pub hidden: BTreeMap<String, String>,
5405 pub conflicts: Vec<crate::project_model::ViewConflict>,
5408 pub assets: HashMap<String, bynk_syntax::ast::AssetDecl>,
5414 pub embeds: HashMap<String, bynk_syntax::ast::EmbedDecl>,
5419 pub consts: HashMap<String, bynk_syntax::ast::ConstDecl>,
5423}
5424
5425impl SuiteView {
5426 fn merge_consts(
5429 &mut self,
5430 unit: &str,
5431 unit_tables: &HashMap<String, UnitTable>,
5432 unit_uses: &HashMap<String, Vec<String>>,
5433 ) {
5434 let own = unit_tables.get(unit).into_iter().map(|t| (unit, t, true));
5437 let used = unit_uses
5438 .get(unit)
5439 .into_iter()
5440 .flatten()
5441 .filter_map(|u| unit_tables.get(u).map(|t| (u.as_str(), t, false)));
5442 for (owner, table, is_own) in own.chain(used) {
5443 for (name, decl) in table
5444 .consts
5445 .iter()
5446 .filter(|(_, d)| is_own || d.private.is_none())
5447 {
5448 self.consts.entry(name.clone()).or_insert_with(|| {
5449 let mut decl = decl.clone();
5450 if !is_own
5453 && matches!(decl.init.kind, ExprKind::Ident(_))
5454 && let Some(text) = crate::consts::alias_literal(
5455 |u| {
5456 unit_tables
5457 .get(u)
5458 .map(|t| (t, unit_uses.get(u).map_or(&[][..], Vec::as_slice)))
5459 },
5460 owner,
5461 &decl,
5462 )
5463 {
5464 decl.init.kind = ExprKind::StrLit(text);
5465 }
5466 decl
5467 });
5468 }
5469 }
5470 }
5471
5472 fn merge_embeds(
5475 &mut self,
5476 unit: &str,
5477 unit_tables: &HashMap<String, UnitTable>,
5478 unit_uses: &HashMap<String, Vec<String>>,
5479 ) {
5480 let own = unit_tables.get(unit).into_iter().map(|t| (t, true));
5483 let used = unit_uses
5484 .get(unit)
5485 .into_iter()
5486 .flatten()
5487 .filter_map(|u| unit_tables.get(u))
5488 .map(|t| (t, false));
5489 for (table, is_own) in own.chain(used) {
5490 for (name, decl) in table
5491 .embeds
5492 .iter()
5493 .filter(|(_, d)| is_own || d.private.is_none())
5494 {
5495 self.embeds
5496 .entry(name.clone())
5497 .or_insert_with(|| decl.clone());
5498 }
5499 }
5500 }
5501
5502 fn merge_assets(
5505 &mut self,
5506 unit: &str,
5507 unit_tables: &HashMap<String, UnitTable>,
5508 unit_uses: &HashMap<String, Vec<String>>,
5509 ) {
5510 self.merge_assets_where(unit, unit_tables, unit_uses, |_| true);
5511 }
5512
5513 fn merge_assets_where(
5515 &mut self,
5516 unit: &str,
5517 unit_tables: &HashMap<String, UnitTable>,
5518 unit_uses: &HashMap<String, Vec<String>>,
5519 keep: impl Fn(&bynk_syntax::ast::AssetDecl) -> bool,
5520 ) {
5521 let own = unit_tables.get(unit).into_iter().map(|t| (t, true));
5524 let used = unit_uses
5525 .get(unit)
5526 .into_iter()
5527 .flatten()
5528 .filter_map(|u| unit_tables.get(u))
5529 .map(|t| (t, false));
5530 for (table, is_own) in own.chain(used) {
5531 for (name, decl) in table
5532 .assets
5533 .iter()
5534 .filter(|(_, d)| keep(d) && (is_own || d.private.is_none()))
5535 {
5536 self.assets
5537 .entry(name.clone())
5538 .or_insert_with(|| decl.clone());
5539 }
5540 }
5541 }
5542
5543 pub fn reach(&self) -> crate::project_model::ViewReach {
5545 crate::project_model::ViewReach {
5546 hidden: self.hidden.clone(),
5547 conflicts: self.conflicts.clone(),
5548 }
5549 }
5550
5551 fn merge(&mut self, t: &UnitTable, with_fns: bool, with_statics: bool) {
5555 for (n, d) in &t.types {
5556 self.types.entry(n.clone()).or_insert_with(|| d.clone());
5557 }
5558 if with_fns {
5559 for (n, f) in &t.fns {
5560 self.fns.entry(n.clone()).or_insert_with(|| f.clone());
5561 }
5562 }
5563 for (n, mt) in &t.methods {
5564 let entry = self.methods.entry(n.clone()).or_default();
5565 for (m, decl) in &mt.instance {
5566 entry
5567 .instance
5568 .entry(m.clone())
5569 .or_insert_with(|| decl.clone());
5570 }
5571 if with_statics {
5572 for (m, decl) in &mt.statics {
5573 entry
5574 .statics
5575 .entry(m.clone())
5576 .or_insert_with(|| decl.clone());
5577 }
5578 }
5579 }
5580 }
5581
5582 fn reach_first_party_types(
5598 &mut self,
5599 participants: &[String],
5600 unit_tables: &HashMap<String, UnitTable>,
5601 ) {
5602 let no_vars = HashSet::new();
5603 let mut queue: Vec<String> = self
5604 .types
5605 .values()
5606 .flat_map(|d| crate::project_model::type_decl_ref_names(d))
5607 .collect();
5608 for f in self.fns.values() {
5609 for p in &f.params {
5610 crate::project_model::type_ref_names(&p.type_ref, &no_vars, &mut queue);
5611 }
5612 crate::project_model::type_ref_names(&f.return_type, &no_vars, &mut queue);
5613 }
5614 for table in participants.iter().filter_map(|p| unit_tables.get(p)) {
5615 for h in table.services.values().flat_map(|s| &s.handlers) {
5616 for p in &h.params {
5617 crate::project_model::type_ref_names(&p.type_ref, &no_vars, &mut queue);
5618 }
5619 crate::project_model::type_ref_names(&h.return_type, &no_vars, &mut queue);
5620 }
5621 }
5622 let first_party = [
5626 crate::firstparty::BYNK_UNIT,
5627 crate::firstparty::CLOUDFLARE_UNIT,
5628 ];
5629 while let Some(name) = queue.pop() {
5630 if self.types.contains_key(&name) {
5631 continue;
5632 }
5633 let found = first_party
5634 .into_iter()
5635 .find_map(|u| unit_tables.get(u).and_then(|t| t.types.get(&name)));
5636 if let Some(decl) = found {
5637 queue.extend(crate::project_model::type_decl_ref_names(decl));
5638 self.types.insert(name, decl.clone());
5639 }
5640 }
5641 }
5642
5643 fn close(
5646 &mut self,
5647 imported: &[String],
5648 unit_tables: &HashMap<String, UnitTable>,
5649 unit_uses: &HashMap<String, Vec<String>>,
5650 actor_identities: bool,
5651 ) {
5652 let reach = crate::project_model::close_view_types(
5653 imported,
5654 unit_tables,
5655 unit_uses,
5656 &mut self.types,
5657 &self.fns,
5658 &mut self.methods,
5659 actor_identities,
5660 );
5661 self.hidden = reach.hidden;
5662 self.conflicts = reach.conflicts;
5663 }
5664}
5665
5666pub fn privileged_view(
5672 owning_unit: &str,
5673 unit_tables: &HashMap<String, UnitTable>,
5674 unit_uses: &HashMap<String, Vec<String>>,
5675 unit_consumes: &HashMap<String, Vec<String>>,
5676) -> Option<SuiteView> {
5677 let local = unit_tables.get(owning_unit)?;
5678 let mut view = SuiteView {
5679 types: local.types.clone(),
5680 fns: local.fns.clone(),
5681 methods: local.methods.clone(),
5682 ..SuiteView::default()
5683 };
5684 let mut imported: Vec<String> = Vec::new();
5685 for t in unit_uses.get(owning_unit).into_iter().flatten() {
5686 if let Some(used) = unit_tables.get(t) {
5687 view.merge(&used.importable(), true, true);
5690 imported.push(t.clone());
5691 }
5692 }
5693 for t in unit_consumes.get(owning_unit).into_iter().flatten() {
5698 if let Some(used) = unit_tables.get(t) {
5699 view.merge(used, false, false);
5700 imported.push(t.clone());
5701 }
5702 }
5703 view.merge_assets(owning_unit, unit_tables, unit_uses);
5704 view.merge_embeds(owning_unit, unit_tables, unit_uses);
5705 view.merge_consts(owning_unit, unit_tables, unit_uses);
5706 for consumed in unit_consumes.get(owning_unit).into_iter().flatten() {
5711 view.merge_assets_where(consumed, unit_tables, unit_uses, |d| d.at.is_none());
5712 }
5713 let hidden_by_local = |n: &String| crate::symbols::local_value_kind(local, n).is_some();
5717 view.fns
5718 .retain(|n, _| local.fns.contains_key(n) || !hidden_by_local(n));
5719 view.assets
5720 .retain(|n, _| local.assets.contains_key(n) || !hidden_by_local(n));
5721 view.embeds
5722 .retain(|n, _| local.embeds.contains_key(n) || !hidden_by_local(n));
5723 view.consts
5724 .retain(|n, _| local.consts.contains_key(n) || !hidden_by_local(n));
5725 view.close(&imported, unit_tables, unit_uses, false);
5726 Some(view)
5727}
5728
5729pub fn integration_view(
5734 uses_targets: &[String],
5735 participants: &[String],
5736 unit_tables: &HashMap<String, UnitTable>,
5737 unit_uses: &HashMap<String, Vec<String>>,
5738) -> SuiteView {
5739 let mut view = SuiteView::default();
5740 let mut imported: Vec<String> = Vec::new();
5741 for (units, with_fns) in [(uses_targets, true), (participants, false)] {
5742 for u in units {
5743 if let Some(t) = unit_tables.get(u) {
5744 if with_fns {
5747 view.merge(&t.importable(), with_fns, true);
5748 } else {
5749 view.merge(t, with_fns, true);
5750 }
5751 imported.push(u.clone());
5752 }
5753 }
5754 }
5755 if let Some((target, others)) = participants.split_first() {
5763 view.merge_assets(target, unit_tables, unit_uses);
5764 for other in others {
5765 view.merge_assets_where(other, unit_tables, unit_uses, |d| d.at.is_none());
5766 }
5767 if let Some(local) = unit_tables.get(target) {
5771 view.assets.retain(|n, _| {
5772 local.assets.contains_key(n) || crate::symbols::local_value_kind(local, n).is_none()
5773 });
5774 }
5775 }
5776 let has_email = participants.iter().any(|p| {
5782 unit_tables.get(p).is_some_and(|t| {
5783 t.services
5784 .values()
5785 .any(|s| matches!(s.protocol, bynk_syntax::ast::ServiceProtocol::Email { .. }))
5786 })
5787 });
5788 if has_email && let Some(cloudflare) = unit_tables.get(crate::firstparty::CLOUDFLARE_UNIT) {
5789 for name in [
5790 "InboundEmail",
5791 "InboundAttachment",
5792 "EmailVerdict",
5793 "EmailReply",
5794 "DmarcVerdict",
5795 "SenderIdentity",
5796 ] {
5797 if let Some(decl) = cloudflare.types.get(name) {
5798 view.types
5799 .entry(name.to_string())
5800 .or_insert_with(|| decl.clone());
5801 }
5802 }
5803 }
5804 let has_d1 = participants.iter().any(|p| {
5807 unit_tables.get(p).is_some_and(|t| {
5808 t.derived
5809 .values()
5810 .any(|d| d.base_unit == crate::firstparty::CLOUDFLARE_UNIT && d.base_cap == "D1")
5811 })
5812 });
5813 if has_d1 && let Some(cloudflare) = unit_tables.get(crate::firstparty::CLOUDFLARE_UNIT) {
5814 for name in [
5815 "SqlValue",
5816 "SqlError",
5817 "SqlReadError",
5818 "SqlRun",
5819 "SqlStatement",
5820 ] {
5821 if let Some(decl) = cloudflare.types.get(name) {
5822 view.types
5823 .entry(name.to_string())
5824 .or_insert_with(|| decl.clone());
5825 }
5826 }
5827 }
5828 view.close(&imported, unit_tables, unit_uses, true);
5830 view.reach_first_party_types(participants, unit_tables);
5831 view
5832}
5833
5834pub fn build_privileged_resolved(
5839 owning_unit: &str,
5840 unit_tables: &HashMap<String, UnitTable>,
5841 unit_uses: &HashMap<String, Vec<String>>,
5842 unit_consumes: &HashMap<String, Vec<String>>,
5843 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5844) -> Option<(ResolvedCommons, crate::project_model::ViewReach)> {
5845 let local = unit_tables.get(owning_unit)?;
5846 let view = privileged_view(owning_unit, unit_tables, unit_uses, unit_consumes)?;
5847 let reach = view.reach();
5848 let assets = view.assets.clone();
5849 let embeds = view.embeds.clone();
5850 let consts = view.consts.clone();
5851 let SuiteView {
5852 types,
5853 fns,
5854 methods,
5855 ..
5856 } = view;
5857 let cross_context = build_cross_context_info(
5858 owning_unit,
5859 unit_consumes,
5860 unit_consumes_aliases,
5861 unit_uses,
5862 unit_tables,
5863 );
5864 let synthetic_commons = Commons {
5865 name: QualifiedName {
5866 parts: owning_unit
5867 .split('.')
5868 .map(|part| Ident {
5869 name: part.to_string(),
5870 span: Span::default(),
5871 })
5872 .collect(),
5873 span: Span::default(),
5874 },
5875 items: Vec::new(),
5876 uses: Vec::new(),
5877 documentation: None,
5878 form: CommonsForm::Brace,
5879 span: Span::default(),
5880 trivia: Trivia::default(),
5881 trailing_comments: Vec::new(),
5882 };
5883 let agents_for_resolved = unit_tables
5884 .get(owning_unit)
5885 .map(|t| t.agents.clone())
5886 .unwrap_or_default();
5887 let no_local_events = HashMap::new();
5888 let resolved = ResolvedCommons::new(
5889 Arc::new(synthetic_commons),
5890 types,
5891 &local.types,
5892 fns,
5893 methods,
5894 agents_for_resolved,
5895 &no_local_events,
5899 cross_context,
5900 HashMap::new(),
5901 false,
5902 HashSet::new(),
5903 )
5904 .with_assets(assets)
5906 .with_embeds(embeds)
5907 .with_consts(consts)
5908 .with_unselected_types(local.unselected_consumed_types.iter().cloned().collect())
5910 .with_shadowed_imports(crate::project_model::shadowed_imports_in(
5913 local,
5914 unit_uses
5915 .get(owning_unit)
5916 .into_iter()
5917 .flatten()
5918 .filter_map(|t| unit_tables.get(t).map(|u| (t, u))),
5919 ));
5920 Some((resolved, reach))
5921}
5922
5923fn suite_import_owners(
5927 suite: &SuiteDecl,
5928 target: &str,
5929 unit_tables: &HashMap<String, UnitTable>,
5930 unit_uses: &HashMap<String, Vec<String>>,
5931 unit_consumes: &HashMap<String, Vec<String>>,
5932) -> std::collections::BTreeMap<String, String> {
5933 let own = |n: &String| {
5934 unit_tables
5935 .get(target)
5936 .is_some_and(|t| t.types.contains_key(n))
5937 || unit_uses
5938 .get(target)
5939 .into_iter()
5940 .flatten()
5941 .any(|u| unit_tables.get(u).is_some_and(|t| t.types.contains_key(n)))
5942 || suite.types.iter().any(|t| t.name.name == *n)
5943 };
5944 let mut owners = std::collections::BTreeMap::new();
5945 for unit in unit_consumes.get(target).into_iter().flatten() {
5946 let Some(table) = unit_tables.get(unit) else {
5947 continue;
5948 };
5949 for name in table.types.keys().filter(|n| !own(n)) {
5953 owners.entry(name.clone()).or_insert_with(|| unit.clone());
5954 }
5955 }
5956 owners
5957}
5958
5959type ProjectMaps<'a> = (
5961 &'a HashMap<String, UnitTable>,
5962 &'a HashMap<String, Vec<String>>,
5963 &'a HashMap<String, Vec<String>>,
5964 &'a HashMap<String, HashMap<String, String>>,
5965);
5966
5967type TargetShadowed = (
5970 HashMap<String, crate::resolver::ShadowedImport>,
5971 HashMap<String, Arc<TypeDecl>>,
5972);
5973
5974fn suite_naming_errors(
5979 suite: &SuiteDecl,
5980 pf: &ParsedFile,
5981 target: &str,
5982 maps: ProjectMaps<'_>,
5983 (hidden, shadowed): (&std::collections::BTreeMap<String, String>, &TargetShadowed),
5984) -> Vec<CompileError> {
5985 let mut errors = resolver::check_hidden_type_names_in_suite(suite, Some(target), hidden);
5986 errors.extend(resolver::check_shadowed_type_names_in_suite(
5987 suite,
5988 &shadowed.0,
5989 &shadowed.1,
5990 ));
5991 errors.extend(check_unselected_suite_imports(
5992 suite,
5993 pf,
5994 target,
5995 maps,
5996 &shadowed.1,
5997 ));
5998 errors
5999}
6000
6001fn check_unselected_suite_imports(
6005 suite: &SuiteDecl,
6006 pf: &ParsedFile,
6007 target: &str,
6008 maps: ProjectMaps<'_>,
6009 types: &HashMap<String, Arc<TypeDecl>>,
6010) -> Vec<CompileError> {
6011 let (unit_tables, unit_uses, unit_consumes, unit_consumes_aliases) = maps;
6012 let owners = suite_import_owners(suite, target, unit_tables, unit_uses, unit_consumes);
6013 let consumed = unit_consumes.get(target).map_or(&[][..], Vec::as_slice);
6014 let none = HashMap::new();
6015 let caps = unit_tables.get(target).map_or(&none, |t| &t.flattened_caps);
6016 let aliases = unit_consumes_aliases.get(target).unwrap_or(&none);
6017 check_unselected_suite_types(suite, pf, &owners, types, consumed, caps, aliases)
6018}
6019
6020fn check_unselected_suite_types(
6023 suite: &SuiteDecl,
6024 pf: &ParsedFile,
6025 owners: &std::collections::BTreeMap<String, String>,
6026 types: &HashMap<String, Arc<TypeDecl>>,
6027 consumed: &[String],
6028 caps: &HashMap<String, String>,
6029 aliases: &HashMap<String, String>,
6030) -> Vec<CompileError> {
6031 let consumed: std::collections::BTreeSet<String> = consumed.iter().cloned().collect();
6032 let file = resolver::FileConsumes {
6033 consumed: &consumed,
6034 aliases: &HashMap::new(),
6038 clauses: &suite.consumes,
6039 insert_at: new_suite_consumes_position(suite, pf.source()),
6040 };
6041 let mut found = resolver::check_unselected_type_names_in_suite(suite, owners, types, &file);
6042 let caps = caps.iter().map(|(n, o)| (n.clone(), o.clone())).collect();
6043 found.extend(resolver::check_unselected_capabilities_in_suite(
6044 suite, &caps, &file,
6045 ));
6046 let prefixes = consumed
6047 .iter()
6048 .map(|u| (u.clone(), u.clone()))
6049 .chain(aliases.iter().map(|(a, u)| (a.clone(), u.clone())))
6050 .collect();
6051 found.extend(resolver::check_unconsumed_unit_calls_in_suite(
6052 suite, &prefixes, &file,
6053 ));
6054 found
6055}
6056
6057fn new_suite_consumes_position(suite: &SuiteDecl, source: &str) -> Option<(usize, String)> {
6061 let last = suite
6062 .uses
6063 .iter()
6064 .map(|u| u.span.end)
6065 .chain(suite.consumes.iter().map(|c| c.span.end))
6066 .max();
6067 let mut end = suite.target.span.end;
6068 let rest = source.get(end..)?;
6069 let after_blank = rest.trim_start_matches([' ', '\t']);
6070 if let Some(tier) = after_blank
6071 .strip_prefix("as")
6072 .filter(|t| t.starts_with([' ', '\t']))
6073 {
6074 let word = tier.trim_start_matches([' ', '\t']);
6075 let len = word
6076 .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
6077 .unwrap_or(word.len());
6078 end = source.len() - word.len() + len;
6079 }
6080 let braced = suite.form == CommonsForm::Brace;
6081 resolver::new_consumes_position(source, last, end, braced)
6082}
6083
6084#[cfg(test)]
6085mod tests {
6086 use super::*;
6087
6088 fn handler_body(src: &str) -> Block {
6090 let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
6091 let unit = bynk_syntax::parser::parse_unit(&tokens, src).expect("parse");
6092 let SourceUnit::Context(ctx) = unit else {
6093 panic!("expected a context unit");
6094 };
6095 ctx.items
6096 .into_iter()
6097 .find_map(|item| match item {
6098 bynk_syntax::ast::CommonsItem::Service(s) => s.handlers.into_iter().next(),
6099 _ => None,
6100 })
6101 .expect("a service handler")
6102 .body
6103 }
6104
6105 const SRC: &str = "context demo\n\
6106 service svc {\n\
6107 on call(n: Int) -> Effect[Int] by Caller {\n\
6108 let a <- first(n)\n\
6109 let b = if n > 0 { let c = second(n)\n c } else { third(n) }\n\
6110 fourth(a + b)\n\
6111 }\n\
6112 }\n";
6113
6114 #[test]
6118 fn exprs_in_order_is_source_order() {
6119 let body = handler_body(SRC);
6120 let calls: Vec<&str> = exprs_in_order(&body)
6121 .into_iter()
6122 .filter_map(|e| match &e.kind {
6123 ExprKind::Call { name, .. } => Some(name.name.as_str()),
6124 _ => None,
6125 })
6126 .collect();
6127 assert_eq!(calls, ["first", "second", "third", "fourth"]);
6128 }
6129
6130 #[test]
6133 fn blocks_deep_reaches_nested_lets() {
6134 let body = handler_body(SRC);
6135 let lets: Vec<String> = blocks_deep(&body)
6136 .iter()
6137 .flat_map(|b| &b.statements)
6138 .filter_map(|s| match s {
6139 Statement::Let(l) | Statement::EffectLet(l) => Some(l.name.name.clone()),
6140 _ => None,
6141 })
6142 .collect();
6143 assert!(lets.contains(&"c".to_string()), "{lets:?}");
6144 assert!(lets.contains(&"a".to_string()) && lets.contains(&"b".to_string()));
6145 }
6146
6147 const CART_API: &str = "context shop.api
6149
6150type UserId = String where NonEmpty
6151actor User { auth = Bearer(secret = \"AUTH_SECRET\"), identity = UserId }
6152
6153type Item = { sku: String }
6154
6155service api from http {
6156 on POST(\"/cart\") (body: Item) -> Effect[HttpResult[Item]] by u: User {
6157 Created(body)
6158 }
6159}
6160";
6161
6162 fn nobody_case(body: &str) -> crate::testkit::Analysed {
6163 crate::testkit::analyse(&[
6164 ("shop/api.bynk", CART_API),
6165 (
6166 "shop/tests/api.test.bynk",
6167 &format!(
6168 "suite shop.api as system {{\n case \"c\" as unit {{\n{body}\n }}\n}}\n"
6169 ),
6170 ),
6171 ])
6172 }
6173
6174 #[test]
6175 fn a_unit_case_calling_by_nobody_needs_system() {
6176 nobody_case(
6177 " let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n expect r is Rejected(Unauthorized)",
6178 )
6179 .assert_reports("bynk.test.credential_needs_system");
6180 }
6181
6182 const HOOKS: &str = "context pay.hooks
6184
6185actor Processor { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\", tolerance = 300) }
6186
6187service webhooks from http {
6188 on POST(\"/hook\") (body: String) -> Effect[HttpResult[String]] by Processor {
6189 Ok(body)
6190 }
6191}
6192
6193service jobs {
6194 on call(n: Int) -> Effect[Int] by Caller { Effect.pure(n) }
6195}
6196";
6197
6198 fn hooks_case(tier: &str, body: &str) -> crate::testkit::Analysed {
6199 crate::testkit::analyse(&[
6200 ("pay/hooks.bynk", HOOKS),
6201 (
6202 "pay/tests/hooks.test.bynk",
6203 &format!("suite pay.hooks{tier} {{\n case \"c\" {{\n{body}\n }}\n}}\n"),
6204 ),
6205 ])
6206 }
6207
6208 const SUMS: &str = "context pay.sums
6211
6212type UserId = String where NonEmpty
6213
6214actor User { auth = Bearer(secret = \"AUTH\"), identity = UserId }
6215
6216actor Untimed { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\") }
6217
6218actor Timed { auth = Signature(secret = \"HOOK\", header = \"X-Sig\", timestamp = \"X-Ts\", tolerance = 300) }
6219
6220service api from http {
6221 on POST(\"/untimed\") (body: String) -> Effect[HttpResult[String]] by Untimed {
6222 Ok(body)
6223 }
6224
6225 on POST(\"/mixed\") (body: String) -> Effect[HttpResult[String]] by who: User | Timed {
6226 match who {
6227 User(u) => Ok(u)
6228 Timed => Ok(body)
6229 }
6230 }
6231
6232 on POST(\"/open\") (body: String) -> Effect[HttpResult[String]] by who: Timed | Visitor {
6233 match who {
6234 Timed => Ok(body)
6235 Visitor => Ok(\"stranger\")
6236 }
6237 }
6238
6239 on GET(\"/greet\") () -> Effect[HttpResult[String]] by who: User | Visitor {
6240 match who {
6241 User(u) => Ok(u)
6242 Visitor => Ok(\"stranger\")
6243 }
6244 }
6245}
6246";
6247
6248 fn sums_case(body: &str) -> crate::testkit::Analysed {
6249 crate::testkit::analyse(&[
6250 ("pay/sums.bynk", SUMS),
6251 (
6252 "pay/tests/sums.test.bynk",
6253 &format!("suite pay.sums as system {{\n case \"c\" {{\n{body}\n }}\n}}\n"),
6254 ),
6255 ])
6256 }
6257
6258 #[test]
6259 fn a_stale_call_needs_a_tolerance_not_just_a_timestamp() {
6260 sums_case(
6261 " let r <- api.POST(\"/untimed\", \"x\") by Stale\n expect r is Rejected(Unauthorized)",
6262 )
6263 .assert_reports("bynk.test.stale_needs_timestamp");
6264 }
6265
6266 #[test]
6267 fn forged_stale_and_nobody_are_admitted_on_a_sum_with_a_signature_member() {
6268 sums_case(
6269 " let a <- api.POST(\"/mixed\", \"x\") by Forged\n let b <- api.POST(\"/mixed\", \"x\") by Stale\n let c <- api.POST(\"/mixed\", \"x\") by Nobody\n expect a is Rejected(Unauthorized)\n expect b is Rejected(Unauthorized)\n expect c is Rejected(Unauthorized)",
6270 )
6271 .assert_clean();
6272 }
6273
6274 #[test]
6277 fn forged_and_stale_are_refused_on_a_sum_with_visitor() {
6278 for who in ["Forged", "Stale"] {
6279 sums_case(&format!(
6280 " let r <- api.POST(\"/open\", \"x\") by {who}\n expect r is Rejected(Unauthorized)"
6281 ))
6282 .assert_reports("bynk.test.forged_needs_signature_route");
6283 }
6284 }
6285
6286 #[test]
6287 fn nobody_is_refused_on_a_sum_with_visitor() {
6288 sums_case(
6289 " let r <- api.GET(\"/greet\") by Nobody\n expect r is Rejected(Unauthorized)",
6290 )
6291 .assert_reports("bynk.test.nobody_needs_secured_route");
6292 sums_case(
6293 " let r <- api.POST(\"/open\", \"x\") by Nobody\n expect r is Rejected(Unauthorized)",
6294 )
6295 .assert_reports("bynk.test.nobody_needs_secured_route");
6296 }
6297
6298 #[test]
6299 fn a_forged_call_needs_a_signature_member_on_a_sum() {
6300 sums_case(
6301 " let r <- api.GET(\"/greet\") by Forged\n expect r is Rejected(Unauthorized)",
6302 )
6303 .assert_reports("bynk.test.forged_needs_signature_route");
6304 }
6305
6306 #[test]
6307 fn an_expired_call_is_refused_off_a_bearer_route() {
6308 sums_case(
6309 " let r <- api.POST(\"/mixed\", \"x\") by Expired\n expect r is Rejected(Unauthorized)",
6310 )
6311 .assert_clean();
6312 for route in ["/untimed", "/open"] {
6313 sums_case(&format!(
6314 " let r <- api.POST(\"{route}\", \"x\") by Expired\n expect r is Rejected(Unauthorized)"
6315 ))
6316 .assert_reports("bynk.test.expired_needs_bearer_route");
6317 }
6318 hooks_case(" as system", " let r <- webhooks.POST(\"/hook\", \"x\") by Expired\n expect r is Rejected(Unauthorized)")
6319 .assert_reports("bynk.test.expired_needs_bearer_route");
6320 hooks_case(
6321 " as system",
6322 " let r <- jobs.call(1) by Expired\n expect r == 1",
6323 )
6324 .assert_reports("bynk.test.expired_needs_bearer_route");
6325 }
6326
6327 #[test]
6328 fn an_expired_call_at_unit_needs_system() {
6329 hooks_case(
6330 "",
6331 " let r <- webhooks.POST(\"/hook\", \"x\") by Expired\n expect r is Rejected(Unauthorized)",
6332 )
6333 .assert_reports("bynk.test.forged_needs_system");
6334 }
6335
6336 #[test]
6337 fn a_forged_fault_claim_below_system_is_refused() {
6338 hooks_case(
6339 "",
6340 " expect webhooks.POST(\"/hook\", \"x\") by Forged faults",
6341 )
6342 .assert_reports("bynk.test.faults_needs_in_process");
6343 }
6344
6345 #[test]
6346 fn a_stale_call_at_unit_needs_system() {
6347 hooks_case(
6348 "",
6349 " let r <- webhooks.POST(\"/hook\", \"x\") by Stale\n expect r is Rejected(Unauthorized)",
6350 )
6351 .assert_reports("bynk.test.forged_needs_system");
6352 }
6353
6354 #[test]
6355 fn a_forged_call_service_needs_a_signature_route() {
6356 hooks_case("", " let r <- jobs.call(1) by Forged\n expect r == 1")
6357 .assert_reports("bynk.test.forged_needs_signature_route");
6358 }
6359
6360 #[test]
6361 fn a_by_nobody_nested_in_a_block_needs_system_too() {
6362 nobody_case(
6364 " let ok = if true {\n let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n r is Rejected(Unauthorized)\n } else { false }\n expect ok",
6365 )
6366 .assert_reports("bynk.test.credential_needs_system");
6367 }
6368}
6369
6370#[cfg(test)]
6374mod typed_outcome_tests {
6375 const API: &str = "context app.web
6376
6377type Item = { sku: String }
6378
6379service api from http {
6380 on GET(\"/x\") () -> Effect[HttpResult[()]] by Visitor {
6381 Raw(Bytes.fromUtf8(\"hi\"), \"text/plain\")
6382 }
6383 on GET(\"/name\") () -> Effect[HttpResult[String]] by Visitor {
6384 Ok(\"ada\")
6385 }
6386 on GET(\"/item\") () -> Effect[HttpResult[Item]] by Visitor {
6387 Ok(Item { sku: \"w\" })
6388 }
6389}
6390
6391service calc {
6392 on call(n: Int) -> Effect[Int] by Caller {
6393 n
6394 }
6395}
6396
6397service sweeper from cron {
6398 on schedule(\"0 0 * * *\") () -> Effect[Result[(), String]] {
6399 Ok(())
6400 }
6401}
6402
6403service intake from queue(\"orders\") {
6404 on message(item: Item) -> Effect[QueueResult] {
6405 Ack
6406 }
6407}
6408";
6409
6410 fn case(body: &str) -> crate::testkit::Analysed {
6411 crate::testkit::analyse(&[
6412 ("app/web.bynk", API),
6413 (
6414 "app/tests/web.test.bynk",
6415 &format!("suite app.web {{\n case \"c\" {{\n{body}\n }}\n}}\n"),
6416 ),
6417 ])
6418 }
6419
6420 #[test]
6423 fn an_http_outcome_has_the_handlers_result_type() {
6424 let get = " let r <- api.GET(\"/name\") by Visitor\n";
6425 case(&format!("{get} match r {{\n Ok(v) => expect v.length() == 3\n _ => expect false\n }}"))
6426 .assert_clean();
6427 case(&format!("{get} match r {{\n Ok(v) => expect v.nosuch() == 3\n _ => expect false\n }}"))
6428 .assert_reports("bynk.types.method_not_found");
6429 case(&format!(
6430 "{get} expect r is Ok(v) && v.startsWith(\"a\")"
6431 ))
6432 .assert_clean();
6433 case(&format!("{get} expect r == Ok(\"ada\")")).assert_clean();
6434 let item = " let r <- api.GET(\"/item\") by Visitor\n";
6435 case(&format!(
6436 "{item} expect r is Ok(i) && i.sku.length() == 1"
6437 ))
6438 .assert_clean();
6439 case(&format!("{item} expect r is Ok(i) && i.nosuch == 1"))
6440 .assert_reports("bynk.types.unknown_field");
6441 }
6442
6443 #[test]
6446 fn fixed_payloads_and_arms_are_checked() {
6447 let get = " let r <- api.GET(\"/x\") by Visitor\n";
6448 case(&format!("{get} match r {{\n Raw(body, ct) => expect body.length() == 2 && ct.startsWith(\"text/\")\n _ => expect false\n }}"))
6449 .assert_clean();
6450 case(&format!("{get} match r {{\n Raw(_, _) => expect nope == 1\n _ => expect false\n }}"))
6451 .assert_reports("bynk.resolve.unknown_name");
6452 case(&format!("{get} match r {{\n BadRequest(m) | NotFound => expect m.length() == 9\n _ => expect false\n }}"))
6453 .assert_reports("bynk.types.or_pattern_binding_mismatch");
6454 case(&format!("{get} expect r is Bogus(_)"))
6455 .assert_reports("bynk.types.is_unknown_variant");
6456 }
6457
6458 #[test]
6460 fn a_call_outcome_has_the_handlers_return_type() {
6461 case(" let n <- calc.call(2)\n expect n.abs() == 2").assert_clean();
6462 case(" let n <- calc.call(2)\n expect n.length() == 2")
6463 .assert_reports("bynk.types.method_not_found");
6464 }
6465
6466 #[test]
6469 fn cron_and_queue_outcomes_are_typed() {
6470 case(" let r <- sweeper.schedule(\"0 0 * * *\")\n match r {\n Ok(_) => expect true\n Err(e) => expect e.length() > 0\n }")
6471 .assert_clean();
6472 case(" let r <- intake.message(Item { sku: \"x\" })\n expect r is Ack")
6473 .assert_clean();
6474 case(" let r <- intake.message(Item { sku: \"x\" })\n match r {\n Retry(why) => expect why.length() > 0\n Ack => expect true\n }")
6475 .assert_clean();
6476 case(" let r <- intake.message(Item { sku: \"x\" })\n expect r is Ok(_)")
6477 .assert_reports("bynk.types.is_unknown_variant");
6478 }
6479
6480 const CART_API: &str = "context shop.api
6482
6483type UserId = String where NonEmpty
6484actor User { auth = Bearer(secret = \"AUTH_SECRET\"), identity = UserId }
6485
6486type Item = { sku: String }
6487
6488service api from http {
6489 on POST(\"/cart\") (body: Item) -> Effect[HttpResult[Item]] by u: User {
6490 Created(body)
6491 }
6492}
6493";
6494
6495 fn system_case(body: &str) -> crate::testkit::Analysed {
6496 crate::testkit::analyse(&[
6497 ("shop/api.bynk", CART_API),
6498 (
6499 "shop/tests/api.test.bynk",
6500 &format!("suite shop.api as system {{\n case \"c\" {{\n{body}\n }}\n}}\n"),
6501 ),
6502 ])
6503 }
6504
6505 #[test]
6507 fn a_typed_system_call_is_the_handlers_result() {
6508 system_case(" let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by User(\"a\")\n expect r is Created(i) && i.sku == \"w\"")
6509 .assert_clean();
6510 system_case(" let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by User(\"a\")\n expect r is Rejected(_)")
6511 .assert_reports("bynk.types.is_unknown_variant");
6512 }
6513
6514 #[test]
6518 fn a_call_past_the_handlers_types_is_an_http_outcome() {
6519 let wire = " let r <- api.POST(\"/cart\", Wire(\"{}\")) by User(\"a\")\n";
6520 system_case(&format!("{wire} match r {{\n Rejected(RefinementViolation(d)) => expect d.length() > 0\n Rejected(_) => expect false\n Handled(Created(i)) => expect i.sku == \"w\"\n Handled(_) => expect false\n }}"))
6521 .assert_clean();
6522 system_case(&format!("{wire} match r {{\n Rejected(Unauthorized(d)) => expect true\n _ => expect false\n }}"))
6523 .assert_reports("bynk.types.pattern_arity");
6524 system_case(&format!("{wire} expect r is Rejected(Refinement(_))"))
6525 .assert_reports("bynk.types.unknown_variant_in_pattern");
6526 system_case(&format!("{wire} expect r is Created(_)"))
6527 .assert_reports("bynk.types.is_unknown_variant");
6528 system_case(" let r <- api.POST(\"/cart\", Item { sku: \"w\" }) by Nobody\n expect r is Rejected(Unauthorized)")
6529 .assert_clean();
6530 system_case(" let r <- api.POST(\"/cart\", Wire(\"{}\")) by Nobody\n expect r is Rejected(Unauthorized)")
6532 .assert_clean();
6533 system_case(
6534 " let r <- api.POST(\"/cart\", Wire(\"{}\")) by Nobody\n expect r is Created(_)",
6535 )
6536 .assert_reports("bynk.types.is_unknown_variant");
6537 system_case(
6538 " let r <- api.DELETE(\"/cart\")\n expect r is Rejected(MethodNotAllowed)",
6539 )
6540 .assert_clean();
6541 system_case(" let r <- api.DELETE(\"/cart\")\n expect r is NotFound")
6542 .assert_reports("bynk.types.is_unknown_variant");
6543 }
6544}
6545
6546#[cfg(test)]
6547mod participant_tests {
6548 use super::*;
6549
6550 type Subscribers = BTreeMap<(String, String), Vec<(String, String)>>;
6553
6554 fn project() -> (
6560 HashMap<String, Vec<String>>,
6561 BTreeMap<String, UnitKind>,
6562 Subscribers,
6563 ) {
6564 let edges = [
6565 ("ops.hub", &["ops.store", "bynk"][..]),
6566 ("ops.audit", &["ops.hub", "ops.archive"][..]),
6567 ("ops.mirror", &["ops.store"][..]),
6568 ("ops.digest", &["ops.audit"][..]),
6569 ];
6570 let unit_consumes = edges
6571 .iter()
6572 .map(|(u, ds)| (u.to_string(), ds.iter().map(|d| d.to_string()).collect()))
6573 .collect();
6574 let mut kinds: BTreeMap<String, UnitKind> = [
6575 "ops.hub",
6576 "ops.store",
6577 "ops.audit",
6578 "ops.archive",
6579 "ops.mirror",
6580 "ops.digest",
6581 ]
6582 .iter()
6583 .map(|c| (c.to_string(), UnitKind::Context))
6584 .collect();
6585 kinds.insert("bynk".to_string(), UnitKind::Adapter);
6586 let sub = |owner: &str, event: &str, ctx: &str| {
6587 (
6588 (owner.to_string(), event.to_string()),
6589 vec![(ctx.to_string(), "On".to_string())],
6590 )
6591 };
6592 let subscribers = [
6593 sub("ops.hub", "Ping", "ops.audit"),
6594 sub("ops.store", "Saved", "ops.mirror"),
6595 sub("ops.audit", "Noted", "ops.digest"),
6596 ]
6597 .into_iter()
6598 .collect();
6599 (unit_consumes, kinds, subscribers)
6600 }
6601
6602 #[test]
6605 fn participants_are_the_consumes_closure() {
6606 let (consumes, kinds, _) = project();
6607 assert_eq!(
6608 infer_participants("ops.hub", &consumes, &kinds),
6609 ["ops.hub", "ops.store"]
6610 );
6611 }
6612
6613 #[test]
6617 fn the_harness_adds_subscribers_and_their_closures_transitively() {
6618 let (consumes, kinds, subscribers) = project();
6619 assert_eq!(
6620 infer_harness_participants("ops.hub", &consumes, &kinds, &subscribers),
6621 [
6622 "ops.hub",
6623 "ops.store",
6624 "ops.audit",
6625 "ops.mirror",
6626 "ops.archive",
6627 "ops.digest"
6628 ]
6629 );
6630 }
6631
6632 #[test]
6634 fn without_subscribers_the_harness_is_the_case_set() {
6635 let (consumes, kinds, _) = project();
6636 assert_eq!(
6637 infer_harness_participants("ops.hub", &consumes, &kinds, &BTreeMap::new()),
6638 infer_participants("ops.hub", &consumes, &kinds)
6639 );
6640 }
6641}
6642
6643#[cfg(test)]
6647mod history_pattern_tests {
6648 use super::*;
6649
6650 fn ident(name: &str) -> Ident {
6651 Ident {
6652 name: name.to_string(),
6653 span: Span::default(),
6654 }
6655 }
6656
6657 fn variant(type_name: Option<&str>, name: &str) -> Pattern {
6658 Pattern::Variant {
6659 type_name: type_name.map(ident),
6660 variant: ident(name),
6661 bindings: Vec::new(),
6662 span: Span::default(),
6663 }
6664 }
6665
6666 fn payload_variant(name: &str) -> Pattern {
6667 Pattern::Variant {
6668 type_name: None,
6669 variant: ident(name),
6670 bindings: vec![PatternBinding {
6671 kind: PatternBindingKind::Positional {
6672 pattern: Pattern::Wildcard(Span::default()),
6673 },
6674 span: Span::default(),
6675 }],
6676 span: Span::default(),
6677 }
6678 }
6679
6680 fn int(n: i64) -> Pattern {
6681 Pattern::Literal {
6682 value: LiteralValue::Int(n),
6683 text: None,
6684 span: Span::default(),
6685 }
6686 }
6687
6688 #[test]
6689 fn same_payload_free_variant_matches() {
6690 assert!(history_pattern_matches(
6691 &variant(None, "Closed"),
6692 &variant(None, "Closed")
6693 ));
6694 assert!(history_pattern_matches(
6695 &variant(Some("Status"), "Closed"),
6696 &variant(Some("Status"), "Closed")
6697 ));
6698 }
6699
6700 #[test]
6701 fn different_variant_names_do_not_match() {
6702 assert!(!history_pattern_matches(
6703 &variant(None, "Open"),
6704 &variant(None, "Closed")
6705 ));
6706 }
6707
6708 #[test]
6709 fn qualifier_present_vs_absent_does_not_match() {
6710 assert!(!history_pattern_matches(
6711 &variant(Some("Status"), "Closed"),
6712 &variant(None, "Closed")
6713 ));
6714 assert!(!history_pattern_matches(
6715 &variant(None, "Closed"),
6716 &variant(Some("Status"), "Closed")
6717 ));
6718 assert!(!history_pattern_matches(
6719 &variant(Some("Status"), "Closed"),
6720 &variant(Some("Other"), "Closed")
6721 ));
6722 }
6723
6724 #[test]
6725 fn literals_match_by_value() {
6726 assert!(history_pattern_matches(&int(3), &int(3)));
6727 assert!(!history_pattern_matches(&int(3), &int(4)));
6728 assert!(!history_pattern_matches(&int(3), &variant(None, "Closed")));
6729 }
6730
6731 #[test]
6732 fn payload_variant_never_matches() {
6733 assert!(!history_pattern_matches(
6734 &payload_variant("Some"),
6735 &payload_variant("Some")
6736 ));
6737 assert!(!history_pattern_matches(
6738 &payload_variant("Some"),
6739 &variant(None, "Some")
6740 ));
6741 }
6742}
6743
6744#[cfg(test)]
6747mod event_address_tests {
6748 use crate::testkit::analyse;
6749
6750 const ORDER: &str =
6751 "context shop.order\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n";
6752
6753 fn ledger(consumes: &str, extra: &str) -> String {
6754 format!(
6755 "context shop.ledger\n\n{consumes}\n{extra}\nservice OnPlaced from Events(Placed) {{\n on event(e: Placed) -> Effect[()] {{\n ()\n }}\n}}\n"
6756 )
6757 }
6758
6759 fn suite(body: &str) -> String {
6760 format!("suite shop.ledger {{\n case \"c\" {{\n{body}\n }}\n}}\n")
6761 }
6762
6763 #[test]
6764 fn an_envelope_the_suite_cannot_name_notes_consumes_bynk() {
6765 let a = analyse(&[
6766 ("shop/order.bynk", ORDER),
6767 ("shop/ledger.bynk", &ledger("consumes shop.order", "")),
6768 (
6769 "shop/tests/ledger.test.bynk",
6770 &suite(" let _ <- OnPlaced.event(Placed { id: \"o1\" }, \"evt-1\")"),
6771 ),
6772 ]);
6773 let e = a
6774 .analysis
6775 .errors
6776 .iter()
6777 .find(|e| e.error.category == "bynk.types.argument_mismatch")
6778 .expect("an argument mismatch on the envelope");
6779 assert!(
6780 e.error
6781 .notes
6782 .iter()
6783 .any(|n| n.contains("must `consumes bynk`")),
6784 "expected the `consumes bynk` note, got {:?}",
6785 e.error.notes
6786 );
6787 }
6788
6789 #[test]
6790 fn a_same_named_event_outside_the_targets_scope_is_a_plain_mismatch() {
6791 let a = analyse(&[
6794 ("shop/order.bynk", ORDER),
6795 (
6796 "shop/archive.bynk",
6797 "context shop.archive\n\nevent Note = { text: String }\n",
6798 ),
6799 (
6800 "shop/ledger.bynk",
6801 &ledger("consumes shop.order", "\ntype Note = { text: String }\n"),
6802 ),
6803 (
6804 "shop/tests/ledger.test.bynk",
6805 &suite(" let _ <- OnPlaced.event(Note { text: \"n\" })"),
6806 ),
6807 ]);
6808 a.assert_reports("bynk.types.argument_mismatch");
6809 assert!(
6810 !a.categories().contains(&"bynk.test.event_not_subscribed"),
6811 "a record named like an unconsumed context's event is not an event: {:?}",
6812 a.categories()
6813 );
6814 }
6815
6816 #[test]
6817 fn a_same_named_event_in_an_unconsumed_context_leaves_the_publisher_unique() {
6818 let a = analyse(&[
6819 ("shop/order.bynk", ORDER),
6820 (
6821 "shop/archive.bynk",
6822 "context shop.archive\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n",
6823 ),
6824 ("shop/ledger.bynk", &ledger("consumes shop.order", "")),
6825 (
6826 "shop/tests/ledger.test.bynk",
6827 &suite(" let _ <- OnPlaced.event(Placed { id: \"o1\" })")
6829 .replace("{\n case", "{\n consumes shop.order\n case"),
6830 ),
6831 ]);
6832 a.assert_clean();
6833 }
6834
6835 #[test]
6836 fn two_consumed_publishers_refuse_a_default_envelope() {
6837 let a = analyse(&[
6838 ("shop/order.bynk", ORDER),
6839 (
6840 "shop/archive.bynk",
6841 "context shop.archive\n\nexports transparent { Placed }\n\nevent Placed = { id: String }\n",
6842 ),
6843 (
6844 "shop/ledger.bynk",
6845 &ledger("consumes shop.order\nconsumes shop.archive", ""),
6846 ),
6847 (
6848 "shop/tests/ledger.test.bynk",
6849 &suite(" let _ <- OnPlaced.event(Placed { id: \"o1\" })"),
6850 ),
6851 ]);
6852 a.assert_reports("bynk.test.event_publisher_ambiguous");
6853 }
6854}