telltale-types 14.0.0

Core session types for Telltale - matching Lean definitions
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Local Type Merging for Projection
//!
//! This module implements the merge operation for local types, which is essential
//! for correct projection of global types to local types when a role is not
//! involved in a choice.
//!
//! Based on: "A Very Gentle Introduction to Multiparty Session Types" (Yoshida & Gheri)
//!
//! # Merge Semantics
//!
//! When projecting a global type `G` with a choice made by role `p` onto a role `q`
//! that is not `p` and doesn't receive the choice, we need to merge the projections
//! of all branches:
//!
//! ```text
//! G = p → r : {l₁.G₁, l₂.G₂}    (q ≠ p, q ≠ r)
//! G↓q = merge(G₁↓q, G₂↓q)
//! ```
//!
//! # Merge Rules
//!
//! The merge operation `T₁ ⊔ T₂` is defined as:
//!
//! 1. `end ⊔ end = end`
//! 2. `!q{lᵢ.Tᵢ} ⊔ !q{l'ⱼ.T'ⱼ}` requires **identical** label sets (fails if different)
//! 3. `?p{lᵢ.Tᵢ} ⊔ ?p{l'ⱼ.T'ⱼ} = ?p{(lᵢ.Tᵢ) ∪ (l'ⱼ.T'ⱼ)}` unions labels
//! 4. `μt.T ⊔ μt.T' = μt.(T ⊔ T')` if T and T' use the same variable
//! 5. `t ⊔ t = t` for type variables
//!
//! # Lean Correspondence
//!
//! This implementation corresponds to `lean/Choreography/Projection/`:
//! - `merge_send_branches` ↔ Lean's `LocalTypeR.mergeSendSorted`
//! - `merge_recv_branches` ↔ Lean's `LocalTypeR.mergeRecvSorted`
//!
//! The key difference between send and recv merge:
//! - **Send merge**: Requires identical label sets. A non-participant cannot choose
//!   different outgoing messages based on a choice it didn't observe.
//! - **Recv merge**: Unions label sets. A non-participant can handle any incoming
//!   message regardless of which branch was taken.

use crate::{Label, LocalTypeR};
use std::collections::BTreeMap;
use thiserror::Error;

/// Errors that can occur during type merging
#[derive(Debug, Clone, Error)]
pub enum MergeError {
    /// Cannot merge End with a non-End type
    #[error("cannot merge end with non-end type: {0:?}")]
    EndMismatch(LocalTypeR),

    /// Cannot merge types with different partners
    #[error("partner mismatch in merge: expected {expected}, found {found}")]
    PartnerMismatch { expected: String, found: String },

    /// Cannot merge types with different directions (send vs recv)
    #[error("direction mismatch in merge: cannot merge send with recv")]
    DirectionMismatch,

    /// Labels with the same name have incompatible continuations
    #[error("incompatible continuations for label '{label}'")]
    IncompatibleContinuations { label: String },

    /// Labels with the same name have incompatible payload annotations
    #[error("payload annotation mismatch for label '{label}': left={left}, right={right}")]
    PayloadAnnotationMismatch {
        label: String,
        left: String,
        right: String,
    },

    /// Send branches have different label sets (not allowed for internal choice)
    #[error("send branch label mismatch: cannot merge sends with different labels '{left}' vs '{right}'")]
    SendLabelMismatch { left: String, right: String },

    /// Send branches have different number of labels
    #[error("send branch count mismatch: {left} labels vs {right} labels")]
    SendBranchCountMismatch { left: usize, right: usize },

    /// Cannot merge recursive types with different variable names
    #[error("recursive variable mismatch: expected {expected}, found {found}")]
    RecursiveVariableMismatch { expected: String, found: String },

    /// Cannot merge type variables with different names
    #[error("type variable mismatch: expected {expected}, found {found}")]
    VariableMismatch { expected: String, found: String },

    /// Merge of these types is not defined
    #[error("cannot merge incompatible types")]
    IncompatibleTypes,
}

/// Result type for merge operations
pub type MergeResult = Result<LocalTypeR, MergeError>;

