logicaffeine_compile/concurrency/
classify.rs1use 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
24pub 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 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 direct_nondet_witnesses(stmt, out);
43 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
94fn collect_concurrent_print(stmts: &[Stmt], out: &mut Vec<NondetWitness>) {
106 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 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 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 if block_directly_shows(stmts) || calls_in_stmts(stmts).into_iter().any(&fn_prints) {
146 printers += 1;
147 }
148
149 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 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
185fn 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
224fn 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
255fn 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
266pub 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
285pub 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 writes: HashSet<Symbol>,
310 refs: HashSet<Symbol>,
312 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 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
466fn 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}