daml-fmt 0.7.4

A canonical code formatter for the Daml smart-contract language, built on daml-parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
//! AST-driven canonical layout.
//!
//! This is an own-design canonical layout built from the daml-parser AST.
//! We do NOT aim to match an external formatter baseline: the formatter makes
//! its own consistent layout decisions. This is the shipping backend behind
//! `format_source`.
//!
//! Main mechanism:
//!   1. Walk the AST; every node carries a byte `Span`.
//!   2. For a layout block, reindent ONLY the block's child lines so the anchor
//!      construct lands at its canonical column. Current passes cover
//!      module/import continuations, choices, declarations, guards/where
//!      bindings, record updates, `try`/`catch`, explicit tuple/list
//!      continuations, `do`, `if`, `case`, `let-in`, constructor `with`, and
//!      template/interface bodies. The anchor line itself is never moved, which
//!      makes each rule a fixpoint: a second pass computes delta 0. Children
//!      shift by one uniform delta, so the block's internal structure (and any
//!      nested blocks) ride along. A `template`/`interface` body is the one
//!      STRUCTURED rule: a template's `with`/`where` keywords go to
//!      `head_col + 2` and the field / signatory-choice-decl blocks to
//!      `head_col + 4` (two different deltas), so a 4-space ladder collapses to
//!      the canonical 2-space one; an interface's inline-`where` body sits at
//!      `head_col + 2`.
//!   3. Comments are sacred: comment lines are never measured-from and never
//!      shifted (CLAUDE.md). Block-comment interiors are trivia, untouched.
//!   4. Gate pure reindent candidates on `same_tokens` = identical LAID-OUT
//!      token stream (offside virtuals included) ⇒ identical parse ⇒ identical
//!      desugar. Any accepted pure reindent is desugar-safe BY CONSTRUCTION.
//!   5. Fall back to the input (verbatim) when the gate rejects or a node is
//!      not modeled.
//!
//! On top of the structural pass we compose import organization and expression
//! layout rewrites that intentionally change layout form. Those rules are
//! covered by focused tests and the desugar/idempotence corpus verification.
//! Final whitespace + colon-spacing normalization remains token-gated
//! (`crate::normalize_gaps`).

use crate::{FormatRule, ImportOrder};
use daml_parser::ast::{
    Alt, ChoiceDecl, Decl, DoStmt, Expr, FieldAssign, GuardQualifier, Module, Span,
    TemplateBodyDecl, TypeAnnotation,
};
use daml_parser::lexer::TriviaKind;
use daml_syntax::{SourceFile, SourceTokens};
use std::ops::{Add, AddAssign, Index};

const INDENT: i64 = 2;
const INDENT_WIDTH: usize = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct ByteOffset(usize);

impl ByteOffset {
    const fn new(value: usize) -> Self {
        Self(value)
    }

