midenc-codegen-masm 0.10.0

Miden Assembly backend for the Miden compiler
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
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
use alloc::{collections::BTreeMap, format, rc::Rc, string::String};
use core::cell::RefCell;

use midenc_hir::{
    Context, OperationRef, PointerType,
    diagnostics::Uri,
    dialects::builtin::{FunctionRef, attributes::UnitAttr},
};
use midenc_session::{
    InputFile, Options, Session,
    diagnostics::{CaptureEmitter, DefaultSourceManager},
};

use super::*;

// -------------------------------------------------------------------------------------
// Fixtures.
//
// Task 7's, copied from `midenc-compile/src/pipeline/frontends/hir.rs` rather than shared:
// `midenc-compile` depends on this crate, so nothing here can import from it. Its report
// records which shapes parse — in particular that a component id is *one quoted*
// symbol-path component, because `ComponentId::try_from` splits the `:` and the `@` back
// out of it itself.
// -------------------------------------------------------------------------------------

/// A component, written on its own — the other half of the equivalence [`WORLD`] pins.
const COMPONENT: &str = r#"
builtin.component private @"hir_ns:test@1.0.0" {
builtin.module private @test {
    builtin.function public extern("C") @main() {
        builtin.ret;
    };
};
};
"#;

/// [`COMPONENT`] inside the world that declares it — the *shape* `--emit=hir` writes, and so
/// the shape a whole-world `.hir` file has.
///
/// Not its literal text, though: `OpPrinter for builtin::Component` prints the id **bare**
/// (`@hir_ns:test@1.0.0`) while the parser requires it **quoted**, so `--emit=hir` output
/// holding a component does not re-parse. The quoting here works around that; the defect
/// is recorded as a `TODO(hir)` on that printer.
const WORLD: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module private @test {
        builtin.function public extern("C") @main() {
            builtin.ret;
        };
    };
};
};
"#;

/// [`WORLD`] with an *external dependency represented in the IR* beside its component.
///
/// The sibling's one function is declared and not defined — an empty body is what
/// `Symbol::is_declaration` keys on, and therefore what `is_declaration_only` asks about.
///
/// The braces are empty rather than absent on purpose. `builtin.function` carries the
/// `SingleRegion` trait, so a function written with no region at all fails verification
/// ("requires exactly one region, but got 0") even though that is precisely how the printer
/// writes a declaration. An empty region is a body with no blocks, which is what
/// `is_declaration` means.
const WORLD_WITH_DECLARATION_ONLY_SIBLING: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module private @test {
        builtin.function public extern("C") @main() {
            builtin.ret;
        };
    };
};
builtin.module public @external_dep {
    builtin.function public extern("C") @sibling() {
    };
};
};
"#;

/// [`WORLD`] with a *supporting module* beside its component.
///
/// Identical to [`WORLD_WITH_DECLARATION_ONLY_SIBLING`] but for the sibling's body, which is
/// the single bit `is_declaration_only` decides on — and, since this one defines a function
/// and owns no memory, the fixture every "translated beside the component" assertion rests on.
const WORLD_WITH_SUPPORTING_SIBLING: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module private @test {
        builtin.function public extern("C") @main() {
            builtin.ret;
        };
    };
};
builtin.module public @supporting {
    builtin.function public extern("C") @sibling() {
        builtin.ret;
    };
};
};
"#;

/// [`WORLD_WITH_SUPPORTING_SIBLING`] whose component *calls* the sibling beside it.
///
/// Written out rather than derived, because the call is what it exists for: it is the only
/// fixture here with a cross-item invocation for the assembler's linker to resolve.
///
/// The `@test` module is `public` because its `main` is this component's whole interface: the
/// assembled package surface is derived from the root's public submodules, so a private module
/// here would leave the library with no exports at all.
const WORLD_CALLING_ITS_SUPPORTING_SIBLING: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @test {
        builtin.function public extern("C") @main() {
            hir.exec ::@supporting::@sibling() : extern("C") () -> ();
            builtin.ret;
        };
    };
};
builtin.module public @supporting {
    builtin.function public extern("C") @sibling() {
        builtin.ret;
    };
};
};
"#;

/// [`WORLD_WITH_SUPPORTING_SIBLING`] whose sibling also *defines a global variable*.
///
/// Derived from the shared fixture rather than written out, so the only thing that can differ
/// between "translated beside the component" and "diagnosed" is the item this inserts —
/// exactly the bit `module_owns_memory` decides on.
fn world_with_a_sibling_defining_a_global() -> String {
    WORLD_WITH_SUPPORTING_SIBLING.replace(
        "builtin.module public @supporting {",
        "builtin.module public @supporting {\n        builtin.global_variable public @g : i32 \
         {\n            builtin.ret_imm 1 : i32;\n        };",
    )
}

/// [`WORLD_WITH_SUPPORTING_SIBLING`] whose sibling *declares* a global rather than defining
/// one.
///
/// The discriminating half of [`world_with_a_sibling_defining_a_global`]: a declaration
/// contributes nothing to the data layout — `Linker::link` skips it — but it is still an item
/// a component owns, so the rule treats it the same way.
fn world_with_a_sibling_declaring_a_global() -> String {
    WORLD_WITH_SUPPORTING_SIBLING.replace(
        "builtin.module public @supporting {",
        "builtin.module public @supporting {\n        builtin.global_variable public @g : i32;",
    )
}

/// [`WORLD_WITH_SUPPORTING_SIBLING`] with the identity `frontend/wasm` gives the component it
/// wraps around a core Wasm module.
///
/// The id alone does not make it the wrapper — see [`mark_as_synthetic_wrapper`], which is what
/// a fixture standing in for the wrapper has to be put through as well.
fn wrapper_world_with_a_supporting_sibling() -> String {
    WORLD_WITH_SUPPORTING_SIBLING.replace("hir_ns:test@1.0.0", "root_ns:root@1.0.0")
}

/// Mark `world`'s component as one the compiler invented, the way `frontend/wasm` marks the
/// wrapper it builds around a bare core Wasm module.
///
/// This cannot be written into a fixture: `builtin.component`'s textual form carries no
/// attributes, so the marker has to be set on the parsed IR — which is where the frontend sets
/// it too, rather than on any text.
fn mark_as_synthetic_wrapper(world: builtin::WorldRef) {
    let mut component = {
        let world = world.borrow();
        let body = world.body();
        let component = body
            .entry()
            .body()
            .iter()
            .find_map(|op| op.as_operation_ref().try_downcast_op::<builtin::Component>().ok());
        component.expect("the fixture must declare a component to mark")
    };
    component.borrow_mut().mark_synthetic_wrapper();
}

/// [`WORLD_WITH_SUPPORTING_SIBLING`] whose supporting module also holds a function with **no
/// body**.
///
/// Derived from the shared fixture, so the sibling still owns no memory and still defines
/// `@sibling` — it is therefore *not* declaration-only, and `classify_siblings` hands it over to
/// be translated. The inserted function is the only difference, and the only thing that can make
/// the lowering fail.
///
/// A module whose functions are *all* body-less is a different case entirely: that is
/// [`WORLD_WITH_DECLARATION_ONLY_SIBLING`], an external dependency represented in the IR, which
/// is dropped before it ever reaches codegen. Only a module that mixes the two gets here.
fn world_with_a_sibling_declaring_one_of_its_functions() -> String {
    WORLD_WITH_SUPPORTING_SIBLING.replace(
        "builtin.module public @supporting {",
        "builtin.module public @supporting {\n        builtin.function public extern(\"C\") \
         @undefined() {\n        };",
    )
}

/// [`COMPONENT`] whose module also holds a function with **no body**.
///
/// The component-path counterpart of
/// [`world_with_a_sibling_declaring_one_of_its_functions`], derived from the very fixture that
/// `a_component_lowers_rooted_at_its_own_id` lowers successfully, so the inserted function is
/// again the only difference. See [`WORLD_WITH_DECLARATION_ONLY_SIBLING`] on why the braces are
/// empty rather than absent.
fn component_with_a_declared_function_in_its_module() -> String {
    COMPONENT.replace(
        "builtin.module private @test {",
        "builtin.module private @test {\n        builtin.function public extern(\"C\") \
         @undefined() {\n        };",
    )
}

/// [`COMPONENT`] with a body-less function of its own, beside its module rather than inside it.
///
/// A component may declare functions directly — `Component`'s own docs call them
/// "component-level functions, e.g. a program entrypoint" — and those reach
/// `MasmComponentBuilder::define_function` rather than `MasmModuleBuilder::define_function`,
/// which is the *other* caller of `MasmFunctionBuilder::new`.
fn component_with_a_declared_component_level_function() -> String {
    COMPONENT.replace(
        "builtin.module private @test {",
        "builtin.function public extern(\"C\") @undefined() {\n    };\n    builtin.module private \
         @test {",
    )
}

/// Define a data segment in `module`.
///
/// Built rather than written, because a `builtin.segment` **cannot be written in `.hir` text
/// at all**: its `offset` is a `U32Attr`, and an attribute dictionary parses its values with
/// `Type::Unknown` (`Parser::parse_attribute_dict`), for which an integer literal falls
/// through to "invalid attribute value" (`hir/src/ir/parse/parser.rs:412`). Recorded here
/// rather than only in a report, since the next person to want a segment fixture will land on
/// the same wall.
fn define_a_data_segment_in(module: builtin::ModuleRef) {
    use midenc_hir::dialects::builtin::ModuleBuilder;

    ModuleBuilder::new(module)
        .define_data_segment(1024, alloc::vec![1u8, 2, 3, 4], true, SourceSpan::default())
        .expect("should define a data segment");
}

/// The top-level module of `world` named `name`.
fn top_level_module(world: &builtin::World, name: &str) -> builtin::ModuleRef {
    world
        .body()
        .entry()
        .body()
        .iter()
        .find_map(|op| {
            op.as_operation_ref()
                .try_downcast_op::<builtin::Module>()
                .ok()
                .filter(|module| module.borrow().name().as_str() == name)
        })
        .unwrap_or_else(|| panic!("the fixture declares a top-level module named '{name}'"))
}

/// The paths of `component`'s modules, in the order lowering defined them.
fn module_paths(component: &MasmComponent) -> Vec<String> {
    component.modules.iter().map(|module| module.path().to_string()).collect()
}

/// A world declaring two components, which is what this crate does not implement.
const TWO_COMPONENT_WORLD: &str = r#"
builtin.world {
builtin.component private @"hir_ns:first@1.0.0" {
    builtin.module private @first {
        builtin.function public extern("C") @main() {
            builtin.ret;
        };
    };
};
builtin.component private @"hir_ns:second@1.0.0" {
    builtin.module private @second {
        builtin.function public extern("C") @other() {
            builtin.ret;
        };
    };
};
};
"#;

/// A bare `builtin.module`, which the parser likewise anchors at a world of its own.
///
/// That world holds no component at all, which is the shape `frontend/masm`'s disassembler
/// produces — `declare_modules` defines modules directly on the world — and therefore the
/// live path this change must leave alone.
const MODULE: &str = r#"
builtin.module public @lib {
builtin.function public extern("C") @main() {
    builtin.ret;
};
};
"#;

/// [`MODULE`] twice over: a component-less world declaring **several** top-level modules.
///
/// Derived from the shared fixture rather than written out, so it cannot drift from the
/// single-module shape it is the counterpart of — the same construction
/// `a_hir_root_declaring_several_top_level_modules_declares_nothing` uses in
/// `midenc-compile/src/pipeline/prepare.rs`, which is the preparation half of the same
/// question.
fn two_module_world() -> String {
    format!("builtin.world {{{}{}}};\n", MODULE, MODULE.replace("@lib", "@second"))
}

