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
//! T1b `~ { … }` block/loop/indexed-assignment lowering
//! (`docs/t1b-surface-spec.md` §2, §4).
//!
//! Block bodies are pure logic — no weave concepts (content, choices,
//! diverts, gathers, threads) ever appear in `hir::BlockStmt`, enforced by
//! construction in the HIR shape (§2's seam rule) — so every construct here
//! lowers to a **flat** `lir::Stmt` sequence within the enclosing
//! container's own body. No child containers are ever created:
//!
//! - `if`/`else if`/`else` reuse `lir::Conditional` (`CondKind::IfElse`) —
//!   the exact same shape a weave multiline conditional's branches use,
//!   minus the container wrapping weave conditionals need for choice
//!   isolation (block bodies never contain choices).
//! - `while` lowers to `lir::LogicWhile`, compiled by the bytecode backend
//!   to a flat backward-jump loop in the same container.
//! - `for x in arr` / `for k in map` desugars entirely to a `LogicWhile`
//!   (index-based iteration over `CollectionKeys(iterable)` — see that
//!   opcode's doc for why one opcode covers both cases) with the index
//!   increment in `LogicWhile::post` so `continue` still advances the loop.
//! - Indexed assignment (`a[i] = v`, chained `grid[y][x] = v`) desugars to
//!   the ratified RMW discipline exactly: take → `make_mut` → write-back on
//!   the root cell, chains as nested RMW via synthetic temps — never
//!   interior references. Every sub-expression (root, each index, the
//!   value) is evaluated exactly once, in source order.
//!
//! Block-scoped `temp` declarations (including `for` loop variables and the
//! synthetic temps this module allocates for desugaring) get fresh slots via
//! [`LowerCtx::alloc_block_slot`] and are visible only within their
//! `push_block_scope`/`pop_block_scope` bracket — shadowing an
//! already-visible temp (an outer classic `~ temp` or an enclosing block's
//! temp) is legal but produces an E054 warning (§2).

use crate::hir;
use crate::symbols::SymbolKind;
use crate::{AssignOp, Diagnostic, DiagnosticCode, InfixOp};

use super::context::LowerCtx;
use super::context::TypeMode;
use super::context::UfcsVerdict;
use super::expr::lower_expr;
use super::lir;

/// Lower a `~ { … }` block's statements into the enclosing body's flat
/// statement sequence, honoring [`hir::LogicBlock::scope`] — almost always
/// [`hir::LogicBlockScope::Standalone`] (push a new T1b lexical scope for
/// the block's own `temp` declarations on entry, pop it on return), except
/// when a code-ground body's `> text` prose-line escape has split it into
/// several sibling `LogicBlock`s (issue #1992 review finding F1,
/// `hir::lower_native::body::mark_split_logic_block_scopes`'s doc): those
/// siblings share one scope, so only the first (`Opens`) pushes; a
/// `Continues` sibling neither pushes nor pops. **Neither `Opens` nor
/// `Continues` pops here** — the matching pop is the enclosing block's
/// responsibility ([`super::lower_block_with_children`]), since a
/// `Stmt::Content` sibling produced by a trailing `> text` line can
/// legally come after the last split run and still needs the scope open.
pub(super) fn lower_logic_block(lb: &hir::LogicBlock, ctx: &mut LowerCtx<'_>) -> Vec<lir::Stmt> {
    use hir::LogicBlockScope as Scope;
    match lb.scope {
        Scope::Standalone => {
            ctx.push_block_scope();
            let out = lower_block_stmt_list(&lb.stmts, ctx);
            ctx.pop_block_scope();
            out
        }
        Scope::Opens => {
            ctx.push_block_scope();
            lower_block_stmt_list(&lb.stmts, ctx)
        }
        Scope::Continues => lower_block_stmt_list(&lb.stmts, ctx),
    }
}

pub(super) fn lower_block_stmt_list(
    stmts: &[hir::BlockStmt],
    ctx: &mut LowerCtx<'_>,
) -> Vec<lir::Stmt> {
    let mut out = Vec::new();
    for stmt in stmts {
        lower_block_stmt(stmt, ctx, &mut out);
    }
    out
}

/// Best-known provenance for a T1b `~ { … }` block statement (issue #3183)
/// — mirrors [`super::stmts::stmt_provenance`] for `hir::BlockStmt`. Every
/// payload but `Return` (`Option<Provenance>`, synthesized-node caveat same
/// as the classic-line `Return`) and `ExprStmt` (no `.ptr` of its own —
/// [`crate::hir::expr_span`], ambient fallback) carries a real `Provenance`.
fn block_stmt_provenance(stmt: &hir::BlockStmt, ctx: &LowerCtx<'_>) -> crate::Provenance {
    match stmt {
        hir::BlockStmt::TempDecl(decl) => decl.ptr,
        hir::BlockStmt::Assignment(assign) => assign.ptr,
        hir::BlockStmt::Return(ret) => ret.ptr.unwrap_or(ctx.current_stmt_provenance),
        hir::BlockStmt::If(if_stmt) => if_stmt.ptr,
        hir::BlockStmt::While(w) => w.ptr,
        hir::BlockStmt::For(f) => f.ptr,
        hir::BlockStmt::Break(ptr) | hir::BlockStmt::Continue(ptr) => *ptr,
        hir::BlockStmt::ExprStmt(e) => crate::hir::expr_span(e)
            .map_or(ctx.current_stmt_provenance, |r| {
                ctx.provenance_at(r, crate::NodeClass::Expr)
            }),
        hir::BlockStmt::Await(a) => a.ptr,
    }
}

fn lower_block_stmt(stmt: &hir::BlockStmt, ctx: &mut LowerCtx<'_>, out: &mut Vec<lir::Stmt>) {
    let provenance = ctx.enter_stmt(block_stmt_provenance(stmt, ctx));
    match stmt {
        hir::BlockStmt::TempDecl(decl) => lower_block_temp_decl(decl, ctx, out),
        hir::BlockStmt::Assignment(assign) => lower_block_assignment(assign, ctx, out),
        hir::BlockStmt::Return(ret) => {
            let value = ret.value.as_ref().map(|e| lower_expr(e, ctx));
            out.push(lir::Stmt::new(
                lir::StmtKind::Return {
                    value,
                    is_tunnel: ret.kind == hir::ReturnKind::TunnelRedirect,
                    args: Vec::new(),
                },
                provenance,
            ));
        }
        hir::BlockStmt::If(if_stmt) => {
            let mut branches = Vec::new();
            lower_if_branch(if_stmt, ctx, &mut branches);
            out.push(lir::Stmt::new(
                lir::StmtKind::Conditional(lir::Conditional {
                    kind: lir::CondKind::IfElse,
                    branches,
                }),
                provenance,
            ));
        }
        hir::BlockStmt::While(w) => {
            // `while await cond { … }` (docs/flow-suspension-spec.md §3): the
            // persistent-await loop is a suspension point, fenced at lowering
            // (E052) exactly like a bare `await` until FS-3. A plain `while`
            // loop lowers as usual.
            if w.is_await {
                super::stmts::emit_await_lowering_fence(ctx, w.ptr.text_range());
                return;
            }
            // Same bracket shape as `lower_if_branch`: the scope opens
            // before the condition so an `as` binding declares into it.
            // `LogicWhile` re-evaluates `condition` each pass, so the
            // binding rebinds per iteration with no extra machinery (B1b,
            // issue #1475).
            ctx.push_block_scope();
            let condition = match &w.binding {
                Some(binding) => lower_bound_condition(&w.condition, binding, ctx),
                None => lower_expr(&w.condition, ctx),
            };
            ctx.loop_depth += 1;
            let body = lower_block_stmt_list(&w.body, ctx);
            ctx.loop_depth -= 1;
            ctx.pop_block_scope();
            out.push(lir::Stmt::new(
                lir::StmtKind::LogicWhile(lir::LogicWhile {
                    condition,
                    body,
                    post: Vec::new(),
                }),
                provenance,
            ));
        }
        hir::BlockStmt::For(f) => lower_for_stmt(f, ctx, out),
        hir::BlockStmt::Break(ptr) => {
            lower_loop_control(ptr, "break", lir::StmtKind::LogicBreak, ctx, out);
        }
        hir::BlockStmt::Continue(ptr) => {
            lower_loop_control(ptr, "continue", lir::StmtKind::LogicContinue, ctx, out);
        }
        hir::BlockStmt::ExprStmt(expr) => {
            if !try_lower_postfix_stmt(expr, ctx, out)
                && !try_lower_mutator_stmt(expr, ctx, out)
                && !try_lower_frame_local_auto_ref_stmt(expr, ctx, out)
            {
                out.push(lir::Stmt::new(
                    lir::StmtKind::ExprStmt(lower_expr(expr, ctx)),
                    provenance,
                ));
            }
        }
        // `await <cond>` inside a `~ { … }` block (docs/flow-suspension-spec.md
        // §3) — fenced at lowering (E052) until FS-3, same as the top-level
        // `~ await` and `while await` forms.
        hir::BlockStmt::Await(a) => {
            super::stmts::emit_await_lowering_fence(ctx, a.ptr.text_range());
        }
    }
}

/// Lower a `break`/`continue` statement, rejecting it with E057 when it's
/// not nested inside any `while`/`for` loop (`ctx.loop_depth == 0`) instead
/// of emitting an unguarded `LogicBreak`/`LogicContinue` — codegen's
/// `loop_stack` has no jump target for one and previously degraded it to a
/// silent `Nop` (#577 review). The malformed statement is skipped (not
/// pushed to `out`), matching how an unresolvable assignment target is
/// already skipped elsewhere in this module — the diagnostic is what
/// surfaces this to authors, and it's Error-severity (unlike the E054
/// shadow warning above), so `brink-db`'s `lir_query` refuses to hand back
/// a `Program` at all, independent of and non-suppressible relative to any
/// analysis-phase diagnostic covering the same construct.
fn lower_loop_control(
    ptr: &crate::Provenance,
    keyword: &str,
    kind: lir::StmtKind,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    if ctx.loop_depth == 0 {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range: ptr.text_range(),
            message: format!(
                "{}: `{keyword}` used outside any enclosing while/for loop",
                DiagnosticCode::E057.title(),
            ),
            code: DiagnosticCode::E057,
        });
        return;
    }
    out.push(lir::Stmt::new(kind, *ptr));
}

fn lower_if_branch(
    if_stmt: &hir::IfStmt,
    ctx: &mut LowerCtx<'_>,
    branches: &mut Vec<lir::CondBranch>,
) {
    // The scope opens BEFORE the condition so an `as` binding (B1b, issue
    // #1475) can declare into it; it closes after the success arm, which is
    // exactly the binding's ruled scope — the `else`/`else if` arms below
    // are lowered outside the bracket and never see the name.
    ctx.push_block_scope();
    let condition = Some(match &if_stmt.binding {
        Some(binding) => lower_bound_condition(&if_stmt.condition, binding, ctx),
        None => lower_expr(&if_stmt.condition, ctx),
    });
    let body = lower_block_stmt_list(&if_stmt.body, ctx);
    ctx.pop_block_scope();
    branches.push(lir::CondBranch { condition, body });

    match &if_stmt.else_branch {
        Some(hir::ElseBranch::ElseIf(inner)) => lower_if_branch(inner, ctx, branches),
        Some(hir::ElseBranch::Else(else_body)) => {
            ctx.push_block_scope();
            let body = lower_block_stmt_list(else_body, ctx);
            ctx.pop_block_scope();
            branches.push(lir::CondBranch {
                condition: None,
                body,
            });
        }
        None => {}
    }
}

/// Lower a condition that carries an `as` binding (B1b, issue #1475) into
/// the `OptionBind` condition expression, with the binding's scope already
/// open.
///
/// The caller **must** be inside its own `push_block_scope` bracket when it
/// calls this and must pop it after lowering the success arm — that bracket
/// IS the "scoped strictly to the success arm" rule (an `else`/`else if`
/// arm is lowered outside it, so the name is invisible there).
///
/// The binding shares `declare_shadow_checked`'s slot allocation and E054
/// shadow warning with an ordinary block `let`: an `as` binding is a
/// block-scoped immutable local, so shadowing an outer temp is legal and
/// warned about in exactly the same way.
pub(super) fn lower_bound_condition(
    condition: &hir::Expr,
    binding: &crate::Name,
    ctx: &mut LowerCtx<'_>,
) -> lir::Expr {
    // The condition is evaluated before the name becomes visible, so
    // `if find(s) as s { … }` reads the OUTER `s` in its own condition —
    // the same rule `lower_block_temp_decl` applies to `let x = x`.
    let value = lower_expr(condition, ctx);
    let (slot, name) = declare_shadow_checked(&binding.text, binding.range, ctx);
    // The binding is immutable by ruling — record the slot so every write
    // path refuses it (`stmts::lower_assign_target`, E148).
    ctx.as_binding_slots.insert(slot);
    lir::ExprKind::OptionBind {
        value: Box::new(value),
        slot,
        name,
    }
    .at(ctx.current_stmt_provenance)
}

/// Declare a block-scoped `temp`, emitting the E054 shadow warning if `name`
/// is already visible (an outer classic temp/param or an enclosing block
/// scope). Returns the allocated slot and interned name.
fn declare_shadow_checked(
    name: &str,
    range: rowan::TextRange,
    ctx: &mut LowerCtx<'_>,
) -> (u16, brink_format::NameId) {
    if ctx.is_name_visible(name) {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range,
            message: format!(
                "`{name}` shadows an already-visible temp — block-scoped `temp` \
                 declarations may shadow outer temps (docs/t1b-surface-spec.md §2), \
                 but double-check this is intentional"
            ),
            code: DiagnosticCode::E054,
        });
    }
    let slot = ctx.alloc_block_slot();
    let name_id = ctx.names.intern(name);
    ctx.declare_block_local(name.to_string(), slot);
    (slot, name_id)
}

