shape-ast 0.1.8

AST types and Pest grammar for the Shape programming language
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
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
//! Advanced feature parsing tests
//!
//! This module contains tests for:
//! - Pattern matching
//! - Decomposition patterns
//! - Fuzzy comparisons
//! - Annotation definitions
//! - Complex integration tests

use super::super::*;
use crate::error::{Result, ShapeError};

/// Helper to parse a full program
fn parse_program_helper(input: &str) -> Result<Vec<crate::ast::Item>> {
    let pairs = ShapeParser::parse(Rule::program, input).map_err(|e| ShapeError::ParseError {
        message: e.to_string(),
        location: None,
    })?;

    let mut items = Vec::new();
    for pair in pairs {
        if pair.as_rule() == Rule::program {
            for inner in pair.into_inner() {
                if let Rule::item = inner.as_rule() {
                    items.push(parse_item(inner)?);
                }
            }
        }
    }
    Ok(items)
}

fn handler_param_names(handler: &crate::ast::AnnotationHandler) -> Vec<&str> {
    handler.params.iter().map(|p| p.name.as_str()).collect()
}

// =========================================================================
// Annotation Lifecycle Handler Tests
// =========================================================================

#[test]
fn test_annotation_def_with_on_define() {
    // Annotation with on_define lifecycle handler
    let content = r#"
        annotation pattern() {
            on_define(fn, ctx) {
                ctx.registry("patterns").set(fn.name, fn)
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with on_define should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    assert_eq!(items.len(), 1);

    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "pattern");
        assert_eq!(ann_def.handlers.len(), 1);
        assert_eq!(
            ann_def.handlers[0].handler_type,
            crate::ast::AnnotationHandlerType::OnDefine
        );
        assert_eq!(handler_param_names(&ann_def.handlers[0]), vec!["fn", "ctx"]);
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_legacy_at_annotation_definition_is_rejected() {
    let result = ShapeParser::parse(
        Rule::annotation_def,
        "@annotation old_style() { metadata() { { legacy: true } } }",
    );
    assert!(
        result.is_err(),
        "Legacy @annotation syntax must be rejected"
    );
}

#[test]
fn test_typeof_is_valid_identifier() {
    // typeof is no longer a reserved keyword — it parses as a regular function call.
    let content = r#"
        function test() {
            return typeof(1)
        }
    "#;
    let result = parse_program_helper(content);
    assert!(result.is_ok(), "typeof should parse as a regular identifier/function call");
}

#[test]
fn test_annotation_def_with_metadata() {
    // Annotation with metadata handler
    let content = r#"
        annotation indicator() {
            metadata() { { cacheable: true, pure: true } }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with metadata should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.handlers.len(), 1);
        assert_eq!(
            ann_def.handlers[0].handler_type,
            crate::ast::AnnotationHandlerType::Metadata
        );
        assert!(ann_def.handlers[0].params.is_empty());
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_annotation_def_with_before_after() {
    // Annotation with before and after handlers for caching
    let content = r#"
        annotation cached() {
            before(fn, args, ctx) {
                let key = hash(fn.name, args);
                ctx.cache.get(key)
            }
            after(fn, args, result, ctx) {
                let key = hash(fn.name, args);
                ctx.cache.set(key, result);
                result
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with before/after should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "cached");
        assert_eq!(ann_def.handlers.len(), 2);
        assert_eq!(
            ann_def.handlers[0].handler_type,
            crate::ast::AnnotationHandlerType::Before
        );
        assert_eq!(
            ann_def.handlers[1].handler_type,
            crate::ast::AnnotationHandlerType::After
        );
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_annotation_def_with_params() {
    // Annotation with parameters (like @warmup(period))
    let content = r#"
        annotation warmup(period) {
            before(fn, args, ctx) {
                ctx.data.extend_back(period)
            }
            after(fn, args, result, ctx) {
                ctx.data.restore_range();
                result
            }
            metadata() { { warmup_period: period } }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with params should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "warmup");
        assert_eq!(ann_def.params.len(), 1);
        assert_eq!(ann_def.params[0].simple_name(), Some("period"));
        assert_eq!(ann_def.handlers.len(), 3);
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_annotation_def_with_return_in_metadata() {
    let content = r#"
        annotation cached(ttl) {
            before(fn, args, ctx) {
                let key = hash(fn.name, args);
                ctx.cache.get(key)
            }

            after(fn, args, result, ctx) {
                let key = hash(fn.name, args);
                ctx.cache.set(key, result);
                result
            }

            metadata() {
                return {
                    cacheable: true,
                    ttl: ttl
                }
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with return in metadata should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Export Functions with Annotations
// =========================================================================

#[test]
fn test_parse_export_function_with_annotation() {
    // Export with @warmup annotation
    let content = "pub @warmup(period) fn foo(series, period) { return series; }";
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Export with annotation should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Block Expression Tests
// =========================================================================

#[test]
fn test_block_expr_with_return() {
    let content = r#"
        let x = {
            let y = 10;
            return y * 2
        };
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Block with return should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Decomposition Pattern Tests
// =========================================================================

#[test]
fn test_decomposition_pattern_simple() {
    // Decomposition pattern extracts component types from an intersection
    let content = r#"
        let (a: TypeA, b: TypeB) = merged_value;
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Decomposition pattern should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    assert!(!items.is_empty(), "Expected at least one item");
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        match &decl.pattern {
            crate::ast::DestructurePattern::Decomposition(bindings) => {
                assert_eq!(bindings.len(), 2);
                assert_eq!(bindings[0].name, "a");
                assert_eq!(bindings[1].name, "b");
            }
            other => panic!("Expected Decomposition pattern, got {:?}", other),
        }
    } else {
        panic!("Expected VariableDecl, got {:?}", items[0]);
    }
}

#[test]
fn test_decomposition_pattern_three_bindings() {
    let content = r#"
        let (x: TypeX, y: TypeY, z: TypeZ) = abc;
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Decomposition with 3 bindings should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        match &decl.pattern {
            crate::ast::DestructurePattern::Decomposition(bindings) => {
                assert_eq!(bindings.len(), 3);
            }
            other => panic!("Expected Decomposition pattern, got {:?}", other),
        }
    } else {
        panic!("Expected VariableDecl, got {:?}", items[0]);
    }
}

#[test]
fn test_decomposition_pattern_with_generic_types() {
    let content = r#"
        let (reader: Reader<string>, writer: Writer<number>) = io;
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Decomposition with generic types should parse: {:?}",
        result.err()
    );
}

#[test]
fn test_decomposition_pattern_shorthand_field_set() {
    // Shorthand syntax: field names only, no types
    let content = r#"let (d: {x}, e: {y, z}) = c;"#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Decomposition with shorthand field set should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        match &decl.pattern {
            crate::ast::DestructurePattern::Decomposition(bindings) => {
                assert_eq!(bindings.len(), 2);
                assert_eq!(bindings[0].name, "d");
                assert_eq!(bindings[1].name, "e");
                // First binding should have Object type with field "x"
                match &bindings[0].type_annotation {
                    crate::ast::TypeAnnotation::Object(fields) => {
                        assert_eq!(fields.len(), 1);
                        assert_eq!(fields[0].name, "x");
                    }
                    other => panic!("Expected Object type annotation, got {:?}", other),
                }
                // Second binding should have Object type with fields "y", "z"
                match &bindings[1].type_annotation {
                    crate::ast::TypeAnnotation::Object(fields) => {
                        assert_eq!(fields.len(), 2);
                        assert_eq!(fields[0].name, "y");
                        assert_eq!(fields[1].name, "z");
                    }
                    other => panic!("Expected Object type annotation, got {:?}", other),
                }
            }
            other => panic!("Expected Decomposition pattern, got {:?}", other),
        }
    } else {
        panic!("Expected VariableDecl, got {:?}", items[0]);
    }
}

#[test]
fn test_decomposition_pattern_full_object_types() {
    // Full object type syntax with field types
    let content = r#"let (f: {x: int}, g: {y: int, z: int}) = c;"#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Decomposition with full object types should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        match &decl.pattern {
            crate::ast::DestructurePattern::Decomposition(bindings) => {
                assert_eq!(bindings.len(), 2);
                assert_eq!(bindings[0].name, "f");
                assert_eq!(bindings[1].name, "g");
                match &bindings[0].type_annotation {
                    crate::ast::TypeAnnotation::Object(fields) => {
                        assert_eq!(fields.len(), 1);
                        assert_eq!(fields[0].name, "x");
                    }
                    other => panic!("Expected Object type annotation, got {:?}", other),
                }
                match &bindings[1].type_annotation {
                    crate::ast::TypeAnnotation::Object(fields) => {
                        assert_eq!(fields.len(), 2);
                        assert_eq!(fields[0].name, "y");
                        assert_eq!(fields[1].name, "z");
                    }
                    other => panic!("Expected Object type annotation, got {:?}", other),
                }
            }
            other => panic!("Expected Decomposition pattern, got {:?}", other),
        }
    } else {
        panic!("Expected VariableDecl, got {:?}", items[0]);
    }
}

// =========================================================================
// Fuzzy Comparison Tests
// =========================================================================

#[test]
fn test_fuzzy_equal_basic() {
    let result = parse_program_helper("let x = 1 ~= 2;");
    assert!(
        result.is_ok(),
        "Basic fuzzy equal should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { op, tolerance, .. }) = &decl.value {
            assert_eq!(*op, crate::ast::operators::FuzzyOp::Equal);
            // Default tolerance is 2%
            assert!(
                matches!(tolerance, crate::ast::operators::FuzzyTolerance::Percentage(p) if (*p - 0.02).abs() < 0.001)
            );
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    } else {
        panic!("Expected VariableDecl");
    }
}

#[test]
fn test_fuzzy_greater_basic() {
    let result = parse_program_helper("let x = a ~> b;");
    assert!(
        result.is_ok(),
        "Basic fuzzy greater should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { op, .. }) = &decl.value {
            assert_eq!(*op, crate::ast::operators::FuzzyOp::Greater);
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    }
}

#[test]
fn test_fuzzy_less_basic() {
    let result = parse_program_helper("let x = a ~< b;");
    assert!(
        result.is_ok(),
        "Basic fuzzy less should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { op, .. }) = &decl.value {
            assert_eq!(*op, crate::ast::operators::FuzzyOp::Less);
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    }
}

#[test]
fn test_fuzzy_with_absolute_tolerance() {
    let result = parse_program_helper("let x = a ~= b within 0.05;");
    assert!(
        result.is_ok(),
        "Fuzzy with absolute tolerance should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { tolerance, .. }) = &decl.value {
            assert!(
                matches!(tolerance, crate::ast::operators::FuzzyTolerance::Absolute(v) if (*v - 0.05).abs() < 0.001)
            );
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    }
}

#[test]
fn test_fuzzy_with_percentage_tolerance() {
    let result = parse_program_helper("let x = a ~= b within 5%;");
    assert!(
        result.is_ok(),
        "Fuzzy with percentage tolerance should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { tolerance, .. }) = &decl.value {
            // 5% should be stored as 0.05
            assert!(
                matches!(tolerance, crate::ast::operators::FuzzyTolerance::Percentage(v) if (*v - 0.05).abs() < 0.001)
            );
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    }
}

#[test]
fn test_fuzzy_with_integer_tolerance() {
    let result = parse_program_helper("let x = a ~= b within 10;");
    assert!(
        result.is_ok(),
        "Fuzzy with integer tolerance should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::Statement(crate::ast::Statement::VariableDecl(decl, _), _) = &items[0]
    {
        if let Some(crate::ast::Expr::FuzzyComparison { tolerance, .. }) = &decl.value {
            assert!(
                matches!(tolerance, crate::ast::operators::FuzzyTolerance::Absolute(v) if (*v - 10.0).abs() < 0.001)
            );
        } else {
            panic!("Expected FuzzyComparison, got {:?}", decl.value);
        }
    }
}

#[test]
fn test_fuzzy_in_function() {
    let result = parse_program_helper(
        r#"
        function is_close(a, b) {
            return a ~= b within 0.01;
        }
    "#,
    );
    assert!(
        result.is_ok(),
        "Fuzzy in function should parse: {:?}",
        result.err()
    );
}

#[test]
fn test_fuzzy_chained_with_and() {
    let result = parse_program_helper("let x = a ~= b within 0.1 and c ~> d;");
    assert!(
        result.is_ok(),
        "Fuzzy chained with and should parse: {:?}",
        result.err()
    );
}

#[test]
fn test_enum_with_typed_function_param() {
    let result = parse_program_helper(
        r#"
        enum Status { Active, Inactive, Pending }

        function check(s: Status) {
            return match s {
                Status::Active => "yes"
            };
        }
    "#,
    );
    assert!(
        result.is_ok(),
        "Enum with typed function param should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Complex Integration Tests
// =========================================================================

#[test]
fn test_parse_trend_adx_pattern() {
    // Simplified version of adx from trend.shape
    let content = r#"
pub fn adx(high, low, close, period = 14) {
    let adx_val = 42;
    let plus_di = 50;
    let minus_di = 30;

    {
        adx: adx_val,
        plus_di: plus_di,
        minus_di: minus_di
    }
}
"#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "ADX pattern should parse: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_trend_file_minimal() {
    // Minimal reproduction of trend.shape structure
    let content = r#"
from std::finance::indicators::moving_averages use { ema }
from std::finance::indicators::volatility use { atr }
from std::core::utils::rolling use { linear_recurrence, rolling_mean }
from std::core::utils::vector use { select }

// Wilder's Smoothing (Running Moving Average)
function rma(series, period) {
    let alpha = 1.0 / period;
    42
}

pub @warmup(period * 3) fn adx(high, low, close, period = 14) {
    let adx_val = 42;
    {
        adx: adx_val
    }
}
"#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Trend file minimal should parse: {:?}",
        result.err()
    );
}

#[test]
fn test_parse_trend_file_full() {
    // Read the actual trend.shape file
    let content = include_str!("../../../../shape-runtime/stdlib-src/finance/indicators/trend.shape");
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Full trend.shape should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Async/Await Tests (Phase 2)
// =========================================================================

#[test]
fn test_async_function_def() {
    let content = r#"async function foo() { return 1 }"#;
    let items = parse_program_helper(content).expect("async function should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "foo");
            assert!(func_def.is_async, "function should be async");
            assert!(!func_def.is_comptime, "function should NOT be comptime");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_async_fn_def() {
    let content = r#"async fn foo() { return 1 }"#;
    let items = parse_program_helper(content).expect("async fn should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "foo");
            assert!(func_def.is_async, "function should be async");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_sync_function_def() {
    let content = r#"function bar() { return 2 }"#;
    let items = parse_program_helper(content).expect("sync function should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "bar");
            assert!(!func_def.is_async, "function should NOT be async");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_sync_fn_def() {
    let content = r#"fn bar() { return 2 }"#;
    let items = parse_program_helper(content).expect("sync fn should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "bar");
            assert!(!func_def.is_async, "function should NOT be async");
            assert!(!func_def.is_comptime, "function should NOT be comptime");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_comptime_fn_def() {
    let content = r#"comptime fn helper() { return 2 }"#;
    let items = parse_program_helper(content).expect("comptime fn should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "helper");
            assert!(!func_def.is_async, "function should NOT be async");
            assert!(func_def.is_comptime, "function should be comptime");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_await_expr_parses() {
    let content = r#"function foo() { let x = await bar(); return x }"#;
    let items = parse_program_helper(content).expect("await expr should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "foo");
            // The body should contain a let statement with an await expression
            assert!(!func_def.body.is_empty());
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_async_function_with_await() {
    let content = r#"async function fetch_data() { let result = await get_data(); return result }"#;
    let items = parse_program_helper(content).expect("async function with await should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        crate::ast::Item::Function(func_def, _) => {
            assert_eq!(func_def.name, "fetch_data");
            assert!(func_def.is_async);
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

// =========================================================================
// Block Comment Tests (Phase 3.1)
// =========================================================================

#[test]
fn test_block_comment_simple() {
    let content = r#"/* simple block comment */ let x = 1"#;
    let items = parse_program_helper(content).expect("block comment should be ignored");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_block_comment_nested() {
    let content = r#"/* outer /* inner */ still outer */ let x = 1"#;
    let items = parse_program_helper(content).expect("nested block comment should work");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_block_comment_multiline() {
    let content = r#"
/*
  This is a multiline
  block comment
*/
let x = 1
"#;
    let items = parse_program_helper(content).expect("multiline block comment should work");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_block_comment_between_items() {
    let content = r#"
let x = 1
/* between items */
let y = 2
"#;
    let items = parse_program_helper(content).expect("block comment between items should work");
    assert_eq!(items.len(), 2);
}

#[test]
fn test_block_comment_inline() {
    let content = r#"let x = /* inline */ 42"#;
    let items = parse_program_helper(content).expect("inline block comment should work");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_doc_comment_line() {
    let content = r#"
/// This is a doc comment
function foo() { return 1 }
"#;
    let program = parse_program(content).expect("doc comment should parse");
    assert_eq!(program.items.len(), 1);
    assert_eq!(
        program
            .docs
            .comment_for_path("foo")
            .map(|doc| doc.summary.as_str()),
        Some("This is a doc comment")
    );
}

#[test]
fn test_doc_comment_block() {
    let content = r#"
/** This is a block doc comment */
function foo() { return 1 }
"#;
    let program = parse_program(content).expect("block doc comment should be parsed as comment");
    assert_eq!(program.items.len(), 1);
    assert!(program.docs.comment_for_path("foo").is_none());
}

#[test]
fn test_mixed_comments() {
    let content = r#"
// line comment
/* block comment */
/// doc comment
/** block doc comment */
let x = 1
"#;
    let items = parse_program_helper(content).expect("mixed comments should all work");
    assert_eq!(items.len(), 1);
}

// ===== Data Source and Query Declaration Tests =====

#[test]
fn test_datasource_declaration() {
    let content = r#"datasource MarketData: DataSource<CandleRow> = provider("market_data")"#;
    let items = parse_program_helper(content).expect("datasource decl should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::DataSource(ds, _) => {
            assert_eq!(ds.name, "MarketData");
        }
        other => panic!("expected DataSource, got {:?}", other),
    }
}

#[test]
fn test_query_declaration_with_sql() {
    let content = r#"query UserById: Query<UserRow, Params> = sql(DB, "SELECT id, name FROM users WHERE id = $1")"#;
    let items = parse_program_helper(content).expect("query decl should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::QueryDecl(q, _) => {
            assert_eq!(q.name, "UserById");
            assert_eq!(q.source_name, "DB");
            assert!(q.sql.contains("SELECT"));
        }
        other => panic!("expected QueryDecl, got {:?}", other),
    }
}

#[test]
fn test_datasource_with_semicolon() {
    let content = r#"datasource DB: DataSource<UserRow> = provider("postgres");"#;
    let items = parse_program_helper(content).expect("datasource with semicolon should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::DataSource(ds, _) => {
            assert_eq!(ds.name, "DB");
        }
        other => panic!("expected DataSource, got {:?}", other),
    }
}

// =========================================================================
// Extend Block Parser Tests
// =========================================================================

#[test]
fn test_extend_basic() {
    let content = r#"
        extend Number {
            method double() {
                return self * 2
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Basic extend block should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Extend(ext, _) => {
            assert_eq!(ext.methods.len(), 1);
            assert_eq!(ext.methods[0].name, "double");
        }
        other => panic!("expected Extend, got {:?}", other),
    }
}

#[test]
fn test_extend_with_params() {
    let content = r#"
        extend Number {
            method add(n: number) {
                return self + n
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Extend with params should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Extend(ext, _) => {
            assert_eq!(ext.methods[0].params.len(), 1);
            assert_eq!(ext.methods[0].params[0].simple_name(), Some("n"));
        }
        other => panic!("expected Extend, got {:?}", other),
    }
}

#[test]
fn test_extend_multiple_methods() {
    let content = r#"
        extend Number {
            method double() {
                return self * 2
            }
            method triple() {
                return self * 3
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Extend with multiple methods should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Extend(ext, _) => {
            assert_eq!(ext.methods.len(), 2);
            assert_eq!(ext.methods[0].name, "double");
            assert_eq!(ext.methods[1].name, "triple");
        }
        other => panic!("expected Extend, got {:?}", other),
    }
}

#[test]
fn test_extend_generic_type() {
    let content = r#"
        extend Vec<number> {
            method sum() {
                return self.reduce(|a, b| a + b, 0)
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Extend on generic type should parse: {:?}",
        result.err()
    );
}

// =========================================================================
// Trait Definition Parser Tests
// =========================================================================

#[test]
fn test_trait_basic() {
    let content = r#"
        trait Queryable {
            filter(predicate: (T) => bool): Self,
            execute(): Result<Table>
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Basic trait should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Trait(def, _) => {
            assert_eq!(def.name, "Queryable");
            assert!(def.type_params.is_none());
            assert_eq!(def.members.len(), 2);
        }
        other => panic!("expected Trait, got {:?}", other),
    }
}

#[test]
fn test_trait_with_type_params() {
    let content = r#"
        trait Queryable<T> {
            filter(predicate: (T) => bool): Self,
            execute(): Result<Table<T>>
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Trait with type params should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Trait(def, _) => {
            assert_eq!(def.name, "Queryable");
            assert_eq!(def.type_params.as_ref().unwrap().len(), 1);
        }
        other => panic!("expected Trait, got {:?}", other),
    }
}

#[test]
fn test_trait_with_supertrait_colon_syntax() {
    let content = r#"
        trait AdvancedQueryable<T>: Queryable<T> {
            groupBy(column: string): Self
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Trait with supertrait : syntax should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Trait(def, _) => {
            assert_eq!(def.name, "AdvancedQueryable");
            assert_eq!(def.super_traits.len(), 1);
            match &def.super_traits[0] {
                crate::ast::TypeAnnotation::Generic { name, args } => {
                    assert_eq!(name, "Queryable");
                    assert_eq!(args.len(), 1);
                }
                other => panic!("expected Generic supertrait, got {:?}", other),
            }
        }
        other => panic!("expected Trait, got {:?}", other),
    }
}

#[test]
fn test_trait_with_multiple_supertraits() {
    let content = r#"
        trait Foo: Bar + Baz {
            method(self): int
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Trait with multiple supertraits should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Trait(def, _) => {
            assert_eq!(def.name, "Foo");
            assert_eq!(def.super_traits.len(), 2);
            assert_eq!(def.super_traits[0].as_simple_name(), Some("Bar"));
            assert_eq!(def.super_traits[1].as_simple_name(), Some("Baz"));
        }
        other => panic!("expected Trait, got {:?}", other),
    }
}

// =========================================================================
// Impl Block Parser Tests
// =========================================================================

#[test]
fn test_impl_basic() {
    let content = r#"
        impl Queryable for Table {
            method filter(predicate) {
                return self
            }
            method execute() {
                return self
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Basic impl block should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Impl(impl_block, _) => {
            assert_eq!(
                impl_block.trait_name,
                crate::ast::TypeName::Simple("Queryable".into())
            );
            assert_eq!(
                impl_block.target_type,
                crate::ast::TypeName::Simple("Table".into())
            );
            assert_eq!(impl_block.methods.len(), 2);
            assert_eq!(impl_block.methods[0].name, "filter");
            assert_eq!(impl_block.methods[1].name, "execute");
        }
        other => panic!("expected Impl, got {:?}", other),
    }
}

#[test]
fn test_impl_generic_types() {
    let content = r#"
        impl Queryable<T> for Table<T> {
            method filter(predicate) {
                return self
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Impl with generic types should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Impl(impl_block, _) => {
            match &impl_block.trait_name {
                crate::ast::TypeName::Generic { name, type_args } => {
                    assert_eq!(name, "Queryable");
                    assert_eq!(type_args.len(), 1);
                }
                other => panic!("expected Generic trait name, got {:?}", other),
            }
            match &impl_block.target_type {
                crate::ast::TypeName::Generic { name, type_args } => {
                    assert_eq!(name, "Table");
                    assert_eq!(type_args.len(), 1);
                }
                other => panic!("expected Generic target type, got {:?}", other),
            }
        }
        other => panic!("expected Impl, got {:?}", other),
    }
}

#[test]
fn test_impl_with_method_params() {
    let content = r#"
        impl Sortable for Vec {
            method sort(comparator: (a, b) => number) {
                return self
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Impl with method params should parse: {:?}",
        result.err()
    );
    let items = result.unwrap();
    match &items[0] {
        Item::Impl(impl_block, _) => {
            assert_eq!(impl_block.methods.len(), 1);
            assert_eq!(impl_block.methods[0].name, "sort");
            assert_eq!(impl_block.methods[0].params.len(), 1);
        }
        other => panic!("expected Impl, got {:?}", other),
    }
}

// =========================================================================
// Sprint 7: Structured Concurrency Parser Tests
// =========================================================================

#[test]
fn test_async_let_parses() {
    let content = r#"
        async function test() {
            async let x = 1 + 2
            await x
        }
    "#;
    let items = parse_program_helper(content).expect("async let should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Function(func_def, _) => {
            assert!(func_def.is_async, "function should be async");
            assert_eq!(func_def.name, "test");
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_async_scope_parses() {
    let content = r#"
        async function test() {
            async scope {
                let x = 42
                x
            }
        }
    "#;
    let items = parse_program_helper(content).expect("async scope should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Function(func_def, _) => {
            assert!(func_def.is_async);
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_for_await_parses() {
    let content = r#"
        async function consume() {
            let items = [1, 2, 3]
            for await item in items {
                print(item)
            }
        }
    "#;
    let items = parse_program_helper(content).expect("for await should parse");
    assert_eq!(items.len(), 1);
    match &items[0] {
        Item::Function(func_def, _) => {
            assert!(func_def.is_async);
        }
        other => panic!("expected Function, got {:?}", other),
    }
}

#[test]
fn test_for_await_expr_parses() {
    let content = r#"
        async function test() {
            let result = for await x in [1, 2, 3] { x * 2 }
            result
        }
    "#;
    let items = parse_program_helper(content).expect("for await expr should parse");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_nested_async_scope_parses() {
    let content = r#"
        async function test() {
            async scope {
                async scope {
                    42
                }
            }
        }
    "#;
    let items = parse_program_helper(content).expect("nested async scope should parse");
    assert_eq!(items.len(), 1);
}

#[test]
fn test_legacy_annotation_comptime_handler_is_rejected() {
    let content = r#"
        annotation derive_debug() {
            comptime(target) {
                let name = target.name
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_err(),
        "Legacy `comptime(target)` handler syntax must be rejected"
    );
}

#[test]
fn test_legacy_comptime_before_after_phases_are_rejected() {
    let old_before = r#"
        annotation schema() {
            comptime before(target, ctx) {
                target.name
            }
        }
    "#;
    assert!(
        parse_program_helper(old_before).is_err(),
        "Legacy comptime before(...) phase syntax must be rejected"
    );

    let old_after = r#"
        annotation schema() {
            comptime after(target, ctx) {
                target.name
            }
        }
    "#;
    assert!(
        parse_program_helper(old_after).is_err(),
        "Legacy comptime after(...) phase syntax must be rejected"
    );
}

#[test]
fn test_annotation_keyword_and_variadic_handler_params() {
    let content = r#"
        annotation schema() {
            comptime post(target, ctx, ...config) {
                target.name
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "annotation keyword + variadic params should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "schema");
        assert_eq!(ann_def.handlers.len(), 1);
        let handler = &ann_def.handlers[0];
        assert_eq!(
            handler.handler_type,
            crate::ast::AnnotationHandlerType::ComptimePost
        );
        assert_eq!(
            handler_param_names(handler),
            vec!["target", "ctx", "config"]
        );
        assert!(!handler.params[0].is_variadic);
        assert!(!handler.params[1].is_variadic);
        assert!(handler.params[2].is_variadic);
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_annotation_def_with_comptime_pre_post_handlers() {
    let content = r#"
        annotation schema() {
            comptime pre(target, ctx) {
                target.name
            }
            comptime post(target, ctx) {
                target.return_type
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with comptime pre/post handlers should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "schema");
        assert_eq!(ann_def.handlers.len(), 2);
        assert_eq!(
            ann_def.handlers[0].handler_type,
            crate::ast::AnnotationHandlerType::ComptimePre
        );
        assert_eq!(
            ann_def.handlers[1].handler_type,
            crate::ast::AnnotationHandlerType::ComptimePost
        );
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_function_param_const_flag_parses() {
    let content = r#"
        fn connect(const conn_str: string) {
            conn_str
        }
    "#;

    let items = parse_program_helper(content).expect("function with const param should parse");
    let func = match &items[0] {
        crate::ast::Item::Function(func, _) => func,
        other => panic!("expected function item, got {:?}", other),
    };
    assert_eq!(func.params.len(), 1);
    assert!(
        func.params[0].is_const,
        "parameter should be parsed as const"
    );
}

#[test]
fn test_annotation_def_with_explicit_targets_and_handler() {
    let content = r#"
        annotation only_types() {
            targets: [type, expression]
            comptime post(target, ctx) {
                target.kind
            }
        }
    "#;
    let result = parse_program_helper(content);
    assert!(
        result.is_ok(),
        "Annotation with explicit targets should parse: {:?}",
        result.err()
    );

    let items = result.unwrap();
    if let crate::ast::Item::AnnotationDef(ann_def, _) = &items[0] {
        assert_eq!(ann_def.name, "only_types");
        let targets = ann_def
            .allowed_targets
            .clone()
            .expect("targets should parse");
        assert_eq!(
            targets,
            vec![
                crate::ast::AnnotationTargetKind::Type,
                crate::ast::AnnotationTargetKind::Expression
            ]
        );
        assert_eq!(ann_def.handlers.len(), 1);
        assert_eq!(
            ann_def.handlers[0].handler_type,
            crate::ast::AnnotationHandlerType::ComptimePost
        );
    } else {
        panic!("Expected AnnotationDef");
    }
}

#[test]
fn test_annotation_comptime_directives_parse_in_block() {
    let content = r#"
        annotation transform() {
            targets: [expression]
            comptime post(target, ctx) {
                remove target
            }
        }
    "#;
    let result = parse_program_helper(content).expect("parse should succeed");
    let ann = match &result[0] {
        crate::ast::Item::AnnotationDef(ann_def, _) => ann_def,
        other => panic!("expected AnnotationDef, got {:?}", other),
    };
    let handler = &ann.handlers[0];
    let body_items = match &handler.body {
        crate::ast::Expr::Block(block, _) => &block.items,
        other => panic!("expected block body, got {:?}", other),
    };
    assert!(
        body_items.iter().any(|item| matches!(
            item,
            crate::ast::BlockItem::Statement(crate::ast::Statement::RemoveTarget(_))
        )),
        "expected remove target statement in comptime handler body"
    );
}

#[test]
fn test_annotation_typed_comptime_directives_parse() {
    let content = r#"
        annotation schema() {
            targets: [function]
            comptime post(target, ctx) {
                set param uri: string
                set return DbConnection
                replace body {
                    return runtime_connect(uri)
                }
            }
        }
    "#;

    let result = parse_program_helper(content).expect("parse should succeed");
    let ann = match &result[0] {
        crate::ast::Item::AnnotationDef(ann_def, _) => ann_def,
        other => panic!("expected AnnotationDef, got {:?}", other),
    };
    let handler = &ann.handlers[0];
    let body_items = match &handler.body {
        crate::ast::Expr::Block(block, _) => &block.items,
        other => panic!("expected block body, got {:?}", other),
    };
    assert!(body_items.iter().any(|item| matches!(
        item,
        crate::ast::BlockItem::Statement(crate::ast::Statement::SetParamType { .. })
    )));
    assert!(body_items.iter().any(|item| matches!(
        item,
        crate::ast::BlockItem::Statement(crate::ast::Statement::SetReturnType { .. })
    )));
    assert!(body_items.iter().any(|item| matches!(
        item,
        crate::ast::BlockItem::Statement(crate::ast::Statement::ReplaceBody { .. })
    )));
}

#[test]
fn test_annotation_replace_body_expr_directive_parse() {
    let content = r#"
        annotation schema() {
            targets: [function]
            comptime post(target, ctx) {
                replace body (gen_body(target))
            }
        }
    "#;

    let result = parse_program_helper(content).expect("parse should succeed");
    let ann = match &result[0] {
        crate::ast::Item::AnnotationDef(ann_def, _) => ann_def,
        other => panic!("expected AnnotationDef, got {:?}", other),
    };
    let handler = &ann.handlers[0];
    let body_items = match &handler.body {
        crate::ast::Expr::Block(block, _) => &block.items,
        other => panic!("expected block body, got {:?}", other),
    };
    assert!(body_items.iter().any(|item| matches!(
        item,
        crate::ast::BlockItem::Statement(crate::ast::Statement::ReplaceBodyExpr { .. })
    )));
}

#[test]
fn test_annotation_replace_module_expr_directive_parse() {
    let content = r#"
        annotation schema() {
            targets: [module]
            comptime post(target, ctx) {
                replace module (gen_module(target))
            }
        }
    "#;

    let result = parse_program_helper(content).expect("parse should succeed");
    let ann = match &result[0] {
        crate::ast::Item::AnnotationDef(ann_def, _) => ann_def,
        other => panic!("expected AnnotationDef, got {:?}", other),
    };
    assert!(
        ann.allowed_targets
            .as_ref()
            .is_some_and(|targets| targets.contains(&crate::ast::AnnotationTargetKind::Module)),
        "annotation should allow module targets"
    );

    let handler = &ann.handlers[0];
    let body_items = match &handler.body {
        crate::ast::Expr::Block(block, _) => &block.items,
        other => panic!("expected block body, got {:?}", other),
    };
    assert!(body_items.iter().any(|item| matches!(
        item,
        crate::ast::BlockItem::Statement(crate::ast::Statement::ReplaceModuleExpr { .. })
    )));
}