/// A library target whose namespace is `namespace`, as [`MasmComponent::source_inputs`]
/// receives one.
fn library_target(namespace: &str) -> midenc_session::miden_project::Target {
    midenc_session::miden_project::Target::library(
        Arc::<masm::Path>::from(
            masm::LibraryPath::new(namespace)
                .unwrap()
                .to_absolute()
                .unwrap()
                .into_owned()
                .into_boxed_path(),
        ),
        Uri::new("lib.hir"),
    )
}

/// Assemble `component` as a library and return its complete, sorted public procedure surface.
fn assembled_library_exports(
    context: &Rc<Context>,
    component: &MasmComponent,
    namespace: &str,
) -> Vec<String> {
    let target = library_target(namespace);
    let sources = component
        .source_inputs(&target, context.session())
        .expect("the lowered component should provide assembler inputs");
    let package = miden_assembly::Assembler::new(context.session().source_manager.clone())
        .assemble_library(namespace, sources.root, sources.support)
        .expect("the lowered component should assemble as a library");
    let mut exports = package
        .manifest
        .exports()
        .map(|export| export.path().as_ref().as_str().to_string())
        .collect::<Vec<_>>();
    exports.sort();
    exports
}

/// Parse `text`, returning the top-level operation it holds.
///
/// `verify: true` matches what the `.hir` frontend does, since HIR that arrives as text has
/// not been through any of the builders that maintain the IR's invariants.
fn parse(context: &Rc<Context>, text: &str) -> OperationRef {
    let config = midenc_hir::parse::ParserConfig {
        context: context.clone(),
        verify: true,
    };
    midenc_hir::parse::parse_any(config, Uri::new("test.hir"), text)
        .expect("the fixture should parse")
}

/// Lower `world`, as `pipeline::backend::codegen` does when extraction named no component:
/// the analysis manager is rooted at the world, not at anything inside it.
fn lower_world(world: builtin::WorldRef) -> Result<MasmComponent, Report> {
    let analysis_manager = AnalysisManager::new(world.as_operation_ref(), None);
    let world = world.borrow();
    world.to_masm_component(analysis_manager)
}

/// Lower `text`, whose top-level operation must be a `builtin.component`, as
/// `pipeline::backend::codegen` does when extraction *did* name a component: through the
/// component impl directly, with the world the parser anchored it at never consulted. This is
/// the path every WebAssembly and Rust build takes.
fn lower_component(context: &Rc<Context>, text: &str) -> Result<MasmComponent, Report> {
    let op = parse(context, text);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    let analysis_manager = AnalysisManager::new(op, None);
    component.borrow().to_masm_component(analysis_manager)
}

/// Lower a component through the MASM legalization boundary used by the compiler pipeline.
fn legalize_and_lower_component(
    context: &Rc<Context>,
    text: &str,
) -> Result<MasmComponent, Report> {
    use midenc_hir::pass::{Nesting, PassManager};

    let op = parse(context, text);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    let mut pm = PassManager::on::<builtin::Component>(context.clone(), Nesting::Implicit);
    pm.add_pass(alloc::boxed::Box::new(crate::LegalizeForMasm));
    pm.enable_verifier(false);
    pm.run(component.as_operation_ref())?;

    let analysis_manager = AnalysisManager::new(op, None);
    component.borrow().to_masm_component(analysis_manager)
}

/// Lower a world through the MASM legalization boundary used by the compiler pipeline.
fn legalize_and_lower_world(context: &Rc<Context>, text: &str) -> Result<MasmComponent, Report> {
    use midenc_hir::pass::{Nesting, PassManager};

    let world = parse_world(context, text);
    let mut pm = PassManager::on::<builtin::World>(context.clone(), Nesting::Implicit);
    pm.add_pass(alloc::boxed::Box::new(crate::LegalizeForMasm));
    pm.enable_verifier(false);
    pm.run(world.as_operation_ref())?;
    lower_world(world)
}

/// Parse `text`, whose top-level operation must be a `builtin.world`.
fn parse_world(context: &Rc<Context>, text: &str) -> builtin::WorldRef {
    parse(context, text)
        .try_downcast_op::<builtin::World>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a world"))
}

/// The world the parser anchored `op` at.
///
/// Only for fixtures whose top-level operation is *not* a world; one that is comes back as
/// the root, with nothing above it. See [`parse_world`].
fn anchoring_world(op: OperationRef) -> builtin::WorldRef {
    op.parent_op()
        .expect("the parser anchors every non-world top-level operation at a world it creates")
        .try_downcast_op::<builtin::World>()
        .unwrap_or_else(|_| panic!("and that anchor is a world"))
}

/// A context whose session captures its diagnostics instead of printing them.
///
/// Needed because the sibling stub's whole observable behaviour is a *warning*: it must not
/// fail the build and must not be silent, and neither half is checkable against a session
/// that writes to stderr.
fn capturing_context() -> (Rc<Context>, alloc::sync::Arc<CaptureEmitter>) {
    let emitter = alloc::sync::Arc::new(CaptureEmitter::new());
    let options = alloc::boxed::Box::new(Options::default());
    let source_manager = alloc::sync::Arc::new(DefaultSourceManager::default());
    let session = Session::new(InputFile::empty(), options, Some(emitter.clone()), source_manager)
        .expect("should build a session");
    (Rc::new(Context::new(Rc::new(session))), emitter)
}

fn context_with_entrypoint(entrypoint: &str) -> Rc<Context> {
    let options = Options {
        entrypoint: Some(entrypoint.to_string()),
        ..Default::default()
    };
    let source_manager = alloc::sync::Arc::new(DefaultSourceManager::default());
    let session =
        Session::new(InputFile::empty(), alloc::boxed::Box::new(options), None, source_manager)
            .expect("should build a session");
    Rc::new(Context::new(Rc::new(session)))
}

fn context_with_entrypoint_and_test_harness(entrypoint: &str) -> Rc<Context> {
    let options = Options {
        entrypoint: Some(entrypoint.to_string()),
        flags: midenc_session::CompileFlags::new(["--test-harness"])
            .expect("the test-harness flag must parse"),
        ..Default::default()
    };
    let source_manager = alloc::sync::Arc::new(DefaultSourceManager::default());
    let session =
        Session::new(InputFile::empty(), alloc::boxed::Box::new(options), None, source_manager)
            .expect("should build a session");
    Rc::new(Context::new(Rc::new(session)))
}

/// Everything a caller can observe about a lowered component, as one comparable value.
fn summarize(component: &MasmComponent) -> String {
    format!(
        "id: {:?}\nroot: {}\ninit: {:?}\nentrypoint: {:?}\nheap_base: {}\nstack_pointer: \
         {:?}\nrodata: {:?}\n{component}",
        component.id.as_ref().map(|id| id.to_string()),
        component.root,
        component.init,
        component.entrypoint,
        component.heap_base,
        component.stack_pointer,
        component.rodata,
    )
}

/// Find and mark a uniquely named function as the component's core Wasm start function.
fn mark_start_function(context: &Rc<Context>, root: OperationRef, name: &str) -> FunctionRef {
    let mut found = None;
    root.borrow().prewalk_all(|op| {
        let Some(function) = op.downcast_ref::<builtin::Function>() else {
            return;
        };
        if function.name().as_str() == name {
            assert!(found.is_none(), "fixture function name '{name}' must be unique");
            found = Some(function.as_function_ref());
        }
    });
    let mut function = found.unwrap_or_else(|| panic!("fixture must define function '{name}'"));
    let marker = context.create_attribute::<UnitAttr, _>(());
    function
        .borrow_mut()
        .as_operation_mut()
        .set_attribute(midenc_dialect_hir::WASM_COMPONENT_START_ATTR, marker);
    function
}

fn exec_paths(block: &masm::Block) -> Vec<String> {
    block
        .iter()
        .filter_map(|op| match op {
            masm::Op::Inst(inst) => match inst.inner() {
                masm::Instruction::Exec(masm::InvocationTarget::Path(path)) => {
                    Some(path.inner().as_str().to_string())
                }
                masm::Instruction::Exec(masm::InvocationTarget::Symbol(name)) => {
                    Some(name.as_str().to_string())
                }
                _ => None,
            },
            _ => None,
        })
        .collect()
}

fn component_init(component: &MasmComponent) -> &masm::Procedure {
    component.modules[0]
        .procedures()
        .find(|procedure| procedure.name().as_str() == "init")
        .expect("a marked component must define `init`")
}

/// A world holding a single component lowers to exactly what that component lowers to.
///
/// The defect: the world's *own* operation used to be handed to
/// [`MasmComponentBuilder::build`], which walks a component *body* and accepts only
/// modules, interfaces and functions — so it panicked with "invalid component-level
/// operation: 'builtin.component' is not supported in a component body" on the first
/// component it met.
///
/// The equality is the point, and it is why the fix delegates rather than reimplements: a
/// component is what a Miden package is rooted at, so the world around it must not change
/// the answer.
///
/// The world here is parsed from `.hir` text rather than taken from the parser's anchor, so
/// the world under test is the one the file declares — the shape `--emit=hir` writes. See
/// [`WORLD`] for why the id is quoted here but is not in what `--emit=hir` actually prints.
#[test]
fn a_world_holding_one_component_lowers_as_that_component() {
    let context = Rc::new(Context::default());
    let from_world =
        lower_world(parse_world(&context, WORLD)).expect("a single-component world lowers");

    // A second context, so that neither lowering can be reading anything the other cached.
    let context = Rc::new(Context::default());
    let op = parse(&context, COMPONENT);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture parses as a component"));
    let analysis_manager = AnalysisManager::new(op, None);
    let from_component = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("and so does the component on its own");

    assert_eq!(
        summarize(&from_world),
        summarize(&from_component),
        "a world holding one component must lower to what that component lowers to"
    );
}

/// And a component on its own still lowers rooted at its own id.
///
/// The discriminating half. Without it the equality above could be satisfied by breaking
/// the *component* path to match the world's — no id, a root taken from the enclosing
/// namespace — which is the path every Wasm, Rust and manifest build takes.
#[test]
fn a_component_lowers_rooted_at_its_own_id() {
    let context = Rc::new(Context::default());
    let op = parse(&context, COMPONENT);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture parses as a component"));
    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("the component lowers");

    let id = lowered.id.as_ref().expect("a component knows its own id");
    assert_eq!(id.to_string(), "hir_ns:test@1.0.0");
    assert_eq!(
        lowered.root.to_string(),
        "::\"hir_ns:test@1.0.0\"",
        "a component's Miden Assembly is rooted at its id, as one quoted path component"
    );
    assert!(
        format!("{lowered}").contains("main"),
        "and its function must have been lowered: {lowered}"
    );
}

/// A start marker is sufficient to create component `init`, and the marked function is its final
/// same-context invocation even when the component has no ordinary memory initialization needs.
#[test]
fn a_marked_start_is_the_final_component_initialization_step() {
    let context = Rc::new(Context::default());
    let op = parse(&context, COMPONENT);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    mark_start_function(&context, op, "main");
    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("a component whose only initialization is its start must lower");

    let init = component_init(&lowered);
    let execs = exec_paths(init.body());
    assert_eq!(
        execs.last().map(String::as_str),
        Some("::\"hir_ns:test@1.0.0\"::test::main"),
        "the start function must be the final `exec` in `init`: {execs:?}"
    );
    assert!(
        init.invoked().any(|invoke| {
            invoke.kind == masm::InvokeKind::Exec
                && invoke.target.unwrap_path().as_str() == "::\"hir_ns:test@1.0.0\"::test::main"
        }),
        "the start edge must be present in `init`'s invocation metadata"
    );

    let lowered_start = lowered
        .modules
        .iter()
        .find(|module| module.path().as_str().ends_with("::test"))
        .and_then(|module| {
            module.procedures().find(|procedure| procedure.name().as_str() == "main")
        })
        .expect("the marked function must still be lowered");
    assert!(
        !lowered_start.has_attribute(midenc_dialect_hir::WASM_COMPONENT_START_ATTR),
        "the HIR-only marker must be consumed rather than copied to MASM"
    );
}

