telltale-runtime 17.0.0

Choreographic programming for Telltale - effect-based distributed protocols
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
//! Comprehensive tests for the choreographic DSL parser.
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

use telltale_runtime::ast::{LocalType, Protocol};
use telltale_runtime::compiler::parser::{parse_choreography_str, ParseError};
use telltale_runtime::compiler::projection::project;

#[test]
fn test_parse_simple_protocol() {
    let input = r"
protocol PingPong =
    roles Alice, Bob

    Alice -> Bob : Ping
    Bob -> Alice : Pong
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok(), "Failed to parse: {:?}", result.err());

    let choreo = result.unwrap();
    assert_eq!(choreo.name.to_string(), "PingPong");
    assert_eq!(choreo.roles.len(), 2);
}

#[test]
fn test_parse_canonical_timeout_surface() {
    let input = r#"
protocol TimedRequest =
  roles Client, Server
  timeout 5s Client at
    Server -> Client : Response
  on timeout =>
    Client -> Server : Cancel
"#;

    let choreo = parse_choreography_str(input).expect("canonical timeout should parse");
    assert!(matches!(choreo.protocol, Protocol::Timeout { .. }));
}

#[test]
fn test_reject_multiline_type_equals_surface() {
    let input = r#"
type AcceptError
  = NotFound

protocol Demo =
  roles A, B
  A -> B : Ping
"#;

    parse_choreography_str(input).expect_err("multiline type equals should fail");
}

#[test]
fn test_reject_multiline_protocol_equals_surface() {
    let input = r#"
protocol Demo
  =
  roles A, B
  A -> B : Ping
"#;

    parse_choreography_str(input).expect_err("multiline protocol equals should fail");
}

#[test]
fn test_projection_projects_authority_case_constructs() {
    let input = r#"
effect Runtime
  authoritative ready : Session -> Result CommitError ReadyWitness
  {
    class : authoritative
    progress : may_block
    region : fragment
    agreement_use : required
    reentrancy : reject_same_fragment
  }

protocol CommitFlow uses Runtime =
  roles Coordinator, Worker
  authoritative let readiness = check Runtime.ready(session)
  case readiness of
    | Ok(witness) =>
        Coordinator -> Worker : Commit(witness)
    | Err(reason) =>
        Coordinator -> Worker : Retry(reason)
"#;

    let choreo = parse_choreography_str(input).expect("parse should succeed");
    let coordinator = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Coordinator")
        .expect("coordinator role");
    let worker = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Worker")
        .expect("worker role");

    let coordinator_projection =
        project(&choreo, coordinator).expect("case projection should succeed");
    let worker_projection = project(&choreo, worker).expect("case projection should succeed");

    assert!(matches!(
        coordinator_projection,
        LocalType::LocalChoice { ref branches }
            if branches.iter().map(|(label, _)| label.to_string()).collect::<Vec<_>>()
                == vec!["Ok", "Err"]
    ));
    assert!(matches!(
        worker_projection,
        LocalType::Branch { ref from, ref branches }
            if from.name() == "Coordinator"
                && branches.iter().map(|(label, _)| label.to_string()).collect::<Vec<_>>()
                    == vec!["Err", "Ok"]
    ));
}

#[test]
fn test_projection_projects_timeout_constructs() {
    let input = r#"
protocol TimeoutFlow =
  roles Coordinator, Worker
  timeout 5s Coordinator at
    Worker -> Coordinator : Ready
  on timeout =>
    Coordinator -> Worker : Cancel
"#;

    let choreo = parse_choreography_str(input).expect("parse should succeed");
    let coordinator = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Coordinator")
        .expect("coordinator role");
    let worker = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Worker")
        .expect("worker role");

    let coordinator_projection =
        project(&choreo, coordinator).expect("timeout projection should succeed");
    let worker_projection = project(&choreo, worker).expect("timeout projection should succeed");

    assert!(matches!(
        coordinator_projection,
        LocalType::Timeout {
            body,
            on_timeout,
            on_cancel: None,
            ..
        } if matches!(
            (body.as_ref(), on_timeout.as_ref()),
            (
                LocalType::Receive { from, .. },
                LocalType::Send { to, .. },
            ) if from.name() == "Worker" && to.name() == "Worker"
        )
    ));
    assert!(matches!(
        worker_projection,
        LocalType::Timeout {
            body,
            on_timeout,
            on_cancel: None,
            ..
        } if matches!(
            (body.as_ref(), on_timeout.as_ref()),
            (
                LocalType::Send { to, .. },
                LocalType::Receive { from, .. },
            ) if to.name() == "Coordinator" && from.name() == "Coordinator"
        )
    ));
}

