assura-resolve 0.4.3

Name resolution and symbol table for the Assura contract 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
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
use super::*;
use assura_parser::ast::Spanned;

/// Helper: parse source text into a `SourceFile` (panics on error).
fn parse_ok(source: &str) -> SourceFile {
    assura_parser::parse_unwrap(source)
}

#[test]
fn builtins_registered() {
    let file = parse_ok("");
    let resolved = resolve(&file).expect("resolve should succeed on empty file");
    // All built-in types should be in the table.
    assert!(resolved.symbols.len() >= BUILTIN_TYPES.len());
    for &name in BUILTIN_TYPES {
        let found = resolved
            .symbols
            .symbols
            .iter()
            .any(|s| s.name == name && s.kind == SymbolKind::BuiltinType);
        assert!(found, "built-in type `{name}` not found");
    }
}

#[test]
fn collects_top_level_decls() {
    let src = r#"
contract Foo {
  requires { true }
}

type Bar {
  x: Int
}

enum Baz {
  A
  B
}

fn helper(n: Int) -> Int {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let names: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind != SymbolKind::BuiltinType)
        .map(|s| s.name.as_str())
        .collect();
    assert!(names.contains(&"Foo"), "missing Foo");
    assert!(names.contains(&"Bar"), "missing Bar");
    assert!(names.contains(&"Baz"), "missing Baz");
    assert!(names.contains(&"helper"), "missing helper");
}

#[test]
fn duplicate_detection() {
    let src = r#"
contract Foo {
  requires { true }
}

contract Foo {
  ensures { true }
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should detect duplicate");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02003");
    assert!(
        errs[0].message.contains("`Foo`"),
        "error should name the duplicate definition `Foo`, got: {}",
        errs[0].message
    );
}