    const fn get(self) -> usize {
        self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct LineIndex(usize);

impl LineIndex {
    const fn new(value: usize) -> Self {
        Self(value)
    }

    const fn get(self) -> usize {
        self.0
    }
}

impl Add<usize> for LineIndex {
    type Output = Self;

    fn add(self, rhs: usize) -> Self::Output {
        Self(self.0 + rhs)
    }
}

impl AddAssign<usize> for LineIndex {
    fn add_assign(&mut self, rhs: usize) {
        self.0 += rhs;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct IndentDelta(i64);

impl IndentDelta {
    const fn new(value: i64) -> Self {
        Self(value)
    }

    const fn get(self) -> i64 {
        self.0
    }

    const fn is_zero(self) -> bool {
        self.0 == 0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct LineStarts(Vec<usize>);

impl LineStarts {
    fn get(&self, line: LineIndex) -> Option<&usize> {
        self.0.get(line.get())
    }

    const fn len(&self) -> usize {
        self.0.len()
    }

    fn iter(&self) -> impl Iterator<Item = (LineIndex, usize)> + '_ {
        self.0
            .iter()
            .copied()
            .enumerate()
            .map(|(line, start)| (LineIndex::new(line), start))
    }
}

impl Index<LineIndex> for LineStarts {
    type Output = usize;

    fn index(&self, index: LineIndex) -> &Self::Output {
        &self.0[index.get()]
    }
}

/// Upper bound on structural-reindent iterations. The do-pass and if-pass can
/// unblock one another (the if-pass's `else` shift can remove a collision that
/// made the do-pass's gate reject), so they are iterated to a fixpoint for
/// single-call idempotence. Real inputs converge in 1-2; the cap only guards a
/// pathological non-convergence (the last output is still gate-safe).
const MAX_STRUCTURAL_PASSES: usize = 6;

/// Format with AST-driven structural reindents, layout-organizing rewrites, and
/// final token-gated gap normalization.
#[must_use]
pub fn format_ast(src: &str, options: crate::FormatOptions) -> String {
    if has_source_location_expectation(src) || has_trailing_with_comment(src) {
        return src.to_string();
    }

    let rules = options.rules();

    // Step 1: structural reindent, each family as its own gated pass.
    let mut base = if rules.contains(FormatRule::Layout) {
        run_structural_passes(src)
    } else {
        src.to_string()
    };

    // Step 2: layout-organizing rewrites that intentionally change layout
    // tokens while preserving the non-layout token stream. Import organization
    // is controlled separately because it reorders import declarations.
    if rules.contains(FormatRule::Imports) && options.import_order() == ImportOrder::Organize {
        base = organize_imports(&base);
    }
    if rules.contains(FormatRule::SyntaxNormalization) {
        base = rewrite_syntax_forms(&base, rules.contains(FormatRule::Layout));
        if rules.contains(FormatRule::Layout) {
            base = run_structural_passes(&base);
        }
    } else if rules.contains(FormatRule::Layout) {
        base = rewrite_pure_layout_forms(&base);
        base = run_structural_passes(&base);
    }

    // Step 3: whitespace + colon normalization on top, gated vs `base`.
    // same_tokens keeps this final spacing step from changing `base`'s parse.
    if rules.contains(FormatRule::Spacing) {
        let full = crate::normalize_gaps(&base, crate::ColonSpacingMode::Canonical);
        if same_tokens(&base, &full) {
            return full;
        }
        let ws_only = crate::normalize_gaps(&base, crate::ColonSpacingMode::Preserve);
        if same_tokens(&base, &ws_only) {
            return ws_only;
        }
    }
    base
}

fn run_structural_passes(src: &str) -> String {
    let mut base = src.to_string();
    for _ in 0..MAX_STRUCTURAL_PASSES {
        let mut next = base.clone();
        next = gated_module_pass(&next);
        next = gated_template_pass(&next);
        next = gated_choice_pass(&next);
        next = gated_type_def_pass(&next);
        next = gated_guard_pass(&next);
        next = gated_record_update_pass(&next);
        next = gated_try_pass(&next);
        next = gated_continuation_pass(&next);
        next = gated_do_pass(&next);
        next = gated_if_pass(&next);
        next = gated_case_pass(&next);
        next = gated_letin_pass(&next);
        next = gated_con_with_pass(&next);
        if next == base {
            break;
        }
        base = next;
    }
    base
}

/// Do-block reindent of `src`, accepted only if it passes the `same_tokens`
/// gate; otherwise `src` unchanged.
fn gated_do_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_do_blocks(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// if/then/else clause reindent of `src`, gated like the do-pass. Re-parses its
/// own input so spans match the (possibly already do-reindented) bytes.
fn gated_if_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_ifs(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// case-alternative reindent of `src`, gated like the do-pass.
fn gated_case_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_cases(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// `let … in` binding-block reindent of `src`, gated like the do-pass.
fn gated_letin_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_letins(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// `Con with` construction field-block reindent of `src`, gated like the do-pass.
fn gated_con_with_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_con_with(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Structured template-body reindent of `src`, gated like the do-pass.
fn gated_template_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_templates(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Module headers and import/export-list continuations.
fn gated_module_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_modules_and_imports(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Choice signature/parameter/controller/observer/body ladders.
fn gated_choice_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_choices(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Top-level `data`/`type`/`class`/`instance`/`exception` declaration ladders.
fn gated_type_def_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_type_defs(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Guard bars and their bodies in function equations.
fn gated_guard_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_guards(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Record UPDATE field blocks (`expr with`) distinct from constructor `Con with`.
fn gated_record_update_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_record_updates(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// `try`/`catch` body and handler ladders.
fn gated_try_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_tries(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Existing multiline expression continuations inside explicit delimiters.
fn gated_continuation_pass(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let r = reindent_continuations(src, source_file.module());
    if r != src && same_tokens(src, &r) {
        r
    } else {
        src.to_string()
    }
}

/// Count structural edit candidates over modeled AST constructs.
///
/// This powers `bin/coverage`; unlike the original do-only metric, it covers
/// every current AST layout family: do, if, case, let-in, constructor `with`,
/// and template/interface bodies. This is not a normalized coverage ratio: one
/// construct can produce multiple edits.
#[must_use]
pub fn coverage(src: &str) -> crate::FormatCoverage {
    let source_file = SourceFile::parse(src);
    let module = source_file.module();
    let formatted = do_block_edits(src, module).len()
        + module_edits(src, module).len()
        + choice_edits(src, module).len()
        + type_def_edits(src, module).len()
        + guard_edits(src, module).len()
        + record_update_edits(src, module).len()
        + try_edits(src, module).len()
        + continuation_edits(src, module).len()
        + if_edits(src, module).len()
        + case_edits(src, module).len()
        + letin_edits(src, module).len()
        + con_with_edits(src, module).len()
        + template_edits(src, module).len();
    crate::FormatCoverage {
        edit_candidates: formatted,
        modeled_constructs: modeled_construct_count(module),
    }
}

fn modeled_construct_count(module: &Module) -> usize {
    let mut count = 0usize;
    walk_module_expressions(module, &mut |e| match e {
        Expr::Do { .. } | Expr::If { .. } | Expr::Case { .. } | Expr::LetIn { .. } => count += 1,
        Expr::Record { base, fields, .. }
            if matches!(base.as_ref(), Expr::Con { .. }) && !fields.is_empty() =>
        {
            count += 1
        }
        _ => {}
    });
    for d in &module.decls {
        match d {
            Decl::Template(t) if !t.fields.is_empty() || !t.body.is_empty() => count += 1,
            Decl::Interface(i) if !i.methods.is_empty() || !i.choices.is_empty() => count += 1,
            Decl::TypeDef { .. } => count += 1,
            _ => {}
        }
    }
    count += module.imports.iter().filter(|i| !i.span.is_empty()).count();
    count
}

/// True iff `a` and `b` share the same LAID-OUT token stream (offside virtuals
/// included) — the desugar-safety gate.
fn same_tokens(a: &str, b: &str) -> bool {
    let a = SourceTokens::lex(a);
    let b = SourceTokens::lex(b);
    let la = a.laid_out_tokens();
    let lb = b.laid_out_tokens();
    la.len() == lb.len() && la.iter().zip(lb).all(|(x, y)| x.kind() == y.kind())
}

fn has_source_location_expectation(src: &str) -> bool {
    src.lines()
        .filter(|line| line.trim_start().starts_with("-- @"))
        .any(|line| {
            line.contains("range=")
                || line.contains(".location")
                || line.contains("start_line")
                || line.contains("start_col")
                || line.contains("end_line")
                || line.contains("end_col")
        })
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Replacement {
    start: usize,
    end: usize,
    text: String,
}

fn apply_replacements(src: &str, replacements: &[Replacement]) -> String {
    if replacements.is_empty() {
        return src.to_string();
    }
    let mut ordered = replacements.to_vec();
    ordered.sort_by_key(|r| (r.start, r.end));
    let mut out = String::with_capacity(src.len());
    let mut cursor = 0usize;
    for r in ordered {
        if r.start < cursor || r.start > r.end || r.end > src.len() {
            return src.to_string();
        }
        out.push_str(&src[cursor..r.start]);
        out.push_str(&r.text);
        cursor = r.end;
    }
    out.push_str(&src[cursor..]);
    out
}

fn rewrite_syntax_forms(src: &str, include_pure_layout: bool) -> String {
    let mut base = rewrite_line_forms(src);
    if include_pure_layout {
        base = rewrite_pure_layout_forms(&base);
    }
    let source_file = SourceFile::parse(&base);
    let mut replacements = Vec::new();
    collect_inline_expression_rewrites(&base, source_file.module(), &mut replacements);
    apply_replacements(&base, &replacements)
}

fn rewrite_pure_layout_forms(src: &str) -> String {
    let base = rewrite_line_infix_continuations(src);
    let base = rewrite_lambda_bodies(&base);
    rewrite_infix_continuations(&base)
}

fn rewrite_line_infix_continuations(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    let mut last_expr_indent: Option<usize> = None;
    for line in src.split_inclusive('\n') {
        let (body, ending) = split_line_ending(line);
        let leading = body.len() - body.trim_start_matches(' ').len();
        let trimmed = body[leading..].trim_end();
        if trimmed.is_empty() || trimmed.starts_with("--") {
            out.push_str(line);
            continue;
        }
        if let Some(comment_at) = body.find("--") {
            if !body[..comment_at].trim().is_empty() {
                out.push_str(line);
                continue;
            }
        }

        if starts_with_infix_operator(trimmed) {
            if let Some(prev) = last_expr_indent {
                let target = prev.saturating_add(INDENT_WIDTH);
                if leading != target {
                    out.push_str(&" ".repeat(target));
                    out.push_str(trimmed);
                    out.push_str(ending);
                    continue;
                }
            }
        }

        out.push_str(line);
        if !starts_with_infix_operator(trimmed)
            && !starts_with_word(trimmed, "module")
            && !starts_with_word(trimmed, "import")
            && !trimmed.ends_with(':')
        {
            last_expr_indent = Some(leading);
        }
    }
    out
}

fn rewrite_line_forms(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    for line in src.split_inclusive('\n') {
        let (body, ending) = split_line_ending(line);
        let leading = body.len() - body.trim_start_matches(' ').len();
        let trimmed = body[leading..].trim_end();
        if trimmed.is_empty() || trimmed.starts_with("--") {
            out.push_str(line);
            continue;
        }
        if let Some(comment_at) = body.find("--") {
            if !body[..comment_at].trim().is_empty() {
                out.push_str(line);
                continue;
            }
        }

        if let Some(rewritten) = rewrite_signature_line(body, ending) {
            out.push_str(&rewritten);
            continue;
        }
        if let Some(rewritten) = rewrite_inline_let_line(body, ending) {
            out.push_str(&rewritten);
            continue;
        }
        if let Some(rewritten) = rewrite_long_application_line(body, ending) {
            out.push_str(&rewritten);
            continue;
        }

        out.push_str(line);
    }
    out
}

fn split_line_ending(line: &str) -> (&str, &str) {
    line.strip_suffix("\r\n").map_or_else(
        || {
            line.strip_suffix('\n')
                .map_or((line, ""), |body| (body, "\n"))
        },
        |body| (body, "\r\n"),
    )
}

fn rewrite_signature_line(body: &str, ending: &str) -> Option<String> {
    let leading = body.len() - body.trim_start_matches(' ').len();
    let trimmed = body[leading..].trim_end();
    let colon = trimmed.find(':')?;
    if trimmed[..colon].contains('=') {
        return None;
    }
    let name = trimmed[..colon].trim();
    if name.is_empty() || name.contains(' ') {
        return None;
    }
    let ty = trimmed[colon + 1..].trim();
    let arrow_count = ty.matches("->").count();
    if arrow_count < 3 && trimmed.chars().count() <= 80 {
        return None;
    }
    let indent = " ".repeat(leading);
    let parts = split_top_level_arrows(ty)?;
    if parts.len() < 2 {
        return None;
    }
    let mut out = format!("{indent}{name}:");
    for (idx, part) in parts.iter().enumerate() {
        out.push_str(ending);
        out.push_str(&indent);
        out.push_str("  ");
        if idx > 0 {
            out.push_str("-> ");
        }
        out.push_str(part);
    }
    out.push_str(ending);
    Some(out)
}

fn split_top_level_arrows(ty: &str) -> Option<Vec<&str>> {
    let bytes = ty.as_bytes();
    let mut parts = Vec::new();
    let mut start = 0usize;
    let mut depth = 0i32;
    let mut i = 0usize;
    while i + 1 < bytes.len() {
        match bytes[i] {
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b'-' if bytes[i + 1] == b'>' && depth == 0 => {
                let part = ty[start..i].trim();
                if part.is_empty() {
                    return None;
                }
                parts.push(part);
                i += 2;
                start = i;
                continue;
            }
            _ => {}
        }
        if depth < 0 {
            return None;
        }
        i += 1;
    }
    let part = ty[start..].trim();
    if part.is_empty() {
        return None;
    }
    parts.push(part);
    Some(parts)
}

fn rewrite_inline_let_line(body: &str, ending: &str) -> Option<String> {
    let leading = body.len() - body.trim_start_matches(' ').len();
    let trimmed = body[leading..].trim_end();
    let marker = " = let ";
    let let_at = trimmed.find(marker)? + " = ".len();
    let prefix = trimmed[..let_at].trim_end();
    let rest = &trimmed[let_at + "let ".len()..];
    let in_at = rest.rfind(" in ")?;
    let bindings = &rest[..in_at];
    let body_expr = rest[in_at + " in ".len()..].trim();
    if !bindings.contains(';') {
        return None;
    }
    let indent = " ".repeat(leading.saturating_add(INDENT_WIDTH));
    let nested = " ".repeat(leading.saturating_add(2 * INDENT_WIDTH));
    let mut out = format!("{}{}{}", " ".repeat(leading), prefix, ending);
    out.push_str(&indent);
    out.push_str("let");
    out.push_str(ending);
    for binding in bindings.split(';').map(str::trim).filter(|b| !b.is_empty()) {
        out.push_str(&nested);
        out.push_str(binding);
        out.push_str(ending);
    }
    out.push_str(&indent);
    out.push_str("in ");
    out.push_str(body_expr);
    out.push_str(ending);
    Some(out)
}

fn rewrite_long_application_line(body: &str, ending: &str) -> Option<String> {
    let leading = body.len() - body.trim_start_matches(' ').len();
    let trimmed = body[leading..].trim_end();
    let marker = " = ";
    let eq_at = trimmed.find(marker)?;
    let prefix = trimmed[..eq_at + marker.len() - 1].trim_end();
    let rhs = trimmed[eq_at + marker.len()..].trim();
    if rhs.contains('"')
        || rhs.chars().any(|c| {
            matches!(
                c,
                '+' | '*'
                    | '/'
                    | '<'
                    | '>'
                    | '='
                    | ';'
                    | '\\'
                    | '('
                    | ')'
                    | '['
                    | ']'
                    | '{'
                    | '}'
                    | ','
            )
        })
    {
        return None;
    }
    if rhs.chars().any(|c| matches!(c, '\''))
        && rhs.split_whitespace().any(|part| part.starts_with('\''))
    {
        return None;
    }
    let parts: Vec<_> = rhs.split_whitespace().collect();
    if parts.len() < 7 {
        return None;
    }
    if parts[0]
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_uppercase())
    {
        return None;
    }
    let indent = " ".repeat(leading.saturating_add(INDENT_WIDTH));
    let nested = " ".repeat(leading.saturating_add(2 * INDENT_WIDTH));
    let mut out = format!("{}{}{}", " ".repeat(leading), prefix, ending);
    out.push_str(&indent);
    out.push_str(parts[0]);
    out.push_str(ending);
    for part in parts.iter().skip(1) {
        out.push_str(&nested);
        out.push_str(part);
        out.push_str(ending);
    }
    Some(out)
}

fn collect_inline_expression_rewrites(
    src: &str,
    module: &Module,
    replacements: &mut Vec<Replacement>,
) {
    for decl in &module.decls {
        let Decl::Function(fun) = decl else {
            continue;
        };
        for eq in &fun.equations {
            let line_starts = line_start_table(src);
            let eq_line = line_of(&line_starts, ByteOffset::new(eq.span.start_usize()));
            if leading_has_tab(src, line_starts[eq_line]) {
                continue;
            }
            let body_indent =
                indent_of_usize(src, &line_starts, eq_line).saturating_add(INDENT_WIDTH);
            collect_expr_rewrite(
                src,
                &eq.body,
                body_indent,
                RewriteLeadMode::LeadCandidate,
                replacements,
            );
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RewriteLeadMode {
    LeadCandidate,
    InlineOnly,
}

fn case_alts_are_simple_inline(alts: &[Alt]) -> bool {
    alts.iter().all(|alt| {
        alt.branches.len() == 1
            && alt.branches[0].guards.is_empty()
            && alt.where_bindings.is_empty()
    })
}

fn collect_case_alt_rewrites(
    src: &str,
    alts: &[Alt],
    indent: usize,
    rewrite_mode: RewriteLeadMode,
    replacements: &mut Vec<Replacement>,
) {
    for alt in alts {
        for branch in &alt.branches {
            for guard in &branch.guards {
                match guard {
                    GuardQualifier::Bool { expr, .. } | GuardQualifier::Pattern { expr, .. } => {
                        collect_expr_rewrite(src, expr, indent, rewrite_mode, replacements)
                    }
                    _ => {}
                }
            }
            collect_expr_rewrite(src, &branch.body, indent, rewrite_mode, replacements);
        }
        for wb in &alt.where_bindings {
            collect_expr_rewrite(src, &wb.expr, indent, rewrite_mode, replacements);
        }
    }
}

fn collect_expr_rewrite(
    src: &str,
    expr: &Expr,
    indent: usize,
    rewrite_mode: RewriteLeadMode,
    replacements: &mut Vec<Replacement>,
) {
    let span = expr.span();
    let line_starts = line_start_table(src);
    match expr {
        Expr::If {
            cond,
            then_branch,
            else_branch,
            ..
        } if rewrite_mode == RewriteLeadMode::LeadCandidate
            && same_line_span(src, span)
            && inline_if_parts_are_simple(src, cond, then_branch, else_branch) =>
        {
            let ind = " ".repeat(indent);
            let nested = " ".repeat(indent.saturating_add(INDENT_WIDTH));
            let mut text = String::new();
            if rewrite_mode == RewriteLeadMode::LeadCandidate {
                text.push('\n');
                text.push_str(&ind);
            }
            text.push_str("if ");
            text.push_str(src[cond.span().range()].trim());
            text.push('\n');
            text.push_str(&nested);
            text.push_str("then ");
            text.push_str(src[then_branch.span().range()].trim());
            text.push('\n');
            text.push_str(&nested);
            text.push_str("else ");
            text.push_str(src[else_branch.span().range()].trim());
            replacements.push(Replacement {
                start: span.start_usize(),
                end: span.end_usize(),
                text,
            });
        }
        Expr::Case {
            scrutinee, alts, ..
        } if rewrite_mode == RewriteLeadMode::LeadCandidate
            && same_line_span(src, span)
            && !alts.is_empty()
            && case_alts_are_simple_inline(alts) =>
        {
            let ind = " ".repeat(indent);
            let mut text = String::from("case ");
            text.push_str(src[scrutinee.span().range()].trim());
            text.push_str(" of");
            for alt in alts {
                text.push('\n');
                text.push_str(&ind);
                text.push_str(src[alt.pat.span().range()].trim());
                text.push_str(" -> ");
                text.push_str(src[alt.body.span().range()].trim());
            }
            replacements.push(Replacement {
                start: span.start_usize(),
                end: span.end_usize(),
                text,
            });
        }
        Expr::LetIn { bindings, body, .. }
            if rewrite_mode == RewriteLeadMode::LeadCandidate
                && same_line_span(src, span)
                && !bindings.is_empty() =>
        {
            let ind = " ".repeat(indent);
            let nested = " ".repeat(indent.saturating_add(INDENT_WIDTH));
            let mut text = String::new();
            if rewrite_mode == RewriteLeadMode::LeadCandidate {
                text.push('\n');
                text.push_str(&ind);
            }
            text.push_str("let");
            for binding in bindings {
                text.push('\n');
                text.push_str(&nested);
                text.push_str(src[binding.span.range()].trim());
            }
            text.push('\n');
            text.push_str(&ind);
            text.push_str("in ");
            text.push_str(src[body.span().range()].trim());
            replacements.push(Replacement {
                start: span.start_usize(),
                end: span.end_usize(),
                text,
            });
        }
        Expr::Record { base, fields, .. }
            if rewrite_mode == RewriteLeadMode::LeadCandidate
                && same_line_span(src, span)
                && src[span.range()].contains(';')
                && matches!(base.as_ref(), Expr::Con { .. })
                && fields.len() > 1 =>
        {
            let ind = " ".repeat(indent);
            let mut text = String::new();
            text.push_str(src[base.span().range()].trim());
            text.push_str(" with");
            for field in fields {
                text.push('\n');
                text.push_str(&ind);
                text.push_str(src[field.span().range()].trim());
            }
            replacements.push(Replacement {
                start: span.start_usize(),
                end: span.end_usize(),
                text,
            });
        }
        Expr::App { func, args, .. }
            if rewrite_mode == RewriteLeadMode::LeadCandidate
                && same_line_span(src, span)
                && args.len() >= 6
                && root_app_func(func).is_some()
                && app_args_are_simple(src, args) =>
        {
            let ind = " ".repeat(indent);
            let nested = " ".repeat(indent.saturating_add(INDENT_WIDTH));
            let mut text = String::new();
            if rewrite_mode == RewriteLeadMode::LeadCandidate {
                text.push('\n');
                text.push_str(&ind);
            }
            text.push_str(src[func.span().range()].trim());
            for arg in args {
                text.push('\n');
                text.push_str(&nested);
                text.push_str(src[arg.span().range()].trim());
            }
            replacements.push(Replacement {
                start: span.start_usize(),
                end: span.end_usize(),
                text,
            });
        }
        _ => {
            let expr_line = line_of(&line_starts, ByteOffset::new(span.start_usize()));
            let child_indent = if expr_line.get() < line_starts.len() {
                indent_of_usize(src, &line_starts, expr_line).saturating_add(INDENT_WIDTH)
            } else {
                indent.saturating_add(INDENT_WIDTH)
            };
            match expr {
                Expr::App { func, args, .. } => {
                    collect_expr_rewrite(
                        src,
                        func,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    for arg in args {
                        collect_expr_rewrite(
                            src,
                            arg,
                            child_indent,
                            RewriteLeadMode::InlineOnly,
                            replacements,
                        );
                    }
                }
                Expr::BinOp { lhs, rhs, .. } => {
                    collect_expr_rewrite(
                        src,
                        lhs,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    collect_expr_rewrite(
                        src,
                        rhs,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                }
                Expr::If {
                    cond,
                    then_branch,
                    else_branch,
                    ..
                } => {
                    collect_expr_rewrite(
                        src,
                        cond,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    collect_expr_rewrite(
                        src,
                        then_branch,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    collect_expr_rewrite(
                        src,
                        else_branch,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                }
                Expr::Case {
                    scrutinee, alts, ..
                } => {
                    collect_expr_rewrite(
                        src,
                        scrutinee,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    collect_case_alt_rewrites(
                        src,
                        alts,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                }
                Expr::LetIn { bindings, body, .. } => {
                    for binding in bindings {
                        collect_expr_rewrite(
                            src,
                            &binding.expr,
                            child_indent,
                            RewriteLeadMode::InlineOnly,
                            replacements,
                        );
                    }
                    collect_expr_rewrite(
                        src,
                        body,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                }
                Expr::Record { base, fields, .. } => {
                    collect_expr_rewrite(
                        src,
                        base,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                    for field in fields {
                        if let FieldAssign::Assign { value, .. } = field {
                            collect_expr_rewrite(
                                src,
                                value,
                                child_indent,
                                RewriteLeadMode::InlineOnly,
                                replacements,
                            );
                        }
                    }
                }
                Expr::Lambda { body, .. } | Expr::Neg { expr: body, .. } => {
                    collect_expr_rewrite(
                        src,
                        body,
                        child_indent,
                        RewriteLeadMode::InlineOnly,
                        replacements,
                    );
                }
                _ => {}
            }
        }
    }
}

fn root_app_func(expr: &Expr) -> Option<()> {
    matches!(expr, Expr::Var { .. }).then_some(())
}

fn inline_if_parts_are_simple(
    src: &str,
    cond: &Expr,
    then_branch: &Expr,
    else_branch: &Expr,
) -> bool {
    [cond.span(), then_branch.span(), else_branch.span()]
        .into_iter()
        .map(|span| src[span.range()].trim())
        .all(is_simple_inline_piece)
}

fn is_simple_inline_piece(text: &str) -> bool {
    !text.is_empty()
        && !text.contains('\n')
        && !text
            .chars()
            .any(|c| matches!(c, '(' | ')' | '{' | '}' | '[' | ']' | ';' | ','))
}

fn app_args_are_simple(src: &str, args: &[Expr]) -> bool {
    args.iter()
        .map(|arg| src[arg.span().range()].trim())
        .all(is_simple_app_arg)
}

fn is_simple_app_arg(text: &str) -> bool {
    !text.is_empty()
        && !text.contains('\n')
        && text
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '\'' | '.' | '-'))
}

fn same_line_span(src: &str, span: Span) -> bool {
    !src[span.range()].contains('\n')
}

fn has_trailing_with_comment(src: &str) -> bool {
    src.lines().any(|line| {
        let Some(comment_at) = line.find("--") else {
            return false;
        };
        line[..comment_at]
            .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '\''))
            .any(|word| word == "with")
    })
}

#[derive(Clone, Copy)]
struct BorrowedImport<'a> {
    group: ImportGroup,
    module_name: &'a str,
    text: &'a str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum ImportGroup {
    DamlStdlib,
    DaLibrary,
    LocalOrExternal,
}

fn organize_imports(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let module = source_file.module();
    if module.imports.len() < 2 {
        return src.to_string();
    }
    let Some(first) = module.imports.first() else {
        return src.to_string();
    };
    let Some(last) = module.imports.last() else {
        return src.to_string();
    };

    let line_starts = line_start_table(src);
    let start_line = line_of(&line_starts, ByteOffset::new(first.span.start_usize()));
    let end_line = line_of(
        &line_starts,
        ByteOffset::new(last.span.end_usize().saturating_sub(1)),
    );
    let block_start = line_starts[start_line];
    let block_end = *line_starts.get(end_line + 1).unwrap_or(&src.len());
    if src[block_start..block_end].contains("--")
        || src[block_start..block_end].contains("{-")
        || src[block_start..block_end]
            .lines()
            .any(|line| line.trim_start().starts_with('#'))
    {
        return src.to_string();
    }

    let mut imports: Vec<BorrowedImport<'_>> = module
        .imports
        .iter()
        .map(|imp| BorrowedImport {
            group: import_group(&imp.module_name),
            module_name: &imp.module_name,
            text: src[imp.span.range()].trim(),
        })
        .collect();
    imports.sort_by(|a, b| {
        a.group
            .cmp(&b.group)
            .then_with(|| a.module_name.cmp(b.module_name))
            .then_with(|| a.text.cmp(b.text))
    });

    let order_unchanged = module
        .imports
        .iter()
        .zip(&imports)
        .all(|(imp, sorted)| sorted.text == src[imp.span.range()].trim());
    if order_unchanged {
        return src.to_string();
    }

    let mut text = String::new();
    let mut prev_group = None;
    for entry in imports {
        if prev_group.is_some_and(|g| g != entry.group) {
            text.push('\n');
        }
        text.push_str(entry.text);
        text.push('\n');
        prev_group = Some(entry.group);
    }

    let mut out = String::with_capacity(src.len());
    out.push_str(&src[..block_start]);
    out.push_str(&text);
    out.push_str(&src[block_end..]);
    out
}

fn import_group(module_name: &str) -> ImportGroup {
    if module_name.starts_with("Daml.") {
        ImportGroup::DamlStdlib
    } else if module_name.starts_with("DA.") {
        ImportGroup::DaLibrary
    } else {
        ImportGroup::LocalOrExternal
    }
}

fn rewrite_lambda_bodies(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let module = source_file.module();
    let line_starts = line_start_table(src);
    let mut edits = Vec::new();
    walk_module_expressions(module, &mut |expr| {
        let Expr::Lambda { span, body, .. } = expr else {
            return;
        };
        let lambda_line = line_of(&line_starts, ByteOffset::new(span.start_usize()));
        let body_line = line_of(&line_starts, ByteOffset::new(body.span().start_usize()));
        if body_line <= lambda_line || leading_has_tab(src, line_starts[body_line]) {
            return;
        }
        let target = indent_of(src, &line_starts, lambda_line) + INDENT;
        let delta = target - indent_of(src, &line_starts, body_line);
        if delta != 0 {
            edits.push(Edit {
                child_start: ByteOffset::new(line_starts[body_line]),
                block_end: ByteOffset::new(body.span().end_usize()),
                delta: IndentDelta::new(delta),
            });
        }
    });
    if edits.is_empty() {
        return src.to_string();
    }
    let shifted = apply_shifts(src, &edits);
    if same_tokens(src, &shifted) {
        shifted
    } else {
        src.to_string()
    }
}

fn rewrite_infix_continuations(src: &str) -> String {
    let source_file = SourceFile::parse(src);
    let module = source_file.module();
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();
    for decl in &module.decls {
        let Decl::Function(fun) = decl else {
            continue;
        };
        for eq in &fun.equations {
            let body_span = eq.body.span();
            let first_line = line_of(&line_starts, ByteOffset::new(body_span.start_usize()));
            let target = indent_of(src, &line_starts, first_line) + INDENT;
            let mut line = first_line + 1;
            while line.get() < line_starts.len() && line_starts[line] < body_span.end_usize() {
                let Some(trimmed) = code_line_trimmed(src, &line_starts, &comments, line) else {
                    line += 1;
                    continue;
                };
                if starts_with_infix_operator(trimmed) {
                    push_code_line_edit(&mut edits, src, &line_starts, &comments, line, target);
                }
                line += 1;
            }
        }
    }
    if edits.is_empty() {
        return src.to_string();
    }
    let shifted = apply_shifts(src, &edits);
    if same_tokens(src, &shifted) {
        shifted
    } else {
        src.to_string()
    }
}

fn starts_with_infix_operator(trimmed: &str) -> bool {
    if trimmed.starts_with("->")
        || trimmed == ":"
        || trimmed
            .strip_prefix('|')
            .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
    {
        return false;
    }
    trimmed
        .chars()
        .next()
        .is_some_and(|c| matches!(c, '&' | '|' | '+' | '-' | '*' | '/' | '<' | '>' | '=' | ':'))
}

/// One reindent: shift every child line in `[child_start, block_end)` by `delta`.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Edit {
    child_start: ByteOffset,
    block_end: ByteOffset,
    delta: IndentDelta,
}

/// Apply every do-block edit: shift child-line indentation so each accepted
/// block's first real statement lands at `do_col + 2`.
fn reindent_do_blocks(src: &str, module: &Module) -> String {
    let edits = do_block_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

/// Compute the (non-zero) shift for each OUTERMOST, eligible do-block. Nested
/// do-blocks are skipped — they ride along inside their parent's child region.
fn do_block_edits(src: &str, module: &Module) -> Vec<Edit> {
    let mut do_block_spans: Vec<Span> = Vec::new();
    collect_do_block_spans(module, &mut do_block_spans);
    // Outermost first (smaller start, then larger end).
    do_block_spans.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));

    let line_starts = line_start_table(src);
    let comments = comment_spans(src);

    let mut edits: Vec<Edit> = Vec::new();
    let mut accepted: Vec<Span> = Vec::new();
    for do_span in do_block_spans {
        // Skip a do-block nested in one we already accepted (it rides along).
        if accepted.iter().any(|a| {
            a.start_usize() <= do_span.start_usize()
                && do_span.end_usize() <= a.end_usize()
                && *a != do_span
        }) {
            continue;
        }
        let do_line = line_of(&line_starts, ByteOffset::new(do_span.start_usize()));
        let do_indent = indent_of(src, &line_starts, do_line);
        // First real (non-blank, non-comment) statement line after the do line.
        let Some(first_stmt_line) =
            first_code_line_after(src, &line_starts, &comments, do_line, do_span.end_usize())
        else {
            continue; // inline `do stmt` — nothing on its own line; leave it
        };
        accepted.push(do_span);
        // Tab-indented bodies are left verbatim: we measure/emit only spaces,
        // so shifting would prepend spaces in front of tabs (silent mangling).
        if leading_has_tab(src, line_starts[first_stmt_line]) {
            continue;
        }
        let cur = indent_of(src, &line_starts, first_stmt_line);
        let delta = (do_indent + INDENT) - cur;
        if delta != 0 {
            edits.push(Edit {
                child_start: ByteOffset::new(line_starts[first_stmt_line]),
                block_end: ByteOffset::new(do_span.end_usize()),
                delta: IndentDelta::new(delta),
            });
        }
    }
    edits
}

/// Shift the leading-space indentation of every code line whose first content
/// byte lies in some edit's child region, by that edit's delta. Blank lines and
/// comment lines are never touched (comments are sacred). do-edits never
/// overlap (nested do-blocks are skipped), so any line matches at most one edit.
fn apply_shifts(src: &str, edits: &[Edit]) -> String {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut out = String::with_capacity(src.len());
    for (li, ls) in line_starts.iter() {
        let le = *line_starts.get(li + 1).unwrap_or(&src.len());
        let line = &src[ls..le];
        let trimmed = line.trim_start_matches(' ');
        let cur = line.len() - trimmed.len();
        let content_byte = ByteOffset::new(ls + cur);

        let delta = edits
            .iter()
            .find(|e| e.child_start <= content_byte && content_byte < e.block_end)
            .map(|e| e.delta)
            .unwrap_or(IndentDelta::new(0));

        if delta.is_zero()
            || line.trim().is_empty()
            || is_comment_line(&comments, content_byte.get())
            || leading_has_tab(src, ls)
        {
            out.push_str(line);
            continue;
        }
        let new = add_signed_to_usize_saturating(cur, delta.get());
        out.push_str(&" ".repeat(new));
        out.push_str(&line[cur..]);
    }
    out
}

// ---- comment-line awareness ------------------------------------------------

/// Byte spans of every comment (line + block); sorted by start.
fn comment_spans(src: &str) -> Vec<(usize, usize)> {
    let source_tokens = SourceTokens::lex(src);
    let mut v: Vec<(usize, usize)> = source_tokens
        .trivia()
        .iter()
        .filter(|t| matches!(t.kind(), TriviaKind::LineComment | TriviaKind::BlockComment))
        .map(|t| (t.start().get(), t.end().get()))
        .collect();
    v.sort_by_key(|&(s, _)| s);
    v
}

/// True if the line's first content byte falls inside a comment span.
fn is_comment_line(comments: &[(usize, usize)], content_byte: usize) -> bool {
    comments
        .iter()
        .any(|&(s, e)| s <= content_byte && content_byte < e)
}

// ---- line-table helpers ----------------------------------------------------

fn line_start_table(src: &str) -> LineStarts {
    LineStarts(
        std::iter::once(0)
            .chain(src.match_indices('\n').map(|(i, _)| i + 1))
            .collect(),
    )
}
fn line_of(line_starts: &LineStarts, byte: ByteOffset) -> LineIndex {
    match line_starts.0.binary_search(&byte.get()) {
        Ok(i) => LineIndex::new(i),
        Err(i) => LineIndex::new(i - 1),
    }
}
fn indent_of_usize(src: &str, line_starts: &LineStarts, line: LineIndex) -> usize {
    src[line_starts[line]..]
        .chars()
        .take_while(|&c| c == ' ')
        .count()
}
fn indent_of(src: &str, line_starts: &LineStarts, line: LineIndex) -> i64 {
    usize_to_i64_saturating(indent_of_usize(src, line_starts, line))
}
fn usize_to_i64_saturating(value: usize) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}
fn add_signed_to_usize_saturating(value: usize, delta: i64) -> usize {
    if delta >= 0 {
        value.saturating_add(usize::try_from(delta).unwrap_or(usize::MAX))
    } else {
        value.saturating_sub(usize::try_from(delta.unsigned_abs()).unwrap_or(usize::MAX))
    }
}
/// True if the line beginning at `line_start` has a tab anywhere in its leading
/// whitespace. Such lines are left verbatim (we measure/emit spaces only).
fn leading_has_tab(src: &str, line_start: usize) -> bool {
    src[line_start..]
        .chars()
        .take_while(|&c| c == ' ' || c == '\t')
        .any(|c| c == '\t')
}

/// First line strictly after `do_line` (and before `block_end`) that is neither
/// blank nor a comment line — i.e. the first real statement.
fn first_code_line_after(
    src: &str,
    line_starts: &LineStarts,
    comments: &[(usize, usize)],
    do_line: LineIndex,
    block_end: usize,
) -> Option<LineIndex> {
    let mut l = do_line + 1;
    while l.get() < line_starts.len() && line_starts[l] < block_end {
        let ls = line_starts[l];
        let le = *line_starts.get(l + 1).unwrap_or(&src.len());
        let line = &src[ls..le];
        let cur = line.len() - line.trim_start_matches(' ').len();
        if !line.trim().is_empty() && !is_comment_line(comments, ls + cur) {
            return Some(l);
        }
        l += 1;
    }
    None
}

fn next_code_line_starts_with_keyword(
    src: &str,
    line_starts: &LineStarts,
    comments: &[(usize, usize)],
    after_line: LineIndex,
    keyword: &str,
) -> Option<LineIndex> {
    let mut l = after_line + 1;
    while l.get() < line_starts.len() {
        let ls = line_starts[l];
        let le = *line_starts.get(l + 1).unwrap_or(&src.len());
        let line = &src[ls..le];
        let cur = line.len() - line.trim_start_matches(' ').len();
        let trimmed = line[cur..].trim_end();
        if line.trim().is_empty() || is_comment_line(comments, ls + cur) {
            l += 1;
            continue;
        }
        return trimmed
            .strip_prefix(keyword)
            .is_some_and(|rest| {
                rest.is_empty()
                    || rest
                        .chars()
                        .next()
                        .is_some_and(|c| !c.is_ascii_alphanumeric() && c != '_')
            })
            .then_some(l);
    }
    None
}

// ---- AST walks -------------------------------------------------------------

fn collect_do_block_spans(module: &Module, do_block_spans: &mut Vec<Span>) {
    walk_module_expressions(module, &mut |expr| {
        if let Expr::Do { span, .. } = expr {
            do_block_spans.push(*span);
        }
    });
}

/// Visit every expression in the module, pre-order. The generic walker behind
/// construct-specific rules (do, if/then/else, ...).
fn walk_module_expressions(module: &Module, f: &mut impl FnMut(&Expr)) {
    for decl in &module.decls {
        match decl {
            Decl::Function(fun) => {
                for eq in &fun.equations {
                    walk_expression(&eq.body, f);
                    for (g, b) in &eq.guards {
                        walk_expression(g, f);
                        walk_expression(b, f);
                    }
                    for wb in &eq.where_bindings {
                        walk_expression(&wb.expr, f);
                    }
                }
            }
            Decl::Template(t) => {
                for b in &t.body {
                    match b {
                        TemplateBodyDecl::Choice(c) => {
                            if let Some(body) = &c.body {
                                walk_expression(body, f);
                            }
                        }
                        TemplateBodyDecl::Ensure { expr, .. }
                        | TemplateBodyDecl::Key { expr, .. }
                        | TemplateBodyDecl::Maintainer { expr, .. } => walk_expression(expr, f),
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
}

fn walk_expression(expr: &Expr, f: &mut impl FnMut(&Expr)) {
    f(expr);
    match expr {
        Expr::App { func, args, .. } => {
            walk_expression(func, f);
            args.iter().for_each(|arg| walk_expression(arg, f));
        }
        Expr::BinOp { lhs, rhs, .. } => {
            walk_expression(lhs, f);
            walk_expression(rhs, f);
        }
        Expr::Neg { expr, .. } | Expr::Lambda { body: expr, .. } => walk_expression(expr, f),
        Expr::If {
            cond,
            then_branch,
            else_branch,
            ..
        } => {
            walk_expression(cond, f);
            walk_expression(then_branch, f);
            walk_expression(else_branch, f);
        }
        Expr::Case {
            scrutinee, alts, ..
        } => {
            walk_expression(scrutinee, f);
            for alt in alts {
                for branch in &alt.branches {
                    for guard in &branch.guards {
                        match guard {
                            GuardQualifier::Bool { expr, .. }
                            | GuardQualifier::Pattern { expr, .. } => walk_expression(expr, f),
                            _ => {}
                        }
                    }
                    walk_expression(&branch.body, f);
                }
                for wb in &alt.where_bindings {
                    walk_expression(&wb.expr, f);
                }
            }
        }
        Expr::Do { stmts, .. } => {
            for s in stmts {
                match s {
                    DoStmt::Bind { expr, .. } | DoStmt::Expr { expr, .. } => {
                        walk_expression(expr, f)
                    }
                    DoStmt::Let { bindings, .. } => {
                        bindings.iter().for_each(|b| walk_expression(&b.expr, f))
                    }
                    _ => {}
                }
            }
        }
        Expr::LetIn { bindings, body, .. } => {
            bindings.iter().for_each(|b| walk_expression(&b.expr, f));
            walk_expression(body, f);
        }
        Expr::Record { base, fields, .. } => {
            walk_expression(base, f);
            for fa in fields {
                if let FieldAssign::Assign { value, .. } = fa {
                    walk_expression(value, f);
                }
            }
        }
        Expr::Tuple { items, .. } | Expr::List { items, .. } => {
            items.iter().for_each(|item| walk_expression(item, f))
        }
        Expr::Try { body, handlers, .. } => {
            walk_expression(body, f);
            for handler in handlers {
                for branch in &handler.branches {
                    for guard in &branch.guards {
                        match guard {
                            GuardQualifier::Bool { expr, .. }
                            | GuardQualifier::Pattern { expr, .. } => walk_expression(expr, f),
                            _ => {}
                        }
                    }
                    walk_expression(&branch.body, f);
                }
                for wb in &handler.where_bindings {
                    walk_expression(&wb.expr, f);
                }
            }
        }
        Expr::LeftSection { operand, .. } | Expr::RightSection { operand, .. } => {
            walk_expression(operand, f);
        }
        _ => {}
    }
}

/// Byte offset of the standalone keyword `kw` in `src[from..to)`, skipping any
/// match that falls inside a comment. The region between two sibling expression
/// spans is only layout + the keyword, so a word-boundary scan is safe.
fn find_keyword(
    src: &str,
    from: usize,
    to: usize,
    kw: &str,
    comments: &[(usize, usize)],
) -> Option<usize> {
    let hay = &src[from..to.min(src.len())];
    let bytes = hay.as_bytes();
    let mut i = 0;
    while let Some(rel) = hay[i..].find(kw) {
        let at = i + rel;
        let before_ok = at == 0 || !is_ident_byte(bytes[at - 1]);
        let after = at + kw.len();
        let after_ok = after >= hay.len() || !is_ident_byte(bytes[after]);
        let abs = from + at;
        if before_ok && after_ok && !is_comment_line(comments, abs) {
            return Some(abs);
        }
        i = at + 1;
    }
    None
}

/// Reindent the `then` and `else` clauses of multi-line `if`/`then`/`else` so
/// each keyword lands at `if_col + 2`. Only a clause whose keyword starts its
/// own line is moved, and the whole clause (keyword line + its branch's
/// continuation lines) shifts by ONE uniform delta — the let-block trick — so
/// the branch's internal layout is preserved. `same_tokens` still gates it.
fn if_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);

    // (if_span, if_byte, cond_end, then_span, else_span), outermost first.
    let mut ifs: Vec<(Span, usize, usize, Span, Span)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::If {
            span,
            cond,
            then_branch,
            else_branch,
            ..
        } = e
        {
            ifs.push((
                *span,
                span.start_usize(),
                cond.span().end_usize(),
                then_branch.span(),
                else_branch.span(),
            ));
        }
    });
    ifs.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits: Vec<Edit> = Vec::new();
    let mut accepted: Vec<Span> = Vec::new();
    for (if_span, if_byte, cond_end, then_span, else_span) in ifs {
        // Skip an if nested in one we already claimed (it rides the outer shift).
        if accepted.iter().any(|a| {
            a.start_usize() <= if_span.start_usize()
                && if_span.end_usize() <= a.end_usize()
                && *a != if_span
        }) {
            continue;
        }
        accepted.push(if_span);

        let if_line = line_of(&line_starts, ByteOffset::new(if_byte));
        if leading_has_tab(src, line_starts[if_line]) {
            continue;
        }
        // Visual column of the `if` keyword on its line — count CHARACTERS, not
        // bytes, so a multibyte char before `if` does not over-indent (the shift
        // emits spaces and `indent_of` counts chars, so these must agree).
        let if_col = usize_to_i64_saturating(src[line_starts[if_line]..if_byte].chars().count());
        let target = if_col + INDENT;

        let then_byte = find_keyword(src, cond_end, then_span.start_usize(), "then", &comments);
        let else_byte = find_keyword(
            src,
            then_span.end_usize(),
            else_span.start_usize(),
            "else",
            &comments,
        );

        for (kw_byte, branch_end) in [
            (then_byte, then_span.end_usize()),
            (else_byte, else_span.end_usize()),
        ] {
            let Some(kw_byte) = kw_byte else { continue };
            let kw_line = line_of(&line_starts, ByteOffset::new(kw_byte));
            let ls = line_starts[kw_line];
            // Only move a clause whose keyword STARTS its line (leading spaces
            // only). An inline `if c then x else y` is left alone.
            if src[ls..kw_byte].chars().any(|c| c != ' ') {
                continue;
            }
            if leading_has_tab(src, ls) {
                continue;
            }
            let cur = indent_of(src, &line_starts, kw_line);
            let delta = target - cur;
            if delta != 0 {
                edits.push(Edit {
                    child_start: ByteOffset::new(ls),
                    block_end: ByteOffset::new(branch_end),
                    delta: IndentDelta::new(delta),
                });
            }
        }
    }
    edits
}

fn reindent_ifs(src: &str, module: &Module) -> String {
    let edits = if_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

/// Reindent the alternative block of a multi-line `case … of` so the alts land
/// at `case_line_indent + 2` (the same anchor convention as a `do`-block). The
/// whole alt block shifts by ONE uniform delta, so each alt's body — including
/// nested do/case/if — rides along; `same_tokens` rejects any shift that would
/// dedent the block below its offside requirement (e.g. a `case` hanging in a
/// `where` binding). Inline `case x of A -> …` alts and tab-indented blocks are
/// left verbatim. Mirrors `do_block_edits`.
fn case_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);

    // (case_span, first_alt_start, last_alt_end), outermost first.
    let mut cases: Vec<(Span, usize, usize)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::Case { span, alts, .. } = e {
            if let (Some(first), Some(last)) = (alts.first(), alts.last()) {
                cases.push((*span, first.span.start_usize(), last.span.end_usize()));
            }
        }
    });
    cases.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits: Vec<Edit> = Vec::new();
    let mut accepted: Vec<Span> = Vec::new();
    for (case_span, first_alt, last_alt_end) in cases {
        // Skip a case nested in one we already claimed (it rides the outer shift).
        if accepted.iter().any(|a| {
            a.start_usize() <= case_span.start_usize()
                && case_span.end_usize() <= a.end_usize()
                && *a != case_span
        }) {
            continue;
        }
        accepted.push(case_span);

        let case_line = line_of(&line_starts, ByteOffset::new(case_span.start_usize()));
        let alt_line = line_of(&line_starts, ByteOffset::new(first_alt));
        // Inline `case x of A -> …` (alts share the case line): leave verbatim.
        if alt_line <= case_line {
            continue;
        }
        if leading_has_tab(src, line_starts[case_line])
            || leading_has_tab(src, line_starts[alt_line])
        {
            continue;
        }
        let case_indent = indent_of(src, &line_starts, case_line);
        let cur = indent_of(src, &line_starts, alt_line);
        let delta = (case_indent + INDENT) - cur;
        if delta != 0 {
            edits.push(Edit {
                child_start: ByteOffset::new(line_starts[alt_line]),
                block_end: ByteOffset::new(last_alt_end),
                delta: IndentDelta::new(delta),
            });
        }
    }
    edits
}

fn reindent_cases(src: &str, module: &Module) -> String {
    let edits = case_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

/// Reindent the binding block of a `let … in` EXPRESSION so the bindings land at
/// `let_line_indent + 2` (the do/case convention). The bindings form a layout
/// block opened after `let`; the whole block shifts by ONE uniform delta, so
/// multi-line / multi-binding bodies ride along. `in` and the let body are left
/// alone; `same_tokens` rejects any shift whose result would relayout the block
/// (e.g. moving bindings off the `in` keyword's offside). Inline `let x = … in`
/// (binding shares the `let` line) and tab-indented blocks stay verbatim.
fn letin_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);

    // (letin_span, first_binding_start, last_binding_end), outermost first.
    let mut lets: Vec<(Span, usize, usize)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::LetIn { span, bindings, .. } = e {
            if let (Some(first), Some(last)) = (bindings.first(), bindings.last()) {
                lets.push((*span, first.span.start_usize(), last.span.end_usize()));
            }
        }
    });
    lets.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits: Vec<Edit> = Vec::new();
    let mut accepted: Vec<Span> = Vec::new();
    for (let_span, first_bind, last_bind_end) in lets {
        if accepted.iter().any(|a| {
            a.start_usize() <= let_span.start_usize()
                && let_span.end_usize() <= a.end_usize()
                && *a != let_span
        }) {
            continue;
        }
        accepted.push(let_span);

        let let_line = line_of(&line_starts, ByteOffset::new(let_span.start_usize()));
        let bind_line = line_of(&line_starts, ByteOffset::new(first_bind));
        // Inline `let x = … in …` (binding shares the let line): leave verbatim.
        if bind_line <= let_line {
            continue;
        }
        // Only canonicalize a LINE-LEADING `let`. For a mid-line `let` (`= let`,
        // `$ let`, a guard's `let`) the `in` keyword stays at the let-keyword
        // column while the bindings would anchor on the (smaller) line indent —
        // a mismatch. Unlike do/case (whose `name = do`/`= case` line-indent
        // convention is idiomatic), let-in needs `let` at line start for the
        // `bindings = let_indent + 2`, `in = let_indent` shape to line up.
        if src[line_starts[let_line]..let_span.start_usize()]
            .chars()
            .any(|c| c != ' ')
        {
            continue;
        }
        if leading_has_tab(src, line_starts[let_line])
            || leading_has_tab(src, line_starts[bind_line])
        {
            continue;
        }
        let let_indent = indent_of(src, &line_starts, let_line);
        let cur = indent_of(src, &line_starts, bind_line);
        let delta = (let_indent + INDENT) - cur;
        if delta != 0 {
            edits.push(Edit {
                child_start: ByteOffset::new(line_starts[bind_line]),
                block_end: ByteOffset::new(last_bind_end),
                delta: IndentDelta::new(delta),
            });
        }
    }
    edits
}

fn reindent_letins(src: &str, module: &Module) -> String {
    let edits = letin_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

/// Reindent the field block of a `Con with …` record CONSTRUCTION so the fields
/// land at `construction_line_indent + 2`. Only constructions (base is a bare
/// constructor `Con`) are touched here; record UPDATES (`expr with …`) are handled
/// by their own gated pass. Inline and tab-indented blocks stay verbatim. The
/// field block shifts by ONE uniform delta (so nested values ride along) and
/// `same_tokens` gates it. Mirrors the case rule.
fn con_with_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);

    // (record_span, base_end, first_field_start, last_field_end), outermost first.
    let mut recs: Vec<(Span, usize, usize, usize)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::Record {
            span, base, fields, ..
        } = e
        {
            // Construction only: base is a bare constructor.
            if !matches!(base.as_ref(), Expr::Con { .. }) {
                return;
            }
            if let (Some(first), Some(last)) = (fields.first(), fields.last()) {
                recs.push((
                    *span,
                    base.span().end_usize(),
                    first.span().start_usize(),
                    last.span().end_usize(),
                ));
            }
        }
    });
    recs.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits: Vec<Edit> = Vec::new();
    let mut accepted: Vec<Span> = Vec::new();
    for (rec_span, base_end, first_field, last_field_end) in recs {
        if accepted.iter().any(|a| {
            a.start_usize() <= rec_span.start_usize()
                && rec_span.end_usize() <= a.end_usize()
                && *a != rec_span
        }) {
            continue;
        }
        accepted.push(rec_span);

        let rec_line = line_of(&line_starts, ByteOffset::new(rec_span.start_usize()));
        let field_line = line_of(&line_starts, ByteOffset::new(first_field));
        // Inline `Con with a = 1` (first field shares the line): leave verbatim.
        if field_line <= rec_line {
            continue;
        }
        // Only when `with` sits on the base (`Con`) line — then anchoring the
        // fields at base_line_indent + 2 lines them up under the construction.
        // A split `Con\n  with\n    fields` (with on its own line) would put the
        // fields left of `with`, so leave it verbatim.
        match find_keyword(src, base_end, first_field, "with", &comments) {
            Some(w) if line_of(&line_starts, ByteOffset::new(w)) == rec_line => {}
            _ => continue,
        }
        if leading_has_tab(src, line_starts[rec_line])
            || leading_has_tab(src, line_starts[field_line])
        {
            continue;
        }
        let rec_indent = indent_of(src, &line_starts, rec_line);
        let cur = indent_of(src, &line_starts, field_line);
        let target = rec_indent + INDENT;
        if next_code_line_starts_with_keyword(
            src,
            &line_starts,
            &comments,
            line_of(
                &line_starts,
                ByteOffset::new(last_field_end.saturating_sub(1)),
            ),
            "where",
        )
        .is_some_and(|next_line| indent_of(src, &line_starts, next_line) <= target)
        {
            continue;
        }
        let delta = target - cur;
        if delta != 0 {
            edits.push(Edit {
                child_start: ByteOffset::new(line_starts[field_line]),
                block_end: ByteOffset::new(last_field_end),
                delta: IndentDelta::new(delta),
            });
        }
    }
    edits
}

fn reindent_con_with(src: &str, module: &Module) -> String {
    let edits = con_with_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

/// Shift a SINGLE line to `target` indent (for a `with`/`where` keyword line).
fn push_line_edit(edits: &mut Vec<Edit>, ls: &LineStarts, src: &str, line: LineIndex, target: i64) {
    if leading_has_tab(src, ls[line]) {
        return;
    }
    let delta = target - indent_of(src, ls, line);
    if delta != 0 {
        let end = *ls.get(line + 1).unwrap_or(&src.len());
        edits.push(Edit {
            child_start: ByteOffset::new(ls[line]),
            block_end: ByteOffset::new(end),
            delta: IndentDelta::new(delta),
        });
    }
}

/// Shift a block `[first_byte .. end_byte)` to `target`, anchored on its first
/// line — but only when that first line is its own line (line-leading, and below
/// `head_line`), so an inline `with f : T` / `template X with` is left alone.
fn push_block_edit(
    edits: &mut Vec<Edit>,
    ls: &LineStarts,
    src: &str,
    first_byte: usize,
    end_byte: usize,
    target: i64,
    head_line: LineIndex,
) {
    let first_line = line_of(ls, ByteOffset::new(first_byte));
    if first_line <= head_line {
        return;
    }
    // The first element must start its line (nothing but spaces before it).
    if src[ls[first_line]..first_byte].chars().any(|c| c != ' ') {
        return;
    }
    if leading_has_tab(src, ls[first_line]) {
        return;
    }
    let delta = target - indent_of(src, ls, first_line);
    if delta != 0 {
        edits.push(Edit {
            child_start: ByteOffset::new(ls[first_line]),
            block_end: ByteOffset::new(end_byte),
            delta: IndentDelta::new(delta),
        });
    }
}

/// Byte span of a template body declaration (the enum's variants each carry
/// their own span).
const fn body_decl_span(d: &TemplateBodyDecl) -> Span {
    match d {
        TemplateBodyDecl::Signatory { span, .. }
        | TemplateBodyDecl::Observer { span, .. }
        | TemplateBodyDecl::Ensure { span, .. }
        | TemplateBodyDecl::Key { span, .. }
        | TemplateBodyDecl::Maintainer { span, .. }
        | TemplateBodyDecl::Other { span, .. } => *span,
        TemplateBodyDecl::Choice(c) => c.span,
        TemplateBodyDecl::InterfaceInstance(i) => i.span,
        _ => Span::from_usize(0, 0),
    }
}

/// Structured `template` body reindent: the `with`/`where` keyword lines to
/// `template_indent + 2` and the field / signatory-choice-decl blocks to
/// `template_indent + 4`. Unlike a single uniform shift, the two DIFFERENT
/// deltas turn a 4-space ladder into the canonical 2-space one; choice bodies
/// (and any nested do-blocks) ride the decl-block shift and are then
/// canonicalized by the do-pass. `same_tokens` gates the whole candidate.
/// Reindent one keyword-introduced block (`with …` / `where …`): move the
/// keyword line to `kw_target` when it is on its OWN line (inline keywords like
/// `template X with` / `interface X where` stay put), and shift the block to
/// `body_target`. The two targets are passed in, not derived — a template is a
/// 2-level ladder (keywords at head + 2, contents at head + 4 even when the
/// keyword is inline, since the sibling block's keyword closes it), whereas an
/// interface's lone `where`-block sits at head + 2.
#[allow(clippy::too_many_arguments)]
fn reindent_keyword_block(
    edits: &mut Vec<Edit>,
    ls: &LineStarts,
    src: &str,
    comments: &[(usize, usize)],
    head_line: LineIndex,
    kw_target: i64,
    body_target: i64,
    kw: &str,
    kw_from: usize,
    block_first: usize,
    block_last_end: usize,
) {
    if let Some(w) = find_keyword(src, kw_from, block_first, kw, comments) {
        if line_of(ls, ByteOffset::new(w)) > head_line {
            push_line_edit(edits, ls, src, line_of(ls, ByteOffset::new(w)), kw_target);
        }
    }
    push_block_edit(
        edits,
        ls,
        src,
        block_first,
        block_last_end,
        body_target,
        head_line,
    );
}

fn template_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();
    for d in &module.decls {
        let head_byte = match d {
            Decl::Template(t) => t.span.start_usize(),
            Decl::Interface(i) => i.span.start_usize(),
            _ => continue,
        };
        let head_line = line_of(&line_starts, ByteOffset::new(head_byte));
        if leading_has_tab(src, line_starts[head_line]) {
            continue;
        }
        let head_indent = indent_of(src, &line_starts, head_line);
        let kw_target = head_indent + INDENT;

        match d {
            Decl::Template(t) => {
                // A template is a 2-level ladder: with/where at head + 2, their
                // contents at head + 4 (even an inline `template X with`, since
                // the `where` keyword at + 2 must close the with-block).
                let body_target = head_indent + 2 * INDENT;
                // with-block: field block, anchored on the `with` keyword.
                if let (Some(f0), Some(fl)) = (t.fields.first(), t.fields.last()) {
                    reindent_keyword_block(
                        &mut edits,
                        &line_starts,
                        src,
                        &comments,
                        head_line,
                        kw_target,
                        body_target,
                        "with",
                        t.span.start_usize(),
                        f0.span.start_usize(),
                        fl.span.end_usize(),
                    );
                }
                // where-block: signatory/choice decls, anchored on `where`.
                if let (Some(b0), Some(bl)) = (t.body.first(), t.body.last()) {
                    let b0_start = body_decl_span(b0).start;
                    let bl_end = body_decl_span(bl).end;
                    let where_from = t
                        .fields
                        .last()
                        .map(|f| f.span.end_usize())
                        .unwrap_or_else(|| t.span.start_usize());
                    reindent_keyword_block(
                        &mut edits,
                        &line_starts,
                        src,
                        &comments,
                        head_line,
                        kw_target,
                        body_target,
                        "where",
                        where_from,
                        b0_start.get(),
                        bl_end.get(),
                    );
                }
            }
            Decl::Interface(i) => {
                // Interface body = viewtype + methods + choices. `viewtype`
                // carries no span and sits first, so anchor the block on the
                // first CODE LINE after the head (which includes it) rather than
                // on the first method/choice — otherwise the viewtype would be
                // left behind and break the offside (the gate would just reject).
                let mut last_end = None;
                for s in i
                    .methods
                    .iter()
                    .map(|m| m.span)
                    .chain(i.choices.iter().map(|c| c.span))
                {
                    last_end = Some(
                        last_end.map_or_else(|| s.end_usize(), |e: usize| e.max(s.end_usize())),
                    );
                }
                if let Some(last_end) = last_end {
                    if let Some(fbl) =
                        first_code_line_after(src, &line_starts, &comments, head_line, last_end)
                    {
                        // An interface's lone `where`-block (where is inline on
                        // the head line) sits at head + 2.
                        reindent_keyword_block(
                            &mut edits,
                            &line_starts,
                            src,
                            &comments,
                            head_line,
                            kw_target,
                            head_indent + INDENT,
                            "where",
                            i.span.start_usize(),
                            line_starts[fbl],
                            last_end,
                        );
                    }
                }
            }
            _ => {}
        }
    }
    edits
}

fn reindent_templates(src: &str, module: &Module) -> String {
    let edits = template_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- module / import continuations ------------------------------------------

fn module_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();

    if !module.header.is_empty() {
        push_continuation_lines(
            &mut edits,
            src,
            &line_starts,
            &comments,
            module.header,
            INDENT,
        );
    }
    for imp in &module.imports {
        push_continuation_lines(&mut edits, src, &line_starts, &comments, imp.span, INDENT);
    }
    edits
}

fn reindent_modules_and_imports(src: &str, module: &Module) -> String {
    let edits = module_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

fn push_continuation_lines(
    edits: &mut Vec<Edit>,
    src: &str,
    ls: &LineStarts,
    comments: &[(usize, usize)],
    span: Span,
    offset: i64,
) {
    let head_line = line_of(ls, ByteOffset::new(span.start_usize()));
    let target = indent_of(src, ls, head_line) + offset;
    let mut line = head_line + 1;
    while line.get() < ls.len() && ls[line] < span.end_usize() {
        push_code_line_edit(edits, src, ls, comments, line, target);
        line += 1;
    }
}

// ---- choice internals --------------------------------------------------------

fn collect_choices<'a>(module: &'a Module, choices: &mut Vec<&'a ChoiceDecl>) {
    for decl in &module.decls {
        match decl {
            Decl::Template(t) => {
                for body in &t.body {
                    if let TemplateBodyDecl::Choice(c) = body {
                        choices.push(c);
                    }
                }
            }
            Decl::Interface(i) => choices.extend(i.choices.iter()),
            _ => {}
        }
    }
    choices.sort_by(|a, b| {
        a.span
            .start
            .cmp(&b.span.start)
            .then(b.span.end_usize().cmp(&a.span.end_usize()))
    });
}

fn choice_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut choices = Vec::new();
    collect_choices(module, &mut choices);

    let mut edits = Vec::new();
    for c in choices {
        let choice_line = line_of(&line_starts, ByteOffset::new(c.span.start_usize()));
        if leading_has_tab(src, line_starts[choice_line]) {
            continue;
        }
        let choice_indent = indent_of(src, &line_starts, choice_line);
        let clause_target = choice_indent + INDENT;
        let nested_target = choice_indent + 2 * INDENT;

        if let TypeAnnotation::Present(ty) = &c.return_ty {
            if let Some(colon) = find_symbol(
                src,
                c.span.start_usize(),
                ty.span().start_usize(),
                ":",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    colon,
                    ty.span().end_usize(),
                    clause_target,
                );
            }
        }

        if let (Some(first), Some(last)) = (c.params.first(), c.params.last()) {
            let kw_from = c
                .return_ty
                .as_type()
                .map_or_else(|| c.span.start_usize(), |t| t.span().end_usize());
            if let Some(w) = find_keyword(src, kw_from, first.span.start_usize(), "with", &comments)
            {
                let with_line = line_of(&line_starts, ByteOffset::new(w));
                let first_param_line =
                    line_of(&line_starts, ByteOffset::new(first.span.start_usize()));
                if first_param_line == with_line {
                    push_span_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        w,
                        last.span.end_usize(),
                        clause_target,
                    );
                } else {
                    push_line_edit(&mut edits, &line_starts, src, with_line, clause_target);
                    push_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        first.span.start_usize(),
                        last.span.end_usize(),
                        nested_target,
                        choice_line,
                    );
                }
            }
        }

        if let (Some(first), Some(last)) = (c.observers.first(), c.observers.last()) {
            if let Some(k) = find_keyword(
                src,
                c.span.start_usize(),
                first.span().start_usize(),
                "observer",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    k,
                    last.span().end_usize(),
                    clause_target,
                );
            }
        }
        if let (Some(first), Some(last)) = (c.controllers.first(), c.controllers.last()) {
            if let Some(k) = find_keyword(
                src,
                c.span.start_usize(),
                first.span().start_usize(),
                "controller",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    k,
                    last.span().end_usize(),
                    clause_target,
                );
            }
        }
        if let (Some(first), Some(last)) = (c.authority_exprs.first(), c.authority_exprs.last()) {
            if let Some(k) = find_keyword(
                src,
                c.span.start_usize(),
                first.span().start_usize(),
                "authority",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    k,
                    last.span().end_usize(),
                    clause_target,
                );
            }
        }

        if let Some(body) = &c.body {
            push_span_block_edit(
                &mut edits,
                &line_starts,
                src,
                body.span().start_usize(),
                body.span().end_usize(),
                clause_target,
            );
        }
    }
    edits
}

fn reindent_choices(src: &str, module: &Module) -> String {
    let edits = choice_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- top-level type/data/class/instance/exception declarations ---------------

fn type_def_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();
    for decl in &module.decls {
        let Decl::TypeDef { span, .. } = decl else {
            continue;
        };
        let head_line = line_of(&line_starts, ByteOffset::new(span.start_usize()));
        if leading_has_tab(src, line_starts[head_line]) {
            continue;
        }
        let head_indent = indent_of(src, &line_starts, head_line);
        let head_has_with = line_contains_word(src, &line_starts, head_line, "with");
        let mut in_with = head_has_with;
        let mut with_body_target = if head_has_with {
            first_body_anchor_indent_after(
                src,
                &line_starts,
                &comments,
                head_line,
                span.end_usize(),
            )
            .unwrap_or(head_indent + INDENT)
        } else {
            head_indent + 2 * INDENT
        };
        let head_has_where = line_contains_word(src, &line_starts, head_line, "where");
        let mut in_where = head_has_where;
        let mut where_body_target = if head_has_where {
            first_body_anchor_indent_after(
                src,
                &line_starts,
                &comments,
                head_line,
                span.end_usize(),
            )
            .unwrap_or(head_indent + INDENT)
        } else {
            head_indent + INDENT
        };
        let mut after_variant = line_contains_symbol(src, &line_starts, head_line, "=");
        let mut after_bar_variant = false;

        let mut line = head_line + 1;
        while line.get() < line_starts.len() && line_starts[line] < span.end_usize() {
            let Some(trimmed) = code_line_trimmed(src, &line_starts, &comments, line) else {
                line += 1;
                continue;
            };
            let target = if starts_with_word(trimmed, "where") {
                in_with = false;
                in_where = true;
                where_body_target = head_indent + 2 * INDENT;
                after_variant = false;
                Some(head_indent + INDENT)
            } else if starts_with_word(trimmed, "with") {
                let target = if after_bar_variant {
                    head_indent + 2 * INDENT
                } else {
                    head_indent + INDENT
                };
                in_with = true;
                in_where = false;
                with_body_target = target + INDENT;
                after_variant = false;
                after_bar_variant = false;
                Some(target)
            } else if trimmed.starts_with('=') || trimmed.starts_with('|') {
                in_with = false;
                in_where = false;
                after_variant = true;
                after_bar_variant = trimmed.starts_with('|');
                Some(head_indent + INDENT)
            } else if starts_with_word(trimmed, "deriving") {
                in_with = false;
                in_where = false;
                after_variant = false;
                after_bar_variant = false;
                Some(head_indent + INDENT)
            } else if in_with {
                Some(with_body_target)
            } else if in_where {
                Some(where_body_target)
            } else if after_variant {
                Some(head_indent + INDENT)
            } else {
                None
            };
            if let Some(target) = target {
                push_code_line_edit(&mut edits, src, &line_starts, &comments, line, target);
            }
            line += 1;
        }
    }
    edits
}

fn first_body_anchor_indent_after(
    src: &str,
    ls: &LineStarts,
    comments: &[(usize, usize)],
    after_line: LineIndex,
    block_end: usize,
) -> Option<i64> {
    let mut line = after_line + 1;
    while line.get() < ls.len() && ls[line] < block_end {
        if leading_has_tab(src, ls[line]) {
            return None;
        }
        let end = *ls.get(line + 1).unwrap_or(&src.len());
        let text = &src[ls[line]..end];
        let cur = text.len() - text.trim_start_matches(' ').len();
        let trimmed = text[cur..].trim_end();
        if trimmed.is_empty() {
            line += 1;
            continue;
        }
        if is_comment_line(comments, ls[line] + cur) && !trimmed.starts_with("{-#") {
            line += 1;
            continue;
        }
        return Some(indent_of(src, ls, line));
    }
    None
}

fn reindent_type_defs(src: &str, module: &Module) -> String {
    let edits = type_def_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- function guards and where-bindings --------------------------------------

fn guard_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();
    for decl in &module.decls {
        let Decl::Function(fun) = decl else {
            continue;
        };
        for eq in &fun.equations {
            let eq_line = line_of(&line_starts, ByteOffset::new(eq.span.start_usize()));
            if leading_has_tab(src, line_starts[eq_line]) {
                continue;
            }
            let guard_target = indent_of(src, &line_starts, eq_line) + INDENT;
            let mut cursor = eq.span.start_usize();
            for (guard, body) in &eq.guards {
                if let Some(pipe) =
                    find_symbol(src, cursor, guard.span().start_usize(), "|", &comments)
                {
                    push_span_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        pipe,
                        body.span().end_usize(),
                        guard_target,
                    );
                }
                cursor = body.span().end_usize();
            }
            if let (Some(first), Some(last)) = (eq.where_bindings.first(), eq.where_bindings.last())
            {
                if let Some(w) =
                    find_keyword(src, cursor, first.span.start_usize(), "where", &comments)
                {
                    push_span_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        w,
                        w + "where".len(),
                        guard_target,
                    );
                    push_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        first.span.start_usize(),
                        last.span.end_usize(),
                        guard_target + INDENT,
                        eq_line,
                    );
                }
            }
        }
    }
    edits
}

fn reindent_guards(src: &str, module: &Module) -> String {
    let edits = guard_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- record updates ----------------------------------------------------------

fn record_update_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut recs: Vec<(Span, usize, usize, usize)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::Record {
            span, base, fields, ..
        } = e
        {
            if matches!(base.as_ref(), Expr::Con { .. }) {
                return;
            }
            if let (Some(first), Some(last)) = (fields.first(), fields.last()) {
                recs.push((
                    *span,
                    base.span().end_usize(),
                    first.span().start_usize(),
                    last.span().end_usize(),
                ));
            }
        }
    });
    recs.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits = Vec::new();
    for (rec_span, base_end, first_field, last_field_end) in recs {
        let rec_line = line_of(&line_starts, ByteOffset::new(rec_span.start_usize()));
        let field_line = line_of(&line_starts, ByteOffset::new(first_field));
        if field_line <= rec_line || leading_has_tab(src, line_starts[rec_line]) {
            continue;
        }
        let Some(w) = find_keyword(src, base_end, first_field, "with", &comments) else {
            continue;
        };
        let with_line = line_of(&line_starts, ByteOffset::new(w));
        let rec_indent = indent_of(src, &line_starts, rec_line);
        let field_target = if with_line > rec_line {
            push_line_edit(
                &mut edits,
                &line_starts,
                src,
                with_line,
                rec_indent + INDENT,
            );
            rec_indent + 2 * INDENT
        } else {
            rec_indent + INDENT
        };
        push_block_edit(
            &mut edits,
            &line_starts,
            src,
            first_field,
            last_field_end,
            field_target,
            rec_line,
        );
    }
    edits
}

fn reindent_record_updates(src: &str, module: &Module) -> String {
    let edits = record_update_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- try/catch ---------------------------------------------------------------

fn try_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut tries: Vec<(Span, Span, Vec<Span>)> = Vec::new();
    walk_module_expressions(module, &mut |e| {
        if let Expr::Try {
            span,
            body,
            handlers,
            ..
        } = e
        {
            tries.push((
                *span,
                body.span(),
                handlers.iter().map(|h| h.span).collect(),
            ));
        }
    });
    tries.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));