#[test]
fn a_marked_start_remains_resolvable_when_a_synthetic_wrapper_is_rebased() {
    let context = Rc::new(Context::default());
    let op = parse(&context, COMPONENT);
    let mut component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    component.borrow_mut().mark_synthetic_wrapper();
    mark_start_function(&context, op, "main");
    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("a marked synthetic wrapper must lower");

    let target = library_target("rebased");
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("the marked wrapper must produce rebased assembler inputs");
    let mut assembler = miden_assembly::Assembler::new(context.session().source_manager.clone());
    assembler
        .link_package(crate::intrinsics::load(), miden_assembly::Linkage::Static)
        .expect("the compiler intrinsics should link");
    assembler
        .assemble_library("rebased", sources.root, sources.support)
        .expect("rebasing must update the start target recorded in `init`");
}

/// Add a global and table to the marked component so the start's position is tested against both
/// phases whose ordering is semantically observable to constructors.
fn component_with_global_table_and_start() -> String {
    WORLD_WITH_A_PRIVATE_TABLE_CALLEE.replace(
        "builtin.function private extern(\"C\") @private_callee() {",
        "builtin.global_variable private @g : i32 {\n            builtin.ret_imm 1 : i32;\n        };\n\n        builtin.function public extern(\"C\") @component_start() {\n            builtin.ret;\n        };\n\n        builtin.function private extern(\"C\") @private_callee() {",
    )
}

#[test]
fn component_start_runs_after_globals_and_function_tables() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, &component_with_global_table_and_start());
    mark_start_function(&context, world.as_operation_ref(), "component_start");
    let lowered = lower_world(world).expect("a fully initialized marked component must lower");

    let execs = exec_paths(component_init(&lowered).body());
    let table = execs
        .iter()
        .position(|target| target.ends_with("::wasm::__init_function_table"))
        .expect("function-table initialization must be invoked");
    let start = execs
        .iter()
        .position(|target| target.ends_with("::wasm::component_start"))
        .expect("the component start must be invoked");
    assert!(table < start, "table initialization must precede start: {execs:?}");
    assert_eq!(start + 1, execs.len(), "nothing may execute after start in `init`: {execs:?}");
}

const COMPONENT_WITH_CANONICAL_ENTRYPOINT_AND_START: &str = r#"
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.function public extern("component-model") @entry() {
        builtin.ret;
    };
    builtin.module private @core {
        builtin.global_variable private @g : i32 {
            builtin.ret_imm 1 : i32;
        };
        builtin.function public extern("C") @component_start() {
            builtin.ret;
        };
        builtin.function public extern("C") @core_entry() {
            builtin.ret;
        };
    };
};
"#;

/// Generated `main` retains component-init ownership and the public canonical wrapper retains its
/// fresh-context prologue. Only the selected marked executable gets a private no-init body.
#[test]
fn marked_component_uses_private_no_init_canonical_executable_entrypoint() {
    let context = context_with_entrypoint_and_test_harness("\"hir_ns:test@1.0.0\"::entry");
    let op = parse(&context, COMPONENT_WITH_CANONICAL_ENTRYPOINT_AND_START);
    mark_start_function(&context, op, "component_start");
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));

    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("a marked canonical executable entrypoint must lower through its private copy");

    let public_entry = lowered.modules[0]
        .procedures()
        .find(|procedure| procedure.name().as_str() == "entry")
        .expect("the public canonical wrapper must remain defined");
    assert_eq!(
        exec_paths(public_entry.body()).first().map(String::as_str),
        Some("init"),
        "fresh-context calls through the public wrapper must still initialize"
    );
    let private_entry = lowered
        .executable_entrypoint_without_init
        .as_ref()
        .expect("the marked executable must carry a private no-init entry body");
    assert_eq!(private_entry.name().as_str(), EXECUTABLE_ENTRYPOINT_WITHOUT_INIT_PROC);
    assert_eq!(private_entry.visibility(), masm::Visibility::Private);
    assert!(
        !exec_paths(private_entry.body()).iter().any(|target| target == "init"),
        "the executable-only entry body must not repeat component initialization"
    );

    let target = midenc_session::miden_project::Target::executable(
        "component-start",
        Uri::new("component-start.hir"),
    );
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("the marked canonical executable should generate main and its private entry");
    let private_entry = sources
        .root
        .procedures()
        .find(|procedure| procedure.name().as_str() == EXECUTABLE_ENTRYPOINT_WITHOUT_INIT_PROC)
        .expect("the no-init entry body must be private to the executable module");
    assert_eq!(private_entry.visibility(), masm::Visibility::Private);
    let main = sources
        .root
        .procedures()
        .find(|procedure| procedure.name().is_main())
        .expect("the executable root must define main");
    let init = main
        .body()
        .iter()
        .position(|op| {
            matches!(
                op,
                masm::Op::Inst(inst)
                    if matches!(
                        inst.inner(),
                        masm::Instruction::Exec(masm::InvocationTarget::Path(path))
                            if path.inner().as_str() == "::\"hir_ns:test@1.0.0\"::init"
                    )
            )
        })
        .expect("generated main must retain component init");
    let harness = main
        .body()
        .iter()
        .position(|op| {
            matches!(
                op,
                masm::Op::Inst(inst) if matches!(inst.inner(), masm::Instruction::AdvPush)
            )
        })
        .expect("the fixture enables test-harness initialization");
    let entry = main
        .body()
        .iter()
        .position(|op| {
            matches!(
                op,
                masm::Op::Inst(inst)
                    if matches!(
                        inst.inner(),
                        masm::Instruction::Exec(masm::InvocationTarget::Symbol(name))
                            if name.as_str() == EXECUTABLE_ENTRYPOINT_WITHOUT_INIT_PROC
                    )
            )
        })
        .expect("generated main must invoke the private no-init entry body");
    assert!(
        init < harness && harness < entry,
        "generated main must preserve init -> harness -> entry ordering"
    );
}

#[test]
fn unmarked_canonical_executable_keeps_the_existing_entrypoint_path() {
    let context = context_with_entrypoint("\"hir_ns:test@1.0.0\"::entry");
    let lowered = lower_component(&context, COMPONENT_WITH_CANONICAL_ENTRYPOINT_AND_START)
        .expect("the unmarked canonical executable must remain supported");
    assert!(lowered.executable_entrypoint_without_init.is_none());

    let target = midenc_session::miden_project::Target::executable(
        "component-start",
        Uri::new("component-start.hir"),
    );
    let sources = lowered.source_inputs(&target, context.session()).unwrap();
    let main = sources.root.procedures().find(|procedure| procedure.name().is_main()).unwrap();
    let execs = exec_paths(main.body());
    assert!(execs.iter().any(|target| target.ends_with("::init")));
    assert!(execs.iter().any(|target| target.ends_with("::entry")));
    assert!(!execs.iter().any(|target| target == EXECUTABLE_ENTRYPOINT_WITHOUT_INIT_PROC));
}

const COMPONENT_WITH_NESTED_CANONICAL_ENTRYPOINT_AND_START: &str = r#"
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @api {
        builtin.function public extern("component-model") @entry() {
            builtin.ret;
        };
    };
    builtin.module private @core {
        builtin.function public extern("C") @component_start() {
            builtin.ret;
        };
    };
};
"#;

#[test]
fn nested_canonical_entrypoint_cannot_bypass_marked_component_rejection() {
    let context = context_with_entrypoint("\"hir_ns:test@1.0.0\"::api::entry");
    let op = parse(&context, COMPONENT_WITH_NESTED_CANONICAL_ENTRYPOINT_AND_START);
    mark_start_function(&context, op, "component_start");
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    let analysis_manager = AnalysisManager::new(op, None);

    let err = match component.borrow().to_masm_component(analysis_manager) {
        Ok(_) => panic!("a nested canonical entrypoint has ambiguous init ownership"),
        Err(err) => err,
    };
    assert!(err.to_string().contains("must be defined directly"), "{err}");
}

const WORLD_WITH_SUPPORTING_CANONICAL_ENTRYPOINT_AND_START: &str = r#"
builtin.world {
    builtin.component private @"hir_ns:test@1.0.0" {
        builtin.module private @core {
            builtin.function public extern("C") @component_start() {
                builtin.ret;
            };
        };
    };
    builtin.module public @supporting {
        builtin.function public extern("component-model") @entry() {
            builtin.ret;
        };
    };
};
"#;

#[test]
fn supporting_canonical_entrypoint_cannot_bypass_marked_component_rejection() {
    let context = context_with_entrypoint("supporting::entry");
    let world = parse_world(&context, WORLD_WITH_SUPPORTING_CANONICAL_ENTRYPOINT_AND_START);
    mark_start_function(&context, world.as_operation_ref(), "component_start");

    let err = match lower_world(world) {
        Ok(_) => {
            panic!("a supporting canonical entrypoint would still initialize the component twice")
        }
        Err(err) => err,
    };
    assert!(err.to_string().contains("initialization twice"), "{err}");
}

#[test]
fn generated_executable_main_owns_marked_core_entrypoint_initialization_once() {
    let context = context_with_entrypoint("\"hir_ns:test@1.0.0\"::core::core_entry");
    let op = parse(&context, COMPONENT_WITH_CANONICAL_ENTRYPOINT_AND_START);
    let component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    mark_start_function(&context, op, "component_start");
    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("a marked core-C executable entrypoint remains supported");

    let target = midenc_session::miden_project::Target::executable(
        "component-start",
        Uri::new("component-start.hir"),
    );
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("the marked executable should generate its main module");
    let main = sources
        .root
        .procedures()
        .find(|procedure| procedure.name().is_main())
        .expect("the executable root should define main");
    let execs = exec_paths(main.body());
    let init = "::\"hir_ns:test@1.0.0\"::init";
    let entry = "\"hir_ns:test@1.0.0\"::core::core_entry";
    assert_eq!(execs.iter().filter(|target| target.as_str() == init).count(), 1);
    let init = execs
        .iter()
        .position(|target| target == init)
        .expect("generated main must invoke component init");
    let entry = execs
        .iter()
        .position(|target| target == entry)
        .unwrap_or_else(|| panic!("generated main must invoke the core entrypoint: {execs:?}"));
    assert!(
        init < entry,
        "generated main must initialize once before executing the core entrypoint: {execs:?}"
    );
}

/// A world declaring more than one component is reported, not merged and not panicked on.
#[test]
fn a_world_declaring_two_components_is_reported_as_unimplemented() {
    let context = Rc::new(Context::default());
    let op = parse(&context, TWO_COMPONENT_WORLD);
    let world = op
        .try_downcast_op::<builtin::World>()
        .unwrap_or_else(|_| panic!("the fixture parses as a world"));
    let err = lower_world(world)
        .err()
        .expect("lowering two components into one package is not implemented");

    let msg = format!("{err}");
    assert!(
        msg.contains("lowering a world containing 2 components"),
        "the report must say what it found, and how many of them: {msg}"
    );
    assert!(
        msg.contains("not yet implemented"),
        "and must read as a limitation of the compiler rather than a malformed input: {msg}"
    );
}

