blue-lang-syntax 0.0.54

blue's surface syntax: lexer, parser, and lowering to the tatara-lisp quoted form.
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
//! Precedence-climbing parser, lowering straight to the tatara-lisp
//! quoted form.
//!
//! **The load-bearing design decision, made here and once:** the parser's
//! output IS a `tatara_lisp::Sexp`. There is no private blue AST that later
//! gets converted. That is Tenet 1 — *blue source parses to tatara-lisp* —
//! and building it any other way would make homoiconicity a conversion step
//! rather than an identity, which is the difference between blue's macro
//! story working and merely being claimed.
//!
//! The consequence to keep in view: every surface construct must have a
//! well-defined s-expression it means. Where the mapping is not obvious it
//! is written down in the test module, because the tests are the
//! specification of the surface until the mechanized spec exists.
//!
//! ## Spans are built, not bolted on
//!
//! Every production returns a [`Spanned`] — tatara-lisp's parallel tree where
//! **each node** carries the byte range that produced it — and the spanless
//! [`parse_program`] is a projection of it via `Spanned::to_sexp`.
//!
//! That direction is deliberate and it is the second time this file has learned
//! the lesson: the spanless tree is derivable from the spanned one and the
//! reverse is not. When the parser produced `Sexp` and callers wanted positions,
//! the only answers available were *invent one* (a squiggle under unrelated
//! code) or *use nothing* — and the type checker took the second, so every type
//! error in the editor was reported at line 0, column 0 regardless of where it
//! was. A span discarded at the parser cannot be recovered by anything
//! downstream, exactly as [`crate::lex`] says of trivia.
//!
//! Two honest limits, both stated where they are caused rather than inferred:
//!
//! - A node blue **synthesizes** (the `define` a `def` lowers to, the `not` an
//!   `unless` lowers to, the `equal?` a `case` arm compares with) has no source
//!   text of its own. It is given the span of the token that *caused* it — the
//!   `def`, the `unless`, the `when` — which is where a reader looks when told
//!   something about it.
//! - An interpolation's inner expression is parsed from a **sub-source** (the
//!   text between `#{` and `}`), so its own offsets are relative to that
//!   substring and would point into the wrong buffer. Those nodes are stamped
//!   with the whole string literal's span instead. Sub-span accuracy inside an
//!   interpolation needs the lexer to record each part's offset in the outer
//!   source, which it does not.

use tatara_lisp::{Atom, Sexp, Spanned, SpannedForm};

use crate::lex::{lex, Span, Token, TokenKind};

/// Why a source did not parse, and where.
///
/// **Structured, and located at the boundary.** `message` says what was
/// expected and what was found, in blue's own words; `span` is the byte range
/// of the offending text; `line` and `col` are that range's start, 1-based,
/// with the column counted in characters. Every public entry point fills
/// `line`/`col` from the source it was given, so `Display` reads
/// `3:7: expected `)`, found `]`` and never a byte offset.
///
/// The byte offsets used to BE the display (`… at 10..11`), and a Rust
/// `Debug` rendering named the token (`found Ident("y")`). Both are facts
/// about the implementation; neither is something an author can act on.
/// The span stays, as data, for any consumer that needs to point into the
/// buffer — an editor squiggle, a diagnostic code attached downstream.
#[derive(Clone, Debug, PartialEq)]
pub struct ParseError {
    pub message: String,
    pub span: Span,
    /// 1-based line of `span.start`.
    pub line: usize,
    /// 1-based column of `span.start`, in characters.
    pub col: usize,
}

impl ParseError {
    /// An error at `span`, not yet located: the parser sees tokens, not text,
    /// so the line and column are filled by [`Self::located`] at the entry
    /// point that holds the source.
    fn new(message: impl Into<String>, span: Span) -> Self {
        Self {
            message: message.into(),
            span,
            line: 0,
            col: 0,
        }
    }

    /// Resolve `line`/`col` against the source this error's span indexes.
    fn located(mut self, src: &str) -> Self {
        let (line, col) = Span::line_col(src, self.span.start.min(src.len()));
        self.line = line;
        self.col = col;
        self
    }
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}: {}", self.line, self.col, self.message)
    }
}

impl std::error::Error for ParseError {}

impl From<crate::lex::LexError> for ParseError {
    fn from(e: crate::lex::LexError) -> Self {
        Self::new(e.message, e.span)
    }
}

/// Parse a blue program into a sequence of tatara-lisp forms.
pub fn parse_program(src: &str) -> Result<Vec<Sexp>, ParseError> {
    parse_program_with_depth(src, MAX_EXPR_DEPTH)
}

/// Parse a blue program keeping **every node's** source span.
///
/// This is the parser's real output; [`parse_program`] projects the spans away.
/// Reach for this one whenever a position is going to be shown to a human — an
/// editor squiggle, a `line:col` in a CLI error, a future debugger's breakpoint
/// table. Reach for [`parse_program`] only when the consumer genuinely does not
/// care where anything was.
pub fn parse_program_tree(src: &str) -> Result<Vec<Spanned>, ParseError> {
    parse_program_tree_with_depth(src, MAX_EXPR_DEPTH)
}

/// [`parse_program_tree`] with the nesting bound supplied by the caller.
pub fn parse_program_tree_with_depth(
    src: &str,
    max_depth: usize,
) -> Result<Vec<Spanned>, ParseError> {
    let toks: Vec<Token> = lex(src)
        .map_err(|e| ParseError::from(e).located(src))?
        .into_iter()
        .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
        .collect();
    let mut p = Parser {
        toks,
        pos: 0,
        depth: 0,
        max_depth,
    };
    p.program().map_err(|e| e.located(src))
}

/// Parse a program written in a [`Yakugo`](crate::yakugo::Yakugo) surface.
///
/// The pack is applied to the TOKEN STREAM, between lexing and parsing, so the
/// parser below is untouched and every keyword site works by construction.
/// What comes out is the same `Sexp` the English surface produces — that is
/// the invariant the pack tests assert, and the only thing that makes a
/// surface a surface rather than a dialect.
///
/// # Errors
///
/// Lex and parse errors propagate unchanged. A pack cannot repair source that
/// does not tokenize, and reporting otherwise would name the wrong problem.
pub fn parse_program_in(src: &str, pack: &crate::yakugo::Yakugo) -> Result<Vec<Sexp>, ParseError> {
    Ok(parse_program_tree_in(src, pack)?
        .iter()
        .map(Spanned::to_sexp)
        .collect())
}

/// [`parse_program_in`] keeping **every node's** source span.
///
/// The same relation [`parse_program_tree`] has to [`parse_program`], and it
/// exists for the same reason: a surface is a spelling, so a program written in
/// one has positions exactly as real as an English-surface program's. Without
/// this door, `pipeline::run_in_surface` would have to lift a spanless tree back
/// up and every type error in a `yakugo` program would report `<synthetic>` —
/// a position the parser HAD and threw away one line earlier, which is the
/// class `Diagnostic::span`'s own docs name.
///
/// [`parse_program_in`] is now its projection, so the two cannot drift.
///
/// # Errors
///
/// As [`parse_program_in`].
pub fn parse_program_tree_in(
    src: &str,
    pack: &crate::yakugo::Yakugo,
) -> Result<Vec<Spanned>, ParseError> {
    let toks: Vec<Token> = crate::yakugo::canonical_tokens(src, pack)
        .map_err(|e| ParseError::from(e).located(src))?
        .into_iter()
        .filter(|t| !matches!(t.kind, TokenKind::Comment(_)))
        .collect();
    let mut p = Parser {
        toks,
        pos: 0,
        depth: 0,
        max_depth: MAX_EXPR_DEPTH,
    };
    p.program().map_err(|e| e.located(src))
}

/// [`parse_program`] with the nesting bound supplied by the caller.
///
/// The bound is a **safety limit, not a dialect**: `max_depth` cannot change
/// what any program means, only whether a pathological one is refused before
/// the stack is at risk. That is why it is a parameter here and
/// [`MAX_EXPR_DEPTH`] is only the default — a knob that could alter meaning
/// would belong nowhere near a config file (see `blue-lang-cli`'s `config`
/// module for the rule this obeys).
pub fn parse_program_with_depth(src: &str, max_depth: usize) -> Result<Vec<Sexp>, ParseError> {
    Ok(parse_program_tree_with_depth(src, max_depth)?
        .iter()
        .map(Spanned::to_sexp)
        .collect())
}

/// Parse, keeping each top-level form's source span.
///
/// The spans are what let the formatter put comments back. A comment is not
/// part of a program's *meaning*, so it has no place in the `Sexp` tree —
/// putting it there would break canonicality, since two programs differing only
/// in a comment would stop formatting identically. Instead the formatter renders
/// the tree and re-interleaves comments by position, which needs to know where
/// each form started and ended.
///
/// A projection of [`parse_program_tree`], which carries a span on every node
/// rather than only the top-level ones. This entry point survives because the
/// formatter wants exactly the top-level pairing and nothing deeper.
pub fn parse_program_spanned(src: &str) -> Result<Vec<(Sexp, Span)>, ParseError> {
    parse_program_spanned_with_depth(src, MAX_EXPR_DEPTH)
}

/// [`parse_program_spanned`] with the nesting bound supplied by the caller.
pub fn parse_program_spanned_with_depth(
    src: &str,
    max_depth: usize,
) -> Result<Vec<(Sexp, Span)>, ParseError> {
    Ok(parse_program_tree_with_depth(src, max_depth)?
        .iter()
        .map(|f| (f.to_sexp(), f.span))
        .collect())
}

/// Every comment in `src`, with its byte span and whether it sits alone on its
/// line.
///
/// `own_line` is the distinction that decides placement: a comment alone on its
/// line belongs *before* the form that follows, while one after code on the same
/// line belongs *to* that line. Conflating them moves a trailing note onto the
/// wrong row.
pub fn comments(src: &str) -> Vec<Comment> {
    lex(src)
        .map(|toks| {
            toks.iter()
                .filter_map(|t| match &t.kind {
                    TokenKind::Comment(text) => Some(Comment {
                        text: text.clone(),
                        span: t.span,
                        own_line: line_before_is_blank(src, t.span.start),
                    }),
                    _ => None,
                })
                .collect()
        })
        .unwrap_or_default()
}