fn lower_block_temp_decl(decl: &hir::TempDecl, ctx: &mut LowerCtx<'_>, out: &mut Vec<lir::Stmt>) {
    // Evaluate the initializer BEFORE the new name becomes visible — matches
    // classic (non-block) `TempDecl` lowering, so `temp x = x` reads the
    // outer `x`, not itself.
    let value = decl.value.as_ref().map(|e| lower_expr(e, ctx));
    let (slot, name) = declare_shadow_checked(&decl.name.text, decl.name.range, ctx);
    ctx.record_temp_annotation(slot, decl.annotation.as_ref());
    out.push(lir::Stmt::new(
        lir::StmtKind::DeclareTemp {
            slot,
            name,
            value,
            synthetic: decl.synthetic,
        },
        ctx.current_stmt_provenance,
    ));
}

fn lower_block_assignment(
    assign: &hir::Assignment,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    if try_lower_field_assignment(assign, ctx, out) {
        return;
    }
    if let hir::Expr::Index(idx) = &assign.target {
        lower_indexed_assignment(idx, assign.op, &assign.value, ctx, out);
        return;
    }
    // Plain variable target — `LowerCtx::temp_slot` (used internally by
    // `lower_assign_target`) already checks open T1b block scopes first, so
    // this correctly resolves a block-scoped-shadowed name to its own slot.
    if let Some(target) = super::stmts::lower_assign_target(&assign.target, ctx) {
        let value = lower_expr(&assign.value, ctx);
        out.push(lir::Stmt::new(
            lir::StmtKind::Assign {
                target,
                op: assign.op,
                value,
            },
            ctx.current_stmt_provenance,
        ));
    }
    // An unresolvable target (e.g. a genuinely undeclared name) silently
    // drops the statement — the same behavior classic `~ x = …` assignment
    // lowering already has (`lower_stmt`'s `Assignment` arm); the analyzer's
    // E025 unresolved-variable diagnostic is what surfaces this to authors,
    // not LIR lowering.
}

/// Attempt to lower `assign` as a TM-4c struct field write (`p.field =
/// expr`/`p.field op= expr`, `docs/typed-mode-spec.md` §6) — single level
/// only, mirroring [`lower_indexed_assignment`]'s `n == 1` fast path (take →
/// `make_mut` → write-back on the root cell). Returns `false` (nothing
/// lowered or diagnosed) when `assign.target` isn't this shape at all, so
/// the caller falls through to ordinary assignment/indexed-assignment
/// handling.
///
/// A bare `ident.ident` (or longer) chain always parses as one multi-segment
/// `hir::Expr::Path` (see `expr::lower_ambiguous_dotted_path`'s doc) — that
/// is the *only* shape a genuine `p.field = v` target ever takes. A
/// **chained** write (`p.a.b = v`, 3+ segments) or a **mixed** chain
/// (`arr[i].field = v`/`foo().field = v`, the "unambiguous" `FieldAccessExpr`
/// target grammar, whose base is never a plain `Path`) is recognized here
/// too, but rejected with a real, non-suppressible `E074` diagnostic (the
/// T1e boundary the issue fences off) rather than silently miscompiled —
/// this still returns `true` (handled: the diagnostic *is* the handling),
/// so the caller doesn't fall through to a different lowering path that
/// might mishandle the same target shape.
pub(super) fn try_lower_field_assignment(
    assign: &hir::Assignment,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    if let hir::Expr::Path(path) = &assign.target
        && path.segments.len() > 1
        && let Some(info) = ctx.resolve_path(path.range)
        && matches!(
            info.kind,
            SymbolKind::Variable | SymbolKind::Constant | SymbolKind::Param | SymbolKind::Temp
        )
    {
        if path.segments.len() > 2 {
            emit_chained_field_write_diagnostic(path.range, ctx);
        } else {
            lower_single_level_field_write(path, info, assign.op, &assign.value, ctx, out);
        }
        return true;
    }

    if let hir::Expr::FieldAccess(fa) = &assign.target {
        emit_chained_field_write_diagnostic(fa.ptr.text_range(), ctx);
        return true;
    }

    false
}

/// Issue #2174 — the classic-line remainder of #2121/PR #2171.
///
/// `lower_block_assignment` (the `~ { … }` T1b block surface, just below)
/// dispatches an `Index` assignment target straight to
/// [`lower_indexed_assignment`] — which is where
/// [`reject_field_projection_index_root`]'s guard lives. But the
/// classic-line (non-block) statement dispatch (`mod.rs`'s `hir::Stmt`
/// match) only ever tried [`try_lower_field_assignment`]'s `Path`/
/// `FieldAccess` targets before falling through to `stmts::lower_stmt`,
/// whose own `lower_assign_target` recognizes only a bare `Path` — an
/// `Index` target (`a[i] = v`) fell through its `_ => None` arm and
/// **silently dropped the whole statement**, with no diagnostic at all.
///
/// This isn't only the field-projected-root shape (`a.items[0] = v`) #2121
/// fixed for the block surface — reproduced against a real compile+run
/// (rule 20a): even the *bare-variable* classic-line spelling (`~ a[0] =
/// 99`, `a: Array<int>`, no struct involved) compiled clean and the write
/// never happened, because the classic-line dispatch never reached
/// `lower_indexed_assignment` at all, for any `Index` target.
///
/// Factored out here (mirroring `try_lower_field_assignment`'s guard-arm
/// shape) so both surfaces share the exact same call into
/// `lower_indexed_assignment`, instead of the classic-line dispatch growing
/// a second, divergent copy: a bare-variable root now lowers correctly, and
/// a struct-field-projected root gets the identical non-suppressible
/// `E074` the block form already raises via
/// `reject_field_projection_index_root`.
pub(super) fn try_lower_indexed_assignment(
    assign: &hir::Assignment,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    let hir::Expr::Index(idx) = &assign.target else {
        return false;
    };
    lower_indexed_assignment(idx, assign.op, &assign.value, ctx, out);
    true
}

fn emit_chained_field_write_diagnostic(range: rowan::TextRange, ctx: &mut LowerCtx<'_>) {
    emit_field_projection_refusal(range, ctx, DiagnosticCode::E074.title());
}

/// Issue #2185 refusal message for a mutator whose receiver argument is a
/// record-field projection (`pop(a.items)`, `heap_pop(a.items)`) — same
/// non-suppressible `E074`, accurate shape name (these are not chained field
/// *writes*, so `E074.title()`'s "(p.a.b = v)" wording would misdescribe
/// them).
pub(super) const FIELD_PROJECTION_MUTATOR_ARG: &str = "field-projection mutator argument (`pop(a.items)`) is not supported — copy the field into a \
     temp, mutate it, and write it back";

/// Issue #2185 refusal message for a postfix `++`/`--` whose target is a
/// record-field projection (`~ a.count++`).
pub(super) const FIELD_PROJECTION_POSTFIX_TARGET: &str = "field-projection increment/decrement target (`a.count++`) is not supported — copy the field \
     into a temp, mutate it, and write it back";

/// Issue #2185 refusal message for the classic-ink *implicit*-by-ref calling
/// convention handing a record-field projection to a `ref` parameter
/// (`f(a.items)` with no `ref` keyword at the call site). Unlike the other
/// two shapes there is a fully supported spelling: the explicit T1e
/// projection argument (`f(ref a.items)`), which lowers through
/// `expr::lower_ref_projection_arg` to a real [`lir::CallArg::RefProjection`]
/// — the message points there.
pub(super) const FIELD_PROJECTION_IMPLICIT_REF_ARG: &str = "field-projection argument to a `ref` parameter (`f(a.items)`) is not supported without an \
     explicit `ref` — write `f(ref a.items)` to pass a real projection";

/// [`emit_chained_field_write_diagnostic`] with a caller-supplied message —
/// the issue #2185 refusal sites (`pop`/`heap_pop` arguments, postfix
/// `++`/`--` targets, implicit-`ref` call arguments) reject shapes that are
/// *not* chained field writes, so `E074.title()`'s "(p.a.b = v)" wording
/// would misdescribe them. Same non-suppressible `E074` code either way —
/// only the message text names the actual refused shape.
fn emit_field_projection_refusal(range: rowan::TextRange, ctx: &mut LowerCtx<'_>, message: &str) {
    ctx.diagnostics.push(Diagnostic {
        file: ctx.file,
        range,
        message: message.to_string(),
        code: DiagnosticCode::E074,
    });
}

/// Issue #2121 — the "one level down" remainder of #1495/PR #2106's fix.
/// `push(a.items[0], v)` and `a.items[0] = v` reach
/// [`lower_indexed_assignment`]/[`lower_lvalue_container_chain`] with an
/// `Index` lvalue whose *root* (after [`flatten_index_chain`] unwinds the
/// index chain) is still a raw multi-segment `hir::Expr::Path` — `a.items`
/// parses as one `Path` (never `hir::Expr::FieldAccess`, same TM-4b shape
/// [`try_lower_field_assignment`]'s doc describes), and PR #2106 only taught
/// the *bare* Path-lvalue dispatch (`lower_mutator_call`'s own `if let
/// hir::Expr::Path` arm) and `try_lower_field_assignment` to split on
/// `segments.len() > 1` — neither of those call sites is on this Index-root
/// path, so `super::stmts::lower_assign_target` still resolves the whole
/// `a.items` range down to the **root** symbol `a` (a `Record`), routing the
/// write onto `a` itself instead of `a.items` (the `Array`) — reproduced
/// against a real compile+run: compiles clean (no diagnostic) and faults at
/// runtime with `NotIndexable("record")`, the identical silent-misroute
/// symptom #1495's own repro had.
///
/// Rejected here with the same non-suppressible `E074`
/// `try_lower_field_assignment`/`lower_mutator_call` already raise for a
/// chained field *write*/*mutator*, mirroring that fix's shape exactly
/// rather than inventing a second approach: a correct lowering here would
/// need to route the index op through the field's `RecordGet`/`RecordSet`
/// take-then-write-back discipline first (there is no `AssignTarget` shape
/// for "a field of a record" today), which is exactly the general
/// lvalue-resolution extension the issue asks to avoid unless it's the only
/// option — a targeted hard-reject closes the silent-misroute hole without
/// it.
///
/// Also catches the one-level-deeper variant of the same hole (review
/// finding on #2171): an index chain whose root is not a bare `Path` at all
/// but a `hir::Expr::FieldAccess` — `arr[0].items[1] = v`/`push(arr[0].items,
/// v)`, the #674 grammar's Index-then-field target with one more trailing
/// index. `flatten_index_chain` stops unwinding as soon as it hits a
/// non-`Index` base, so this root reaches here as a `FieldAccess` node, not
/// a `Path` — the `Path` arm above never matches it, and without this arm it
/// fell through to `lower_assign_target`, silently resolving to whatever
/// root symbol the `FieldAccess`'s own base resolves to. Mirrors
/// `try_lower_field_assignment`'s existing `hir::Expr::FieldAccess` arm
/// exactly (same diagnostic, same non-suppressible `E074`).
///
/// Returns `true` (diagnosed, caller must stop and lower nothing) when
/// `root_expr` is either of these shapes — a multi-segment `Path` that
/// resolves to an assignable root (`Variable`/`Constant`/`Param`/`Temp`), or
/// a `FieldAccess`; `false` otherwise (a bare single-segment `Path`, or one
/// that doesn't resolve to an assignable root at all — the analyzer's
/// `E025` handles that case, same as every other call site in this module).
///
/// `pub(super)` (issue #2185): `pop`/`heap_pop` (`expr.rs`) and the postfix
/// `++`/`--` desugar (`stmts.rs`) are the "one level up" siblings of the
/// hole this guard already closes for the container-chain
/// (`push`/`insert`/`remove`/…) and classic-line-Index mutators — they call
/// `super::stmts::lower_assign_target` directly on the raw, possibly
/// multi-segment `Path` argument instead of going through
/// `lower_lvalue_container_chain`/`lower_indexed_assignment`, so this guard
/// never ran for them at all. Reused here rather than duplicated, so every
/// call site raises the identical non-suppressible `E074` — those sites pass
/// their own `message` because their refused shape is a mutation *argument*/
/// *target*, not the chained field *write* `E074.title()` describes; the
/// pre-existing index-root sites pass `None` to keep the title verbatim.
pub(super) fn reject_field_projection_index_root(
    root_expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    message: Option<&str>,
) -> bool {
    if let hir::Expr::Path(path) = root_expr
        && reject_field_projection_path(path, ctx, message)
    {
        return true;
    }
    if let hir::Expr::FieldAccess(fa) = root_expr {
        emit_field_projection_refusal(
            fa.ptr.text_range(),
            ctx,
            message.unwrap_or_else(|| DiagnosticCode::E074.title()),
        );
        return true;
    }
    false
}

/// The `hir::Path`-only half of [`reject_field_projection_index_root`],
/// factored out for issue #2185's third call site
/// (`expr::lower_ref_path_call_arg`, the classic-ink *implicit*-by-ref
/// calling convention) — that site only ever holds a `&hir::Path` (the
/// callee's argument list gives it the path's inner data, not an enclosing
/// `hir::Expr::Path` node to match against), so it cannot call the
/// `&hir::Expr`-shaped function above without an avoidable clone. Same
/// check, same diagnostic, no duplicated logic.
pub(super) fn reject_field_projection_path(
    path: &hir::Path,
    ctx: &mut LowerCtx<'_>,
    message: Option<&str>,
) -> bool {
    if path.segments.len() > 1
        && let Some(info) = ctx.resolve_path(path.range)
        && matches!(
            info.kind,
            SymbolKind::Variable | SymbolKind::Constant | SymbolKind::Param | SymbolKind::Temp
        )
    {
        emit_field_projection_refusal(
            path.range,
            ctx,
            message.unwrap_or_else(|| DiagnosticCode::E074.title()),
        );
        return true;
    }
    false
}