/// A declaration-only sibling is ignored entirely, and changes nothing about the result.
///
/// This is an *external dependency represented in the IR* — normal, expected, and worth
/// nothing to code generation. The assertion is the strong one: the world lowers to exactly
/// what the same component lowers to with no sibling at all, so the sibling cannot have
/// leaked into the output. And nothing is warned about, because warning here would make the
/// ordinary case noisy.
#[test]
fn a_declaration_only_sibling_is_ignored() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, WORLD_WITH_DECLARATION_ONLY_SIBLING);
    let with_sibling = lower_world(world).expect("a declaration-only sibling must not fail");

    let context = Rc::new(Context::default());
    let alone = lower_world(parse_world(&context, WORLD)).expect("and neither must its absence");

    assert_eq!(
        summarize(&with_sibling),
        summarize(&alone),
        "a sibling that only declares symbols contributes no Miden Assembly"
    );
    assert!(
        emitter.captured().is_empty(),
        "and it is ignored by design, so it must not be reported: {}",
        emitter.captured()
    );
}

/// A sibling module that owns no memory is translated 1:1, beside the component, silently.
///
/// This is the *supporting module* half of what a world's siblings can be: it is emitted as an
/// ordinary Miden Assembly module and handed to the assembler as an ad-hoc support module,
/// which is what [`MasmComponent::source_inputs`] does with every module that is not the root.
///
/// Silence is asserted as strongly as translation. The previous behaviour warned and dropped
/// it, and a build that now translates the module but still warns about it would be telling
/// the reader something false.
#[test]
fn a_sibling_module_owning_no_memory_is_translated_beside_the_component() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, WORLD_WITH_SUPPORTING_SIBLING);

    let lowered =
        lower_world(world).expect("a supporting module beside a component must not fail the build");
    assert!(
        !context.session().diagnostics.has_errors(),
        "and must not be reported as an error either"
    );
    assert!(
        emitter.captured().is_empty(),
        "a supporting module is translated now, so there is nothing to report: {}",
        emitter.captured()
    );

    // The component itself is untouched by the sibling beside it.
    assert_eq!(
        lowered.id.as_ref().map(|id| id.to_string()).as_deref(),
        Some("hir_ns:test@1.0.0")
    );
    assert_eq!(lowered.root.to_string(), "::\"hir_ns:test@1.0.0\"");

    assert_eq!(
        module_paths(&lowered),
        vec!["::\"hir_ns:test@1.0.0\"", "::\"hir_ns:test@1.0.0\"::test", "::supporting"],
        "the sibling is a top-level module of its own, not a child of the component"
    );
    assert!(
        format!("{lowered}").contains("sibling"),
        "and its procedure must have been lowered: {lowered}"
    );

    // And it reaches the assembler as a support module, which is what makes it linkable.
    let target = library_target("hir_ns:test@1.0.0");
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    assert_eq!(sources.root.path().to_string(), "::\"hir_ns:test@1.0.0\"");
    assert_eq!(
        sources
            .support
            .iter()
            .map(|module| module.path().to_string())
            .collect::<Vec<_>>(),
        vec!["::\"hir_ns:test@1.0.0\"::test", "::supporting"],
    );
}

/// A sibling module that *defines* a global variable is diagnosed, not translated.
///
/// A global variable is owned by a component: the component is what lays out memory for it
/// and emits the code that initializes it. A module at the top level of a world has no parent
/// component, so there is nothing to own its memory — and `Linker::link` cannot see it from
/// the component either, so translating it would lay its globals over the component's.
#[test]
fn a_sibling_module_defining_a_global_variable_is_diagnosed() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, &world_with_a_sibling_defining_a_global());

    let lowered = lower_world(world).expect("and it must still not fail the build");
    assert!(
        !context.session().diagnostics.has_errors(),
        "nor be reported as an error, which would reject a legitimate world"
    );

    let captured = emitter.captured();
    assert!(
        captured.contains("global variable"),
        "the report must name the rule, not merely refuse: {captured}"
    );
    assert!(
        captured.contains("component"),
        "and must say who owns those items, which is what teaches the rule: {captured}"
    );
    assert!(
        captured.contains("supporting"),
        "and must name the item it left out: {captured}"
    );

    assert_eq!(
        module_paths(&lowered),
        vec!["::\"hir_ns:test@1.0.0\"", "::\"hir_ns:test@1.0.0\"::test"],
        "a module that owns memory is left out of the generated package: {lowered}"
    );
}

/// A sibling module that only *declares* a global variable is diagnosed too.
///
/// The discriminating half of the test above, and the one place this predicate is
/// deliberately stricter than `Linker::link`, which skips declarations when computing the
/// layout. A declaration whose definition lives elsewhere is not in the component's layout, so
/// lowering a use of it would panic in `GlobalVariableLayout::get_computed_addr`; and it is a
/// global variable declared by a module with no parent component either way, which is the rule.
#[test]
fn a_sibling_module_declaring_a_global_variable_is_diagnosed() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, &world_with_a_sibling_declaring_a_global());

    let lowered = lower_world(world).expect("and it must still not fail the build");

    assert!(
        emitter.captured().contains("global variable"),
        "a declared global is still a global a component owns: {}",
        emitter.captured()
    );
    assert_eq!(
        module_paths(&lowered),
        vec!["::\"hir_ns:test@1.0.0\"", "::\"hir_ns:test@1.0.0\"::test"],
    );
}

/// A sibling module declaring a data segment is diagnosed, for the same reason.
///
/// Data segments are the other half of what a component owns, and the other half of what
/// `Linker::link` scans a component's modules for.
#[test]
fn a_sibling_module_declaring_a_data_segment_is_diagnosed() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, WORLD_WITH_SUPPORTING_SIBLING);
    define_a_data_segment_in(top_level_module(&world.borrow(), "supporting"));

    let lowered = lower_world(world).expect("and it must still not fail the build");
    assert!(!context.session().diagnostics.has_errors());

    let captured = emitter.captured();
    assert!(
        captured.contains("data segment"),
        "the report must name the rule, not merely refuse: {captured}"
    );
    assert!(captured.contains("component"), "and must say who owns those items: {captured}");

    assert_eq!(
        module_paths(&lowered),
        vec!["::\"hir_ns:test@1.0.0\"", "::\"hir_ns:test@1.0.0\"::test"],
        "a module that owns memory is left out of the generated package: {lowered}"
    );
}

/// A supporting sibling does **not** move when the component beside it is re-rooted.
///
/// A component-less world is re-rooted at its target's namespace, and so is a world holding
/// the synthetic wrapper `frontend/wasm` builds — see
/// [`MasmComponent::has_no_authored_identity`]. That rewrite replaces a root *the compiler
/// invented*, and it applies to the modules nested under it. A top-level sibling is not one of
/// them: its path is a name the source declares, and lowering defines it top-level rather than
/// under the component's root, so `Rebase` leaves it exactly where it is.
///
/// What must move with the root is anything the sibling *calls* inside the component, which is
/// the same walk and needs nothing extra here; this fixture has no such call, so the assertion
/// is about the sibling's own path.
#[test]
fn a_supporting_sibling_does_not_move_when_the_component_is_re_rooted() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, &wrapper_world_with_a_supporting_sibling());
    mark_as_synthetic_wrapper(world);
    let lowered = lower_world(world).expect("a wrapper world with a sibling lowers");
    assert_eq!(
        lowered.root.to_string(),
        "::\"root_ns:root@1.0.0\"",
        "the fixture must really be the wrapper, or this test is about some other case"
    );

    let target = library_target("::example");
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");

    assert_eq!(sources.root.path(), target.namespace.inner().as_ref());
    assert_eq!(
        sources
            .support
            .iter()
            .map(|module| module.path().to_string())
            .collect::<Vec<_>>(),
        vec!["::example::test", "::supporting"],
        "the component's own modules move with its root; the sibling, whose name the source \
         declares and which was never under that root, does not"
    );
}

/// And the component and its supporting sibling assemble, together.
///
/// A module that reaches `support` but cannot be linked would be a worse outcome than the
/// warning this replaces, so this goes as far as building a real library: the assembler parses
/// every module, resolves every recorded callee, and compiles the result to MAST.
///
/// The fixture's component *calls* the sibling, which is what makes this about linking rather
/// than about parsing. A supporting module the assembler accepted but could not resolve a call
/// into would satisfy every assertion above this one and fail every real build.
///
/// The second half is what makes the first half mean something: with the very same root and
/// the sibling withheld, the same assembly must *fail*. Without it, a call the assembler had
/// quietly dropped would look exactly like a call it had resolved.
#[test]
fn a_component_and_its_supporting_sibling_assemble() {
    /// The assembler `MasmComponent::source_inputs` feeds, with the compiler intrinsics
    /// linked as every real build links them.
    fn assembler(session: &Session) -> miden_assembly::Assembler {
        let mut assembler = miden_assembly::Assembler::new(session.source_manager.clone());
        assembler
            .link_package(crate::intrinsics::load(), miden_assembly::Linkage::Static)
            .expect("the compiler intrinsics should link");
        assembler
    }

    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_CALLING_ITS_SUPPORTING_SIBLING);
    let lowered = lower_world(world).expect("a supporting module beside a component lowers");
    let target = library_target("hir_ns:test@1.0.0");

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    assert!(
        sources.support.iter().any(|module| module.path() == "::supporting"),
        "the supporting module must be among the sources, or neither half proves anything"
    );
    assembler(context.session())
        .assemble_library("hir_ns:test@1.0.0", sources.root, sources.support)
        .unwrap_or_else(|err| {
            panic!("a component and its supporting sibling should assemble: {err}")
        });

    // The discriminating half: the same root, without the module it calls into.
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    let withheld = sources
        .support
        .into_iter()
        .filter(|module| module.path() != "::supporting")
        .collect::<Vec<_>>();
    let err = assembler(context.session())
        .assemble_library("hir_ns:test@1.0.0", sources.root, withheld)
        .expect_err("without the supporting module, the component's call cannot resolve");
    assert!(
        format!("{err}").contains("undefined"),
        "and it must fail for that reason, not some other: {err}"
    );
}

/// A function that reaches codegen with no body is **invalid input**, on the world path.
///
/// Not an unsupported case: nothing could ever supply the missing definition. A body-less
/// function names a procedure whose implementation is expected from elsewhere, and Miden
/// Assembly has no later step that could provide one — so this is the input being wrong, which
/// is deliberately *unlike*
/// `a_world_declaring_two_components_is_reported_as_unimplemented`, where the compiler is the
/// thing that is incomplete. The message is asserted for that difference, not merely for
/// erroring.
///
/// Why an error rather than something to skip: a declaration nothing refers to would be removed
/// by dead symbol elimination, so one that survives this far is assumed *referenced*. Skipping
/// it would emit a module whose callers name a procedure it does not define, and the failure
/// would surface out of the assembler with nothing to point at.
///
/// The sibling here is a **mixed** module — one function defined, one not — which is what makes
/// the case reachable at all: a module whose functions are all body-less is declaration-only and
/// is dropped before codegen. Before this check, such a module was translated and then panicked
/// in `Function::entry_block`'s "cannot get entry block for declaration".
#[test]
fn a_body_less_function_in_a_supporting_sibling_is_invalid_input() {
    let (context, emitter) = capturing_context();
    let world = parse_world(&context, &world_with_a_sibling_declaring_one_of_its_functions());

    let err = lower_world(world)
        .err()
        .expect("a function with no body cannot be emitted as Miden Assembly");

    let msg = format!("{err}");
    assert!(
        msg.contains("cannot emit masm for a function with no body"),
        "the report must say what it cannot emit, and why there is nothing to emit: {msg}"
    );
    assert!(
        msg.contains("nothing can provide its definition"),
        "and must name the reason the input is invalid rather than unsupported: {msg}"
    );
    assert!(
        !msg.contains("not yet implemented"),
        "it is not a limitation of the compiler, which is what `too_many_components` is: {msg}"
    );
    assert!(
        emitter.captured().is_empty(),
        "and the module itself owns no memory, so the sibling rule has no quarrel with it and \
         must not add one: {}",
        emitter.captured()
    );

    // The discriminating half: the same sibling with that one function removed still lowers,
    // silently and beside the component, exactly as
    // `a_sibling_module_owning_no_memory_is_translated_beside_the_component` pins in full.
    let context = Rc::new(Context::default());
    let lowered = lower_world(parse_world(&context, WORLD_WITH_SUPPORTING_SIBLING))
        .expect("a sibling whose functions all have bodies is unaffected by this check");
    assert!(
        module_paths(&lowered).contains(&String::from("::supporting")),
        "and is still translated beside the component: {lowered}"
    );
}

