daml-fmt 0.2.2

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
//! AST-driven canonical layout.
//!
//! This is OUR OWN pattern, NOT a port of the LimeChain heuristic: no LimeChain
//! code is consulted; design is from the daml-parser AST.
//! We do NOT aim to match `expected/`: the formatter makes its own consistent
//! layout decisions and may diverge from the LimeChain baseline). This is the
//! shipping backend behind `format_source`.
//!
//! Uniform mechanism (the architecture the prototype validated):
//!   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 the whole candidate on `same_tokens` = identical LAID-OUT token
//!      stream (offside virtuals included) ⇒ identical parse ⇒ identical
//!      desugar. Any accepted reindent is desugar-safe BY CONSTRUCTION.
//!   5. Fall back to the input (verbatim) when the gate rejects or a node is
//!      not modeled. Broader expression wrapping and layout-organizing rewrites
//!      still pass through verbatim — safe, and lets us land one construct family
//!      at a time.
//!
//! On top of the structural pass we compose the proven, token-gated
//! whitespace + colon-spacing normalization (`crate::normalize_gaps`).

use daml_parser::ast::*;
use daml_parser::layout::resolve_layout;
use daml_parser::lexer::{lex_with_trivia, TriviaKind};
use daml_parser::parse::parse_module;

const INDENT: i64 = 2;