/// The single-level case (`path.segments.len() == 2`) — `p.field = v`/`p.field
/// op= v` on a resolvable root. Follows the identical take → `make_mut` →
/// write-back RMW discipline [`lower_flat_indexed_assignment`] uses,
/// substituting a `RecordGet`/`RecordSet` field op for that function's
/// `Index`/`IndexSet`: the RHS is evaluated once (root still intact), then
/// `current = root.field` is *always* computed via a non-taking read (the
/// fault pre-check — see `lower_flat_indexed_assignment`'s doc for why this
/// matters: it forces the exact same missing-field validation the mutate
/// step would hit, before the root is ever taken, so a fault never leaves
/// the root holding `Value::Null`), then the root is taken and mutated in
/// place.
fn lower_single_level_field_write(
    path: &hir::Path,
    head_info: &crate::symbols::SymbolInfo,
    op: AssignOp,
    value_expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    #[expect(
        clippy::indexing_slicing,
        reason = "caller already proved path.segments.len() == 2"
    )]
    let field_name = path.segments[1].text.clone();
    #[expect(
        clippy::indexing_slicing,
        reason = "caller already proved path.segments.len() == 2"
    )]
    let head_name = path.segments[0].text.clone();

    let (root_target, root_shape) = match head_info.kind {
        SymbolKind::Variable | SymbolKind::Constant => {
            // Issue #2201: `CONST c = ...; ~ { c.field = v }` — `c`'s root
            // is a `CONST`. This root-cell resolution never goes through
            // `stmts::lower_assign_target` (see that function's own header
            // doc), so the E187 refusal that guards every *other* write
            // path doesn't apply here without its own call; see
            // `stmts::reject_const_write`'s doc for why that shared helper
            // is the right fix, mirroring `reject_as_binding_write` below.
            if super::stmts::reject_const_write(head_info, path.range, ctx) {
                return;
            }
            (
                lir::AssignTarget::Global(head_info.id),
                ctx.global_shape(head_info.id),
            )
        }
        SymbolKind::Param | SymbolKind::Temp => {
            let Some(slot) = ctx.temp_slot(&head_name) else {
                return;
            };
            // Issue #2122: `if get(bag) as b { b.field = v }` — `b`'s slot
            // is an immutable `as` binding. This root-cell resolution
            // never went through `stmts::lower_assign_target` (see this
            // function's own header doc), so the E148 refusal that guards
            // every *other* write path silently didn't apply here; see
            // `stmts::reject_as_binding_write`'s doc for why that shared
            // helper — not a direct call to `lower_assign_target` — is the
            // right fix.
            if super::stmts::reject_as_binding_write(slot, &head_name, path.range, ctx) {
                return;
            }
            let name_id = ctx.names.intern(&head_name);
            (lir::AssignTarget::Temp(slot, name_id), ctx.temp_shape(slot))
        }
        // `try_lower_field_assignment` only reaches here for these four kinds.
        _ => return,
    };

    // `root_shape` is already a resolved shape `DefinitionId` (issue
    // #2238) — no referrer needed to look it up.
    let static_offset = if ctx.structs.type_mode == TypeMode::Strict {
        root_shape
            .and_then(|d| ctx.structs.shapes.get_by_def(d))
            .and_then(|shape| shape.field(&field_name))
            .map(|(offset, _)| offset)
    } else {
        None
    };
    let field = ctx.names.intern(&field_name);

    // 1. RHS value, evaluated once — root still intact (mirrors
    //    `lower_flat_indexed_assignment` step 2).
    let rhs_value = lower_expr(value_expr, ctx);
    let (rhs_slot, rhs_name) = declare_synthetic("__rhs", rhs_value, ctx, out);

    // 2. Pre-mutation `current = root.field`, ALWAYS computed (fault
    //    pre-check + compound assignment's operand), via an ordinary
    //    (non-taking) read of the still-intact root.
    let current = lir::ExprKind::RecordGet {
        base: Box::new(get_expr_for_target(
            &root_target,
            ctx.current_stmt_provenance,
        )),
        field,
        static_offset,
    }
    .at(ctx.current_stmt_provenance);
    let (current_slot, current_name) = declare_synthetic("__current", current, ctx, out);

    let rhs = if op == AssignOp::Set {
        lir::ExprKind::GetTemp(rhs_slot, rhs_name).at(ctx.current_stmt_provenance)
    } else {
        // `op == AssignOp::Set` is excluded above, so only `Add`/`Sub` ever
        // reach here.
        let infix_op = if op == AssignOp::Sub {
            InfixOp::Sub
        } else {
            InfixOp::Add
        };
        lir::ExprKind::Infix(
            Box::new(
                lir::ExprKind::GetTemp(current_slot, current_name).at(ctx.current_stmt_provenance),
            ),
            infix_op,
            Box::new(lir::ExprKind::GetTemp(rhs_slot, rhs_name).at(ctx.current_stmt_provenance)),
        )
        .at(ctx.current_stmt_provenance)
    };

    // 3. Take the root — step 2 already proved this exact field is valid
    //    against this exact record value (nothing mutated in between), so
    //    nothing from here on can fault; the root is never left holding
    //    `Value::Null` on this path.
    let (c_slot, c_name) = declare_synthetic(
        "__c",
        take_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    );
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(c_slot, c_name),
            op: AssignOp::Set,
            value: lir::ExprKind::RecordSet {
                base: Box::new(
                    lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
                ),
                field,
                static_offset,
                value: Box::new(rhs),
            }
            .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));

    // 4. Write the mutated record back into the root — takes the (now
    //    dead) synthetic temp too, avoiding one final wasted `Arc` clone.
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
}

/// Unwind a (possibly chained) `IndexExpr` into its root expression and the
/// index expressions in left-to-right (written) order — e.g. `grid[y][x]`
/// unwinds to `(Path(grid), [y, x])`.
fn flatten_index_chain(idx: &hir::IndexExpr) -> (&hir::Expr, Vec<&hir::Expr>) {
    let mut indices_outer_first: Vec<&hir::Expr> = vec![&idx.index];
    let mut cur_base = idx.base.as_ref();
    while let hir::Expr::Index(inner) = cur_base {
        indices_outer_first.push(&inner.index);
        cur_base = inner.base.as_ref();
    }
    indices_outer_first.reverse();
    (cur_base, indices_outer_first)
}

fn get_expr_for_target(target: &lir::AssignTarget, provenance: crate::Provenance) -> lir::Expr {
    match target {
        lir::AssignTarget::Global(id) => lir::ExprKind::GetGlobal(*id).at(provenance),
        lir::AssignTarget::Temp(slot, name) => lir::ExprKind::GetTemp(*slot, *name).at(provenance),
    }
}

/// `get_expr_for_target`'s move-semantics counterpart (issue #576,
/// `docs/value-model-spec.md` §5): moves the target's current value out,
/// leaving `Value::Null` behind, instead of cloning (`Arc`-bumping) it.
/// Only safe to use where nothing else needs `target`'s old value again
/// before it's written back — see [`lower_flat_indexed_assignment`] and
/// [`lower_bare_mutator`], the two call sites that establish this.
fn take_expr_for_target(target: &lir::AssignTarget, provenance: crate::Provenance) -> lir::Expr {
    match target {
        lir::AssignTarget::Global(id) => lir::ExprKind::TakeGlobal(*id).at(provenance),
        lir::AssignTarget::Temp(slot, name) => lir::ExprKind::TakeTemp(*slot, *name).at(provenance),
    }
}

fn declare_synthetic(
    prefix: &str,
    value: lir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> (u16, brink_format::NameId) {
    let slot = ctx.alloc_block_slot();
    let name = ctx.names.intern(prefix);
    out.push(lir::Stmt::new(
        lir::StmtKind::DeclareTemp {
            slot,
            name,
            value: Some(value),
            synthetic: false,
        },
        ctx.current_stmt_provenance,
    ));
    (slot, name)
}

/// Lower `base[i0][i1]...[iN-1] OP= value` (§4). Follows the ratified RMW
/// discipline exactly: take → `make_mut` → write-back on the root cell;
/// chains lower to nested RMW via synthetic temps — never interior
/// references (no projections in T1b). Every sub-expression is evaluated
/// exactly once: the root once, each index left-to-right once, the value
/// once.
///
/// `n == 1` (`a[i] = v`/`a[i] op= v` on a bare variable — the loop-append
/// case value-model-spec §5's "one cliff" targets) dispatches to
/// [`lower_flat_indexed_assignment`], which closes the COW cliff via
/// `TakeGlobal`/`TakeTemp` (issue #576). `n > 1` (chained, e.g.
/// `grid[y][x] = v`) keeps the clone-based RMW below unchanged: a nested
/// container's element is necessarily read out via a structural clone
/// before it can be walked further (it's *still referenced from inside its
/// parent* until that parent's own write-back cascade completes), so a
/// take at any level but the root buys nothing there — this is the
/// sanctioned §7 fallback ("per-write path-walking RMW"), not a regression.
fn lower_indexed_assignment(
    idx: &hir::IndexExpr,
    op: AssignOp,
    value_expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    let (root_expr, indices_hir) = flatten_index_chain(idx);
    // Issue #2121: `a.items[0] = v` — the root of the index chain is itself
    // a struct-field projection (`a.items`, a multi-segment `Path`), not a
    // bare variable. See `reject_field_projection_index_root`'s doc for why
    // this must be checked *before* `lower_assign_target` gets a chance to
    // silently misroute it onto the root `a`.
    if reject_field_projection_index_root(root_expr, ctx, None) {
        return;
    }
    let Some(root_target) = super::stmts::lower_assign_target(root_expr, ctx) else {
        // Unresolvable root — same silent-skip discipline as plain
        // assignment (analyzer's E025 is the author-facing signal).
        return;
    };
    let n = indices_hir.len();
    if n == 0 {
        // Structurally unreachable (an `IndexExpr` always has an `index`),
        // guarded rather than asserted so a future grammar change can't
        // corrupt output instead of just doing nothing.
        return;
    }

    if n == 1 {
        #[expect(
            clippy::indexing_slicing,
            reason = "n == 1 just proved indices_hir has exactly one element"
        )]
        let index_hir = indices_hir[0];
        lower_flat_indexed_assignment(root_target, index_hir, op, value_expr, ctx, out);
        return;
    }

    lower_chained_indexed_assignment(root_target, &indices_hir, op, value_expr, ctx, out);
}

/// Fast path for `n == 1` (`a[i] = v`/`a[i] op= v`, `a` a bare variable):
/// closes the indexed-write COW cliff (issue #576, value-model-spec §5) by
/// using `TakeGlobal`/`TakeTemp` (move semantics — `docs/format-v4-rfc.md`
/// §3 "Sharing discipline") for the root read and the mutate step's
/// container operand, so `array_make_mut`/`map_make_mut` sees a unique
/// `Arc` (refcount 1) whenever nothing else aliases the container — O(1)
/// amortized in-place mutation instead of an O(n) COW copy on every write.
///
/// **Evaluation order** (correctness-critical): the index and the RHS value
/// are fully evaluated — via a non-taking, ordinary read of the still-intact
/// root — *before* the root is taken. This matters because either
/// expression may reference the root variable by name (e.g. `a[0] = a[1] +
/// 1`) and must see its pre-mutation value, not the `Value::Null` a take
/// would leave behind if it happened first.
///
/// **Compound assignment** (`+=`/`-=`) additionally computes the
/// pre-mutation `current = a[idx]` read (needed as the operand) *before*
/// the take, via the same non-taking `Index` read — unchanged by issue
/// #856. As a side effect this still catches out-of-bounds/missing-key/
/// non-collection faults before anything is taken, leaving the root
/// completely untouched on a compound-assign fault, exactly like the
/// pre-#576 clone-based RMW.
///
/// **Plain assignment** (`a[idx] = v`) does **not** compute `current` —
/// nothing needs its value, and (issue #856, ruled 2026-07-15) `IndexSet`'s
/// map branch is now insert-on-absent, so there's no missing-key fault left
/// to pre-empt there. The remaining fault causes on this path
/// (out-of-bounds array index, an invalid-domain map key, a non-collection
/// root) are still turn-terminating faults, but now surface *inside* the
/// take-based mutate step rather than before it, so the root can be left
/// `Value::Null` on one of those — the same documented, deliberate
/// no-precheck trade-off `fault_during_insert_leaves_root_null`/
/// `fault_during_remove_at_leaves_root_null` (runtime crate) already accept for
/// `insert`/`remove`/`remove_at`'s author-supplied keys ("a fault anywhere mid-turn
/// already leaves earlier same-turn mutations applied"). See
/// `fault_during_flat_index_assignment_leaves_root_null` (runtime crate,
/// renamed by #856 from `..._leaves_root_unchanged`) for the property test.
fn lower_flat_indexed_assignment(
    root_target: lir::AssignTarget,
    index_hir: &hir::Expr,
    op: AssignOp,
    value_expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    // 1. Index, evaluated once — root is still intact.
    let index_value = lower_expr(index_hir, ctx);
    let (idx_slot, idx_name) = declare_synthetic("__idx", index_value, ctx, out);

    // 2. RHS value, materialized into its own temp *before* the take (see
    //    doc above) — also still reading the intact root if it references
    //    it.
    let rhs_value = lower_expr(value_expr, ctx);
    let (rhs_slot, rhs_name) = declare_synthetic("__rhs", rhs_value, ctx, out);

    // 3. Compound assignment only (`+=`/`-=`): pre-mutation `current =
    //    a[idx]`, needed as the operand, via an ordinary (non-taking) read
    //    of the still-intact root. As a side effect this also validates the
    //    index/key before anything is taken (see doc above) — plain `=`
    //    skips this entirely (issue #856): it doesn't need `current`'s
    //    value, and `IndexSet`'s map branch no longer faults on a missing
    //    key, so there's nothing left to pre-empt for maps; the remaining
    //    fault causes (array OOB, invalid-domain map key, non-collection
    //    root) are still faults, just inside the take-based mutate step.
    let rhs = if op == AssignOp::Set {
        lir::ExprKind::GetTemp(rhs_slot, rhs_name).at(ctx.current_stmt_provenance)
    } else {
        let current = lir::ExprKind::Index {
            base: Box::new(get_expr_for_target(
                &root_target,
                ctx.current_stmt_provenance,
            )),
            index: Box::new(
                lir::ExprKind::GetTemp(idx_slot, idx_name).at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance);
        let (current_slot, current_name) = declare_synthetic("__current", current, ctx, out);
        // `op == AssignOp::Set` is excluded above, so only `Add`/`Sub`
        // ever reach here.
        let infix_op = if op == AssignOp::Sub {
            InfixOp::Sub
        } else {
            InfixOp::Add
        };
        lir::ExprKind::Infix(
            Box::new(
                lir::ExprKind::GetTemp(current_slot, current_name).at(ctx.current_stmt_provenance),
            ),
            infix_op,
            Box::new(lir::ExprKind::GetTemp(rhs_slot, rhs_name).at(ctx.current_stmt_provenance)),
        )
        .at(ctx.current_stmt_provenance)
    };

    // 4. Take the root. For compound assignment, step 3 already proved this
    //    exact index is valid against this exact container value (nothing
    //    mutated in between), so nothing from here on can fault; the root
    //    is never left `Value::Null` on that path. For plain `=`, step 5's
    //    `IndexSet` can still fault (array OOB, invalid-domain map key,
    //    non-collection root) — the documented, deliberate trade-off
    //    `fault_during_insert_leaves_root_null` already accepts for
    //    `insert`/`remove`/`remove_at`'s author-supplied keys applies here too.
    let (c_slot, c_name) = declare_synthetic(
        "__c",
        take_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    );

    // 5. Mutate in place: base is a *take* from `c_slot` too — `c_slot`'s
    //    old value is never read again (this statement's own result
    //    overwrites it), so by the time `array_make_mut`/`map_make_mut`
    //    runs, the only live reference to the container is the one this
    //    statement is about to consume — refcount 1 whenever nothing else
    //    aliases it.
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(c_slot, c_name),
            op: AssignOp::Set,
            value: lir::ExprKind::IndexSet {
                base: Box::new(
                    lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
                ),
                index: Box::new(
                    lir::ExprKind::GetTemp(idx_slot, idx_name).at(ctx.current_stmt_provenance),
                ),
                value: Box::new(rhs),
            }
            .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));

    // 6. Write the mutated container back into the root — takes the (now
    //    dead) synthetic temp too, avoiding one final wasted `Arc` clone.
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
}

