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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use super::*;
pub(crate) fn generate_runner_body(
local_type: &LocalType,
ctx: &mut RecursionContext,
) -> TokenStream {
match local_type {
LocalType::Send {
to,
message,
continuation,
} => {
let msg_type = &message.name;
let cont = generate_runner_body(continuation, ctx);
// Check if destination is a wildcard or range (multi-destination)
if let Some(index) = to.index() {
match index {
crate::ast::role::RoleIndex::Wildcard => {
// Generate broadcast to all instances of the role family
let family_name = to.name().to_string();
return quote! {
// Broadcast to all #family_name instances
let roles = adapter.resolve_family(#family_name)?;
if roles.is_empty() {
return Err(::telltale_choreography::ChoreographyError::EmptyRoleFamily(
#family_name.to_string()
).into());
}
let msg: #msg_type = adapter.provide_message(roles[0]).await?;
adapter.broadcast(&roles, msg).await?;
#cont
};
}
crate::ast::role::RoleIndex::Range(range) => {
// Generate broadcast to a range of role instances
let family_name = to.name().to_string();
let (start_expr, end_expr) = generate_range_exprs(range);
return quote! {
// Broadcast to #family_name range
let roles = adapter.resolve_range(#family_name, #start_expr, #end_expr)?;
if roles.is_empty() {
return Err(::telltale_choreography::ChoreographyError::EmptyRoleFamily(
#family_name.to_string()
).into());
}
let msg: #msg_type = adapter.provide_message(roles[0]).await?;
adapter.broadcast(&roles, msg).await?;
#cont
};
}
_ => {} // Fall through to normal send
}
}
// Normal single-destination send
let to_role = generate_role_id(to);
quote! {
// Send to #to
let msg: #msg_type = adapter.provide_message(#to_role).await?;
adapter.send(#to_role, msg).await?;
#cont
}
}
LocalType::Receive {
from,
message,
continuation,
} => {
let msg_type = &message.name;
let cont = generate_runner_body(continuation, ctx);
// Check if source is a wildcard or range (multi-source collect)
if let Some(index) = from.index() {
match index {
crate::ast::role::RoleIndex::Wildcard => {
// Generate collect from all instances of the role family
let family_name = from.name().to_string();
return quote! {
// Collect from all #family_name instances
let roles = adapter.resolve_family(#family_name)?;
if roles.is_empty() {
return Err(::telltale_choreography::ChoreographyError::EmptyRoleFamily(
#family_name.to_string()
).into());
}
let _msgs: Vec<#msg_type> = adapter.collect(&roles).await?;
output.metadata.messages_received += _msgs.len();
for msg in &_msgs {
let value = ::serde_json::to_value(msg).map_err(|e| {
::telltale_choreography::ChoreographyError::ExecutionError(
e.to_string(),
)
})?;
output.received.push(value);
}
#cont
};
}
crate::ast::role::RoleIndex::Range(range) => {
// Generate collect from a range of role instances
let family_name = from.name().to_string();
let (start_expr, end_expr) = generate_range_exprs(range);
return quote! {
// Collect from #family_name range
let roles = adapter.resolve_range(#family_name, #start_expr, #end_expr)?;
if roles.is_empty() {
return Err(::telltale_choreography::ChoreographyError::EmptyRoleFamily(
#family_name.to_string()
).into());
}
let _msgs: Vec<#msg_type> = adapter.collect(&roles).await?;
output.metadata.messages_received += _msgs.len();
for msg in &_msgs {
let value = ::serde_json::to_value(msg).map_err(|e| {
::telltale_choreography::ChoreographyError::ExecutionError(
e.to_string(),
)
})?;
output.received.push(value);
}
#cont
};
}
_ => {} // Fall through to normal receive
}
}
// Normal single-source receive
let from_role = generate_role_id(from);
quote! {
// Receive from #from
let _msg: #msg_type = adapter.recv(#from_role).await?;
output.metadata.messages_received += 1;
let value = ::serde_json::to_value(&_msg).map_err(|e| {
::telltale_choreography::ChoreographyError::ExecutionError(e.to_string())
})?;
output.received.push(value);
#cont
}
}
LocalType::Select { to, branches } => {
let to_role = generate_role_id(to);
// Generate match arms for each branch
let match_arms: Vec<TokenStream> = branches
.iter()
.map(|(label, cont_type)| {
let cont = generate_runner_body(cont_type, ctx);
quote! {
BranchLabel::#label => {
adapter.choose(#to_role, BranchLabel::#label).await?;
#cont
}
}
})
.collect();
let choice_variants: Vec<TokenStream> = branches
.iter()
.map(|(label, _)| {
quote! { BranchLabel::#label }
})
.collect();
quote! {
// Internal choice - select branch to send to #to
let choice = adapter.select_branch(&[#(#choice_variants),*]).await?;
output.choices.push(choice);
match choice {
#(#match_arms)*
}
}
}
LocalType::Branch { from, branches } => {
let from_role = generate_role_id(from);
// Generate match arms for each branch
let match_arms: Vec<TokenStream> = branches
.iter()
.map(|(label, cont_type)| {
let cont = generate_runner_body(cont_type, ctx);
quote! {
BranchLabel::#label => {
#cont
}
}
})
.collect();
quote! {
// External choice - receive branch selection from #from
let label = adapter.offer(#from_role).await?;
output.choices.push(label);
match label {
#(#match_arms)*
}
}
}
LocalType::LocalChoice { branches } => {
// Generate match arms for each branch
let match_arms: Vec<TokenStream> = branches
.iter()
.map(|(label, cont_type)| {
let cont = generate_runner_body(cont_type, ctx);
quote! {
BranchLabel::#label => {
#cont
}
}
})
.collect();
let choice_variants: Vec<TokenStream> = branches
.iter()
.map(|(label, _)| {
quote! { BranchLabel::#label }
})
.collect();
quote! {
// Local choice - no communication
let choice = adapter.select_branch(&[#(#choice_variants),*]).await?;
output.choices.push(choice);
match choice {
#(#match_arms)*
}
}
}
LocalType::Loop { condition, body } => {
let loop_body = generate_runner_body(body, ctx);
match condition {
Some(crate::ast::Condition::Count(n)) => {
quote! {
// Bounded loop (max #n iterations)
for _i in 0..#n {
#loop_body
}
}
}
Some(crate::ast::Condition::RoleDecides(role)) => {
// Note: RoleDecides loops are normally desugared to choice+rec at parse time.
// This case is only reached if someone constructs a LocalType::Loop with
// RoleDecides directly, bypassing the normal parse/desugar path.
let role_str = role.name().to_string();
quote! {
return Err(::telltale_choreography::ChoreographyError::ExecutionError(
format!(
"role-decided loops are not supported directly in generated runners. \
The parser should desugar 'loop decide by {}' to a choice+rec pattern. \
If you see this error, the LocalType was constructed without going \
through the normal parse path.",
#role_str
)
).into());
}
}
Some(crate::ast::Condition::Custom(expr)) => {
quote! {
// Loop with custom condition
while #expr {
#loop_body
}
}
}
Some(crate::ast::Condition::Fuel(n)) => {
quote! {
// Fuel-bounded loop (max #n iterations)
for _fuel in 0..#n {
#loop_body
}
}
}
Some(crate::ast::Condition::YieldAfter(n)) => {
quote! {
// Yield-after-N loop (max #n steps then yield)
for _step in 0..#n {
#loop_body
}
// Yield control after N steps
}
}
Some(crate::ast::Condition::YieldWhen(condition)) => {
quote! {
// Yield-when loop - INVARIANT: always breaks after one iteration
loop {
#loop_body
// Check yield condition
let _condition = #condition;
break; // Yield when condition met
}
}
}
None => {
quote! {
return Err(::telltale_choreography::ChoreographyError::ExecutionError(
"unbounded loops are not supported in generated runners. \
Use a bounded loop condition like: \
'loop decide by Role' (desugars to choice), \
'loop repeat N' (fixed iterations), \
'loop fuel N' (max iterations), or \
'loop yield_after N' (bounded steps)".to_string()
).into());
}
}
}
}
LocalType::Rec { label, body } => {
let label_str = label.to_string();
// Track recursion
ctx.enter_rec(&label_str);
let rec_body = generate_runner_body(body, ctx);
ctx.exit_rec();
let loop_label = syn::Lifetime::new(
&format!("'rec_{}", label_str),
proc_macro2::Span::call_site(),
);
quote! {
// Recursive type
#loop_label: loop {
#rec_body
break #loop_label;
}
}
}
LocalType::Var(label) => {
let label_str = label.to_string();
let loop_label = syn::Lifetime::new(
&format!("'rec_{}", label_str),
proc_macro2::Span::call_site(),
);
if ctx.is_in_rec(&label_str) {
quote! {
// Continue recursive loop
continue #loop_label;
}
} else {
quote! {
// Recursive variable (unbound) - this indicates a code generator bug
// The variable should have been bound by a Mu construct
return Err(::telltale_choreography::ChoreographyError::ExecutionError(
format!(
"unbound recursive variable '{}'; this indicates a code generator bug",
#label_str
)
).into());
}
}
}
LocalType::Timeout { duration, body } => {
let timeout_ms = duration.as_millis() as u64;
let timeout_body = generate_runner_body(body, ctx);
quote! {
// Timeout after #duration ms
let timeout_result = tokio::time::timeout(
std::time::Duration::from_millis(#timeout_ms),
async {
#timeout_body
Ok::<_, A::Error>(())
}
).await;
match timeout_result {
Ok(inner_result) => inner_result?,
Err(_elapsed) => {
return Err(::telltale_choreography::ChoreographyError::Timeout(
std::time::Duration::from_millis(#timeout_ms),
)
.into());
}
}
}
}
LocalType::End => {
quote! {
// End of protocol
}
}
}
}