/// 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 the AST-driven structural reindents, then the gap normalization;
/// every step is gated for desugar-safety.
pub fn format_ast(src: &str) -> String {
    if has_source_location_expectation(src) {
        return src.to_string();
    }

    // Step 1: structural reindent, each family as its own gated pass. Iterate to
    // a fixpoint so a later pass that unblocks an earlier one's gate still
    // converges within a single call (idempotence).
    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;
    }

    // Step 2: whitespace + colon normalization on top, gated vs `base`.
    // same_tokens is transitive, so gating each step against its own input
    // keeps the final output token-equivalent (and desugar-equivalent) to src.
    let full = crate::normalize_gaps(&base, true);
    if same_tokens(&base, &full) {
        return full;
    }
    let ws_only = crate::normalize_gaps(&base, false);
    if same_tokens(&base, &ws_only) {
        return ws_only;
    }
    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 (module, _) = parse_module(src);
    let r = reindent_do_blocks(src, &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 (module, _) = parse_module(src);
    let r = reindent_ifs(src, &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 (module, _) = parse_module(src);
    let r = reindent_cases(src, &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 (module, _) = parse_module(src);
    let r = reindent_letins(src, &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 (module, _) = parse_module(src);
    let r = reindent_con_with(src, &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 (module, _) = parse_module(src);
    let r = reindent_templates(src, &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 (module, _) = parse_module(src);
    let r = reindent_modules_and_imports(src, &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 (module, _) = parse_module(src);
    let r = reindent_choices(src, &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 (module, _) = parse_module(src);
    let r = reindent_type_defs(src, &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 (module, _) = parse_module(src);
    let r = reindent_guards(src, &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 (module, _) = parse_module(src);
    let r = reindent_record_updates(src, &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 (module, _) = parse_module(src);
    let r = reindent_tries(src, &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 (module, _) = parse_module(src);
    let r = reindent_continuations(src, &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.
pub fn coverage(src: &str) -> (usize, usize) {
    let (module, _diags) = parse_module(src);
    let candidates = 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();
    (candidates, 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 la = resolve_layout(lex_with_trivia(a).0);
    let lb = resolve_layout(lex_with_trivia(b).0);
    la.len() == lb.len() && la.iter().zip(&lb).all(|(x, y)| x.tok == y.tok)
}

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")
        })
}

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

/// 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 <= do_span.start && do_span.end <= a.end && *a != do_span)
        {
            continue;
        }
        let do_line = line_of(&line_starts, do_span.start);
        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)
        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: line_starts[first_stmt_line],
                block_end: do_span.end,
                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().enumerate() {
        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 = ls + cur;

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

        if delta == 0
            || line.trim().is_empty()
            || is_comment_line(&comments, content_byte)
            || leading_has_tab(src, ls)
        {
            out.push_str(line);
            continue;
        }
        let new = (cur as i64 + delta).max(0) as usize;
        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 (_t, trivia, _e) = lex_with_trivia(src);
    let mut v: Vec<(usize, usize)> = trivia
        .iter()
        .filter(|t| matches!(t.kind, TriviaKind::LineComment | TriviaKind::BlockComment))
        .map(|t| (t.start, t.end))
        .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) -> Vec<usize> {
    std::iter::once(0)
        .chain(src.match_indices('\n').map(|(i, _)| i + 1))
        .collect()
}
fn line_of(line_starts: &[usize], byte: usize) -> usize {
    match line_starts.binary_search(&byte) {
        Ok(i) => i,
        Err(i) => i - 1,
    }
}
fn indent_of(src: &str, line_starts: &[usize], line: usize) -> i64 {
    src[line_starts[line]..]
        .chars()
        .take_while(|&c| c == ' ')
        .count() as i64
}
/// 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: &[usize],
    comments: &[(usize, usize)],
    do_line: usize,
    block_end: usize,
) -> Option<usize> {
    let mut l = do_line + 1;
    while l < 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: &[usize],
    comments: &[(usize, usize)],
    after_line: usize,
    keyword: &str,
) -> Option<usize> {
    let mut l = after_line + 1;
    while l < 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);
            alts.iter().for_each(|alt| walk_expression(&alt.body, 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 Some(v) = &fa.value {
                    walk_expression(v, f);
                }
            }
        }
        Expr::Tuple { items, .. } | Expr::List { items, .. } => {
            items.iter().for_each(|item| walk_expression(item, f))
        }
        Expr::Try { body, handlers, .. } => {
            walk_expression(body, f);
            handlers
                .iter()
                .for_each(|handler| walk_expression(&handler.body, f));
        }
        Expr::Section {
            operand: Some(o), ..
        } => walk_expression(o, 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,
                cond.span().end,
                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 <= if_span.start && if_span.end <= a.end && *a != if_span)
        {
            continue;
        }
        accepted.push(if_span);

        let if_line = line_of(&line_starts, 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 = src[line_starts[if_line]..if_byte].chars().count() as i64;
        let target = if_col + INDENT;

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

        for (kw_byte, branch_end) in [(then_byte, then_span.end), (else_byte, else_span.end)] {
            let Some(kw_byte) = kw_byte else { continue };
            let kw_line = line_of(&line_starts, 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: ls,
                    block_end: branch_end,
                    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, last.span.end));
            }
        }
    });
    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 <= case_span.start && case_span.end <= a.end && *a != case_span)
        {
            continue;
        }
        accepted.push(case_span);

        let case_line = line_of(&line_starts, case_span.start);
        let alt_line = line_of(&line_starts, 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: line_starts[alt_line],
                block_end: last_alt_end,
                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, last.span.end));
            }
        }
    });
    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 <= let_span.start && let_span.end <= a.end && *a != let_span)
        {
            continue;
        }
        accepted.push(let_span);

        let let_line = line_of(&line_starts, let_span.start);
        let bind_line = line_of(&line_starts, 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]
            .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: line_starts[bind_line],
                block_end: last_bind_end,
                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, first.span.start, last.span.end));
            }
        }
    });
    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 <= rec_span.start && rec_span.end <= a.end && *a != rec_span)
        {
            continue;
        }
        accepted.push(rec_span);

        let rec_line = line_of(&line_starts, rec_span.start);
        let field_line = line_of(&line_starts, 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, 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, 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: line_starts[field_line],
                block_end: last_field_end,
                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: &[usize], src: &str, line: usize, 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: ls[line],
            block_end: end,
            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: &[usize],
    src: &str,
    first_byte: usize,
    end_byte: usize,
    target: i64,
    head_line: usize,
) {
    let first_line = line_of(ls, 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: ls[first_line],
            block_end: end_byte,
            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,
    }
}

