1use std::collections::{BTreeSet, HashMap, HashSet};
28
29use bynk_syntax::ast::*;
30use bynk_syntax::span::Span;
31
32use crate::agent_state::{PATH_BUDGET, combine_guards};
33use bynk_check::ast_text::{branch_outcome, pattern_summary, peel_paren};
34use bynk_check::store_write::{store_kinds, store_write};
35
36#[derive(Debug, Clone, PartialEq)]
38pub struct HandlerEffects {
39 pub handler: String,
40 pub rows: Vec<EffectRow>,
41 pub truncated: bool,
43}
44
45#[derive(Debug, Clone, PartialEq)]
47pub struct EffectRow {
48 pub guards: Vec<String>,
50 pub writes: Vec<EffectWrite>,
52 pub reads: Vec<String>,
54 pub calls: Vec<String>,
56 pub outcomes: Vec<String>,
58}
59
60#[derive(Debug, Clone, PartialEq)]
61pub struct EffectWrite {
62 pub field: String,
63 pub op: String,
65 pub key: Option<String>,
68 pub span: Span,
69}
70
71pub fn agent_effects(agent: &AgentDecl, agents: &HashSet<String>) -> Vec<HandlerEffects> {
75 let store = store_kinds(agent);
76 agent
77 .handlers
78 .iter()
79 .map(|h| {
80 let mut w = Walker {
81 store: &store,
82 agents,
83 bound: h.params.iter().map(|p| p.name.name.clone()).collect(),
84 truncated: false,
85 };
86 let paths = w.walk_block(&h.body, vec![Path::default()], true);
87 let handler = h
88 .method_name
89 .as_ref()
90 .map_or_else(|| "call".to_string(), |m| m.name.clone());
91 HandlerEffects {
92 handler,
93 truncated: w.truncated,
94 rows: if w.truncated {
95 Vec::new()
96 } else {
97 paths.into_iter().map(Path::into_row).collect()
98 },
99 }
100 })
101 .collect()
102}
103
104#[derive(Debug, Clone, Default)]
105struct Path {
106 guards: BTreeSet<String>,
107 writes: Vec<EffectWrite>,
108 reads: BTreeSet<String>,
109 calls: BTreeSet<String>,
110 outcomes: BTreeSet<String>,
111}
112
113impl Path {
114 fn written(&self, field: &str) -> bool {
115 self.writes.iter().any(|w| w.field == field)
116 }
117
118 fn same_key(&self, other: &Path) -> bool {
121 let ops = |p: &Path| -> Vec<(String, String, Option<String>)> {
122 p.writes
123 .iter()
124 .map(|w| (w.field.clone(), w.op.clone(), w.key.clone()))
125 .collect()
126 };
127 ops(self) == ops(other) && self.reads == other.reads && self.calls == other.calls
128 }
129
130 fn into_row(self) -> EffectRow {
131 EffectRow {
132 guards: self.guards.into_iter().collect(),
133 writes: self.writes,
134 reads: self.reads.into_iter().collect(),
135 calls: self.calls.into_iter().collect(),
136 outcomes: self.outcomes.into_iter().collect(),
137 }
138 }
139}
140
141struct Walker<'a> {
142 store: &'a HashMap<String, String>,
143 agents: &'a HashSet<String>,
144 bound: Vec<String>,
145 truncated: bool,
146}
147
148impl Walker<'_> {
149 fn walk_block(&mut self, block: &Block, mut paths: Vec<Path>, tail: bool) -> Vec<Path> {
150 let scope = self.bound.len();
151 for stmt in &block.statements {
152 if self.truncated {
153 return Vec::new();
154 }
155 paths = self.walk_stmt(stmt, paths);
156 }
157 let paths = self.walk_expr(&block.tail, paths, tail);
158 self.bound.truncate(scope);
159 paths
160 }
161
162 fn walk_stmt(&mut self, stmt: &Statement, paths: Vec<Path>) -> Vec<Path> {
163 match stmt {
164 Statement::Let(l) | Statement::EffectLet(l) => {
165 let paths = self.walk_expr(&l.value, paths, false);
166 self.bound.push(l.name.name.clone());
167 paths
168 }
169 Statement::Do(d) => self.walk_expr(&d.value, paths, false),
170 Statement::Expect(e) => self.walk_expr(&e.value, paths, false),
171 Statement::Advance(a) => self.walk_expr(&a.amount, paths, false),
172 Statement::Assign(a) => {
173 let mut paths = self.walk_expr(&a.value, paths, false);
174 for p in &mut paths {
175 p.writes.push(EffectWrite {
176 field: a.target.name.clone(),
177 op: ":=".to_string(),
178 key: None,
179 span: a.span,
180 });
181 }
182 paths
183 }
184 Statement::Par(p) => p
187 .statements
188 .iter()
189 .fold(paths, |paths, s| self.walk_stmt(s, paths)),
190 }
191 }
192
193 fn walk_expr(&mut self, expr: &Expr, mut paths: Vec<Path>, tail: bool) -> Vec<Path> {
194 if self.truncated || paths.is_empty() {
195 return paths;
196 }
197 let inner = peel_paren(expr);
198 match &inner.kind {
199 ExprKind::If {
200 cond,
201 then_block,
202 else_block,
203 } => {
204 self.scan(cond, &mut paths);
205 let text = bynk_fmt::expr_to_string(cond);
206 let then_paths = guarded(paths.clone(), text.clone());
207 let else_paths = guarded(paths, format!("!({text})"));
208 let mut out = self.walk_block(then_block, then_paths, tail);
209 out.extend(self.walk_block(else_block, else_paths, tail));
210 self.join(out)
211 }
212 ExprKind::Match { discriminant, arms } => {
213 self.scan(discriminant, &mut paths);
214 let subject = bynk_fmt::expr_to_string(discriminant);
215 let mut out = Vec::new();
216 for arm in arms {
217 let mut arm_paths = guarded(
218 paths.clone(),
219 format!("{subject} is {}", pattern_summary(&arm.pattern)),
220 );
221 let scope = self.bound.len();
222 self.bound.extend(
223 arm.pattern
224 .bound_names()
225 .into_iter()
226 .map(|n| n.name.clone()),
227 );
228 if let Some(g) = &arm.guard {
229 self.scan(g, &mut arm_paths);
230 arm_paths = guarded(arm_paths, bynk_fmt::expr_to_string(g));
231 }
232 out.extend(match &arm.body {
233 MatchBody::Expr(e) => self.walk_expr(e, arm_paths, tail),
234 MatchBody::Block(b) => self.walk_block(b, arm_paths, tail),
235 });
236 self.bound.truncate(scope);
237 }
238 self.join(out)
239 }
240 ExprKind::Block(b) => self.walk_block(b, paths, tail),
241 _ => {
242 if let Some(w) = store_write(self.store, &self.bound, inner) {
243 for a in w.args {
244 self.scan(a, &mut paths);
245 }
246 let key = w.args.first().and_then(simple_text);
247 for p in &mut paths {
248 p.writes.push(EffectWrite {
249 field: w.field.name.clone(),
250 op: w.method.name.clone(),
251 key: key.clone(),
252 span: inner.span,
253 });
254 }
255 } else {
257 self.scan(inner, &mut paths);
258 if tail && let Some(o) = branch_outcome(inner) {
259 for p in &mut paths {
260 p.outcomes.insert(o.clone());
261 }
262 }
263 }
264 paths
265 }
266 }
267 }
268
269 fn scan(&self, expr: &Expr, paths: &mut [Path]) {
272 let mut reads = BTreeSet::new();
273 let mut calls = BTreeSet::new();
274 let mut shadow = self.bound.clone();
275 self.collect(expr, &mut shadow, &mut reads, &mut calls);
276 for p in paths {
277 let fresh: Vec<String> = reads.iter().filter(|f| !p.written(f)).cloned().collect();
278 p.reads.extend(fresh);
279 p.calls.extend(calls.iter().cloned());
280 }
281 }
282
283 fn collect(
286 &self,
287 expr: &Expr,
288 shadow: &mut Vec<String>,
289 reads: &mut BTreeSet<String>,
290 calls: &mut BTreeSet<String>,
291 ) {
292 if let ExprKind::Lambda(l) = &expr.kind {
293 let scope = shadow.len();
294 shadow.extend(l.params.iter().map(|p| p.name.name.clone()));
295 self.collect(&l.body, shadow, reads, calls);
296 shadow.truncate(scope);
297 return;
298 }
299 if let Some(w) = store_write(self.store, shadow, expr) {
302 for a in w.args {
303 self.collect(a, shadow, reads, calls);
304 }
305 return;
306 }
307 match &expr.kind {
308 ExprKind::Ident(id)
309 if self.store.contains_key(&id.name) && !shadow.contains(&id.name) =>
310 {
311 reads.insert(id.name.clone());
312 }
313 ExprKind::MethodCall {
314 receiver, method, ..
315 } => {
316 if let ExprKind::Call { name, .. } = &receiver.kind
317 && self.agents.contains(&name.name)
318 {
319 calls.insert(format!("{}.{}", name.name, method.name));
320 }
321 }
322 _ => {}
323 }
324 for c in expr_children(expr) {
325 self.collect(c, shadow, reads, calls);
326 }
327 }
328
329 fn join(&mut self, paths: Vec<Path>) -> Vec<Path> {
330 let mut out: Vec<Path> = Vec::new();
331 for p in paths {
332 match out.iter_mut().find(|q| q.same_key(&p)) {
333 Some(q) => {
334 q.guards = combine_guards(&q.guards, &p.guards);
335 q.outcomes.extend(p.outcomes);
336 }
337 None => out.push(p),
338 }
339 }
340 if out.len() > PATH_BUDGET {
341 self.truncated = true;
342 return Vec::new();
343 }
344 out
345 }
346}
347
348fn guarded(mut paths: Vec<Path>, label: String) -> Vec<Path> {
349 for p in &mut paths {
350 p.guards.insert(label.clone());
351 }
352 paths
353}
354
355fn simple_text(arg: &Expr) -> Option<String> {
357 matches!(
358 peel_paren(arg).kind,
359 ExprKind::Ident(_) | ExprKind::IntLit { .. } | ExprKind::StrLit(_) | ExprKind::BoolLit(_)
360 )
361 .then(|| bynk_fmt::expr_to_string(arg))
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 fn effects(src: &str, agent: &str, agents: &[&str]) -> Vec<HandlerEffects> {
369 let tokens = bynk_syntax::lexer::tokenize(src).expect("tokenize");
370 let (unit, errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, src);
371 assert!(errs.is_empty(), "parse errors: {errs:?}");
372 let Some(SourceUnit::Context(ctx)) = unit else {
373 panic!("expected a context")
374 };
375 let a = ctx
376 .items
377 .iter()
378 .find_map(|i| match i {
379 CommonsItem::Agent(a) if a.name.name == agent => Some(a),
380 _ => None,
381 })
382 .expect("agent");
383 let names = agents.iter().map(|s| s.to_string()).collect();
384 agent_effects(a, &names)
385 }
386
387 fn handler<'a>(all: &'a [HandlerEffects], name: &str) -> &'a HandlerEffects {
388 all.iter().find(|h| h.handler == name).expect("handler")
389 }
390
391 type Summary = (
393 Vec<String>,
394 Vec<String>,
395 Vec<String>,
396 Vec<String>,
397 Vec<String>,
398 );
399
400 fn summary(h: &HandlerEffects) -> Vec<Summary> {
401 h.rows
402 .iter()
403 .map(|r| {
404 let writes = r
405 .writes
406 .iter()
407 .map(|w| match (&w.key, w.op.as_str()) {
408 (_, ":=") => format!("{} :=", w.field),
409 (Some(k), op) => format!("{}.{op}({k})", w.field),
410 (None, op) => format!("{}.{op}", w.field),
411 })
412 .collect();
413 (
414 r.guards.clone(),
415 writes,
416 r.reads.clone(),
417 r.calls.clone(),
418 r.outcomes.clone(),
419 )
420 })
421 .collect()
422 }
423
424 fn v(x: &[&str]) -> Vec<String> {
425 x.iter().map(|s| s.to_string()).collect()
426 }
427
428 const TODOS: &str = r#"context todo
430
431type UserId = String where NonEmpty
432type Title = String where NonEmpty
433type Stored = { seq: Int, title: Title, done: Bool }
434type TodoItem = { id: String, title: Title, done: Bool }
435type TodoError = enum { NotFound }
436
437fn view(id: String, s: Stored) -> TodoItem {
438 TodoItem { id: id, title: s.title, done: s.done }
439}
440
441agent Todos {
442 key owner: UserId
443
444 store items: Map[String, Stored]
445 store lastSeq: Cell[Int]
446
447 on call add(title: Title) -> Effect[TodoItem] {
448 let next = lastSeq + 1
449 let id = "\(next)"
450 let item = Stored { seq: next, title: title, done: false }
451 let _ <- items.put(id, item)
452 lastSeq := next
453 view(id, item)
454 }
455
456 on call pendingCount() -> Effect[Int] {
457 items.values.filter((it) => it.done == false).count()
458 }
459
460 on call complete(id: String) -> Effect[Result[(), TodoError]] {
461 let found <- items.get(id)
462 match found {
463 Some(it) => {
464 let _ <- items.put(id, Stored { ...it, done: true })
465 Ok(())
466 }
467 None => Err(NotFound)
468 }
469 }
470}
471"#;
472
473 #[test]
474 fn todos_add_writes_both_fields_and_reads_the_counter_first() {
475 let all = effects(TODOS, "Todos", &[]);
476 assert_eq!(
477 summary(handler(&all, "add")),
478 [(
479 v(&[]),
480 v(&["items.put(id)", "lastSeq :="]),
481 v(&["lastSeq"]),
482 v(&[]),
483 v(&["view(id, item)"])
484 )]
485 );
486 }
487
488 #[test]
489 fn todos_complete_writes_only_when_the_item_is_found() {
490 let all = effects(TODOS, "Todos", &[]);
491 assert_eq!(
492 summary(handler(&all, "complete")),
493 [
494 (
495 v(&["found is Some"]),
496 v(&["items.put(id)"]),
497 v(&["items"]),
498 v(&[]),
499 v(&["Ok(())"])
500 ),
501 (
502 v(&["found is None"]),
503 v(&[]),
504 v(&["items"]),
505 v(&[]),
506 v(&["Err(NotFound)"])
507 ),
508 ]
509 );
510 }
511
512 #[test]
513 fn a_query_accessor_is_a_read() {
514 let all = effects(TODOS, "Todos", &[]);
515 let rows = summary(handler(&all, "pendingCount"));
516 assert_eq!(rows.len(), 1);
517 assert_eq!(rows[0].1, v(&[]));
518 assert_eq!(rows[0].2, v(&["items"]));
519 }
520
521 #[test]
522 fn the_rate_limiter_reads_then_writes_both_cells() {
523 let src = r#"context ratelimit
524type RateView = { allowed: Bool }
525agent Limiter {
526 key client: String
527 store windowStart: Cell[Int]
528 store count: Cell[Int]
529 on call hit(now: Int) -> Effect[RateView] {
530 let d = decide(windowStart, count, now)
531 windowStart := d.windowStart
532 count := d.count
533 RateView { allowed: d.allowed }
534 }
535}
536"#;
537 let all = effects(src, "Limiter", &[]);
538 let rows = summary(handler(&all, "hit"));
539 assert_eq!(rows.len(), 1);
540 assert_eq!(rows[0].1, v(&["windowStart :=", "count :="]));
541 assert_eq!(rows[0].2, v(&["count", "windowStart"]));
542 }
543
544 #[test]
545 fn a_log_append_is_a_write_and_its_queries_are_reads() {
546 let src = r#"context events
547type Event = { kind: String }
548agent Activity {
549 key stream: String
550 store history: Log[Event]
551 on call add(event: Event) -> Effect[()] {
552 let _ <- history.append(event)
553 Effect.pure(())
554 }
555 on call countSince(t: Int) -> Effect[Int] {
556 history.since(t).count()
557 }
558}
559"#;
560 let all = effects(src, "Activity", &[]);
561 let add = summary(handler(&all, "add"));
562 assert_eq!(add[0].1, v(&["history.append(event)"]));
563 assert_eq!(add[0].2, v(&[]), "the write's receiver is not also a read");
564 let count = summary(handler(&all, "countSince"));
565 assert_eq!(count[0].1, v(&[]));
566 assert_eq!(count[0].2, v(&["history"]));
567 }
568
569 #[test]
570 fn agent_calls_are_listed_and_paths_that_agree_merge() {
571 let src = r#"context shop
572agent Counter {
573 key id: String
574 store n: Cell[Int]
575 on call bump() -> Effect[Int] { n := n + 1
576 n }
577}
578agent Basket {
579 key id: String
580 store total: Cell[Int]
581 on call add(k: String, big: Bool) -> Effect[Int] {
582 let c <- Counter(k).bump()
583 let _ = if big { total := total + 10
584 () } else { total := total + 1
585 () }
586 c
587 }
588}
589"#;
590 let all = effects(src, "Basket", &["Counter", "Basket"]);
591 let rows = summary(handler(&all, "add"));
592 assert_eq!(rows.len(), 1);
595 assert_eq!(rows[0].0, v(&[]));
596 assert_eq!(rows[0].1, v(&["total :="]));
597 assert_eq!(rows[0].2, v(&["total"]));
598 assert_eq!(rows[0].3, v(&["Counter.bump"]));
599 assert_eq!(rows[0].4, v(&["c"]));
600 }
601
602 #[test]
603 fn a_shadowed_field_is_neither_read_nor_written() {
604 let src = r#"context demo
605agent A {
606 key id: String
607 store items: Map[String, Int]
608 on call go(items: List[Int]) -> Effect[Int] {
609 items.size()
610 }
611}
612"#;
613 let all = effects(src, "A", &[]);
614 let rows = summary(handler(&all, "go"));
615 assert_eq!(rows[0].1, v(&[]));
616 assert_eq!(rows[0].2, v(&[]));
617 }
618
619 #[test]
620 fn writes_with_different_keys_stay_separate_rows() {
621 let src = r#"context demo
622agent A {
623 key id: String
624 store items: Map[String, Int]
625 on call go(c: Bool, a: String, b: String, x: Int) -> Effect[()] {
626 let _ = if c { let _ <- items.put(a, x)
627 () } else { let _ <- items.put(b, x)
628 () }
629 Effect.pure(())
630 }
631}
632"#;
633 let all = effects(src, "A", &[]);
634 let h = handler(&all, "go");
635 let rows = summary(h);
636 assert_eq!(rows.len(), 2);
638 assert_eq!(rows[0].1, v(&["items.put(a)"]));
639 assert_eq!(rows[1].1, v(&["items.put(b)"]));
640 assert_ne!(h.rows[0].writes[0].span, h.rows[1].writes[0].span);
641 }
642
643 #[test]
644 fn a_lambda_parameter_shadows_a_field_and_a_nested_write_is_not_a_read() {
645 let src = r#"context demo
646agent A {
647 key id: String
648 store count: Cell[Int]
649 store items: Map[String, Int]
650 on call go(xs: List[Int], k: String) -> Effect[Int] {
651 let ys = xs.map((count) => count + 1)
652 let _ = ignore(items.put(k, 1))
653 ys.size()
654 }
655}
656"#;
657 let all = effects(src, "A", &[]);
658 let rows = summary(handler(&all, "go"));
659 assert_eq!(rows.len(), 1);
660 assert_eq!(rows[0].1, v(&[]), "a nested write is out of scope");
661 assert_eq!(rows[0].2, v(&[]), "neither `count` nor `items` is read");
662 }
663
664 #[test]
665 fn a_handler_past_the_budget_is_truncated() {
666 let choices: String = (0..9)
669 .map(|i| {
670 format!(
671 " let _ = if c{i} {{ a := {i}\n () }} else {{ b := {i}\n () }}\n"
672 )
673 })
674 .collect();
675 let params: Vec<String> = (0..9).map(|i| format!("c{i}: Bool")).collect();
676 let src = format!(
677 "context demo\nagent A {{\n key id: String\n store a: Cell[Int]\n store b: Cell[Int]\n on call go({}) -> Effect[()] {{\n{choices} ()\n }}\n}}\n",
678 params.join(", ")
679 );
680 let all = effects(&src, "A", &[]);
681 let go = handler(&all, "go");
682 assert!(go.truncated);
683 assert!(go.rows.is_empty());
684 }
685}