/// A comment, and where it sat.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comment {
    /// The text, including the leading `#`.
    pub text: String,
    pub span: Span,
    /// Nothing but whitespace precedes it on its line.
    pub own_line: bool,
}

fn line_before_is_blank(src: &str, start: usize) -> bool {
    src[..start.min(src.len())]
        .rsplit('\n')
        .next()
        .is_some_and(|prefix| prefix.trim().is_empty())
}

/// Parse a single blue expression. Convenience for tests and the REPL.
pub fn parse_expr(src: &str) -> Result<Sexp, ParseError> {
    let forms = parse_program(src)?;
    match forms.len() {
        1 => Ok(forms.into_iter().next().expect("checked len")),
        n => Err(ParseError::new(
            format!("expected exactly one expression, found {n}"),
            Span::new(0, src.len()),
        )
        .located(src)),
    }
}

/// What an infix operator binds like, and what it lowers to.
///
/// **One row per operator, carrying both facts.** Precedence and callee
/// used to live apart, and the cost was immediate: the surface spelling was
/// emitted verbatim, so `a == b` lowered to `(== a b)` — a symbol no
/// interpreter binds — and the program died at *runtime* with `unbound
/// symbol ==`. Splitting the two invites exactly that: add an operator to
/// the precedence table, forget the lowering, ship a parse that cannot run.
/// Joined here, "has a precedence" and "has a callee" are the same fact.
#[derive(Clone, Copy, Debug)]
pub struct Infix {
    /// Surface spelling.
    pub op: &'static str,
    /// Left and right binding power. Higher binds tighter.
    pub power: (u8, u8),
    /// The tatara-lisp callee this lowers to.
    pub callee: &'static str,
    /// One line for a reader: what the operator computes, and the trap in it
    /// when there is one. `blue reference` prints it; a row without one fails
    /// `every_operator_and_keyword_is_described`.
    pub doc: &'static str,
}

/// The complete infix table. Precedence follows Ruby's where Ruby has an
/// opinion; `|>` (below) sits under everything so `a |> f |> g` chains
/// without parentheses.
pub const INFIX: &[Infix] = &[
    Infix {
        op: "||",
        power: (1, 2),
        callee: "or",
        doc: "Logical or: the left value if truthy, otherwise the right; the right is evaluated only when needed.",
    },
    Infix {
        op: "&&",
        power: (3, 4),
        callee: "and",
        doc: "Logical and: the right value if the left is truthy, otherwise the left; short-circuits.",
    },
    // `==` is STRUCTURAL equality, so it lowers to `equal?` and not to `=`.
    //
    // tatara's `=` is NUMERIC comparison: `"a" = "a"` is a type error, not
    // false. Lowering `==` to it meant every string, list or nil comparison
    // failed with "expected number, got string" — found by blue's own spec
    // suite the moment a test compared two strings, which is the first thing
    // anybody does.
    //
    // `equal?` is structural and total over the value domain: strings, lists
    // and nil all compare, and numbers still compare as numbers.
    Infix {
        op: "==",
        power: (5, 6),
        callee: "equal?",
        doc: "Structural equality over every value (okite D0001): 4 == 4.0, lists and maps by content, nil only equals nil.",
    },
    Infix {
        op: "!=",
        power: (5, 6),
        callee: "not=",
        doc: "Exactly not(a == b) (okite D0002).",
    },
    Infix {
        op: "<",
        power: (5, 6),
        callee: "<",
        doc: "Numeric less-than. A string operand is a type error: order text with compare(a, b).",
    },
    Infix {
        op: "<=",
        power: (5, 6),
        callee: "<=",
        doc: "Numeric less-than-or-equal. Numbers only, like <.",
    },
    Infix {
        op: ">",
        power: (5, 6),
        callee: ">",
        doc: "Numeric greater-than. Numbers only, like <.",
    },
    Infix {
        op: ">=",
        power: (5, 6),
        callee: ">=",
        doc: "Numeric greater-than-or-equal. Numbers only, like <.",
    },
    Infix {
        op: "+",
        power: (7, 8),
        callee: "+",
        doc: "Numeric addition; an Int and a Float give a Float. Not string concatenation: interpolate instead.",
    },
    Infix {
        op: "-",
        power: (7, 8),
        callee: "-",
        doc: "Numeric subtraction. Written before an operand with nothing on its left, it is unary minus: -n.",
    },
    Infix {
        op: "*",
        power: (9, 10),
        callee: "*",
        doc: "Numeric multiplication.",
    },
    Infix {
        op: "/",
        power: (9, 10),
        callee: "/",
        doc: "Division that never truncates (okite D0008): 7 / 2 is 3.5, while 6 / 2 stays the Int 3. Integer division is floor(a / b).",
    },
    Infix {
        op: "%",
        power: (9, 10),
        callee: "mod",
        doc: "Euclidean remainder: never negative, so (0 - 7) % 3 is 2, not -1. A zero divisor is a runtime error.",
    },
];

/// Every surface keyword that BEGINS an expression.
///
/// Exists so the formatter's corpus can be checked against it. Three separate
/// times a form was added to this parser, the formatter was not extended, and
/// all three formatting laws still passed — because the corpus is
/// hand-maintained and contained no example of the new form. The annotated
/// `def` rendered as a method send; `defmacro` rendered as
/// `defmacro(double, x(), …)`, which does not re-parse at all.
///
/// A law cannot notice a case nobody wrote down. `blue-lang-fmt`'s
/// `every_surface_keyword_appears_in_the_corpus` closes that by making the
/// omission itself the failure, so adding a keyword here forces the corpus
/// entry that exercises the other three laws over it.
///
/// `do` and `end` are absent deliberately: they are block delimiters, not
/// expression heads, and have no standalone rendering to test.
/// The callee `assert e` lowers to.
///
/// **Owned here, by the lowering itself, and read by every consumer.** It was
/// briefly a literal here and a separate `const` in `blue-lang-test`, and the
/// shadowing gate then could not see a parser that lowered to the wrong name:
/// the gate checked its own copy. Same duplication class as the operator table.
pub const LOWERED_ASSERT: &str = "blue-assert";

/// The callee a `{...}` map literal lowers to.
///
/// **`hash-map`, not `map`.** tatara binds `map` to the higher-order function,
/// so a literal lowering to `(map …)` called the HOF with the key/value pairs
/// as arguments and failed with "expected list, got int". Same shadowing class
/// as [`LOWERED_ASSERT`], caught by the same gate once the name was listed
/// there — it was not, which is why this shipped.
pub const LOWERED_MAP: &str = "hash-map";

/// The callee string interpolation lowers to.
///
/// blue's own `concat`, which renders either side through `to_s` — that is what
/// lets `"n=#{42}"` interpolate a number. Not `+`, which is arithmetic.
pub const LOWERED_CONCAT: &str = "concat";

pub const SURFACE_KEYWORDS: &[&str] = &[
    "if",
    "unless",
    "def",
    "defmacro",
    "quote",
    "unquote",
    "unquote_splice",
    "test",
    "assert",
    "fn",
    "case",
];

/// The words that are reserved but are not heads of a `SURFACE_KEYWORDS` form
/// — block delimiters and the three literals.
///
/// Split out as data rather than inlined in a `matches!` because a reserved
/// word is not only the parser's business: a highlighter has to paint exactly
/// this set, and one that reads `SURFACE_KEYWORDS` alone silently under-paints
/// `do` / `end` / `else` / `elsif`. That was not hypothetical — escriba's
/// `escriba-render/src/langs.rs` hand-transcribed "SURFACE_KEYWORDS plus the
/// four block words `is_reserved_word` adds", because the union was
/// unreachable from outside this module. A transcription is a second
/// definition, and it drifts the first time this list changes.
pub const BLOCK_KEYWORDS: &[&str] = &["do", "end", "else", "elsif", "true", "false", "nil"];

/// A surface keyword may not be rebound. `if = 1` is a mistake, not a binding,
/// and letting it through would shadow the form for the rest of the file.
///
/// Public because it is the ONE answer to "is this identifier a keyword" —
/// the parser's rebinding check and every downstream highlighter read it here
/// rather than each carrying its own copy of the list.
pub fn is_reserved_word(name: &str) -> bool {
    SURFACE_KEYWORDS.contains(&name) || BLOCK_KEYWORDS.contains(&name)
}

/// Can `name` be written as the head of a call — `name(…)`?
///
/// True exactly when the lexer reads `name` as one identifier and it is not
/// reserved. Answered BY the lexer rather than by a character class copied
/// from it, so the two cannot disagree: the formatter asks this before
/// printing a tree as `name(args)`, and a head such as `hash-map`, `not=` or
/// `if` — which a tree can carry and a call cannot spell — must get a
/// different rendering or none.
pub fn is_callable_name(name: &str) -> bool {
    // `retsu/first` is written `retsu::first(…)`.
    if qualified(name).is_some() {
        return true;
    }
    !is_reserved_word(name)
        && matches!(
            lex(name).as_deref(),
            Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == name)
                && e.kind == TokenKind::Eof
        )
}

/// The character a qualified name's AST symbol joins its two halves with:
/// `retsu::first` is the symbol `retsu/first`. The surface never writes it
/// (`/` is division, and no identifier can contain it), which is what makes
/// a symbol with text on both sides of one `/` unambiguously qualified.
pub const QUALIFIER: char = '/';

/// The AST symbol for `pkg::name`.
#[must_use]
pub fn qualify(pkg: &str, name: &str) -> String {
    format!("{pkg}{QUALIFIER}{name}")
}

/// `retsu/first` → `Some(("retsu", "first"))`: the package and the name of a
/// qualified symbol. `None` for every other symbol, `/` (division) included.
///
/// The ONE reader of the shape, so the formatter, the name table and the
/// runtime's renderer cannot disagree about what counts as qualified.
#[must_use]
pub fn qualified(sym: &str) -> Option<(&str, &str)> {
    let (pkg, name) = sym.split_once(QUALIFIER)?;
    let ident = |s: &str| {
        matches!(
            lex(s).as_deref(),
            Ok([t, e]) if matches!(&t.kind, TokenKind::Ident(n) if n == s) && e.kind == TokenKind::Eof
        )
    };
    let named = |s: &str| ident(s) || matches!(s, "true" | "false" | "nil");
    (ident(pkg) && !is_reserved_word(pkg) && named(name)).then_some((pkg, name))
}