    let mut edits = Vec::new();
    for (try_span, body_span, handlers) in tries {
        let try_line = line_of(&line_starts, ByteOffset::new(try_span.start_usize()));
        if leading_has_tab(src, line_starts[try_line]) {
            continue;
        }
        let try_col = usize_to_i64_saturating(
            src[line_starts[try_line]..try_span.start_usize()]
                .chars()
                .count(),
        );
        let nested_target = try_col + INDENT;
        push_block_edit(
            &mut edits,
            &line_starts,
            src,
            body_span.start_usize(),
            body_span.end_usize(),
            nested_target,
            try_line,
        );
        if let Some(first_handler) = handlers.first() {
            if let Some(catch) = find_keyword(
                src,
                body_span.end_usize(),
                first_handler.start_usize(),
                "catch",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    catch,
                    catch + "catch".len(),
                    try_col,
                );
            }
        }
        if let (Some(first), Some(last)) = (handlers.first(), handlers.last()) {
            push_block_edit(
                &mut edits,
                &line_starts,
                src,
                first.start_usize(),
                last.end_usize(),
                nested_target,
                try_line,
            );
        }
    }
    edits
}

fn reindent_tries(src: &str, module: &Module) -> String {
    let edits = try_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- expression continuations ------------------------------------------------

fn continuation_edits(src: &str, module: &Module) -> Vec<Edit> {
    let line_starts = line_start_table(src);
    let comments = comment_spans(src);
    let mut edits = Vec::new();
    walk_module_expressions(module, &mut |e| match e {
        Expr::Tuple { span, items, .. } | Expr::List { span, items, .. } => {
            push_item_continuations(
                &mut edits,
                src,
                &line_starts,
                &comments,
                *span,
                items.iter().map(Expr::span),
            );
        }
        _ => {}
    });
    edits
}

fn push_item_continuations(
    edits: &mut Vec<Edit>,
    src: &str,
    ls: &LineStarts,
    comments: &[(usize, usize)],
    span: Span,
    items: impl Iterator<Item = Span>,
) {
    let head_line = line_of(ls, ByteOffset::new(span.start_usize()));
    let target = indent_of(src, ls, head_line) + INDENT;
    for item in items {
        let item_line = line_of(ls, ByteOffset::new(item.start_usize()));
        if item_line <= head_line {
            continue;
        }
        let mut first = item.start_usize();
        let line_start = ls[item_line];
        if let Some(comma) = src[line_start..item.start_usize()].rfind(',') {
            first = line_start + comma;
        }
        if is_comment_line(comments, first) {
            continue;
        }
        push_span_block_edit(edits, ls, src, first, item.end_usize(), target);
    }
}

fn reindent_continuations(src: &str, module: &Module) -> String {
    let edits = continuation_edits(src, module);
    if edits.is_empty() {
        return src.to_string();
    }
    apply_shifts(src, &edits)
}

// ---- shared line-edit helpers ------------------------------------------------

fn push_span_block_edit(
    edits: &mut Vec<Edit>,
    ls: &LineStarts,
    src: &str,
    first_byte: usize,
    end_byte: usize,
    target: i64,
) {
    let first_line = line_of(ls, ByteOffset::new(first_byte));
    if src[ls[first_line]..first_byte].chars().any(|c| c != ' ') {
        return;
    }
    if leading_has_tab(src, ls[first_line]) {
        return;
    }
    let delta = target - indent_of(src, ls, first_line);
    if delta != 0 {
        edits.push(Edit {
            child_start: ByteOffset::new(ls[first_line]),
            block_end: ByteOffset::new(end_byte),
            delta: IndentDelta::new(delta),
        });
    }
}

fn push_code_line_edit(
    edits: &mut Vec<Edit>,
    src: &str,
    ls: &LineStarts,
    comments: &[(usize, usize)],
    line: LineIndex,
    target: i64,
) {
    if code_line_trimmed(src, ls, comments, line).is_none() || leading_has_tab(src, ls[line]) {
        return;
    }
    push_line_edit(edits, ls, src, line, target);
}

fn code_line_trimmed<'a>(
    src: &'a str,
    ls: &LineStarts,
    comments: &[(usize, usize)],
    line: LineIndex,
) -> Option<&'a str> {
    let start = *ls.get(line)?;
    let end = *ls.get(line + 1).unwrap_or(&src.len());
    let text = &src[start..end];
    let cur = text.len() - text.trim_start_matches(' ').len();
    let trimmed = text[cur..].trim_end();
    if trimmed.is_empty() || is_comment_line(comments, start + cur) {
        None
    } else {
        Some(trimmed)
    }
}