/// Merge two local types.
///
/// This is the main entry point for the merge algorithm.
/// Returns `Ok(merged)` if the types can be merged, or `Err(error)` if they
/// have incompatible structure.
///
/// # Errors
///
/// Returns [`MergeError`] if the types have incompatible structure (different
/// partners, mismatched labels for sends, incompatible recursive variables, etc.).
///
/// # Examples
///
/// ```
/// use telltale_types::{merge, can_merge, LocalTypeR, Label};
///
/// // Merging identical send types succeeds
/// let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
/// let t2 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
/// let merged = merge(&t1, &t2).unwrap();
/// assert_eq!(merged, t1);
///
/// // Merging sends with DIFFERENT labels FAILS (Lean correspondence)
/// // A non-participant cannot choose different sends based on unseen choice
/// let s1 = LocalTypeR::send("B", Label::new("yes"), LocalTypeR::End);
/// let s2 = LocalTypeR::send("B", Label::new("no"), LocalTypeR::End);
/// assert!(!can_merge(&s1, &s2));
///
/// // Merging recvs with different labels SUCCEEDS (unions labels)
/// let r1 = LocalTypeR::recv("A", Label::new("yes"), LocalTypeR::End);
/// let r2 = LocalTypeR::recv("A", Label::new("no"), LocalTypeR::End);
/// let merged = merge(&r1, &r2).unwrap();
/// // merged = ?A{yes.end, no.end}
/// ```
pub fn merge(t1: &LocalTypeR, t2: &LocalTypeR) -> MergeResult {
    if t1 == t2 {
        return Ok(t1.clone());
    }

    match (t1, t2) {
        (LocalTypeR::End, LocalTypeR::End) => Ok(LocalTypeR::End),

        (LocalTypeR::End, other) | (other, LocalTypeR::End) => {
            Err(MergeError::EndMismatch(other.clone()))
        }

        (
            LocalTypeR::Send {
                partner: p1,
                branches: b1,
            },
            LocalTypeR::Send {
                partner: p2,
                branches: b2,
            },
        ) => merge_send_pair(p1, b1, p2, b2),

        (
            LocalTypeR::Recv {
                partner: p1,
                branches: b1,
            },
            LocalTypeR::Recv {
                partner: p2,
                branches: b2,
            },
        ) => merge_recv_pair(p1, b1, p2, b2),

        (
            LocalTypeR::Mu {
                var: v1,
                body: body1,
            },
            LocalTypeR::Mu {
                var: v2,
                body: body2,
            },
        ) => merge_recursive_pair(v1, body1, v2, body2),

        (LocalTypeR::Var(v1), LocalTypeR::Var(v2)) => merge_var_pair(v1, v2),

        (LocalTypeR::Send { .. }, LocalTypeR::Recv { .. })
        | (LocalTypeR::Recv { .. }, LocalTypeR::Send { .. }) => Err(MergeError::DirectionMismatch),

        _ => Err(MergeError::IncompatibleTypes),
    }
}

fn merge_send_pair(
    p1: &str,
    b1: &[(Label, Option<crate::ValType>, LocalTypeR)],
    p2: &str,
    b2: &[(Label, Option<crate::ValType>, LocalTypeR)],
) -> MergeResult {
    if p1 != p2 {
        return Err(MergeError::PartnerMismatch {
            expected: p1.to_string(),
            found: p2.to_string(),
        });
    }
    let merged_branches = merge_send_branches(b1, b2)?;
    Ok(LocalTypeR::Send {
        partner: p1.to_string(),
        branches: merged_branches,
    })
}

fn merge_recv_pair(
    p1: &str,
    b1: &[(Label, Option<crate::ValType>, LocalTypeR)],
    p2: &str,
    b2: &[(Label, Option<crate::ValType>, LocalTypeR)],
) -> MergeResult {
    if p1 != p2 {
        return Err(MergeError::PartnerMismatch {
            expected: p1.to_string(),
            found: p2.to_string(),
        });
    }
    let merged_branches = merge_recv_branches(b1, b2)?;
    Ok(LocalTypeR::Recv {
        partner: p1.to_string(),
        branches: merged_branches,
    })
}

