1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Analysis utilities for free-algebra effect programs.
use super::{Effect, Program};
use crate::effects::RoleId;
use std::collections::HashSet;
/// Program analysis utilities
impl<R: RoleId, M> Program<R, M> {
/// Get all roles involved in this program
#[must_use]
pub fn roles_involved(&self) -> HashSet<R> {
let mut roles = HashSet::new();
self.collect_roles(&mut roles);
roles
}
fn collect_roles(&self, roles: &mut HashSet<R>) {
for effect in &self.effects {
match effect {
Effect::Send { to, .. } => {
roles.insert(*to);
}
Effect::Recv { from, .. } => {
roles.insert(*from);
}
Effect::Choose { at, .. } => {
roles.insert(*at);
}
Effect::Offer { from } => {
roles.insert(*from);
}
Effect::Branch {
choosing_role,
branches,
} => {
roles.insert(*choosing_role);
for (_, prog) in branches {
prog.collect_roles(roles);
}
}
Effect::Loop { body, .. } => {
body.collect_roles(roles);
}
Effect::Timeout {
at,
body,
on_timeout,
..
} => {
roles.insert(*at);
body.collect_roles(roles);
if let Some(timeout_body) = on_timeout {
timeout_body.collect_roles(roles);
}
}
Effect::Parallel { programs } => {
for prog in programs {
prog.collect_roles(roles);
}
}
Effect::Extension(ext) => {
for role in ext.participating_roles() {
roles.insert(role);
}
}
Effect::End => {}
}
}
}
/// Count the number of send operations
#[must_use]
pub fn send_count(&self) -> usize {
self.effects
.iter()
.map(|e| match e {
Effect::Send { .. } => 1,
Effect::Branch { branches, .. } => branches
.iter()
.map(|(_, p)| p.send_count())
.max()
.unwrap_or(0),
Effect::Loop { body, .. } => body.send_count(),
Effect::Timeout {
body, on_timeout, ..
} => {
let body_count = body.send_count();
let timeout_count = on_timeout.as_ref().map_or(0, |p| p.send_count());
body_count.max(timeout_count)
}
Effect::Parallel { programs } => programs.iter().map(Program::send_count).sum(),
_ => 0,
})
.sum()
}
/// Count the number of receive operations
#[must_use]
pub fn recv_count(&self) -> usize {
self.effects
.iter()
.map(|e| match e {
Effect::Recv { .. } => 1,
Effect::Branch { branches, .. } => branches
.iter()
.map(|(_, p)| p.recv_count())
.max()
.unwrap_or(0),
Effect::Loop { body, .. } => body.recv_count(),
Effect::Timeout {
body, on_timeout, ..
} => {
let body_count = body.recv_count();
let timeout_count = on_timeout.as_ref().map_or(0, |p| p.recv_count());
body_count.max(timeout_count)
}
Effect::Parallel { programs } => programs.iter().map(Program::recv_count).sum(),
_ => 0,
})
.sum()
}
/// Check if the program has any timeout effects
#[must_use]
pub fn has_timeouts(&self) -> bool {
self.effects
.iter()
.any(|e| matches!(e, Effect::Timeout { .. }))
}
/// Check if the program has any parallel effects
#[must_use]
pub fn has_parallel(&self) -> bool {
self.effects
.iter()
.any(|e| matches!(e, Effect::Parallel { .. }))
}
/// Validate that the program is well-formed
pub fn validate(&self) -> Result<(), ProgramError> {
for (idx, effect) in self.effects.iter().enumerate() {
match effect {
Effect::Branch { branches, .. } => {
if branches.is_empty() {
return Err(ProgramError::InvalidStructure(
"Branch must have at least one branch".to_string(),
));
}
for (_, prog) in branches {
prog.validate()?;
}
}
Effect::Loop { body, .. } => body.validate()?,
Effect::Timeout {
body, on_timeout, ..
} => {
body.validate()?;
if let Some(timeout_body) = on_timeout {
timeout_body.validate()?;
}
}
Effect::Parallel { programs } => {
if programs.is_empty() {
return Err(ProgramError::InvalidStructure(
"Parallel must contain at least one program".to_string(),
));
}
for prog in programs {
prog.validate()?;
}
}
Effect::Extension(_) => {
// Extensions are always valid - validation happens at runtime
}
Effect::End if idx + 1 != self.effects.len() => {
return Err(ProgramError::InvalidStructure(
"End must be the final effect".to_string(),
));
}
Effect::End => {}
_ => {}
}
}
Ok(())
}
}
/// Errors that can occur during program construction or analysis
#[derive(Debug, Clone, PartialEq)]
pub enum ProgramError {
/// Program contains invalid structure
InvalidStructure(String),
/// Program has unbalanced send/receive operations
UnbalancedCommunication,
/// Program contains unreachable effects
UnreachableCode,
}
impl std::fmt::Display for ProgramError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProgramError::InvalidStructure(msg) => write!(f, "Invalid program structure: {msg}"),
ProgramError::UnbalancedCommunication => {
write!(f, "Unbalanced send/receive operations")
}
ProgramError::UnreachableCode => write!(f, "Program contains unreachable code"),
}
}
}
impl std::error::Error for ProgramError {}
/// Result of interpreting a program
#[derive(Debug, Clone)]
pub struct InterpretResult<M> {
/// Messages received during execution
pub received_values: Vec<M>,
/// Final state of the interpreter
pub final_state: InterpreterState,
}
/// State of the program interpreter
#[derive(Debug, Clone, PartialEq)]
pub enum InterpreterState {
/// Program completed successfully
Completed,
/// Program was interrupted by timeout
Timeout,
/// Program failed with an error
Failed(String),
}
/// Type alias for any message type that can be used in programs
pub trait ProgramMessage: Clone + Send + Sync + std::fmt::Debug {}
impl<T: Clone + Send + Sync + std::fmt::Debug> ProgramMessage for T {}