fn starts_with_word(s: &str, word: &str) -> bool {
    s.strip_prefix(word).is_some_and(|rest| {
        rest.is_empty()
            || rest
                .chars()
                .next()
                .is_some_and(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '\'')
    })
}

fn line_contains_word(src: &str, ls: &LineStarts, line: LineIndex, word: &str) -> bool {
    let end = *ls.get(line + 1).unwrap_or(&src.len());
    let line_text = &src[ls[line]..end];
    let mut i = 0;
    while let Some(rel) = line_text[i..].find(word) {
        let at = i + rel;
        let before_ok = at == 0 || !is_ident_byte(line_text.as_bytes()[at - 1]);
        let after = at + word.len();
        let after_ok = after >= line_text.len() || !is_ident_byte(line_text.as_bytes()[after]);
        if before_ok && after_ok {
            return true;
        }
        i = at + 1;
    }
    false
}

const fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b == b'\''
}

fn line_contains_symbol(src: &str, ls: &LineStarts, line: LineIndex, symbol: &str) -> bool {
    let end = *ls.get(line + 1).unwrap_or(&src.len());
    src[ls[line]..end].contains(symbol)
}

fn find_symbol(
    src: &str,
    from: usize,
    to: usize,
    symbol: &str,
    comments: &[(usize, usize)],
) -> Option<usize> {
    let hay = &src[from..to.min(src.len())];
    let mut i = 0;
    while let Some(rel) = hay[i..].find(symbol) {
        let abs = from + i + rel;
        if !is_comment_line(comments, abs) {
            return Some(abs);
        }
        i += rel + symbol.len();
    }
    None
}