#[test]
fn test_projection_projects_evidence_binding_guards() {
    let input = r#"
effect Runtime
  authoritative ready : Session -> Result CommitError ReadyWitness
  {
    class : authoritative
    progress : may_block
    region : fragment
    agreement_use : required
    reentrancy : reject_same_fragment
  }

protocol GuardedChoice uses Runtime =
  roles Coordinator, Worker
  choice Coordinator at
    | Commit when check Runtime.ready(session) yields witness =>
        Coordinator -> Worker : Commit(witness)
    | Abort =>
        Coordinator -> Worker : Abort
"#;

    let choreo = parse_choreography_str(input).expect("parse should succeed");
    let worker = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Worker")
        .expect("worker role");

    let projection = project(&choreo, worker).expect("guarded choice should project directly");
    assert!(matches!(
        projection,
        LocalType::Branch { ref from, ref branches }
            if from.name() == "Coordinator" && branches.len() == 2
    ));
}

#[test]
fn test_projection_projects_authority_wrappers_through_continuation() {
    let input = r#"
protocol WrapperFlow =
  roles Coordinator, Worker
  let receipt = transfer Session from Coordinator to Worker
  publish receipt as DelegationRecorded
  materialize delegationProof from DelegationRecorded
  handoff acceptInvite to Worker with receipt
  dependent work SyncMembership(channel) required for acceptInvite
  Coordinator -> Worker : Commit
"#;

    let choreo = parse_choreography_str(input).expect("parse should succeed");
    let coordinator = choreo
        .roles
        .iter()
        .find(|role| role.name() == "Coordinator")
        .expect("coordinator role");

    let projection = project(&choreo, coordinator).expect("wrapper projection should succeed");
    assert!(matches!(
        projection,
        LocalType::Send { ref to, .. } if to.name() == "Worker"
    ));
}

#[test]
fn test_parse_three_party_protocol() {
    let input = r"
protocol ThreeParty =
    roles Alice, Bob, Carol

    Alice -> Bob : Hello
    Bob -> Carol : Forward
    Carol -> Alice : Response
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());

    let choreo = result.unwrap();
    assert_eq!(choreo.roles.len(), 3);
}

#[test]
fn test_parse_broadcast() {
    let input = r"
protocol Broadcast =
    roles Leader, Worker1, Worker2

    Leader ->* : Start
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse broadcast: {:?}",
        result.err()
    );

    // Verify the broadcast is correctly parsed with to_all populated
    let choreo = result.unwrap();
    assert_eq!(choreo.roles.len(), 3);

    // Check that the protocol is a Broadcast with correct to_all field
    use telltale_runtime::ast::Protocol;
    match &choreo.protocol {
        Protocol::Broadcast {
            from,
            to_all,
            message,
            ..
        } => {
            assert_eq!(from.name().to_string(), "Leader");
            assert_eq!(message.name.to_string(), "Start");
            // to_all should contain Worker1 and Worker2 (all roles except Leader)
            assert_eq!(
                to_all.len(),
                2,
                "Broadcast should target all roles except sender"
            );
            let recipient_names: Vec<String> =
                to_all.iter().map(|r| r.name().to_string()).collect();
            assert!(recipient_names.contains(&"Worker1".to_string()));
            assert!(recipient_names.contains(&"Worker2".to_string()));
            assert!(
                !recipient_names.contains(&"Leader".to_string()),
                "Sender should not be in to_all"
            );
        }
        _ => panic!("Expected Protocol::Broadcast, got {:?}", choreo.protocol),
    }
}