#[test]
fn service_creates_child_scope() {
    let src = r#"
service ImageDecoder {
  type Config {
max_size: Nat
  }

  operation decode {
input { data: Bytes }
output { image: Bytes }
  }

  query status {
output { state: String }
  }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Should have: root scope, module scope, ImageDecoder scope
    assert!(resolved.symbols.scopes.len() >= 3);
    // Service itself is a symbol
    let svc = resolved
        .symbols
        .symbols
        .iter()
        .find(|s| s.name == "ImageDecoder");
    assert!(svc.is_some(), "ImageDecoder not found");
    // Items inside the service are also symbols
    let config = resolved.symbols.symbols.iter().find(|s| s.name == "Config");
    assert!(config.is_some(), "Config not found in service scope");
    let decode = resolved.symbols.symbols.iter().find(|s| s.name == "decode");
    assert!(decode.is_some(), "decode not found in service scope");
    let status = resolved.symbols.symbols.iter().find(|s| s.name == "status");
    assert!(status.is_some(), "status not found in service scope");
}

#[test]
fn empty_file_ok() {
    let file = parse_ok("");
    let resolved = resolve(&file).expect("empty file should resolve");
    // Built-in types + stdlib prelude types (minus duplicates) + prelude contracts
    let stdlib_extras = assura_stdlib::prelude_type_names()
        .iter()
        .filter(|name| !BUILTIN_TYPES.contains(name))
        .count();
    let prelude_contracts = assura_stdlib::prelude_contract_names().len();
    assert_eq!(
        resolved.symbols.symbols.len(),
        BUILTIN_TYPES.len() + stdlib_extras + prelude_contracts
    );
}

#[test]
fn prelude_contracts_registered_as_contract_def() {
    let file = parse_ok("");
    let resolved = resolve(&file).expect("empty file should resolve");
    for &name in &assura_stdlib::prelude_contract_names() {
        let sym = resolved.symbols.symbols.iter().find(|s| s.name == name);
        assert!(
            sym.is_some(),
            "prelude contract '{name}' not in symbol table"
        );
        assert_eq!(
            sym.unwrap().kind,
            SymbolKind::ContractDef,
            "prelude contract '{name}' should be ContractDef"
        );
    }
}

#[test]
fn clamp_resolves_without_import() {
    let src = r#"
contract BoundedValue {
    input(x: Int)
    output(result: Int)
    ensures { clamp(x, 0, 100) >= 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file);
    assert!(
        resolved.is_ok(),
        "clamp should resolve without import: {resolved:?}"
    );
}

#[test]
fn contract_scope_with_type_params() {
    let src = r#"
contract SafeBuffer<T> {
  requires { true }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Contract scope is a child of module scope
    let contract_scope = resolved
        .symbols
        .scopes
        .iter()
        .find(|s| s.name == "SafeBuffer");
    assert!(contract_scope.is_some(), "SafeBuffer scope not found");
    // Type param T should be a symbol
    let tp = resolved
        .symbols
        .symbols
        .iter()
        .find(|s| s.name == "T" && s.kind == SymbolKind::TypeParam);
    assert!(tp.is_some(), "type param T not found");
}

#[test]
fn fn_scope_with_params() {
    let src = r#"
fn helper(n: Int, m: Int) -> Int {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Function scope exists
    let fn_scope = resolved.symbols.scopes.iter().find(|s| s.name == "helper");
    assert!(fn_scope.is_some(), "helper scope not found");
    // Parameters are symbols
    let params: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Parameter)
        .map(|s| s.name.as_str())
        .collect();
    assert!(params.contains(&"n"), "param n not found");
    assert!(params.contains(&"m"), "param m not found");
}

#[test]
fn extern_scope_with_params() {
    let src = r#"
extern fn malloc(size: Nat) -> Bytes
  requires { size > 0 }
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let p = resolved
        .symbols
        .symbols
        .iter()
        .find(|s| s.name == "size" && s.kind == SymbolKind::Parameter);
    assert!(p.is_some(), "extern param size not found");
}

#[test]
fn duplicate_fn_params() {
    let src = r#"
fn bad(x: Int, x: Int) -> Int {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should detect duplicate param");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02003");
    assert!(
        errs[0].message.contains("`x`"),
        "error should name the duplicate parameter `x`, got: {}",
        errs[0].message
    );
}

#[test]
fn type_scope_with_fields() {
    let src = r#"
type Point {
  x: Int;
  y: Int;
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let fields: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Field)
        .map(|s| s.name.as_str())
        .collect();
    assert!(fields.contains(&"x"), "field x not found");
    assert!(fields.contains(&"y"), "field y not found");
}

#[test]
fn duplicate_struct_fields() {
    let src = r#"
type BadStruct {
  x: Int;
  x: Float;
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should detect duplicate field");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02003");
    assert!(
        errs[0].message.contains("`x`"),
        "error should name the duplicate field `x`, got: {}",
        errs[0].message
    );
}

#[test]
fn enum_scope_with_variants() {
    let src = r#"
enum Color {
  Red
  Green
  Blue
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let variants: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::EnumVariant)
        .map(|s| s.name.as_str())
        .collect();
    assert!(variants.contains(&"Red"), "variant Red not found");
    assert!(variants.contains(&"Green"), "variant Green not found");
    assert!(variants.contains(&"Blue"), "variant Blue not found");
}

#[test]
fn duplicate_enum_variants() {
    let src = r#"
enum Bad {
  A
  A
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should detect duplicate variant");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02003");
    assert!(
        errs[0].message.contains("`A`"),
        "error should name the duplicate variant `A`, got: {}",
        errs[0].message
    );
}

#[test]
fn service_nested_type_fields() {
    let src = r#"
service Svc {
  type Config {
max_size: Nat;
retries: Nat;
  }

  operation start {
input { data: Bytes }
  }

  query health {
output { state: String }
  }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Config fields are symbols
    let fields: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Field)
        .map(|s| s.name.as_str())
        .collect();
    assert!(fields.contains(&"max_size"), "field max_size not found");
    assert!(fields.contains(&"retries"), "field retries not found");
    // Operation and query have scopes
    let op_scope = resolved.symbols.scopes.iter().find(|s| s.name == "start");
    assert!(op_scope.is_some(), "start operation scope not found");
    let q_scope = resolved.symbols.scopes.iter().find(|s| s.name == "health");
    assert!(q_scope.is_some(), "health query scope not found");
}

#[test]
fn duplicate_service_operations() {
    let src = r#"
service BadSvc {
  operation go {
input { data: Bytes }
  }

  operation go {
input { other: Bytes }
  }
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should detect duplicate operation");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02003");
    assert!(
        errs[0].message.contains("`go`"),
        "error should name the duplicate operation `go`, got: {}",
        errs[0].message
    );
}

#[test]
fn scope_hierarchy_depth() {
    // Verify that a service with a type def creates
    // root > module > service > type scopes (4 levels).
    let src = r#"
service Deep {
  type Inner {
field: Int
  }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Walk from Inner scope up to root
    let inner_scope = resolved
        .symbols
        .scopes
        .iter()
        .position(|s| s.name == "Inner")
        .expect("Inner scope not found");
    let inner = &resolved.symbols.scopes[inner_scope];
    let svc_id = inner.parent.expect("Inner should have parent");
    let svc = &resolved.symbols.scopes[svc_id];
    assert_eq!(svc.name, "Deep");
    let mod_id = svc.parent.expect("Deep should have parent");
    let module = &resolved.symbols.scopes[mod_id];
    let root_id = module.parent.expect("module should have parent");
    let root = &resolved.symbols.scopes[root_id];
    assert_eq!(root.name, "<root>");
    assert!(root.parent.is_none(), "root should have no parent");
}

#[test]
fn name_shadowing_allowed_across_scopes() {
    // A parameter named the same as a top-level type is OK --
    // shadowing across scope levels is not a duplicate error.
    let src = r#"
type Foo {
  x: Int
}

fn helper(Foo: Int) -> Int {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("shadowing should be allowed");
    // Both exist: one as TypeDef, one as Parameter
    let type_sym = resolved
        .symbols
        .symbols
        .iter()
        .find(|s| s.name == "Foo" && s.kind == SymbolKind::TypeDef);
    let param_sym = resolved
        .symbols
        .symbols
        .iter()
        .find(|s| s.name == "Foo" && s.kind == SymbolKind::Parameter);
    assert!(type_sym.is_some(), "type Foo not found");
    assert!(param_sym.is_some(), "param Foo not found");
}

// -----------------------------------------------------------------------
// Import resolution tests
// -----------------------------------------------------------------------

#[test]
fn import_basic_recorded() {
    let src = r#"
import std.math;
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    assert_eq!(resolved.imports.len(), 1);
    assert_eq!(resolved.imports[0].path, vec!["std", "math"]);
    assert!(resolved.imports[0].alias.is_none());
    assert!(resolved.imports[0].items.is_empty());
    // Without a module map entry, status is Unresolved.
    assert_eq!(resolved.imports[0].status, ImportStatus::Unresolved);
}

#[test]
fn import_aliased_recorded() {
    let src = r#"
import crypto.hash as hash;
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    assert_eq!(resolved.imports.len(), 1);
    assert_eq!(resolved.imports[0].path, vec!["crypto", "hash"]);
    assert_eq!(resolved.imports[0].alias.as_deref(), Some("hash"));
    assert!(resolved.imports[0].items.is_empty());
    assert_eq!(resolved.imports[0].status, ImportStatus::Unresolved);
}

#[test]
fn import_selective_recorded() {
    let src = r#"
import std.collections { List, Map };
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    assert_eq!(resolved.imports.len(), 1);
    assert_eq!(resolved.imports[0].path, vec!["std", "collections"]);
    assert!(resolved.imports[0].alias.is_none());
    assert_eq!(resolved.imports[0].items, vec!["List", "Map"]);
    assert_eq!(resolved.imports[0].status, ImportStatus::Unresolved);
}

#[test]
fn import_multiple_recorded() {
    let src = r#"
import std.math;
import std.collections { List, Map };
import crypto.hash as hash;
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    assert_eq!(resolved.imports.len(), 3);
    assert_eq!(resolved.imports[0].path, vec!["std", "math"]);
    assert_eq!(resolved.imports[1].path, vec!["std", "collections"]);
    assert_eq!(resolved.imports[2].path, vec!["crypto", "hash"]);
}

#[test]
fn import_unresolved_no_hard_error() {
    // External/unknown modules should NOT cause resolution failure.
    let src = r#"
import assura.mem;
import assura.sec;

contract Foo {
  requires { true }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("unresolved imports should not fail");
    assert_eq!(resolved.imports.len(), 2);
    assert_eq!(resolved.imports[0].status, ImportStatus::Unresolved);
    assert_eq!(resolved.imports[1].status, ImportStatus::Unresolved);
    // Declarations are still resolved normally.
    let foo = resolved.symbols.symbols.iter().find(|s| s.name == "Foo");
    assert!(foo.is_some(), "Foo should still be resolved");
}

#[test]
fn import_resolved_with_module_map() {
    // Pre-populate the module map so the import resolves.
    let target_src = r#"
module std.math;

fn abs(x: Int) -> Int {
  ensures { result >= 0 }
}
"#;
    let target_file = parse_ok(target_src);
    let mut module_map = ModuleMap::new();
    module_map.insert("std.math".to_string(), target_file);

    let src = r#"
import std.math;
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    let resolved = resolve_with_modules(&file, &module_map, &mut visited).expect("should succeed");
    assert_eq!(resolved.imports.len(), 1);
    assert_eq!(resolved.imports[0].status, ImportStatus::Resolved);
}

#[test]
fn import_circular_detected() {
    // Simulate circular import: module A is being resolved and it
    // imports module A (itself).
    let src = r#"
module mymod;

import mymod;
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    // Pre-seed visited with "mymod" to simulate a cycle.
    visited.insert("mymod".to_string());
    let result = resolve_with_modules(&file, &ModuleMap::new(), &mut visited);
    assert!(result.is_err(), "circular import should produce an error");
    let errs = result.unwrap_err();
    assert_eq!(errs.len(), 1);
    assert_eq!(errs[0].code, "A02005");
    assert!(
        errs[0].message.contains("`mymod`"),
        "error should name the circular module `mymod`, got: {}",
        errs[0].message
    );
}

#[test]
fn import_circular_indirect() {
    // Simulate indirect circular import: module A imports B, and B
    // is already being resolved (present in visited).
    let src = r#"
module a;

import b;
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    // "b" is already being resolved somewhere up the call chain.
    visited.insert("b".to_string());
    let result = resolve_with_modules(&file, &ModuleMap::new(), &mut visited);
    assert!(result.is_err(), "circular import should produce an error");
    let errs = result.unwrap_err();
    assert_eq!(errs[0].code, "A02005");
    assert!(
        errs[0].message.contains("`b`"),
        "error should name the circular module `b`, got: {}",
        errs[0].message
    );
}

#[test]
fn import_mixed_resolved_and_unresolved() {
    // One import resolves, another does not. Non-empty module map => A02010 error.
    let target_src = r#"
module known.mod;

type Foo { x: Int }
"#;
    let target_file = parse_ok(target_src);
    let mut module_map = ModuleMap::new();
    module_map.insert("known.mod".to_string(), target_file);

    let src = r#"
import known.mod { Foo };
import unknown.mod;
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    let result = resolve_with_modules(&file, &module_map, &mut visited);
    assert!(
        result.is_err(),
        "missing module in project map should hard-error"
    );
    let errs = result.unwrap_err();
    assert!(
        errs.iter()
            .any(|e| e.code == "A02010" && e.message.contains("unknown.mod")),
        "expected A02010 for unknown.mod, got {errs:?}"
    );
}

#[test]
fn no_imports_empty_list() {
    let src = r#"
contract Foo {
  requires { true }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    assert!(resolved.imports.is_empty());
}

#[test]
fn visited_set_cleaned_up_after_resolve() {
    // After resolve_with_modules returns, the current module should
    // be removed from the visited set so sibling modules are not
    // falsely flagged as circular.
    let src = r#"
module a;
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    resolve_with_modules(&file, &ModuleMap::new(), &mut visited).expect("should succeed");
    assert!(
        !visited.contains("a"),
        "module 'a' should be removed from visited after resolution"
    );
}

// -----------------------------------------------------------------------
// Type reference resolution tests (T012)
// -----------------------------------------------------------------------

#[test]
fn builtin_types_resolve_in_fields() {
    let src = r#"
type Point {
  x: Int;
  y: Float;
  name: String;
  active: Bool;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("built-in types in fields should resolve");
}

#[test]
fn builtin_types_resolve_in_fn_params() {
    let src = r#"
fn helper(n: Int, s: String) -> Bool {
  ensures { result == true }
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("built-in types in fn params should resolve");
}

#[test]
fn builtin_types_resolve_in_extern() {
    let src = r#"
extern fn malloc(size: Nat) -> Bytes
  requires { size > 0 }
"#;
    let file = parse_ok(src);
    resolve(&file).expect("built-in types in extern should resolve");
}

#[test]
fn user_defined_type_resolves_in_field() {
    let src = r#"
type UserId = { id: Nat | id > 0 };

type User {
  id: UserId;
  name: String;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("user-defined type in fields should resolve");
}

#[test]
fn user_defined_type_resolves_in_fn() {
    let src = r#"
type UserId = { id: Nat | id > 0 };

fn get_user(id: UserId) -> String {
  ensures { result.length() > 0 }
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("user-defined type in fn params should resolve");
}

#[test]
fn type_param_resolves_in_scope() {
    // Generic type: T should resolve within the type's own scope.
    let src = r#"
type Container<T> {
  items: List;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("type param should resolve in type scope");
}

#[test]
fn unknown_type_a02001_in_field() {
    // No imports, no definition of Banana => A02001
    let src = r#"
type Basket {
  fruit: Banana;
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "unknown type should produce A02001");
    let errs = result.unwrap_err();
    assert!(
        errs.iter().any(|e| e.code == "A02001"),
        "should have A02001"
    );
    assert!(
        errs.iter().any(|e| e.message.contains("Banana")),
        "error should mention Banana"
    );
}

#[test]
fn unknown_type_a02001_in_fn_param() {
    let src = r#"
fn process(item: Unicorn) -> Int {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "unknown type should produce A02001");
    let errs = result.unwrap_err();
    assert!(errs.iter().any(|e| e.code == "A02001"));
    assert!(errs.iter().any(|e| e.message.contains("Unicorn")));
}

#[test]
fn unknown_type_a02001_in_return_type() {
    let src = r#"
fn compute(x: Int) -> Phantom {
  ensures { result == x }
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "unknown return type should produce A02001");
    let errs = result.unwrap_err();
    assert!(errs.iter().any(|e| e.code == "A02001"));
    assert!(errs.iter().any(|e| e.message.contains("Phantom")));
}

#[test]
fn unknown_type_lenient_with_imports() {
    // When there are unresolved imports, unknown types are NOT errors
    // (they may come from the imported module).
    let src = r#"
import external.types;

type Wrapper {
  inner: ExternalType;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("unknown type with unresolved imports should be lenient");
}

#[test]
fn enum_used_as_type_resolves() {
    let src = r#"
enum Color {
  Red
  Green
  Blue
}

type Pixel {
  color: Color;
  x: Int;
  y: Int;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("enum used as field type should resolve");
}

#[test]
fn service_nested_type_refs_resolve() {
    let src = r#"
service Svc {
  type Config {
max_size: Nat;
enabled: Bool;
  }
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("types in service nested type defs should resolve");
}

#[test]
fn lookup_walks_scope_chain() {
    // Verify the lookup method walks up the scope chain.
    let src = r#"
type Outer {
  x: Int
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let table = &resolved.symbols;
    // Find the Outer type scope
    let outer_scope = table
        .scopes
        .iter()
        .position(|s| s.name == "Outer")
        .expect("Outer scope not found");
    // Int is in root scope; lookup from Outer scope should find it
    let int_sym = table.lookup("Int", outer_scope);
    assert_eq!(
        int_sym.expect("Int should be found via scope chain").kind,
        SymbolKind::BuiltinType
    );
    // Nonexistent name should return None
    let missing = table.lookup("DoesNotExist", outer_scope);
    assert!(missing.is_none(), "missing name should return None");
}

#[test]
fn type_alias_refs_resolve() {
    let src = r#"
type PositiveInt = { n: Int | n > 0 };
"#;
    let file = parse_ok(src);
    resolve(&file).expect("type alias with Int reference should resolve");
}

#[test]
fn multiple_unknown_types_reported() {
    let src = r#"
type Bad {
  a: Alpha;
  b: Beta;
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "should report errors for unknown types");
    let errs = result.unwrap_err();
    let a02001_count = errs.iter().filter(|e| e.code == "A02001").count();
    assert_eq!(a02001_count, 2, "should report 2 A02001 errors");
}

#[test]
fn lowercase_tokens_not_checked_as_types() {
    // Lowercase tokens in type positions (e.g., modifiers, keywords)
    // should not trigger A02001.
    let src = r#"
type Wrapper {
  x: Int;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("lowercase tokens should not be checked as types");
}

#[test]
fn sized_int_types_resolve() {
    let src = r#"
type Packet {
  header: U32;
  length: U16;
  checksum: U8;
  signed_val: I64;
  ratio: F32;
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("sized integer types should resolve");
}

#[test]
fn generic_builtin_components_resolve() {
    // In `List<Int>`, both `List` and `Int` should resolve.
    // The raw tokens will be something like ["List", "<", "Int", ">"]
    let src = r#"
fn process(items: List) -> Nat {
  ensures { result >= 0 }
}
"#;
    let file = parse_ok(src);
    resolve(&file).expect("generic type components should resolve");
}

#[test]
fn nested_same_name_scopes_resolve_correctly() {
    // A service-nested type and a top-level type with the same name
    // should each resolve in their own scope without collision.
    let src = r#"
type Config {
  x: Int
}

service MyService {
  type Config {
y: Nat
  }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("should resolve without errors");
    // Both Config types should exist
    let configs: Vec<&Symbol> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.name == "Config")
        .collect();
    assert_eq!(configs.len(), 2, "should have two Config symbols");
}

#[test]
fn block_does_not_register_as_contract() {
    // A block declaration should NOT register as a ContractDef
    let src = r#"
contract RealContract {
  requires { true }
}

feature enhanced_mode {
  requires { true }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("should resolve");
    // RealContract is a ContractDef, but enhanced_mode should not be
    let contract_defs: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::ContractDef)
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        contract_defs.contains(&"RealContract"),
        "RealContract should be ContractDef"
    );
    assert!(
        !contract_defs.contains(&"enhanced_mode"),
        "block should not be registered as ContractDef"
    );
}

#[test]
fn enum_variant_types_checked_in_strict_mode() {
    // In strict mode (no module/project/imports), unknown types in
    // enum variant fields should be reported as A02001.
    let src = r#"
enum MyResult {
  Ok(Int)
  Err(ErrorDetails)
}
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    // ErrorDetails is not a known type, should trigger A02001
    // (Int is a builtin, so only ErrorDetails should fail)
    assert!(
        result.is_err(),
        "should detect unknown type in enum variant"
    );
    let errs = result.unwrap_err();
    assert!(
        errs.iter().any(|e| e.code == "A02001"),
        "should report A02001 for unknown type"
    );
}

#[test]
fn selective_import_injects_symbols() {
    let src = r#"
import std.collections { List, Map };
type MyData {
  items: List
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("should resolve with imported types");
    // List and Map should be in the symbol table as BuiltinType
    let names: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        names.contains(&"List"),
        "List should be injected from import"
    );
    assert!(names.contains(&"Map"), "Map should be injected from import");
}

#[test]
fn aliased_import_injects_alias() {
    let src = r#"
import crypto.hash as hash;
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("should resolve");
    let names: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        names.contains(&"hash"),
        "alias should be injected from import"
    );
}

#[test]
fn bare_import_injects_last_segment() {
    let src = r#"
import std.math;
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("should resolve");
    let names: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        names.contains(&"math"),
        "last path segment should be injected from import"
    );
}

#[test]
fn duplicate_import_detected() {
    let src = r#"
import std.math;
import std.math;
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(result.is_err(), "duplicate import should produce an error");
    let errs = result.unwrap_err();
    assert!(
        errs.iter().any(|e| e.code == "A02006"),
        "should report A02006 for duplicate import"
    );
}

#[test]
fn different_imports_not_duplicate() {
    let src = r#"
import std.math;
import std.collections;
"#;
    let file = parse_ok(src);
    resolve(&file).expect("different imports should not be duplicates");
}

#[test]
fn unused_import_reported_as_warning() {
    // Single-file resolve: unknown import is A02010 (cannot resolve), not
    // the misleading A02007 unused import.
    let src = r#"
import std.math;
contract Foo {
requires { x > 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve succeeds (warnings are not errors)");
    assert!(
        resolved
            .warnings
            .iter()
            .any(|w| w.code == "A02010" && w.message.contains("std.math")),
        "expected A02010 cannot-resolve warning for std.math, got {:?}",
        resolved.warnings
    );
    assert!(
        resolved.warnings.iter().all(|w| w.code != "A02007"),
        "unresolved imports must not also be A02007 unused"
    );
}

#[test]
fn unused_resolved_import_is_a02007() {
    // When the module is in the map, an unused import is A02007.
    let target_src = r#"
module std.math;
type T { x: Int }
"#;
    let target_file = parse_ok(target_src);
    let mut module_map = ModuleMap::new();
    module_map.insert("std.math".to_string(), target_file);

    let src = r#"
import std.math;
contract Foo {
requires { true }
}
"#;
    let file = parse_ok(src);
    let mut visited = HashSet::new();
    let resolved =
        resolve_with_modules(&file, &module_map, &mut visited).expect("resolve succeeds");
    assert!(
        resolved
            .warnings
            .iter()
            .any(|w| w.code == "A02007" && w.message.contains("std.math")),
        "expected A02007 unused for resolved import, got {:?}",
        resolved.warnings
    );
}

#[test]
fn used_import_no_warning() {
    // The import introduces "List" which appears in a type annotation
    let src = r#"
import std.collections { List };
type Wrapper {
items: List
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve succeeds");
    assert!(
        !resolved.warnings.iter().any(|w| w.code == "A02007"),
        "no unused import warning expected when imported name is used"
    );
}

#[test]
fn unused_selective_import_warning() {
    let src = r#"
import std.collections { Map, Set };
type Wrapper {
items: Map
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve succeeds");
    // Map is used, but the import brings both Map and Set.
    // Since at least one name (Map) is referenced, the import is considered used.
    assert!(
        !resolved.warnings.iter().any(|w| w.code == "A02007"),
        "import with at least one used name should not be flagged"
    );
}

#[test]
fn import_path_uppercase_last_segment_allowed() {
    // The last segment of an import path can be uppercase (symbol name).
    // `import std.Math` means "import symbol Math from module std".
    let src = r#"
import std.Math;
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    // Should succeed: uppercase last segment is a symbol reference
    assert!(
        result.is_ok(),
        "uppercase last segment should be allowed: {result:?}"
    );
}

#[test]
fn import_path_uppercase_module_segment_rejected() {
    // Module path segments (non-last) must start with lowercase.
    // `import Std.math` has an uppercase module segment, which is invalid.
    let src = r#"
import Std.math;
"#;
    let file = parse_ok(src);
    let result = resolve(&file);
    assert!(
        result.is_err(),
        "uppercase module segment should produce an error"
    );
    let errs = result.unwrap_err();
    assert!(
        errs.iter().any(|e| e.code == "A02008"),
        "should report A02008 for invalid path segment: {errs:?}"
    );
}

#[test]
fn import_path_valid_segments_pass() {
    // Valid path segments: lowercase, underscores
    let src = r#"
import std.math;
import crypto.hash_utils;
"#;
    let file = parse_ok(src);
    resolve(&file).expect("valid import paths should resolve without errors");
}

#[test]
fn is_valid_path_segment_tests() {
    use imports::is_valid_path_segment;
    assert!(is_valid_path_segment("std"));
    assert!(is_valid_path_segment("math"));
    assert!(is_valid_path_segment("hash_utils"));
    assert!(is_valid_path_segment("_private"));
    assert!(is_valid_path_segment("x86"));
    assert!(!is_valid_path_segment("Math"));
    assert!(!is_valid_path_segment("123"));
    assert!(!is_valid_path_segment(""));
    assert!(!is_valid_path_segment("foo-bar"));
}

// -----------------------------------------------------------------------
// Input param extraction tests
// -----------------------------------------------------------------------

#[test]
fn extract_input_params_raw_tokens() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Raw(vec![
        "a".to_string(),
        ":".to_string(),
        "Int".to_string(),
        ",".to_string(),
        "b".to_string(),
        ":".to_string(),
        "Nat".to_string(),
    ]));
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["a", "b"]);
}

#[test]
fn extract_input_params_generic_type() {
    use assura_parser::ast::Expr;
    // input(items: List<Int>, count: Nat)
    let body = Spanned::no_span(Expr::Raw(vec![
        "items".into(),
        ":".into(),
        "List".into(),
        "<".into(),
        "Int".into(),
        ">".into(),
        ",".into(),
        "count".into(),
        ":".into(),
        "Nat".into(),
    ]));
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["items", "count"]);
}

#[test]
fn extract_input_params_call_expr() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Call {
        func: Box::new(Spanned::no_span(Expr::Ident("input".to_string()))),
        args: vec![
            Spanned::no_span(Expr::Cast {
                expr: Box::new(Spanned::no_span(Expr::Ident("x".to_string()))),
                ty: "Int".to_string(),
            }),
            Spanned::no_span(Expr::Ident("y".to_string())),
        ],
    });
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["x", "y"]);
}

#[test]
fn extract_input_params_ident() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Ident("x".to_string()));
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["x"]);
}

#[test]
fn extract_input_params_cast() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Cast {
        expr: Box::new(Spanned::no_span(Expr::Ident("n".to_string()))),
        ty: "Int".to_string(),
    });
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["n"]);
}

#[test]
fn extract_input_params_tuple() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Tuple(vec![
        Spanned::no_span(Expr::Cast {
            expr: Box::new(Spanned::no_span(Expr::Ident("a".to_string()))),
            ty: "Int".to_string(),
        }),
        Spanned::no_span(Expr::Ident("b".to_string())),
    ]));
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["a", "b"]);
}

#[test]
fn extract_input_params_raw_as_separator() {
    use assura_parser::ast::Expr;
    let body = Spanned::no_span(Expr::Raw(vec![
        "x".into(),
        "as".into(),
        "Int".into(),
        ",".into(),
        "y".into(),
        "as".into(),
        "Nat".into(),
    ]));
    let names = extract_input_param_names(&body);
    assert_eq!(names, vec!["x", "y"]);
}

// -----------------------------------------------------------------------
// Contract input params registered in scope
// -----------------------------------------------------------------------

#[test]
fn contract_input_params_in_scope() {
    let src = r#"
contract Foo {
  input(a: Int, b: Int)
  requires { a > 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // Parameters a and b should be in the contract's scope
    let params: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Parameter)
        .map(|s| s.name.as_str())
        .collect();
    assert!(params.contains(&"a"), "param a not found");
    assert!(params.contains(&"b"), "param b not found");
}

#[test]
fn contract_input_and_inline_fn_same_params_not_duplicate() {
    // Dogfood: natural form combines input(...) with named inline fn.
    let src = r#"
contract Safe {
  input(x: Int, y: Int)
  requires { y != 0 }
  ensures { true }
  fn div(x: Int, y: Int) -> Int
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("input + inline fn should not A02003");
    let params: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Parameter)
        .map(|s| s.name.as_str())
        .collect();
    assert!(params.contains(&"x"));
    assert!(params.contains(&"y"));
    assert_eq!(
        params.iter().filter(|n| **n == "x").count(),
        1,
        "x registered once"
    );
}

#[test]
fn contract_input_params_accessible_from_ensures() {
    // Params declared in input should be usable in ensures
    let src = r#"
contract Div {
  input(a: Int, b: Int)
  output(result: Int)
  requires { b != 0 }
  ensures  { result * b <= a }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let contract_scope = resolved
        .symbols
        .scopes
        .iter()
        .position(|s| s.name == "Div")
        .expect("Div scope not found");
    // a, b, result should all be accessible from the contract scope
    resolved.symbols.lookup("a", contract_scope).unwrap();
    resolved.symbols.lookup("b", contract_scope).unwrap();
    // result is a built-in value name, not in the symbol table,
    // but won't produce a warning in clause body checks
}

// -----------------------------------------------------------------------
// Expression-level name resolution warnings
// -----------------------------------------------------------------------

#[test]
fn undefined_name_in_clause_body_warns() {
    // No imports, no module => strict mode. 'c' is undefined.
    let src = r#"
contract Foo {
  input(a: Int, b: Int)
  requires { c > 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve succeeds (warnings, not errors)");
    let body_warnings: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|w| w.code == "A02001" && w.message.contains("undefined name"))
        .collect();
    assert!(
        body_warnings.iter().any(|w| w.message.contains("`c`")),
        "should warn about undefined `c`: {body_warnings:?}"
    );
}

#[test]
fn defined_name_in_clause_body_no_warning() {
    // 'a' is defined in input clause, should not produce a warning
    let src = r#"
contract Foo {
  input(a: Int, b: Int)
  requires { a > 0 }
  ensures  { result >= 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let body_warnings: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|w| w.message.contains("undefined name"))
        .collect();
    assert!(
        body_warnings.is_empty(),
        "should not warn about defined params: {body_warnings:?}"
    );
}

#[test]
fn fn_param_in_clause_body_no_warning() {
    let src = r#"
fn helper(n: Int) -> Int {
  requires { n > 0 }
  ensures  { result >= n }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let body_warnings: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|w| w.message.contains("undefined name"))
        .collect();
    assert!(
        body_warnings.is_empty(),
        "fn params should not trigger warnings: {body_warnings:?}"
    );
}

#[test]
fn quantifier_var_in_scope_no_warning() {
    // Quantifier variable 'x' should be locally scoped
    let src = r#"
contract ListCheck {
  input(items: List)
  ensures { forall x in items: x > 0 }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    let body_warnings: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|w| w.message.contains("`x`"))
        .collect();
    assert!(
        body_warnings.is_empty(),
        "quantifier var should not trigger warnings: {body_warnings:?}"
    );
}

#[test]
fn lenient_mode_skips_unknown_names() {
    // With imports, lenient mode skips unknown names
    let src = r#"
import std.math;

contract Foo {
  input(a: Int)
  requires { external_check(a) }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed in lenient mode");
    let body_warnings: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|w| w.message.contains("undefined name"))
        .collect();
    assert!(
        body_warnings.is_empty(),
        "lenient mode should not warn: {body_warnings:?}"
    );
}

#[test]
fn service_other_item_body_resolved() {
    // ServiceItem::Other { kind, body } should have its body
    // expression walked for identifier resolution.
    let src = r#"
service Svc {
  priority { true }
}
"#;
    let file = parse_ok(src);
    // "priority" is not a recognized keyword, so it parses as
    // ServiceItem::Other { kind: "priority", body: Ident("true") }.
    // resolve() should succeed without errors, proving the body
    // expression was walked (not silently skipped).
    resolve(&file).expect("service with Other item should resolve");
}

#[test]
fn service_operation_params_in_scope() {
    let src = r#"
service Svc {
  operation doStuff {
input { name: String }
requires { name.length() > 0 }
  }
}
"#;
    let file = parse_ok(src);
    let resolved = resolve(&file).expect("resolve should succeed");
    // 'name' should be registered as a parameter in the operation scope
    let params: Vec<&str> = resolved
        .symbols
        .symbols
        .iter()
        .filter(|s| s.kind == SymbolKind::Parameter && s.name == "name")
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        !params.is_empty(),
        "service operation input params should be in scope"
    );
}

// ===================================================================
// A002: Module resolution tests
// ===================================================================

#[test]
fn find_project_root_with_toml() {
    let dir = std::env::temp_dir().join("assura-test-root");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("assura.toml"), "[project]\nname = \"test\"\n").unwrap();

    let sub = dir.join("src");
    std::fs::create_dir_all(&sub).unwrap();
    let file = sub.join("main.assura");
    std::fs::write(&file, "").unwrap();

    let root = find_project_root(&file);
    assert_eq!(root.unwrap(), dir);

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn find_project_root_none() {
    // A temp file with no assura.toml anywhere above
    let dir = std::env::temp_dir().join("assura-test-no-root");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("test.assura");
    std::fs::write(&file, "").unwrap();

    // May or may not find one depending on whether assura.toml
    // exists somewhere above /tmp. Just check it doesn't panic.
    let _ = find_project_root(&file);

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn resolve_module_path_existing() {
    use project::resolve_module_path;
    let dir = std::env::temp_dir().join("assura-test-mod-resolve");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("math")).unwrap();
    std::fs::write(
        dir.join("math/util.assura"),
        "module math.util;\ncontract Add {\n  input(a: Int)\n}",
    )
    .unwrap();

    let path = vec!["math".into(), "util".into()];
    let result = resolve_module_path(&dir, &path);
    assert!(result.unwrap().ends_with("math/util.assura"));

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn resolve_module_path_missing() {
    use project::resolve_module_path;
    let dir = std::env::temp_dir().join("assura-test-mod-missing");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let path = vec!["nonexistent".into(), "module".into()];
    assert!(resolve_module_path(&dir, &path).is_none());

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn file_to_module_path_conversion() {
    use project::file_to_module_path;
    let root = std::path::Path::new("/project");
    let file = std::path::Path::new("/project/src/math/util.assura");
    let result = file_to_module_path(file, root);
    assert_eq!(result, "src.math.util");
}

#[test]
fn build_module_graph_single_file() {
    use project::{DependencyMap, build_module_graph_with_deps};
    let dir = std::env::temp_dir().join("assura-test-graph-single");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.assura"),
        "module test.main;\ncontract Foo {\n  input(x: Int)\n}",
    )
    .unwrap();

    let graph = build_module_graph_with_deps(&dir.join("main.assura"), &dir, &DependencyMap::new());
    assert_eq!(graph.modules.len(), 1);
    assert_eq!(graph.order.len(), 1);

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn resolve_module_graph_produces_resolved_files() {
    use project::{DependencyMap, build_module_graph_with_deps, resolve_module_graph};
    let dir = std::env::temp_dir().join("assura-test-resolve-graph");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.assura"),
        "module test.main;\ncontract Bar {\n  input(x: Int)\n}",
    )
    .unwrap();

    let graph = build_module_graph_with_deps(&dir.join("main.assura"), &dir, &DependencyMap::new());
    let (resolved, errs) = resolve_module_graph(&graph);
    // The single module may have resolution warnings but should produce a result
    assert!(!resolved.is_empty() || !errs.is_empty());

    let _ = std::fs::remove_dir_all(&dir);
}

// -----------------------------------------------------------------------
// Multi-file project resolution tests (issue #64)
// -----------------------------------------------------------------------

/// Helper: set up a multi-file project in a temp dir and return the root.
fn setup_multi_file_project(name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("assura-multi-{name}"));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(
        dir.join("assura.toml"),
        format!("[project]\nname = \"{name}\""),
    )
    .unwrap();
    dir
}

#[test]
fn multi_file_valid_cross_module_import() {
    let dir = setup_multi_file_project("valid-import");
    let src = dir.join("src");
    std::fs::write(
        src.join("math.assura"),
        "module math\ncontract Add {\n  requires(a: Int, b: Int)\n  ensures(result: Int)\n}",
    )
    .unwrap();
    std::fs::write(
        src.join("main.assura"),
        "module main\nimport math.Add\ncontract Main {\n  requires(x: Int)\n  ensures(result: Int)\n}",
    )
    .unwrap();

    let (resolved, warnings) =
        discover_and_resolve_project(&dir).expect("multi-file project with import should resolve");
    assert!(
        resolved.contains_key("math"),
        "math module should be resolved"
    );
    assert!(
        resolved.contains_key("main"),
        "main module should be resolved"
    );
    assert!(warnings.is_empty(), "no warnings expected: {warnings:?}");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn multi_file_missing_import() {
    let dir = setup_multi_file_project("missing-import");
    let src = dir.join("src");
    std::fs::write(
        src.join("main.assura"),
        "module main\nimport nonexistent.Foo\ncontract Main {\n  requires(x: Int)\n}",
    )
    .unwrap();

    // Missing imports hard-fail with A02010 when a project module map is present.
    let result = discover_and_resolve_project(&dir);
    match result {
        Ok((resolved, issues)) => {
            // Some modules may still resolve; issues must report the miss.
            assert!(
                !issues.is_empty() || !resolved.contains_key("main"),
                "missing import must surface as issue or omit the broken module"
            );
            if !issues.is_empty() {
                assert!(
                    issues
                        .iter()
                        .any(|i| i.contains("nonexistent") || i.contains("resolution")),
                    "expected missing-import issue, got {issues:?}"
                );
            }
        }
        Err(errors) => {
            assert!(
                errors
                    .iter()
                    .any(|e| e.contains("resolution") || e.contains("nonexistent")),
                "expected resolution error, got {errors:?}"
            );
        }
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn multi_file_circular_import() {
    let dir = setup_multi_file_project("circular");
    let src = dir.join("src");
    std::fs::write(
        src.join("a.assura"),
        "module a\nimport b\ncontract Foo {\n  requires { true }\n}",
    )
    .unwrap();
    std::fs::write(
        src.join("b.assura"),
        "module b\nimport a\ncontract Bar {\n  requires { true }\n}",
    )
    .unwrap();

    let (resolved, warnings) = discover_and_resolve_project(&dir)
        .expect("circular import project should return Ok with warnings");
    assert!(!resolved.is_empty(), "at least one module should resolve");
    let has_circ = warnings.iter().any(|w| w.contains("circular"));
    assert!(
        has_circ,
        "a↔b project import cycle must be reported: warnings={warnings:?}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn multi_file_declared_module_name_used_as_key() {
    // Verify that declared module names (not filesystem paths) are used
    let dir = setup_multi_file_project("declared-key");
    let src = dir.join("src");
    std::fs::write(
        src.join("utils.assura"),
        "module helpers\ncontract Aid {\n  requires(x: Int)\n}",
    )
    .unwrap();

    let result = discover_and_resolve_project(&dir);
    let (resolved, _) = result.unwrap();
    // Key should be "helpers" (declared), not "src.utils" (filesystem)
    assert!(
        resolved.contains_key("helpers"),
        "module key should be declared name 'helpers', got keys: {:?}",
        resolved.keys().collect::<Vec<_>>()
    );
    assert!(
        !resolved.contains_key("src.utils"),
        "should NOT use filesystem path as key"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn multi_file_no_assura_files() {
    let dir = setup_multi_file_project("empty");
    // Don't create any .assura files
    let result = discover_and_resolve_project(&dir);
    assert!(result.is_err(), "should fail with no .assura files");
    let errors = result.unwrap_err();
    assert!(
        errors.iter().any(|e| e.contains("no .assura files")),
        "should say no files found: {errors:?}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn find_module_prefix_matches() {
    use imports::find_module_prefix;
    let mut map = ModuleMap::new();
    let source = parse_ok("module math\ncontract Add { requires(x: Int) }");
    map.insert("math".to_string(), source);

    // "math.Add" should find "math" as prefix
    let path = vec!["math".to_string(), "Add".to_string()];
    assert_eq!(find_module_prefix(&path, &map), Some("math".to_string()));

    // "math" should match directly
    let path2 = vec!["math".to_string()];
    assert_eq!(find_module_prefix(&path2, &map), Some("math".to_string()));

    // "nonexistent" should return None
    let path3 = vec!["nonexistent".to_string()];
    assert_eq!(find_module_prefix(&path3, &map), None);
}

/// Regression test for #171: fn params must be visible in clause bodies.
#[test]
fn test_contract_params_visible_in_clauses() {
    let src = r#"
contract Safe {
requires n > 0
ensures result > 0
fn identity(n: Int) -> Int
}
"#;
    let file = assura_parser::parse_unwrap(src);
    let resolved = resolve(&file).expect("resolve failed");
    // No A02001 errors about `n` being undefined
    let a02001_errors: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|e| e.code == "A02001")
        .collect();
    assert!(
        a02001_errors.is_empty(),
        "fn params should not produce A02001, got: {:?}",
        a02001_errors
    );
}

/// feature_max constants must resolve in clause bodies (no false A02001).
/// SMT already binds their values; resolve must register the name.
#[test]
fn test_feature_max_visible_in_clauses() {
    let src = r#"
feature_max MAX_SIZE: Nat = 280
feature_max MAX_LEN: Nat = 15

fn check_bounds(size: Nat, max_len: Nat)
  requires { size <= MAX_SIZE }
  requires { max_len <= MAX_LEN }
  ensures  { size + max_len <= 295 }
  ensures  { MAX_SIZE == 280 }
  effects: pure
"#;
    let file = assura_parser::parse_unwrap(src);
    let resolved = resolve(&file).expect("resolve failed");
    let a02001: Vec<_> = resolved
        .warnings
        .iter()
        .filter(|e| e.code == "A02001")
        .collect();
    assert!(
        a02001.is_empty(),
        "feature_max names must not produce A02001, got: {a02001:?}"
    );
    assert!(
        resolved
            .symbols
            .symbols
            .iter()
            .any(|s| s.name == "MAX_SIZE"),
        "MAX_SIZE should be registered in the symbol table"
    );
}