bynk_check/exec_plan.rs
1//! #2719: which functions need the execution context, and where one is not
2//! available to give them.
3//!
4//! `e.detach()`, `e.within(d)` and `a.race(b)` hand work to the execution context's
5//! `waitUntil`. A service handler reaches it as `deps.__exec`; a function has
6//! no `deps`, so a function whose body (or a function it calls, or names as a
7//! value) uses one of the three takes it as a hidden trailing parameter. This
8//! module computes that *needs-context set* (a fixed point over a unit's
9//! functions, against the set its dependencies already settled) and refuses a
10//! call that would bring the construct into a place with no context
11//! (`bynk.exec.unavailable`).
12//!
13//! The set is built after type checking, from what the checker resolved: a
14//! `within` or `race` counts only when the checker recorded it as the kernel
15//! method on an `Effect` receiver (`Callee::Kernel`), never by name, so a user
16//! type's own `race` method puts nothing in the set.
17//!
18//! Members are keyed by their declaration's [`Span`]: the file id is unique
19//! across a build (dependency packages included), so a callee reached through
20//! `uses`, a package alias or a sibling file names the same key as its
21//! declaration.
22
23use std::collections::{HashMap, HashSet};
24use std::sync::Arc;
25
26use crate::kernel_op::KernelOp;
27
28use bynk_syntax::ast::{
29 Block, ExprId, ExprKind, FnDecl, Handler, HandlerKind, MatchBody, ServiceProtocol, Statement,
30 TypeRef, expr_children,
31};
32use bynk_syntax::error::CompileError;
33use bynk_syntax::span::Span;
34
35use crate::checker::{Callee, Ty, TypedCommons, Types};
36
37/// Why a function is in the needs-context set.
38#[derive(Debug, Clone)]
39pub enum Why {
40 /// Its own body uses the construct, at `span`.
41 Construct { what: &'static str, span: Span },
42 /// It calls (or names as a value) a function already in the set.
43 Calls { callee: String, key: Span, at: Span },
44}
45
46/// The needs-context set for a build so far: every effectful function that
47/// takes the hidden `__exec` parameter, and every service handler whose `deps`
48/// must carry `__exec` (its body uses a construct, or calls or names a member).
49///
50/// Units are checked dependency-first, so a unit extends the set its
51/// dependencies left and every [`TypedCommons`] of the unit then carries a
52/// snapshot of it.
53#[derive(Debug, Clone, Default)]
54pub struct ExecPlan {
55 fns: HashMap<Span, Why>,
56 handlers: HashSet<Span>,
57 /// The subset that reaches a `within` or `race` (not only a `detach`): what puts
58 /// a test module on virtual time, because those register timers on the
59 /// harness clock.
60 timed_fns: HashSet<Span>,
61 timed_handlers: HashSet<Span>,
62}
63
64impl ExecPlan {
65 /// Whether `f` takes the hidden execution-context parameter.
66 pub fn fn_needs(&self, f: &FnDecl) -> bool {
67 self.fns.contains_key(&f.span)
68 }
69
70 /// Whether this service handler's `deps` carry `__exec`: its body uses
71 /// `detach`, `within` or `race`, or calls or names a function that does.
72 pub fn handler_needs(&self, h: &Handler) -> bool {
73 self.handlers.contains(&h.span)
74 }
75
76 /// Whether this service handler reaches a `within` or `race`, directly or
77 /// through the functions it calls or names.
78 pub fn handler_timed(&self, h: &Handler) -> bool {
79 self.timed_handlers.contains(&h.span)
80 }
81
82 /// Whether `f` reaches a `within` or `race`.
83 pub fn fn_timed(&self, f: &FnDecl) -> bool {
84 self.timed_fns.contains(&f.span)
85 }
86
87 /// Whether any function in the build takes the execution context.
88 pub fn any_fn(&self) -> bool {
89 !self.fns.is_empty()
90 }
91
92 /// Whether any function in the build reaches a `within` or `race`.
93 pub fn any_timed_fn(&self) -> bool {
94 !self.timed_fns.is_empty()
95 }
96
97 pub fn is_empty(&self) -> bool {
98 self.fns.is_empty() && self.handlers.is_empty()
99 }
100
101 /// The chain from `key` down to the construct, as `a → b → within`.
102 fn chain(&self, key: Span) -> Option<(Vec<String>, Span)> {
103 let mut names = Vec::new();
104 let mut at = key;
105 // A chain cannot revisit a member (each `Calls` points at a function
106 // that joined the set strictly earlier), so this ends; the bound is a
107 // belt on that reasoning.
108 for _ in 0..=self.fns.len() {
109 match self.fns.get(&at)? {
110 Why::Construct { what, span } => {
111 names.push(format!("`{what}`"));
112 return Some((names, *span));
113 }
114 Why::Calls { callee, key, .. } => {
115 names.push(format!("`{callee}`"));
116 at = *key;
117 }
118 }
119 }
120 None
121 }
122
123 /// Extend the set with one unit's files and report the calls that would
124 /// carry the execution context where none exists.
125 ///
126 /// `files` are all of the unit's checked files: a function in one file may
127 /// call a function in a sibling, and a handler's callees are recorded on
128 /// whichever file the unit-wide handler check ran against.
129 pub fn extend(&mut self, files: &[&TypedCommons]) -> Vec<CompileError> {
130 let Some(first) = files.first() else {
131 return Vec::new();
132 };
133 let tys = &*first.ty_intern;
134 let callees: HashMap<ExprId, &Callee> = files
135 .iter()
136 .flat_map(|f| f.callees.iter().map(|(id, c)| (*id, c)))
137 .collect();
138
139 struct Node<'a> {
140 key: Span,
141 facts: Facts,
142 kind: NodeKind<'a>,
143 }
144 enum NodeKind<'a> {
145 Fn,
146 /// A service handler that has a context to give.
147 Handler(&'a Handler),
148 /// A body with none: an agent handler, a WebSocket handler or a
149 /// provider operation. Only its calls matter, for the diagnostic.
150 NoContext(&'static str),
151 }
152
153 let mut nodes: Vec<Node> = Vec::new();
154 for file in files {
155 for item in &file.commons.items {
156 use bynk_syntax::ast::CommonsItem;
157 match item {
158 CommonsItem::Fn(f) if matches!(f.return_type, TypeRef::Effect(..)) => {
159 nodes.push(Node {
160 key: f.span,
161 facts: scan(&f.body, &callees, tys),
162 kind: NodeKind::Fn,
163 });
164 }
165 // A function that is not effectful has no context to give,
166 // however its result is used: a lambda it returns, or a
167 // function value it names, would reach for one (DECISION C).
168 CommonsItem::Fn(f) => {
169 let mut facts = scan(&f.body, &callees, tys);
170 for c in f.requires.iter().chain(&f.ensures) {
171 let more = scan_expr(&c.predicate, &callees, tys);
172 facts.edges.extend(more.edges);
173 }
174 nodes.push(Node {
175 key: f.span,
176 facts,
177 kind: NodeKind::NoContext("a function that is not effectful"),
178 });
179 }
180 CommonsItem::Const(c) => nodes.push(Node {
181 key: c.span,
182 facts: scan_expr(&c.init, &callees, tys),
183 kind: NodeKind::NoContext("a `const` initialiser"),
184 }),
185 CommonsItem::Service(s) => {
186 let ws = matches!(s.protocol, ServiceProtocol::WebSocket { .. });
187 for h in &s.handlers {
188 let facts = scan(&h.body, &callees, tys);
189 let websocket = ws
190 && matches!(
191 h.kind,
192 HandlerKind::Open | HandlerKind::Message | HandlerKind::Close
193 );
194 nodes.push(Node {
195 key: h.span,
196 facts,
197 kind: if websocket {
198 NodeKind::NoContext("a WebSocket handler")
199 } else {
200 NodeKind::Handler(h)
201 },
202 });
203 }
204 }
205 CommonsItem::Agent(a) => {
206 for init in a.store_fields.iter().filter_map(|sf| sf.init.as_ref()) {
207 nodes.push(Node {
208 key: init.span,
209 facts: scan_expr(init, &callees, tys),
210 kind: NodeKind::NoContext("a `store` initialiser"),
211 });
212 }
213 let predicates = a
214 .invariants
215 .iter()
216 .map(|i| &i.predicate)
217 .chain(a.transitions.iter().map(|t| &t.predicate));
218 for pred in predicates {
219 nodes.push(Node {
220 key: pred.span,
221 facts: scan_expr(pred, &callees, tys),
222 kind: NodeKind::NoContext("a predicate"),
223 });
224 }
225 for h in &a.handlers {
226 nodes.push(Node {
227 key: h.span,
228 facts: scan(&h.body, &callees, tys),
229 kind: NodeKind::NoContext("an agent handler"),
230 });
231 }
232 }
233 CommonsItem::Provider(p) => {
234 for op in &p.ops {
235 nodes.push(Node {
236 key: op.span,
237 facts: scan(&op.body, &callees, tys),
238 kind: NodeKind::NoContext("a provider operation"),
239 });
240 }
241 }
242 _ => {}
243 }
244 }
245 }
246
247 // The fixed point: a function joins when it uses a construct or has an
248 // edge to a member. A member's reason is recorded once, when it joins.
249 loop {
250 let mut grew = false;
251 for n in &nodes {
252 if !matches!(n.kind, NodeKind::Fn) || self.fns.contains_key(&n.key) {
253 continue;
254 }
255 let why = if let Some((what, span)) = n.facts.direct {
256 Some(Why::Construct { what, span })
257 } else {
258 n.facts
259 .edges
260 .iter()
261 .find(|e| self.fns.contains_key(&e.key))
262 .map(|e| Why::Calls {
263 callee: e.name.clone(),
264 key: e.key,
265 at: e.at,
266 })
267 };
268 if let Some(why) = why {
269 self.fns.insert(n.key, why);
270 grew = true;
271 }
272 }
273 if !grew {
274 break;
275 }
276 }
277
278 loop {
279 let mut grew = false;
280 for n in &nodes {
281 if matches!(n.kind, NodeKind::Fn)
282 && !self.timed_fns.contains(&n.key)
283 && (n.facts.timed
284 || n.facts
285 .edges
286 .iter()
287 .any(|e| self.timed_fns.contains(&e.key)))
288 {
289 self.timed_fns.insert(n.key);
290 grew = true;
291 }
292 }
293 if !grew {
294 break;
295 }
296 }
297
298 let mut errors = Vec::new();
299 for n in &nodes {
300 match &n.kind {
301 NodeKind::Fn => {}
302 NodeKind::Handler(h) => {
303 if n.facts.direct.is_some()
304 || n.facts.edges.iter().any(|e| self.fns.contains_key(&e.key))
305 {
306 self.handlers.insert(h.span);
307 }
308 if n.facts.timed
309 || n.facts
310 .edges
311 .iter()
312 .any(|e| self.timed_fns.contains(&e.key))
313 {
314 self.timed_handlers.insert(h.span);
315 }
316 }
317 NodeKind::NoContext(place) => {
318 for e in &n.facts.edges {
319 let Some((chain, construct)) = self.chain(e.key) else {
320 continue;
321 };
322 let mut path = vec![format!("`{}`", e.name)];
323 path.extend(chain);
324 errors.push(
325 CompileError::new(
326 "bynk.exec.unavailable",
327 e.at,
328 format!(
329 "`{}` needs an execution context, which {place} does not have",
330 e.name
331 ),
332 )
333 .with_label(construct, "the execution context is used here")
334 .with_note(format!(
335 "{}: the call hands work to the execution context (`waitUntil`), which only a service handler (not a WebSocket one) supplies; call it from a service handler, or from a function one calls",
336 path.join(" → "),
337 )),
338 );
339 }
340 }
341 }
342 }
343 errors
344 }
345}
346
347/// What one body does with the execution context: a construct it uses itself,
348/// and every function it calls or names as a value.
349#[derive(Default)]
350struct Facts {
351 direct: Option<(&'static str, Span)>,
352 /// The body uses `within` or `race` itself.
353 timed: bool,
354 edges: Vec<Edge>,
355}
356
357struct Edge {
358 name: String,
359 key: Span,
360 at: Span,
361}
362
363fn scan(body: &Block, callees: &HashMap<ExprId, &Callee>, tys: &Types) -> Facts {
364 scan_with(callees, tys, |f| visit_block(body, f))
365}
366
367/// [`scan`] for a lone expression: a `const` or `store` initialiser, a predicate.
368fn scan_expr(e: &bynk_syntax::ast::Expr, callees: &HashMap<ExprId, &Callee>, tys: &Types) -> Facts {
369 scan_with(callees, tys, |f| visit_expr(e, f))
370}
371
372fn scan_with<'a>(
373 callees: &HashMap<ExprId, &Callee>,
374 tys: &Types,
375 walk: impl FnOnce(&mut dyn FnMut(&'a bynk_syntax::ast::Expr)),
376) -> Facts {
377 let mut facts = Facts::default();
378 walk(&mut |e| {
379 match callees.get(&e.id) {
380 Some(Callee::Kernel {
381 recv,
382 op: KernelOp::Effect(op),
383 }) => {
384 if matches!(&*tys.get(*recv), Ty::Effect(_)) {
385 // `detach` registers no timer, so it does not put a test
386 // module on virtual time.
387 facts.timed |= !matches!(op, crate::kernel_op::EffectOp::Detach);
388 facts.direct.get_or_insert((op.name(), e.span));
389 }
390 }
391 Some(
392 Callee::Fn(d, _)
393 | Callee::Method(d, _)
394 | Callee::Static(d, _)
395 | Callee::FnValue(d, _),
396 ) => facts.edges.push(Edge {
397 name: d.name.display(),
398 key: d.span,
399 at: e.span,
400 }),
401 _ => {}
402 }
403 });
404 facts
405}
406
407/// Every expression of `b`, lambdas included. A block
408/// reached through [`expr_children`] would lose its statements' kind, so
409/// `Block`, `If` and `Match` are descended by hand, as `block_needs_exec` does.
410fn visit_block<'a>(b: &'a Block, f: &mut dyn FnMut(&'a bynk_syntax::ast::Expr)) {
411 for s in &b.statements {
412 visit_stmt(s, f);
413 }
414 visit_expr(&b.tail, f);
415}
416
417fn visit_stmt<'a>(s: &'a Statement, f: &mut dyn FnMut(&'a bynk_syntax::ast::Expr)) {
418 match s {
419 Statement::Let(l) | Statement::EffectLet(l) => visit_expr(&l.value, f),
420 Statement::Expect(a) => visit_expr(&a.value, f),
421 Statement::Do(d) => visit_expr(&d.value, f),
422 Statement::Assign(a) => visit_expr(&a.value, f),
423 Statement::Advance(a) => visit_expr(&a.amount, f),
424 Statement::Par(p) => {
425 for s in &p.statements {
426 visit_stmt(s, f);
427 }
428 }
429 }
430}
431
432fn visit_expr<'a>(e: &'a bynk_syntax::ast::Expr, f: &mut dyn FnMut(&'a bynk_syntax::ast::Expr)) {
433 f(e);
434 match &e.kind {
435 ExprKind::Block(b) => visit_block(b, f),
436 ExprKind::If {
437 cond,
438 then_block,
439 else_block,
440 } => {
441 visit_expr(cond, f);
442 visit_block(then_block, f);
443 visit_block(else_block, f);
444 }
445 ExprKind::Match { discriminant, arms } => {
446 visit_expr(discriminant, f);
447 for a in arms {
448 if let Some(g) = &a.guard {
449 visit_expr(g, f);
450 }
451 match &a.body {
452 MatchBody::Expr(e) => visit_expr(e, f),
453 MatchBody::Block(b) => visit_block(b, f),
454 }
455 }
456 }
457 _ => {
458 for c in expr_children(e) {
459 visit_expr(c, f);
460 }
461 }
462 }
463}
464
465/// A shared snapshot, as carried on a [`TypedCommons`].
466pub type SharedExecPlan = Arc<ExecPlan>;