#[cfg(test)]
mod line_helpers {
    use super::*;

    #[test]
    fn comment_line_detection() {
        let src = "x\n-- hi\ny\n";
        let comments = comment_spans(src);
        // "-- hi" starts at byte 2.
        assert!(is_comment_line(&comments, 2));
        assert!(!is_comment_line(&comments, 0)); // 'x'
        assert!(!is_comment_line(&comments, 7)); // 'y'
    }

    #[test]
    fn indent_and_line_helpers() {
        let src = "a\n    b\n";
        let ls = line_start_table(src);
        assert_eq!(indent_of(src, &ls, LineIndex::new(0)), 0);
        assert_eq!(indent_of(src, &ls, LineIndex::new(1)), 4);
        assert_eq!(line_of(&ls, ByteOffset::new(0)), LineIndex::new(0));
        assert_eq!(line_of(&ls, ByteOffset::new(6)), LineIndex::new(1));
    }

    #[test]
    fn formatter_coordinate_domains_are_distinct_types() {
        use std::any::TypeId;

        // The structural reindent helpers must not collapse byte offsets, line
        // indexes, and signed indentation deltas back into interchangeable
        // primitive coordinates.
        assert_ne!(TypeId::of::<ByteOffset>(), TypeId::of::<LineIndex>());
        assert_ne!(TypeId::of::<ByteOffset>(), TypeId::of::<IndentDelta>());
        assert_ne!(TypeId::of::<LineIndex>(), TypeId::of::<IndentDelta>());
    }

    #[test]
    fn import_groups_are_named_domains_with_expected_order() {
        assert_eq!(import_group("Daml.Script"), ImportGroup::DamlStdlib);
        assert_eq!(import_group("DA.List"), ImportGroup::DaLibrary);
        assert_eq!(import_group("My.App"), ImportGroup::LocalOrExternal);
        assert!(ImportGroup::DamlStdlib < ImportGroup::DaLibrary);
        assert!(ImportGroup::DaLibrary < ImportGroup::LocalOrExternal);
    }
}