fn merge_recursive_pair(v1: &str, body1: &LocalTypeR, v2: &str, body2: &LocalTypeR) -> MergeResult {
    if v1 != v2 {
        return Err(MergeError::RecursiveVariableMismatch {
            expected: v1.to_string(),
            found: v2.to_string(),
        });
    }
    let merged_body = merge(body1, body2)?;
    Ok(LocalTypeR::Mu {
        var: v1.to_string(),
        body: Box::new(merged_body),
    })
}

fn merge_var_pair(v1: &str, v2: &str) -> MergeResult {
    if v1 != v2 {
        return Err(MergeError::VariableMismatch {
            expected: v1.to_string(),
            found: v2.to_string(),
        });
    }
    Ok(LocalTypeR::Var(v1.to_string()))
}

fn merge_payload_annotations(
    label: &Label,
    left: &Option<crate::ValType>,
    right: &Option<crate::ValType>,
) -> Result<Option<crate::ValType>, MergeError> {
    if left == right {
        return Ok(left.clone());
    }
    Err(MergeError::PayloadAnnotationMismatch {
        label: label.name.clone(),
        left: format!("{left:?}"),
        right: format!("{right:?}"),
    })
}

/// Merge two sets of send branches (internal choice).
///
/// **Requires identical label sets.** This matches Lean's `mergeSendSorted`.
///
/// A non-participant role cannot choose different outgoing messages based on
/// a choice it didn't observe. If the two branch sets have different labels,
/// merge fails because the role would need to "know" which branch was taken.
///
/// # Example
///
/// - `!B{x.end} ⊔ !B{x.end}` = `!B{x.end}` ✓ (same labels)
/// - `!B{x.end} ⊔ !B{y.end}` = ERROR (different labels)
fn merge_send_branches(
    branches1: &[(Label, Option<crate::ValType>, LocalTypeR)],
    branches2: &[(Label, Option<crate::ValType>, LocalTypeR)],
) -> Result<Vec<(Label, Option<crate::ValType>, LocalTypeR)>, MergeError> {
    // Sort both branch lists for comparison
    let mut sorted1: Vec<_> = branches1.to_vec();
    let mut sorted2: Vec<_> = branches2.to_vec();
    sorted1.sort_by(|a, b| a.0.name.cmp(&b.0.name));
    sorted2.sort_by(|a, b| a.0.name.cmp(&b.0.name));

    // Must have same number of branches
    if sorted1.len() != sorted2.len() {
        return Err(MergeError::SendBranchCountMismatch {
            left: sorted1.len(),
            right: sorted2.len(),
        });
    }

    // Each branch must have the same label, merge continuations
    let mut result = Vec::with_capacity(sorted1.len());
    for ((label1, vt1, cont1), (label2, vt2, cont2)) in sorted1.iter().zip(sorted2.iter()) {
        // Labels must match exactly (name and sort)
        if label1.name != label2.name {
            return Err(MergeError::SendLabelMismatch {
                left: label1.name.clone(),
                right: label2.name.clone(),
            });
        }
        if label1.sort != label2.sort {
            return Err(MergeError::IncompatibleContinuations {
                label: label1.name.clone(),
            });
        }

        // Merge continuations
        let merged_cont =
            merge(cont1, cont2).map_err(|_| MergeError::IncompatibleContinuations {
                label: label1.name.clone(),
            })?;
        let merged_vt = merge_payload_annotations(label1, vt1, vt2)?;

        result.push((label1.clone(), merged_vt, merged_cont));
    }

    Ok(result)
}

