telltale-language 17.0.0

Shared choreography frontend for Telltale DSL parsing, projection, and macro code generation
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Merging of labeled local types during projection.

use super::*;
use proc_macro2::Ident;

#[path = "merge_eq.rs"]
mod merge_eq;

/// A LocalType paired with its choice label.
///
/// Used during merging to preserve semantic choice labels when creating Branch nodes.
pub(super) struct LabeledLocalType {
    pub(super) label: Ident,
    pub(super) local_type: LocalType,
}

/// Merge two labeled LocalTypes, preserving choice labels.
///
/// When merging Receive operations with different messages, this uses the choice labels
/// instead of message type names for the resulting Branch node.
#[allow(clippy::too_many_lines)]
pub(super) fn merge_labeled_local_types(
    t1: &LabeledLocalType,
    t2: &LabeledLocalType,
) -> Result<LabeledLocalType, ProjectionError> {
    // Fast path: identical types (label doesn't matter if types are identical)
    if t1.local_type == t2.local_type {
        return Ok(LabeledLocalType {
            label: t1.label.clone(),
            local_type: t1.local_type.clone(),
        });
    }

    match (&t1.local_type, &t2.local_type) {
        // End merges with End
        (LocalType::End, LocalType::End) => Ok(LabeledLocalType {
            label: t1.label.clone(),
            local_type: LocalType::End,
        }),

        // End can merge with any type (End is neutral)
        (LocalType::End, other) => Ok(LabeledLocalType {
            label: t2.label.clone(),
            local_type: other.clone(),
        }),
        (other, LocalType::End) => Ok(LabeledLocalType {
            label: t1.label.clone(),
            local_type: other.clone(),
        }),

        // Send with same target - must have same message
        (
            LocalType::Send {
                to: to1,
                message: msg1,
                continuation: cont1,
            },
            LocalType::Send {
                to: to2,
                message: msg2,
                continuation: cont2,
            },
        ) if to1 == to2 => {
            if msg1.name == msg2.name {
                // Same message - merge continuations
                let merged_cont = merge_local_types(cont1, cont2)?;
                Ok(LabeledLocalType {
                    label: t1.label.clone(), // Label doesn't matter for Send
                    local_type: LocalType::Send {
                        to: to1.clone(),
                        message: msg1.clone(),
                        continuation: Box::new(merged_cont),
                    },
                })
            } else {
                // Different messages - error for sends
                Err(ProjectionError::MergeFailure(format!(
                    "cannot merge sends with different messages: '{}' vs '{}'",
                    msg1.name, msg2.name
                )))
            }
        }

        // Receive with same source - merge into Branch using CHOICE LABELS
        (
            LocalType::Receive {
                from: from1,
                message: msg1,
                continuation: cont1,
            },
            LocalType::Receive {
                from: from2,
                message: msg2,
                continuation: cont2,
            },
        ) if from1 == from2 => {
            if msg1.name == msg2.name {
                // Same message - merge continuations
                let merged_cont = merge_local_types(cont1, cont2)?;
                Ok(LabeledLocalType {
                    label: t1.label.clone(),
                    local_type: LocalType::Receive {
                        from: from1.clone(),
                        message: msg1.clone(),
                        continuation: Box::new(merged_cont),
                    },
                })
            } else {
                // Different messages - create a Branch with CHOICE LABELS (not message names!)
                let mut branches = vec![
                    (t1.label.clone(), *cont1.clone()), // Use choice label
                    (t2.label.clone(), *cont2.clone()), // Use choice label
                ];
                sort_branches_by_label(&mut branches);
                Ok(LabeledLocalType {
                    label: t1.label.clone(), // Arbitrary choice; branch contains both
                    local_type: LocalType::Branch {
                        from: from1.clone(),
                        branches,
                    },
                })
            }
        }

        // Merge Receive into existing Branch from same source
        (
            LocalType::Branch {
                from: from1,
                branches: br1,
            },
            LocalType::Receive {
                from: from2,
                message: _msg2,
                continuation: cont2,
            },
        ) if from1 == from2 => {
            let mut new_branches = br1.clone();
            // Check if label already exists
            if let Some((_, existing_cont)) = new_branches.iter_mut().find(|(l, _)| l == &t2.label)
            {
                *existing_cont = merge_local_types(existing_cont, cont2)?;
            } else {
                new_branches.push((t2.label.clone(), *cont2.clone())); // Use choice label
            }
            sort_branches_by_label(&mut new_branches);
            Ok(LabeledLocalType {
                label: t1.label.clone(),
                local_type: LocalType::Branch {
                    from: from1.clone(),
                    branches: new_branches,
                },
            })
        }

        // Symmetric case: Receive into Branch
        (
            LocalType::Receive {
                from: from1,
                message: _msg1,
                continuation: cont1,
            },
            LocalType::Branch {
                from: from2,
                branches: br2,
            },
        ) if from1 == from2 => {
            let mut new_branches = br2.clone();
            // Check if label already exists
            if let Some((_, existing_cont)) = new_branches.iter_mut().find(|(l, _)| l == &t1.label)
            {
                *existing_cont = merge_local_types(existing_cont, cont1)?;
            } else {
                new_branches.push((t1.label.clone(), *cont1.clone())); // Use choice label
            }
            sort_branches_by_label(&mut new_branches);
            Ok(LabeledLocalType {
                label: t2.label.clone(),
                local_type: LocalType::Branch {
                    from: from2.clone(),
                    branches: new_branches,
                },
            })
        }

        // Merge Branch with Branch from same source
        (
            LocalType::Branch {
                from: from1,
                branches: br1,
            },
            LocalType::Branch {
                from: from2,
                branches: br2,
            },
        ) if from1 == from2 => {
            let merged_branches = merge_branch_branches(br1, br2)?;
            Ok(LabeledLocalType {
                label: t1.label.clone(),
                local_type: LocalType::Branch {
                    from: from1.clone(),
                    branches: merged_branches,
                },
            })
        }

        // All other cases: fall back to unlabeled merge
        _ => {
            let merged = merge_local_types(&t1.local_type, &t2.local_type)?;
            Ok(LabeledLocalType {
                label: t1.label.clone(),
                local_type: merged,
            })
        }
    }
}

