brink-ir 0.0.17

Intermediate representations for inkle's ink narrative scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
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
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
mod blocks;
mod chunk;
mod content;
mod context;
mod decls;
mod expr;
mod lambda;
pub mod recognize;
mod stmts;
mod structs;
mod temps;

use brink_format::CountingFlags;
use rowan::TextRange;

use crate::FileId;
use crate::determinism::{LookupMap, LookupSet};
use crate::hir;
use crate::provenance::{NodeClass, Provenance};
use crate::symbols::{ResolutionMap, SymbolIndex};

use super::types as lir;
use context::{LowerCtx, NameTable, ResolutionLookup, TempMap};

pub use chunk::ScopeChunk;
pub use context::{
    AnalyzerTables, CoalesceLookup, CoalesceShape, TypeMode, UfcsLookup, UfcsVerdict,
};
pub use structs::{StructFieldEntry, StructShapeData, StructShapeEntry, build_struct_shape_data};

/// Reserved-name recognition (issue #2863): the canonical answer to "is
/// this name a classic uppercase ink intrinsic / a T1b stdlib name",
/// re-exported so `brink-analyzer` (and any other downstream crate) can
/// delegate to a single implementation instead of hand-keeping its own
/// copy. See [`is_builtin_function`]/[`is_t1b_stdlib_name`]'s own docs for
/// why this crate — not `brink-analyzer` — is where the list lives: the
/// dependency edge only runs one way.
pub use expr::{is_builtin_function, is_t1b_stdlib_name};