/// Merge two sets of recv branches (external choice).
///
/// **Unions label sets.** This matches Lean's `mergeRecvSorted`.
///
/// A non-participant role can handle any incoming message regardless of which
/// branch was taken. Labels that appear in both sets have their continuations
/// merged; labels that appear in only one set are included as-is.
///
/// # Example
///
/// - `?A{x.end} ⊔ ?A{y.end}` = `?A{x.end, y.end}` ✓ (union of labels)
/// - `?A{x.T1} ⊔ ?A{x.T2}` = `?A{x.(T1 ⊔ T2)}` ✓ (same label, merge continuations)
fn merge_recv_branches(
    branches1: &[(Label, Option<crate::ValType>, LocalTypeR)],
    branches2: &[(Label, Option<crate::ValType>, LocalTypeR)],
) -> Result<Vec<(Label, Option<crate::ValType>, LocalTypeR)>, MergeError> {
    let mut result: BTreeMap<String, (Label, Option<crate::ValType>, LocalTypeR)> = BTreeMap::new();

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

    // Union with branches from the second set
    for (label, vt, cont) in branches2 {
        if let Some((existing_label, existing_vt, existing_cont)) = result.get(&label.name) {
            // Label exists in both - merge continuations
            let merged_cont =
                merge(existing_cont, cont).map_err(|_| MergeError::IncompatibleContinuations {
                    label: label.name.clone(),
                })?;
            // Labels must have matching sort
            if existing_label.sort != label.sort {
                return Err(MergeError::IncompatibleContinuations {
                    label: label.name.clone(),
                });
            }
            let merged_vt = merge_payload_annotations(label, existing_vt, vt)?;
            result.insert(label.name.clone(), (label.clone(), merged_vt, merged_cont));
        } else {
            // New label - add it (this is the key difference from send merge)
            result.insert(
                label.name.clone(),
                (label.clone(), vt.clone(), cont.clone()),
            );
        }
    }

    Ok(result.into_values().collect())
}

/// Merge multiple local types.
///
/// This is a convenience function for merging more than two types.
/// It folds the merge operation over the list.
///
/// # Errors
///
/// Returns [`MergeError::IncompatibleTypes`] if the list is empty, or
/// [`MergeError`] if any pair of types cannot be merged.
pub fn merge_all(types: &[LocalTypeR]) -> MergeResult {
    match types {
        [] => Err(MergeError::IncompatibleTypes),
        [single] => Ok(single.clone()),
        [first, rest @ ..] => {
            let mut result = first.clone();
            for t in rest {
                result = merge(&result, t)?;
            }
            Ok(result)
        }
    }
}