/// `n > 1` (chained, e.g. `grid[y][x] = v`) — the pre-#576 clone-based RMW,
/// unchanged. See [`lower_indexed_assignment`]'s doc for why the take-based
/// optimization doesn't extend here.
fn lower_chained_indexed_assignment(
    root_target: lir::AssignTarget,
    indices_hir: &[&hir::Expr],
    op: AssignOp,
    value_expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    let n = indices_hir.len();
    // 1. Materialize every index value into its own temp, evaluated once,
    //    left to right, before any container read.
    let idx_slots: Vec<(u16, brink_format::NameId)> = indices_hir
        .iter()
        .map(|e| {
            let v = lower_expr(e, ctx);
            declare_synthetic("__idx", v, ctx, out)
        })
        .collect();

    // 2. Read the root container once, then walk down the chain reading
    //    each level once: c[0] = root; c[k+1] = c[k][idx[k]].
    let mut c_slots: Vec<(u16, brink_format::NameId)> = vec![declare_synthetic(
        "__c",
        get_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    )];
    for k in 0..n - 1 {
        let base =
            lir::ExprKind::GetTemp(c_slots[k].0, c_slots[k].1).at(ctx.current_stmt_provenance);
        let index =
            lir::ExprKind::GetTemp(idx_slots[k].0, idx_slots[k].1).at(ctx.current_stmt_provenance);
        let read = lir::ExprKind::Index {
            base: Box::new(base),
            index: Box::new(index),
        }
        .at(ctx.current_stmt_provenance);
        c_slots.push(declare_synthetic("__c", read, ctx, out));
    }

    // 3. Evaluate the RHS once.
    let mut rhs = lower_expr(value_expr, ctx);

    // 3b. Compound assignment (`+=`/`-=`): rhs = current OP rhs. `current`
    //     re-reads the target path via the already-materialized temps (no
    //     re-evaluation of the root/index expressions).
    if op != AssignOp::Set {
        let last_base = lir::ExprKind::GetTemp(c_slots[n - 1].0, c_slots[n - 1].1)
            .at(ctx.current_stmt_provenance);
        let last_index = lir::ExprKind::GetTemp(idx_slots[n - 1].0, idx_slots[n - 1].1)
            .at(ctx.current_stmt_provenance);
        let current = lir::ExprKind::Index {
            base: Box::new(last_base),
            index: Box::new(last_index),
        }
        .at(ctx.current_stmt_provenance);
        // `op == AssignOp::Set` is excluded by the guard above, so only
        // `Add`/`Sub` ever reach here.
        let infix_op = if op == AssignOp::Sub {
            InfixOp::Sub
        } else {
            InfixOp::Add
        };
        rhs = lir::ExprKind::Infix(Box::new(current), infix_op, Box::new(rhs))
            .at(ctx.current_stmt_provenance);
    }

    // 4. Mutate the deepest level in place: c[N-1] = IndexSet(c[N-1],
    //    idx[N-1], rhs). Turn-terminating fault on OOB/missing-key (§6).
    {
        let (slot, name) = c_slots[n - 1];
        let base = lir::ExprKind::GetTemp(slot, name).at(ctx.current_stmt_provenance);
        let index = lir::ExprKind::GetTemp(idx_slots[n - 1].0, idx_slots[n - 1].1)
            .at(ctx.current_stmt_provenance);
        out.push(lir::Stmt::new(
            lir::StmtKind::Assign {
                target: lir::AssignTarget::Temp(slot, name),
                op: AssignOp::Set,
                value: lir::ExprKind::IndexSet {
                    base: Box::new(base),
                    index: Box::new(index),
                    value: Box::new(rhs),
                }
                .at(ctx.current_stmt_provenance),
            },
            ctx.current_stmt_provenance,
        ));
    }

    // 5. Cascade the write-back upward: c[k] = IndexSet(c[k], idx[k],
    //    c[k+1]) for k = N-2 down to 0.
    for k in (0..n - 1).rev() {
        let (slot, name) = c_slots[k];
        let base = lir::ExprKind::GetTemp(slot, name).at(ctx.current_stmt_provenance);
        let index =
            lir::ExprKind::GetTemp(idx_slots[k].0, idx_slots[k].1).at(ctx.current_stmt_provenance);
        let inner = lir::ExprKind::GetTemp(c_slots[k + 1].0, c_slots[k + 1].1)
            .at(ctx.current_stmt_provenance);
        out.push(lir::Stmt::new(
            lir::StmtKind::Assign {
                target: lir::AssignTarget::Temp(slot, name),
                op: AssignOp::Set,
                value: lir::ExprKind::IndexSet {
                    base: Box::new(base),
                    index: Box::new(index),
                    value: Box::new(inner),
                }
                .at(ctx.current_stmt_provenance),
            },
            ctx.current_stmt_provenance,
        ));
    }

    // 6. Write the final root container back into the root variable.
    let (root_slot, root_name) = c_slots[0];
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::GetTemp(root_slot, root_name).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
}

/// Lower `for x in arr { … }` / `for k in map { … }` — or, on the native
/// surface, `for k, v in map { … }` (§2, plus B2 issue #1461 for the
/// two-binding form). Desugars to an index-based `LogicWhile` — dedicated
/// iterator opcodes are deliberately not part of the T1b surface
/// (`docs/format-v4-rfc.md` §3 note); the iterable is snapshotted once via
/// `CollectionKeys` (which returns the array unchanged for an array input
/// — see that opcode's doc — so one snapshot expression correctly covers
/// both "iterate values" and "iterate keys" without a static array/map
/// type distinction).
///
/// The two-binding form (`f.val_name.is_some()`) is exactly the F10-ruled
/// desugar (`docs/stdlib-spec.md` §5/§9: "`for k, v in m` ... desugars to
/// key-iteration + `let v = m[k]`, total by construction, no pair shape
/// ever materializes") — an extra `DeclareTemp` reading `container[key]`
/// at the top of the body, right after `key` itself is declared. The
/// container is evaluated exactly once, into its own synthetic temp,
/// *before* the keys snapshot — it's read twice (once to snapshot its
/// keys, once per-iteration to index it), and `f.iterable` may be an
/// arbitrary expression (e.g. a call) that must not run twice. The
/// single-binding form keeps the original one-snapshot shape byte-for-byte
/// unchanged (no synthetic container temp) since it only ever reads the
/// snapshot.
#[expect(
    clippy::similar_names,
    reason = "var_name/val_name are the ForStmt field names (k/v's HIR spelling, B2 #1461) — \
              not a pair a rename would clarify"
)]
fn lower_for_stmt(f: &hir::ForStmt, ctx: &mut LowerCtx<'_>, out: &mut Vec<lir::Stmt>) {
    let iterable = lower_expr(&f.iterable, ctx);
    let snapshot_source = if f.val_name.is_some() {
        let (container_slot, container_name) =
            declare_synthetic("__for_container", iterable, ctx, out);
        lir::ExprKind::GetTemp(container_slot, container_name).at(ctx.current_stmt_provenance)
    } else {
        iterable
    };
    let (snap_slot, snap_name) = declare_synthetic(
        "__for_snapshot",
        lir::ExprKind::CollectionKeys(Box::new(snapshot_source.clone()))
            .at(ctx.current_stmt_provenance),
        ctx,
        out,
    );
    let (idx_slot, idx_name) = declare_synthetic(
        "__for_idx",
        lir::ExprKind::Int(0).at(ctx.current_stmt_provenance),
        ctx,
        out,
    );

    let condition = lir::ExprKind::Infix(
        Box::new(lir::ExprKind::GetTemp(idx_slot, idx_name).at(ctx.current_stmt_provenance)),
        InfixOp::Lt,
        Box::new(
            lir::ExprKind::CollectionLen(Box::new(
                lir::ExprKind::GetTemp(snap_slot, snap_name).at(ctx.current_stmt_provenance),
            ))
            .at(ctx.current_stmt_provenance),
        ),
    )
    .at(ctx.current_stmt_provenance);

    ctx.push_block_scope();
    let (var_slot, var_name) = declare_shadow_checked(&f.var_name.text, f.var_name.range, ctx);
    let mut body = vec![lir::Stmt::new(
        lir::StmtKind::DeclareTemp {
            slot: var_slot,
            name: var_name,
            value: Some(
                lir::ExprKind::Index {
                    base: Box::new(
                        lir::ExprKind::GetTemp(snap_slot, snap_name)
                            .at(ctx.current_stmt_provenance),
                    ),
                    index: Box::new(
                        lir::ExprKind::GetTemp(idx_slot, idx_name).at(ctx.current_stmt_provenance),
                    ),
                }
                .at(ctx.current_stmt_provenance),
            ),
            synthetic: false,
        },
        ctx.current_stmt_provenance,
    )];
    if let Some(val_name) = &f.val_name {
        let (val_slot, val_name_id) = declare_shadow_checked(&val_name.text, val_name.range, ctx);
        body.push(lir::Stmt::new(
            lir::StmtKind::DeclareTemp {
                slot: val_slot,
                name: val_name_id,
                value: Some(
                    lir::ExprKind::Index {
                        base: Box::new(snapshot_source),
                        index: Box::new(
                            lir::ExprKind::GetTemp(var_slot, var_name)
                                .at(ctx.current_stmt_provenance),
                        ),
                    }
                    .at(ctx.current_stmt_provenance),
                ),
                synthetic: false,
            },
            ctx.current_stmt_provenance,
        ));
    }
    ctx.loop_depth += 1;
    body.extend(lower_block_stmt_list(&f.body, ctx));
    ctx.loop_depth -= 1;
    ctx.pop_block_scope();

    let post = vec![lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(idx_slot, idx_name),
            op: AssignOp::Add,
            value: lir::ExprKind::Int(1).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    )];

    out.push(lir::Stmt::new(
        lir::StmtKind::LogicWhile(lir::LogicWhile {
            condition,
            body,
            post,
        }),
        ctx.current_stmt_provenance,
    ));
}

// ─── T1b stdlib slice 1 mutators (§5) ──────────────────────────────────
//
// `push(a, v)` / `insert(x, k_or_i, v)` / `remove(m, k)` / `remove_at(a, i)`
// require an lvalue first argument and lower through the same take →
// `make_mut` → write-back RMW discipline as indexed assignment (§4) —
// desugaring to a chain of synthetic-temp `Assign`s exactly like
// `lower_indexed_assignment` above, just with a
// `CollectionInsert`/`CollectionRemove`/`SeqRemoveAt` mutate step instead
// of the deepest level's `IndexSet`.

/// The chain state [`lower_lvalue_container_chain`] returns: the root
/// assign target, the materialized index temps, and the materialized
/// container-read temps. See that function's doc for the shape.
type LvalueContainerChain = (
    lir::AssignTarget,
    Vec<(u16, brink_format::NameId)>,
    Vec<(u16, brink_format::NameId)>,
);