/// One line for a reader on each reserved word: what it writes, and the shape.
///
/// Beside the two tables rather than inside them, because both are `&[&str]`
/// read by the formatter's corpus gate and by highlighters outside this repo;
/// changing their type would break every one of those readers.
/// `every_operator_and_keyword_is_described` makes a word without a line here a
/// red build, so the omission cannot ship. `blue reference` prints these.
#[must_use]
pub fn keyword_doc(word: &str) -> &'static str {
    match word {
        "if" => "`if c … elsif d … else … end`: an expression; its value is the branch taken, nil when none is.",
        "unless" => "`unless c … end`: `if !c`. The formatter writes it as `if !c`.",
        "def" => "`def name(a, b) … end`: a named function; its value is the last expression. Parameters may be typed: `def f(n: Int) -> Int`.",
        "defmacro" => "`defmacro name(x) quote … unquote(x) … end end`: a macro, a rewrite of the unevaluated form.",
        "quote" => "`quote … end`: the form itself as data, not its value. Used inside `defmacro`.",
        "unquote" => "`unquote(x)`: inside `quote`, splice in the value of `x`.",
        "unquote_splice" => "`unquote_splice(xs)`: inside `quote`, splice the items of the form `xs` in place, not the form itself.",
        "test" => "`test \"what must hold\" … end`: a test block, run by `blue test` and ignored by `blue run`.",
        "assert" => "`assert expr`: inside a test, fail it unless `expr` is truthy; the failure quotes the expression.",
        "fn" => "`fn(x) x * 2 end`: an anonymous function, a value. Blue has no brace or do blocks.",
        "case" => "`case v when 1 … when 2 … else … end`: compares with `==`; it does not destructure.",
        "do" => "Reserved and refused: blue has no do-blocks. Pass `fn(x) … end` instead.",
        "end" => "Closes `def`, `defmacro`, `if`, `case`, `fn`, `test` and `quote`.",
        "else" => "The branch of `if` or `case` taken when nothing before it matched.",
        "elsif" => "A further condition in an `if` chain; the formatter writes nested `else if` as `elsif`.",
        "true" => "The boolean true.",
        "false" => "The boolean false. Only `false` and `nil` are falsy; 0, \"\" and [] are truthy.",
        "nil" => "The absent value. It is not `[]` (okite D0004), and only `nil == nil`.",
        _ => "",
    }
}

fn infix(op: &str) -> Option<&'static Infix> {
    INFIX.iter().find(|i| i.op == op)
}

const PIPE_POWER: (u8, u8) = (0, 1);

struct Parser {
    toks: Vec<Token>,
    pos: usize,
    /// Current expression-nesting depth, bounded by [`Self::max_depth`].
    ///
    /// Without this the parser does not fail on deep input — it **aborts the
    /// process** with a stack overflow (SIGABRT), which `catch_unwind` cannot
    /// catch. Measured 2026-08-01: `"(".repeat(2_000)` killed the test runner
    /// outright. Every consumer inherited it — an LSP parsing a half-typed
    /// line, a formatter, and shikumi loading a `.b` config off disk.
    depth: usize,
    /// The bound [`Self::depth`] is checked against.
    ///
    /// Defaults to [`MAX_EXPR_DEPTH`] on every entry point that does not name
    /// one; `parse_program_with_depth` exists so an operator can raise it
    /// without recompiling. It is a **bound**, so raising it changes no
    /// program's meaning — only which pathological inputs are refused.
    max_depth: usize,
}

/// Maximum expression nesting before the parser refuses.
///
/// Chosen well above anything human-written (blue's own `spec/*.b` peaks in
/// single digits) and far below the measured overflow point, so the bound is
/// hit as a typed `Err` long before the stack is at risk. A limit that is
/// merely *near* the crash point is not a safety bound; it is a race.
pub const MAX_EXPR_DEPTH: usize = 256;

/// The parser's internal error: a [`ParseError`] behind a pointer.
///
/// Every production returns a `Result`, and a debug build keeps several per
/// frame down the recursion, so the error's size is paid at every level of
/// nesting whether or not anything fails. Measured 2026-09-29 on a 2 MiB
/// debug thread, parsing `(((…1…)))` with no bound: the unboxed 40-byte error
/// overflowed between 255 and 260 levels, barely past [`MAX_EXPR_DEPTH`];
/// adding `line`/`col` unboxed moved it to 240–250, under the bound, and
/// `depth_beyond_the_limit_is_an_err_not_an_abort` aborted. Boxed, the
/// overflow is between 300 and 310. The error path is cold; the pointer is
/// what keeps the bound a bound.
type Fail = Box<ParseError>;

fn fail(message: impl Into<String>, span: Span) -> Fail {
    Box::new(ParseError::new(message, span))
}

impl Parser {
    fn peek(&self) -> &TokenKind {
        &self.toks[self.pos.min(self.toks.len() - 1)].kind
    }

    fn peek_span(&self) -> Span {
        self.toks[self.pos.min(self.toks.len() - 1)].span
    }

    fn bump(&mut self) -> TokenKind {
        let k = self.toks[self.pos.min(self.toks.len() - 1)].kind.clone();
        if self.pos < self.toks.len() {
            self.pos += 1;
        }
        k
    }

    fn at(&self, k: &TokenKind) -> bool {
        self.peek() == k
    }

    fn eat(&mut self, k: &TokenKind) -> bool {
        if self.at(k) {
            self.bump();
            true
        } else {
            false
        }
    }

    fn expect(&mut self, k: &TokenKind, what: &str) -> Result<(), Fail> {
        if self.eat(k) {
            Ok(())
        } else {
            Err(self.error(format!("expected {what}, found {}", self.peek())))
        }
    }

    fn error(&self, message: impl Into<String>) -> Fail {
        fail(message, self.peek_span())
    }

    /// Skip statement separators (newlines and semicolon-free layout).
    fn skip_newlines(&mut self) {
        while matches!(self.peek(), TokenKind::Newline) {
            self.bump();
        }
    }

    fn at_ident(&self, name: &str) -> bool {
        matches!(self.peek(), TokenKind::Ident(n) if n == name)
    }

    /// Byte offset where the next token begins — the anchor a production spans
    /// *from*. Paired with [`Self::span_since`].
    fn mark(&self) -> usize {
        self.peek_span().start
    }

    /// The span from `start` to the end of the **last consumed** token.
    ///
    /// `pos` has already advanced past that token, so this looks one back. Call
    /// it after a production has consumed everything it owns; calling it early
    /// yields a span that stops short of the node it describes.
    fn span_since(&self, start: usize) -> Span {
        let end = self
            .toks
            .get(self.pos.saturating_sub(1))
            .map_or(start, |t| t.span.end);
        Span::new(start, end.max(start))
    }

    fn program(&mut self) -> Result<Vec<Spanned>, Fail> {
        let mut out = Vec::new();
        loop {
            self.skip_newlines();
            if matches!(self.peek(), TokenKind::Eof) {
                break;
            }
            out.push(self.statement()?);
            self.end_of_statement(&[])?;
        }
        Ok(out)
    }

    /// **A statement ends at the end of its line.** Refuse anything else.
    ///
    /// The lexer has always said newlines "are statement separators", and the
    /// parser never asked for one: `program` and `body` looped over
    /// `statement()` and started the next one wherever the last stopped. So a
    /// form blue does not have became two forms it does, silently —
    /// `y = xs[0]` parsed as `y = xs` then the list `[0]`, and Ruby's
    /// `a = f x` as `a = f` then `x`. Both ran; both bound the wrong value.
    ///
    /// **Refused rather than given a meaning**, because each would be a second
    /// spelling of a tree blue already spells one way (§0's FORM axis):
    /// indexing is the call `nth(i, xs)`, and a call has parentheses. `;` is
    /// refused by the lexer for the same reason — one separator, the newline.
    ///
    /// What may follow a statement: a newline, the end of the file, or — in a
    /// body — the keyword that closes it, which is what keeps
    /// `fn(x) x + 1 end` a one-line lambda.
    fn end_of_statement(&self, terminators: &[&str]) -> Result<(), Fail> {
        let next = self.peek();
        if matches!(next, TokenKind::Newline | TokenKind::Eof)
            || terminators.iter().any(|t| self.at_ident(t))
        {
            return Ok(());
        }
        let prev = self.toks.get(self.pos.wrapping_sub(1)).map(|t| &t.kind);
        let prev_name = match prev {
            Some(TokenKind::Ident(n)) => Some(n.as_str()),
            _ => None,
        };
        let callee = prev_name.unwrap_or("f");
        let why = match (prev, next) {
            (Some(TokenKind::Ident(t)), _) if t == "then" => {
                "blue's `if` has no `then`: put the branch on the next line".to_string()
            }
            (_, TokenKind::Ident(d)) if d == "do" => "blue has no `do` blocks: pass a function \
                 as an argument, `f(xs, fn(x) … end)`"
                .to_string(),
            (_, TokenKind::LBracket) => {
                let index = match (self.toks.get(self.pos + 1), self.toks.get(self.pos + 2)) {
                    (Some(i), Some(close)) if close.kind == TokenKind::RBracket => match &i.kind {
                        TokenKind::Int(n) => n.to_string(),
                        TokenKind::Ident(n) => n.clone(),
                        _ => "i".to_string(),
                    },
                    _ => "i".to_string(),
                };
                let list = prev_name.unwrap_or("xs");
                format!(
                    "blue has no `xs[i]` indexing: write `nth({index}, {list})` \
                     (or `first({list})`, `last({list})`)"
                )
            }
            (_, TokenKind::LBrace) => "blue has no brace blocks: pass a function as an \
                 argument, `map(xs, fn(x) … end)`"
                .to_string(),
            (
                Some(TokenKind::Ident(_)),
                TokenKind::Ident(_)
                | TokenKind::Int(_)
                | TokenKind::Float(_)
                | TokenKind::Str(_)
                | TokenKind::InterpolatedStr { .. }
                | TokenKind::Sym(_)
                | TokenKind::True
                | TokenKind::False
                | TokenKind::Nil,
            ) => {
                let arg = match next {
                    TokenKind::Ident(a) => a.clone(),
                    _ => "x".to_string(),
                };
                format!("a call needs parentheses: write `{callee}({arg})`")
            }
            _ => "put each statement on its own line".to_string(),
        };
        Err(self.error(format!("expected the end of the line, found {next}: {why}")))
    }