/// Merge two LocalTypes for projection.
///
/// This is a simplified merge operation for the extended LocalType.
/// For the full merge algorithm, see the `merge` module which works with `LocalTypeR`.
#[allow(clippy::too_many_lines)]
// RECURSION_SAFE: structural recursion over finite local-type pairs.
pub fn merge_local_types(t1: &LocalType, t2: &LocalType) -> Result<LocalType, ProjectionError> {
    // Fast path: identical types
    if t1 == t2 {
        return Ok(t1.clone());
    }

    match (t1, t2) {
        // End merges with End
        (LocalType::End, LocalType::End) => Ok(LocalType::End),

        // End can merge with any type (End is neutral)
        // This is lenient - strict mode would reject this
        (LocalType::End, other) | (other, LocalType::End) => Ok(other.clone()),

        // Send with same target - must have same message (Lean: mergeSendSorted)
        // A non-participant cannot choose which message to send based on a choice
        // they didn't observe. Different messages cause merge to fail.
        (
            LocalType::Send {
                to: to1,
                message: msg1,
                continuation: cont1,
            },
            LocalType::Send {
                to: to2,
                message: msg2,
                continuation: cont2,
            },
        ) if to1 == to2 => {
            if msg1.name == msg2.name {
                // Same message - merge continuations
                let merged_cont = merge_local_types(cont1, cont2)?;
                Ok(LocalType::Send {
                    to: to1.clone(),
                    message: msg1.clone(),
                    continuation: Box::new(merged_cont),
                })
            } else {
                // Different messages - this is an error for sends
                // Non-participant cannot choose based on unseen choice
                Err(ProjectionError::MergeFailure(format!(
                    "cannot merge sends with different messages: '{}' vs '{}'",
                    msg1.name, msg2.name
                )))
            }
        }

        // Receive with same source - merge into Branch if messages differ
        (
            LocalType::Receive {
                from: from1,
                message: msg1,
                continuation: cont1,
            },
            LocalType::Receive {
                from: from2,
                message: msg2,
                continuation: cont2,
            },
        ) if from1 == from2 => {
            if msg1.name == msg2.name {
                // Same message - merge continuations
                let merged_cont = merge_local_types(cont1, cont2)?;
                Ok(LocalType::Receive {
                    from: from1.clone(),
                    message: msg1.clone(),
                    continuation: Box::new(merged_cont),
                })
            } else {
                // Different messages - ERROR!
                // This function has no label information. If we're merging receives with
                // different messages from a choice, use merge_labeled_local_types instead.
                Err(ProjectionError::MergeFailure(format!(
                    "cannot merge receives with different messages without choice labels: '{}' vs '{}'. \
                     This likely indicates a protocol structure error or requires label-aware merging.",
                    msg1.name, msg2.name
                )))
            }
        }

        // Merge Receive into existing Branch from same source
        (
            LocalType::Branch { from: from1, .. },
            LocalType::Receive {
                from: from2,
                message: msg2,
                ..
            },
        ) if from1 == from2 => {
            // ERROR: Cannot merge Receive into Branch without label information
            // If the Branch has semantic labels, we don't know which branch this Receive belongs to
            Err(ProjectionError::MergeFailure(format!(
                "cannot merge receive of '{}' into branch without label information. \
                 Use merge_labeled_local_types for choice continuations.",
                msg2.name
            )))
        }

        // Merge Branch with Branch from same source (recv semantics - union labels)
        (
            LocalType::Branch {
                from: from1,
                branches: br1,
            },
            LocalType::Branch {
                from: from2,
                branches: br2,
            },
        ) if from1 == from2 => {
            let merged_branches = merge_branch_branches(br1, br2)?;
            Ok(LocalType::Branch {
                from: from1.clone(),
                branches: merged_branches,
            })
        }

        // Symmetric case: Receive into Branch
        (
            LocalType::Receive {
                from: from1,
                message: msg1,
                ..
            },
            LocalType::Branch { from: from2, .. },
        ) if from1 == from2 => {
            // ERROR: Cannot merge Receive into Branch without label information
            Err(ProjectionError::MergeFailure(format!(
                "cannot merge receive of '{}' into branch without label information. \
                 Use merge_labeled_local_types for choice continuations.",
                msg1.name
            )))
        }

        // Select with same target - must have identical label sets (send semantics)
        // A non-participant cannot choose which option to select based on an unseen choice
        (
            LocalType::Select {
                to: to1,
                branches: br1,
            },
            LocalType::Select {
                to: to2,
                branches: br2,
            },
        ) if to1 == to2 => {
            let merged_branches = merge_select_branches(br1, br2)?;
            Ok(LocalType::Select {
                to: to1.clone(),
                branches: merged_branches,
            })
        }

        // Rec with same label
        (
            LocalType::Rec {
                label: l1,
                body: b1,
            },
            LocalType::Rec {
                label: l2,
                body: b2,
            },
        ) if l1 == l2 => {
            let merged_body = merge_local_types(b1, b2)?;
            Ok(LocalType::Rec {
                label: l1.clone(),
                body: Box::new(merged_body),
            })
        }

        // Var with same label
        (LocalType::Var(v1), LocalType::Var(v2)) if v1 == v2 => Ok(LocalType::Var(v1.clone())),

        // Loop with same condition
        (
            LocalType::Loop {
                condition: c1,
                body: b1,
            },
            LocalType::Loop {
                condition: c2,
                body: b2,
            },
        ) if conditions_equal(c1, c2) => {
            let merged_body = merge_local_types(b1, b2)?;
            Ok(LocalType::Loop {
                condition: c1.clone(),
                body: Box::new(merged_body),
            })
        }

        // All other combinations are incompatible
        _ => Err(ProjectionError::MergeFailure(
            "incompatible local types in merge".to_string(),
        )),
    }
}

