Skip to main content

logicaffeine_compile/concurrency/
classify.rs

1//! Determinacy classifier — a whole-program AST walk.
2//!
3//! Mirrors the shape of `codegen::detection::requires_async`. A program
4//! is [`Determinacy::Nondeterminate`] iff a nondeterminism source
5//! (`Select`/`After`/`Try`/`Stop`) appears anywhere in the program — including
6//! function bodies, which is how transitivity through `Call`/`LaunchTask` is
7//! covered: the construct lives in the callee's body and is found by the scan.
8//!
9//! Soundness: this never reports `Determinate` for a program that can make a
10//! nondeterministic choice (the scan visits every reachable construct). It is a
11//! deliberate *over-approximation* in one direction only — a nondeterminism
12//! construct sitting in a defined-but-never-called function is conservatively
13//! counted; a future call-graph reachability refinement can tighten that without
14//! weakening soundness.
15
16use std::collections::{HashMap, HashSet};
17
18use crate::analysis::callgraph::calls_in_stmts;
19use crate::ast::stmt::{Expr, SelectBranch, Stmt};
20use crate::intern::Symbol;
21
22use super::model::{direct_nondet_witnesses, Determinacy, NondetKind, NondetWitness};
23
24/// Classify the determinacy of a whole program.
25pub fn classify_program(stmts: &[Stmt]) -> Determinacy {
26    let mut witnesses = Vec::new();
27    for stmt in stmts {
28        collect_witnesses_stmt(stmt, &mut witnesses);
29    }
30    // A whole-program source the per-statement scan cannot see: two concurrent
31    // threads racing on the shared stdout sink.
32    collect_concurrent_print(stmts, &mut witnesses);
33    if witnesses.is_empty() {
34        Determinacy::Determinate
35    } else {
36        Determinacy::Nondeterminate { witnesses }
37    }
38}
39
40fn collect_witnesses_stmt(stmt: &Stmt, out: &mut Vec<NondetWitness>) {
41    // What this statement is, directly.
42    direct_nondet_witnesses(stmt, out);
43    // Descend into every nested block.
44    match stmt {
45        Stmt::If {
46            then_block,
47            else_block,
48            ..
49        } => {
50            for s in *then_block {
51                collect_witnesses_stmt(s, out);
52            }
53            if let Some(eb) = else_block {
54                for s in *eb {
55                    collect_witnesses_stmt(s, out);
56                }
57            }
58        }
59        Stmt::While { body, .. }
60        | Stmt::Repeat { body, .. }
61        | Stmt::Zone { body, .. }
62        | Stmt::FunctionDef { body, .. } => {
63            for s in *body {
64                collect_witnesses_stmt(s, out);
65            }
66        }
67        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
68            for s in *tasks {
69                collect_witnesses_stmt(s, out);
70            }
71        }
72        Stmt::Inspect { arms, .. } => {
73            for arm in arms.iter() {
74                for s in arm.body.iter() {
75                    collect_witnesses_stmt(s, out);
76                }
77            }
78        }
79        Stmt::Select { branches } => {
80            for branch in branches {
81                match branch {
82                    SelectBranch::Receive { body, .. } | SelectBranch::Timeout { body, .. } => {
83                        for s in body.iter() {
84                            collect_witnesses_stmt(s, out);
85                        }
86                    }
87                }
88            }
89        }
90        _ => {}
91    }
92}
93
94// ─── Concurrent-print (stdout race) analysis ────────────────────────────────
95//
96// Kahn determinacy proves channel *histories* are schedule-independent, but it
97// says nothing about stdout — a shared sink every thread writes to. If two or
98// more concurrently-running threads (the main flow, spawned tasks, `Concurrent`/
99// `Parallel` branches) can each reach a `Show`, the *interleaving* of their lines
100// is a race. We count print-capable concurrent threads; two or more ⇒ a
101// `ConcurrentPrint` witness. The count is a sound over-approximation: we never
102// under-count a printing thread, so a racy program is never called Determinate.
103
104/// Append a `ConcurrentPrint` witness when ≥2 concurrent threads can print.
105fn collect_concurrent_print(stmts: &[Stmt], out: &mut Vec<NondetWitness>) {
106    // Index every function body (defs may nest in Main or other functions).
107    let mut fn_bodies: HashMap<Symbol, &[Stmt]> = HashMap::new();
108    for_each_stmt(stmts, &mut |s| {
109        if let Stmt::FunctionDef { name, body, .. } = s {
110            fn_bodies.insert(*name, body);
111        }
112    });
113
114    // Functions whose OWN body directly reaches a `Show` (recursing ordinary
115    // control flow, but not across call / spawn / definition boundaries).
116    let direct_show_fns: HashSet<Symbol> = fn_bodies
117        .iter()
118        .filter(|(_, body)| block_directly_shows(body))
119        .map(|(name, _)| *name)
120        .collect();
121
122    // Does executing `f` reach a print, following SYNCHRONOUS calls (a spawn is a
123    // different thread, counted on its own)?
124    let fn_prints = |start: Symbol| -> bool {
125        let mut stack = vec![start];
126        let mut seen = HashSet::new();
127        while let Some(g) = stack.pop() {
128            if !seen.insert(g) {
129                continue;
130            }
131            if direct_show_fns.contains(&g) {
132                return true;
133            }
134            if let Some(body) = fn_bodies.get(&g) {
135                stack.extend(calls_in_stmts(body));
136            }
137        }
138        false
139    };
140
141    let mut printers = 0usize;
142
143    // Thread 1 — the root (Main top-level flow): a direct top-level `Show`, or a
144    // synchronous call that reaches a printer.
145    if block_directly_shows(stmts) || calls_in_stmts(stmts).into_iter().any(&fn_prints) {
146        printers += 1;
147    }
148
149    // Each spawned task is its own concurrent thread.
150    let mut launch_targets: Vec<Symbol> = Vec::new();
151    for_each_stmt(stmts, &mut |s| match s {
152        Stmt::LaunchTask { function, .. } | Stmt::LaunchTaskWithHandle { function, .. } => {
153            launch_targets.push(*function)
154        }
155        _ => {}
156    });
157    for f in launch_targets {
158        if printers >= 2 {
159            break;
160        }
161        if fn_prints(f) {
162            printers += 1;
163        }
164    }
165
166    // Each `Show` inside a `Concurrent`/`Parallel` block is a concurrent writer
167    // in its own right (sound over-approximation — every such line is a racer).
168    if printers < 2 {
169        let mut blocks: Vec<&[Stmt]> = Vec::new();
170        for_each_stmt(stmts, &mut |s| {
171            if let Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } = s {
172                blocks.push(tasks);
173            }
174        });
175        printers += blocks.iter().map(|b| count_shows(b)).sum::<usize>();
176    }
177
178    if printers >= 2 {
179        out.push(NondetWitness {
180            kind: NondetKind::ConcurrentPrint,
181        });
182    }
183}
184
185/// Visit every statement in the tree (recursing all nested blocks).
186fn for_each_stmt<'a>(stmts: &'a [Stmt<'a>], f: &mut impl FnMut(&'a Stmt<'a>)) {
187    for s in stmts {
188        f(s);
189        match s {
190            Stmt::If {
191                then_block,
192                else_block,
193                ..
194            } => {
195                for_each_stmt(then_block, f);
196                if let Some(eb) = else_block {
197                    for_each_stmt(eb, f);
198                }
199            }
200            Stmt::While { body, .. }
201            | Stmt::Repeat { body, .. }
202            | Stmt::Zone { body, .. }
203            | Stmt::FunctionDef { body, .. } => for_each_stmt(body, f),
204            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => for_each_stmt(tasks, f),
205            Stmt::Inspect { arms, .. } => {
206                for arm in arms.iter() {
207                    for_each_stmt(arm.body, f);
208                }
209            }
210            Stmt::Select { branches } => {
211                for branch in branches {
212                    match branch {
213                        SelectBranch::Receive { body, .. } | SelectBranch::Timeout { body, .. } => {
214                            for_each_stmt(body, f)
215                        }
216                    }
217                }
218            }
219            _ => {}
220        }
221    }
222}
223
224/// Does this block directly reach a `Show`, recursing ordinary control flow but
225/// NOT crossing call / spawn / function-definition / concurrent-block boundaries
226/// (those are handled as their own threads)?
227fn block_directly_shows(stmts: &[Stmt]) -> bool {
228    stmts.iter().any(stmt_directly_shows)
229}
230
231fn stmt_directly_shows(stmt: &Stmt) -> bool {
232    match stmt {
233        Stmt::Show { .. } => true,
234        Stmt::If {
235            then_block,
236            else_block,
237            ..
238        } => {
239            block_directly_shows(then_block)
240                || else_block.map_or(false, |eb| block_directly_shows(eb))
241        }
242        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
243            block_directly_shows(body)
244        }
245        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| block_directly_shows(arm.body)),
246        Stmt::Select { branches } => branches.iter().any(|branch| match branch {
247            SelectBranch::Receive { body, .. } | SelectBranch::Timeout { body, .. } => {
248                block_directly_shows(body)
249            }
250        }),
251        _ => false,
252    }
253}
254
255/// Count every `Show` anywhere in the subtree.
256fn count_shows(stmts: &[Stmt]) -> usize {
257    let mut n = 0;
258    for_each_stmt(stmts, &mut |s| {
259        if matches!(s, Stmt::Show { .. }) {
260            n += 1;
261        }
262    });
263    n
264}
265
266/// Are the branches of a `Parallel`/`Concurrent` block data-independent?
267///
268/// Conservative (errs toward "dependent"): two branches conflict if they touch
269/// the same `Pipe` channel symbol, both mutate the same variable, or one mutates
270/// a variable the other references. Independent branches are determinate (their
271/// fork-join is order-free); dependent branches that share non-CRDT mutable state
272/// are a data race the Send/escape analysis (Phase 4) will reject.
273pub fn branches_independent(tasks: &[Stmt]) -> bool {
274    let infos: Vec<BranchInfo> = tasks.iter().map(BranchInfo::of).collect();
275    for i in 0..infos.len() {
276        for j in (i + 1)..infos.len() {
277            if infos[i].conflicts_with(&infos[j]) {
278                return false;
279            }
280        }
281    }
282    true
283}
284
285/// Do any two branches of a `Parallel`/`Concurrent` block share *non-channel*
286/// mutable state — a variable or collection one writes and another reads or
287/// writes? This is the data-race predicate the Send/escape analysis rejects on.
288///
289/// It deliberately differs from [`branches_independent`] on one axis: a shared
290/// `Pipe` is **not** a violation here. A channel is safe under concurrent access
291/// (it is the sanctioned message-passing mechanism), so branches that only
292/// communicate through a pipe are race-free — they are merely *nondeterminate*,
293/// which is the determinacy classifier's concern, not safety's.
294pub fn branches_share_mutable_state(tasks: &[Stmt]) -> bool {
295    let infos: Vec<BranchInfo> = tasks.iter().map(BranchInfo::of).collect();
296    for i in 0..infos.len() {
297        for j in (i + 1)..infos.len() {
298            if infos[i].shares_mutable_state_with(&infos[j]) {
299                return true;
300            }
301        }
302    }
303    false
304}
305
306#[derive(Default)]
307struct BranchInfo {
308    /// Variables this branch mutates (Set/Push/Pop/SetIndex/Add/Remove targets).
309    writes: HashSet<Symbol>,
310    /// Variables this branch references in expressions.
311    refs: HashSet<Symbol>,
312    /// Pipe/channel symbols this branch sends to or receives from.
313    pipes: HashSet<Symbol>,
314}
315
316impl BranchInfo {
317    fn of(stmt: &Stmt) -> Self {
318        let mut info = BranchInfo::default();
319        info.scan_stmt(stmt);
320        info
321    }
322
323    fn conflicts_with(&self, other: &BranchInfo) -> bool {
324        !self.pipes.is_disjoint(&other.pipes) || self.shares_mutable_state_with(other)
325    }
326
327    /// The data-race core of [`Self::conflicts_with`], minus the channel axis: a
328    /// write/write or write/read overlap on a shared variable or collection.
329    fn shares_mutable_state_with(&self, other: &BranchInfo) -> bool {
330        !self.writes.is_disjoint(&other.writes)
331            || !self.writes.is_disjoint(&other.refs)
332            || !other.writes.is_disjoint(&self.refs)
333    }
334
335    fn scan_stmt(&mut self, stmt: &Stmt) {
336        match stmt {
337            Stmt::Let { value, .. } => self.scan_expr(value),
338            Stmt::Set { target, value } => {
339                self.writes.insert(*target);
340                self.scan_expr(value);
341            }
342            Stmt::Push { collection, value }
343            | Stmt::Add { collection, value }
344            | Stmt::Remove { collection, value } => {
345                self.note_mutated(collection);
346                self.scan_expr(value);
347            }
348            Stmt::Pop { collection, .. } => self.note_mutated(collection),
349            Stmt::SetIndex {
350                collection,
351                index,
352                value,
353            } => {
354                self.note_mutated(collection);
355                self.scan_expr(index);
356                self.scan_expr(value);
357            }
358            Stmt::Show { object, .. } => self.scan_expr(object),
359            Stmt::Return { value } => {
360                if let Some(v) = value {
361                    self.scan_expr(v);
362                }
363            }
364            Stmt::Call { args, .. } => {
365                for a in args.iter() {
366                    self.scan_expr(a);
367                }
368            }
369            Stmt::LaunchTask { args, .. } | Stmt::LaunchTaskWithHandle { args, .. } => {
370                for a in args.iter() {
371                    self.scan_expr(a);
372                }
373            }
374            Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
375                self.note_pipe(pipe);
376                self.scan_expr(value);
377            }
378            Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
379                self.note_pipe(pipe);
380            }
381            Stmt::If {
382                cond,
383                then_block,
384                else_block,
385            } => {
386                self.scan_expr(cond);
387                for s in *then_block {
388                    self.scan_stmt(s);
389                }
390                if let Some(eb) = else_block {
391                    for s in *eb {
392                        self.scan_stmt(s);
393                    }
394                }
395            }
396            Stmt::While { cond, body, .. } => {
397                self.scan_expr(cond);
398                for s in *body {
399                    self.scan_stmt(s);
400                }
401            }
402            Stmt::Repeat { iterable, body, .. } => {
403                self.scan_expr(iterable);
404                for s in *body {
405                    self.scan_stmt(s);
406                }
407            }
408            Stmt::Zone { body, .. } => {
409                for s in *body {
410                    self.scan_stmt(s);
411                }
412            }
413            _ => {}
414        }
415    }
416
417    fn note_mutated(&mut self, collection: &Expr) {
418        if let Some(root) = root_symbol(collection) {
419            self.writes.insert(root);
420        }
421    }
422
423    fn note_pipe(&mut self, pipe: &Expr) {
424        if let Expr::Identifier(sym) = pipe {
425            self.pipes.insert(*sym);
426        }
427    }
428
429    fn scan_expr(&mut self, expr: &Expr) {
430        match expr {
431            Expr::Identifier(sym) => {
432                self.refs.insert(*sym);
433            }
434            Expr::BinaryOp { left, right, .. } => {
435                self.scan_expr(left);
436                self.scan_expr(right);
437            }
438            Expr::Call { args, .. } => {
439                for a in args.iter() {
440                    self.scan_expr(a);
441                }
442            }
443            Expr::CallExpr { callee, args } => {
444                self.scan_expr(callee);
445                for a in args.iter() {
446                    self.scan_expr(a);
447                }
448            }
449            Expr::Index { collection, index } => {
450                self.scan_expr(collection);
451                self.scan_expr(index);
452            }
453            Expr::FieldAccess { object, .. } => self.scan_expr(object),
454            Expr::Length { collection } => self.scan_expr(collection),
455            Expr::Not { operand } => self.scan_expr(operand),
456            Expr::List(items) | Expr::Tuple(items) => {
457                for i in items.iter() {
458                    self.scan_expr(i);
459                }
460            }
461            _ => {}
462        }
463    }
464}
465
466/// The root variable a (possibly nested field-access) lvalue mutates.
467fn root_symbol(expr: &Expr) -> Option<Symbol> {
468    match expr {
469        Expr::Identifier(sym) => Some(*sym),
470        Expr::FieldAccess { object, .. } => root_symbol(object),
471        Expr::Index { collection, .. } => root_symbol(collection),
472        _ => None,
473    }
474}