/// Defensive backstop for `brink-analyzer`'s dialect gate (E051/E052).
///
/// `brink-syntax` always parses the full superset grammar and `brink-ir`
/// always lowers it to HIR; whether T1b brink-extension constructs
/// (`~ { … }` logic blocks, `#[…]`/`#{…}` sigil literals, postfix indexing)
/// are *allowed* is decided by the dialect gate, which runs as an
/// *analysis* diagnostic. Analysis diagnostics are suppressible
/// (`// brink-disable-all` / line directives — see `crate::suppressions`),
/// so "the gate already rejected this" is not provably true by the time
/// `lower_to_program` runs: a suppressed gate lets a residual
/// `LogicBlock`/`ArrayLiteral`/`MapLiteral`/`Index` HIR node flow in here.
///
/// Scan for that and refuse to lower rather than falling through to the
/// `lower_stmt`/`lower_expr` fallback arms, which would otherwise silently
/// drop the construct (`None`) or replace it with `Null` — a real data-loss
/// bug, not just a `debug_assert!` that's a no-op in release builds. See
/// #572 review.
/// T1b-2 (#570) retirement note: through T1b-1, this module ran a
/// non-suppressible pre-scan (E053) that refused to lower a `LogicBlock`/
/// `ArrayLiteral`/`MapLiteral`/`Index` HIR node reaching here — a defensive
/// backstop for `brink-analyzer`'s dialect gate (E051/E052), which is a
/// *suppressible* analysis diagnostic (`// brink-disable-all`), because the
/// T1b-1 fallback arms for these node kinds were `debug_assert!`-guarded
/// stubs that silently dropped data (`None`) or corrupted it (`Null`) in
/// release builds if the gate was bypassed (#572 review).
///
/// T1b-2 replaces that rejection with real lowering for all four node kinds
/// (`blocks::lower_logic_block` below; `expr::lower_expr`'s
/// `ArrayLiteral`/`MapLiteral`/`Index` arms) — the correctness hazard the
/// backstop existed to catch (silent drop/corruption) no longer exists,
/// because there is no longer a "residual" case: every brink-extension HIR
/// node now lowers to a correct program under both dialects. `strict-ink`
/// enforcement is unchanged and rests solely on E051 (as with every other
/// suppressible diagnostic in this codebase) — see the T1b-2 PR description.
/// A *future* extension construct that lands parse/HIR-only again (as this
/// one briefly did) should reintroduce a scoped version of this backstop
/// for exactly its own node kind(s), not resurrect this one.
///
/// Lower analyzed HIR into a resolved LIR `Program`.
///
/// All references are resolved — the returned `Program` is self-contained
/// and does not need the `SymbolIndex` or `ResolutionMap`.
///
/// `file_paths` maps each `FileId` to its source file path for populating
/// `SourceLocation` on recognized lines.
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn lower_to_program(
    files: &[(FileId, &hir::HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    file_paths: &LookupMap<FileId, String>,
) -> (Option<lir::Program>, Vec<crate::Diagnostic>) {
    lower_to_program_with_type_mode(
        files,
        index,
        resolutions,
        file_paths,
        context::TypeMode::Gradual,
        context::AnalyzerTables {
            ufcs: &context::UfcsLookup::new(),
            coalesce: &context::CoalesceLookup::new(),
        },
    )
}

/// [`lower_to_program`] with an explicit `types` policy (TM-4c,
/// `docs/typed-mode-spec.md` §6).
///
/// **Not on the compile path.** Through FG-4c/d/e, `brink-db`'s production
/// link phase (`lir_lowering_query`, backing `ProjectDb::lir_product`/
/// `story_data`) stopped calling this whole-project entry: it composes the
/// same three phases directly — its own `lir_prelude_decls_query` +
/// `assemble_prelude`, [`lower_root_content_for_prelude`], and the per-knot
/// [`lower_knot_chunk_incremental`] memoized per `DefinitionId` — so a
/// knot-body edit re-lowers one chunk instead of the whole project. FG-6
/// (#841) then removed `brink-compiler`'s own direct call, so every batch
/// consumer (CLI, `brink-web`, `brink-intl`, the oracle harness) now reaches
/// codegen through `ProjectDb::story_data()` too; there is exactly one
/// compile path in production.
///
/// This function stays `pub` regardless — issue #841's audit (grep for
/// external callers) found two real, deliberate direct consumers this
/// composition does not supersede, both outside this crate: the
/// `compile_bench` benchmark's staged/legacy-path rows, which exist
/// specifically to measure this whole-project one-shot call *as the
/// baseline* against the `ProjectDb`-driven per-chunk path (narrowing would
/// delete the comparison, not the redundancy); and `golden_i078.rs`, a
/// golden pipeline test that pins this function's exact LIR output for one
/// fixture in isolation, deliberately bypassing `ProjectDb`. Narrowing to
/// `pub(crate)` would break both for no correctness gain. `brink-ir`'s own
/// `lir_lowering.rs` integration tests are the remaining caller (needs
/// `pub`, not `pub(crate)`, since `tests/` compiles as a separate crate).
///
/// Every other caller (the tests above) gets the gradual default via
/// [`lower_to_program`], which is always semantically valid — gradual never
/// emits a static-offset op gated on `types = strict` (see `expr::
/// known_shape`'s doc).
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn lower_to_program_with_type_mode(
    files: &[(FileId, &hir::HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    file_paths: &LookupMap<FileId, String>,
    type_mode: context::TypeMode,
    tables: context::AnalyzerTables<'_>,
) -> (Option<lir::Program>, Vec<crate::Diagnostic>) {
    // FG-4d/e: this whole-project entry runs the same three pure phases
    // `brink-db`'s production link phase (`lir_lowering_query`) composes
    // from its own per-def/whole-project memos (prelude decls, per-knot
    // chunk, assembly) — so the two are byte-identical by construction, even
    // though `brink-db` no longer routes through this function at all (see
    // this fn's doc). The remaining callers here (this crate's own
    // `lir_lowering.rs` tests, `compile_bench`, `golden_i078.rs`) keep a
    // single whole-project call; `brink-db` caches the per-knot phase
    // individually, per `DefinitionId`, instead.
    let prelude = build_prelude(files, index, resolutions, file_paths, type_mode, tables);
    let resolutions = ResolutionLookup::build(resolutions);
    let struct_ctx = prelude.struct_ctx();

    // Root content (all files, one shared frame) then each knot, collected in
    // the exact interleaved walk order the assembler dedups names against.
    let prelude_files = prelude.files();
    let (root_chunks, root_temp_slots) = lower_root_content_chunks(
        &prelude_files,
        &resolutions,
        index,
        prelude.root_id,
        file_paths,
        &struct_ctx,
        tables,
    );

    // Diagnostic order mirrors the old monolithic path exactly: declaration
    // diagnostics first, then per-file (root content then that file's knots).
    let mut lir_diagnostics = prelude.decl_diagnostics.clone();
    let mut ordered_chunks = Vec::new();
    let mut root_iter = root_chunks.into_iter();
    for &(file_id, hir_file) in &prelude_files {
        if let Some((chunk, diags)) = root_iter.next() {
            ordered_chunks.push(chunk);
            lir_diagnostics.extend(diags);
        }
        for knot in &hir_file.knots {
            let (chunk, diags) = lower_knot_chunk(
                hir_file,
                knot,
                index,
                &resolutions,
                file_paths,
                &struct_ctx,
                prelude.root_id,
                file_id,
                tables,
            );
            ordered_chunks.push(chunk);
            lir_diagnostics.extend(diags);
        }
    }

    let program = assemble_program(&prelude, ordered_chunks, root_temp_slots, index, file_paths);
    (Some(program), lir_diagnostics)
}

// ─── FG-4d: incremental lowering seam ───────────────────────────────
//
// `lower_to_program_with_type_mode` above is the composition of the three
// functions below. `brink-db`'s salsa pipeline calls them separately so the
// middle one (`lower_knot_chunk`) can be memoized per `DefinitionId`: an
// edit that doesn't touch a knot leaves its chunk memo pointer-identical,
// and the whole-project `assemble_program` link re-runs but backdates on the
// `StoryData` `Eq` firebreak (`docs/fine-grained-salsa-proposal.md` §5 + the
// three-resolution-moments appendix).

/// Whole-project data every chunk lowering and the final assembly need but
/// that is not chunk-local: normalized+stamped HIR (topological order), the
/// collected declarations, the struct-shape table, the seeded project name
/// table (decl + struct names, in the fixed order chunk-local names dedup
/// against), and the `StoryData`-bound `private_defs`/`aliases`.
pub struct LirPrelude {
    normalized: Vec<(FileId, hir::HirFile)>,
    root_id: brink_format::DefinitionId,
    globals: Vec<lir::GlobalDef>,
    lists: Vec<lir::ListDef>,
    list_items: Vec<lir::ListItemDef>,
    externals: Vec<lir::ExternalDef>,
    shape_table: structs::ShapeTable,
    global_shapes: structs::GlobalShapeMap,
    name_seed: Vec<String>,
    type_mode: context::TypeMode,
    private_defs: Vec<brink_format::DefinitionId>,
    aliases: Vec<brink_format::AliasEntry>,
    /// Declaration-phase diagnostics (`collect_globals`'s constant-eval
    /// errors) — the diagnostics the monolithic path pushes before any chunk.
    pub decl_diagnostics: Vec<crate::Diagnostic>,
    /// Lambda-lifted containers synthesized while folding a `VAR`/`CONST`
    /// declaration default that is itself a lambda literal (issue #1774) —
    /// see [`PreludeDecls`]'s matching field for why no relocation is
    /// needed. [`assemble_program`] appends these to the assembled root's
    /// children.
    lifted: Vec<lir::Container>,
}

impl LirPrelude {
    /// The prelude's normalized+stamped HIR as borrow pairs (topo order).
    #[must_use]
    pub fn files(&self) -> Vec<(FileId, &hir::HirFile)> {
        self.normalized.iter().map(|(id, h)| (*id, h)).collect()
    }

    /// The `root` container's `DefinitionId`.
    #[must_use]
    pub fn root_id(&self) -> brink_format::DefinitionId {
        self.root_id
    }

    fn struct_ctx(&self) -> context::StructCtx<'_> {
        context::StructCtx {
            shapes: &self.shape_table,
            global_shapes: &self.global_shapes,
            type_mode: self.type_mode,
        }
    }
}

/// The declaration-level half of [`LirPrelude`] (issue #839 / FG-4e): every
/// collected `VAR`/`CONST`/`LIST`/`EXTERNAL`/`STRUCT` declaration, the seeded
/// project name table, and the `StoryData`-bound `private_defs`/`aliases` —
/// everything [`build_prelude_decls`] produces. Deliberately *not* the
/// normalized+stamped HIR (`LirPrelude::normalized`): [`collect_globals`],
/// [`collect_lists`], [`collect_externals`], [`build_shape_table`], and
/// [`build_global_shape_map`] read only a file's `constants`/`variables`/
/// `lists`/`structs`/`externals` fields — never `root_content`/`knots`, which
/// [`hir::normalize_file`]/[`hir::stamp_container_ids`] are the only passes
/// that touch — so this half is byte-identical whether it's built from raw,
/// decl-only-projected, or normalized+stamped HIR (`brink-db`'s
/// `lir_prelude_decls_query` exploits exactly this: it reads a per-file
/// decl-only projection that backdates across a body-only edit, so a knot
/// body edit doesn't force this struct's declarations/name table/shape table
/// to be recomputed — the FG-4d `struct_shape_data_query` precedent, applied
/// to the rest of the prelude).
///
/// [`collect_globals`]: decls::collect_globals
/// [`collect_lists`]: decls::collect_lists
/// [`collect_externals`]: decls::collect_externals
/// [`build_shape_table`]: structs::build_shape_table
/// [`build_global_shape_map`]: structs::build_global_shape_map
#[derive(Clone)]
pub struct PreludeDecls {
    root_id: brink_format::DefinitionId,
    globals: Vec<lir::GlobalDef>,
    lists: Vec<lir::ListDef>,
    list_items: Vec<lir::ListItemDef>,
    externals: Vec<lir::ExternalDef>,
    shape_table: structs::ShapeTable,
    global_shapes: structs::GlobalShapeMap,
    name_seed: Vec<String>,
    type_mode: context::TypeMode,
    private_defs: Vec<brink_format::DefinitionId>,
    aliases: Vec<brink_format::AliasEntry>,
    decl_diagnostics: Vec<crate::Diagnostic>,
    /// Lambda-lifted containers synthesized while folding a `VAR`/`CONST`
    /// declaration default that is itself a lambda literal (issue #1774).
    /// Siblings of the project's knots — [`assemble_program`] appends them
    /// to the assembled root's children directly, with no relocation: they
    /// were interned against this same seeded `NameTable`
    /// ([`decls::collect_globals`]'s `names` parameter), not a per-chunk
    /// local one, so their `NameId`s are already valid in the table
    /// [`assemble_program`] reconstructs from [`Self::name_seed`].
    lifted: Vec<lir::Container>,
}

impl PreludeDecls {
    /// The empty prelude decls — no reachable entry (`brink-db`'s
    /// `lir_prelude_decls_query`/`lir_lowering_query` early-return case).
    #[must_use]
    pub fn empty(type_mode: context::TypeMode) -> Self {
        Self {
            root_id: context::root_definition_id(),
            globals: Vec::new(),
            lists: Vec::new(),
            list_items: Vec::new(),
            externals: Vec::new(),
            shape_table: structs::ShapeTable::default(),
            global_shapes: structs::GlobalShapeMap::default(),
            name_seed: Vec::new(),
            type_mode,
            private_defs: Vec::new(),
            aliases: Vec::new(),
            decl_diagnostics: Vec::new(),
            lifted: Vec::new(),
        }
    }
}

/// Collect declaration-level LIR data — `VAR`/`CONST`/`LIST`/`EXTERNAL`/
/// `STRUCT` — and seed the project name table, without touching
/// `root_content`/`knots` (see [`PreludeDecls`]'s doc for why that's safe:
/// none of the collection passes below ever read a body). This is exactly
/// steps 1–2 of the old monolithic `build_prelude` (name collection +
/// struct-shape table), factored out so `brink-db` can memoize it
/// independently of the normalize+stamp step (step 0).
///
/// `file_paths` reaches [`decls::collect_globals`]'s lambda-lifting path
/// (issue #1774) — a lambda-literal `VAR`/`CONST` default qualifies its
/// synthesized function's address by the owning file, the same #1504
/// collision-avoidance every other per-file anonymous container gets.
#[must_use]
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn build_prelude_decls(
    files: &[(FileId, &hir::HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    file_paths: &LookupMap<FileId, String>,
    type_mode: context::TypeMode,
    tables: context::AnalyzerTables<'_>,
) -> PreludeDecls {
    let resolutions_lookup = ResolutionLookup::build(resolutions);
    let mut names = NameTable::new();
    let root_id = context::root_definition_id();

    // The struct-shape table is built *first* (issue #1530): a `VAR`/`CONST`
    // whose default is a construction literal folds into
    // `lir::ConstValue::Record`, which needs the shape's id and declaration
    // field order. Nothing in the shape table depends on the collected
    // declarations, so this is a pure reordering — it only moves the struct
    // and field names ahead of the declaration names in the seeded
    // `NameTable`, and a `NameId` is an index into that same seed, emitted
    // alongside it.
    //
    // `decl_diagnostics` is allocated here (rather than after, as it used to
    // be) so `build_shape_table` can push its own `E181` backstop (issue
    // #2240) into the same accumulator every other decl-collection pass
    // below shares — declaration diagnostics lead in emission order, and a
    // struct-shape drop is exactly as early as it gets.
    let mut decl_diagnostics = Vec::new();
    let shape_table = structs::build_shape_table(
        files,
        &mut names,
        index,
        &resolutions_lookup,
        &mut decl_diagnostics,
    );
    let global_shapes =
        structs::build_global_shape_map(files, index, &resolutions_lookup, &shape_table);

    let mut ids = context::IdAllocator::new();
    let mut lifted: Vec<lir::Container> = Vec::new();
    let struct_ctx = context::StructCtx {
        shapes: &shape_table,
        global_shapes: &global_shapes,
        type_mode,
    };
    // The real, caller-supplied UFCS/`or`-coalescing verdict tables (issue
    // #1774 review) — a decl-default lambda body is lowered through the same
    // `lower_lambda` machinery as any other lambda, so it needs the same
    // analyzer side-tables any other lambda body gets, not a placeholder
    // empty pair. See [`decls::GlobalLambdaCtx::tables`]'s doc.
    let mut lambda_ctx = decls::GlobalLambdaCtx {
        ids: &mut ids,
        lifted: &mut lifted,
        file_paths,
        structs: &struct_ctx,
        tables,
        root_id,
    };
    let mut globals = decls::collect_globals(
        files,
        index,
        &mut names,
        &resolutions_lookup,
        &shape_table,
        &mut decl_diagnostics,
        &mut lambda_ctx,
    );
    let (lists, list_items, list_globals) = decls::collect_lists(files, index, &mut names);
    globals.extend(list_globals);
    let externals = decls::collect_externals(files, index, &mut names, &mut decl_diagnostics);

    let name_seed = names.into_entries();

    let mut private_defs: Vec<brink_format::DefinitionId> = index
        .symbols
        .iter()
        .filter(|(_, info)| info.visibility == crate::symbols::Visibility::Private)
        .map(|(id, _)| *id)
        .collect();
    private_defs.sort_by_key(|id| id.to_raw());

    let mut aliases = index.aliases.clone();
    aliases.sort_unstable();

    PreludeDecls {
        root_id,
        globals,
        lists,
        list_items,
        externals,
        shape_table,
        global_shapes,
        name_seed,
        type_mode,
        private_defs,
        aliases,
        decl_diagnostics,
        lifted,
    }
}

/// Assemble a [`LirPrelude`] from independently-computed [`PreludeDecls`]
/// (issue #839 / FG-4e) plus the normalized+stamped HIR (`brink-db`'s link
/// builds `normalized` from the already-memoized per-file
/// `normalized_stamped_query` instead of recomputing normalize+stamp
/// inline). Pure assembly — no lowering work of its own.
#[must_use]
pub fn assemble_prelude(
    decls: PreludeDecls,
    normalized: Vec<(FileId, hir::HirFile)>,
) -> LirPrelude {
    LirPrelude {
        normalized,
        root_id: decls.root_id,
        globals: decls.globals,
        lists: decls.lists,
        list_items: decls.list_items,
        externals: decls.externals,
        shape_table: decls.shape_table,
        global_shapes: decls.global_shapes,
        name_seed: decls.name_seed,
        type_mode: decls.type_mode,
        private_defs: decls.private_defs,
        aliases: decls.aliases,
        decl_diagnostics: decls.decl_diagnostics,
        lifted: decls.lifted,
    }
}

/// Build the whole-project [`LirPrelude`]: normalize + stamp HIR, collect
/// declarations, and build the struct-shape table — steps 0–2 of the old
/// monolithic `lower_to_program`, verbatim and in the same order, so the
/// seeded name table is byte-identical. Now a thin composition of
/// [`build_prelude_decls`] (steps 1–2) over the normalized files (step 0) —
/// see [`PreludeDecls`]'s doc for why running decl collection on normalized
/// vs. raw HIR is byte-identical.
///
/// `file_paths` reaches the stamping pass, which qualifies each file's
/// root-content scope path with it (#1504 — see
/// [`hir::root_content_scope_path`]).
#[must_use]
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn build_prelude(
    files: &[(FileId, &hir::HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    file_paths: &LookupMap<FileId, String>,
    type_mode: context::TypeMode,
    tables: context::AnalyzerTables<'_>,
) -> LirPrelude {
    // #3275 (stage 3a): stamp BEFORE normalize — mirrors
    // `brink-db`'s `normalized_stamped_query` exactly (the two roads must
    // stay in lockstep; the id-equality gate in `brink-test-harness`
    // pins it). Ids are minted on the pristine tree and the lift inherits
    // them, deriving fresh ids only for genuine clones.
    let mut normalized: Vec<(FileId, hir::HirFile)> = files
        .iter()
        .map(|(id, hir_file)| (*id, (*hir_file).clone()))
        .collect();
    hir::stamp_container_ids(&mut normalized, index, file_paths);
    for (_, h) in &mut normalized {
        hir::normalize_file(h);
    }

    let normalized_refs: Vec<(FileId, &hir::HirFile)> =
        normalized.iter().map(|(id, h)| (*id, h)).collect();
    let decls = build_prelude_decls(
        &normalized_refs,
        index,
        resolutions,
        file_paths,
        type_mode,
        tables,
    );
    assemble_prelude(decls, normalized)
}

/// Lower every file's root-level content into one chunk per file, sharing a
/// single temp/block-slot frame across the whole root scope (files share one
/// call frame — `LowerCtx::next_block_slot`). Returns each `(chunk,
/// lowering-diagnostics)` pair in `files` order plus the total root temp-slot
/// count. This is the root-content half of the old `lower_root`, unchanged.
///
/// The synthesized root terminus ([`attach_root_final_gather`]) is attached to
/// the **last** chunk only — see that function's doc for why that is the one
/// place C# puts it.
#[must_use]
fn lower_root_content_chunks(
    files: &[(FileId, &hir::HirFile)],
    resolutions: &ResolutionLookup,
    index: &SymbolIndex,
    root_id: brink_format::DefinitionId,
    file_paths: &LookupMap<FileId, String>,
    struct_ctx: &context::StructCtx<'_>,
    tables: context::AnalyzerTables<'_>,
) -> (Vec<(chunk::ScopeChunk, Vec<crate::Diagnostic>)>, u16) {
    let mut chunks = Vec::new();

    // Content-pure allocator (seq resets per chunk; `alloc_address` is a
    // deterministic hash) — a fresh one is byte-identical to the shared one.
    let mut ids = context::IdAllocator::new();
    let _ = ids.alloc_address("");

    let root_blocks: Vec<&hir::Block> = files.iter().map(|(_, hir)| &hir.root_content).collect();
    let temp_map = temps::alloc_temps(&[], &[], &root_blocks);
    let mut block_slot = temp_map.total_slots();

    // Only the last root-content chunk — the tail of the assembled root body —
    // may carry the synthesized terminus (issue #1502). See
    // `attach_root_final_gather`.
    let last_chunk = files.len().saturating_sub(1);

    for (chunk_index, &(file_id, hir_file)) in files.iter().enumerate() {
        let mut local_names = NameTable::new();
        let mut diagnostics = Vec::new();
        // #1504: every path this allocator mints for the chunk below (inline
        // sequence wrappers, the synthesized terminus) restarts per file, so
        // qualify them by the owning file — the same qualifier the stamping
        // pass gave this file's anonymous choice/gather containers. `ctx
        // .scope_path` deliberately stays empty: it also drives author-label
        // lookup (`LowerCtx::qualify_label`), and a root-level label is
        // addressed by its bare name.
        ids.set_path_prefix(hir::root_content_scope_path(
            file_paths.get(&file_id).map(String::as_str),
        ));
        let mut lifted: Vec<lir::Container> = Vec::new();
        let (stmts, mut block_children) = {
            let mut ctx = make_ctx(
                file_id,
                hir_file.native,
                resolutions,
                index,
                &temp_map,
                &mut local_names,
                &mut ids,
                root_id,
                String::new(),
                true,
                &[],
                file_paths,
                &mut block_slot,
                &mut diagnostics,
                struct_ctx,
                tables,
                &mut lifted,
            );
            let mut cc = 0;
            let mut gc = 0;
            ctx.ids.reset_seq_counter();
            lower_block_with_children(&hir_file.root_content, &mut ctx, &mut cc, &mut gc)
        };
        if chunk_index == last_chunk {
            attach_root_final_gather(&mut block_children, &mut ids);
        }
        // Lambda-lifted functions (issue #1709) are appended *after* the
        // terminus so the root weave's own container order is untouched:
        // nothing enters a container by falling off a sibling, so their
        // position among root children is inert.
        block_children.append(&mut lifted);
        chunks.push((
            chunk::ScopeChunk::root_content(stmts, block_children, local_names.into_entries()),
            diagnostics,
        ));
    }

    (chunks, block_slot)
}

/// Lower one knot (its body, stitches, and inline children) into a
/// self-contained [`chunk::ScopeChunk`] against a fresh local name table and
/// a fresh content-pure allocator — the per-`DefinitionId` unit `brink-db`
/// memoizes. Byte-identical to the knot's slice of the old `lower_root`.
#[expect(clippy::too_many_arguments)]
#[must_use]
fn lower_knot_chunk(
    hir_file: &hir::HirFile,
    knot: &hir::Knot,
    index: &SymbolIndex,
    resolutions: &ResolutionLookup,
    file_paths: &LookupMap<FileId, String>,
    struct_ctx: &context::StructCtx<'_>,
    root_id: brink_format::DefinitionId,
    file_id: FileId,
    tables: context::AnalyzerTables<'_>,
) -> (chunk::ScopeChunk, Vec<crate::Diagnostic>) {
    let mut local_names = NameTable::new();
    let mut ids = context::IdAllocator::new();
    let _ = ids.alloc_address("");
    // #2229 (LIR half of the same M-2d collision the HIR stamping pass
    // fixed): every path this allocator mints below is built from
    // `ctx.scope_path`, which starts at the **bare** knot name — so two
    // files' same-named knots (M-2d coexistence, #790) minted the same
    // `{knot}.…` path for every LIR-time container at the same structural
    // position. The stamping pass only covers containers HIR stamps;
    // *inline* sequence wrappers (`LowerCtx::alloc_sequence_id`,
    // `content::lower_inline_sequence` — e.g. an alternation inside choice
    // text) are minted right here at LIR time and collided identically
    // (`E060`). Qualify by the owning file exactly like
    // `lower_root_content_chunks` does for root content (#1504) — same
    // prefix, same degradation to the bare path when the caller supplied
    // no file path. Set *after* the root-placeholder `alloc_address("")`
    // above, mirroring the root-content ordering.
    ids.set_path_prefix(hir::root_content_scope_path(
        file_paths.get(&file_id).map(String::as_str),
    ));
    let mut diagnostics = Vec::new();
    let mut lifted = Vec::new();
    let knot_container = lower_knot(
        file_id,
        hir_file,
        knot,
        resolutions,
        index,
        &mut local_names,
        &mut ids,
        root_id,
        file_paths,
        &mut diagnostics,
        struct_ctx,
        tables,
        &mut lifted,
    );
    (
        chunk::ScopeChunk::knot(knot_container, lifted, local_names.into_entries()),
        diagnostics,
    )
}

/// The part of a knot chunk's lowering environment that is the *same* for
/// every knot in the project: the flattened resolution lookup, the
/// reconstructed throwaway `ShapeTable`/`GlobalShapeMap`, the `FileId`→path
/// map, and the type mode.
///
/// Built once per project revision and shared by every
/// [`lower_knot_chunk_incremental`] call (issue #460 — `brink-db` memoizes it
/// in `chunk_lowering_ctx_query`). Before this existed, each per-knot memo
/// rebuilt all of it from scratch, so a K-knot project paid
/// `K × O(project resolutions + struct shapes + files)` on every cold compile
/// and on every recompile that invalidated the chunk memos — the measured
/// dominant cost of the per-knot LIR layer.
///
/// Contents are byte-identical to what the per-knot build produced: same
/// inputs, same constructors, and the throwaway `NameTable` the shape table
/// is interned into is never read (every name is re-interned into the
/// chunk's own local table), so sharing one instance across knots cannot
/// change a chunk's bytes.
pub struct ChunkLoweringCtx {
    resolutions: ResolutionLookup,
    shapes: structs::ShapeTable,
    global_shapes: structs::GlobalShapeMap,
    file_paths: LookupMap<FileId, String>,
    type_mode: context::TypeMode,
}

impl ChunkLoweringCtx {
    /// Build the shared context from the same cutoff-friendly inputs the
    /// per-knot memo already depends on.
    #[must_use]
    pub fn new(
        resolutions: &ResolutionMap,
        shape_data: &StructShapeData,
        file_paths: LookupMap<FileId, String>,
        type_mode: context::TypeMode,
    ) -> Self {
        let mut throwaway = NameTable::new();
        let shapes = structs::rebuild_shape_table(shape_data, &mut throwaway);
        let global_shapes = structs::rebuild_global_shape_map(shape_data);
        Self {
            resolutions: ResolutionLookup::build(resolutions),
            shapes,
            global_shapes,
            file_paths,
            type_mode,
        }
    }
}

/// Incremental entry point (`brink-db`'s per-knot salsa memo): lower a single
/// knot from cutoff-friendly inputs — the declaring file's already
/// normalized+stamped HIR, the whole-project symbol index, and the
/// project-wide [`ChunkLoweringCtx`] (which the memo reads through its own
/// query, so every knot shares one build of it).
#[must_use]
pub fn lower_knot_chunk_incremental(
    hir_file: &hir::HirFile,
    knot: &hir::Knot,
    index: &SymbolIndex,
    ctx: &ChunkLoweringCtx,
    file_id: FileId,
    tables: context::AnalyzerTables<'_>,
) -> (chunk::ScopeChunk, Vec<crate::Diagnostic>) {
    let struct_ctx = context::StructCtx {
        shapes: &ctx.shapes,
        global_shapes: &ctx.global_shapes,
        type_mode: ctx.type_mode,
    };
    lower_knot_chunk(
        hir_file,
        knot,
        index,
        &ctx.resolutions,
        &ctx.file_paths,
        &struct_ctx,
        context::root_definition_id(),
        file_id,
        tables,
    )
}

/// Lower the whole root scope from an already-built [`LirPrelude`] — the
/// link phase's own root-content step. Uses the prelude's real struct-shape
/// table (not the reconstructed projection), so it is byte-identical to the
/// monolithic composition's root-content lowering. `brink-db`'s link query
/// calls this; the per-knot memos use [`lower_knot_chunk_incremental`]
/// (cutoff-friendly `StructShapeData`) instead.
#[expect(
    clippy::implicit_hasher,
    reason = "internal API called only by brink-db"
)]
#[must_use]
pub fn lower_root_content_for_prelude(
    prelude: &LirPrelude,
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    file_paths: &LookupMap<FileId, String>,
    tables: context::AnalyzerTables<'_>,
) -> (Vec<(chunk::ScopeChunk, Vec<crate::Diagnostic>)>, u16) {
    let resolutions = ResolutionLookup::build(resolutions);
    let struct_ctx = prelude.struct_ctx();
    lower_root_content_chunks(
        &prelude.files(),
        &resolutions,
        index,
        prelude.root_id,
        file_paths,
        &struct_ctx,
        tables,
    )
}

/// Assemble the per-chunk lowering products into a finished [`lir::Program`]
/// — the FG-4 **link phase** (`docs/fine-grained-salsa-proposal.md` §5).
/// Merges every chunk's local name table into the seeded project table in
/// walk order, relocates ids, applies counting flags over the whole tree,
/// and attaches the struct-shape / private-def / alias `StoryData` tables.
/// `chunks` must be in the interleaved walk order (per file: root content
/// then that file's knots), so the assembled name ids are byte-identical to
/// the single shared-table walk.
#[must_use]
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn assemble_program(
    prelude: &LirPrelude,
    chunks: Vec<chunk::ScopeChunk>,
    root_temp_slots: u16,
    _index: &SymbolIndex,
    file_paths: &LookupMap<FileId, String>,
) -> lir::Program {
    let mut names = NameTable::from_entries(prelude.name_seed.clone());
    let (mut root_body, mut root_children) = chunk::assemble_scopes(chunks, &mut names);

    // Issue #1774: lambda-lifted functions synthesized from a VAR/CONST
    // decl default (`decls::collect_globals`'s lambda path) are siblings of
    // the project's knots, same placement `lower::lambda`'s own lifted
    // functions get. No relocation needed — see `PreludeDecls::lifted`'s
    // doc for why their `NameId`s are already valid against `names` above.
    root_children.extend(prelude.lifted.iter().cloned());

    let ends_with_divert = root_body
        .last()
        .is_some_and(|s| matches!(&s.kind, lir::StmtKind::Divert(_)));
    if !ends_with_divert {
        // No single HIR node produced this implicit `-> DONE` — it is
        // whole-program assembly filling in ink's "falling off the end of
        // root content is a safe implicit end" rule (issue #1503), not a
        // desugar of any one statement. Inherit the last real statement's
        // provenance when there is one (closest honest anchor: "right
        // after whatever came last"); a project with no root content at
        // all falls back to a synthetic marker, since there is truly
        // nothing to point at (issue #3183 — bare `Provenance`, never a
        // fabricated-but-plausible-looking range).
        let provenance = root_body.last().map_or_else(
            || crate::Provenance::synthetic(crate::NodeClass::Stmt, TextRange::empty(0.into())),
            |s| s.provenance,
        );
        root_body.push(lir::Stmt::new(
            lir::StmtKind::Divert(lir::Divert {
                target: lir::DivertTarget::Done,
                args: Vec::new(),
            }),
            provenance,
        ));
    }

    let mut root = lir::Container {
        id: prelude.root_id,
        // The implicit root container spans the whole project, not one
        // definition site — synthetic by construction (issue #3183).
        provenance: Provenance::synthetic(NodeClass::Knot, TextRange::empty(0.into())),
        name: None,
        kind: lir::ContainerKind::Root,
        params: Vec::new(),
        body: root_body,
        children: root_children,
        counting_flags: CountingFlags::empty(),
        temp_slot_count: root_temp_slots,
        labeled: false,
        inline: false,
        is_function: false,
        local: false,
    };

    apply_counting_flags(&mut root, &prelude.globals);

    let struct_shapes = structs::struct_shape_defs(&prelude.shape_table);

    lir::Program {
        root,
        globals: prelude.globals.clone(),
        lists: prelude.lists.clone(),
        list_items: prelude.list_items.clone(),
        externals: prelude.externals.clone(),
        name_table: names.into_entries(),
        struct_shapes,
        private_defs: prelude.private_defs.clone(),
        aliases: prelude.aliases.clone(),
        // D6 (`docs/debugger-spec.md` §2.3): retained so codegen can build
        // the `DebugInfo` file table without re-deriving file identity —
        // see `lir::Program::file_paths`'s doc. `BTreeMap` for the same
        // determinism reason that field's own doc gives; the source
        // `LookupMap` (`HashMap`) is never iterated to produce this, only
        // collected key-by-key, so the resulting order is `FileId`'s `Ord`,
        // not insertion/hash order.
        file_paths: file_paths.iter().map(|(k, v)| (*k, v.clone())).collect(),
    }
}

// ─── Tree-building lowering ─────────────────────────────────────────

#[expect(clippy::too_many_arguments)]
fn lower_knot(
    file_id: FileId,
    hir_file: &hir::HirFile,
    knot: &hir::Knot,
    resolutions: &ResolutionLookup,
    index: &SymbolIndex,
    names: &mut NameTable,
    ids: &mut context::IdAllocator,
    root_id: brink_format::DefinitionId,
    file_paths: &LookupMap<FileId, String>,
    diagnostics: &mut Vec<crate::Diagnostic>,
    structs: &context::StructCtx<'_>,
    tables: context::AnalyzerTables<'_>,
    lifted: &mut Vec<lir::Container>,
) -> lir::Container {
    let knot_name = &knot.name.text;
    let knot_id = lookup_container_id(index, file_id, knot_name).unwrap_or(root_id);

    let mut scope_blocks: Vec<&hir::Block> = vec![&knot.body];
    for stitch in &knot.stitches {
        scope_blocks.push(&stitch.body);
    }

    let temp_map = temps::alloc_temps(&knot.params, &knot.stitches, &scope_blocks);
    let params = lower_params(&knot.params, names, &temp_map);
    // Shared across the knot body + every one of its stitches — they share
    // one call frame, so block-scoped slots must not restart per stitch
    // (see `LowerCtx::next_block_slot` doc).
    let mut block_slot = temp_map.total_slots();

    let knot_param_names: Vec<&str> = knot.params.iter().map(|p| p.name.text.as_str()).collect();
    let mut ctx = make_ctx(
        file_id,
        hir_file.native,
        resolutions,
        index,
        &temp_map,
        names,
        ids,
        root_id,
        knot_name.clone(),
        false,
        &knot_param_names,
        file_paths,
        &mut block_slot,
        diagnostics,
        structs,
        tables,
        lifted,
    );
    let mut cc = 0;
    let mut gc = 0;
    ctx.ids.reset_seq_counter();
    let (body, mut children) = lower_block_with_children(&knot.body, &mut ctx, &mut cc, &mut gc);
    drop(ctx);

    // Add stitches as children
    for stitch in &knot.stitches {
        children.push(lower_stitch(
            file_id,
            hir_file.native,
            knot,
            stitch,
            &temp_map,
            resolutions,
            index,
            names,
            ids,
            root_id,
            file_paths,
            &mut block_slot,
            diagnostics,
            structs,
            tables,
            lifted,
        ));
    }

    // First-stitch auto-enter: if knot body is empty, divert to first stitch
    let mut final_body = body;
    if final_body.is_empty()
        && !knot.stitches.is_empty()
        && let Some(first_stitch) = children
            .iter()
            .find(|c| c.kind == lir::ContainerKind::Stitch)
    {
        final_body.push(lir::Stmt::new(
            lir::StmtKind::Divert(lir::Divert {
                target: lir::DivertTarget::Address(first_stitch.id),
                args: Vec::new(),
            }),
            knot.ptr,
        ));
    }

    lir::Container {
        id: knot_id,
        provenance: knot.ptr,
        name: Some(knot_name.clone()),
        kind: lir::ContainerKind::Knot,
        params,
        body: final_body,
        children,
        counting_flags: CountingFlags::empty(),
        temp_slot_count: block_slot,
        labeled: false,
        inline: false,
        is_function: knot.is_function,
        local: knot.is_local,
    }
}

#[expect(clippy::too_many_arguments)]
fn lower_stitch(
    file_id: FileId,
    native: bool,
    knot: &hir::Knot,
    stitch: &hir::Stitch,
    temp_map: &TempMap,
    resolutions: &ResolutionLookup,
    index: &SymbolIndex,
    names: &mut NameTable,
    ids: &mut context::IdAllocator,
    root_id: brink_format::DefinitionId,
    file_paths: &LookupMap<FileId, String>,
    block_slot: &mut u16,
    diagnostics: &mut Vec<crate::Diagnostic>,
    structs: &context::StructCtx<'_>,
    tables: context::AnalyzerTables<'_>,
    lifted: &mut Vec<lir::Container>,
) -> lir::Container {
    let stitch_name = &stitch.name.text;
    let stitch_path = format!("{}.{stitch_name}", knot.name.text);
    let stitch_id = lookup_container_id(index, file_id, &stitch_path).unwrap_or(root_id);
    let params = lower_params(&stitch.params, names, temp_map);

    let stitch_param_names: Vec<&str> =
        stitch.params.iter().map(|p| p.name.text.as_str()).collect();
    let mut ctx = make_ctx(
        file_id,
        native,
        resolutions,
        index,
        temp_map,
        names,
        ids,
        root_id,
        stitch_path,
        false,
        &stitch_param_names,
        file_paths,
        block_slot,
        diagnostics,
        structs,
        tables,
        lifted,
    );
    let mut cc = 0;
    let mut gc = 0;
    ctx.ids.reset_seq_counter();
    let (body, children) = lower_block_with_children(&stitch.body, &mut ctx, &mut cc, &mut gc);

    lir::Container {
        id: stitch_id,
        provenance: stitch.ptr,
        name: Some(stitch_name.clone()),
        kind: lir::ContainerKind::Stitch,
        params,
        body,
        children,
        counting_flags: CountingFlags::empty(),
        temp_slot_count: 0,
        labeled: false,
        inline: false,
        is_function: false,
        local: stitch.is_local,
    }
}

/// #3274 (stage-2 flip): lower a variant-claimed content line to
/// [`lir::StmtKind::EmitLineVariants`] plus its shared alternative stub
/// containers (one per authored construct — visit-state carriers, never
/// entered).
///
/// Returns `None` when the line is not claimed (the caller keeps its
/// existing recognition paths), when a [`recognize::VARIANT_CAP`] breach
/// was just diagnosed (E191 — the fallback lowering below is
/// error-recovery shape only, the compile already fails), or on
/// claim/stamp drift (a missing stamped id, a variant recognition
/// refuses) — where the `EmitContent` fallback's inline lowering still
/// carries correct shared-state semantics and only the line-table shape
/// degrades to fragments.
fn try_lower_variant_line(
    content: &hir::Content,
    ctx: &mut LowerCtx<'_>,
    stmt_prov: Provenance,
) -> Option<(lir::StmtKind, Vec<lir::Container>)> {
    let en = match recognize::enumerate_variant_contents(content) {
        Ok(Some(en)) => en,
        Ok(None) => return None,
        Err(breach) => {
            // Stamping consumed one sequence index per alternative on this
            // (claimed) line; consume the same count so every SIBLING
            // container downstream keeps the name its stamped id was
            // hashed from, even in this failing compile.
            for part in &content.parts {
                if matches!(part, hir::ContentPart::InlineSequence(_)) {
                    let _ = ctx.ids.next_seq_index();
                }
            }
            let range = content
                .ptr
                .map_or_else(|| stmt_prov.text_range(), |p| p.text_range());
            ctx.diagnostics.push(crate::Diagnostic {
                file: ctx.file,
                range,
                message: format!(
                    "{}: this line's alternatives enumerate to {} whole-line variants, over \
                     the {} cap — each variant is a real line-table entry, a translation \
                     unit, and a VO slot, so the product is bounded; split the line or move \
                     an alternative onto its own line",
                    crate::DiagnosticCode::E191.title(),
                    breach.product,
                    breach.cap,
                ),
                code: crate::DiagnosticCode::E191,
            });
            return None;
        }
    };

    // Stamped ids — present iff `claims_variant_line` held during
    // normalization/stamping. A missing one means this line reached here
    // without being claimed (drift): fall back rather than invent an id
    // nothing else agrees on.
    let mut alt_ids = Vec::with_capacity(en.alts.len());
    for alt in &en.alts {
        let hir::ContentPart::InlineSequence(seq) = &content.parts[alt.part_idx] else {
            return None;
        };
        // #3401: a lift clone counts on its ORIGINAL's container — touch
        // and stub that id, so this claimed line and every other clone
        // site advance one state.
        alt_ids.push((seq.counter_id.or(seq.container_id)?, seq.ptr));
    }

    // Recognize every variant BEFORE consuming sequence indices, so a
    // refusal leaves the allocator untouched. `claims_variant_line`
    // guarantees static recognizability, so a refusal here is drift
    // between that mirror and the recognizer itself.
    let mut variants = Vec::with_capacity(en.variants.len());
    for v in &en.variants {
        let Some(emission) = recognize::try_recognize(v, ctx) else {
            debug_assert!(
                false,
                "claims_variant_line admitted a variant try_recognize refuses: {v:?}"
            );
            return None;
        };
        variants.push(emission);
    }

    let mut alts = Vec::with_capacity(en.alts.len());
    let mut stubs = Vec::with_capacity(en.alts.len());
    for (alt, (id, ptr)) in en.alts.iter().zip(alt_ids) {
        // One sequence index per alternative — the same count stamping
        // consumed, so the `s-{n}` name here matches the path the stamped
        // id was hashed from. For a SHUFFLE alternative that name is
        // load-bearing beyond debugging: the stub's path_hash seeds its
        // permutation (`ShuffleIndexOf`), and this path is byte-identical
        // to the path the pre-#3274 lifted wrapper had, so existing
        // stories keep their shuffle orders.
        let seq_idx = ctx.ids.next_seq_index();
        // #3275 (stage 3a): a stateful alternative cloned across a lifted
        // construct's branches SHARES one stamped id (ruled 2026-08-29) —
        // each claiming branch line reaches this emission with the same
        // `id`, and the stubs are identical (empty, visit-counted). Emit
        // the container once; later sites reference it through the alt's
        // `container_id` alone. The sequence index is consumed either way
        // so sibling container names stay stable.
        // #3401: if a bodied wrapper already owns this id (the clone that
        // keeps the original id lifted, and lowered first — clone 0 always
        // precedes its siblings), it carries the visit count this stub
        // would — emit nothing here. The reverse order cannot arise: only
        // clone 0 ever builds a bodied wrapper under the stamped id, so a
        // stub emitted first is never followed by one, and codegen's E060
        // guard stays the arbiter for any duplicate that does slip through.
        if !ctx.ids.is_bodied_emitted(id) && ctx.ids.mark_shared_emitted(id) {
            stubs.push(lir::Container {
                id,
                provenance: ptr,
                name: Some(format!("s-{seq_idx}")),
                kind: lir::ContainerKind::Sequence,
                params: Vec::new(),
                body: Vec::new(),
                children: Vec::new(),
                counting_flags: CountingFlags::VISITS,
                temp_slot_count: 0,
                labeled: false,
                inline: false,
                is_function: false,
                local: false,
            });
        }
        alts.push(lir::VariantAltEmission {
            container_id: id,
            kind: alt.kind,
            branch_count: alt.branch_count,
        });
    }

    Some((
        lir::StmtKind::EmitLineVariants(lir::VariantLineEmission {
            alts,
            dims: en.dims,
            variants,
        }),
        stubs,
    ))
}

/// Lower a block, returning both statements and any child containers
/// (choice targets, gathers) produced by choice sets within the block.
///
/// When a `ChoiceSet` with a gather is encountered, remaining statements
/// go into the gather's body (not the current block).
#[expect(clippy::too_many_lines)]
fn lower_block_with_children(
    block: &hir::Block,
    ctx: &mut LowerCtx<'_>,
    choice_counter: &mut usize,
    gather_counter: &mut usize,
) -> (Vec<lir::Stmt>, Vec<lir::Container>) {
    let mut stmts = Vec::new();
    let mut children = Vec::new();
    let mut pos = 0;
    // Issue #1992 review finding F1: a code-ground body's `> text` split
    // (`hir::lower_native::body::mark_split_logic_block_scopes`) opens one
    // shared T1b scope across every split `LogicBlock` run, but leaves the
    // matching pop to *this* function rather than to any particular run —
    // a `Stmt::Content` sibling from a trailing `> text` line can legally
    // follow the last split run in `block.stmts` and still needs the scope
    // open. Sound because splitting only ever happens at the top level of
    // the one `hir::Block` `lower_stmt_block_as_body` produces, never
    // inside a nested block this function recurses into — so an `Opens`
    // seen here is always matched by a pop here, never by a caller further
    // up or a recursive call further down.
    let mut pending_split_scope = false;

    while pos < block.stmts.len() {
        let stmt = &block.stmts[pos];
        // Issue #3183: every `lir::Stmt`/`lir::Container` synthesized while
        // handling `stmt` — including by helpers this loop calls into —
        // inherits its provenance via `ctx.current_stmt_provenance`. The
        // value is also captured locally (`stmt_prov`) because recursing
        // into a child body (a choice's body, a conditional/sequence
        // branch) through the same `ctx` mutates the ambient as a side
        // effect — anything in *this* arm that still needs `stmt`'s own
        // provenance after such a recursive call must read `stmt_prov`,
        // never `ctx.current_stmt_provenance`, and the ambient is restored
        // to `stmt_prov` at the bottom of the loop so a later sibling
        // statement that falls back to the ambient (EndOfLine,
        // EndElementRun, an option-less Divert/Content) inherits this
        // statement's own context, not a nested descendant's.
        let stmt_prov = ctx.enter_stmt(stmts::stmt_provenance(stmt, ctx));
        match stmt {
            hir::Stmt::ChoiceSet(cs) => {
                // Every choice set gets a gather target — read from stamped HIR.
                let gather_target = cs.gather_id;
                *gather_counter += 1;

                // Build choice target children
                let mut choice_children = Vec::new();
                let choices: Vec<lir::Choice> = cs
                    .choices
                    .iter()
                    .map(|choice| {
                        let (lir_choice, child) =
                            lower_choice_with_child(choice, ctx, choice_counter, gather_target);
                        if let Some(c) = child {
                            choice_children.push(c);
                        }
                        lir_choice
                    })
                    .collect();

                stmts.push(lir::Stmt::new(
                    lir::StmtKind::ChoiceSet(lir::ChoiceSet {
                        choices,
                        gather_target,
                    }),
                    stmt_prov,
                ));
                children.append(&mut choice_children);

                // Build gather container from the continuation block.
                // The HIR nests all post-gather content into the continuation,
                // so no trailing-stmt consumption is needed.
                let gather_container = build_continuation_container(
                    &cs.continuation,
                    ctx,
                    gather_target,
                    *gather_counter - 1,
                    choice_counter,
                    gather_counter,
                    stmt_prov,
                );
                children.push(gather_container);
                pos += 1;
            }
            hir::Stmt::LabeledBlock(labeled) => {
                // Labeled block wrapping content (standalone gather or opening
                // gather pattern). Enter the wrapper container so execution
                // returns to the parent when the child finishes — this allows
                // sibling LabeledBlocks to chain (e.g. `- (opts) ... - (test)`).
                let wrapper_id = labeled.container_id.unwrap_or(ctx.root_id);
                *gather_counter += 1;

                stmts.push(lir::Stmt::new(
                    lir::StmtKind::EnterContainer(wrapper_id),
                    stmt_prov,
                ));

                let display_name = labeled
                    .label
                    .as_ref()
                    .map_or_else(|| format!("g-{}", *gather_counter - 1), |l| l.text.clone());

                let labeled_flag = labeled
                    .label
                    .as_ref()
                    .is_some_and(|label| ctx.lookup_address_id(&label.text).is_some());

                // Lower the labeled block's contents
                let (mut inner_stmts, inner_children) =
                    lower_block_with_children(labeled, ctx, choice_counter, gather_counter);

                // If inside a choice body, append goto gather so the
                // container is self-sufficient when entered via divert.
                if let Some(gather_id) = ctx.choice_gather_target {
                    let ends_terminal = inner_stmts.last().is_some_and(|s| {
                        matches!(
                            &s.kind,
                            lir::StmtKind::Divert(d) if matches!(
                                d.target,
                                lir::DivertTarget::Done
                                    | lir::DivertTarget::End
                                    | lir::DivertTarget::Address(_)
                            )
                        ) || matches!(&s.kind, lir::StmtKind::ChoiceSet(_))
                    });
                    if !ends_terminal {
                        inner_stmts.push(lir::Stmt::new(
                            lir::StmtKind::Divert(lir::Divert {
                                target: lir::DivertTarget::Address(gather_id),
                                args: Vec::new(),
                            }),
                            stmt_prov,
                        ));
                    }
                }

                children.push(lir::Container {
                    id: wrapper_id,
                    provenance: stmt_prov,
                    name: Some(display_name),
                    kind: lir::ContainerKind::Gather,
                    params: Vec::new(),
                    body: inner_stmts,
                    children: inner_children,
                    counting_flags: CountingFlags::empty(),
                    temp_slot_count: 0,
                    labeled: labeled_flag,
                    inline: true,
                    is_function: false,
                    local: false,
                });
                pos += 1;
            }
            hir::Stmt::Conditional(cond) => {
                // Lower conditional branches with lower_block_with_children
                // so ChoiceSets inside branches produce child containers.
                // Each branch body is wrapped in its own child container.
                //
                // The `in_conditional_branch` flag in codegen suppresses `Done`
                // inside branch containers. This is correct because ink
                // conditionals can gate choice visibility — choices across all
                // branches form a single logical ChoiceSet, and the runtime
                // auto-presents pending choices on frame/container exhaustion
                // (vm.rs handle_frame_exhaustion), so no explicit `Done` is needed.
                let kind = match &cond.kind {
                    hir::CondKind::InitialCondition => lir::CondKind::InitialCondition,
                    hir::CondKind::IfElse => lir::CondKind::IfElse,
                    hir::CondKind::Switch(expr) => {
                        lir::CondKind::Switch(expr::lower_expr(expr, ctx))
                    }
                };

                let cond_idx = ctx.ids.next_seq_index();

                // Push a scope prefix for this conditional so nested
                // conditionals inside branches get unique container paths.
                let cond_scope = format!("b-{cond_idx}");
                let old_scope = ctx.scope_path.clone();

                let branches = cond
                    .branches
                    .iter()
                    .enumerate()
                    .map(|(branch_idx, b)| {
                        // B1b (issue #1475): the block-level `{if EXPR as
                        // n: … else: …}` template form. The branch body
                        // becomes its own container, but containers share
                        // the enclosing call frame's temp slots, so the
                        // binding's slot is visible inside it — the scope
                        // bracket below is the lowering-time name scope,
                        // and it closes before the next branch is walked.
                        ctx.push_block_scope();
                        let condition = match (b.condition.as_ref(), b.binding.as_ref()) {
                            (Some(e), Some(binding)) => {
                                Some(blocks::lower_bound_condition(e, binding, ctx))
                            }
                            (Some(e), None) => Some(expr::lower_expr(e, ctx)),
                            (None, _) => None,
                        };

                        // Set scope_path for this branch so nested containers
                        // (choices, gathers, nested conditionals) get unique IDs.
                        let branch_scope = if old_scope.is_empty() {
                            format!("{cond_scope}.{branch_idx}")
                        } else {
                            format!("{old_scope}.{cond_scope}.{branch_idx}")
                        };
                        ctx.scope_path = branch_scope;

                        // Pass through parent choice/gather counters — a ChoiceSet
                        // inside a conditional shares the enclosing scope and must
                        // not collide with sibling gathers/choices.
                        let (body, branch_children) =
                            lower_block_with_children(&b.body, ctx, choice_counter, gather_counter);

                        // Read pre-stamped container ID from HIR.
                        let branch_id = b.container_id.unwrap_or(ctx.root_id);

                        // `b.ptr` is this branch's own span (condition + body,
                        // issue #404) — finer-grained than the enclosing
                        // Conditional's whole-construct range, so both the
                        // branch container and its `EnterContainer` marker
                        // stamp it directly rather than the coarser ambient
                        // (issue #3183).
                        let branch_container = lir::Container {
                            id: branch_id,
                            provenance: b.ptr,
                            name: Some(format!("{branch_idx}")),
                            kind: lir::ContainerKind::ConditionalBranch,
                            params: Vec::new(),
                            body,
                            children: branch_children,
                            counting_flags: CountingFlags::empty(),
                            temp_slot_count: 0,
                            labeled: false,
                            inline: false,
                            is_function: false,
                            local: false,
                        };
                        children.push(branch_container);
                        // Closes the `as`-binding scope opened above — the
                        // next branch (an `else`) must not see the name.
                        ctx.pop_block_scope();

                        // The branch body in the Conditional struct is just EnterContainer
                        lir::CondBranch {
                            condition,
                            body: vec![lir::Stmt::new(
                                lir::StmtKind::EnterContainer(branch_id),
                                b.ptr,
                            )],
                        }
                    })
                    .collect();

                // Restore scope_path after processing branches.
                ctx.scope_path = old_scope;

                stmts.push(lir::Stmt::new(
                    lir::StmtKind::Conditional(lir::Conditional { kind, branches }),
                    stmt_prov,
                ));
                pos += 1;
            }
            hir::Stmt::Sequence(seq) => {
                // Read pre-stamped wrapper container ID; keep counter in sync.
                let seq_idx = ctx.ids.next_seq_index();
                let wrapper_id = seq.container_id.unwrap_or(ctx.root_id);
                // #3401: see `content::lower_inline_sequence` — the wrapper
                // under the stamped id owns the counted state; the variant
                // path must not stub that id again.
                if seq.container_id.is_some() && seq.counter_id.is_none() {
                    ctx.ids.mark_bodied_emitted(wrapper_id);
                }

                // Push the wrapper's name onto the scope path so that nested
                // sequences inside branches get unique IDs (e.g. `scope.s-0.s-0`
                // instead of colliding with the parent's `scope.s-0`).
                let display_name = format!("s-{seq_idx}");
                let old_scope = ctx.scope_path.clone();
                ctx.scope_path = if old_scope.is_empty() {
                    display_name.clone()
                } else {
                    format!("{old_scope}.{display_name}")
                };

                // Lower each sequence branch into its own child container.
                // The wrapper's Sequence.branches hold [EnterContainer(branch_id)]
                // for each branch, and the actual branch content lives in child
                // containers.
                let mut wrapper_children = Vec::new();
                let branches: Vec<Vec<lir::Stmt>> = seq
                    .branches
                    .iter()
                    .enumerate()
                    .map(|(branch_idx, b)| {
                        let mut bc = 0;
                        let mut gc = 0;
                        let (body, branch_children) =
                            lower_block_with_children(&b.body, ctx, &mut bc, &mut gc);

                        // Read pre-stamped container ID from HIR branch block.
                        let branch_id = b.body.container_id.unwrap_or(ctx.root_id);

                        // `b.ptr` is this branch's own span — sibling of
                        // `CondBranch::ptr` above (issue #3183).
                        let branch_container = lir::Container {
                            id: branch_id,
                            provenance: b.ptr,
                            name: Some(format!("{branch_idx}")),
                            kind: lir::ContainerKind::SequenceBranch,
                            params: Vec::new(),
                            body,
                            children: branch_children,
                            counting_flags: CountingFlags::empty(),
                            temp_slot_count: 0,
                            labeled: false,
                            inline: false,
                            is_function: false,
                            local: false,
                        };
                        wrapper_children.push(branch_container);

                        // The branch body in the Sequence struct is just EnterContainer
                        vec![lir::Stmt::new(
                            lir::StmtKind::EnterContainer(branch_id),
                            b.ptr,
                        )]
                    })
                    .collect();

                ctx.scope_path = old_scope;
                let wrapper = lir::Container {
                    id: wrapper_id,
                    provenance: stmt_prov,
                    name: Some(display_name),
                    kind: lir::ContainerKind::Sequence,
                    params: Vec::new(),
                    body: vec![lir::Stmt::new(
                        lir::StmtKind::Sequence(lir::Sequence {
                            kind: seq.kind,
                            branches,
                            counter: seq.counter_id,
                        }),
                        stmt_prov,
                    )],
                    children: wrapper_children,
                    counting_flags: content::sequence_counting_flags(seq),
                    temp_slot_count: 0,
                    labeled: false,
                    inline: false,
                    is_function: false,
                    local: false,
                };
                children.push(wrapper);

                stmts.push(lir::Stmt::new(
                    lir::StmtKind::EnterContainer(wrapper_id),
                    stmt_prov,
                ));
                pos += 1;
            }
            hir::Stmt::Content(content) => {
                // #3274 (stage-2 flip): a variant-claimed line — left whole
                // by normalization — lowers to one EmitLineVariants over
                // shared alternative stub containers.
                if let Some((kind, mut stubs)) = try_lower_variant_line(content, ctx, stmt_prov) {
                    stmts.push(lir::Stmt::new(kind, stmt_prov));
                    children.append(&mut stubs);
                }
                // Try direct recognition.
                else if let Some(emission) = recognize::try_recognize(content, ctx) {
                    stmts.push(lir::Stmt::new(lir::StmtKind::EmitLine(emission), stmt_prov));
                }
                // Try with boundary glue stripping.
                else if let Some((leading, emission, trailing)) =
                    recognize::try_recognize_with_glue(content, ctx)
                {
                    if leading {
                        stmts.push(lir::Stmt::new(
                            lir::StmtKind::EmitContent(lir::Content {
                                parts: vec![lir::ContentPart::Glue],
                                tags: vec![],
                                // Pure structural glue marker synthesized here
                                // (boundary-glue stripping around a recognized
                                // line) — carries no text, so `add_line` never
                                // runs on it; there is no line-table entry to
                                // attribute a location to (issue #3181).
                                source_location: None,
                            }),
                            stmt_prov,
                        ));
                    }
                    stmts.push(lir::Stmt::new(lir::StmtKind::EmitLine(emission), stmt_prov));
                    if trailing {
                        stmts.push(lir::Stmt::new(
                            lir::StmtKind::EmitContent(lir::Content {
                                parts: vec![lir::ContentPart::Glue],
                                tags: vec![],
                                // Pure structural glue marker synthesized here
                                // (boundary-glue stripping around a recognized
                                // line) — carries no text, so `add_line` never
                                // runs on it; there is no line-table entry to
                                // attribute a location to (issue #3181).
                                source_location: None,
                            }),
                            stmt_prov,
                        ));
                    }
                }
                // Fallback: emit content parts individually.
                else {
                    stmts.push(lir::Stmt::new(
                        lir::StmtKind::EmitContent(content::lower_content(content, ctx)),
                        stmt_prov,
                    ));
                }
                children.append(&mut ctx.pending_children);
                pos += 1;
            }
            hir::Stmt::LogicBlock(lb) => {
                // T1b `~ { … }` block (docs/t1b-surface-spec.md §2) — pure
                // logic, spliced directly into the enclosing container's
                // flat statement sequence (never a child container: block
                // bodies never contain weave concepts, so there's nothing
                // that needs container isolation).
                if matches!(lb.scope, hir::LogicBlockScope::Opens) {
                    pending_split_scope = true;
                }
                stmts.extend(blocks::lower_logic_block(lb, ctx));
                pos += 1;
            }

            // A classic (non-block) `~ p.field = expr` logic line (TM-4c,
            // docs/typed-mode-spec.md §6) — same single-level RMW
            // desugaring `~ { … }` block statements use, splicing
            // possibly-multiple `lir::Stmt`s here since `stmts::lower_stmt`'s
            // `Option<Stmt>` return can't express that. Falls through to the
            // ordinary `stmts::lower_stmt` path (the `_` arm below) for
            // every other assignment (plain variable) — indexed targets are
            // caught by the arm just below instead.
            hir::Stmt::Assignment(assign)
                if blocks::try_lower_field_assignment(assign, ctx, &mut stmts) =>
            {
                children.append(&mut ctx.pending_children);
                pos += 1;
            }

            // A classic (non-block) `~ a[i] = expr` logic line whose target
            // is an index expression (issue #2174) — the same dispatch
            // `lower_block_assignment` already gives the `~ { … }` block
            // form, factored into `try_lower_indexed_assignment` so both
            // surfaces share it rather than the classic-line dispatch
            // growing a second, divergent copy. Before this arm existed,
            // an `Index` target fell through to `stmts::lower_stmt`, whose
            // `lower_assign_target` only recognizes a bare `Path` — the
            // statement silently vanished with no diagnostic, for *every*
            // classic-line indexed assignment (not only the struct-field-
            // projected-root shape #2121 fixed for the block surface).
            // Handles a bare-variable root correctly and rejects a
            // struct-field-projected root with `E074`
            // (`reject_field_projection_index_root`), mirroring #2121.
            hir::Stmt::Assignment(assign)
                if blocks::try_lower_indexed_assignment(assign, ctx, &mut stmts) =>
            {
                children.append(&mut ctx.pending_children);
                pos += 1;
            }

            // Issue #2903 — a classic (non-block) `~ a[i]++`/`~ a[i]--` logic
            // line whose postfix operand is an `Index` target (`a[0]++`,
            // `m["k"]++`). `try_lower_postfix_stmt` now routes an
            // Index-operand postfix through `lower_indexed_assignment`,
            // which can splice *several* `lir::Stmt`s (the RMW
            // take/mutate/write-back sequence) — `stmts::lower_stmt`'s
            // `Option<Stmt>` return truncates that to just its first element
            // (harmless but non-mutating: the actual write-back never runs),
            // the same shape of bug `try_lower_indexed_assignment` above was
            // added to prevent for `~ a[i] = v`. Dispatched here, before the
            // `_` fallback, for the same reason.
            hir::Stmt::ExprStmt(expr) if blocks::try_lower_postfix_stmt(expr, ctx, &mut stmts) => {
                children.append(&mut ctx.pending_children);
                pos += 1;
            }

            // A classic (non-block) `~ push(a, v)` logic line — same
            // mutator recognition/RMW desugaring `~ { … }` block statements
            // use (docs/t1b-surface-spec.md §5), splicing possibly-multiple
            // `lir::Stmt`s here since `stmts::lower_stmt`'s `Option<Stmt>`
            // return can't express that. Falls through to the ordinary
            // `stmts::lower_stmt` path (the `_` arm below) for every other
            // expression statement, including a shadowed `push`/`insert`/
            // `remove` user function.
            hir::Stmt::ExprStmt(expr) if blocks::try_lower_mutator_stmt(expr, ctx, &mut stmts) => {
                children.append(&mut ctx.pending_children);
                pos += 1;
            }

            // A classic (non-block) frame-local projection auto-ref
            // (`g.hp.heal(5)`, issue #1531) — same RMW splicing the block
            // form (`blocks::lower_block_stmt`'s `ExprStmt` arm) uses, and
            // for the same reason: the read/call/write-back sequence needs
            // more than one `lir::Stmt`.
            hir::Stmt::ExprStmt(expr)
                if blocks::try_lower_frame_local_auto_ref_stmt(expr, ctx, &mut stmts) =>
            {
                children.append(&mut ctx.pending_children);
                pos += 1;
            }

            _ => {
                if let Some(s) = stmts::lower_stmt(stmt, ctx) {
                    stmts.push(s);
                }
                // Drain any inline sequence containers created during content lowering.
                children.append(&mut ctx.pending_children);
                pos += 1;
            }
        }

        // Restore the ambient to this statement's own provenance — a
        // recursive call above (a choice's body, a conditional/sequence
        // branch) may have advanced `ctx.current_stmt_provenance` to a
        // nested descendant's value. Without this, the next sibling
        // statement that falls back to the ambient (EndOfLine,
        // EndElementRun, an option-less Divert/Content) would inherit that
        // descendant's context instead of its own preceding sibling's
        // (issue #3183 follow-up).
        ctx.current_stmt_provenance = stmt_prov;
    }

    if pending_split_scope {
        ctx.pop_block_scope();
    }

    (stmts, children)
}

/// Build a gather container from a `ChoiceSet`'s continuation block.
///
/// The continuation's label becomes the container name, its stmts become
/// the body (lowered via `lower_block_with_children` to handle nested
/// `ChoiceSet`s in gather-choice chains).
fn build_continuation_container(
    continuation: &hir::Block,
    ctx: &mut LowerCtx<'_>,
    gather_id: Option<brink_format::DefinitionId>,
    gather_index: usize,
    choice_counter: &mut usize,
    gather_counter: &mut usize,
    provenance: Provenance,
) -> lir::Container {
    let id = gather_id.unwrap_or(ctx.root_id);
    let display_name = continuation
        .label
        .as_ref()
        .map_or_else(|| format!("g-{gather_index}"), |l| l.text.clone());

    // Check if the gather has a source-level label that resolves.
    let labeled = continuation
        .label
        .as_ref()
        .is_some_and(|label| ctx.lookup_address_id(&label.text).is_some());

    if continuation.stmts.is_empty() && continuation.label.is_none() {
        // Empty continuation with no label — the choice set is the last
        // thing in its enclosing block. At the story's root content this
        // is a safe implicit end (real ink lets root content run out), so
        // emit the same `-> DONE` a genuine `-> DONE` statement would
        // produce. Inside a knot/stitch, though, running off the end
        // without an explicit `-> DONE`/`-> END` is a real ink runtime
        // error ("ran out of content") — leaving the body empty here lets
        // the VM's normal frame-exhaustion path (`handle_frame_exhaustion`)
        // surface that instead of masking it as a safe exit (issue #1503).
        let body = if ctx.is_root_content_scope {
            // Nested inside a choice body that has a gather of its own, the
            // empty continuation falls into THAT gather — the exit is
            // emitted here directly so `patch_innermost_gather` never has to
            // overwrite a terminator to reach it (issue #3383).
            let target = ctx
                .choice_gather_target
                .map_or(lir::DivertTarget::Done, lir::DivertTarget::Address);
            vec![lir::Stmt::new(
                lir::StmtKind::Divert(lir::Divert {
                    target,
                    args: Vec::new(),
                }),
                provenance,
            )]
        } else {
            Vec::new()
        };
        return lir::Container {
            id,
            // `hir::Block` (the continuation) carries no `.ptr` of its own —
            // inherit the explicit `provenance` the caller passed, which is
            // the enclosing `ChoiceSet`'s own provenance (issue #3183). This
            // is passed explicitly rather than read off
            // `ctx.current_stmt_provenance` because by the time this
            // function runs, the choices have already been lowered through
            // the same `ctx` (each recursing into its own body), so the
            // ambient no longer reflects the ChoiceSet's own provenance.
            provenance,
            name: Some(display_name),
            kind: lir::ContainerKind::Gather,
            params: Vec::new(),
            body,
            children: Vec::new(),
            counting_flags: CountingFlags::empty(),
            temp_slot_count: 0,
            labeled: false,
            inline: false,
            is_function: false,
            local: false,
        };
    }

    // Lower continuation stmts — may contain nested ChoiceSets (gather-choice chains)
    let (body, children) =
        lower_block_with_children(continuation, ctx, choice_counter, gather_counter);

    lir::Container {
        id,
        // Same reasoning as the empty-continuation branch above: `provenance`
        // is the ChoiceSet's own provenance passed explicitly by the caller,
        // not the (by-now-stale) ambient — the `lower_block_with_children`
        // call just above advances `ctx.current_stmt_provenance` to whatever
        // the continuation's own last statement is.
        provenance,
        name: Some(display_name),
        kind: lir::ContainerKind::Gather,
        params: Vec::new(),
        body,
        children,
        counting_flags: CountingFlags::empty(),
        temp_slot_count: 0,
        labeled,
        inline: false,
        is_function: false,
        local: false,
    }
}

/// Cover two optional source locations — the smallest range containing
/// both, when they name the same file (review finding, #3202). One-sided
/// inputs pass through unchanged; differing files (should not arise for two
/// regions of the same choice) fall back to whichever side is present,
/// preferring `a`, since there is no single range that could honestly
/// cover both. Mirrors `brink-codegen-inkb::container::union_source_location`
/// — duplicated rather than shared because the two crates have no common
/// dependency to host it in besides `brink_format` itself.
fn union_source_location(
    a: Option<&brink_format::SourceLocation>,
    b: Option<&brink_format::SourceLocation>,
) -> Option<brink_format::SourceLocation> {
    match (a, b) {
        (None, None) => None,
        (Some(loc), None) | (None, Some(loc)) => Some(loc.clone()),
        (Some(a), Some(b)) if a.file == b.file => Some(brink_format::SourceLocation {
            file: a.file.clone(),
            range_start: a.range_start.min(b.range_start),
            range_end: a.range_end.max(b.range_end),
        }),
        (Some(a), Some(_)) => Some(a.clone()),
    }
}

#[expect(clippy::too_many_lines, reason = "choice lowering has many parts")]
fn lower_choice_with_child(
    choice: &hir::Choice,
    ctx: &mut LowerCtx<'_>,
    choice_counter: &mut usize,
    gather_target: Option<brink_format::DefinitionId>,
) -> (lir::Choice, Option<lir::Container>) {
    *choice_counter += 1;

    let target = choice.container_id.unwrap_or(ctx.root_id);

    // The block scope opens BEFORE the condition (so a guard-`as` binding,
    // B1b issue #1508, can declare into it) and stays open across the
    // choice's own content (start/bracket/inner) AND the *body* lowering
    // below — unlike `blocks::lower_if_branch`'s bracket (which closes
    // after the success arm and never reaches an `else`), a choice has no
    // sibling arm to hide the binding from, so the scope simply wraps
    // condition -> content -> body together. Every choice pushes/pops a
    // scope, whether it binds or not, exactly like an ordinary `if`.
    //
    // This ordering matters: `{n}` appearing in the choice's own
    // start/bracket/inner content (not just its body) must resolve
    // through the same block-scoped temp slot the binding declares, so
    // the content lowering below MUST happen after `push_block_scope`
    // and the condition/binding lowering, not before.
    ctx.push_block_scope();
    let condition = match (choice.condition.as_ref(), choice.binding.as_ref()) {
        (Some(cond_hir), Some(binding)) => {
            Some(blocks::lower_bound_condition(cond_hir, binding, ctx))
        }
        (Some(cond_hir), None) => Some(expr::lower_expr(cond_hir, ctx)),
        (None, _) => None,
    };

    // Preserve the three-part content split for codegen backends.
    let start_content = choice
        .start_content
        .as_ref()
        .map(|c| content::lower_content(c, ctx));
    let choice_only_content = choice
        .bracket_content
        .as_ref()
        .map(|c| content::lower_content(c, ctx));
    let inner_content = choice
        .inner_content
        .as_ref()
        .map(|c| content::lower_content(c, ctx));

    // ── Compose and recognize display/output content at HIR level ──
    // Display = start + bracket, Output = start + inner.
    let display_hir = recognize::compose_hir_content_opt(
        choice.start_content.as_ref(),
        choice.bracket_content.as_ref(),
    );
    let output_hir = recognize::compose_hir_content_opt(
        choice.start_content.as_ref(),
        choice.inner_content.as_ref(),
    );

    // Skip recognition when composed content starts with whitespace-only
    // text — the inline emission path's `push_text` suppresses leading whitespace
    // that `EvalLine`/`EmitLine` would preserve, changing observable behavior.
    let display_ws = display_hir
        .as_ref()
        .is_some_and(recognize::starts_with_whitespace_only_text);
    let output_ws = output_hir
        .as_ref()
        .is_some_and(recognize::starts_with_whitespace_only_text);

    let display_emission = if display_ws {
        None
    } else {
        display_hir
            .as_ref()
            .and_then(|c| recognize::try_recognize(c, ctx))
    };
    let output_emission = if output_ws {
        None
    } else {
        output_hir
            .as_ref()
            .and_then(|c| recognize::try_recognize(c, ctx))
    };

    let tags: Vec<Vec<lir::ContentPart>> = choice
        .tags
        .iter()
        .map(|t| content::lower_content_parts_pub(&t.parts, ctx))
        .collect();

    // Lower choice body into a child container.
    // Update scope_path to match the planner's convention so nested
    // choice/gather keys resolve to the correct container IDs.
    // Set choice_gather_target so labeled containers within the body
    // can include an explicit goto to the gather.
    let old_scope = ctx.scope_path.clone();
    let old_gather_target = ctx.choice_gather_target;
    // `c-{n}`, dash-separated — the same synthesized-segment spelling the
    // stamping pass uses for `child_scope` (`hir::stamp::stamp_stmt`) and
    // the display `child_name` below always used. Kept in lock-step with
    // the stamping pass deliberately (#1727's parity ruling: stamped
    // lambda ids derive from these exact scope strings), and the dash is
    // load-bearing for the ids *this* scope mints too
    // (`alloc_sequence_id`'s `{scope}.s-{n}` wrappers): a bare `c{n}` can
    // equal an authored knot named `c0`, colliding under the shared
    // `#file:` namespace (issue #2229 review).
    ctx.scope_path = format!("{}.c-{}", old_scope, *choice_counter - 1);
    ctx.choice_gather_target = gather_target;
    let mut cc = 0;
    let mut gc = 0;
    let (body_stmts, mut children) = lower_block_with_children(&choice.body, ctx, &mut cc, &mut gc);
    ctx.scope_path = old_scope;
    ctx.choice_gather_target = old_gather_target;
    ctx.pop_block_scope();

    // Build the choice target container body. The output after selecting
    // a choice is: ChoiceOutput(content) + body stmts.
    // The HIR body already contains the inline divert and EndOfLine as
    // its first statements, so they flow naturally into the LIR body.
    let mut body: Vec<lir::Stmt> = Vec::new();

    // 1. Choice output preamble: start+inner content with their tags.
    // Tags on start/inner content appear in the output after choosing;
    // bracket-only tags are suppressed (they only affect choice display).
    {
        let mut output_parts = Vec::new();
        let mut output_tags = Vec::new();
        // The cover of start's and inner's locations (review finding,
        // #3202) — not start's alone. `emit_content_parts`
        // (`brink-codegen-inkb`) stamps this one location on every
        // fragment it emits from `output_parts`, including inner's
        // fragments once combined here; "start's location wins" made an
        // inner-only fragment carry a range that doesn't even contain its
        // own text. Mirrors `container.rs`'s `combine_choice_content` fix
        // for the same start-then-bracket/inner join on the pre-selection
        // display side.
        let mut output_source_location = None;
        if let Some(ref sc) = start_content {
            output_parts.extend(sc.parts.clone());
            output_tags.extend(sc.tags.clone());
            output_source_location.clone_from(&sc.source_location);
        }
        if let Some(ref ic) = inner_content {
            output_parts.extend(ic.parts.clone());
            output_tags.extend(ic.tags.clone());
            output_source_location =
                union_source_location(output_source_location.as_ref(), ic.source_location.as_ref());
        }
        if !output_parts.is_empty() || !output_tags.is_empty() {
            body.push(lir::Stmt::new(
                lir::StmtKind::ChoiceOutput {
                    content: lir::Content {
                        parts: output_parts,
                        tags: output_tags,
                        source_location: output_source_location,
                    },
                    emission: output_emission.clone(),
                },
                // `choice.ptr` — this choice's own range (issue #3183),
                // finer-grained than the ambient ChoiceSet-wide fallback.
                choice.ptr,
            ));
        }
    }

    // 2. Body statements from the choice's block (includes inline divert + EndOfLine)
    body.extend(body_stmts);

    // 5. Auto-gather divert when the body doesn't end with Done/End.
    let ends_with_terminal = body.last().is_some_and(|s| {
        matches!(
            &s.kind,
            lir::StmtKind::Divert(d) if matches!(d.target, lir::DivertTarget::Done | lir::DivertTarget::End)
        )
    });
    if !ends_with_terminal && let Some(gather_id) = gather_target {
        let body_ends_with_choice_set = body
            .last()
            .is_some_and(|s| matches!(&s.kind, lir::StmtKind::ChoiceSet(_)));

        let divert = lir::Divert {
            target: lir::DivertTarget::Address(gather_id),
            args: Vec::new(),
        };

        if body_ends_with_choice_set {
            // The body ends with a ChoiceSet → `done` stops execution,
            // so a divert appended to the body would be dead code.
            // Instead, patch the innermost gather container so that
            // after the inner gather's content, execution flows to the
            // outer gather. This recurses through nested choice-set-
            // in-gather chains (multi-level weaves).
            patch_innermost_gather(&mut children, divert);
        } else {
            body.push(lir::Stmt::new(lir::StmtKind::Divert(divert), choice.ptr));
        }
    }

    // Check if the choice has a source-level label that resolves.
    let labeled = choice
        .label
        .as_ref()
        .is_some_and(|label| ctx.lookup_address_id(&label.text).is_some());

    let child_name = format!("c-{}", *choice_counter - 1);
    let child = lir::Container {
        id: target,
        provenance: choice.ptr,
        name: Some(child_name),
        kind: lir::ContainerKind::ChoiceTarget,
        params: Vec::new(),
        body,
        children,
        counting_flags: if choice.is_sticky {
            CountingFlags::empty()
        } else {
            CountingFlags::VISITS | CountingFlags::COUNT_START_ONLY
        },
        temp_slot_count: 0,
        labeled,
        inline: false,
        is_function: false,
        local: false,
    };

    let lir_choice = lir::Choice {
        is_sticky: choice.is_sticky,
        is_fallback: choice.is_fallback,
        condition,
        start_content,
        choice_only_content,
        inner_content,
        display_emission,
        output_emission,
        target,
        tags,
    };

    (lir_choice, Some(child))
}

// `lower_gather_choice_chain` and `build_gather_container` removed in Phase 2.
// Gather-choice chains are now handled via nested continuation blocks in the
// HIR, lowered naturally by `lower_block_with_children` + `build_continuation_container`.

// ─── Helpers ────────────────────────────────────────────────────────

#[expect(clippy::too_many_arguments)]
fn make_ctx<'a>(
    file: FileId,
    native: bool,
    resolutions: &'a ResolutionLookup,
    index: &'a SymbolIndex,
    temps: &'a TempMap,
    names: &'a mut NameTable,
    ids: &'a mut context::IdAllocator,
    root_id: brink_format::DefinitionId,
    scope_path: String,
    is_root_content_scope: bool,
    param_names: &[&str],
    file_paths: &'a LookupMap<FileId, String>,
    next_block_slot: &'a mut u16,
    diagnostics: &'a mut Vec<crate::Diagnostic>,
    structs: &'a context::StructCtx<'a>,
    tables: context::AnalyzerTables<'a>,
    lifted: &'a mut Vec<lir::Container>,
) -> LowerCtx<'a> {
    LowerCtx {
        file,
        native,
        resolutions,
        index,
        temps,
        names,
        ids,
        scope_path,
        is_root_content_scope,
        pending_children: Vec::new(),
        visible_temps: param_names.iter().map(|s| (*s).to_string()).collect(),
        file_paths,
        root_id,
        choice_gather_target: None,
        next_block_slot,
        block_scopes: Vec::new(),
        as_binding_slots: LookupSet::new(),
        block_scoped_temp_names: LookupSet::new(),
        diagnostics,
        loop_depth: 0,
        structs,
        temp_shapes: LookupMap::new(),
        tables,
        lifted,
        // Overwritten by `ctx.enter_stmt(..)` before any real statement
        // lowers (issue #3183) — this seed is never observed by a
        // well-formed container, whose body is never empty of statements
        // reaching a dispatch point.
        current_stmt_provenance: Provenance::synthetic(NodeClass::Stmt, TextRange::empty(0.into())),
    }
}

fn lower_params(
    params: &[hir::Param],
    names: &mut NameTable,
    temp_map: &TempMap,
) -> Vec<lir::Param> {
    params
        .iter()
        .map(|p| {
            let name = names.intern(&p.name.text);
            let slot = temp_map.get(&p.name.text).unwrap_or(0);
            lir::Param {
                name,
                slot,
                is_ref: p.is_ref,
                is_divert: p.is_divert,
            }
        })
        .collect()
}

/// Look up a container's own `DefinitionId` by name in the symbol index —
/// "what id did the analyzer already assign to the knot/stitch/label THIS
/// FILE is lowering right now."
///
/// Checks for knot, stitch, or label symbols — the same container
/// types the analyzer registers.
///
/// **File-scoped, not project-flat** (issue #2197): with M-2d
/// (`is_cross_declared_module_collision`) letting same-name definitions in
/// different *declared* modules coexist in `index.by_name`, a bare
/// unscoped `.find()` here would pick whichever candidate happens to sort
/// first for *every* file lowering a container of that name — so two
/// distinctly-hashed, distinctly-declared knots (e.g. a project's own
/// `scene_entered` and `brink_environment`'s mounted
/// `std/conventions/screenplay.brink`'s own `scene_entered`) both mint the
/// SAME container id, which trips the `#1673` duplicate-`DefinitionId`
/// codegen guard (`E060`) the moment both are walked into the container
/// tree. Preferring the entry declared in `file` is the correct semantic
/// regardless of module visibility policy — a container's own identity is
/// always the one *this file* declared — and it is what actually resolves
/// the collision, since the two files' own entries are already correctly
/// distinct per-module hashes (`brink_analyzer::manifest::insert_symbol`).
/// Falling back to the unscoped first match preserves byte-identical
/// behavior for every pre-#2197 call, where `by_name` never held more than
/// one Knot/Stitch/Label candidate for a given name.
fn lookup_container_id(
    index: &SymbolIndex,
    file: FileId,
    name: &str,
) -> Option<brink_format::DefinitionId> {
    use crate::symbols::SymbolKind;
    fn is_container(info: &crate::symbols::SymbolInfo) -> bool {
        matches!(
            info.kind,
            SymbolKind::Knot | SymbolKind::Stitch | SymbolKind::Label
        )
    }
    index.by_name.get(name).and_then(|ids| {
        ids.iter()
            .find(|&&id| {
                index
                    .symbols
                    .get(&id)
                    .is_some_and(|info| is_container(info) && info.file == file)
            })
            .or_else(|| {
                ids.iter()
                    .find(|&&id| index.symbols.get(&id).is_some_and(is_container))
            })
            .copied()
    })
}

// ─── Counting flags ─────────────────────────────────────────────────

fn apply_counting_flags(root: &mut lir::Container, globals: &[lir::GlobalDef]) {
    let mut visit_ids = Vec::new();
    let mut turns_ids = Vec::new();

    // Collect phase: walk entire tree for explicit visit/turn refs
    collect_counting_refs_tree(root, &mut visit_ids, &mut turns_ids);

    // Also scan global variable defaults for DivertTarget values
    // (e.g. `VAR x = -> knot` — the target could be reached via variable divert)
    for g in globals {
        if let lir::ConstValue::DivertTarget(id) = &g.default {
            visit_ids.push(*id);
            turns_ids.push(*id);
        }
    }

    // Apply phase: walk entire tree
    apply_counting_flags_tree(root, &visit_ids, &turns_ids, false);
}

fn collect_counting_refs_tree(
    container: &lir::Container,
    visit_ids: &mut Vec<brink_format::DefinitionId>,
    turns_ids: &mut Vec<brink_format::DefinitionId>,
) {
    collect_counting_refs(&container.body, visit_ids, turns_ids);
    for child in &container.children {
        collect_counting_refs_tree(child, visit_ids, turns_ids);
    }
}

fn apply_counting_flags_tree(
    container: &mut lir::Container,
    visit_ids: &[brink_format::DefinitionId],
    turns_ids: &[brink_format::DefinitionId],
    in_local_scope: bool,
) {
    // `#@local` on a knot/stitch declares that its counts are per-flow
    // memory (#496): force VISITS on the marked container and on every
    // scope-owning container in its definition subtree (a marked knot
    // covers its stitches — the runtime privatizes the whole subtree at
    // policy resolution), regardless of the read-site analysis below.
    // Interior containers are untouched: sequences already carry VISITS
    // intrinsically (branch selection needs the counter), and unread
    // labels stay compiled out exactly as in unmarked scopes.
    let in_local_scope = in_local_scope || container.local;
    if in_local_scope
        && matches!(
            container.kind,
            lir::ContainerKind::Knot | lir::ContainerKind::Stitch
        )
    {
        container.counting_flags |= CountingFlags::VISITS;
    }

    if visit_ids.contains(&container.id) {
        container.counting_flags |= CountingFlags::VISITS;
        // Labeled containers (gathers with labels like `- (loop)`) need
        // COUNT_START_ONLY so that self-goto loops correctly increment
        // the visit count in the runtime's goto_target handler.
        if container.labeled {
            container.counting_flags |= CountingFlags::COUNT_START_ONLY;
        }
    }
    if turns_ids.contains(&container.id) {
        container.counting_flags |= CountingFlags::TURNS;
    }
    for child in &mut container.children {
        apply_counting_flags_tree(child, visit_ids, turns_ids, in_local_scope);
    }
}

fn collect_counting_refs(
    stmts: &[lir::Stmt],
    visit_ids: &mut Vec<brink_format::DefinitionId>,
    turns_ids: &mut Vec<brink_format::DefinitionId>,
) {
    for stmt in stmts {
        match &stmt.kind {
            lir::StmtKind::EmitContent(content) | lir::StmtKind::ChoiceOutput { content, .. } => {
                collect_counting_refs_content(content, visit_ids, turns_ids);
            }
            lir::StmtKind::EmitLine(emission) | lir::StmtKind::EvalLine(emission) => {
                // Template slot expressions may contain counting refs.
                if let lir::RecognizedLine::Template { slot_exprs, .. } = &emission.line {
                    for e in slot_exprs {
                        collect_counting_refs_expr(e, visit_ids, turns_ids);
                    }
                }
                // Tags may contain dynamic expressions — traverse them.
                for tag in &emission.tags {
                    for part in tag {
                        if let lir::ContentPart::Interpolation(e) = part {
                            collect_counting_refs_expr(e, visit_ids, turns_ids);
                        }
                    }
                }
            }
            lir::StmtKind::Assign { value: e, .. }
            | lir::StmtKind::DeclareTemp { value: Some(e), .. }
            | lir::StmtKind::Return { value: Some(e), .. }
            | lir::StmtKind::ExprStmt(e) => {
                collect_counting_refs_expr(e, visit_ids, turns_ids);
            }
            lir::StmtKind::ChoiceSet(cs) => {
                for choice in &cs.choices {
                    if let Some(ref cond) = choice.condition {
                        collect_counting_refs_expr(cond, visit_ids, turns_ids);
                    }
                    if let Some(ref c) = choice.start_content {
                        collect_counting_refs_content(c, visit_ids, turns_ids);
                    }
                    if let Some(ref c) = choice.choice_only_content {
                        collect_counting_refs_content(c, visit_ids, turns_ids);
                    }
                    if let Some(ref c) = choice.inner_content {
                        collect_counting_refs_content(c, visit_ids, turns_ids);
                    }
                    // Traverse recognized emissions for counting refs in slot exprs.
                    for emission in choice
                        .display_emission
                        .iter()
                        .chain(choice.output_emission.iter())
                    {
                        if let lir::RecognizedLine::Template { slot_exprs, .. } = &emission.line {
                            for e in slot_exprs {
                                collect_counting_refs_expr(e, visit_ids, turns_ids);
                            }
                        }
                    }
                }
            }
            lir::StmtKind::Conditional(cond) => {
                for branch in &cond.branches {
                    if let Some(ref e) = branch.condition {
                        collect_counting_refs_expr(e, visit_ids, turns_ids);
                    }
                    collect_counting_refs(&branch.body, visit_ids, turns_ids);
                }
            }
            lir::StmtKind::Sequence(seq) => {
                for branch in &seq.branches {
                    collect_counting_refs(branch, visit_ids, turns_ids);
                }
            }
            lir::StmtKind::Divert(d) => {
                for arg in &d.args {
                    collect_counting_refs_call_arg(arg, visit_ids, turns_ids);
                }
            }
            lir::StmtKind::TunnelCall(tc) => {
                for t in &tc.targets {
                    for arg in &t.args {
                        collect_counting_refs_call_arg(arg, visit_ids, turns_ids);
                    }
                }
            }
            lir::StmtKind::ThreadStart(ts) => {
                for arg in &ts.args {
                    collect_counting_refs_call_arg(arg, visit_ids, turns_ids);
                }
            }
            // EnterContainer, DeclareTemp(None), Return(None), etc.
            _ => {}
        }
    }
}

fn collect_counting_refs_content(
    content: &lir::Content,
    visit_ids: &mut Vec<brink_format::DefinitionId>,
    turns_ids: &mut Vec<brink_format::DefinitionId>,
) {
    for part in &content.parts {
        match part {
            lir::ContentPart::Interpolation(e) => {
                collect_counting_refs_expr(e, visit_ids, turns_ids);
            }
            lir::ContentPart::InlineConditional(cond) => {
                for branch in &cond.branches {
                    if let Some(ref e) = branch.condition {
                        collect_counting_refs_expr(e, visit_ids, turns_ids);
                    }
                    collect_counting_refs(&branch.body, visit_ids, turns_ids);
                }
            }
            lir::ContentPart::InlineSequence(seq) => {
                for branch in &seq.branches {
                    collect_counting_refs(branch, visit_ids, turns_ids);
                }
            }
            // Text, Glue, EnterSequence
            _ => {}
        }
    }
}

/// A `TURNS_SINCE`/`READ_COUNT` reference inside a call argument — a plain
/// `Value` arg's expression, or (T1e) a `RefProjection`'s segment
/// expressions (`ref arr[READ_COUNT(-> x)]` is a legal, if unusual, snapshot
/// segment). `RefGlobal`/`RefTemp` carry no expression to scan.
fn collect_counting_refs_call_arg(
    arg: &lir::CallArg,
    visit_ids: &mut Vec<brink_format::DefinitionId>,
    turns_ids: &mut Vec<brink_format::DefinitionId>,
) {
    match arg {
        lir::CallArg::Value(e) => collect_counting_refs_expr(e, visit_ids, turns_ids),
        lir::CallArg::RefProjection { segments, .. } => {
            for seg in segments {
                collect_counting_refs_expr(seg, visit_ids, turns_ids);
            }
        }
        lir::CallArg::RefGlobal(_) | lir::CallArg::RefTemp(_, _) => {}
    }
}

fn collect_counting_refs_expr(
    expr: &lir::Expr,
    visit_ids: &mut Vec<brink_format::DefinitionId>,
    turns_ids: &mut Vec<brink_format::DefinitionId>,
) {
    match &expr.kind {
        lir::ExprKind::VisitCount(id) => visit_ids.push(*id),
        lir::ExprKind::DivertTarget(id) => {
            // Any container whose address is taken could be reached via
            // variable divert/tunnel — conservatively mark for visit tracking.
            visit_ids.push(*id);
            turns_ids.push(*id);
        }
        lir::ExprKind::CallBuiltin {
            builtin: lir::BuiltinFn::TurnsSince,
            args,
        } => {
            for a in args {
                if let lir::ExprKind::DivertTarget(id) = &a.kind {
                    turns_ids.push(*id);
                }
                collect_counting_refs_expr(a, visit_ids, turns_ids);
            }
        }
        lir::ExprKind::Prefix(_, inner) | lir::ExprKind::Postfix(inner, _) => {
            collect_counting_refs_expr(inner, visit_ids, turns_ids);
        }
        // B1 `or`-coalescing (#1471) is a dedicated variant, not generic
        // `Infix` — but the walk is identical (both operands, `shape`
        // carries no reference), so it rides the same arm rather than a
        // duplicate one, matching `chunk::remap_expr`'s precedent.
        lir::ExprKind::Infix(lhs, _, rhs) | lir::ExprKind::Coalesce { lhs, rhs, shape: _ } => {
            collect_counting_refs_expr(lhs, visit_ids, turns_ids);
            collect_counting_refs_expr(rhs, visit_ids, turns_ids);
        }
        lir::ExprKind::Call { args, .. } | lir::ExprKind::CallExternal { args, .. } => {
            for arg in args {
                collect_counting_refs_call_arg(arg, visit_ids, turns_ids);
            }
        }
        lir::ExprKind::CallBuiltin { args, .. } => {
            for a in args {
                collect_counting_refs_expr(a, visit_ids, turns_ids);
            }
        }
        lir::ExprKind::String(s) => {
            for p in &s.parts {
                if let lir::StringPart::Interpolation(e) = p {
                    collect_counting_refs_expr(e, visit_ids, turns_ids);
                }
            }
        }
        _ => {}
    }
}

/// Display name of the synthesized root terminus container. `-` is not a
/// legal character in an ink label and the auto-gather convention is the
/// numeric `g-{index}`, so this segment can never collide with an authored
/// or auto-generated gather name.
const ROOT_TERMINUS_NAME: &str = "g-final";

/// Mirror inklecate's **implicit final gather** at the end of the root weave
/// (`FlowBase.SplitWeaveAndSubFlowContent`, `FlowBase.cs:69-72`, which appends
/// `Gather(null, 1)` + `-> DONE` when lowering the root story): a branch that
/// simply runs out of root-weave content ends the flow cleanly instead of
/// faulting with `RanOutOfContent`.
///
/// The root container's own trailing `Divert(Done)`
/// ([`assemble_program`]) cannot serve this purpose: a gather is reached by
/// `goto`, which clears the container stack, so once execution lands in a
/// gather container the root body is no longer on the frame and its `Done`
/// can never run.
///
/// **Root scope only** (#1448). A knot, stitch, tunnel or function whose
/// content runs out is a genuine authoring error that C# ink reports and
/// brink must keep reporting — extending a terminus to every weave terminus
/// regresses those cases.
///
/// **Entry file only** (#1502). C# appends the implicit gather exactly once,
/// to the *root story's* weave — `SplitWeaveAndSubFlowContent`'s
/// `if (isRootStory)` guard. An `INCLUDE`d file is parsed as
/// `Story(isInclude: true)` and gets none: `Story.PreProcessTopLevelObjects`
/// splices its non-flow content in as the included story's own already-built
/// `Weave`, which becomes a nested weave *container* in the root — so a
/// trailing gather there is entered by divert (clearing the container stack)
/// and running out of it faults with `RanOutOfContent`, exactly as it does in
/// brink. Terminating included files individually would silently end the flow
/// mid-story instead, which is strictly worse than the loud fault it replaces.
///
/// Callers therefore apply this to the **last** root-content chunk only. For
/// an ink project that is the entry file by construction:
/// `compilation_closure_files` orders the closure with
/// `IncludeGraph::topological_order(entry)`, a post-order DFS from `entry`
/// that pushes `entry` after everything it includes, so `entry` is always the
/// final element. (A native project's closure is `FileId`-ordered instead,
/// but `.brink` modules have no root weave to terminate.) Positionally this
/// is also the only correct spot: the chunks concatenate into one root body,
/// and C#'s implicit gather sits at the very end of it.
fn attach_root_final_gather(children: &mut Vec<lir::Container>, ids: &mut context::IdAllocator) {
    // `#` never appears in a lowering scope path, so this key cannot collide
    // with a real container address. Content-pure since #1504: it used to be
    // keyed `#root-terminus.{file_id}`, the one `alloc_address` call in this
    // crate keyed by a `FileId` — an allocation-history-derived id (the
    // editor mints a different `FileId` for the same file when a sibling is
    // registered first), which `docs/fine-grained-salsa-proposal.md` §FG-4d
    // forbids. The owning file now reaches the key through the allocator's
    // path prefix (`IdAllocator::set_path_prefix`), which is derived from
    // that file's project path instead.
    let terminus_id = ids.alloc_address("#root-terminus");

    if !patch_root_loose_end(children, terminus_id) {
        return;
    }

    // Whole-program synthetic (issue #3183) — C#'s implicit end-of-root-
    // weave marker has no HIR node of its own to point at, and this
    // assembly-time function has no `LowerCtx` to fall back on either.
    let provenance = Provenance::synthetic(NodeClass::Stmt, TextRange::empty(0.into()));
    children.push(lir::Container {
        id: terminus_id,
        provenance,
        name: Some(ROOT_TERMINUS_NAME.to_string()),
        kind: lir::ContainerKind::Gather,
        params: Vec::new(),
        body: vec![lir::Stmt::new(
            lir::StmtKind::Divert(lir::Divert {
                target: lir::DivertTarget::Done,
                args: Vec::new(),
            }),
            provenance,
        )],
        children: Vec::new(),
        counting_flags: CountingFlags::empty(),
        temp_slot_count: 0,
        labeled: false,
        inline: false,
        is_function: false,
        local: false,
    });
}

/// Divert the root weave's outermost loose end to `terminus`, returning
/// whether one was found (and therefore whether the terminus container is
/// reachable and worth emitting).
///
/// HIR nests each choice set's post-gather content into that set's
/// continuation, so the root weave's outermost loose end is the tail of the
/// gather chain hanging off the last root-level child: descend while a gather
/// ends with another `ChoiceSet` (its continuation gather holds the deeper
/// content), then patch the first gather that does not.
///
/// Nothing is patched when the tail already ends in a terminal — an authored
/// `-> DONE` / `-> END` / divert is not a loose end, and unlike
/// [`patch_innermost_gather`] this must never overwrite one.
///
/// An `inline` gather (the wrapper a source-level standalone gather lowers to)
/// is never patched in its own right: it is entered with `EnterContainer` and
/// returns to its parent when exhausted, so it already falls through to the
/// root body's own `Done`. Its *children* are still descended into, because a
/// choice set inside it diverts — clearing the container stack — into a
/// continuation gather that is a genuine loose end.
fn patch_root_loose_end(
    children: &mut [lir::Container],
    terminus: brink_format::DefinitionId,
) -> bool {
    let Some(gather) = children
        .last_mut()
        .filter(|c| c.kind == lir::ContainerKind::Gather)
    else {
        return false;
    };

    if gather
        .body
        .last()
        .is_some_and(|s| matches!(&s.kind, lir::StmtKind::ChoiceSet(_)))
    {
        return patch_root_loose_end(&mut gather.children, terminus);
    }

    if gather.inline {
        return false;
    }

    let ends_terminal = gather.body.last().is_some_and(|s| {
        matches!(
            &s.kind,
            lir::StmtKind::Divert(d)
                if matches!(
                    d.target,
                    lir::DivertTarget::End
                        | lir::DivertTarget::Done
                        | lir::DivertTarget::Address(_)
                )
        )
    });
    if ends_terminal {
        return false;
    }

    // No `LowerCtx` reaches this post-assembly patching pass — inherit the
    // gather container's own provenance (issue #3183), stamped when it was
    // built, for the divert being spliced into its body.
    let provenance = gather.provenance;
    gather.body.push(lir::Stmt::new(
        lir::StmtKind::Divert(lir::Divert {
            target: lir::DivertTarget::Address(terminus),
            args: Vec::new(),
        }),
        provenance,
    ));
    true
}

/// Recursively find the innermost gather container in a chain of
/// gather-contains-`ChoiceSet` nesting and patch it with the given divert.
///
/// When a choice body ends with a `ChoiceSet`, its gather container may
/// itself end with another `ChoiceSet` (multi-level weaves). The divert
/// to the outer gather must be placed in the innermost gather that
/// doesn't end with yet another `ChoiceSet`, otherwise it becomes dead
/// code after the `done` emitted by codegen for the `ChoiceSet`.
fn patch_innermost_gather(children: &mut [lir::Container], divert: lir::Divert) {
    let Some(gather) = children
        .last_mut()
        .filter(|c| c.kind == lir::ContainerKind::Gather)
    else {
        return;
    };

    let gather_body_ends_with_choice_set = gather
        .body
        .last()
        .is_some_and(|s| matches!(&s.kind, lir::StmtKind::ChoiceSet(_)));

    if gather_body_ends_with_choice_set {
        // Recurse into the gather's children to find the deeper gather
        patch_innermost_gather(&mut gather.children, divert);
        return;
    }

    let gather_body_ends_terminal = gather.body.last().is_some_and(|s| {
        matches!(
            &s.kind,
            lir::StmtKind::Divert(d)
                if matches!(
                    d.target,
                    lir::DivertTarget::End
                        | lir::DivertTarget::Done
                        | lir::DivertTarget::Address(_)
                )
        )
    });

    // A gather that already transfers control keeps its own terminator:
    // an authored `-> target` / `-> END` / `-> DONE` at the end of a nested
    // gather is that gather's exit, not a placeholder for the outer one
    // (issue #3383 — replacing it silently dropped the divert). The only
    // synthesized terminator a continuation can carry is the exit
    // `build_continuation_container` emits for an *empty* root-content
    // continuation, and that one already targets the enclosing gather.
    if gather_body_ends_terminal {
        return;
    }
    // Same no-`LowerCtx`-here rationale as `patch_root_loose_end`: inherit
    // the gather's own provenance.
    let provenance = gather.provenance;
    gather
        .body
        .push(lir::Stmt::new(lir::StmtKind::Divert(divert), provenance));
}