/// Merge two sets of labeled branches for Select types (send semantics).
///
/// Select merge requires IDENTICAL label sets. This matches Lean's `mergeSendSorted`
/// semantics: a non-participant cannot choose which option to select based on
/// an unseen choice.
fn merge_select_branches(
    branches1: &[(proc_macro2::Ident, LocalType)],
    branches2: &[(proc_macro2::Ident, LocalType)],
) -> Result<Vec<(proc_macro2::Ident, LocalType)>, ProjectionError> {
    // Sort both branch lists for comparison
    let mut sorted1: Vec<_> = branches1.to_vec();
    let mut sorted2: Vec<_> = branches2.to_vec();
    sorted1.sort_by_key(|a| a.0.to_string());
    sorted2.sort_by_key(|a| a.0.to_string());

    // Must have same number of branches
    if sorted1.len() != sorted2.len() {
        return Err(ProjectionError::MergeFailure(format!(
            "select branch count mismatch: {} vs {}",
            sorted1.len(),
            sorted2.len()
        )));
    }

    // Each branch must have the same label, merge continuations
    let mut result = Vec::with_capacity(sorted1.len());
    for ((label1, cont1), (label2, cont2)) in sorted1.iter().zip(sorted2.iter()) {
        if label1 != label2 {
            return Err(ProjectionError::MergeFailure(format!(
                "select branch label mismatch: '{}' vs '{}'",
                label1, label2
            )));
        }
        let merged_cont = merge_local_types(cont1, cont2)?;
        result.push((label1.clone(), merged_cont));
    }

    Ok(result)
}