#[test]
fn test_parse_choice_two_branches() {
    let input = r"
protocol Choice =
    roles A, B

    A -> B : Propose

    choice B at
        | accept =>
            B -> A : Accept
        | reject =>
            B -> A : Reject
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_choice_three_branches() {
    let input = r"
protocol ThreeWayChoice =
    roles Client, Server

    choice Client at
        | get =>
            Client -> Server : Get
        | post =>
            Client -> Server : Post
        | delete =>
            Client -> Server : Delete
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_nested_choice() {
    let input = r"
protocol NestedChoice =
    roles A, B, C

    choice A at
        | path1 =>
            A -> B : First
            choice B at
                | inner1 =>
                    B -> C : InnerA
                | inner2 =>
                    B -> C : InnerB
        | path2 =>
            A -> C : Second
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_loop_with_count() {
    let input = r"
protocol LoopCount =
    roles Client, Server

    loop repeat 5
        Client -> Server : Request
        Server -> Client : Response
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_loop_with_role_decides() {
    let input = r"
protocol LoopRoleDecides =
    roles Client, Server

    loop decide by Client
        Client -> Server : Request
        Server -> Client : Response
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_loop_with_custom_condition() {
    let input = r#"
protocol LoopCustom =
    roles A, B

    loop while "has_more_data"
        A -> B : Data
"#;

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_loop_without_condition() {
    let input = r"
protocol InfiniteLoop =
    roles A, B

    loop forever
        A -> B : Tick
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_parallel() {
    let input = r"
protocol Parallel =
    roles A, B, C, D

    par
      | A -> B : Msg1
      | C -> D : Msg2
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_recursive() {
    let input = r"
protocol Recursive =
    roles A, B

    rec Loop
        A -> B : Data
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_recursive_with_continue() {
    let input = r"
protocol Recursive =
    roles A, B

    rec Loop
        A -> B : Ping
        B -> A : Pong
        continue Loop
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());

    use telltale_runtime::ast::Protocol;

    let choreo = result.unwrap();
    // Verify the rec body contains a continue
    match &choreo.protocol {
        Protocol::Rec { label, body } => {
            assert_eq!(label.to_string(), "Loop");
            // The body should be a Send -> Send -> Var chain
            match body.as_ref() {
                Protocol::Send { continuation, .. } => match continuation.as_ref() {
                    Protocol::Send { continuation, .. } => match continuation.as_ref() {
                        Protocol::Var(var_label) => {
                            assert_eq!(var_label.to_string(), "Loop");
                        }
                        other => panic!("Expected Var, got {:?}", other),
                    },
                    other => panic!("Expected Send, got {:?}", other),
                },
                other => panic!("Expected Send, got {:?}", other),
            }
        }
        other => panic!("Expected Rec, got {:?}", other),
    }
}

#[test]
fn test_parse_complex_protocol() {
    let input = r"
protocol ComplexProtocol =
    roles Buyer, Seller, Shipper

    Buyer -> Seller : Inquiry
    Seller -> Buyer : Quote

    choice Buyer at
        | order =>
            Buyer -> Seller : Order
            Seller -> Shipper : ShipRequest
            Shipper -> Buyer : Tracking

            loop decide by Buyer
                Buyer -> Shipper : StatusCheck
                Shipper -> Buyer : StatusUpdate

            Shipper -> Buyer : Delivered
            Buyer -> Seller : Confirmation
        | cancel =>
            Buyer -> Seller : Cancel
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse complex protocol: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_with_payload() {
    let input = r"
protocol WithPayload =
    roles A, B

    A -> B : Message(data : String)
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

// Error cases

#[test]
fn test_error_undefined_role_in_send() {
    let input = r"
protocol Invalid =
    roles Alice

    Alice -> Bob : Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(err, ParseError::UndefinedRole { ref role, .. } if role == "Bob"));

    // Verify error message includes span information
    let err_str = err.to_string();
    assert!(err_str.contains("Undefined role"));
    assert!(err_str.contains("Bob"));
    assert!(err_str.contains("-->")); // Rust-style error format
}

#[test]
fn test_error_undefined_role_in_choice() {
    let input = r"
protocol Invalid =
    roles Alice

    choice Bob at
        | opt =>
            Alice -> Alice : Self
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(err, ParseError::UndefinedRole { ref role, .. } if role == "Bob"));

    // Verify error message includes span information
    let err_str = err.to_string();
    assert!(err_str.contains("Undefined role"));
    assert!(err_str.contains("Bob"));
}

#[test]
fn test_error_undefined_role_in_loop_decides() {
    let input = r"
protocol Invalid =
    roles Alice

    loop decide by Bob
        Alice -> Alice : Msg
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(err, ParseError::UndefinedRole { ref role, .. } if role == "Bob"));

    // Verify error message includes span information
    let err_str = err.to_string();
    assert!(err_str.contains("Undefined role"));
    assert!(err_str.contains("Bob"));
}

#[test]
fn test_error_duplicate_role() {
    let input = r"
protocol Invalid =
    roles Alice, Bob, Alice

    Alice -> Bob : Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(err, ParseError::DuplicateRole { ref role, .. } if role == "Alice"));

    // Verify error message includes span information
    let err_str = err.to_string();
    assert!(err_str.contains("Duplicate role"));
    assert!(err_str.contains("Alice"));
}

#[test]
fn test_error_no_roles() {
    let input = r"
protocol Invalid =
    Alice -> Bob : Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
}

#[test]
fn test_error_invalid_syntax() {
    let input = r"
protocol Invalid =
    roles A, B

    A -> -> B : Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
}

#[test]
fn test_parse_with_comments() {
    let input = r"
-- This is a comment
protocol CommentTest =
    roles Alice, Bob  -- Inline comment

    {- Multi-line
       comment -}
    Alice -> Bob : Hello
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse with comments: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_typed_payload_with_inline_comment() {
    let input = r"
protocol TypedCommentedPayload =
    roles A, B

    A -> B : Message(
        value = 1 -- inline payload comment
        flag = true
    )
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse typed payload with inline comment: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_typed_payload_with_block_comment() {
    let input = r#"
protocol TypedPayloadBlockComment =
    roles A, B

    A -> B : Message(
        value = 1
        {- block payload comment -}
        kind = "ok"
    )
"#;

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse typed payload with block comment: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_whitespace_variations() {
    let input = r"
protocol WhitespaceTest =
    roles Alice,Bob
    Alice->Bob:Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_empty_protocol_body() {
    let input = r"
protocol Empty =
    roles A, B
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_role_names_with_underscores() {
    let input = r"
protocol UnderscoreRoles =
    roles Alice_Client, Bob_Server

    Alice_Client -> Bob_Server : Request
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_role_names_with_numbers() {
    let input = r"
protocol NumericRoles =
    roles Worker1, Worker2, Worker3

    Worker1 -> Worker2 : Data
    Worker2 -> Worker3 : Forward
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_parse_sequence_of_sends() {
    let input = r"
protocol Sequence =
    roles A, B, C, D

    A -> B : Msg1
    B -> C : Msg2
    C -> D : Msg3
    D -> A : Msg4
";

    let result = parse_choreography_str(input);
    assert!(result.is_ok());
}

#[test]
fn test_integration_with_projection() {
    use telltale_runtime::compiler::projection;

    let input = r"
protocol TwoParty =
    roles Client, Server

    Client -> Server : Request
    Server -> Client : Response
";

    let choreo = parse_choreography_str(input).expect("Failed to parse");

    // Test that we can project this choreography
    for role in &choreo.roles {
        let result = projection::project(&choreo, role);
        assert!(
            result.is_ok(),
            "Failed to project for role {}: {:?}",
            role.name(),
            result.err()
        );
    }
}

#[test]
fn test_integration_validation() {
    let input = r"
protocol ValidProtocol =
    roles A, B

    A -> B : Hello
    B -> A : World
";

    let choreo = parse_choreography_str(input).expect("Failed to parse");

    // Test that the choreography validates
    let validation_result = choreo.validate();
    assert!(
        validation_result.is_ok(),
        "Validation failed: {:?}",
        validation_result.err()
    );
}

#[test]
fn test_error_message_quality() {
    // This test verifies that error messages include helpful span information
    let input = r"
protocol Example =
    roles Alice, Bob

    Alice -> Charlie : Hello
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());

    let err = result.unwrap_err();
    let err_msg = err.to_string();

    // Should include error type
    assert!(err_msg.contains("Undefined role"));

    // Should include the offending role name
    assert!(err_msg.contains("Charlie"));

    // Should include location information
    assert!(err_msg.contains("-->"));

    // Should include line and column numbers
    assert!(err_msg.contains("5:"));

    // Should include code snippet
    assert!(err_msg.contains("Alice -> Charlie : Hello"));

    // Should have visual indicator (underline)
    assert!(err_msg.contains('^'));
}

#[test]
fn test_error_span_precision() {
    // Test that the span precisely identifies the error location
    let input = r"
protocol Test =
    roles Alice, Bob

    Alice -> UnknownRole : Message
    Bob -> Alice : Response
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());

    let err = result.unwrap_err();
    let err_msg = err.to_string();

    // Should point to the specific undefined role
    assert!(err_msg.contains("UnknownRole"));

    // Should show the line with the error
    assert!(err_msg.contains("Alice -> UnknownRole : Message"));
}

// Protocol composition tests

#[test]
fn test_parse_protocol_composition_simple() {
    let input = r"
protocol CompositionExample =
    roles Alice, Bob

    call Handshake
    Alice -> Bob : Data
where
    protocol Handshake =
        Alice -> Bob : Hello
        Bob -> Alice : Hi
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse protocol composition: {:?}",
        result.err()
    );

    let choreo = result.unwrap();
    assert_eq!(choreo.name.to_string(), "CompositionExample");
}

#[test]
fn test_parse_protocol_composition_multiple_defs() {
    let input = r"
protocol MultipleProtocols =
    roles A, B, C

    call Step1
    call Step2
    call Step3
where
    protocol Step1 =
        A -> B : Start
    protocol Step2 =
        B -> C : Continue
    protocol Step3 =
        C -> A : Finish
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse multiple protocols: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_protocol_composition_nested_calls() {
    let input = r"
protocol NestedCalls =
    roles Alice, Bob

    call Outer
where
    protocol Inner =
        Alice -> Bob : Data1
        Bob -> Alice : Ack1
    protocol Outer =
        call Inner
        Alice -> Bob : Data2
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse nested calls: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_protocol_composition_in_choice() {
    let input = r"
protocol CallInChoice =
    roles Client, Server

    Client -> Server : Request

    choice Server at
        | ok =>
            call Success
        | error =>
            call Failure
where
    protocol Success =
        Server -> Client : Success
    protocol Failure =
        Server -> Client : Failure
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse call in choice: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_protocol_composition_in_loop() {
    let input = r"
protocol CallInLoop =
    roles A, B

    loop repeat 3
        call Exchange
where
    protocol Exchange =
        A -> B : Request
        B -> A : Response
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse call in loop: {:?}",
        result.err()
    );
}

#[test]
fn test_error_undefined_protocol_call() {
    let input = r"
protocol UndefinedCall =
    roles A, B

    call NonExistent
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(
        err,
        telltale_runtime::compiler::parser::ParseError::UndefinedProtocol { .. }
    ));

    let err_msg = err.to_string();
    assert!(err_msg.contains("Undefined protocol"));
    assert!(err_msg.contains("NonExistent"));
}

#[test]
fn test_error_duplicate_protocol_def() {
    let input = r"
protocol DuplicateDef =
    roles A, B
where
    protocol MyProtocol =
        A -> B : First
    protocol MyProtocol =
        A -> B : Second
";

    let result = parse_choreography_str(input);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(
        err,
        telltale_runtime::compiler::parser::ParseError::DuplicateProtocol { .. }
    ));

    let err_msg = err.to_string();
    assert!(err_msg.contains("Duplicate protocol"));
    assert!(err_msg.contains("MyProtocol"));
}

// Guard tests

#[test]
fn test_parse_choice_with_guard() {
    let input = r"
protocol GuardExample =
    roles Client, Server

    choice Client at
        | buy when (balance > price) =>
            Client -> Server : Purchase
        | cancel =>
            Client -> Server : Cancel
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse choice with guard: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_choice_with_multiple_guards() {
    let input = r"
protocol MultiGuards =
    roles A, B

    choice A at
        | option1 when (x > 0) =>
            A -> B : Msg1
        | option2 when (x < 0) =>
            A -> B : Msg2
        | option3 =>
            A -> B : Msg3
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse multiple guards: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_guard_with_complex_expression() {
    let input = r"
protocol ComplexGuard =
    roles Client, Server

    choice Client at
        | proceed when (balance >= price && is_authenticated) =>
            Client -> Server : Action
        | reject =>
            Client -> Server : Reject
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse complex guard: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_guard_in_nested_choice() {
    let input = r"
protocol NestedGuard =
    roles A, B, C

    choice A at
        | outer when (condition1) =>
            A -> B : Start
            choice B at
                | inner when (condition2) =>
                    B -> C : Inner
                | fallback =>
                    B -> C : Fallback
        | skip =>
            A -> C : Skip
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse nested guard: {:?}",
        result.err()
    );
}

// ============================================================================
// Annotation Syntax (Rejected)
// ============================================================================

#[test]
fn test_annotation_syntax_is_rejected() {
    let input = r"
@optimize
protocol Simple =
    roles A, B
    A -> B : Msg
";

    let result = parse_choreography_str(input);
    assert!(result.is_err(), "Annotation syntax should be rejected");
}

// ============================================================================
// Type Annotation Tests
// ============================================================================

#[test]
fn test_parse_message_with_of_type() {
    let input = r"
protocol TypedMessages =
    roles A, B

    A -> B : Request of shop.Request
    B -> A : Response of shop.Response
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse `of`-typed messages: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_message_with_structured_payload() {
    let input = r"
protocol StructuredPayload =
    roles A, B

    A -> B : Data(first : String, second : I32, flag : Bool)
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse structured payload: {:?}",
        result.err()
    );
}

#[test]
fn test_reject_message_with_generic_angle_bracket_types() {
    let input = r"
protocol Generics =
    roles A, B

    A -> B : Container<Vec<String>>
    B -> A : Result<i32, Error>
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_err(),
        "angle-bracket generic message types must be rejected"
    );
}

#[test]
fn test_parse_message_with_of_type_and_payload() {
    let input = r"
protocol TypedWithPayload =
    roles A, B

    A -> B : Request of shop.Request(data)
    B -> A : Response of shop.Response(result)
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse `of`-typed message with payload: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_message_with_path_types() {
    let input = r"
protocol PathTypes =
    roles A, B

    A -> B : Data of std.string.String
    B -> A : Result of std.collections.Vector
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse dotted path types: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_message_with_of_payload_and_dotted_path() {
    let input = r"
protocol PayloadOf =
    roles A, B

    A -> B : Request of shop.Order
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse message with `of` payload syntax: {:?}",
        result.err()
    );

    let choreo = result.unwrap();
    match &choreo.protocol {
        Protocol::Send { message, .. } => {
            assert_eq!(message.name.to_string(), "Request");
            assert_eq!(
                message.payload.as_ref().map(ToString::to_string),
                Some("shop :: Order".to_string())
            );
        }
        _ => panic!("Expected Send"),
    }
}

#[test]
fn test_reject_message_with_of_missing_payload_type() {
    let input = r"
protocol MissingPayloadOf =
    roles A, B

    A -> B : Request of
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_err(),
        "missing payload type after `of` should not parse"
    );
}

#[test]
fn test_reject_message_with_dotted_angle_bracket_type() {
    let input = r"
protocol DottedTyped =
    roles A, B

    A -> B : Request<shop.Order>
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_err(),
        "angle-bracket dotted types must be rejected in favor of `of` syntax"
    );
}

// ============================================================================
// Parameterized Roles Tests
// ============================================================================

#[test]
fn test_parse_parameterized_role() {
    let input = r"
protocol WorkerPool =
    roles Master, Worker[N]

    Master -> Worker[0] : Task
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse parameterized role: {:?}",
        result.err()
    );

    let choreo = result.unwrap();
    assert_eq!(choreo.roles.len(), 2);
    assert!(choreo.roles[1].is_parameterized());
}

#[test]
fn test_parse_concrete_indexed_role() {
    let input = r"
protocol IndexedWorkers =
    roles Master, Worker[3]

    Master -> Worker[0] : Task1
    Master -> Worker[1] : Task2
    Master -> Worker[2] : Task3
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse indexed roles: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_multiple_parameterized_roles() {
    let input = r"
protocol MultiParam =
    roles Coordinator, Worker[N], Monitor[M]

    Coordinator -> Worker[i] : Start
    Worker[i] -> Monitor[j] : Report
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse multiple parameterized roles: {:?}",
        result.err()
    );

    let choreo = result.unwrap();
    assert_eq!(choreo.roles.len(), 3);
}

#[test]
fn test_parse_parameterized_role_in_choice() {
    let input = r"
protocol ParameterizedChoice =
    roles Master, Worker[N]

    choice Master at
        | assign =>
            Master -> Worker[i] : Task
        | skip =>
            Master -> Worker[0] : Skip
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse parameterized role in choice: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_parameterized_role_loop() {
    let input = r"
protocol ParameterizedLoop =
    roles Master, Worker[N]

    loop repeat N
        Master -> Worker[i] : Work
        Worker[i] -> Master : Result
";

    let result = parse_choreography_str(input);
    assert!(
        result.is_ok(),
        "Failed to parse parameterized role in loop: {:?}",
        result.err()
    );
}