    /// A statement: either a binding or an expression.
    ///
    /// `x = 5` lowers to `(define x 5)`. Blue had NO way to name a value — a
    /// capability probe found `x = 5` was a parse error, which makes every
    /// program a single expression. That is more fundamental than anything else
    /// the probe found.
    ///
    /// Only at STATEMENT position, never inside an expression, so `f(x = 1)` is
    /// still an error rather than a silent binding. Ruby allows assignment as an
    /// expression and it is a well-known footgun — `if x = 1` where `==` was
    /// meant. Blue declines it, and the cost is only that a walrus-style idiom
    /// has to be two lines.
    fn statement(&mut self) -> Result<Spanned, Fail> {
        // The SECOND recursion cycle, and it needs the same guard as `expr`.
        //
        // Guarding `expr` alone was not enough — measured 2026-08-01: with the
        // expression bound in place, `"def a\n".repeat(2_000)` STILL aborted
        // the process. Block nesting (`def` opening a body that contains more
        // statements) recurses through here, not through `expr`, so a fix
        // applied to one cycle silently left the other reachable. Two paths to
        // the same crash; one guard covered one of them.
        //
        // Shares `self.depth` with `expr` on purpose: what the stack cares
        // about is TOTAL nesting, not which grammar production produced it, so
        // two independent counters would each permit their own full budget and
        // together exceed what the stack can hold.
        let max = self.max_depth;
        if self.depth >= max {
            return Err(self.error(format!(
                "statement nests deeper than {max}; refusing to \
                 recurse further (this is a limit, not a syntax error)"
            )));
        }
        self.depth += 1;
        let r = self.statement_inner();
        self.depth -= 1;
        r
    }

    fn statement_inner(&mut self) -> Result<Spanned, Fail> {
        if let TokenKind::Ident(name) = self.peek().clone() {
            if self.peek_at(1) == "=" && !is_reserved_word(&name) {
                let name_span = self.peek_span();
                self.bump(); // name
                self.bump(); // =
                self.skip_newlines();
                let value = self.expr(0)?;
                // `define` is synthesized — `x = 5` contains no such word — so
                // it takes the span of the name being bound, which is what a
                // reader looks at when told something about the binding.
                return Ok(list_at(
                    self.span_since(name_span.start),
                    vec![sym_at(name_span, "define"), sym_at(name_span, &name), value],
                ));
            }
        }
        self.expr(0)
    }

    /// The token `n` positions ahead, for the two-token lookahead a binding
    /// needs. Returns `Eof` past the end rather than panicking.
    fn peek_at(&self, n: usize) -> String {
        match self.toks.get(self.pos + n).map(|t| &t.kind) {
            Some(TokenKind::Op(o)) => o.clone(),
            _ => String::new(),
        }
    }

    /// Pratt loop.
    fn expr(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
        // Depth guard at the single recursion cycle (`expr` -> `prefix` ->
        // `expr`). Returning an Err here converts an UNRECOVERABLE abort into
        // an ordinary parse failure a caller can render — the difference
        // between an LSP showing a squiggle and an LSP being gone.
        //
        // The decrement is deliberately not RAII: every exit from this
        // function is via `?` or a normal return, and both are covered by the
        // explicit decrements below. A guard object would be tidier but would
        // also hide the invariant this comment is here to state.
        let max = self.max_depth;
        if self.depth >= max {
            return Err(self.error(format!(
                "expression nests deeper than {max}; refusing to \
                 recurse further (this is a limit, not a syntax error)"
            )));
        }
        self.depth += 1;
        let r = self.expr_inner(min_bp);
        self.depth -= 1;
        r
    }

    fn expr_inner(&mut self, min_bp: u8) -> Result<Spanned, Fail> {
        let start = self.mark();
        let mut lhs = self.prefix()?;

        loop {
            // Postfix: `.name`, `.name(args)`, `(args)`
            match self.peek() {
                TokenKind::Dot => {
                    self.bump();
                    lhs = self.finish_send(start, lhs)?;
                    continue;
                }
                TokenKind::LParen => {
                    // A call on an expression already parsed: `f(x)`.
                    let args = self.paren_args()?;
                    let mut list = vec![lhs];
                    list.extend(args);
                    lhs = list_at(self.span_since(start), list);
                    continue;
                }
                _ => {}
            }

            // Infix
            // `callee == None` marks the pipeline, which is a rewrite rather
            // than a call.
            let op_span = self.peek_span();
            let (callee, (lbp, rbp)) = match self.peek() {
                TokenKind::Pipe => (None, PIPE_POWER),
                TokenKind::Op(o) => match infix(o) {
                    Some(i) => (Some(i.callee), i.power),
                    None => break,
                },
                _ => break,
            };
            if lbp < min_bp {
                break;
            }
            self.bump();
            self.skip_newlines();
            let rhs = self.expr(rbp)?;

            lhs = if callee.is_none() {
                // `x |> f`      => (f x)
                // `x |> f(a)`   => (f x a)   — the pipeline threads into
                //                  the FIRST argument position, as Elixir's
                //                  does; that is what makes it composable.
                let rhs_span = rhs.span;
                match rhs.form {
                    SpannedForm::List(mut items) if !items.is_empty() => {
                        items.insert(1, lhs);
                        list_at(self.span_since(start), items)
                    }
                    callee => list_at(
                        self.span_since(start),
                        vec![Spanned::new(rhs_span, callee), lhs],
                    ),
                }
            } else {
                // The callee symbol takes the OPERATOR's span, not the whole
                // expression's: `a + b` lowers to `(+ a b)` and the `+` node is
                // the one byte-range in the source that means it. Handing it the
                // whole expression's span would make a diagnostic about the
                // operator underline both operands too.
                list_at(
                    self.span_since(start),
                    vec![sym_at(op_span, callee.unwrap()), lhs, rhs],
                )
            };
        }

        Ok(lhs)
    }

    fn prefix(&mut self) -> Result<Spanned, Fail> {
        let span = self.peek_span();
        match self.bump() {
            TokenKind::Int(v) => Ok(atom_at(span, Atom::Int(v))),
            TokenKind::Float(v) => Ok(atom_at(span, Atom::Float(v))),
            TokenKind::Str(s) => Ok(atom_at(span, Atom::Str(s))),

            // `"a#{x}b"` → `(concat (concat "a" x) "b")`.
            //
            // Lowered to `concat`, not to `+`: blue's `+` is arithmetic (see
            // the INFIX table), and interpolation must render a value of ANY
            // type — `concat` goes through `to_s`, which is what makes
            // `"n=#{42}"` work.
            //
            // The expression source is parsed HERE with the ordinary parser
            // rather than lexed inside the string, so an interpolation can hold
            // anything an expression can and the two can never drift.
            TokenKind::InterpolatedStr { parts, exprs } => {
                // Every node here carries the WHOLE string literal's span.
                //
                // The inner expression is parsed from `raw` — a substring — so
                // its own offsets index that substring, not `src`. Carrying them
                // through would produce spans that look real and point into a
                // buffer nobody has: for `"a#{x}"` at offset 40, `x`'s span
                // would be 0..1, i.e. the start of the file. The lexer does not
                // record where each part sat in the outer source, so the string
                // literal is the most precise honest answer available.
                let mut acc = atom_at(span, Atom::Str(parts[0].clone()));
                for (i, raw) in exprs.iter().enumerate() {
                    let inner = parse_expr(raw).map_err(|e| {
                        fail(
                            format!("in interpolation `#{{{raw}}}`: {}", e.message),
                            span,
                        )
                    })?;
                    let inner = Spanned::from_sexp_at(&inner, span);
                    acc = list_at(span, vec![sym_at(span, LOWERED_CONCAT), acc, inner]);
                    // `parts.len() == exprs.len() + 1` by construction, so this
                    // index is always in range.
                    acc = list_at(
                        span,
                        vec![
                            sym_at(span, LOWERED_CONCAT),
                            acc,
                            atom_at(span, Atom::Str(parts[i + 1].clone())),
                        ],
                    );
                }
                Ok(acc)
            }
            TokenKind::Sym(s) => Ok(atom_at(span, Atom::Keyword(s))),
            TokenKind::True => Ok(atom_at(span, Atom::Bool(true))),
            TokenKind::False => Ok(atom_at(span, Atom::Bool(false))),
            TokenKind::Nil => Ok(Spanned::new(span, SpannedForm::Nil)),

            TokenKind::Op(o) if o == "-" => {
                let rhs = self.expr(11)?; // binds tighter than `*`
                Ok(list_at(
                    self.span_since(span.start),
                    vec![sym_at(span, "-"), atom_at(span, Atom::Int(0)), rhs],
                ))
            }
            TokenKind::Op(o) if o == "!" => {
                let rhs = self.expr(11)?;
                Ok(list_at(
                    self.span_since(span.start),
                    vec![sym_at(span, "not"), rhs],
                ))
            }

            TokenKind::LParen => {
                self.skip_newlines();
                let inner = self.expr(0)?;
                self.skip_newlines();
                self.expect(&TokenKind::RParen, "`)`")?;
                // The inner expression's own span, NOT one widened to include
                // the parentheses: grouping is not part of the expression's
                // meaning, and `(a + b)` should underline `a + b`.
                Ok(inner)
            }

            TokenKind::LBracket => self.list_literal(span),
            TokenKind::LBrace => self.map_literal(span),

            TokenKind::Ident(name) if self.at(&TokenKind::PathSep) => {
                self.qualified_name(span, &name)
            }
            TokenKind::PathSep => Err(fail(
                "a qualified name is `package::name`, with the package written before `::`",
                span,
            )),
            TokenKind::Ident(name) => match name.as_str() {
                "if" => self.if_form(span, false),
                "unless" => self.if_form(span, true),
                "def" => self.def_form(span),
                "defmacro" => self.defmacro_form(span),
                "case" => self.case_form(span),
                "fn" => self.lambda_form(span),
                "test" => self.test_form(span),
                "assert" => self.assert_form(span),
                "quote" => self.quote_form(span),
                "unquote" => self.unquote_form(span, false),
                "unquote_splice" => self.unquote_form(span, true),
                "do" => Err(fail(
                    "blue has no `do` blocks: pass a function as an argument, \
                     `f(xs, fn(x) … end)`",
                    span,
                )),
                "end" => Err(fail(
                    "unexpected `end`: nothing open here for it to close",
                    span,
                )),
                _ => Ok(sym_at(span, &name)),
            },

            other => Err(fail(format!("expected an expression, found {other}"), span)),
        }
    }