/// The same on the component path: a function declared inside a component's own module.
///
/// The component impl is reached directly by `pipeline::backend::codegen` whenever extraction
/// named a component — every WebAssembly and Rust build — so it never passes through the world
/// impl above. That is why the check sits in `MasmFunctionBuilder::new`, the one point every
/// function reaches, rather than at either impl: the two entry points share nothing else.
#[test]
fn a_body_less_function_in_a_components_module_is_invalid_input() {
    let context = Rc::new(Context::default());
    let err = lower_component(&context, &component_with_a_declared_function_in_its_module())
        .err()
        .expect("the component path reaches the same check, by a different route");

    let msg = format!("{err}");
    assert!(
        msg.contains("cannot emit masm for a function with no body"),
        "and reports it identically, since it is the same defect in the input: {msg}"
    );

    // The discriminating half: the fixture this is derived from, unmodified, lowers — so the
    // difference is the declared function and not the route taken to it.
    let context = Rc::new(Context::default());
    let lowered = lower_component(&context, COMPONENT)
        .expect("a component whose functions all have bodies is unaffected by this check");
    assert!(
        format!("{lowered}").contains("main"),
        "and its module's procedure is emitted as before: {lowered}"
    );
}

/// And a *component-level* function with no body, which reaches the check by the third route.
///
/// `MasmComponentBuilder::define_function` handles a function declared directly by a component;
/// `MasmModuleBuilder::define_function` handles one inside a module or an interface. Both call
/// `MasmFunctionBuilder::new`, and this is the half of that claim the two tests above do not
/// cover — without it, moving the check down into the module builder would still pass them.
#[test]
fn a_body_less_component_level_function_is_invalid_input() {
    let context = Rc::new(Context::default());
    let err = lower_component(&context, &component_with_a_declared_component_level_function())
        .err()
        .expect("a component-level function with no body cannot be emitted either");

    assert!(
        format!("{err}").contains("cannot emit masm for a function with no body"),
        "whichever kind of item declares it, the answer is the same: {err}"
    );
}

/// A world holding no component at all still lowers as one logical component.
///
/// The other live path this change must not disturb: `frontend/masm`'s disassembler builds
/// exactly this shape, and `frontend/masm/tests/e2e.rs` lowers it back through this impl.
#[test]
fn a_world_of_modules_still_lowers_as_a_component_body() {
    let context = Rc::new(Context::default());
    let module = parse(&context, MODULE);
    let lowered =
        lower_world(anchoring_world(module)).expect("a world of modules lowers as it always did");

    assert!(lowered.id.is_none(), "a world declares no component id of its own");
    assert_eq!(
        lowered.root.to_string(),
        "::lib",
        "its root is the single top-level namespace it holds"
    );
    assert!(
        format!("{lowered}").contains("main"),
        "and the module's function must have been lowered: {lowered}"
    );
}

/// A component-less world's Miden Assembly is rooted at the *target's* namespace.
///
/// Lowering has no target and so cannot answer this: with several top-level modules
/// `world_body_to_masm_component` falls through to the placeholder `::init`, which is not a
/// name any source declares and which therefore no synthesized namespace can equal. Since
/// `load_target_sources` rejects a root module that does not sit exactly at its target's
/// namespace, such a build could not assemble at all. The first assertion pins that lowering
/// still produces the placeholder, which is what makes the second one about
/// [`MasmComponent::source_inputs`] rather than about lowering.
///
/// # What this does *not* claim
///
/// The second assertion pins the limitation that comes with it, so the next person reads it
/// here rather than rediscovering it. With several top-level modules the placeholder root is
/// an **empty** module and the real ones are its *siblings*, not its children —
/// `define_module` finds their absolute paths do not begin with the root and defines them
/// top-level — so moving the root moves nothing else, and they stay outside the namespace.
/// Such a build therefore still does not assemble; what it no longer does is fail on a
/// namespace no source could have produced.
///
/// TODO(codegen): decide what a world of several top-level modules should *be*. Nesting them
/// under the target's namespace would rename every procedure in them, which is not this
/// change's to do; rejecting the shape outright may well be the better answer.
#[test]
fn a_world_of_several_modules_is_rooted_at_the_target_namespace() {
    let context = Rc::new(Context::default());
    let lowered = lower_world(parse_world(&context, &two_module_world()))
        .expect("a world of several modules lowers");
    assert_eq!(
        lowered.root.to_string(),
        "::init",
        "lowering has no target to root at, so it still picks its placeholder"
    );

    let target = library_target("::example");
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("and its source inputs are what the assembler is handed");

    assert_eq!(
        sources.root.path(),
        target.namespace.inner().as_ref(),
        "a world declaring no component has no identity of its own, so its root is the namespace \
         its target names"
    );
    assert_eq!(
        sources
            .support
            .iter()
            .map(|module| module.path().to_string())
            .collect::<Vec<_>>(),
        vec!["::lib", "::second"],
        "and the modules the world declares are siblings of the placeholder rather than children \
         of it, so they do not move with it"
    );
}

/// A component-less world whose root already agrees with its target comes back unchanged.
///
/// The single-module shape, end to end from `.hir`: lowering roots at `::{module}`, and
/// preparation's `.hir` scan reads that same module's name, so the two normally agree and
/// subsuming this case into the same rule costs the common case nothing.
///
/// What this pins is the *outcome* — that nothing observable moved — which is what a caller
/// sees. It does not pin the equality guard in `MasmComponent::source_inputs`, and cannot:
/// this fixture's one procedure calls nothing, so there is no call target whose rewriting
/// would be detectable, and re-rooting to the same path is lossless anyway. The guard itself
/// is pinned by `a_component_less_world_already_at_the_target_namespace_is_left_alone` in
/// `artifact.rs`, against a fixture that does have callees.
#[test]
fn a_world_of_one_module_already_at_its_targets_namespace_is_left_alone() {
    let context = Rc::new(Context::default());
    let module = parse(&context, MODULE);
    let lowered = lower_world(anchoring_world(module)).expect("a world of one module lowers");
    let emitted = format!("{}", lowered.modules[0]);

    let target = library_target("::lib");
    assert_eq!(
        lowered.root.as_ref(),
        target.namespace.inner().as_ref(),
        "the module's own name and the target's namespace must really be the same path, or this \
         test is about some other case"
    );

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");

    assert_eq!(sources.root.path(), target.namespace.inner().as_ref());
    assert_eq!(format!("{}", sources.root), emitted, "and nothing in it moved");
}

/// A world holding a component keeps that component's id, whatever its target is called.
///
/// The discriminating half of the two above, at the seam that decides it: re-rooting is
/// justified only for a component-less world, whose modules have no identity beyond the
/// namespace they sit in. An authored component id *is* the code's identity — every dependent
/// addresses its procedures through it — so a target named something else must not silently
/// rename them, and this is the shape every Wasm and Rust build produces.
#[test]
fn a_world_holding_one_component_keeps_that_components_id() {
    let context = Rc::new(Context::default());
    let lowered =
        lower_world(parse_world(&context, WORLD)).expect("a single-component world lowers");

    let target = library_target("::example");
    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");

    assert_eq!(
        sources.root.path().to_string(),
        "::\"hir_ns:test@1.0.0\"",
        "an authored component's root is its own library path, and a target named otherwise must \
         fail the assembler's root-module check rather than be quietly accommodated"
    );
}

#[test]
fn type_expr_from_hir_pointer_conversion_preserves_address_space() {
    for addrspace in [masm::types::AddressSpace::Byte, masm::types::AddressSpace::Element] {
        let ty = Type::from(PointerType::new_with_address_space(Type::U32, addrspace));

        let masm::TypeExpr::Ptr(ptr) = masm::TypeExpr::from(ty) else {
            panic!("expected pointer type expression");
        };
        assert_eq!(ptr.address_space(), addrspace);
    }
}

#[derive(Clone, Copy, Debug)]
enum ProcedureRootCallerOwner {
    Component,
    Interface,
    Module,
}

/// A component whose procedure-root user and callee lower to different MASM modules.
///
/// `callee_first` lets the regressions prove that visibility behavior is independent of lowering
/// order. `callee_visibility` is substituted as HIR source so the same fixture covers the rejected
/// private target and the explicitly cross-module-linkable internal target.
fn component_with_cross_module_procedure_root(
    caller_owner: ProcedureRootCallerOwner,
    callee_visibility: &str,
    callee_first: bool,
) -> String {
    let callee_module = format!(
        r#"    builtin.module private @callee_mod {{
        builtin.function {callee_visibility} extern("C") @callee() {{
            builtin.ret;
        }};
    }};"#
    );
    let caller_function = r#"builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
        %r0, %r1, %r2, %r3 = hir.procedure_root ::@"hir_ns:test@1.0.0"::@callee_mod::@callee;
        builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
    };"#;
    let caller = match caller_owner {
        ProcedureRootCallerOwner::Component => format!("    {caller_function}"),
        ProcedureRootCallerOwner::Interface => format!(
            r#"    builtin.interface @caller {{
        {caller_function}
    }};"#
        ),
        ProcedureRootCallerOwner::Module => format!(
            r#"    builtin.module public @caller_mod {{
        {caller_function}
    }};"#
        ),
    };
    let (first, second) = if callee_first {
        (callee_module.as_str(), caller.as_str())
    } else {
        (caller.as_str(), callee_module.as_str())
    };

    format!(
        r#"builtin.component private @"hir_ns:test@1.0.0" {{
{first}
{second}
}};
"#
    )
}

/// A component whose procedure-root user and private callee share one MASM module.
fn component_with_same_owner_private_procedure_root(
    owner: ProcedureRootCallerOwner,
    callee_first: bool,
) -> String {
    let callee = r#"builtin.function private extern("C") @callee() {
        builtin.ret;
    };"#;
    let root = r#"builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
        %r0, %r1, %r2, %r3 = hir.procedure_root @callee;
        builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
    };"#;
    let (first, second) = if callee_first {
        (callee, root)
    } else {
        (root, callee)
    };
    let owner = match owner {
        ProcedureRootCallerOwner::Component => format!("    {first}\n\n    {second}"),
        ProcedureRootCallerOwner::Interface => format!(
            r#"    builtin.interface @api {{
        {first}

        {second}
    }};"#
        ),
        ProcedureRootCallerOwner::Module => format!(
            r#"    builtin.module public @api {{
        {first}

        {second}
    }};"#
        ),
    };

    format!(
        r#"builtin.component private @"hir_ns:test@1.0.0" {{
{owner}
}};
"#
    )
}