/// Merge two sets of labeled branches for Branch types (recv semantics).
///
/// Branch merge UNIONS label sets. This matches Lean's `mergeRecvSorted`
/// semantics: a non-participant can receive any label regardless of which
/// branch was taken.
fn merge_branch_branches(
    branches1: &[(proc_macro2::Ident, LocalType)],
    branches2: &[(proc_macro2::Ident, LocalType)],
) -> Result<Vec<(proc_macro2::Ident, LocalType)>, ProjectionError> {
    use std::collections::HashMap;

    let mut result: HashMap<String, (proc_macro2::Ident, LocalType)> = HashMap::new();

    // Add all branches from the first set
    for (label, cont) in branches1 {
        result.insert(label.to_string(), (label.clone(), cont.clone()));
    }

    // Merge with branches from the second set
    for (label, cont) in branches2 {
        let label_str = label.to_string();
        if let Some((_, existing_cont)) = result.get(&label_str) {
            // Label exists - merge continuations
            let merged_cont = merge_local_types(existing_cont, cont)?;
            result.insert(label_str, (label.clone(), merged_cont));
        } else {
            // New label - add it
            result.insert(label_str, (label.clone(), cont.clone()));
        }
    }

    // Convert back to vector, sorted by label name for determinism
    let mut branches: Vec<_> = result.into_values().collect();
    branches.sort_by_key(|a| a.0.to_string());

    Ok(branches)
}

fn sort_branches_by_label(branches: &mut [(proc_macro2::Ident, LocalType)]) {
    branches.sort_by_key(|a| a.0.to_string());
}

/// Compare two optional conditions for equality.
///
/// Since `Condition::Custom` contains `TokenStream` which doesn't implement
/// `PartialEq`, we compare Custom conditions conservatively (always different).
fn conditions_equal(
    c1: &Option<crate::ast::protocol::Condition>,
    c2: &Option<crate::ast::protocol::Condition>,
) -> bool {
    use crate::ast::protocol::Condition;

    match (c1, c2) {
        (None, None) => true,
        (Some(Condition::Count(n1)), Some(Condition::Count(n2))) => n1 == n2,
        (Some(Condition::RoleDecides(r1)), Some(Condition::RoleDecides(r2))) => r1 == r2,
        // Custom conditions are incomparable (TokenStream doesn't impl PartialEq)
        (Some(Condition::Custom(_)), Some(Condition::Custom(_))) => false,
        _ => false,
    }
}

// Helper to compare LocalTypes for equality