    /// After `package`, at `::`: `retsu::first` lowers to the ONE symbol
    /// `retsu/first` — tatara's `require` shape, so a qualified name means the
    /// same thing in both lisps.
    ///
    /// After `::` any identifier is a name, reserved words included:
    /// `kueri::if` names kueri's definition, never the `if` form, because a
    /// reserved word is reserved only where it could start a form. The
    /// package side is never a reserved word, and a name has exactly one
    /// qualifier (`a::b::c` is refused), since a package is one level deep.
    fn qualified_name(&mut self, pkg_span: Span, pkg: &str) -> Result<Spanned, Fail> {
        if is_reserved_word(pkg) {
            return Err(fail(
                format!("`{pkg}` is a reserved word and cannot name a package"),
                pkg_span,
            ));
        }
        self.bump(); // ::
        let name_span = self.peek_span();
        let name = match self.bump() {
            TokenKind::Ident(n) => n,
            // `true`, `false` and `nil` lex as their own tokens.
            TokenKind::True => "true".to_string(),
            TokenKind::False => "false".to_string(),
            TokenKind::Nil => "nil".to_string(),
            other => {
                return Err(fail(
                    format!("expected a name after `{pkg}::`, found {other}"),
                    name_span,
                ))
            }
        };
        if self.at(&TokenKind::PathSep) {
            return Err(self.error(format!(
                "a qualified name has one qualifier: `package::name`, and `{pkg}::{name}::…` has two"
            )));
        }
        Ok(sym_at(
            self.span_since(pkg_span.start),
            &qualify(pkg, &name),
        ))
    }

    /// After a `.`: `recv.name` or `recv.name(args)`.
    ///
    /// **A bare `recv.name` is a SEND, not a field read.** Blue commits to
    /// the uniform access principle here: a structure exposes no public
    /// fields, so a field can later become a computed method without
    /// breaking a caller.
    fn finish_send(&mut self, start: usize, recv: Spanned) -> Result<Spanned, Fail> {
        let name_span = self.peek_span();
        let name = match self.bump() {
            // A RESERVED WORD is not a method name.
            //
            // Found by the formatter property suite, minimal input `1.def`.
            // The send parsed happily into `(def 1)` — `def` is just an
            // identifier to the lexer — and the formatter then rendered that
            // as `def(1)`, which the parser rejects. So `format` turned valid
            // source into source that does not parse: corruption, not a style
            // choice, and silent until a round-trip property looked.
            //
            // Rejecting here rather than teaching the formatter to quote it
            // fixes the class instead of the symptom: `x.if`, `x.end` and
            // `x.case` all lower onto special forms the same way, and none of
            // them is a method anyone meant to call.
            TokenKind::Ident(n) if is_reserved_word(&n) => {
                return Err(self.error(format!(
                    "`{n}` is a reserved word and cannot be a method name — \
                     `recv.{n}` would lower onto the `{n}` form itself"
                )))
            }
            TokenKind::Ident(n) => n,
            other => {
                return Err(fail(
                    format!("expected a method name after `.`, found {other}"),
                    name_span,
                ))
            }
        };
        let mut list = vec![sym_at(name_span, &name), recv];
        if self.at(&TokenKind::LParen) {
            list.extend(self.paren_args()?);
        }
        Ok(list_at(self.span_since(start), list))
    }

    fn paren_args(&mut self) -> Result<Vec<Spanned>, Fail> {
        self.expect(&TokenKind::LParen, "`(`")?;
        let mut args = Vec::new();
        self.skip_newlines();
        if self.eat(&TokenKind::RParen) {
            return Ok(args);
        }
        loop {
            self.skip_newlines();
            args.push(self.expr(0)?);
            self.skip_newlines();
            if self.eat(&TokenKind::Comma) {
                continue;
            }
            self.expect(&TokenKind::RParen, "`,` or `)`")?;
            break;
        }
        Ok(args)
    }