#[test]
fn cross_module_private_procedure_roots_are_rejected_for_every_owner_in_both_orders() {
    for caller_owner in [
        ProcedureRootCallerOwner::Component,
        ProcedureRootCallerOwner::Interface,
        ProcedureRootCallerOwner::Module,
    ] {
        for callee_first in [true, false] {
            let context = Rc::new(Context::default());
            let source =
                component_with_cross_module_procedure_root(caller_owner, "private", callee_first);
            let err = legalize_and_lower_component(&context, &source)
                .err()
                .expect("a cross-module procedure_root must not target a private callee");
            let message = err.to_string();
            assert!(
                message.contains("private callee")
                    && message.contains("callee_mod/callee")
                    && message.contains("not linkable from another Miden Assembly module"),
                "owner: {caller_owner:?}, callee_first: {callee_first}, error: {message}"
            );
        }
    }
}

#[test]
fn direct_lowering_reports_both_sides_of_a_private_cross_module_procedure_root() {
    let context = Rc::new(Context::default());
    let source = component_with_cross_module_procedure_root(
        ProcedureRootCallerOwner::Module,
        "private",
        true,
    );
    let err = legalize_and_lower_component(&context, &source)
        .err()
        .expect("the compiler lowering path must preflight procedure_root visibility");
    let labels = err
        .labels()
        .expect("the structured diagnostic must label both operations")
        .filter_map(|label| label.label().map(str::to_string))
        .collect::<Vec<_>>();
    assert!(
        labels
            .iter()
            .any(|label| { label == "this reference crosses a Miden Assembly module boundary" }),
        "the root use must be the primary diagnostic site: {labels:?}"
    );
    assert!(
        labels
            .iter()
            .any(|label| label == "this callee is private to its defining module"),
        "the private callee must be identified as the secondary site: {labels:?}"
    );
    let help = err.help().expect("the diagnostic must explain the valid remedies").to_string();
    assert!(
        help.contains("declare the callee internal or public"),
        "the diagnostic must explain both valid remedies: {help}"
    );
}

const COMPONENT_WITH_PRIVATE_NESTED_PROCEDURE_ROOT_TARGET: &str = r#"
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
        %r0, %r1, %r2, %r3 = hir.procedure_root ::@"hir_ns:test@1.0.0"::@outer::@hidden::@callee;
        builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
    };
    builtin.module public @outer {
        builtin.module private @hidden {
            builtin.function internal extern("C") @callee() {
                builtin.ret;
            };
        };
    };
};
"#;

#[test]
fn procedure_root_rejects_an_internal_callee_beneath_a_private_nested_module() {
    let context = Rc::new(Context::default());
    let err =
        legalize_and_lower_component(&context, COMPONENT_WITH_PRIVATE_NESTED_PROCEDURE_ROOT_TARGET)
            .err()
            .expect("an internal procedure is not reachable through a private nested module");
    let message = err.to_string();
    assert!(
        message.contains("callee")
            && message.contains("private module")
            && message.contains("hidden"),
        "the diagnostic must identify the inaccessible module path: {message}"
    );
}

#[test]
fn synthetic_wrapper_procedure_roots_use_effective_module_visibility() {
    let context = Rc::new(Context::default());
    let op = parse(&context, COMPONENT_WITH_PRIVATE_NESTED_PROCEDURE_ROOT_TARGET);
    let mut component = op
        .try_downcast_op::<builtin::Component>()
        .unwrap_or_else(|_| panic!("the fixture should parse as a component"));
    component.borrow_mut().mark_synthetic_wrapper();
    let analysis_manager = AnalysisManager::new(op, None);
    let lowered = component
        .borrow()
        .to_masm_component(analysis_manager)
        .expect("a synthetic wrapper exposes its nested module path");

    let exports = assembled_library_exports(&context, &lowered, "hir_ns:test@1.0.0");
    assert!(exports.iter().any(|export| export.ends_with("root")), "exports: {exports:?}");
    assert!(exports.iter().any(|export| export.ends_with("callee")), "exports: {exports:?}");
}

const COMPONENT_LESS_WORLD_WITH_COALESCED_PRIVATE_PROCEDURE_ROOT: &str = r#"
builtin.world {
    builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
        %r0, %r1, %r2, %r3 = hir.procedure_root @only::@callee;
        builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
    };
    builtin.module public @only {
        builtin.function private extern("C") @callee() {
            builtin.ret;
        };
    };
};
"#;

#[test]
fn a_component_less_world_procedure_root_shares_its_single_modules_masm_root() {
    let context = Rc::new(Context::default());
    let lowered = legalize_and_lower_world(
        &context,
        COMPONENT_LESS_WORLD_WITH_COALESCED_PRIVATE_PROCEDURE_ROOT,
    )
    .expect("the world-level caller and sole module callee share one MASM module");
    let exports = assembled_library_exports(&context, &lowered, "only");
    assert_eq!(exports.len(), 1, "only the public root should be exported: {exports:?}");
    assert!(exports[0].ends_with("root"), "unexpected package surface: {exports:?}");
}

const COMPONENT_LESS_WORLD_WITH_EFFECTIVELY_PUBLIC_NESTED_MODULES: &str = r#"
builtin.world {
    builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
        %r0, %r1, %r2, %r3 = hir.procedure_root @only::@hidden::@callee;
        builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
    };
    builtin.module private @only {
        builtin.module private @hidden {
            builtin.function internal extern("C") @callee() {
                builtin.ret;
            };
        };
    };
};
"#;

#[test]
fn component_less_world_procedure_roots_use_effective_module_visibility() {
    let context = Rc::new(Context::default());
    let lowered = legalize_and_lower_world(
        &context,
        COMPONENT_LESS_WORLD_WITH_EFFECTIVELY_PUBLIC_NESTED_MODULES,
    )
    .expect("component-less world modules form the public artifact interface");
    let exports = assembled_library_exports(&context, &lowered, "only");
    assert!(exports.iter().any(|export| export.ends_with("root")), "exports: {exports:?}");
    assert!(exports.iter().any(|export| export.ends_with("callee")), "exports: {exports:?}");
}

const COMPONENT_WITH_DEEP_CALLER_AND_PRIVATE_SIBLING_CALLEE_MODULE: &str = r#"
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module private @internal {
        builtin.function internal extern("C") @callee() {
            builtin.ret;
        };
    };
    builtin.module public @api {
        builtin.module public @deep {
            builtin.function public extern("C") @root() -> (felt, felt, felt, felt) {
                %r0, %r1, %r2, %r3 = hir.procedure_root ::@"hir_ns:test@1.0.0"::@internal::@callee;
                builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
            };
        };
    };
};
"#;

#[test]
fn a_deep_procedure_root_caller_can_reach_its_ancestors_private_child() {
    let context = Rc::new(Context::default());
    let lowered = legalize_and_lower_component(
        &context,
        COMPONENT_WITH_DEEP_CALLER_AND_PRIVATE_SIBLING_CALLEE_MODULE,
    )
    .expect("a private child is visible to every descendant of its parent");
    let exports = assembled_library_exports(&context, &lowered, "hir_ns:test@1.0.0");
    assert_eq!(exports.len(), 1, "only the public root should be exported: {exports:?}");
    assert!(exports[0].ends_with("root"), "unexpected package surface: {exports:?}");
}

const WORLD_WITH_OMITTED_INVALID_PROCEDURE_ROOT_USER: &str = r#"
builtin.world {
    builtin.component private @"hir_ns:test@1.0.0" {
        builtin.module public @api {
            builtin.function private extern("C") @callee() {
                builtin.ret;
            };
        };
    };
    builtin.interface @omitted {
        builtin.function public extern("C") @unused() -> (felt, felt, felt, felt) {
            %r0, %r1, %r2, %r3 = hir.procedure_root ::@"hir_ns:test@1.0.0"::@api::@callee;
            builtin.ret %r0, %r1, %r2, %r3 : (felt, felt, felt, felt);
        };
    };
};
"#;

#[test]
fn legalization_does_not_validate_procedure_roots_in_an_omitted_world_sibling() {
    let (context, emitter) = capturing_context();
    legalize_and_lower_world(&context, WORLD_WITH_OMITTED_INVALID_PROCEDURE_ROOT_USER)
        .expect("an omitted sibling must not fail the selected component's build");
    let captured = emitter.captured();
    assert!(
        captured.contains("this build omits"),
        "the established omission warning must still be emitted: {captured}"
    );
}

#[test]
fn cross_module_internal_procedure_roots_assemble_in_both_module_orders() {
    for callee_first in [true, false] {
        let context = Rc::new(Context::default());
        let source = component_with_cross_module_procedure_root(
            ProcedureRootCallerOwner::Component,
            "internal",
            callee_first,
        );
        let lowered = legalize_and_lower_component(&context, &source)
            .expect("an explicitly internal cross-module procedure_root target must lower");
        let exports = assembled_library_exports(&context, &lowered, "hir_ns:test@1.0.0");
        assert_eq!(exports.len(), 1, "only the public root should be exported: {exports:?}");
        assert!(exports[0].ends_with("root"), "unexpected package surface: {exports:?}");
    }
}

#[test]
fn same_owner_private_procedure_roots_stay_private_in_both_orders() {
    for owner in [ProcedureRootCallerOwner::Component, ProcedureRootCallerOwner::Module] {
        for callee_first in [true, false] {
            let context = Rc::new(Context::default());
            let source = component_with_same_owner_private_procedure_root(owner, callee_first);
            let lowered = legalize_and_lower_component(&context, &source)
                .expect("a procedure_root may target a private callee in its own MASM module");
            let exports = assembled_library_exports(&context, &lowered, "hir_ns:test@1.0.0");
            assert_eq!(
                exports.len(),
                1,
                "owner: {owner:?}, callee_first: {callee_first}, exports: {exports:?}"
            );
            assert!(
                exports[0].ends_with("root"),
                "owner: {owner:?}, callee_first: {callee_first}, exports: {exports:?}"
            );
        }
    }
}

/// A component whose public interface is a component-level function, with its implementation in
/// a private module beside it.
///
/// The module's `helper` must be a *public procedure* for the cross-module `exec` to resolve,
/// which is exactly the combination the package surface must not leak: a public procedure of a
/// private submodule.
const WORLD_WITH_A_PRIVATE_MODULE_BEHIND_ITS_INTERFACE: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.function public extern("C") @entry() {
        hir.exec ::@"hir_ns:test@1.0.0"::@test::@helper() : extern("C") () -> ();
        builtin.ret;
    };
    builtin.module private @test {
        builtin.function public extern("C") @helper() {
            builtin.ret;
        };
    };
};
};
"#;

/// A private module's public procedures are callable within the package, but are not part of
/// the assembled package's export surface: the surface is derived from the modules reachable
/// through *public* submodule declarations, and a private HIR module is declared private.
#[test]
fn a_private_module_is_not_part_of_the_package_surface() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_A_PRIVATE_MODULE_BEHIND_ITS_INTERFACE);
    let lowered = lower_world(world).expect("a component with a private module lowers");
    let target = library_target("hir_ns:test@1.0.0");

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    let package = miden_assembly::Assembler::new(context.session().source_manager.clone())
        .assemble_library("hir_ns:test@1.0.0", sources.root, sources.support)
        .expect("a public interface calling into a private module assembles");

    let exports = package
        .manifest
        .exports()
        .map(|export| export.path().as_ref().as_str().to_string())
        .collect::<Vec<_>>();
    assert!(
        exports.iter().any(|export| export.ends_with("entry")),
        "the component-level function is the public surface, got exports: {exports:?}"
    );
    assert!(
        !exports.iter().any(|export| export.contains("helper")),
        "a public procedure of a private module must not be exported, got exports: {exports:?}"
    );
}