/// A collection mutator recognized from a call expression
/// (`docs/t1b-surface-spec.md` §5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MutatorKind {
    /// `push(a, v)` — 2 args; desugars to `insert(a, len(a), v)`.
    Push,
    /// `insert(x, k_or_i, v)` — 3 args.
    Insert,
    /// `remove(m, k)` — 2 args. Map-only as of issue #1484: `remove`
    /// uniformly names identity-based, idempotent-total removal (map keys,
    /// flags values). The array-index leg lives at `RemoveAt` now.
    Remove,
    /// `remove_at(a, i)` — 2 args (issue #1484, joining the `_at`
    /// faulting-index family with `char_at`): removes the array element at
    /// `i`, faulting out of bounds.
    RemoveAt,
    /// `clear(m)` — 1 arg (NS-A1, `docs/stdlib-spec.md` §5): empty the map
    /// in place, total.
    Clear,
    /// `shuffle(a)` — 1 arg (NS-A6, `docs/stdlib-spec.md` §7): Fisher-Yates
    /// shuffle of the array in place; every element swap draws through the
    /// one RNG cell. `shuffled(a)` is the functional twin (ordinary
    /// expression lowering).
    Shuffle,
    /// `sort(a)` — 1 arg (NS-A4, `docs/stdlib-spec.md` §4b): sort the
    /// array in place by the doctrine order (dev NaN-fault / prod pinned
    /// placement at the runtime knob). `sorted(a)` is the functional twin.
    Sort,
    /// `sort_by(a, cmp)` — 2 args (NS-A4, F0 ruled 2026-07-19): sort the
    /// array in place by a comparator function value `fn(T, T): int`.
    /// `sorted_by(a, cmp)` is the functional twin.
    SortBy,
    /// `heap_push(a, x)` — 2 args (NS-A7, `docs/stdlib-spec.md` §8): sift
    /// `x` into the min-heap maintained over the array, in place (§4b
    /// entry check: dev NaN-fault / prod pinned placement at the runtime
    /// knob). `heap_pop`/`heap_peek` are not mutator-statement shapes —
    /// `heap_pop` is the `pop` expression/bracket shape, `heap_peek` a
    /// pure expression.
    HeapPush,
}

impl MutatorKind {
    /// Every `MutatorKind` variant, for exhaustive iteration (issue #2863
    /// review: a test that iterates a hand-copied name list instead of
    /// this array can't catch a 10th mutator variant that was added to the
    /// enum but never wired into this list — the array itself is built
    /// from an exhaustive `match` in [`Self::name`], so a new variant is a
    /// compile error here, not a silent gap). Test-only: no production
    /// caller needs the full variant set today.
    #[cfg(test)]
    const ALL: [Self; 9] = [
        Self::Push,
        Self::Insert,
        Self::Remove,
        Self::RemoveAt,
        Self::Clear,
        Self::Shuffle,
        Self::Sort,
        Self::SortBy,
        Self::HeapPush,
    ];

    /// The mutator's stdlib name, as `from_name` recognizes it — the
    /// inverse of `from_name`, kept as its own exhaustive `match` (rather
    /// than a lookup table) so adding a variant without adding it here is
    /// a compile error. Test-only: no production caller needs the name
    /// back from a `MutatorKind` today.
    #[cfg(test)]
    const fn name(self) -> &'static str {
        match self {
            Self::Push => "push",
            Self::Insert => "insert",
            Self::Remove => "remove",
            Self::RemoveAt => "remove_at",
            Self::Clear => "clear",
            Self::Shuffle => "shuffle",
            Self::Sort => "sort",
            Self::SortBy => "sort_by",
            Self::HeapPush => "heap_push",
        }
    }

    /// The mutator names are a subset of `super::expr::is_t1b_stdlib_name`
    /// (which also covers the pure functions) — kept as an explicit
    /// `matches!` here rather than depending on that function so this
    /// module doesn't need to filter out the pure names on every call.
    fn from_name(name: &str) -> Option<Self> {
        match name {
            "push" => Some(Self::Push),
            "insert" => Some(Self::Insert),
            "remove" => Some(Self::Remove),
            "remove_at" => Some(Self::RemoveAt),
            "clear" => Some(Self::Clear),
            "shuffle" => Some(Self::Shuffle),
            "sort" => Some(Self::Sort),
            "sort_by" => Some(Self::SortBy),
            "heap_push" => Some(Self::HeapPush),
            _ => None,
        }
    }

    fn expected_argc(self) -> usize {
        match self {
            Self::Clear | Self::Shuffle | Self::Sort => 1,
            Self::Push | Self::Remove | Self::RemoveAt | Self::SortBy | Self::HeapPush => 2,
            Self::Insert => 3,
        }
    }

    /// The mutator's documented signature (§5), for a targeted E058 message
    /// naming exactly what was expected.
    fn signature(self) -> &'static str {
        match self {
            Self::Push => "push(container, value)",
            Self::Insert => "insert(container, key_or_index, value)",
            Self::Remove => "remove(map, key)",
            Self::RemoveAt => "remove_at(array, index)",
            Self::Clear => "clear(map)",
            Self::Shuffle => "shuffle(array)",
            Self::Sort => "sort(array)",
            Self::SortBy => "sort_by(array, comparator)",
            Self::HeapPush => "heap_push(array, value)",
        }
    }
}

/// Whether `expr` is a valid mutator lvalue (§5: "a variable, temp, or
/// indexed path") — a bare path, or an (arbitrarily chained) indexed path
/// rooted in one. Anything else (a call, literal, operator, collection
/// literal, …) is an rvalue.
fn is_lvalue_expr(expr: &hir::Expr) -> bool {
    match expr {
        hir::Expr::Path(_) => true,
        hir::Expr::Index(idx) => is_lvalue_expr(&idx.base),
        _ => false,
    }
}

/// Recognize and fully lower a `push`/`insert`/`remove`/`remove_at` call
/// statement (§5), splicing its RMW expansion into `out`. Returns `false`
/// (nothing pushed) when `expr` isn't one of these mutator calls, or
/// resolves to a real user symbol — a temp/param holding a divert target,
/// or a resolved
/// knot/external/list/variable (shadowed; the caller falls through to
/// ordinary call lowering, and `brink-analyzer`'s symbol-declaration pass
/// separately emits the E035 shadow warning at the declaration site).
///
/// Called from both `~ { … }` block statements (`lower_block_stmt` above)
/// and classic non-block `~ push(...)` logic lines (`lower::mod`'s
/// `lower_block_with_children`) — a function call used as a statement for
/// its side effect is not a T1b-only concept (ordinary knots/externals are
/// already callable that way outside any block).
/// `seed(n)` (NS-A6, `docs/stdlib-spec.md` §7): statement-only like the
/// mutators, but its argument is an ordinary value, not an lvalue
/// receiver — it writes the RNG cell, not its argument — so it takes its
/// own path rather than joining `MutatorKind`'s lvalue/RMW machinery. It
/// lowers to the frozen `SEED_RANDOM` builtin (one RNG cell, two
/// surfaces, no drift); `ExprStmt` discards the op's `Null`. Same shadow
/// discipline as the mutators: a resolvable user symbol of the same name
/// falls through to ordinary call lowering.
fn try_lower_seed_stmt(
    path: &hir::Path,
    args: &[hir::Expr],
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    if ctx.temp_slot("seed").is_some() || ctx.resolve_path(path.range).is_some() {
        return false;
    }
    if args.len() != 1 {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range: path.range,
            message: format!(
                "{}: `seed` expects 1 argument(s), got {} — expected signature: `seed(n)`",
                DiagnosticCode::E058.title(),
                args.len(),
            ),
            code: DiagnosticCode::E058,
        });
        return true;
    }
    let arg = lower_expr(&args[0], ctx);
    out.push(lir::Stmt::new(
        lir::StmtKind::ExprStmt(
            lir::ExprKind::CallBuiltin {
                builtin: lir::BuiltinFn::SeedRandom,
                args: vec![arg],
            }
            .at(ctx.current_stmt_provenance),
        ),
        ctx.current_stmt_provenance,
    ));
    true
}

/// Issue #2894 — bare-variable postfix `x++`/`x--` inside a `~ { … }` block,
/// and (post-#2900 review) the shared postfix→`Assign` conversion for
/// *both* surfaces: `stmts::lower_stmt`'s classic-line `ExprStmt` arm calls
/// this directly rather than keeping its own copy, so the block form
/// (`lower_block_stmt`'s `ExprStmt` arm, below) and the classic-line form
/// can never re-diverge the way #2894 itself was caused by (a conversion
/// written for one surface and never given to the other).
///
/// Without this conversion, a bare-variable postfix reached only the
/// generic `lower_expr` fallback, which lowers `hir::Expr::Postfix` to a
/// *pure* `lir::ExprKind::Postfix` — codegen computes `x + 1`/`x - 1` as a value
/// and the enclosing `ExprStmt` immediately pops it
/// (`brink-codegen-inkb/src/expr.rs`): the write never happens, with no
/// diagnostic at all (a `~ { x++ }` compiled clean and silently did
/// nothing — reproduced against a real compile+run, not just unit
/// lowering).
///
/// Field-operand refusal comes first, on both surfaces: `a.count++` is the
/// identical field-projection misroute #2185/PR #2897 closed for the
/// classic-line spelling (the write would otherwise land on the whole
/// record root, not the field) — refused here with the same
/// non-suppressible `E074` via `reject_field_projection_index_root`, so
/// this fix cannot reintroduce that misroute for either surface.
///
/// Issue #2903 — the sibling gap PR #2900's review found: an **index**
/// operand (`a[0]++`, `m["k"]++`) is neither `Path` nor `FieldAccess`, so
/// `reject_field_projection_index_root` never matched it and
/// `lower_assign_target` below (which only recognizes a bare `Path`) fell
/// through its `_ => None` arm — the exact same silent-drop #2894 fixed for
/// a bare variable, just on an `Index` target instead. An `Index` operand is
/// now routed through [`lower_indexed_assignment`] (the same take/mutate/
/// write-back RMW discipline `a[0] += 1` already uses, proven correct for
/// both a list index and a map key — `crates/brink-test-harness`'s
/// `take_rmw.rs` proptests and `brink-runtime/tests/issue_2903_index_postfix.rs`'s
/// `map_key_compound_{add,sub}_assign_matches_manual_rmw_end_to_end`) rather
/// than a second, divergent refusal path: `lower_indexed_assignment`
/// re-flattens the index chain and re-applies
/// `reject_field_projection_index_root` on the *flattened root* itself, so a
/// field-projected index root (`p.items[0]++`) still refuses with the
/// identical E074 #2121 already established for `p.items[0] = v` — it is
/// caught one level down from where the plain `FieldAccess` arm above
/// catches `a.count++`, not skipped.
///
/// Returns `true` (handled — either lowered to a real `Assign`/RMW sequence
/// and pushed onto `out`, or refused with a diagnostic and nothing pushed)
/// for any `hir::Expr::Postfix`; `false` for every other expression shape,
/// so the caller falls through to ordinary lowering (including a postfix
/// whose operand doesn't resolve to an assignable root at all — the
/// analyzer's own `E025` covers that case). `out` holds zero elements on
/// refusal (no `ExprStmt(Null)` placeholder — matching every other
/// malformed-statement arm in this module, e.g. `lower_loop_control`'s E057
/// refusal), exactly one for a bare-variable/temp target, or several (issue
/// #2903) for an `Index` target's RMW take/mutate/write-back sequence — a
/// caller that can only take a *single* `Option<lir::Stmt>` back out (the
/// `stmts::lower_stmt` fallback callers still reach for a non-`Index`
/// postfix) must not call this function for an `Index`-operand postfix; see
/// this function's own #2903 paragraph above for which callers already
/// guard against that by intercepting `Index` first.
pub(super) fn try_lower_postfix_stmt(
    expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    let hir::Expr::Postfix(inner, op) = expr else {
        return false;
    };
    let assign_op = match op {
        crate::PostfixOp::Increment => AssignOp::Add,
        crate::PostfixOp::Decrement => AssignOp::Sub,
    };
    // Issue #2903: an Index-operand postfix (`a[0]++`, `m["k"]++`) is
    // handled before the field-operand check below — `reject_field_projection_index_root`
    // never matches a bare `hir::Expr::Index` (it only matches `Path`/
    // `FieldAccess`), so leaving this arm out would still fall through to
    // `lower_assign_target`'s `_ => None` and silently drop the statement.
    // `lower_indexed_assignment` performs its own field-projection-root
    // check internally (see doc above), so a field-projected root still
    // refuses correctly from inside this call.
    if let hir::Expr::Index(idx) = inner.as_ref() {
        lower_indexed_assignment(idx, assign_op, &hir::Expr::Int(1), ctx, out);
        return true;
    }
    if reject_field_projection_index_root(inner, ctx, Some(FIELD_PROJECTION_POSTFIX_TARGET)) {
        return true;
    }
    let Some(target) = super::stmts::lower_assign_target(inner, ctx) else {
        return false;
    };
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target,
            op: assign_op,
            value: lir::ExprKind::Int(1).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
    true
}

pub(super) fn try_lower_mutator_stmt(
    expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    let hir::Expr::Call(path, args) = expr else {
        return false;
    };
    let name = super::expr::path_to_string(path);

    if name == "seed" && try_lower_seed_stmt(path, args, ctx, out) {
        return true;
    }
    if name == "seed" {
        return false;
    }

    // B3a UFCS (issue #1506): `m.insert(k, v)` reaches here as a
    // multi-segment `Call` path. `path_to_string` on a multi-segment path
    // yields the dotted string ("m.insert"), which never matches
    // `MutatorKind::from_name` (it only recognizes the bare verb) — so
    // without this arm, every mutator verb spelled as method-call syntax
    // fell through to `lower_call`'s UFCS dispatch
    // (`lower_ufcs_prelude_desugar` → `lower_t1b_stdlib_call`), which
    // unconditionally refuses every mutator name with E056 ("used in
    // expression position") even from statement position. A UFCS call site
    // always carries a resolution at `path.range` naming the *receiver*
    // (see `expr::lower_ufcs_call`'s own doc), so the ordinary
    // `ctx.resolve_path(path.range).is_some()` shadow check below would
    // always bail out for one of these — this arm runs first, reading the
    // analyzer's verdict directly instead of that resolution, and splices
    // the receiver in as the mutator's first argument before running the
    // same RMW expansion a bare `insert(m, k, v)` statement gets.
    if path.segments.len() > 1
        && let Some(UfcsVerdict::PreludeDesugar { name: verb }) =
            ctx.tables.ufcs.get(ctx.file, path.range).cloned()
        && let Some(kind) = MutatorKind::from_name(&verb)
    {
        let receiver = super::expr::ufcs_receiver_path(path);
        let mut desugared_args = Vec::with_capacity(args.len() + 1);
        desugared_args.push(hir::Expr::Path(receiver));
        desugared_args.extend(args.iter().cloned());
        lower_mutator_call(kind, &verb, path, &desugared_args, ctx, out);
        return true;
    }

    let Some(kind) = MutatorKind::from_name(&name) else {
        return false;
    };
    if ctx.temp_slot(&name).is_some() || ctx.resolve_path(path.range).is_some() {
        return false;
    }

    lower_mutator_call(kind, &name, path, args, ctx, out);
    true
}