    fn list_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
        let mut items = vec![sym_at(open, "list")];
        self.skip_newlines();
        if self.eat(&TokenKind::RBracket) {
            return Ok(list_at(self.span_since(open.start), items));
        }
        loop {
            self.skip_newlines();
            items.push(self.expr(0)?);
            self.skip_newlines();
            if self.eat(&TokenKind::Comma) {
                continue;
            }
            self.expect(&TokenKind::RBracket, "`,` or `]`")?;
            break;
        }
        Ok(list_at(self.span_since(open.start), items))
    }

    /// `{a: 1, "k" => v}` — both spellings, one tree.
    ///
    /// This is §V.13's rendering law at the parser: `a: 1` and `:a => 1`
    /// produce the *same* s-expression, which is precisely why the
    /// formatter may always choose the shorthand. The rocket survives only
    /// where the key is not a plain symbol.
    fn map_literal(&mut self, open: Span) -> Result<Spanned, Fail> {
        let mut items = vec![sym_at(open, LOWERED_MAP)];
        self.skip_newlines();
        if self.eat(&TokenKind::RBrace) {
            return Ok(list_at(self.span_since(open.start), items));
        }
        loop {
            self.skip_newlines();
            match self.peek().clone() {
                TokenKind::Label(name) => {
                    let label_span = self.peek_span();
                    self.bump();
                    self.skip_newlines();
                    items.push(atom_at(label_span, Atom::Keyword(name)));
                    items.push(self.expr(0)?);
                }
                _ => {
                    let k = self.expr(0)?;
                    self.skip_newlines();
                    self.expect(&TokenKind::Rocket, "`=>` in a map literal")?;
                    self.skip_newlines();
                    items.push(k);
                    items.push(self.expr(0)?);
                }
            }
            self.skip_newlines();
            if self.eat(&TokenKind::Comma) {
                continue;
            }
            self.expect(&TokenKind::RBrace, "`,` or `}`")?;
            break;
        }
        Ok(list_at(self.span_since(open.start), items))
    }

    /// `if c ... [else ...] end`, and `unless` as its negation.
    ///
    /// `unless` lowers to `(if (not c) ...)` rather than to a distinct
    /// form: one tree per meaning, so the formatter and every downstream
    /// tool see exactly one shape.
    /// An `elsif` arm: an `if` that does NOT consume the closing `end`.
    ///
    /// `if / elsif / elsif / else / end` is one `end` for the whole chain, so
    /// every arm but the first must leave it for its parent.
    fn if_chain(&mut self, head: Span) -> Result<Spanned, Fail> {
        let cond = self.expr(0)?;
        let then = self.body(&["elsif", "else", "end"])?;
        let els = if self.at_ident("elsif") {
            let elsif = self.peek_span();
            self.bump();
            Some(self.if_chain(elsif)?)
        } else if self.at_ident("else") {
            self.bump();
            let e = self.body(&["end"])?;
            self.expect_ident("end")?;
            Some(e)
        } else {
            self.expect_ident("end")?;
            None
        };
        let mut out = vec![sym_at(head, "if"), cond, then];
        if let Some(e) = els {
            out.push(e);
        }
        Ok(list_at(self.span_since(head.start), out))
    }

    fn if_form(&mut self, head: Span, negate: bool) -> Result<Spanned, Fail> {
        let cond = self.expr(0)?;
        let cond = if negate {
            // `unless c` lowers to `(if (not c) …)`. The synthesized `not` takes
            // the `unless` keyword's span — that word is what put it there.
            let inner = cond.span;
            list_at(head.merge(inner), vec![sym_at(head, "not"), cond])
        } else {
            cond
        };
        // `elsif` terminates the then-body too, or the chain is swallowed.
        //
        // It used to be absent entirely — not a keyword, not reserved, nowhere
        // in this file — so `elsif cond` parsed as a stray expression inside
        // the then-body and the branch it guarded VANISHED. No error: the
        // program ran and returned the `else` value. Measured:
        //
        //   if a < 1 then 1 elsif a < 5 then 2 else 3 end   with a = 3
        //     wanted 2, returned 3
        //
        // A silent wrong answer in the most-used control form in the language,
        // reachable by writing the Ruby every blue user already knows.
        let then = self.body(&["elsif", "else", "end"])?;
        let els = if self.at_ident("elsif") {
            let elsif = self.peek_span();
            self.bump();
            // The chain shares ONE `end`, so recurse without consuming it and
            // let the outermost `if` close the whole thing.
            Some(self.if_chain(elsif)?)
        } else if self.at_ident("else") {
            self.bump();
            let e = self.body(&["end"])?;
            self.expect_ident("end")?;
            Some(e)
        } else {
            self.expect_ident("end")?;
            None
        };
        let mut out = vec![sym_at(head, "if"), cond, then];
        if let Some(e) = els {
            out.push(e);
        }
        Ok(list_at(self.span_since(head.start), out))
    }

    /// `def name(a, b) ... end`            => `(define (name a b) body)`
    /// `def name(a: T, b: T) -> R ... end`  => `(define-typed (name (a T) (b T)) R body)`
    ///
    /// **The two shapes are deliberately different heads.** §0 says an
    /// unannotated program gets ZERO analysis, and the cleanest way to
    /// mean that is for untyped code not to reach the typing machinery at
    /// all — not to reach it and be waved through. A checker that must
    /// walk every node to discover there is nothing to check has already
    /// paid the cost the ladder exists to avoid.
    ///
    /// Annotations are per-parameter, so a signature may be partially
    /// annotated. That is the ladder at its finest grain: `a: Int` is
    /// checked and a bare `b` stays `dyn`, in the same signature.
    /// `case subject / when a / … / else / … / end` => a `cond` over equality.
    ///
    /// **Value matching, not destructuring.** Elixir's `case` binds pattern
    /// variables; blue's compares with the same `equal?` the `==` operator uses,
    /// so `when [1, 2]` matches a list by value. Destructuring needs a pattern
    /// language and a binder, which blue does not have — and a `case` that
    /// *looked* like Elixir's while silently only comparing would be worse than
    /// one that plainly compares.
    ///
    /// The subject is evaluated ONCE, into a binding, so `case expensive()` does
    /// not re-run per arm. That is a correctness property, not an optimisation:
    /// a subject with a side effect would fire once per `when`.
    fn case_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let subject = self.expr(0)?;
        self.skip_newlines();

        // A fresh name the surface cannot spell, so it cannot capture a user
        // binding of the same name.
        let subject_var = "case-subject";
        let mut arms: Vec<Spanned> = Vec::new();
        let mut otherwise: Option<Spanned> = None;
        // The `else` keyword's own span, so the synthesized `(else body)` clause
        // sits where the author wrote it rather than back at `case`.
        let mut else_kw: Option<Span> = None;

        loop {
            self.skip_newlines();
            if self.at_ident("end") {
                break;
            }
            let maybe_else = self.peek_span();
            if self.eat_ident("else") {
                else_kw = Some(maybe_else);
                otherwise = Some(self.body(&["end"])?);
                continue;
            }
            let when = self.peek_span();
            if !self.eat_ident("when") {
                return Err(self.error(format!(
                    "expected `when`, `else` or `end` in a case, found {}",
                    self.peek()
                )));
            }
            self.skip_newlines();
            let pattern = self.expr(0)?;
            let body = self.body(&["when", "else", "end"])?;
            // The synthesized comparison takes the arm's `when` span: that word
            // is what put an `equal?` there, and it is where a reader looks when
            // told an arm cannot match.
            let test = list_at(
                when.merge(pattern.span),
                vec![sym_at(when, "equal?"), sym_at(when, subject_var), pattern],
            );
            arms.push(list_at(when.merge(body.span), vec![test, body]));
        }
        self.expect_ident("end")?;

        if arms.is_empty() && otherwise.is_none() {
            return Err(self.error("a case needs at least one `when` or an `else`".to_string()));
        }

        // A case with no matching arm and no else is NIL, matching Ruby. Elixir
        // raises CaseClauseError; blue follows Ruby because its `if` without an
        // else is already nil, and having two different answers to "no branch
        // taken" in one language is the inconsistency.
        let mut cond = vec![sym_at(head, "cond")];
        cond.extend(arms);
        // The `else` clause spans its own keyword through its body. Anchoring it
        // at `head` — the `case` keyword — put a node whose subtree sits at the
        // END of the form at a span near its START, so the else body escaped its
        // parent's range entirely. `every_node_sits_inside_its_parents_span`
        // caught that; it is the kind of mistake no output-shape test can see,
        // because the tree is correct and only the positions are wrong.
        let else_span = else_kw.unwrap_or(head);
        let else_body = otherwise.unwrap_or_else(|| Spanned::new(else_span, SpannedForm::Nil));
        cond.push(list_at(
            else_span.merge(else_body.span),
            vec![sym_at(else_span, "else"), else_body],
        ));

        let whole = self.span_since(head.start);
        let binding = list_at(
            head.merge(subject.span),
            vec![sym_at(head, subject_var), subject],
        );
        Ok(list_at(
            whole,
            vec![
                sym_at(head, "let"),
                list_at(binding.span, vec![binding]),
                list_at(whole, cond),
            ],
        ))
    }

    /// `fn(a, b) ... end` => `(lambda (a b) body)`
    ///
    /// Without this the higher-order functions are unreachable in practice:
    /// `map(inc, xs)` works only because `inc` happens to be a named stdlib
    /// function, and there was no way to write the one-off the call site
    /// actually wants.
    ///
    /// `fn` rather than Ruby's `->` or `lambda`: `->` collides with the return-
    /// type arrow the typed `def` already uses, and reusing one glyph for two
    /// unrelated things is the ambiguity the FORM axis exists to prevent.
    fn lambda_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let mut params: Vec<Spanned> = Vec::new();
        if self.at(&TokenKind::LParen) {
            self.bump();
            self.skip_newlines();
            if !self.eat(&TokenKind::RParen) {
                loop {
                    self.skip_newlines();
                    let p_span = self.peek_span();
                    match self.bump() {
                        TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
                        other => {
                            return Err(fail(
                                format!("expected a parameter name, found {other}"),
                                p_span,
                            ))
                        }
                    }
                    self.skip_newlines();
                    if self.eat(&TokenKind::Comma) {
                        continue;
                    }
                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
                    break;
                }
            }
        }
        let params_span = cover(&params, head);
        let body = self.body(&["end"])?;
        self.expect_ident("end")?;
        Ok(list_at(
            self.span_since(head.start),
            vec![sym_at(head, "lambda"), list_at(params_span, params), body],
        ))
    }

    /// `test "name" ... end` => `(deftest "name" body)`
    ///
    /// A string, not an identifier: a test name is prose for a human report,
    /// and forcing it into an identifier is how test names become
    /// `test_adds_two_numbers_correctly`.
    fn test_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let name_span = self.peek_span();
        let name = match self.bump() {
            TokenKind::Str(s) => s,
            other => {
                return Err(fail(
                    format!("expected a string name after `test`, found {other}"),
                    name_span,
                ))
            }
        };
        let body = self.body(&["end"])?;
        self.expect_ident("end")?;
        Ok(list_at(
            self.span_since(head.start),
            vec![
                sym_at(head, "deftest"),
                atom_at(name_span, Atom::Str(name)),
                body,
            ],
        ))
    }

    /// `assert expr` => `(blue-assert 'expr expr)`
    ///
    /// **`blue-assert`, not `assert`.** tatara-lisp's stdlib already defines
    /// `assert` as a macro — `(defmacro assert (pred message) …)` — and a macro
    /// in the expander is consulted before any primitive in the registry. So
    /// lowering to `assert` bound `pred` to the *quoted form*, which is
    /// truthy, and **every assertion silently passed**. A test framework whose
    /// assertions always pass is the worst defect it can have: every test in
    /// the suite goes green.
    ///
    /// The lesson generalizes: any name blue lowers to that tatara already
    /// binds is silently captured. `blue_lang_test`'s
    /// `no_lowered_name_is_shadowed_by_the_runtime` gates the whole class.
    ///
    /// **Both the form and the value.** A test framework whose failure says
    /// only "assertion failed" makes the author re-derive what they were
    /// checking; one that shows the expression does not. The quoted form is
    /// the expression as DATA, so the runner can render it — and it renders it
    /// through `blue-lang-fmt`, meaning the failure message is in canonical
    /// blue syntax rather than the underlying tatara-lisp.
    ///
    /// This is homoiconicity paying for itself: the capture needs no source
    /// map, no macro hygiene, and no string of the original text.
    fn assert_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let e = self.expr(0)?;
        let quoted = Spanned::new(e.span, SpannedForm::Quote(Box::new(e.clone())));
        Ok(list_at(
            self.span_since(head.start),
            vec![sym_at(head, LOWERED_ASSERT), quoted, e],
        ))
    }

    /// `defmacro name(a, b) ... end` => `(defmacro name (a b) body)`
    ///
    /// **Deliberately untyped.** A macro's parameters are *source forms*, not
    /// values, so `a: Int` would be a category error: the argument at expansion
    /// time is a fragment of syntax. §IV's ladder types values; macro
    /// parameters are not on it. Annotating one is rejected rather than
    /// silently ignored — an ignored annotation is how an author comes to
    /// believe a check is running.
    fn defmacro_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let name_span = self.peek_span();
        let name = match self.bump() {
            TokenKind::Ident(n) => n,
            other => {
                return Err(fail(
                    format!("expected a name after `defmacro`, found {other}"),
                    name_span,
                ))
            }
        };
        let mut params: Vec<Spanned> = Vec::new();
        if self.at(&TokenKind::LParen) {
            self.bump();
            self.skip_newlines();
            if !self.eat(&TokenKind::RParen) {
                loop {
                    self.skip_newlines();
                    let p_span = self.peek_span();
                    match self.bump() {
                        TokenKind::Ident(p) => params.push(sym_at(p_span, &p)),
                        TokenKind::Label(p) => {
                            return Err(self.error(format!(
                                "macro parameter `{p}` cannot be typed: a macro receives \
                                 source forms, not values"
                            )))
                        }
                        other => {
                            return Err(fail(
                                format!("expected a parameter name, found {other}"),
                                p_span,
                            ))
                        }
                    }
                    self.skip_newlines();
                    if self.eat(&TokenKind::Comma) {
                        continue;
                    }
                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
                    break;
                }
            }
        }
        if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
            return Err(self.error(
                "a macro has no return type: it produces source forms, not values".to_string(),
            ));
        }

        let params_span = cover(&params, name_span);
        let body = self.body(&["end"])?;
        self.expect_ident("end")?;

        // `(defmacro name (params) body)` — tatara-lisp's own shape, so blue
        // registers into the SAME expander rather than a parallel one.
        Ok(list_at(
            self.span_since(head.start),
            vec![
                sym_at(head, "defmacro"),
                sym_at(name_span, &name),
                list_at(params_span, params),
                body,
            ],
        ))
    }

    /// `quote ... end` => `` `body `` (a quasiquote).
    ///
    /// Quasiquote rather than plain quote, because a macro body that could not
    /// splice its arguments in would be useless — this is Elixir's `quote do`,
    /// which is likewise a template and not inert data.
    fn quote_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let body = self.body(&["end"])?;
        self.expect_ident("end")?;
        // `Sexp::Quasiquote`, NOT `(quasiquote body)` as a list.
        //
        // The list form Displays as the text `(quasiquote …)`, which the
        // tatara-lisp reader reads back as an ordinary list whose head happens
        // to be the symbol `quasiquote` — losing the structure. The evaluator
        // then reached the inner `,x` with no enclosing quasiquote and rejected
        // it: "unquote outside of quasiquote". Building the real variant makes
        // it Display as `` ` `` and survive the round trip.
        Ok(Spanned::new(
            self.span_since(head.start),
            SpannedForm::Quasiquote(Box::new(body)),
        ))
    }

    /// `unquote(expr)` => `,expr`; `unquote_splice(expr)` => `,@expr`.
    fn unquote_form(&mut self, head: Span, splice: bool) -> Result<Spanned, Fail> {
        self.expect(&TokenKind::LParen, "`(` after unquote")?;
        self.skip_newlines();
        let inner = self.expr(0)?;
        self.skip_newlines();
        self.expect(&TokenKind::RParen, "`)`")?;
        let span = self.span_since(head.start);
        Ok(Spanned::new(
            span,
            if splice {
                SpannedForm::UnquoteSplice(Box::new(inner))
            } else {
                SpannedForm::Unquote(Box::new(inner))
            },
        ))
    }

    fn def_form(&mut self, head: Span) -> Result<Spanned, Fail> {
        let name_span = self.peek_span();
        let name = match self.bump() {
            TokenKind::Ident(n) => n,
            other => {
                return Err(fail(
                    format!("expected a name after `def`, found {other}"),
                    name_span,
                ))
            }
        };
        let mut params: Vec<(String, Span, Option<Spanned>)> = Vec::new();
        if self.at(&TokenKind::LParen) {
            self.bump();
            self.skip_newlines();
            if !self.eat(&TokenKind::RParen) {
                loop {
                    self.skip_newlines();
                    let p_span = self.peek_span();
                    match self.bump() {
                        // `a` — unannotated
                        TokenKind::Ident(p) => params.push((p, p_span, None)),
                        // `a:` came through as one token, so a type follows
                        TokenKind::Label(p) => {
                            self.skip_newlines();
                            let ty = self.type_expr()?;
                            params.push((p, p_span, Some(ty)));
                        }
                        other => {
                            return Err(fail(
                                format!("expected a parameter name, found {other}"),
                                p_span,
                            ))
                        }
                    }
                    self.skip_newlines();
                    if self.eat(&TokenKind::Comma) {
                        continue;
                    }
                    self.expect(&TokenKind::RParen, "`,` or `)`")?;
                    break;
                }
            }
        }
        // The signature list spans the name through the closing `)`.
        let sig_span = self.span_since(name_span.start);

        // Optional `-> R`
        let ret = if matches!(self.peek(), TokenKind::Op(o) if o == "->") {
            self.bump();
            self.skip_newlines();
            Some(self.type_expr()?)
        } else {
            None
        };

        let body = self.body(&["end"])?;
        self.expect_ident("end")?;
        let whole = self.span_since(head.start);

        let annotated = ret.is_some() || params.iter().any(|(_, _, t)| t.is_some());
        if !annotated {
            let mut sig = vec![sym_at(name_span, &name)];
            sig.extend(params.into_iter().map(|(p, s, _)| sym_at(s, &p)));
            return Ok(list_at(
                whole,
                vec![sym_at(head, "define"), list_at(sig_span, sig), body],
            ));
        }

        // Typed shape. An un-annotated parameter in an otherwise annotated
        // signature is written `(p dyn)` so the checker sees the ladder
        // position explicitly rather than inferring it from absence.
        //
        // A `dyn` written by the parser rather than the author takes the
        // parameter's own span, so a diagnostic about it points at the
        // parameter — the only thing in the source it could mean.
        let mut sig = vec![sym_at(name_span, &name)];
        for (p, s, t) in params {
            let ty = t.unwrap_or_else(|| sym_at(s, "dyn"));
            sig.push(list_at(s.merge(ty.span), vec![sym_at(s, &p), ty]));
        }
        Ok(list_at(
            whole,
            vec![
                sym_at(head, "define-typed"),
                list_at(sig_span, sig),
                ret.unwrap_or_else(|| sym_at(head, "dyn")),
                body,
            ],
        ))
    }

    /// A type expression. Currently a bare name (`Int`, `Str`, `dyn`) or a
    /// one-argument constructor (`List(Int)`).
    fn type_expr(&mut self) -> Result<Spanned, Fail> {
        let name_span = self.peek_span();
        let name = match self.bump() {
            TokenKind::Ident(n) => n,
            other => {
                return Err(fail(
                    format!("expected a type name, found {other}"),
                    name_span,
                ))
            }
        };
        if self.at(&TokenKind::LParen) {
            let args = self.paren_args()?;
            let mut list = vec![sym_at(name_span, &name)];
            list.extend(args);
            return Ok(list_at(self.span_since(name_span.start), list));
        }
        Ok(sym_at(name_span, &name))
    }

    /// Consume `name` if it is the next token, else leave the position alone.
    fn eat_ident(&mut self, name: &str) -> bool {
        if self.at_ident(name) {
            self.bump();
            true
        } else {
            false
        }
    }

    fn expect_ident(&mut self, name: &str) -> Result<(), Fail> {
        if self.at_ident(name) {
            self.bump();
            Ok(())
        } else {
            Err(self.error(format!("expected `{name}`, found {}", self.peek())))
        }
    }

    /// A sequence of expressions up to one of `terminators`, wrapped in
    /// `(begin ...)` when there is more than one.
    fn body(&mut self, terminators: &[&str]) -> Result<Spanned, Fail> {
        // Anchored BEFORE the leading newlines are skipped, so an empty body's
        // span sits where the body would have started.
        let start = self.mark();
        let mut forms = Vec::new();
        loop {
            self.skip_newlines();
            if matches!(self.peek(), TokenKind::Eof) {
                return Err(self.error(format!(
                    "unterminated block: expected {} before the end of the file",
                    one_of(terminators)
                )));
            }
            if terminators.iter().any(|t| self.at_ident(t)) {
                break;
            }
            forms.push(self.statement()?);
            self.end_of_statement(terminators)?;
        }
        Ok(match forms.len() {
            0 => Spanned::new(Span::new(start, start), SpannedForm::Nil),
            1 => forms.into_iter().next().expect("checked len"),
            _ => {
                // `cover`, NOT `span_since`: the loop breaks *before* consuming
                // the terminator but *after* `skip_newlines`, so the last token
                // behind `pos` can be a newline and `span_since` would stretch
                // the body across trailing blank lines. The forms know exactly
                // where they are.
                let span = cover(&forms, Span::new(start, start));
                // The synthesized `begin` is zero-width at the FIRST FORM's
                // start, not at `start`. `start` is anchored before the leading
                // newlines are skipped, so it sits earlier than the body itself
                // — and a head node outside its own list's span is a span bug
                // that `every_node_sits_inside_its_parents_span` reports.
                let head = Span::new(span.start, span.start);
                let mut list = vec![sym_at(head, "begin")];
                list.extend(forms);
                list_at(span, list)
            }
        })
    }
}