/// 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: &[usize],
    src: &str,
    comments: &[(usize, usize)],
    head_line: usize,
    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, w) > head_line {
            push_line_edit(edits, ls, src, line_of(ls, 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,
            Decl::Interface(i) => i.span.start,
            _ => continue,
        };
        let head_line = line_of(&line_starts, 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,
                        f0.span.start,
                        fl.span.end,
                    );
                }
                // 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).unwrap_or(t.span.start);
                    reindent_keyword_block(
                        &mut edits,
                        &line_starts,
                        src,
                        &comments,
                        head_line,
                        kw_target,
                        body_target,
                        "where",
                        where_from,
                        b0_start,
                        bl_end,
                    );
                }
            }
            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(s.end, |e: usize| e.max(s.end)));
                }
                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,
                            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: &[usize],
    comments: &[(usize, usize)],
    span: Span,
    offset: i64,
) {
    let head_line = line_of(ls, span.start);
    let target = indent_of(src, ls, head_line) + offset;
    let mut line = head_line + 1;
    while line < ls.len() && ls[line] < span.end {
        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.cmp(&a.span.end))
    });
}

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, c.span.start);
        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 Some(ty) = &c.return_ty {
            if let Some(colon) = find_symbol(src, c.span.start, ty.span().start, ":", &comments) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    colon,
                    ty.span().end,
                    clause_target,
                );
            }
        }

        if let (Some(first), Some(last)) = (c.params.first(), c.params.last()) {
            let kw_from = c.return_ty.as_ref().map_or(c.span.start, |t| t.span().end);
            if let Some(w) = find_keyword(src, kw_from, first.span.start, "with", &comments) {
                let with_line = line_of(&line_starts, w);
                let first_param_line = line_of(&line_starts, first.span.start);
                if first_param_line == with_line {
                    push_span_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        w,
                        last.span.end,
                        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,
                        last.span.end,
                        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, first.span().start, "observer", &comments)
            {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    k,
                    last.span().end,
                    clause_target,
                );
            }
        }
        if let (Some(first), Some(last)) = (c.controllers.first(), c.controllers.last()) {
            if let Some(k) = find_keyword(
                src,
                c.span.start,
                first.span().start,
                "controller",
                &comments,
            ) {
                push_span_block_edit(
                    &mut edits,
                    &line_starts,
                    src,
                    k,
                    last.span().end,
                    clause_target,
                );
            }
        }

        if let Some(body) = &c.body {
            push_span_block_edit(
                &mut edits,
                &line_starts,
                src,
                body.span().start,
                body.span().end,
                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, span.start);
        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)
                .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)
                .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 < line_starts.len() && line_starts[line] < span.end {
            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: &[usize],
    comments: &[(usize, usize)],
    after_line: usize,
    block_end: usize,
) -> Option<i64> {
    let mut line = after_line + 1;
    while line < 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, eq.span.start);
            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;
            for (guard, body) in &eq.guards {
                if let Some(pipe) = find_symbol(src, cursor, guard.span().start, "|", &comments) {
                    push_span_block_edit(
                        &mut edits,
                        &line_starts,
                        src,
                        pipe,
                        body.span().end,
                        guard_target,
                    );
                }
                cursor = body.span().end;
            }
            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, "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,
                        last.span.end,
                        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, first.span.start, last.span.end));
            }
        }
    });
    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, rec_span.start);
        let field_line = line_of(&line_starts, 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, 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, try_span.start);
        if leading_has_tab(src, line_starts[try_line]) {
            continue;
        }
        let try_col = src[line_starts[try_line]..try_span.start].chars().count() as i64;
        let nested_target = try_col + INDENT;
        push_block_edit(
            &mut edits,
            &line_starts,
            src,
            body_span.start,
            body_span.end,
            nested_target,
            try_line,
        );
        if let Some(first_handler) = handlers.first() {
            if let Some(catch) =
                find_keyword(src, body_span.end, first_handler.start, "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,
                last.end,
                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: &[usize],
    comments: &[(usize, usize)],
    span: Span,
    items: impl Iterator<Item = Span>,
) {
    let head_line = line_of(ls, span.start);
    let target = indent_of(src, ls, head_line) + INDENT;
    for item in items {
        let item_line = line_of(ls, item.start);
        if item_line <= head_line {
            continue;
        }
        let mut first = item.start;
        let line_start = ls[item_line];
        if let Some(comma) = src[line_start..item.start].rfind(',') {
            first = line_start + comma;
        }
        if is_comment_line(comments, first) {
            continue;
        }
        push_span_block_edit(edits, ls, src, first, item.end, 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: &[usize],
    src: &str,
    first_byte: usize,
    end_byte: usize,
    target: i64,
) {
    let first_line = line_of(ls, 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: ls[first_line],
            block_end: end_byte,
            delta,
        });
    }
}

fn push_code_line_edit(
    edits: &mut Vec<Edit>,
    src: &str,
    ls: &[usize],
    comments: &[(usize, usize)],
    line: usize,
    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: &[usize],
    comments: &[(usize, usize)],
    line: usize,
) -> 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: &[usize], line: usize, 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: &[usize], line: usize, 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 tests {
    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, 0), 0);
        assert_eq!(indent_of(src, &ls, 1), 4);
        assert_eq!(line_of(&ls, 0), 0);
        assert_eq!(line_of(&ls, 6), 1);
    }

    #[test]
    fn do_body_reindented_to_anchor_plus_two() {
        // do at col 0; body stmt at col 6 -> should move to col 2.
        let src = "f = do\n      pure ()\n";
        let out = format_ast(src);
        assert_eq!(out, "f = do\n  pure ()\n");
    }

    #[test]
    fn source_range_expectation_files_stay_byte_exact() {
        let src = "module M where\n-- @ WARN range=3:8-3:9; x\nfoo : Int\nfoo = 1\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn source_location_query_files_stay_byte_exact() {
        let src = "-- @QUERY-LF .location.range | (.start_line == 8 and .start_col == 9)\n\n\nmodule Locations where\nfoo : Int\nfoo = 1\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn idempotent_on_reindent() {
        let src = "f = do\n      pure ()\n";
        let once = format_ast(src);
        let twice = format_ast(&once);
        assert_eq!(once, twice);
    }

    #[test]
    fn leading_comment_not_measured_or_moved() {
        // The first body line is a col-0 comment; the real stmt is at col 6.
        // The comment must stay at col 0; the stmt moves to col 2.
        let src = "f = do\n-- note\n      pure ()\n";
        let out = format_ast(src);
        assert_eq!(out, "f = do\n-- note\n  pure ()\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn inline_do_left_alone() {
        let src = "f = do pure ()\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn tab_indented_body_left_verbatim() {
        // Tabs in indentation must never get spaces prepended in front of them.
        let src = "f = do\n\t\tpure ()\n";
        assert_eq!(format_ast(src), src);
        assert_eq!(format_ast(&format_ast(src)), format_ast(src));
    }

    #[test]
    fn do_block_starting_with_let_is_reindented() {
        // A `do` whose first statement is a `let` is no longer verbatim. The
        // whole block shifts by ONE uniform delta to land the first stmt at
        // do_col + 2, so the `let` line, its continuation binding, and the
        // following statement all move together — the bindings stay aligned
        // (x and y both end at col 6) without a separate let-internal rule.
        let src = "f = do\n      let x = 1\n          y = 2\n      pure (x + y)\n";
        let out = format_ast(src);
        assert_eq!(out, "f = do\n  let x = 1\n      y = 2\n  pure (x + y)\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn do_block_with_try_is_reindented() {
        // A do-block containing try/catch is now owned by the do and try passes.
        let src = "f = do\n      _ <- try foo catch _ -> bar\n      pure ()\n";
        let out = format_ast(src);
        assert_eq!(out, "f = do\n  _ <- try foo catch _ -> bar\n  pure ()\n");
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn if_then_else_reindented_to_if_col_plus_two() {
        // `if` at col 2; then/else lines move to col 4 (if_col + 2).
        let src = "f x =\n  if x > 0\n      then 1\n      else 2\n";
        let out = format_ast(src);
        assert_eq!(out, "f x =\n  if x > 0\n    then 1\n    else 2\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn if_then_else_already_aligned_is_a_fixpoint() {
        let src = "f x =\n  if x > 0\n    then 1\n    else 2\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn single_line_if_is_untouched() {
        // Inline then/else are not line-leading, so the rule leaves them alone.
        let src = "g x = if x then 1 else 2\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn do_then_if_passes_reach_a_single_call_fixpoint() {
        // Regression: a do-block as the `then`-branch where `then`/`else` are at
        // different columns. In pass 1 the do-pass's body shift collides with
        // the not-yet-moved `else` (offside VSemi) so its gate rejects; the
        // if-pass then moves `else`, removing the collision. The structural
        // passes must iterate to a fixpoint so a SINGLE format call is already
        // idempotent — format(format(x)) == format(x).
        let src = "f =\n  if c\n    then do\n       a\n       b\n      else d\n";
        let once = format_ast(src);
        let twice = format_ast(&once);
        assert_eq!(once, twice, "single-call output must be a fixpoint");
    }

    #[test]
    fn if_then_else_multiline_branch_rides_uniform_shift() {
        // A then-branch spanning extra lines shifts by ONE uniform delta, so the
        // branch's own indentation structure is preserved (8->6, 10->8).
        let src = "f x =\n  if x > 0\n      then g\n             a\n      else h\n";
        let out = format_ast(src);
        assert_eq!(
            out,
            "f x =\n  if x > 0\n    then g\n           a\n    else h\n"
        );
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn case_alts_reindented_to_case_indent_plus_two() {
        // case-line indent 0; alts at col 6 move to col 2.
        let src = "f x = case x of\n      None -> 1\n      Some y -> y\n";
        let out = format_ast(src);
        assert_eq!(out, "f x = case x of\n  None -> 1\n  Some y -> y\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn case_alts_already_aligned_is_a_fixpoint() {
        let src = "f x = case x of\n  None -> 1\n  Some y -> y\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn inline_case_is_untouched() {
        // alts share the `case` line — left verbatim.
        let src = "f x = case x of None -> 1; Some y -> y\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn nested_case_rides_outer_shift() {
        // Inner case (an alt body) rides the outer alt block's uniform shift; the
        // inner alts stay aligned relative to their own `case`.
        let src = "f x = case x of\n      A -> case y of\n             P -> 1\n             Q -> 2\n      B -> 0\n";
        let out = format_ast(src);
        // Outer alts to col 2; inner alts ride the same -4 shift (13 -> 9).
        let want =
            "f x = case x of\n  A -> case y of\n         P -> 1\n         Q -> 2\n  B -> 0\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn letin_bindings_reindented_to_let_indent_plus_two() {
        // `let` on its own line at col 2; bindings at col 6 move to col 4; `in`
        // is left at col 2.
        let src = "f =\n  let\n      x = 1\n      y = 2\n  in x + y\n";
        let out = format_ast(src);
        assert_eq!(out, "f =\n  let\n    x = 1\n    y = 2\n  in x + y\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn letin_already_aligned_is_a_fixpoint() {
        let src = "f =\n  let\n    x = 1\n    y = 2\n  in x + y\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn inline_letin_is_untouched() {
        // binding shares the `let` line — left verbatim.
        let src = "f = let x = 1 in x\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn con_with_fields_reindented_to_indent_plus_two() {
        // `create Asset with` at line indent 0; fields at col 6 move to col 2.
        let src = "f = create Asset with\n      issuer = a\n      owner = b\n";
        let out = format_ast(src);
        assert_eq!(out, "f = create Asset with\n  issuer = a\n  owner = b\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn record_update_fields_are_reindented() {
        // base is an expression (`this`), not a bare constructor: an update.
        let src = "f this p = this with\n      owner = p\n";
        let out = format_ast(src);
        assert_eq!(out, "f this p = this with\n  owner = p\n");
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn split_with_on_own_line_stays_verbatim() {
        // `with` is on its own line, not the `Con` line: reindenting the fields
        // to the Con line's indent + 2 would put them left of `with`, so the
        // rule leaves it verbatim.
        let src = "f = WithField\n    with\n        f1 = 10\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn inline_con_with_is_untouched() {
        let src = "f = Asset with issuer = a; owner = b\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn con_with_before_where_keeps_fields_inside_expression() {
        let src = "module M where\nquery : T\nquery = lift $ QueryACS with\n    parties = p\n    tplId = t\n  where\n    convert = x\n";
        let out = format_ast(src);
        assert_eq!(
            out,
            "module M where\nquery: T\nquery = lift $ QueryACS with\n    parties = p\n    tplId = t\n  where\n    convert = x\n"
        );
    }

    #[test]
    fn template_four_space_ladder_canonicalized_to_two() {
        // The case the uniform shift could NOT fix: a 4-space ladder. The
        // structured reindent uses different deltas for keywords (-> +2) and
        // fields/decls (-> +4), so it becomes the canonical 2-space ladder, and
        // the choice's internal 2-space ladder rides the decl-block shift.
        let src = "template Coin\n    with\n        issuer : Party\n    where\n        signatory issuer\n        choice Burn : ()\n          controller issuer\n          do pure ()\n";
        let out = format_ast(src);
        let want = "template Coin\n  with\n    issuer: Party\n  where\n    signatory issuer\n    choice Burn: ()\n      controller issuer\n      do pure ()\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn interface_body_canonicalized_to_two() {
        // `interface X where` has `where` inline, so the body (viewtype +
        // methods + choices) sits at head + 2, and a choice's internals ride to
        // head + 4.
        let src = "interface Asset where\n    viewtype V\n    getOwner : Party\n    choice Xfer : ()\n      controller getOwner this\n      do pure ()\n";
        let out = format_ast(src);
        let want = "interface Asset where\n  viewtype V\n  getOwner: Party\n  choice Xfer: ()\n    controller getOwner this\n    do pure ()\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn inline_with_template_keeps_fields_at_head_plus_four() {
        // Regression: `template T with` (with inline on the head line) is still
        // a 2-level ladder — fields at head + 4, NOT head + 2, because the
        // `where` at + 2 must close the with-block. (Sending them to + 2 made
        // the SDK reject the output.)
        let src = "template T with\n    p: Party\n  where\n    signatory p\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn canonical_template_is_a_fixpoint() {
        let src = "template Coin\n  with\n    issuer: Party\n  where\n    signatory issuer\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn under_indented_template_body_canonicalized() {
        // where-decls at the `where` column (2) move to template_indent + 4 = 4.
        let src = "template Coin\n  with\n    issuer: Party\n  where\n  signatory issuer\n";
        let out = format_ast(src);
        assert_eq!(
            out,
            "template Coin\n  with\n    issuer: Party\n  where\n    signatory issuer\n"
        );
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn mid_line_let_is_left_verbatim() {
        // A `let` that does not start its line: the `in` stays at the keyword
        // column while the bindings would anchor on the (smaller) line indent,
        // which mismatches — so the rule leaves it alone rather than dedent the
        // bindings left of `let`/`in`.
        let src = "f x = let\n        a = 1\n        b = 2\n      in a + b\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn choice_internal_ladder_is_canonicalized() {
        let src = "template T\n  with\n    p: Party\n  where\n    choice C\n          : ()\n          with\n              arg: Text\n          observer p\n          controller p\n          do\n              pure ()\n";
        let out = format_ast(src);
        let want = "template T\n  with\n    p: Party\n  where\n    choice C\n      : ()\n      with\n        arg: Text\n      observer p\n      controller p\n      do\n        pure ()\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn choice_keyword_scan_ignores_identifier_fragments() {
        let src = "template T\n  with\n    p: Party\n  where\n    choice C\n          : ()\n          with\n              observer_name: Party\n          observer p\n          controller p\n          do\n              pure ()\n";
        let out = format_ast(src);
        let want = "template T\n  with\n    p: Party\n  where\n    choice C\n      : ()\n      with\n        observer_name: Party\n      observer p\n      controller p\n      do\n        pure ()\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn type_def_ladders_are_canonicalized() {
        let src = "data Color = Grey\n           | RGB\n                with r: Int\n           deriving (Eq, Show)\n\nexception E\n      with\n          msg: Text\n      where\n          message msg\n";
        let out = format_ast(src);
        let want = "data Color = Grey\n  | RGB\n    with r: Int\n  deriving (Eq, Show)\n\nexception E\n  with\n    msg: Text\n  where\n    message msg\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn data_record_with_ladder_keeps_with_above_fields() {
        let src =
            "data ReceiverAmount = ReceiverAmount\n    with\n      receiver : Party\n      amount : Decimal\n";
        let out = format_ast(src);
        let want =
            "data ReceiverAmount = ReceiverAmount\n  with\n    receiver: Party\n    amount: Decimal\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn inline_data_record_with_braces_keeps_body_column() {
        let src = "data Data = Data with\n  { dummy : ()\n  , srcLoc : SrcLoc\n  }\n";
        assert_eq!(format_ast(src), src);
    }

    #[test]
    fn class_where_body_with_comments_keeps_body_indent() {
        let src = "class ActionState s m | m -> s where\n  {-# MINIMAL get, (put | modify) #-}\n  -- | Fetch the current value.\n  get : m s\n\n  -- | Set the value.\n  put : s -> m ()\n  put = modify . const\n";
        let out = format_ast(src);
        let want = "class ActionState s m | m -> s where\n  {-# MINIMAL get, (put | modify) #-}\n  -- | Fetch the current value.\n  get: m s\n\n  -- | Set the value.\n  put: s -> m ()\n  put = modify . const\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn class_where_body_with_indented_pragma_keeps_pragma_indent() {
        let src = "class Foo t where\n    {-# MINIMAL foo1 | foo2 #-}\n\n    foo1 : t -> Int\n    foo1 x = foo1 x + 1\n";
        let out = format_ast(src);
        let want = "class Foo t where\n    {-# MINIMAL foo1 | foo2 #-}\n\n    foo1: t -> Int\n    foo1 x = foo1 x + 1\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn guards_and_where_bindings_are_canonicalized() {
        let src =
            "f x\n      | x > 0 = g\n               x\n      | otherwise = 0\n      where\n          g y = y\n";
        let out = format_ast(src);
        let want = "f x\n  | x > 0 = g\n           x\n  | otherwise = 0\n  where\n    g y = y\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn multiline_try_catch_is_canonicalized() {
        let src = "f = try\n        foo\n      catch\n        _ -> bar\n";
        let out = format_ast(src);
        let want = "f = try\n      foo\n    catch\n      _ -> bar\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn explicit_list_continuations_are_canonicalized() {
        let src = "x = [ 1\n      , 2\n      , 3 ]\n";
        let out = format_ast(src);
        let want = "x = [ 1\n  , 2\n  , 3 ]\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn module_and_import_continuations_are_canonicalized() {
        let src = "module M\n      ( f\n      , g\n      ) where\n\nimport DA.Map\n      ( Map\n      )\n";
        let out = format_ast(src);
        let want = "module M\n  ( f\n  , g\n  ) where\n\nimport DA.Map\n  ( Map\n  )\n";
        assert_eq!(out, want);
        assert_eq!(format_ast(&out), out);
    }

    #[test]
    fn duplicate_space_after_colon_collapsed() {
        // The formatter owns type-annotation colon spacing, so `x:  T` must
        // canonicalize to `x: T` symmetrically with `x : T` -> `x: T`.
        let src = "module M where\nfoo:  Int -> Int\nfoo x = x\n";
        let out = format_ast(src);
        assert_eq!(out, "module M where\nfoo: Int -> Int\nfoo x = x\n");
        assert_eq!(format_ast(&out), out); // idempotent
    }

    #[test]
    fn space_around_colon_canonicalized_both_sides() {
        let src = "module M where\nfoo  :  Int\nfoo = 1\n";
        assert_eq!(format_ast(src), "module M where\nfoo: Int\nfoo = 1\n");
    }

    #[test]
    fn after_colon_collapse_skips_braces_and_parens() {
        // At brace/paren depth the convention keeps the surrounding space, so
        // the after-colon collapse must NOT fire (same gate as before-colon).
        let braced = "module M where\nx = { a :  Int }\n";
        assert_eq!(format_ast(braced), braced);
        let parened = "module M where\nf (n :  Int) = n\n";
        assert_eq!(format_ast(parened), parened);
    }

    #[test]
    fn crlf_final_newline_not_mixed() {
        // A CRLF file must not end up with a lone LF on its last line.
        let src = "module M where\r\nx = 1   \r\n";
        let out = format_ast(src);
        assert!(out.ends_with("\r\n"), "got: {:?}", out);
        assert!(!out.ends_with("\n\n"));
        assert_eq!(format_ast(&out), out); // idempotent
    }
}