/// Frame-local projection auto-ref (issue #1531, RULED 2026-07-27 —
/// `docs/decision-log.md`): `g.hp.heal(5)` where `g` is a temp/param and
/// `heal`'s first parameter is `ref`. `brink-analyzer::ufcs::
/// auto_ref_fault` now accepts a frame-local, single-field-deep receiver
/// like this one as a legal `FreeFnAutoRef` verdict — a frame-local cell is
/// a valid projection root, and the mutation needs no effect row because it
/// is unobservable outside the frame.
///
/// There is still no *expression*-shaped lowering for it, though:
/// [`lir::CallArg::RefProjection`]'s root is a durable global
/// [`brink_format::DefinitionId`] only (`docs/format-v4-rfc.md` §1) — using
/// a frame-local's `LocalVar`-tagged id there would fault at runtime as
/// `UnresolvedGlobal` with no compile diagnostic (the same hazard
/// `expr::lower_ref_path_call_arg`'s block-scoped-temp guard already
/// documents for the bare-receiver case). So this recognizes the shape at
/// **statement** position only and expands it as the same RMW discipline
/// `try_lower_field_assignment` already established for `g.hp = v`: read
/// the field into a synthetic temp, call the target passing that temp by
/// `ref` (an ordinary bare [`lir::CallArg::RefTemp`], never a projection),
/// then write the temp back into the field. `expr::lower_ref_projection_arg`
/// carries the matching defense-in-depth refusal for the same verdict
/// reached from *expression* position (nested inside a larger expression,
/// where this recognizer never gets a chance to run) — see that function's
/// own frame-local guard.
///
/// Returns `false` (nothing lowered) for every other call shape, so the
/// caller falls through to ordinary call lowering — including a
/// `FreeFnAutoRef` verdict whose receiver is a durable global or a bare
/// (non-projection) frame-local, both of which
/// `expr::lower_ufcs_desugared_call` already handles correctly, and a
/// receiver more than one field deep, which `brink-analyzer`'s own gate
/// still refuses with `E143` before lowering ever sees it.
#[expect(
    clippy::too_many_lines,
    reason = "one straight-line RMW desugar (read/call/write-back); issue #3183's \
              provenance stamping pushed it just over the line budget"
)]
pub(super) fn try_lower_frame_local_auto_ref_stmt(
    expr: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> bool {
    let hir::Expr::Call(path, args) = expr else {
        return false;
    };
    let Some(UfcsVerdict::FreeFnAutoRef { target }) =
        ctx.tables.ufcs.get(ctx.file, path.range).cloned()
    else {
        return false;
    };
    let receiver = super::expr::ufcs_receiver_path(path);
    if receiver.segments.len() != 2 {
        return false;
    }
    #[expect(
        clippy::indexing_slicing,
        reason = "just proved receiver.segments.len() == 2"
    )]
    let head_name = receiver.segments[0].text.clone();
    #[expect(
        clippy::indexing_slicing,
        reason = "just proved receiver.segments.len() == 2"
    )]
    let field_name = receiver.segments[1].text.clone();
    // A durable global (or an unresolved name) falls through to the
    // ordinary `RefProjection` desugar — only a genuine frame-local takes
    // this path.
    let Some(root_slot) = ctx.temp_slot(&head_name) else {
        return false;
    };
    // B1b (issue #1475): the same `ref`-bypasses-immutability hole
    // `lower_ref_path_call_arg` and `lower_ref_projection_arg` both guard —
    // this recognizer writes the receiver back into `root_slot` too (step
    // 3 below), so an `as` binding must be refused here as well. Return
    // `true` (handled) rather than `false`: falling through would let this
    // same call reach `expr::lower_ref_projection_arg`'s frame-local guard
    // instead, which emits the misleading "must be its own statement"
    // `E143` — this call *is* its own statement; the real problem is the
    // `as` binding's immutability.
    if ctx.as_binding_slots.contains(&root_slot) {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range: path.range,
            message: format!(
                "{}: `{head_name}` is an `as` binding — it is immutable and cannot be passed \
                 by `ref`",
                DiagnosticCode::E148.title(),
            ),
            code: DiagnosticCode::E148,
        });
        return true;
    }
    let Some(target_info) = ctx.index.symbols.get(&target) else {
        // Structurally unreachable — `target` came from the analyzer's own
        // resolution against this same project index, exactly like
        // `expr::lower_ufcs_desugared_call`'s identical guard. Falling
        // through lets that function's own copy of this guard handle it.
        return false;
    };

    let head_name_id = ctx.names.intern(&head_name);
    let field = ctx.names.intern(&field_name);
    let root_target = lir::AssignTarget::Temp(root_slot, head_name_id);

    let static_offset = if ctx.structs.type_mode == TypeMode::Strict {
        ctx.temp_shape(root_slot)
            .and_then(|d| ctx.structs.shapes.get_by_def(d))
            .and_then(|shape| shape.field(&field_name))
            .map(|(offset, _)| offset)
    } else {
        None
    };

    // 1. Read the field into a synthetic temp — the call's receiver
    //    argument. A non-mutating read, so it can't itself trigger a COW.
    let current = lir::ExprKind::RecordGet {
        base: Box::new(get_expr_for_target(
            &root_target,
            ctx.current_stmt_provenance,
        )),
        field,
        static_offset,
    }
    .at(ctx.current_stmt_provenance);
    let (recv_slot, recv_name) = declare_synthetic("__recv", current, ctx, out);

    // 2. The call: `target(ref __recv, args…)` — a bare receiver, so it
    //    rides the ordinary `RefTemp` write-through (`Opcode::
    //    PushTempPointer`/`SetTemp`'s `Value::TempPointer` arm), never a
    //    projection.
    let rest_params = target_info.params.get(1..).unwrap_or(&[]);
    let mut call_args = Vec::with_capacity(args.len() + 1);
    call_args.push(lir::CallArg::RefTemp(recv_slot, recv_name));
    call_args.extend(super::expr::lower_call_args(args, rest_params, ctx));
    let call_expr = if target_info.kind == SymbolKind::External {
        lir::ExprKind::CallExternal {
            target,
            #[expect(
                clippy::cast_possible_truncation,
                reason = "ink externals have <=255 params"
            )]
            arg_count: target_info.params.len() as u8,
            args: call_args,
        }
        .at(ctx.current_stmt_provenance)
    } else {
        lir::ExprKind::Call {
            target,
            args: call_args,
        }
        .at(ctx.current_stmt_provenance)
    };
    out.push(lir::Stmt::new(
        lir::StmtKind::ExprStmt(call_expr),
        ctx.current_stmt_provenance,
    ));

    // 3. Write the (possibly mutated) receiver back into the field. No
    //    fault pre-check is needed here — step 1's read already proved this
    //    exact field is valid on this exact root, and nothing between then
    //    and now could have invalidated that.
    let write_back = lir::ExprKind::RecordSet {
        base: Box::new(take_expr_for_target(
            &root_target,
            ctx.current_stmt_provenance,
        )),
        field,
        static_offset,
        value: Box::new(
            lir::ExprKind::GetTemp(recv_slot, recv_name).at(ctx.current_stmt_provenance),
        ),
    }
    .at(ctx.current_stmt_provenance);
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: write_back,
        },
        ctx.current_stmt_provenance,
    ));

    true
}