/// [`WORLD_WITH_A_PRIVATE_MODULE_BEHIND_ITS_INTERFACE`] carrying the id `frontend/wasm` gives
/// the wrapper it invents around a bare core module — written by an author here, rather than
/// invented, which is the whole point: nothing marks this component synthetic.
///
/// Derived from the shared fixture rather than written out, so the component id is the only
/// thing that differs from the case beside it.
fn world_with_an_authored_root_id() -> String {
    WORLD_WITH_A_PRIVATE_MODULE_BEHIND_ITS_INTERFACE
        .replace("hir_ns:test@1.0.0", "root_ns:root@1.0.0")
}

/// The compiler's wrapper around a bare core module is recognized by a marker the frontend
/// sets, not by its id: an author may legitimately name a component `root_ns:root@1.0.0`, and
/// theirs keeps the module visibility they declared.
///
/// The discriminating half of [`a_private_module_is_not_part_of_the_package_surface`]: the same
/// fixture and the same assertion, with only the id changed. Recognizing the wrapper by
/// comparing the id forces this component's modules public, which puts `helper` — a procedure
/// its author put behind a private module — on the assembled package's export surface.
#[test]
fn an_authored_component_named_like_the_wrapper_keeps_private_modules_private() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, &world_with_an_authored_root_id());
    let lowered = lower_world(world).expect("an authored root-named component lowers");
    let target = library_target("root_ns:root@1.0.0");

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    let package = miden_assembly::Assembler::new(context.session().source_manager.clone())
        .assemble_library("root_ns:root@1.0.0", sources.root, sources.support)
        .expect("it assembles");

    let exports = package
        .manifest
        .exports()
        .map(|export| export.path().as_ref().as_str().to_string())
        .collect::<Vec<_>>();
    assert!(
        exports.iter().any(|export| export.ends_with("entry")),
        "the component-level function is still the public surface, got exports: {exports:?}"
    );
    assert!(
        !exports.iter().any(|export| export.contains("helper")),
        "a private module of an authored component must not be exported, got: {exports:?}"
    );
}

/// `builtin.Module` permits nesting, and a nested module's procedures belong to the component
/// as much as a top-level module's. Lowering must place them at their own path rather than
/// panicking on a module it did not expect to find in a module body.
const WORLD_WITH_A_NESTED_MODULE: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @outer {
        builtin.function public extern("C") @entry() {
            builtin.ret;
        };

        builtin.module public @inner {
            builtin.function public extern("C") @nested() {
                builtin.ret;
            };
        };
    };
};
};
"#;

#[test]
fn a_nested_module_is_lowered_at_its_own_path() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_A_NESTED_MODULE);
    let lowered = lower_world(world).expect("a component with a nested module lowers");

    let paths = lowered
        .modules
        .iter()
        .map(|module| module.path().to_string())
        .collect::<Vec<_>>();
    assert!(
        paths.iter().any(|path| path.ends_with("outer::inner")),
        "the nested module must be lowered at its own path, got: {paths:?}"
    );
}

/// [`WORLD_WITH_A_NESTED_MODULE`] with the *inner* module private.
///
/// Derived from the shared fixture rather than written out, because the inner module's
/// visibility is the only thing that differs, and it is the only thing this asks about.
fn world_with_a_private_nested_module() -> String {
    WORLD_WITH_A_NESTED_MODULE
        .replace("builtin.module public @inner", "builtin.module private @inner")
}

/// Nesting does not widen the surface. A private module's public procedures stay off the
/// assembled package's exports whether the module sits at the top level or inside another —
/// the surface is derived from the modules reachable from the root through *public* submodule
/// declarations, and a private declaration ends that walk at any depth.
///
/// The depth is what makes this worth pinning separately from
/// [`a_private_module_is_not_part_of_the_package_surface`]: nested modules are lowered by
/// recursion through `define_module`, and it is `define_module_tree` — which forces every
/// *intermediate* module public so references through it resolve — that decides which
/// declaration carries the author's visibility. A recursion that applied the visibility to the
/// wrong link of the chain would leave `nested` exported here while the top-level case still
/// passed.
#[test]
fn a_private_nested_module_is_not_part_of_the_package_surface() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, &world_with_a_private_nested_module());
    let lowered = lower_world(world).expect("a component with a private nested module lowers");
    let target = library_target("hir_ns:test@1.0.0");

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    let package = miden_assembly::Assembler::new(context.session().source_manager.clone())
        .assemble_library("hir_ns:test@1.0.0", sources.root, sources.support)
        .expect("a public module holding a private one assembles");

    let exports = package
        .manifest
        .exports()
        .map(|export| export.path().as_ref().as_str().to_string())
        .collect::<Vec<_>>();
    assert!(
        exports.iter().any(|export| export.ends_with("entry")),
        "the public outer module's procedure is the surface, got exports: {exports:?}"
    );
    assert!(
        !exports.iter().any(|export| export.contains("nested")),
        "a public procedure of a private *nested* module must not be exported, got: {exports:?}"
    );
}

/// The shape pure core-Wasm translation produces: a public module (the artifact's interface)
/// holding a private, address-taken function in a function table.
const WORLD_WITH_A_PRIVATE_TABLE_CALLEE: &str = r#"
builtin.world {
builtin.component private @"root_ns:root@1.0.0" {
    builtin.module public @wasm {
        builtin.function private extern("C") @private_callee() {
            builtin.ret;
        };

        builtin.function_table private @tbl : 1 {
            builtin.function_table_entry 0 @private_callee tag 1;
        };

        builtin.function public extern("C") @dispatch(%index: u32) {
            hir.exec_indirect @tbl[%index] : extern("C") () -> () tag 1;
            builtin.ret;
        };
    };
};
};
"#;

/// A function whose address is taken is still private: the package's export manifest is its
/// author's interface, and an address-taken private function is not part of it. Initialization
/// must reach the callee without promoting it, which it does by emitting the `procref` in the
/// callee's own module.
#[test]
fn a_private_table_callee_is_not_part_of_the_package_surface() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_A_PRIVATE_TABLE_CALLEE);
    let lowered = lower_world(world).expect("a component with a private table callee lowers");
    let target = library_target("root_ns:root@1.0.0");

    let sources = lowered
        .source_inputs(&target, context.session())
        .expect("its source inputs are what the assembler is handed");
    // A component owning a function table needs an `init`, and `init` opens by calling the
    // intrinsic heap initializer, so this one must link the intrinsics as a real build does.
    let mut assembler = miden_assembly::Assembler::new(context.session().source_manager.clone());
    assembler
        .link_package(crate::intrinsics::load(), miden_assembly::Linkage::Static)
        .expect("the compiler intrinsics should link");
    let package = assembler
        .assemble_library("root_ns:root@1.0.0", sources.root, sources.support)
        .expect("a table initialized from its callee's own module assembles");

    let mut exports = package
        .manifest
        .exports()
        .map(|export| export.path().as_ref().as_str().to_string())
        .collect::<Vec<_>>();
    exports.sort();

    // The whole set, not just the two memberships this is named for. Initializing a table trades
    // one symbol off the manifest for another: `@private_callee` stays the author's, while
    // `__init_function_table` — the compiler's own, and public only so `init` can reach it —
    // joins the surface. That trade is the design, so it is asserted rather than tolerated, and
    // any *third* symbol arriving on the public surface should be a test failure and not a
    // discovery made downstream.
    assert_eq!(
        exports,
        vec![
            "::\"root_ns:root@1.0.0\"::init",
            "::\"root_ns:root@1.0.0\"::wasm::__init_function_table",
            "::\"root_ns:root@1.0.0\"::wasm::dispatch",
        ],
        "the public surface is the author's `dispatch` plus the compiler's own initializers"
    );
}

/// A table entry naming a function in a declaration-only sibling.
///
/// The sibling is an external dependency represented in the IR — `@sibling` has no body — so
/// `classify_siblings` drops it and no module is ever lowered at `::external_dep`. The entry
/// still resolves and `@sibling` still has a signature, so the `hir.exec_indirect` verifier and
/// legalization both accept this: it reaches code generation intact.
const WORLD_WITH_A_TABLE_CALLEE_IN_A_DECLARATION_ONLY_SIBLING: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @wasm {
        builtin.function_table private @tbl : 1 {
            builtin.function_table_entry 0 ::@external_dep::@sibling tag 1;
        };

        builtin.function public extern("C") @dispatch(%index: u32) {
            hir.exec_indirect @tbl[%index] : extern("C") () -> () tag 1;
            builtin.ret;
        };
    };
};
builtin.module public @external_dep {
    builtin.function public extern("C") @sibling() {
    };
};
};
"#;

/// A table entry whose callee has no definition to take the address of is invalid input, and is
/// diagnosed as such.
///
/// This is the shape that used to panic. Everything upstream accepts it — the entry resolves and
/// the callee's signature matches the call site's, which is all the verifier asks — so the first
/// thing a producer of this IR saw was a `.expect` firing inside the slot-filling code, with a
/// message written for a compiler bug rather than for them.
#[test]
fn a_table_callee_in_an_unlowered_module_is_invalid_input() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_A_TABLE_CALLEE_IN_A_DECLARATION_ONLY_SIBLING);
    let err = lower_world(world)
        .err()
        .expect("a table entry naming a callee with no definition must not lower");
    let err = err.to_string();

    assert!(
        err.contains("sibling") && err.contains("external_dep"),
        "the diagnostic must name the callee and the module it was expected in, got: {err}"
    );
    assert!(
        err.contains("only declarations"),
        "the diagnostic must say why there was no module to attach the code to, got: {err}"
    );
}

/// A component whose table callees are spread across three modules, one of them nested.
///
/// `@a` declares the only table, and its three slots name callees in three different modules —
/// so the slot-filling code for a *single* table is split three ways, which is the case grouping
/// by callee rather than by table exists for. `@outer` defines a callee of its own, which makes
/// it the nearest fragment-bearing ancestor of `@inner` and so the module whose initializer has
/// to reach it.
const WORLD_WITH_TABLE_CALLEES_ACROSS_MODULES: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @a {
        builtin.function private extern("C") @callee_a() {
            builtin.ret;
        };

        builtin.function_table private @tbl : 3 {
            builtin.function_table_entry 0 @callee_a tag 1;
            builtin.function_table_entry 1 ::@"hir_ns:test@1.0.0"::@outer::@callee_b tag 1;
            builtin.function_table_entry 2 ::@"hir_ns:test@1.0.0"::@outer::@inner::@callee_c tag 1;
        };

        builtin.function public extern("C") @dispatch(%index: u32) {
            hir.exec_indirect @tbl[%index] : extern("C") () -> () tag 1;
            builtin.ret;
        };
    };

    builtin.module public @outer {
        builtin.function private extern("C") @callee_b() {
            builtin.ret;
        };

        builtin.module public @inner {
            builtin.function private extern("C") @callee_c() {
                builtin.ret;
            };
        };
    };
};
};
"#;

/// A table whose only slot is written twice: a dead entry naming a callee in `@z`, then the live
/// entry naming `@live` in `@a`.
///
/// The table's documented rule is last-entry-per-slot-wins, so slot 0 holds `@live` and nothing
/// else. The module names are what make this discriminating: slot-filling code is grouped by the
/// callee's defining module and those groups run in path order, so `@a` runs before `@z` and a
/// codegen that emitted *both* stores would leave `@dead`'s MAST root in the slot — the entry the
/// `hir.exec_indirect` verifier never looked at, with a signature it never checked.
const WORLD_WITH_AN_OVERWRITTEN_TABLE_SLOT: &str = r#"
builtin.world {
builtin.component private @"hir_ns:test@1.0.0" {
    builtin.module public @a {
        builtin.function private extern("C") @live() {
            builtin.ret;
        };

        builtin.function_table private @tbl : 1 {
            builtin.function_table_entry 0 ::@"hir_ns:test@1.0.0"::@z::@dead tag 1;
            builtin.function_table_entry 0 @live tag 1;
        };

        builtin.function public extern("C") @dispatch(%index: u32) {
            hir.exec_indirect @tbl[%index] : extern("C") () -> () tag 1;
            builtin.ret;
        };
    };

    builtin.module public @z {
        builtin.function private extern("C") @dead(%v: u32) {
            builtin.ret;
        };
    };
};
};
"#;