/// `` `a` ``, `` `a` or `b` ``, `` `a`, `b` or `c` `` — a list of keywords as
/// a sentence says it.
fn one_of(words: &[&str]) -> String {
    let quoted: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
    match quoted.split_last() {
        None => String::new(),
        Some((last, [])) => last.clone(),
        Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
    }
}

/// A symbol node at `span`.
fn sym_at(span: Span, s: &str) -> Spanned {
    Spanned::new(span, SpannedForm::Atom(Atom::Symbol(s.to_string())))
}

/// An atom node at `span`.
fn atom_at(span: Span, a: Atom) -> Spanned {
    Spanned::new(span, SpannedForm::Atom(a))
}

/// A list node at `span`.
fn list_at(span: Span, items: Vec<Spanned>) -> Spanned {
    Spanned::new(span, SpannedForm::List(items))
}

/// The smallest span covering every node in `items`, or `fallback` when there
/// are none.
///
/// The fallback is a parameter rather than `Span::synthetic()` because a
/// synthetic span is a claim that a node has no source origin at all — and an
/// empty parameter list in `def f()` very much has one. Defaulting to synthetic
/// here is how "no span" leaks into a tree where every node does have a place.
fn cover(items: &[Spanned], fallback: Span) -> Span {
    let merged = items
        .iter()
        .fold(Span::synthetic(), |acc, s| acc.merge(s.span));
    if merged.is_synthetic() {
        fallback
    } else {
        merged
    }
}

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

    /// Render an `Sexp` to canonical text so tests can state the expected
    /// quoted form as a string. This is `Display`, which tatara-lisp owns —
    /// blue does not build Lisp syntax by concatenation.
    fn q(src: &str) -> String {
        parse_expr(src)
            .map(|s| s.to_string())
            .unwrap_or_else(|e| panic!("{src:?}: {e}"))
    }

    // ---- the thesis: Ruby-shaped source becomes tatara-lisp ----------

    #[test]
    fn arithmetic_respects_precedence() {
        assert_eq!(q("1 + 2 * 3"), "(+ 1 (* 2 3))");
        assert_eq!(q("(1 + 2) * 3"), "(* (+ 1 2) 3)");
    }

    #[test]
    fn comparison_binds_looser_than_arithmetic() {
        assert_eq!(q("a + 1 < b"), "(< (+ a 1) b)");
    }

    /// The expected tree names `or`/`and`, not `||`/`&&`: the surface
    /// spelling is the SURFACE's, and lowering renames it to the form
    /// tatara-lisp actually has. This test previously asserted the verbatim
    /// spelling, which is how `(== a b)` — a symbol nothing binds — shipped.
    #[test]
    fn logical_operators_bind_loosest_and_lower_to_tataras_names() {
        assert_eq!(q("a && b || c"), "(or (and a b) c)");
    }

    #[test]
    fn left_associativity() {
        assert_eq!(q("1 - 2 - 3"), "(- (- 1 2) 3)");
    }

    /// A bare `recv.name` is a SEND. Blue commits to uniform access here,
    /// so a field can later become a computed method without breaking
    /// callers.
    #[test]
    fn method_call_without_parens_is_a_send() {
        assert_eq!(q("user.name"), "(name user)");
    }

    #[test]
    fn method_call_with_args() {
        assert_eq!(q("user.greet(1, 2)"), "(greet user 1 2)");
    }

    #[test]
    fn chained_sends_read_left_to_right() {
        assert_eq!(q("a.b.c"), "(c (b a))");
    }

    #[test]
    fn plain_call() {
        assert_eq!(q("f(1, 2)"), "(f 1 2)");
    }

    /// The pipeline threads into the FIRST argument, as Elixir's does —
    /// that is what makes `|>` composable rather than decorative.
    #[test]
    fn pipeline_threads_into_first_argument() {
        assert_eq!(q("x |> f"), "(f x)");
        assert_eq!(q("x |> f(1)"), "(f x 1)");
        assert_eq!(q("x |> f |> g"), "(g (f x))");
    }

    #[test]
    fn pipeline_binds_looser_than_arithmetic() {
        assert_eq!(q("1 + 2 |> f"), "(f (+ 1 2))");
    }

    // ---- §V.13's rendering law, enforced at the parser ---------------

    /// `a: 1` and `:a => 1` are the SAME TREE. That is exactly why the
    /// formatter may always render the shorthand: they are not two
    /// spellings of two things, they are two spellings of one thing.
    #[test]
    fn label_and_rocket_produce_the_same_tree_for_a_symbol_key() {
        assert_eq!(q("{a: 1}"), q("{:a => 1}"));
        assert_eq!(q("{a: 1}"), "(hash-map :a 1)");
    }

    /// And where the key is NOT a plain symbol, the rocket is the only
    /// spelling — so it survives because it must, never as a style choice.
    #[test]
    fn a_string_key_has_no_shorthand() {
        assert_eq!(q(r#"{"k" => 1}"#), r#"(hash-map "k" 1)"#);
    }

    #[test]
    fn list_literal() {
        assert_eq!(q("[1, 2, 3]"), "(list 1 2 3)");
        assert_eq!(q("[]"), "(list)");
    }

    // ---- blocks ------------------------------------------------------

    #[test]
    fn if_else_end() {
        assert_eq!(q("if a\n  1\nelse\n  2\nend"), "(if a 1 2)");
    }

    #[test]
    fn if_without_else() {
        assert_eq!(q("if a\n  1\nend"), "(if a 1)");
    }

    /// `unless` lowers to `(if (not c) …)` — one tree per meaning, so
    /// every downstream tool sees exactly one shape.
    #[test]
    fn unless_is_a_negated_if() {
        assert_eq!(q("unless a\n  1\nend"), "(if (not a) 1)");
    }

    #[test]
    fn multi_statement_body_becomes_begin() {
        assert_eq!(q("if a\n  1\n  2\nend"), "(if a (begin 1 2))");
    }

    #[test]
    fn def_lowers_to_define() {
        assert_eq!(
            q("def add(a, b)\n  a + b\nend"),
            "(define (add a b) (+ a b))"
        );
    }

    #[test]
    fn def_with_no_params() {
        assert_eq!(q("def zero()\n  0\nend"), "(define (zero) 0)");
    }

    // ---- literals ----------------------------------------------------

    #[test]
    fn literals_lower_to_atoms() {
        assert_eq!(q("42"), "42");
        assert_eq!(q("true"), "#t");
        assert_eq!(q(":ok"), ":ok");
        assert_eq!(q(r#""hi""#), r#""hi""#);
    }

    #[test]
    fn unary_minus_and_not() {
        assert_eq!(q("-x"), "(- 0 x)");
        assert_eq!(q("!x"), "(not x)");
    }

    // ---- programs and errors -----------------------------------------

    #[test]
    fn a_program_is_a_sequence_of_forms() {
        let forms = parse_program("def f()\n  1\nend\nf()").expect("parse");
        assert_eq!(forms.len(), 2);
        assert_eq!(forms[1].to_string(), "(f)");
    }

    #[test]
    fn unterminated_block_is_an_error_naming_what_was_expected() {
        let e = parse_program("if a\n  1").expect_err("must fail");
        assert!(e.message.contains("unterminated"), "{}", e.message);
    }

    #[test]
    fn a_parse_error_carries_a_span_into_the_source() {
        let src = "1 + )";
        let e = parse_program(src).expect_err("must fail");
        assert!(e.span.start < src.len(), "span {:?} outside source", e.span);
    }

    // ---- one statement per line -------------------------------------

    /// `y = xs[0]` was TWO statements, `(define y xs)` and `(list 0)`: nothing
    /// required a separator between statements, so the parser finished `xs`,
    /// saw a list literal and started a new statement on the same line. The
    /// program ran and `y` was the whole list. Found by the 2026-09-29 audit.
    #[test]
    fn postfix_indexing_is_refused_naming_nth() {
        let e = parse_program("y = xs[0]").expect_err("must not split into two statements");
        assert!(e.message.contains("`nth(0, xs)`"), "{}", e.message);
        assert_eq!((e.line, e.col), (1, 7), "{e}");
    }

    /// `a = f x` — Ruby's command call — parsed as `a = f` and then `x`.
    #[test]
    fn a_call_without_parentheses_is_refused_naming_the_call() {
        let e = parse_program("a = f x").expect_err("must not split into two statements");
        assert!(e.message.contains("`f(x)`"), "{}", e.message);
        assert_eq!((e.line, e.col), (1, 7), "{e}");
    }

    /// The same rule inside a block body, and in every body shape.
    #[test]
    fn two_statements_on_one_line_are_refused_in_a_body() {
        for src in [
            "def f(xs)\n  xs[0]\nend",
            "if a\n  f x\nend",
            "fn(x) x 1 end",
            "test \"t\"\n  assert a b\nend",
            "1 2",
        ] {
            assert!(parse_program(src).is_err(), "{src:?} must not parse");
        }
    }

    /// The controls: every place a statement legitimately ends on its line.
    /// A block keyword closing the body on the same line is one of them, which
    /// is what keeps a one-line lambda one line.
    #[test]
    fn a_statement_may_end_at_a_newline_the_end_or_a_closing_keyword() {
        for src in [
            "fn(x) x + 1 end",
            "map(fn(x) x end, xs)",
            "if a\n  1\nelse\n  2\nend",
            "if a 1 else 2 end",
            "case x\nwhen 1 :a\nwhen 2 :b\nelse :c\nend",
            "x = 1\ny = 2",
            "x = 1",
        ] {
            assert!(
                parse_program(src).is_ok(),
                "{src:?}: {:?}",
                parse_program(src)
            );
        }
    }

    /// `if c then a else b end` read `then` as a statement and `a` as another.
    #[test]
    fn then_is_refused_by_name() {
        let e = parse_program("x = if c then 1 else 2 end").expect_err("then is not a keyword");
        assert!(e.message.contains("`then`"), "{}", e.message);
    }

    /// A brace block after a send is not a map literal the author meant.
    #[test]
    fn a_brace_block_is_refused_naming_fn() {
        let e = parse_program("xs.map { |x| x }").expect_err("no brace blocks");
        assert!(e.message.contains("fn(x)"), "{}", e.message);
    }

    // ---- qualified names ------------------------------------------------

    /// `retsu::first(xs)` is one symbol, tatara's `require` shape.
    ///
    /// Red run (2026-09-29), before the `::` token: `expected an expression,
    /// found `:``.
    #[test]
    fn a_qualified_name_is_one_symbol() {
        assert_eq!(q("retsu::first(xs)"), "(retsu/first xs)");
        assert_eq!(q("retsu::first"), "retsu/first");
        assert_eq!(q("xs |> retsu::first"), "(retsu/first xs)");
        assert_eq!(q("blue::length(xs)"), "(blue/length xs)");
    }

    /// Whitespace around `::` is layout, not meaning.
    #[test]
    fn whitespace_around_the_qualifier_is_accepted() {
        assert_eq!(q("retsu :: first(xs)"), "(retsu/first xs)");
    }

    /// After `::` a reserved word is a name: `kueri::if` is kueri's
    /// definition, not the `if` form.
    #[test]
    fn a_reserved_word_after_the_qualifier_is_a_name() {
        assert_eq!(q("kueri::if(a, b)"), "(kueri/if a b)");
        assert_eq!(q("heni::test(x)"), "(heni/test x)");
        assert_eq!(q("sabi::fn"), "sabi/fn");
    }

    #[test]
    fn a_qualified_name_has_exactly_one_qualifier() {
        for (src, says) in [
            ("::first(xs)", "`package::name`"),
            ("a::b::c", "one qualifier"),
            ("if::x", "reserved word"),
            ("retsu::1", "expected a name after `retsu::`"),
        ] {
            let e = parse_program(src).expect_err(src);
            assert!(e.message.contains(says), "{src}: {}", e.message);
        }
    }

    /// The one reader of the shape: division is not qualified, and neither
    /// is anything the surface could not have written.
    #[test]
    fn qualified_reads_only_the_package_name_shape() {
        assert_eq!(qualified("retsu/first"), Some(("retsu", "first")));
        assert_eq!(qualified("kueri/if"), Some(("kueri", "if")));
        assert_eq!(qualified("nisshi/pair?"), Some(("nisshi", "pair?")));
        for not in ["/", "a/", "/a", "a/b/c", "if/x", "hash-map", "a"] {
            assert_eq!(qualified(not), None, "{not}");
        }
        assert!(is_callable_name("kueri/if"));
    }

    /// `:pair?` is the symbol `pair?`: an import list can name a predicate.
    ///
    /// Red run (2026-09-29), before: `unexpected character `?``, found by
    /// `blue migrate` listing nisshi's `pair?`.
    #[test]
    fn a_symbol_may_end_in_a_question_or_bang() {
        assert_eq!(q("[:pair?, :set!]"), "(list :pair? :set!)");
        assert_eq!(q("use(\"n\", [:empty?])"), "(use \"n\" (list :empty?))");
        assert_eq!(q(":a != :b"), "(not= :a :b)");
    }

    // ---- errors a person can read -------------------------------------

    /// `line:col` and blue's words, never `at 10..11` and `Ident("y")`.
    #[test]
    fn a_parse_error_displays_line_col_and_the_source_text() {
        let e = parse_program("x = 1\ny = [1, 2 y]").expect_err("must fail");
        assert_eq!(e.to_string(), "2:11: expected `,` or `]`, found `y`");
        assert_eq!(e.span, Span::new(16, 17), "the span stays, as data");
    }

    /// Every token kind renders without Rust's `Debug` shape.
    #[test]
    fn no_error_message_names_a_rust_variant() {
        for src in [
            "f(1 2)",
            "{a: 1 b}",
            "def 1\nend",
            "x.1",
            "if a\n",
            "fn(1) 2 end",
            "[1 :b]",
            "1 +",
            "(1",
        ] {
            let e = parse_program(src).expect_err(src);
            let shown = e.to_string();
            for tell in [
                "Ident(", "Int(", "Op(", "Label(", "Sym(", "Str(", "LParen", "RBracket", "Eof",
                "Newline", "..",
            ] {
                assert!(!shown.contains(tell), "{src:?} -> {shown}");
            }
            assert!(e.line >= 1 && e.col >= 1, "{src:?} not located: {shown}");
        }
    }

    /// A lex error reaches the author through the same door, located.
    #[test]
    fn a_lex_error_is_located_too() {
        let e = parse_program("x = 1\ny = 2; z = 3").expect_err("no semicolons");
        assert_eq!((e.line, e.col), (2, 6), "{e}");
        assert!(e.message.contains("new line"), "{e}");
    }

    /// Anti-vacuity: `q` must be able to FAIL. If every input parsed, the
    /// assertions above would be worthless.
    #[test]
    fn the_parser_rejects_garbage() {
        assert!(parse_program("def").is_err());
        assert!(parse_program("(1").is_err());
        assert!(parse_program("end").is_err());
    }
}