/// The arity check / lvalue check / RMW-expansion body shared by
/// [`try_lower_mutator_stmt`]'s two call shapes: the direct call
/// (`insert(m, k, v)`) and the UFCS desugar (`m.insert(k, v)`, issue
/// #1506) — in the UFCS case the caller has already spliced the receiver
/// into `args[0]`, so from here on both shapes are identical. `name` is the
/// bare mutator verb (never the dotted UFCS spelling) — used only for
/// diagnostic messages.
#[expect(
    clippy::too_many_lines,
    reason = "arity/lvalue checks plus the three lvalue-shape dispatches \
              (bare variable, struct field, indexed chain) read better as \
              one function than split across an arbitrary line boundary"
)]
fn lower_mutator_call(
    kind: MutatorKind,
    name: &str,
    path: &hir::Path,
    args: &[hir::Expr],
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    // RULED 2026-07-12 (#581, docs/decision-log.md): a mutator arity
    // mismatch is a targeted compile error naming the expected signature
    // (E058), replacing the generic E031 warning this used to share with
    // ordinary function-call arity checking. E031 only ever warned — it
    // never blocked compilation — so the malformed statement fell through
    // to "return true, push nothing," silently dropping the RMW lowering
    // (the mutator call vanished from the bytecode with no compile
    // failure). E058 is Error-severity, so `brink-db`'s `lir_query` now
    // refuses to hand back a `Program` for it, exactly like E055/E056.
    // Pure-function arity checking (ordinary knot/external calls) is
    // untouched — this only covers the mutator names.
    let expected = kind.expected_argc();
    if args.len() != expected {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range: path.range,
            message: format!(
                "{}: `{}` expects {expected} argument(s), got {} — expected signature: `{}`",
                DiagnosticCode::E058.title(),
                name,
                args.len(),
                kind.signature(),
            ),
            code: DiagnosticCode::E058,
        });
        return;
    }

    let lvalue_expr = &args[0];
    if !is_lvalue_expr(lvalue_expr) {
        ctx.diagnostics.push(Diagnostic {
            file: ctx.file,
            range: path.range,
            message: format!(
                "{}: `{name}` mutates its first argument — bind it to a variable first",
                DiagnosticCode::E055.title(),
            ),
            code: DiagnosticCode::E055,
        });
        return;
    }

    // Bare-variable lvalue (`push(a, v)`, not `push(grid[y], v)`) — the
    // loop-append benchmark's shape — dispatches to the take-based fast
    // path (issue #576). A chained lvalue keeps the clone-based fallback
    // below unchanged, for the same reason `lower_indexed_assignment`
    // scopes its own fast path to `n == 1`: a nested element is still
    // referenced from inside its parent until the write-back cascade
    // completes, so Take buys nothing at any level but the root.
    //
    // A bare `ident.ident` chain (`push(a.items, v)`) always parses as one
    // multi-segment `hir::Expr::Path` too — never `hir::Expr::FieldAccess`
    // (see `try_lower_field_assignment`'s doc) — so it lands in this same
    // arm. Issue #1495: without this split, `path.segments.len() > 1`
    // silently fell into the bare-variable path below, whose
    // `lower_assign_target` resolves the *whole path's range* to the
    // **root** variable (the TM-4b resolution-fallback shape) — routing
    // the mutator onto `a` (a `Record`) instead of `a.items` (the `Array`),
    // a silent misroute that only surfaced as a runtime `NotIndexable`
    // fault. Mirrors `try_lower_field_assignment`'s own split exactly: a
    // single-segment path (or one that doesn't resolve to a struct-field
    // root) keeps the bare-variable fast path; a struct-field projection
    // routes through `lower_field_mutator`; a chained projection (3+
    // segments) is rejected with the same non-suppressible `E074` that
    // function's chained-write case already raises, rather than silently
    // miscompiled.
    if let hir::Expr::Path(path) = lvalue_expr {
        if path.segments.len() > 1
            && let Some(info) = ctx.resolve_path(path.range)
            && matches!(
                info.kind,
                SymbolKind::Variable | SymbolKind::Constant | SymbolKind::Param | SymbolKind::Temp
            )
        {
            if path.segments.len() > 2 {
                emit_chained_field_write_diagnostic(path.range, ctx);
            } else {
                lower_field_mutator(kind, path, info, args, ctx, out);
            }
            return;
        }
        lower_bare_mutator(kind, lvalue_expr, args, ctx, out);
        return;
    }

    let Some((root_target, idx_slots, c_slots)) =
        lower_lvalue_container_chain(lvalue_expr, ctx, out)
    else {
        // Two ways here: (1) genuinely structurally unreachable given the
        // `is_lvalue_expr` guard above — guarded rather than asserted so a
        // future grammar change can't corrupt output instead of doing
        // nothing (same discipline as `lower_indexed_assignment`'s `n == 0`
        // guard); (2) issue #2121 — `reject_field_projection_index_root`
        // fired inside `lower_lvalue_container_chain` and already pushed the
        // `E074` diagnostic, so returning here without pushing anything
        // *is* the handling.
        return;
    };
    // `lower_lvalue_container_chain` always pushes the root as `c_slots[0]`
    // before ever returning `Some`, so `c_slots` is never empty.
    let Some(&(last_slot, last_name)) = c_slots.last() else {
        return;
    };
    // Snapshot the ambient provenance before the closure below captures it —
    // `container` reads it on every call, but a `Copy` snapshot (not `ctx`
    // itself) keeps `ctx` free for the `&mut` calls (`lower_expr`, etc.)
    // this function still needs alongside it.
    let stmt_prov = ctx.current_stmt_provenance;
    let container = move || lir::ExprKind::GetTemp(last_slot, last_name).at(stmt_prov);

    let new_container = match kind {
        MutatorKind::Push => {
            let value = lower_expr(&args[1], ctx);
            lir::ExprKind::CollectionInsert {
                base: Box::new(container()),
                key: Box::new(
                    lir::ExprKind::CollectionLen(Box::new(container()))
                        .at(ctx.current_stmt_provenance),
                ),
                value: Box::new(value),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::Insert => {
            let key = lower_expr(&args[1], ctx);
            let value = lower_expr(&args[2], ctx);
            lir::ExprKind::CollectionInsert {
                base: Box::new(container()),
                key: Box::new(key),
                value: Box::new(value),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::Remove => {
            let key = lower_expr(&args[1], ctx);
            lir::ExprKind::CollectionRemove {
                base: Box::new(container()),
                key: Box::new(key),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::RemoveAt => {
            let index = lower_expr(&args[1], ctx);
            lir::ExprKind::SeqRemoveAt {
                base: Box::new(container()),
                index: Box::new(index),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::Clear => {
            lir::ExprKind::MapClear(Box::new(container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::Shuffle => {
            lir::ExprKind::RandShuffle(Box::new(container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::Sort => {
            lir::ExprKind::SeqSorted(Box::new(container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::SortBy => lir::ExprKind::SeqSortedBy {
            seq: Box::new(container()),
            cmp: Box::new(lower_expr(&args[1], ctx)),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::HeapPush => lir::ExprKind::HeapPush {
            seq: Box::new(container()),
            value: Box::new(lower_expr(&args[1], ctx)),
        }
        .at(ctx.current_stmt_provenance),
    };

    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(last_slot, last_name),
            op: AssignOp::Set,
            value: new_container,
        },
        ctx.current_stmt_provenance,
    ));
    writeback_lvalue_container_chain(
        root_target,
        &idx_slots,
        &c_slots,
        out,
        ctx.current_stmt_provenance,
    );
}

/// Fast path for a mutator (`push`/`insert`/`remove`/`remove_at`) whose
/// lvalue is a bare variable — mirrors [`lower_flat_indexed_assignment`]'s
/// Take-based RMW (issue #576): the root is taken (not cloned) only *after*
/// every mutator argument is fully evaluated into its own synthetic temp,
/// since any of them may reference the root by name (e.g. `insert(a, 0,
/// a[0])`); the container fed to
/// `CollectionInsert`/`CollectionRemove`/`SeqRemoveAt` is itself a take
/// from the synthetic root temp, so `array_make_mut`/`map_make_mut` sees a
/// unique `Arc` whenever nothing else aliases the container.
///
/// **Fault-during-RMW slot state**: `push`'s key is always `len(container)`
/// — by construction always a valid insert index — so `push` can only ever
/// fault via `NotIndexable` (the root isn't an array/map at runtime), and
/// this path pre-checks exactly that (the `CollectionLen` read below is
/// non-mutating, so it can't itself trigger a COW) *before* taking the
/// root, giving `push` the same "root is never lost to a fault" guarantee
/// `lower_flat_indexed_assignment` has — and for free, since that same
/// `CollectionLen` read also IS the value `push`'s key needs. `insert`/
/// `remove`/`remove_at` at an arbitrary author-supplied key don't get an
/// equivalent cheap pre-check (validating an arbitrary key/index without mutating
/// would need a dedicated "is this key valid" primitive this issue doesn't
/// add — see the PR's scope notes): a fault there leaves the root holding
/// `Value::Null`, a deliberate, documented, and tested trade-off consistent
/// with this VM's pre-existing no-rollback-on-fault model (a fault
/// anywhere mid-turn already leaves earlier same-turn mutations applied;
/// this extends that same contract to the RMW's own target). See
/// `fault_during_push_leaves_root_unchanged` and
/// `fault_during_insert_leaves_root_null` (runtime crate) for the property
/// tests.
#[expect(
    clippy::too_many_lines,
    reason = "one dispatch arm per MutatorKind; issue #3183's provenance stamping \
              pushed it just over the line budget, splitting would obscure the \
              exhaustive dispatch"
)]
fn lower_bare_mutator(
    kind: MutatorKind,
    root_expr: &hir::Expr,
    args: &[hir::Expr],
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    let Some(root_target) = super::stmts::lower_assign_target(root_expr, ctx) else {
        // Structurally unreachable: `root_expr` is a `hir::Expr::Path`
        // already validated as a resolvable lvalue by `is_lvalue_expr` and
        // (indirectly) `try_lower_mutator_stmt`'s shadow check above —
        // guarded rather than asserted per this module's usual discipline.
        return;
    };

    // Evaluate the mutator's own args (key/value) before touching root —
    // any of them may reference the root by name.
    let arg_slots: Vec<(u16, brink_format::NameId)> = args[1..]
        .iter()
        .map(|a| {
            let v = lower_expr(a, ctx);
            declare_synthetic("__arg", v, ctx, out)
        })
        .collect();

    // `push`'s fault pre-check doubles as its key (see doc above) — read
    // while root is still intact.
    let push_len = matches!(kind, MutatorKind::Push).then(|| {
        declare_synthetic(
            "__len",
            lir::ExprKind::CollectionLen(Box::new(get_expr_for_target(
                &root_target,
                ctx.current_stmt_provenance,
            )))
            .at(ctx.current_stmt_provenance),
            ctx,
            out,
        )
    });

    // Take the root.
    let (c_slot, c_name) = declare_synthetic(
        "__c",
        take_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    );

    let new_container = match kind {
        MutatorKind::Push => {
            let Some((len_slot, len_name)) = push_len else {
                // Structurally unreachable: `push_len` is always `Some` for
                // `MutatorKind::Push` by the `matches!` guard above.
                return;
            };
            lir::ExprKind::CollectionInsert {
                base: Box::new(
                    lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
                ),
                key: Box::new(
                    lir::ExprKind::GetTemp(len_slot, len_name).at(ctx.current_stmt_provenance),
                ),
                value: Box::new(
                    lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                        .at(ctx.current_stmt_provenance),
                ),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::Insert => lir::ExprKind::CollectionInsert {
            base: Box::new(lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance)),
            key: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
            value: Box::new(
                lir::ExprKind::GetTemp(arg_slots[1].0, arg_slots[1].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::Remove => lir::ExprKind::CollectionRemove {
            base: Box::new(lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance)),
            key: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::RemoveAt => lir::ExprKind::SeqRemoveAt {
            base: Box::new(lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance)),
            index: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::Clear => lir::ExprKind::MapClear(Box::new(
            lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        ))
        .at(ctx.current_stmt_provenance),
        MutatorKind::Shuffle => lir::ExprKind::RandShuffle(Box::new(
            lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        ))
        .at(ctx.current_stmt_provenance),
        MutatorKind::Sort => lir::ExprKind::SeqSorted(Box::new(
            lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        ))
        .at(ctx.current_stmt_provenance),
        MutatorKind::SortBy => lir::ExprKind::SeqSortedBy {
            seq: Box::new(lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance)),
            cmp: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::HeapPush => lir::ExprKind::HeapPush {
            seq: Box::new(lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance)),
            value: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
    };

    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(c_slot, c_name),
            op: AssignOp::Set,
            value: new_container,
        },
        ctx.current_stmt_provenance,
    ));
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::TakeTemp(c_slot, c_name).at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
}

/// Struct-field-projection sibling of [`lower_bare_mutator`] (issue #1495):
/// `push`/`insert`/`remove`/… whose lvalue is a single-level struct-field
/// projection (`push(a.items, v)`, `a: Bag`, `Bag.items: Array<int>`) — a
/// bare `ident.ident` chain, which always parses as one multi-segment
/// `hir::Expr::Path`, never a `hir::Expr::FieldAccess` (see
/// `try_lower_field_assignment`'s doc for why).
///
/// #1495 shipped this reading `current = root.field` via an ordinary
/// *cloning* `RecordGet`, leaving the root record fully intact until the
/// very end. That meant the field's `Arc` was always doubly referenced by
/// the time the RMW ran — once still embedded in the intact root, once in
/// `current`'s own temp — so `array_make_mut`/`map_make_mut` always saw
/// `strong_count >= 2` and paid the O(n) copy on *every* call: an O(n²)
/// loop-append cliff one field deeper than #576 closed (issue #2123). There
/// is still no dedicated field-level "take" opcode — the fix below answers
/// #2123's ask without adding one, using only the existing `RecordSet` to
/// null out the record's *own* reference to the field immediately after
/// taking the root, so nothing but `current`'s temp holds the field's `Arc`
/// by the time the RMW mutates it:
///
/// 1. The mutator's own args (key/value), evaluated once each — mirrors
///    `lower_bare_mutator`'s step 1, since any of them may reference the
///    root or the field by name and both are still intact.
/// 2. `current = root.field`, via a non-taking `RecordGet` (the fault
///    pre-check — proves root is genuinely a record with this field,
///    exactly like `lower_single_level_field_write`'s `current`) — also
///    `push`'s key (`CollectionLen(current)`), read here while the field's
///    current value is still cheaply at hand. Root is still fully intact.
/// 3. **De-alias (issue #2123's fix)**: take the root, overwrite *its own*
///    copy of the mutated field with `Value::Null` via `RecordSet`, and
///    write this "husk" record straight back into `root_target` —
///    *before* the RMW below runs. This drops the record's own reference
///    to the field's `Arc`, so `current`'s temp becomes the sole owner
///    whenever nothing else aliases the field specifically (the ordinary,
///    non-shared case) — closing the cliff. Writing the husk back
///    immediately (rather than holding it in a temp until step 5) means a
///    fault in step 4 leaves `root_target` a *structurally valid record*
///    with only this one field blown away to `Value::Null` — a narrower,
///    field-scoped version of `lower_bare_mutator`'s already-ratified,
///    tested "fault leaves the root holding `Value::Null`" trade-off
///    (`fault_during_insert_leaves_root_null` et al.,
///    `crates/internal/brink-test-harness/tests/take_rmw.rs`), not a new
///    kind of risk — see the mirrored field-scoped tests in
///    `field_mutator_take_rmw.rs`.
/// 4. The mutator's RMW expansion (`CollectionInsert`/`CollectionRemove`/…)
///    runs against `current`'s temp, now uniquely owned by construction
///    whenever nothing else aliases the field — `array_make_mut`/
///    `map_make_mut` mutates in place instead of COW-copying. This can
///    still fault on an author-supplied key/index (`insert`/`remove`/
///    `remove_at`/`sort_by`/…), which is exactly the field-scoped
///    `Value::Null` trade-off step 3 sets up for.
/// 5. The root (the husk from step 3) is taken again, the mutated field
///    written back via `RecordSet`, and the result written back into
///    `root_target`. This second take/`RecordSet` pair stays cheap even
///    when the record itself is shared (e.g. `b = a`): step 3 already
///    forked the record's own field vector once if that was needed, so by
///    this point the husk is uniquely owned and this `record_make_mut` is
///    free (an `Arc::make_mut` uniqueness check, not a copy).
#[expect(
    clippy::too_many_lines,
    reason = "mirrors lower_bare_mutator's own per-MutatorKind RMW dispatch, \
              plus the field-projection take/RecordSet/write-back steps —\
              now twice, once to de-alias the field before the RMW runs and \
              once to write the mutated field back — lower_single_level_field_write \
              needs a single instance of for a plain field write; reads \
              better as one function than split across an arbitrary line \
              boundary"
)]
fn lower_field_mutator(
    kind: MutatorKind,
    path: &hir::Path,
    head_info: &crate::symbols::SymbolInfo,
    args: &[hir::Expr],
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) {
    #[expect(
        clippy::indexing_slicing,
        reason = "caller already proved path.segments.len() == 2"
    )]
    let field_name = path.segments[1].text.clone();
    #[expect(
        clippy::indexing_slicing,
        reason = "caller already proved path.segments.len() == 2"
    )]
    let head_name = path.segments[0].text.clone();

    let (root_target, root_shape) = match head_info.kind {
        SymbolKind::Variable | SymbolKind::Constant => {
            // Issue #2201: `CONST c = ...; ~ { push(c.items, 1) }` — same
            // hole and same fix as `lower_single_level_field_write`'s
            // identical arm; see that function's comment and
            // `stmts::reject_const_write`'s doc.
            if super::stmts::reject_const_write(head_info, path.range, ctx) {
                return;
            }
            (
                lir::AssignTarget::Global(head_info.id),
                ctx.global_shape(head_info.id),
            )
        }
        SymbolKind::Param | SymbolKind::Temp => {
            let Some(slot) = ctx.temp_slot(&head_name) else {
                return;
            };
            // Issue #2122: `if get(bag) as b { push(b.items, 1) }` — same
            // hole and same fix as `lower_single_level_field_write`'s
            // identical arm; see that function's comment and
            // `stmts::reject_as_binding_write`'s doc.
            if super::stmts::reject_as_binding_write(slot, &head_name, path.range, ctx) {
                return;
            }
            let name_id = ctx.names.intern(&head_name);
            (lir::AssignTarget::Temp(slot, name_id), ctx.temp_shape(slot))
        }
        // The caller only reaches here for these four kinds (mirrors
        // `lower_single_level_field_write`'s identical match).
        _ => return,
    };

    // `root_shape` is already a resolved shape `DefinitionId` (issue
    // #2238) — no referrer needed to look it up.
    let static_offset = if ctx.structs.type_mode == TypeMode::Strict {
        root_shape
            .and_then(|d| ctx.structs.shapes.get_by_def(d))
            .and_then(|shape| shape.field(&field_name))
            .map(|(offset, _)| offset)
    } else {
        None
    };
    let field = ctx.names.intern(&field_name);

    // 1. The mutator's own args (key/value), evaluated once each — root and
    //    field both still intact.
    let arg_slots: Vec<(u16, brink_format::NameId)> = args[1..]
        .iter()
        .map(|a| {
            let v = lower_expr(a, ctx);
            declare_synthetic("__arg", v, ctx, out)
        })
        .collect();

    // 2. `current = root.field`, ALWAYS computed via a non-taking read (the
    //    fault pre-check, exactly like `lower_single_level_field_write`).
    let current = lir::ExprKind::RecordGet {
        base: Box::new(get_expr_for_target(
            &root_target,
            ctx.current_stmt_provenance,
        )),
        field,
        static_offset,
    }
    .at(ctx.current_stmt_provenance);
    let (current_slot, current_name) = declare_synthetic("__current", current, ctx, out);
    // Same `ctx`-vs-closure-capture reason as `lower_bare_mutator`'s own
    // `container` closure above.
    let stmt_prov = ctx.current_stmt_provenance;
    let container = move || lir::ExprKind::GetTemp(current_slot, current_name).at(stmt_prov);

    // `push`'s fault pre-check doubles as its key (see `lower_bare_mutator`'s
    // doc) — read from the field's current value, before anything is taken.
    let push_len = matches!(kind, MutatorKind::Push).then(|| {
        declare_synthetic(
            "__len",
            lir::ExprKind::CollectionLen(Box::new(container())).at(ctx.current_stmt_provenance),
            ctx,
            out,
        )
    });

    // 3. De-alias (issue #2123): take the root, null out *its own* copy of
    //    the field via `RecordSet`, write the husk straight back into
    //    `root_target` — before the RMW below ever runs. After this,
    //    `current_slot` is the field's sole owner whenever nothing else
    //    aliases it, which is the entire point of this fix (see the
    //    function doc's step 3).
    let (dealias_slot, dealias_name) = declare_synthetic(
        "__c",
        take_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    );
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(dealias_slot, dealias_name),
            op: AssignOp::Set,
            value: lir::ExprKind::RecordSet {
                base: Box::new(
                    lir::ExprKind::TakeTemp(dealias_slot, dealias_name)
                        .at(ctx.current_stmt_provenance),
                ),
                field,
                static_offset,
                value: Box::new(lir::ExprKind::Null.at(ctx.current_stmt_provenance)),
            }
            .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target.clone(),
            op: AssignOp::Set,
            value: lir::ExprKind::TakeTemp(dealias_slot, dealias_name)
                .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));

    // The RMW's own mutating operand takes `current_slot` (issue #2123) —
    // `container()` above is a *cloning* `GetTemp`, deliberately kept for
    // `push_len`'s pre-mutation read, but feeding that same clone into the
    // mutate step itself would leave `current_slot`'s own copy of the field
    // as a second, un-consumed owner at exactly the moment
    // `array_make_mut`/`map_make_mut` runs — recreating the cliff step 3
    // just closed, independent of the record's own reference. Taking it
    // instead means the value handed to the opcode is `current_slot`'s
    // *only* reference, so uniqueness (and step 3's de-alias) is what
    // `array_make_mut` actually sees.
    let take_container =
        || lir::ExprKind::TakeTemp(current_slot, current_name).at(ctx.current_stmt_provenance);

    let new_field = match kind {
        MutatorKind::Push => {
            let Some((len_slot, len_name)) = push_len else {
                // Structurally unreachable: `push_len` is always `Some` for
                // `MutatorKind::Push` by the `matches!` guard above.
                return;
            };
            lir::ExprKind::CollectionInsert {
                base: Box::new(take_container()),
                key: Box::new(
                    lir::ExprKind::GetTemp(len_slot, len_name).at(ctx.current_stmt_provenance),
                ),
                value: Box::new(
                    lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                        .at(ctx.current_stmt_provenance),
                ),
            }
            .at(ctx.current_stmt_provenance)
        }
        MutatorKind::Insert => lir::ExprKind::CollectionInsert {
            base: Box::new(take_container()),
            key: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
            value: Box::new(
                lir::ExprKind::GetTemp(arg_slots[1].0, arg_slots[1].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::Remove => lir::ExprKind::CollectionRemove {
            base: Box::new(take_container()),
            key: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::RemoveAt => lir::ExprKind::SeqRemoveAt {
            base: Box::new(take_container()),
            index: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::Clear => {
            lir::ExprKind::MapClear(Box::new(take_container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::Shuffle => {
            lir::ExprKind::RandShuffle(Box::new(take_container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::Sort => {
            lir::ExprKind::SeqSorted(Box::new(take_container())).at(ctx.current_stmt_provenance)
        }
        MutatorKind::SortBy => lir::ExprKind::SeqSortedBy {
            seq: Box::new(take_container()),
            cmp: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
        MutatorKind::HeapPush => lir::ExprKind::HeapPush {
            seq: Box::new(take_container()),
            value: Box::new(
                lir::ExprKind::GetTemp(arg_slots[0].0, arg_slots[0].1)
                    .at(ctx.current_stmt_provenance),
            ),
        }
        .at(ctx.current_stmt_provenance),
    };

    // 4. Materialize the RMW result into its own temp — reads only
    //    `current` (now uniquely owned whenever nothing else aliases the
    //    field, per step 3 above) and the arg temps, never the root. Any
    //    fault it raises (an out-of-range `remove_at`, an absent `remove`
    //    key, …) leaves `root_target` holding the step-3 husk — a
    //    structurally valid record missing only this one field, per the
    //    function doc's field-scoped trade-off.
    let (new_slot, new_name) = declare_synthetic("__new", new_field, ctx, out);

    // 5. Take the root (the husk from step 3) back, write the mutated
    //    field via `RecordSet`, write the resulting record back. `new_slot`
    //    is taken, not cloned (issue #2123): this statement is its only
    //    remaining use, but a loop body is the *same* compiled statement
    //    re-executed every iteration, so a `GetTemp` here would leave
    //    `new_slot` holding a live reference to this iteration's mutated
    //    array that outlives the statement — still there, unconsumed, the
    //    *next* time this same code runs and reads the field back out via
    //    step 2's `RecordGet`, permanently pinning every iteration's array
    //    at `strong_count == 2` and reintroducing the cliff this whole fix
    //    exists to close.
    let (writeback_slot, writeback_name) = declare_synthetic(
        "__c",
        take_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    );
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: lir::AssignTarget::Temp(writeback_slot, writeback_name),
            op: AssignOp::Set,
            value: lir::ExprKind::RecordSet {
                base: Box::new(
                    lir::ExprKind::TakeTemp(writeback_slot, writeback_name)
                        .at(ctx.current_stmt_provenance),
                ),
                field,
                static_offset,
                value: Box::new(
                    lir::ExprKind::TakeTemp(new_slot, new_name).at(ctx.current_stmt_provenance),
                ),
            }
            .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::TakeTemp(writeback_slot, writeback_name)
                .at(ctx.current_stmt_provenance),
        },
        ctx.current_stmt_provenance,
    ));
}

/// Resolve an lvalue expression (§5 — "a variable, temp, or indexed path")
/// for a collection mutator's first argument, materializing the same
/// take-chain shape indexed-assignment lowering uses (§4): every index
/// sub-expression evaluated once, left to right, then the container read
/// once at each chain level.
///
/// Returns `root_target` (the ultimate variable to write the mutated
/// container back into), the index temps (empty for a bare variable), and
/// the container-read temps: `c_slots[0]` is the root's current value,
/// `c_slots[k]` is the root indexed by `idx_slots[0..k]`, and
/// `c_slots.last()` — after all `idx_slots.len()` index levels — is the
/// container the mutator itself reads and replaces.
///
/// Contrast [`lower_indexed_assignment`]'s `c_slots`, which stops one level
/// short: an indexed *assignment* only ever needs to read as far as the
/// second-to-last level, since the deepest write is expressed via
/// `IndexSet` directly on that level. A mutator instead needs to read all
/// the way to the fully-indexed value, because that value — not one level
/// up — is the collection being mutated (`push(grid[y], v)` pushes onto the
/// array *at* `grid[y]`, not to some slot of `grid` itself).
///
/// Returns `None` only if `lvalue` isn't a `Path`/`Index` shape, or its root
/// doesn't resolve to an assignable target — both structurally unreachable
/// once the caller has checked [`is_lvalue_expr`] (a genuinely undeclared
/// root is already rejected by the analyzer's E025 before lowering runs).
fn lower_lvalue_container_chain(
    lvalue: &hir::Expr,
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<lir::Stmt>,
) -> Option<LvalueContainerChain> {
    let (root_expr, indices_hir) = match lvalue {
        hir::Expr::Index(idx) => flatten_index_chain(idx),
        hir::Expr::Path(_) => (lvalue, Vec::new()),
        _ => return None,
    };
    // Issue #2121: `push(a.items[0], v)` — the root of the index chain is
    // itself a struct-field projection (`a.items`). See
    // `reject_field_projection_index_root`'s doc for why this must be
    // checked *before* `lower_assign_target` gets a chance to silently
    // misroute it onto the root `a`. Returning `None` here reaches the
    // caller's (`lower_mutator_call`) "structurally unreachable" `else`
    // branch, which is now reachable *for this one diagnosed reason* — it
    // returns without pushing anything, which is correct: the diagnostic
    // already emitted is the handling.
    if reject_field_projection_index_root(root_expr, ctx, None) {
        return None;
    }
    let root_target = super::stmts::lower_assign_target(root_expr, ctx)?;

    let idx_slots: Vec<(u16, brink_format::NameId)> = indices_hir
        .iter()
        .map(|e| {
            let v = lower_expr(e, ctx);
            declare_synthetic("__idx", v, ctx, out)
        })
        .collect();

    let mut c_slots: Vec<(u16, brink_format::NameId)> = vec![declare_synthetic(
        "__c",
        get_expr_for_target(&root_target, ctx.current_stmt_provenance),
        ctx,
        out,
    )];
    for k in 0..idx_slots.len() {
        let base =
            lir::ExprKind::GetTemp(c_slots[k].0, c_slots[k].1).at(ctx.current_stmt_provenance);
        let index =
            lir::ExprKind::GetTemp(idx_slots[k].0, idx_slots[k].1).at(ctx.current_stmt_provenance);
        let read = lir::ExprKind::Index {
            base: Box::new(base),
            index: Box::new(index),
        }
        .at(ctx.current_stmt_provenance);
        c_slots.push(declare_synthetic("__c", read, ctx, out));
    }

    Some((root_target, idx_slots, c_slots))
}

/// Cascade the write-back for a mutated container chain built by
/// [`lower_lvalue_container_chain`]: `c_slots.last()` must already hold the
/// mutated value (the caller assigns it there before calling this) — this
/// writes it back up through an `IndexSet` at each index level and finally
/// into `root_target`, mirroring `lower_indexed_assignment`'s steps 5-6. A
/// bare-variable lvalue (`idx_slots` empty) skips straight to the root
/// write.
fn writeback_lvalue_container_chain(
    root_target: lir::AssignTarget,
    idx_slots: &[(u16, brink_format::NameId)],
    c_slots: &[(u16, brink_format::NameId)],
    out: &mut Vec<lir::Stmt>,
    provenance: crate::Provenance,
) {
    for k in (0..idx_slots.len()).rev() {
        let Some(&(slot, name)) = c_slots.get(k) else {
            return;
        };
        let Some(&(next_slot, next_name)) = c_slots.get(k + 1) else {
            return;
        };
        let base = lir::ExprKind::GetTemp(slot, name).at(provenance);
        let index = lir::ExprKind::GetTemp(idx_slots[k].0, idx_slots[k].1).at(provenance);
        let inner = lir::ExprKind::GetTemp(next_slot, next_name).at(provenance);
        out.push(lir::Stmt::new(
            lir::StmtKind::Assign {
                target: lir::AssignTarget::Temp(slot, name),
                op: AssignOp::Set,
                value: lir::ExprKind::IndexSet {
                    base: Box::new(base),
                    index: Box::new(index),
                    value: Box::new(inner),
                }
                .at(provenance),
            },
            provenance,
        ));
    }
    let Some(&(root_slot, root_name)) = c_slots.first() else {
        return;
    };
    out.push(lir::Stmt::new(
        lir::StmtKind::Assign {
            target: root_target,
            op: AssignOp::Set,
            value: lir::ExprKind::GetTemp(root_slot, root_name).at(provenance),
        },
        provenance,
    ));
}

#[cfg(test)]
mod mutator_kind_tests {
    use super::MutatorKind;

    /// Issue #2863 review: iterates [`MutatorKind::ALL`] — an exhaustively
    /// built array (a 10th variant that isn't added to `ALL`/`name` is a
    /// compile error, not a silent gap) — rather than a hardcoded name
    /// list written inside the test itself, which a prior version of this
    /// test did and which a new `MutatorKind` variant could silently
    /// escape.
    ///
    /// Checks both `from_name` is a true inverse of `name` (round-trips
    /// back to the same variant) and [`MutatorKind::from_name`]'s own doc
    /// claim that its names are "a subset of
    /// `super::expr::is_t1b_stdlib_name`" — mechanically checked here
    /// rather than trusted. A name recognized as a mutator but *not* a
    /// real T1b stdlib name would mean a statement-position call to it
    /// silently takes the mutator RMW path instead of falling through to
    /// ordinary call lowering (or an E025 for a genuinely unresolved
    /// name) — the exact "one copy edited, the other forgotten" drift
    /// shape this issue is about, just with a subset relationship instead
    /// of an equality one.
    #[test]
    fn every_mutator_name_is_a_real_t1b_stdlib_name() {
        for kind in MutatorKind::ALL {
            let name = kind.name();
            assert_eq!(
                MutatorKind::from_name(name),
                Some(kind),
                "`{name}` (MutatorKind::{kind:?}) should round-trip through from_name"
            );
            assert!(
                super::super::expr::is_t1b_stdlib_name(name),
                "`{name}` is recognized as a mutator but is_t1b_stdlib_name doesn't know it \
                 — MutatorKind::from_name has drifted out of the subset its own doc claims"
            );
        }
    }
}