/// Check if two local types are mergeable without actually merging them.
///
/// This is useful for validation without constructing the merged type.
#[must_use]
pub fn can_merge(t1: &LocalTypeR, t2: &LocalTypeR) -> bool {
    merge(t1, t2).is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ValType;
    use assert_matches::assert_matches;

    #[test]
    fn test_merge_identical_end() {
        let result = merge(&LocalTypeR::End, &LocalTypeR::End).unwrap();
        assert_eq!(result, LocalTypeR::End);
    }

    #[test]
    fn test_merge_identical_send() {
        let t = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let result = merge(&t, &t).unwrap();
        assert_eq!(result, t);
    }

    // =========================================================================
    // Send merge tests - requires IDENTICAL label sets (Lean correspondence)
    // =========================================================================

    #[test]
    fn test_merge_sends_same_labels_succeeds() {
        // !B{x.end} ⊔ !B{x.end} = !B{x.end}
        let t1 = LocalTypeR::send("B", Label::new("x"), LocalTypeR::End);
        let t2 = LocalTypeR::send("B", Label::new("x"), LocalTypeR::End);

        let result = merge(&t1, &t2).unwrap();
        assert_matches!(result, LocalTypeR::Send { partner, branches } => {
            assert_eq!(partner, "B");
            assert_eq!(branches.len(), 1);
            assert_eq!(branches[0].0.name, "x");
        });
    }

    #[test]
    fn test_merge_sends_different_labels_fails() {
        // !B{x.end} ⊔ !B{y.end} = ERROR (different labels)
        // This matches Lean's mergeSendSorted behavior
        let t1 = LocalTypeR::send("B", Label::new("yes"), LocalTypeR::End);
        let t2 = LocalTypeR::send("B", Label::new("no"), LocalTypeR::End);

        let result = merge(&t1, &t2);
        assert!(
            matches!(result, Err(MergeError::SendLabelMismatch { .. })),
            "Expected SendLabelMismatch, got {:?}",
            result
        );
    }

    #[test]
    fn test_merge_sends_different_count_fails() {
        // !B{x.end, y.end} ⊔ !B{x.end} = ERROR (different count)
        let t1 = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![
                (Label::new("x"), None, LocalTypeR::End),
                (Label::new("y"), None, LocalTypeR::End),
            ],
        };
        let t2 = LocalTypeR::send("B", Label::new("x"), LocalTypeR::End);

        let result = merge(&t1, &t2);
        assert!(
            matches!(result, Err(MergeError::SendBranchCountMismatch { .. })),
            "Expected SendBranchCountMismatch, got {:?}",
            result
        );
    }

    #[test]
    fn test_merge_sends_payload_annotation_mismatch_fails() {
        let t1 = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![(Label::new("x"), Some(ValType::Nat), LocalTypeR::End)],
        };
        let t2 = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![(Label::new("x"), Some(ValType::Bool), LocalTypeR::End)],
        };

        let result = merge(&t1, &t2);
        assert!(matches!(
            result,
            Err(MergeError::PayloadAnnotationMismatch { .. })
        ));
    }

    #[test]
    fn test_merge_sends_payload_annotation_none_some_mismatch_fails() {
        let t1 = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![(Label::new("x"), None, LocalTypeR::End)],
        };
        let t2 = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![(Label::new("x"), Some(ValType::Nat), LocalTypeR::End)],
        };

        let result = merge(&t1, &t2);
        assert!(matches!(
            result,
            Err(MergeError::PayloadAnnotationMismatch { .. })
        ));
    }

    #[test]
    fn test_merge_sends_different_partners_fails() {
        let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::send("C", Label::new("msg"), LocalTypeR::End);

        let result = merge(&t1, &t2);
        assert!(matches!(result, Err(MergeError::PartnerMismatch { .. })));
    }

    // =========================================================================
    // Recv merge tests - UNIONS label sets (Lean correspondence)
    // =========================================================================

    #[test]
    fn test_merge_recvs_different_labels_succeeds() {
        // ?A{x.end} ⊔ ?A{y.end} = ?A{x.end, y.end}
        // This matches Lean's mergeRecvSorted behavior
        let t1 = LocalTypeR::recv("A", Label::new("x"), LocalTypeR::End);
        let t2 = LocalTypeR::recv("A", Label::new("y"), LocalTypeR::End);

        let result = merge(&t1, &t2).unwrap();
        assert_matches!(result, LocalTypeR::Recv { partner, branches } => {
            assert_eq!(partner, "A");
            assert_eq!(branches.len(), 2);
            let labels: Vec<_> = branches.iter().map(|(l, _, _)| l.name.as_str()).collect();
            assert!(labels.contains(&"x"));
            assert!(labels.contains(&"y"));
        });
    }

    #[test]
    fn test_merge_recvs_same_label_merges_continuations() {
        // ?A{x.T1} ⊔ ?A{x.T2} = ?A{x.(T1 ⊔ T2)}
        let t1 = LocalTypeR::recv(
            "A",
            Label::new("x"),
            LocalTypeR::send("B", Label::new("m"), LocalTypeR::End),
        );
        let t2 = LocalTypeR::recv(
            "A",
            Label::new("x"),
            LocalTypeR::send("B", Label::new("m"), LocalTypeR::End),
        );

        let result = merge(&t1, &t2).unwrap();
        assert_matches!(result, LocalTypeR::Recv { branches, .. } => {
            assert_eq!(branches.len(), 1);
            // Continuation should be merged (same as input since identical)
            assert_matches!(&branches[0].2, LocalTypeR::Send { partner, .. } => {
                assert_eq!(partner, "B");
            });
        });
    }

    #[test]
    fn test_merge_recvs_overlapping_labels() {
        // ?A{x.end, y.end} ⊔ ?A{y.end, z.end} = ?A{x.end, y.end, z.end}
        let t1 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![
                (Label::new("x"), None, LocalTypeR::End),
                (Label::new("y"), None, LocalTypeR::End),
            ],
        };
        let t2 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![
                (Label::new("y"), None, LocalTypeR::End),
                (Label::new("z"), None, LocalTypeR::End),
            ],
        };

        let result = merge(&t1, &t2).unwrap();
        assert_matches!(result, LocalTypeR::Recv { partner, branches } => {
            assert_eq!(partner, "A");
            assert_eq!(branches.len(), 3);
            let labels: Vec<_> = branches.iter().map(|(l, _, _)| l.name.as_str()).collect();
            assert!(labels.contains(&"x"));
            assert!(labels.contains(&"y"));
            assert!(labels.contains(&"z"));
        });
    }

    #[test]
    fn test_merge_recvs_overlapping_payload_annotation_mismatch_fails() {
        let t1 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![(Label::new("y"), Some(ValType::Nat), LocalTypeR::End)],
        };
        let t2 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![(Label::new("y"), Some(ValType::Bool), LocalTypeR::End)],
        };

        let result = merge(&t1, &t2);
        assert!(matches!(
            result,
            Err(MergeError::PayloadAnnotationMismatch { .. })
        ));
    }

    #[test]
    fn test_merge_recvs_overlapping_payload_annotation_match_succeeds() {
        let t1 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![(Label::new("y"), Some(ValType::Nat), LocalTypeR::End)],
        };
        let t2 = LocalTypeR::Recv {
            partner: "A".to_string(),
            branches: vec![(Label::new("y"), Some(ValType::Nat), LocalTypeR::End)],
        };

        let result = merge(&t1, &t2).expect("matching payload annotations should merge");
        assert_matches!(result, LocalTypeR::Recv { branches, .. } => {
            assert_eq!(branches.len(), 1);
            assert_eq!(branches[0].1, Some(ValType::Nat));
        });
    }

    // =========================================================================
    // Direction mismatch tests
    // =========================================================================

    #[test]
    fn test_merge_send_recv_fails() {
        let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::recv("B", Label::new("msg"), LocalTypeR::End);

        let result = merge(&t1, &t2);
        assert!(matches!(result, Err(MergeError::DirectionMismatch)));
    }

    // =========================================================================
    // merge_all tests
    // =========================================================================

    #[test]
    fn test_merge_all_sends_same_labels() {
        // All sends with same labels should succeed
        let types = vec![
            LocalTypeR::send("B", Label::new("x"), LocalTypeR::End),
            LocalTypeR::send("B", Label::new("x"), LocalTypeR::End),
            LocalTypeR::send("B", Label::new("x"), LocalTypeR::End),
        ];

        let result = merge_all(&types).unwrap();
        assert_matches!(result, LocalTypeR::Send { branches, .. } => {
            assert_eq!(branches.len(), 1);
            assert_eq!(branches[0].0.name, "x");
        });
    }

    #[test]
    fn test_merge_all_sends_different_labels_fails() {
        // Sends with different labels should fail
        let types = vec![
            LocalTypeR::send("B", Label::new("a"), LocalTypeR::End),
            LocalTypeR::send("B", Label::new("b"), LocalTypeR::End),
        ];

        let result = merge_all(&types);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_all_recvs_different_labels() {
        // Recvs with different labels should union
        let types = vec![
            LocalTypeR::recv("A", Label::new("a"), LocalTypeR::End),
            LocalTypeR::recv("A", Label::new("b"), LocalTypeR::End),
            LocalTypeR::recv("A", Label::new("c"), LocalTypeR::End),
        ];

        let result = merge_all(&types).unwrap();
        assert_matches!(result, LocalTypeR::Recv { branches, .. } => {
            assert_eq!(branches.len(), 3);
        });
    }

    // =========================================================================
    // can_merge tests
    // =========================================================================

    #[test]
    fn test_can_merge_sends_same_label() {
        let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        assert!(can_merge(&t1, &t2));
    }

    #[test]
    fn test_can_merge_sends_different_labels_false() {
        // Different labels for sends should NOT be mergeable
        let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::send("B", Label::new("other"), LocalTypeR::End);
        assert!(!can_merge(&t1, &t2));
    }

    #[test]
    fn test_can_merge_recvs_different_labels_true() {
        // Different labels for recvs SHOULD be mergeable
        let t1 = LocalTypeR::recv("A", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::recv("A", Label::new("other"), LocalTypeR::End);
        assert!(can_merge(&t1, &t2));
    }

    #[test]
    fn test_can_merge_send_recv_false() {
        let t1 = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::End);
        let t2 = LocalTypeR::recv("B", Label::new("msg"), LocalTypeR::End);
        assert!(!can_merge(&t1, &t2));
    }
}