/// The target of every `procref` in `body`, in order.
fn procrefs_in(body: &masm::Block) -> Vec<String> {
    body.iter()
        .filter_map(|op| match op {
            masm::Op::Inst(inst) => match inst.inner() {
                masm::Instruction::ProcRef(masm::InvocationTarget::Path(path)) => {
                    Some(path.inner().as_str().to_string())
                }
                _ => None,
            },
            _ => None,
        })
        .collect()
}

/// An entry a later entry overwrites is dead, and dead entries are not written to their slot.
///
/// This is a soundness property, not a size optimization. The `hir.exec_indirect` verifier checks
/// only the entry that wins a slot, so a dead entry's signature is never compared against the call
/// site's — writing its MAST root into the slot anyway would let a callee with a different stack
/// contract run behind a tag the runtime check accepts, which is exactly the type confusion the
/// tag exists to prevent.
#[test]
fn a_dead_table_entry_is_not_written_to_its_slot() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_AN_OVERWRITTEN_TABLE_SLOT);
    let lowered = lower_world(world).expect("a component with an overwritten table slot lowers");

    let mut procrefs = Vec::new();
    for module in lowered.modules.iter() {
        for procedure in module.procedures() {
            if procedure.name().as_str() == super::FUNCTION_TABLE_INIT_PROC {
                procrefs.extend(procrefs_in(procedure.body()));
            }
        }
    }
    procrefs.sort();

    assert_eq!(
        procrefs,
        vec!["::\"hir_ns:test@1.0.0\"::a::live"],
        "only the entry that wins the slot may be written to it"
    );

    // The dead entry was the sole reason `@z` would have carried an initializer at all, so its
    // absence is the same fact stated where a reader will notice it first.
    let owners = lowered
        .modules
        .iter()
        .filter(|module| {
            module
                .procedures()
                .any(|proc| proc.name().as_str() == super::FUNCTION_TABLE_INIT_PROC)
        })
        .map(|module| module.path().to_string())
        .collect::<Vec<_>>();
    assert_eq!(
        owners,
        vec!["::\"hir_ns:test@1.0.0\"::a"],
        "a module whose only table entry is dead defines no initializer"
    );
}

/// The path of the module whose `__init_function_table` each `exec` in `body` names, in order.
///
/// Only the generated initializers are of interest, so anything else `body` invokes — the heap
/// intrinsic `init` opens with, most of all — is skipped.
fn function_table_initializers_invoked(body: &masm::Block) -> Vec<String> {
    let suffix = format!("::{}", super::FUNCTION_TABLE_INIT_PROC);
    body.iter()
        .filter_map(|op| match op {
            masm::Op::Inst(inst) => match inst.inner() {
                masm::Instruction::Exec(masm::InvocationTarget::Path(path)) => {
                    path.inner().as_str().strip_suffix(&suffix).map(String::from)
                }
                _ => None,
            },
            _ => None,
        })
        .collect()
}

/// Every module defining a table callee initializes the slots of the callees *it* defines, and
/// is invoked exactly once — by its nearest enclosing initializer if it has one, and by the
/// component's `init` otherwise.
///
/// Both halves matter and neither implies the other. A module reached twice writes its slots
/// twice, which is merely wasteful; a module reached by nobody leaves its slots as the zero word,
/// and `dynexec` on a zero slot traps at runtime — a whole table's worth of dispatch failing for
/// a callee that happened to live one module over.
#[test]
fn every_module_defining_a_table_callee_is_initialized_exactly_once() {
    let context = Rc::new(Context::default());
    let world = parse_world(&context, WORLD_WITH_TABLE_CALLEES_ACROSS_MODULES);
    let lowered = lower_world(world).expect("a component with table callees across modules lowers");

    // The three modules defining a callee each carry an initializer, and no other module does
    let mut owners = lowered
        .modules
        .iter()
        .filter(|module| {
            module
                .procedures()
                .any(|proc| proc.name().as_str() == super::FUNCTION_TABLE_INIT_PROC)
        })
        .map(|module| module.path().to_string())
        .collect::<Vec<_>>();
    owners.sort();
    assert_eq!(
        owners,
        vec![
            "::\"hir_ns:test@1.0.0\"::a",
            "::\"hir_ns:test@1.0.0\"::outer",
            "::\"hir_ns:test@1.0.0\"::outer::inner",
        ],
        "a module defines an initializer if and only if it defines a table callee"
    );

    // ...and each is invoked exactly once across `init` and every initializer
    let mut invoked = Vec::new();
    for module in lowered.modules.iter() {
        for procedure in module.procedures() {
            if matches!(procedure.name().as_str(), "init" | super::FUNCTION_TABLE_INIT_PROC) {
                invoked.extend(function_table_initializers_invoked(procedure.body()));
            }
        }
    }
    invoked.sort();
    assert_eq!(invoked, owners, "every initializer must be reached exactly once");

    // Which one reaches which is the recursive shape a single component-global table would be
    // initialized with, and is not implied by the count above: `init` reaching all three
    // directly satisfies "exactly once" just as well, and would be a different design.
    let invoked_by = |module_path: &str, procedure_name: &str| -> Vec<String> {
        let module = lowered
            .modules
            .iter()
            .find(|module| module.path() == module_path)
            .unwrap_or_else(|| panic!("no module lowered at '{module_path}'"));
        let procedure = module
            .procedures()
            .find(|procedure| procedure.name().as_str() == procedure_name)
            .unwrap_or_else(|| panic!("no '{procedure_name}' in '{module_path}'"));
        let mut invoked = function_table_initializers_invoked(procedure.body());
        invoked.sort();
        invoked
    };

    assert_eq!(
        invoked_by("::\"hir_ns:test@1.0.0\"", "init"),
        vec!["::\"hir_ns:test@1.0.0\"::a", "::\"hir_ns:test@1.0.0\"::outer"],
        "`init` reaches the outermost initializers, and only those"
    );
    assert_eq!(
        invoked_by("::\"hir_ns:test@1.0.0\"::outer", super::FUNCTION_TABLE_INIT_PROC),
        vec!["::\"hir_ns:test@1.0.0\"::outer::inner"],
        "a module's initializer reaches the initializers of the modules nested within it"
    );
    for leaf in ["::\"hir_ns:test@1.0.0\"::a", "::\"hir_ns:test@1.0.0\"::outer::inner"] {
        assert!(
            invoked_by(leaf, super::FUNCTION_TABLE_INIT_PROC).is_empty(),
            "an initializer with nothing nested within it reaches no other, but '{leaf}' did"
        );
    }
}

#[test]
fn frame_base_locals_use_the_locked_debugger_encoding() {
    use miden_core::{Felt, serde::Serializable};

    let expression = Expression::with_ops(vec![ExpressionOp::FrameBase {
        base: FrameBase::Local(2),
        byte_offset: 28,
    }]);
    let location = DebugVarLocation::Expression(expression.to_bytes());

    let patched = patch_debug_var_location(&location, 8, None);
    let DebugVarLocation::FrameBase {
        global_index,
        byte_offset,
    } = patched
    else {
        panic!("local frame bases must use the debugger-supported location variant");
    };
    assert_eq!(
        global_index,
        FRAME_BASE_LOCAL_MARKER | u32::from(u16::from_le_bytes((-6i16).to_le_bytes()))
    );
    assert_eq!(byte_offset, 28);

    let value = miden_debug::resolve_variable_value(
        &DebugVarLocation::FrameBase {
            global_index,
            byte_offset,
        },
        &[],
        |address| (address == 32).then_some(Felt::new(13).unwrap()),
        |offset| (offset == -6).then_some(Felt::new(100).unwrap()),
    );
    assert_eq!(value, Some(Felt::new(13).unwrap()));
}

#[test]
fn unrepresentable_nested_frame_bases_kill_the_active_debugger_location() {
    use miden_debug::processor::trace::RowIndex;

    for stack_pointer_addr in [None, Some(1 << 31)] {
        let kill = patch_nested_frame_base(stack_pointer_addr);
        assert_eq!(kill.value_location(), &debug_var_kill_location());

        let events = Rc::new(RefCell::new(BTreeMap::new()));
        let mut tracker = miden_debug::DebugVarTracker::new(events);
        tracker.record_events(
            RowIndex::from(1),
            vec![masm::DebugVarInfo::new(
                "x",
                DebugVarLocation::Const(miden_core::Felt::new(7).unwrap()),
            )],
        );
        tracker.record_events(RowIndex::from(2), vec![kill]);
        tracker.update_to_cycle(RowIndex::from(1));
        assert!(tracker.get_variable("x").is_some());
        tracker.update_to_cycle(RowIndex::from(2));
        assert!(tracker.get_variable("x").is_none());
    }
}

#[test]
fn out_of_range_fmp_offsets_become_debugger_kills() {
    use miden_core::serde::Serializable;

    let positive_frame_base = DebugVarLocation::Expression(
        Expression::with_ops(vec![ExpressionOp::FrameBase {
            base: FrameBase::Local(i16::MAX as u32 + 1),
            byte_offset: 0,
        }])
        .to_bytes(),
    );
    let negative_frame_base = DebugVarLocation::Expression(
        Expression::with_ops(vec![ExpressionOp::FrameBase {
            base: FrameBase::Local(0),
            byte_offset: 0,
        }])
        .to_bytes(),
    );

    for (location, aligned_num_locals) in [
        (DebugVarLocation::Local(i16::MIN), 1),
        (positive_frame_base, 0),
        (negative_frame_base, i16::MAX as u16 + 2),
    ] {
        assert_eq!(
            patch_debug_var_location(&location, aligned_num_locals, None),
            debug_var_kill_location()
        );
    }
}

#[test]
fn final_debugger_locations_and_opaque_expressions_are_preserved() {
    use miden_core::serde::Serializable;

    let opaque = DebugVarLocation::Expression(
        Expression::with_ops(vec![ExpressionOp::Address { address: 7 }, ExpressionOp::Deref])
            .to_bytes(),
    );
    let kill = debug_var_kill_location();

    for location in [
        DebugVarLocation::Stack(0),
        DebugVarLocation::Memory(1),
        DebugVarLocation::Const(miden_core::Felt::new(2).unwrap()),
        opaque,
        kill,
    ] {
        assert_eq!(patch_debug_var_location(&location, 8, None), location);
    }
}

fn patch_nested_frame_base(stack_pointer_addr: Option<u32>) -> masm::DebugVarInfo {
    let span = SourceSpan::default();
    let debug_var = masm::DebugVarInfo::new(
        "x",
        DebugVarLocation::FrameBase {
            global_index: 0,
            byte_offset: -4,
        },
    );
    let nested = masm::Block::new(
        span,
        vec![masm::Op::Inst(Span::new(span, masm::Instruction::DebugVar(debug_var)))],
    );
    let mut block = masm::Block::new(span, vec![masm::Op::While { span, body: nested }]);

    patch_debug_var_locals_in_block(&mut block, 0, stack_pointer_addr);

    let masm::Op::While { body, .. } = block.iter().next().unwrap() else {
        unreachable!();
    };
    let masm::Op::Inst(inst) = body.iter().next().unwrap() else {
        unreachable!();
    };
    let masm::Instruction::DebugVar(info) = inst.inner() else {
        unreachable!();
    };
    info.clone()
}