htl-core 0.6.3

Engine of htl (Holistic Typed Lua): Teal check / gen / lint / fmt / test / bundle on an embedded mlua state. Use the `htl` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
//! htl: Teal, hidden.
//!
//! Embeds the Teal compiler (`tl.lua`) into an mlua state so `.tl` sources can be
//! type-checked, generated and executed without any external toolchain.
//!
//! - [`Htl::check`] / [`Htl::gen_lua`]: type-check and generate Lua from a `.tl` file
//! - [`Htl::install_searcher`]: strict `require` for `.tl` (type errors abort the require)
//! - [`Htl::preload`]: register generated Lua (e.g. from `include_tl!`) under a module name
//! - [`bundle`]: stripped-bytecode bundles produced by `htl build`
//!
//! Two libraries ship inside the binary rather than on a project's search path, and both
//! are installed the same way — a `package.preload` entry for the run, a `.d.tl` under
//! [`lib_dir`] for the checker: `htl.test` ([`Htl::install_test_lib`], `describe` / `it` /
//! `expect`) and, with the `std` feature, `std.*` — mlua-batteries' modules under the
//! namespace that crate leaves to its host. The method that installs them is named and
//! linked below when the feature that compiles it is on; a link to an item that is not
//! compiled is a broken one.
#![cfg_attr(
    feature = "std",
    doc = "
//! That method is [`Htl::install_std`]."
)]
// Every public item here is `htl`'s public API: that crate is `pub use htl_core::*;`, and
// `missing_docs` fires where an item is defined rather than where it is re-exported — so
// the ratchet `htl` took in #224 does nothing for the half a reader actually meets unless
// it is here too. It arrives with the change that took the count to zero, which is the
// only moment it costs nothing and the only one at which it is true.
#![deny(missing_docs)]

pub use mlua;

use anyhow::{Context, Result, anyhow, bail};
use mlua::chunk::ChunkMode;
use mlua::{Function, Lua, Table, Value, Variadic};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

pub mod build_target;
pub mod bundle;
pub mod cache;
#[cfg(feature = "dts")]
pub mod cexport;
pub mod config;
pub mod contract;
#[cfg(feature = "dts")]
pub mod dep_dts;
pub mod diagnostic;
#[cfg(feature = "dts")]
pub mod dts;
#[cfg(feature = "ffi")]
pub mod ffi;
pub mod fix;
// The rules there are, and which of them a run has on. Both halves of htl report under
// these names, so the list is here rather than in `lint.lua`, which is one of the halves.
pub mod link;
pub mod lint;
#[cfg(feature = "pkg")]
pub mod pkg;
// The project layer: a walk over many files, the run cache under it, and the decisions
// both `htl check` and a macro expansion make about that store. It reaches the mlua-pkg
// project a file belongs to and the Cargo package around it, so it asks for the two
// features that provide them; every consumer that has a project to check has both.
#[cfg(all(feature = "pkg", feature = "dts"))]
pub mod project;
// What one module name resolves to, and what that hides. Reads the project the same way
// the project layer does — the installed deps, the config's search paths, the notes `htl
// dts` leaves under `types/<crate>/` — so it carries the same features.
#[cfg(all(feature = "pkg", feature = "dts"))]
pub mod resolve;
// `std.*`: mlua-batteries, preloaded and declared the way `htl.test` is. Its own module
// rather than a corner of `testing.rs` because the two libraries are unrelated apart from
// how they are installed, and that part they share through `lib_dir`. Named for the crate
// and not for the namespace: a module called `std` at the crate root would shadow `::std`
// in every path this file writes.
#[cfg(feature = "std")]
pub mod batteries;
pub mod teal;
pub mod testing;
// The complement of the require closure: what no entry reaches. On the project layer,
// whose check hands it the graph, so it carries that layer's features.
#[cfg(all(feature = "pkg", feature = "dts"))]
pub mod unused;

pub use build_target::BuildTarget;
pub use diagnostic::{Diagnostic, Severity};
pub use teal::Strict;

/// Registry key under which the prelude table is stored (lets `pkg::TealResolver`
/// reach the compiler from a bare `&Lua`).
pub(crate) const PRELUDE_REGISTRY_KEY: &str = "htl.prelude";

const TL_SRC: &str = include_str!("../vendor/tl.lua");
const LINT_SRC: &str = include_str!("lint.lua");
const FMT_SRC: &str = include_str!("fmt.lua");
const PRELUDE: &str = include_str!("prelude.lua");

/// A hash of the Lua the checker is made of: the vendored `tl`, the lints, the formatter
/// and the prelude. Two builds with the same value generate the same Lua for the same
/// input, whatever else differs about them.
///
/// The run cache stamps its entries with this ([`cache`]). The CLI also stamps them with
/// its own binary, which moves on every rebuild; inside a proc macro the binary is
/// `rustc`, which does not move when htl does, and this is what tells those entries apart
/// from a checker that no longer exists.
pub fn checker_identity() -> &'static str {
    static ID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    ID.get_or_init(|| {
        let mut h = blake3::Hasher::new();
        for src in [TL_SRC, LINT_SRC, FMT_SRC, PRELUDE] {
            h.update(src.as_bytes());
            h.update(b"\0");
        }
        h.finalize().to_hex().to_string()
    })
}

/// Teal version vendored into this crate.
pub const TEAL_VERSION: &str = "0.24.8";

/// Result of type-checking one `.tl` file.
#[derive(Debug, Clone, Default)]
pub struct CheckInfo {
    /// `file:line:col: message` for syntax and type errors.
    pub errors: Vec<String>,
    /// `file:line:col: message` for warnings (non-fatal).
    pub warnings: Vec<String>,
    /// Files pulled in via `require` during checking (`.tl` / `.d.tl` / `.lua`).
    pub deps: Vec<PathBuf>,
    /// htl lint findings (`nil-index`, `enum-exhaustive`). Advisory unless the caller
    /// promotes them (`htl check --strict`, `include_tl!`).
    pub lints: Vec<String>,
    /// Every `require("<literal>")` in the file and where the checker resolved it.
    /// Input to [`require_cycles`].
    pub requires: Vec<RequireSite>,
    /// `error_fixes[i]` is the fix for `errors[i]`, when the error has one.
    pub error_fixes: Vec<Option<Fix>>,
    /// `lint_fixes[i]` is the fix for `lints[i]`, when the lint has one.
    pub lint_fixes: Vec<Option<Fix>>,
    /// Type errors in the modules this check pulled in through `require`, transitively,
    /// each dependency once. Not in `errors`, and not what [`ok`](Self::ok) answers: the
    /// file itself checked, and generates; it is the `require` of that module that will
    /// raise at run time ([`Htl::install_searcher`]), which is why a caller reporting on a
    /// project treats these as errors too (`htl check`, `include_tl!`).
    pub dependency_errors: Vec<DependencyError>,
}

/// A type error in a module a check reached through `require` (see
/// [`CheckInfo::dependency_errors`]).
///
/// The checker checks a required module into the same environment and hands the
/// requirer its *type*; the module's own errors stay with the module's result. This is
/// that result's error, said against the file that required it, so a report can name
/// both — a dependency is only ever checked through a `require`, since its sources are
/// not the project's to walk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DependencyError {
    /// The file the error is in, as the checker found it on the search path.
    pub file: PathBuf,
    /// The file whose `require` (direct or through another dependency) pulled it in:
    /// the first one on this check's walk.
    pub required_by: PathBuf,
    /// `file:line:col: message`, formatted as the file's own errors are.
    pub text: String,
}

/// How safely a [`Fix`] can be applied without a human looking at it.
///
/// Serializes as its [`as_str`](Applicability::as_str) name, which is what a stored fix
/// and `--format json` both carry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Applicability {
    /// The rewrite does not change what the program does at run time.
    Safe,
    /// It may; applied only when asked (`htl fix --unsafe`).
    Unsafe,
    /// Shown, never applied (a placeholder to fill, a choice to make).
    Suggest,
}

impl Applicability {
    /// The lowercase word this is stored and printed as — the one spelling that crosses
    /// between a run, `--format json`, and the cached fix a later run reads back.
    pub fn as_str(self) -> &'static str {
        match self {
            Applicability::Safe => "safe",
            Applicability::Unsafe => "unsafe",
            Applicability::Suggest => "suggest",
        }
    }
}

/// One text replacement: `[start, end)` in 1-based line / byte-column coordinates;
/// an insertion has `end == start`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Edit {
    /// First line of the range to replace, counted from 1.
    pub line: usize,
    /// First byte-column, counted from 1. Bytes rather than characters, because that is
    /// what the checker reports and what an applier slices with.
    pub col: usize,
    /// Line the range ends on. Equal to [`line`](Self::line) for an edit within one line.
    pub end_line: usize,
    /// Byte-column the range ends at, exclusive — so the character at `end_col` survives.
    /// Equal to [`col`](Self::col) for an insertion, which replaces nothing.
    pub end_col: usize,
    /// What goes in the range's place. Empty deletes it.
    pub text: String,
}

/// A mechanical rewrite attached to a diagnostic (see [`fix`]).
///
/// Serializes as [`cache::FixJson`] does, since the two describe the same thing and the
/// store reads back what `--format json` prints.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Fix {
    /// Whether `htl fix` may apply this without being asked twice.
    pub applicability: Applicability,
    /// The rewrite, as one or more replacements. A fix is all of them or none: they are
    /// applied together, because a rewrite that lands half-way is worse than one that did
    /// not land.
    pub edits: Vec<Edit>,
}

/// One literal `require` call in a checked file.
#[derive(Debug, Clone)]
pub struct RequireSite {
    /// The name as the call spells it, before any separator or entry mapping.
    pub module: String,
    /// Resolved file, `None` when the checker could not find it.
    pub path: Option<PathBuf>,
    /// Line of the `require` call, counted from 1.
    pub line: usize,
    /// Byte-column of the call, counted from 1.
    pub col: usize,
}

/// A named function of a `.tl` file, for coverage (see [`Htl::coverage_spans`]).
///
/// The body is `line + 1 ..= last - 1`, strictly between the two: defining a function
/// runs both ends of it, so neither says whether the function was ever entered. A
/// never-called `function m.f()` spanning lines 12..15 comes back from the line hook
/// with 12 and 15 executed and 13, 14 not. Functions with nothing in between (one
/// line, or an empty body) have no such span and are not reported at all.
#[derive(Debug, Clone)]
pub struct FunctionSpan {
    /// As the source writes it: `f`, `M.f`, `M:f`.
    pub name: String,
    /// The line the function is declared on.
    pub line: usize,
    /// The line its `end` is on. Always at least `line + 2`.
    pub last: usize,
}

/// What one parse gives a coverage report: the statement ranges, and the functions
/// those ranges sit in. See [`Htl::coverage_spans`].
pub type CoverageSpans = (Vec<(usize, usize)>, Vec<FunctionSpan>);

/// What a file on the search path is, for [`Htl::module_candidates`]. The three the
/// searchers try, in the order they try them: a `.tl` source beats a `.d.tl` declaration
/// wherever the two sit, and a plain `.lua` is what is left when neither is reachable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ModuleKind {
    /// A `.tl` the checker compiles and the program runs — the only kind that is both.
    Source,
    /// A `.d.tl`: types with no implementation. Requiring one at run time gets an empty
    /// table, which is why a module that resolves to a declaration and nothing else
    /// type-checks and then fails.
    Declaration,
    /// A plain `.lua`, which the checker has nothing to say about. What is left when
    /// neither of the other two is reachable.
    Lua,
}

impl ModuleKind {
    fn of(s: &str) -> Self {
        match s {
            "source" => Self::Source,
            "declaration" => Self::Declaration,
            _ => Self::Lua,
        }
    }

    /// As a report says it.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Source => "source",
            Self::Declaration => "declaration",
            Self::Lua => "lua",
        }
    }
}

impl std::fmt::Display for ModuleKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One file `require(name)` could have resolved to. See [`Htl::module_candidates`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleCandidate {
    /// The file itself.
    pub path: PathBuf,
    /// Which of the three it is, which is what decides whether it wins over the ones
    /// found after it.
    pub kind: ModuleKind,
    /// The search-path directory it was found under.
    pub dir: PathBuf,
}

/// Result of a static contract check (see [`Htl::contract_check`]).
#[derive(Debug, Clone, Default)]
pub struct ContractResult {
    /// Type errors from `local m: <T> = require("<mod>")`.
    pub errors: Vec<String>,
    /// Declared fields absent from the module's returned table literal; `None` when the
    /// return value is not a literal (not decidable statically).
    pub missing: Option<Vec<String>>,
    /// Line and column of the returned table literal, for the report about
    /// [`missing`](Self::missing) to point at. `(1, 1)` when the checker gave no position,
    /// so a message always has somewhere to point rather than none.
    pub missing_at: (usize, usize),
    /// Names `require_fields` asked for that the contract type does not declare. The
    /// config is wrong about the type, which is a different finding from a module that
    /// fails the contract, and no module can fix it.
    pub bad_require_fields: Vec<String>,
}

impl Htl {
    /// Make an `htl.toml` project's dirs visible to the checker: `root`, `root/src` and
    /// `[check] paths`. `root` is the directory holding `htl.toml`.
    pub fn apply_config(&self, root: &Path, cfg: &config::HtlConfig) -> Result<()> {
        self.add_search_paths(&cfg.search_paths(root))
    }

    /// Put `dirs` on the search path so they are consulted **in the order given** — the
    /// order [`search_paths`](config::HtlConfig::search_paths) documents, and the one a
    /// reader assumes from a list. [`add_path`](Self::add_path) prepends, so adding the
    /// list front to back would leave its last entry first; this adds it back to front.
    ///
    /// It decides one thing: which of two declarations of the same module is read. A
    /// `.tl` source beats a `.d.tl` wherever the two sit, so until neither is a source
    /// the order is invisible.
    pub fn add_search_paths(&self, dirs: &[PathBuf]) -> Result<()> {
        for p in dirs.iter().rev() {
            self.add_path(p)?;
        }
        Ok(())
    }

    /// Static form of `TealResolver::expect_type` / `require_fields` for one module file:
    /// `modname` is what a `require` would say (its stem), `type_path` is `"defs.Mod"`.
    pub fn contract_check(
        &self,
        file: &Path,
        modname: &str,
        type_path: &str,
        require_fields: &config::RequireFields,
    ) -> Result<ContractResult> {
        let f: Function = self.h.get("contract_check")?;
        // `true` for "everything the type declares", the list itself when it names them.
        let wanted = match require_fields.named() {
            Some(names) => mlua::Value::Table(self.lua().create_sequence_from(names.to_vec())?),
            None => mlua::Value::Boolean(require_fields.is_on()),
        };
        let t: Table = f.call((path_str(file), modname, type_path, wanted))?;
        let errors: Table = t.get("errors")?;
        let errors = errors
            .sequence_values::<String>()
            .collect::<mlua::Result<_>>()?;
        let missing = match t.get::<Option<Table>>("missing")? {
            Some(m) => Some(
                m.sequence_values::<String>()
                    .collect::<mlua::Result<Vec<_>>>()?,
            ),
            None => None,
        };
        let missing_at = (
            t.get::<Option<usize>>("missing_y")?.unwrap_or(1),
            t.get::<Option<usize>>("missing_x")?.unwrap_or(1),
        );
        let bad_require_fields = match t.get::<Option<Table>>("bad_require_fields")? {
            Some(b) => b
                .sequence_values::<String>()
                .collect::<mlua::Result<Vec<_>>>()?,
            None => Vec::new(),
        };
        Ok(ContractResult {
            errors,
            missing,
            missing_at,
            bad_require_fields,
        })
    }
}

/// `contract` lint for one file: when `file` sits directly under the directory a
/// contract holds (relative to `root`, the directory holding `htl.toml`), check it
/// against that contract statically. Returns lint lines (empty when none applies).
///
/// `contracts` comes from [`contract::resolve`], which reads the `---@contract` markers;
/// resolving once per run rather than once per file is the caller's job.
pub fn contract_lints(
    h: &Htl,
    root: &Path,
    cfg: &config::HtlConfig,
    contracts: &[contract::Resolved],
    file: &Path,
) -> Result<Vec<String>> {
    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    let file_abs = canon(file);
    let mut out = Vec::new();
    if !is_tl_source(&file_abs) {
        return Ok(out);
    }
    let modname = file_abs
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_string();
    for c in contracts {
        let Some(dir) = c
            .dirs(root)
            .into_iter()
            .map(|d| canon(&d))
            .find(|d| file_abs.parent() == Some(d.as_path()))
        else {
            continue;
        };
        if !c.applies_to(&modname) {
            continue;
        }
        // Same visibility as `TealResolver::for_contract`: the contract dir, plus what
        // `HtlConfig::search_paths` gives (the project root, its `src/` and `types/`,
        // then `[check] paths`). Both sides go through that one function.
        h.add_path(&dir)?;
        h.apply_config(root, cfg)?;
        let r = h.contract_check(&file_abs, &modname, &c.type_path, &c.require_fields)?;
        if !r.bad_require_fields.is_empty() {
            // A `---@required` the checker cannot see as a field of the record: the
            // marker is on something else, and no module under the dir can satisfy it.
            out.push(format!(
                "{}:{}:1: ---@required on field(s) {} does not declare: {} [htl contract]",
                c.declared_in.display(),
                c.declared_at,
                c.type_path,
                r.bad_require_fields.join(", ")
            ));
            continue;
        }
        for e in &r.errors {
            // The stub's own "<contract ...>:L:C: " prefix says nothing useful; keep the
            // message. The same reading of a diagnostic's text every other caller makes.
            let msg = diagnostic::position(e)
                .map_or(e.as_str(), |(_, _, _, msg)| msg)
                .trim();
            out.push(format!(
                "{}:1:1: does not satisfy contract {} ({}): {msg} [htl contract]",
                file.display(),
                c.type_path,
                c.dir
            ));
        }
        if let Some(missing) = &r.missing
            && !missing.is_empty()
        {
            out.push(format!(
                "{}:{}:{}: returned table lacks declared field(s) of {}: {} [htl contract]",
                file.display(),
                r.missing_at.0,
                r.missing_at.1,
                c.type_path,
                missing.join(", ")
            ));
        }
    }
    Ok(out)
}

/// `duplicate-declaration` lint: a module `file` requires resolved to a `.d.tl` while
/// another `.d.tl` for the same module was reachable further along the search path. One
/// was read and the other was not, decided by position, and until now nothing said so —
/// the case this catches is a host publishing a declaration into a project that also
/// keeps a hand-written one for the same module.
///
/// Only declarations collide. A `.tl` source beats every `.d.tl` wherever the two sit
/// (`prelude.lua` searches sources across the whole path first), so a require that
/// landed on a source is not reported, and neither is a module declared once.
///
/// A require that landed on a source is where the other lint here lives.
/// `host-module-shadowed`: `host_modules` are the names the surrounding crate registers
/// in `package.preload` (from `#[host_module]`, scanned without a build), and Lua
/// consults preload before any path searcher. So when a require of one of those names
/// resolved to a file, the check read the file and the run will load the host: what was
/// checked is not what runs, and the program fails at the first call of anything the two
/// do not share. Both halves of that are already in hand at this point — the name the
/// host registers, and the path the checker read — which is why it is asked here.
///
/// A require of a host module name that landed on a `.d.tl` is not reported: a
/// declaration is how a host module is given types at all, and `htl dts` writes exactly
/// that file, so the two agree by construction.
///
/// Call it with the search path the file was checked under: the answer depends on it.
pub fn declaration_conflict_lints(
    h: &Htl,
    file: &Path,
    info: &CheckInfo,
    host_modules: &[String],
) -> Result<Vec<String>> {
    let f: Function = h.h.get("declaration_sites")?;
    let mut out = Vec::new();
    let mut seen: Vec<&str> = Vec::new();
    for site in &info.requires {
        let Some(read) = site.path.as_ref() else {
            continue;
        };
        // One report per module, not one per `require` of it.
        if seen.contains(&site.module.as_str()) {
            continue;
        }
        if !is_declaration(read) {
            if host_modules.contains(&site.module) {
                seen.push(&site.module);
                out.push(format!(
                    "{}:{}:{}: {} is a host module of this crate and also {}: the check \
                     reads the file, the run loads the host — package.preload is consulted \
                     before any path searcher, so what is checked here is not what runs \
                     [htl host-module-shadowed]",
                    file.display(),
                    site.line,
                    site.col,
                    site.module,
                    read.display(),
                ));
            }
            continue;
        }
        let sites: Vec<String> = f
            .call::<Table>(site.module.as_str())?
            .sequence_values::<String>()
            .collect::<mlua::Result<_>>()?;
        let shadowed: Vec<&str> = sites
            .iter()
            .map(|s| s.as_str())
            .filter(|s| !same_file(Path::new(s), read))
            .collect();
        if shadowed.is_empty() {
            continue;
        }
        seen.push(&site.module);
        out.push(format!(
            "{}:{}:{}: {} is declared more than once on the search path: {} is read, {} {} not [htl duplicate-declaration]",
            file.display(),
            site.line,
            site.col,
            site.module,
            read.display(),
            shadowed.join(" and "),
            if shadowed.len() == 1 { "is" } else { "are" },
        ));
    }
    Ok(out)
}

/// `contract-unenforced` lint: a contract only becomes a run-time guarantee when the
/// host builds its resolver from it. Scan the host crate's Rust sources (under
/// `cargo_root`) for `contract_resolvers(`. No host crate (`cargo_root` = None) means a
/// script-only project: nothing to enforce.
///
/// One call to look for, not four. `contract_resolvers(root, &config)` is what the README
/// documents and what keeps the host and `htl check` reading the same markers; a resolver
/// assembled by hand from `expect_type` / `require_fields` now has to restate what the
/// record already says, so recognising it would be recognising the drift this lint
/// exists to prevent. Enforcement the scan cannot see at all — a Lua-side validator, a
/// resolver in a sibling crate, generated code, or a resolver built by hand — is what
/// `[[contract]] enforced_by` is for: it names the file the enforcement lives in, and
/// that contract is then not held to the scan. The file has to exist, which is what
/// separates the key from a per-contract off switch, and a name that points at nothing is
/// reported under this same rule whether or not the call was found.
pub fn contract_enforcement_lints(
    cfg_path: &Path,
    contracts: &[contract::Resolved],
    cargo_root: Option<&Path>,
) -> Vec<String> {
    let mut out = Vec::new();
    if contracts.is_empty() {
        return out;
    }
    let Some(root) = cargo_root else { return out };
    let mut sources = String::new();
    for sub in ["src", "examples", "tests", "benches"] {
        let dir = root.join(sub);
        if !dir.is_dir() {
            continue;
        }
        for e in walkdir::WalkDir::new(&dir).into_iter().flatten() {
            let p = e.path();
            if p.is_file()
                && p.extension().and_then(|s| s.to_str()) == Some("rs")
                && let Ok(t) = std::fs::read_to_string(p)
            {
                sources.push_str(&t);
                sources.push('\n');
            }
        }
    }
    let by_config = sources.contains("contract_resolvers(");
    for c in contracts {
        // A contract with nothing under it is not enforced by anyone; the dir may be
        // populated later (glob dirs especially), so say nothing about the host.
        if c.dirs(root_of(cfg_path)).is_empty() {
            continue;
        }
        match &c.enforced_by {
            // The path is the whole of what makes `enforced_by` a claim rather than an
            // off switch, so it is checked whether or not the scan found the call: a name
            // that points at nothing is a broken statement either way.
            Some(p) => {
                let at = config::resolve_path(root_of(cfg_path), p);
                if !at.exists() {
                    out.push(format!(
                        "{}:1:1: contract {} -> {} says it is enforced by {:?}, and there \
                         is no such file: name where the enforcement lives, or drop the \
                         key and let the scan look for \
                         htl::pkg::contract_resolvers(root, &config) \
                         [htl contract-unenforced]",
                        cfg_path.display(),
                        c.dir,
                        c.type_path,
                        p,
                    ));
                }
            }
            None if !by_config => out.push(format!(
                "{}:{}:1: contract {} -> {} is declared but the host does not enforce it: \
                 build resolvers with htl::pkg::contract_resolvers(root, &config), or say \
                 where it is enforced with [[contract]] enforced_by \
                 [htl contract-unenforced]",
                c.declared_in.display(),
                c.declared_at,
                c.dir,
                c.type_path,
            )),
            None => {}
        }
    }
    out
}

fn root_of(cfg_path: &Path) -> &Path {
    cfg_path.parent().unwrap_or(Path::new("."))
}

/// Cycles in the require graph of a set of checked files, one message per cycle,
/// anchored at the first edge's call site. Teal types a circular require as an opaque
/// `circular_require`, so a cycle shows up elsewhere as "cannot index" errors; naming
/// the loop is the useful part. Files outside `infos` are treated as leaves.
pub fn require_cycles(infos: &[(PathBuf, CheckInfo)]) -> Vec<String> {
    use std::collections::{HashMap, HashSet};
    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    let mut edges: HashMap<PathBuf, Vec<(PathBuf, &RequireSite)>> = HashMap::new();
    let mut display: HashMap<PathBuf, PathBuf> = HashMap::new();
    for (file, ci) in infos {
        let from = canon(file);
        display.insert(from.clone(), file.clone());
        let list = edges.entry(from).or_default();
        for r in &ci.requires {
            if let Some(p) = &r.path {
                list.push((canon(p), r));
            }
        }
    }
    let nodes: Vec<PathBuf> = {
        let mut v: Vec<PathBuf> = edges.keys().cloned().collect();
        v.sort();
        v
    };
    let mut out = Vec::new();
    let mut reported: HashSet<Vec<PathBuf>> = HashSet::new();
    let mut state: HashMap<PathBuf, u8> = HashMap::new(); // 1 = on stack, 2 = done
    let mut stack: Vec<(PathBuf, Option<&RequireSite>)> = Vec::new();

    fn dfs<'a>(
        node: PathBuf,
        edges: &HashMap<PathBuf, Vec<(PathBuf, &'a RequireSite)>>,
        state: &mut HashMap<PathBuf, u8>,
        stack: &mut Vec<(PathBuf, Option<&'a RequireSite>)>,
        reported: &mut HashSet<Vec<PathBuf>>,
        display: &HashMap<PathBuf, PathBuf>,
        out: &mut Vec<String>,
    ) {
        state.insert(node.clone(), 1);
        if let Some(list) = edges.get(&node) {
            for (to, site) in list {
                match state.get(to).copied() {
                    Some(1) => {
                        // back edge: cycle = stack from `to` .. node, then back to `to`
                        let start = stack.iter().position(|(n, _)| n == to).unwrap_or(0);
                        let mut members: Vec<PathBuf> = stack[start..]
                            .iter()
                            .map(|(n, _)| n.clone())
                            .chain(std::iter::once(node.clone()))
                            .collect();
                        members.dedup();
                        let mut key = members.clone();
                        key.sort();
                        if reported.insert(key) {
                            let name = |p: &PathBuf| {
                                display
                                    .get(p)
                                    .unwrap_or(p)
                                    .file_name()
                                    .map(|s| s.to_string_lossy().into_owned())
                                    .unwrap_or_else(|| p.display().to_string())
                            };
                            let chain: Vec<String> = members
                                .iter()
                                .map(name)
                                .chain(std::iter::once(name(to)))
                                .collect();
                            let first_file = display
                                .get(&members[0])
                                .cloned()
                                .unwrap_or_else(|| members[0].clone());
                            // anchor: the edge leaving the cycle's first member
                            let anchor = stack.get(start + 1).and_then(|(_, s)| *s).unwrap_or(site);
                            out.push(format!(
                                "{}:{}:{}: require cycle: {} (Teal types the back edge as an opaque circular require; \
                                 break it by moving shared types into a module both sides require) [htl require-cycle]",
                                first_file.display(),
                                anchor.line,
                                anchor.col,
                                chain.join(" -> ")
                            ));
                        }
                    }
                    Some(2) => {}
                    _ => {
                        stack.push((to.clone(), Some(site)));
                        dfs(to.clone(), edges, state, stack, reported, display, out);
                        stack.pop();
                    }
                }
            }
        }
        state.insert(node, 2);
    }

    for n in nodes {
        if !state.contains_key(&n) {
            stack.push((n.clone(), None));
            dfs(
                n,
                &edges,
                &mut state,
                &mut stack,
                &mut reported,
                &display,
                &mut out,
            );
            stack.pop();
        }
    }
    out.sort();
    out
}

impl CheckInfo {
    /// `true` when nothing failed the check — errors only. Warnings and lints are the
    /// caller's to promote ([`clean`](Self::clean) is the stricter question), so this is
    /// what decides whether generated code may be run.
    pub fn ok(&self) -> bool {
        self.errors.is_empty()
    }

    /// `true` when there are no errors, warnings or lints.
    pub fn clean(&self) -> bool {
        self.errors.is_empty() && self.warnings.is_empty() && self.lints.is_empty()
    }

    /// Everything this check found about the file itself, structured, in the order the
    /// text output says it: warnings, then lints, then errors.
    ///
    /// Errors in what the file *required* are not here — they belong to the module they
    /// are in, and it is the reporting caller that decides how to say them
    /// ([`dependency_errors`](Self::dependency_errors)).
    pub fn diagnostics(&self) -> Vec<Diagnostic> {
        let mut out = self.warning_diagnostics();
        out.extend(self.lint_diagnostics());
        out.extend(self.error_diagnostics());
        out
    }

    /// [`errors`](Self::errors) with their positions and their fixes.
    pub fn error_diagnostics(&self) -> Vec<Diagnostic> {
        parsed(Severity::Error, &self.errors, &self.error_fixes)
    }

    /// [`warnings`](Self::warnings) with their positions. Warnings carry no fix.
    pub fn warning_diagnostics(&self) -> Vec<Diagnostic> {
        parsed(Severity::Warning, &self.warnings, &[])
    }

    /// [`lints`](Self::lints) with their positions, their rule names and their fixes.
    pub fn lint_diagnostics(&self) -> Vec<Diagnostic> {
        parsed(Severity::Lint, &self.lints, &self.lint_fixes)
    }
}

/// `texts[i]` parsed, with `fixes[i]` attached when there is one.
fn parsed(severity: Severity, texts: &[String], fixes: &[Option<Fix>]) -> Vec<Diagnostic> {
    texts
        .iter()
        .enumerate()
        .map(|(i, text)| {
            let mut d = Diagnostic::parse(severity, text);
            d.fix = fixes.get(i).and_then(|f| f.clone());
            d
        })
        .collect()
}

/// An mlua state with the Teal compiler loaded.
pub struct Htl {
    /// The program's state: `require`, preloads, `exec`, bundles.
    lua: Lua,
    /// The prelude table (checker API). Lives in `lua` unless this is a split state
    /// made by [`with_checker`](Self::with_checker), where it belongs to the checker.
    h: Table,
    /// `true` when the checker is another Lua state (`with_checker`).
    split: bool,
}

/// Checker prelude of another state, kept in a runtime state's app data so the
/// mlua-pkg resolvers find their checker (`Htl::with_checker`).
pub(crate) struct CheckerHandle(pub(crate) Table);

const RUNTIME_REGISTRY_KEY: &str = "htl.runtime";

/// Registry key under which a state remembers, per bundle entry, which `package.preload`
/// names that bundle wrote (`Htl::bundle_record`).
const BUNDLE_REGISTRY_KEY: &str = "htl.bundles";

/// What [`Htl::replace_bundle`] did, so a host can say it rather than guess.
///
/// Three lists because three things happen to a name, and a host that logs "reloaded" for
/// all of them is hiding the two that matter: a module that went away for good, and one
/// whose live value was deliberately spared.
///
/// A module both bundles carry appears in `dropped` *and* in `added` — which is what
/// happened to it: the old one was taken out of `package.loaded`, and the new one is what
/// the next `require` will evaluate. Nothing is in both `dropped` and `kept`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Replaced {
    /// Names the old bundle had installed that are now out of `package.preload` and
    /// `package.loaded`: the next `require` of one evaluates whatever answers it now, and
    /// for a name the new bundle does not carry there may be nothing left to answer.
    pub dropped: Vec<String>,
    /// Names from `keep` that the old bundle had actually installed, and whose evaluated
    /// value is still in `package.loaded`. Shorter than the `keep` that was asked for when
    /// a name in it was never this bundle's — the host's own module, or a typo — which is
    /// the only report of that.
    pub kept: Vec<String>,
    /// Names the new bundle wrote into `package.preload`. Not what it carries: a name the
    /// host had registered first is still the host's and is not here.
    pub added: Vec<String>,
}

/// The part of the prelude a runtime state needs when its checker lives elsewhere:
/// the strict searcher (asking the checker through `gen`), the declaration-only
/// module, and `package.path` bookkeeping.
const RUNTIME_PRELUDE: &str = r#"
local R = {}

function R.type_only_module(module_name, decl_path)
   return setmetatable({}, {
      __index = function(_, key)
         error(string.format(
            "module '%s' is declaration-only here (%s): '%s' has no implementation on this path. " ..
            "It must be provided by the host program (e.g. a Rust #[host_module] via cargo run) " ..
            "or by a .tl/.lua module with that name.",
            module_name, decl_path, tostring(key)), 2)
      end,
   })
end

-- gen(name) -> kind, a, b  (see resolve_for_require in the checker prelude)
function R.install_searcher(gen)
   table.insert(package.searchers, 2, function(module_name)
      local kind, a, b = gen(module_name)
      if kind == "code" then
         local chunk, lerr = load(a, "@" .. b, "t")
         if not chunk then
            error("htl: generated Lua failed to load: " .. tostring(lerr), 0)
         end
         return function(modname) return chunk(modname, b) end, b
      elseif kind == "type_only" then
         return function() return R.type_only_module(module_name, a) end, a
      end
      return a
   end)
end

-- Put already-generated Lua in front of the searcher for one module name.
--
-- `package.preload` is searcher position 1 and R.install_searcher puts htl's at 2, so a
-- preloaded module is never asked of the searcher — which is the point: asking would check
-- and generate it again. Loaded the same way the searcher would have loaded it, so the
-- module sees the same chunk name and the same arguments.
function R.preload_generated(module_name, code, filename)
   -- Never displace what is already there. The test library and anything a host preloads are
   -- put in package.preload by whoever owns them, and Lua generated from a `.tl` of the same
   -- name is not the same module: preloading over `htl.test` gives the file a stand-in whose
   -- `run()` reports nothing, and every test silently stops counting.
   if package.preload[module_name] ~= nil then return end
   local chunk, lerr = load(code, "@" .. filename, "t")
   if not chunk then
      error("htl: cached Lua failed to load: " .. tostring(lerr), 0)
   end
   package.preload[module_name] = function(modname) return chunk(modname, filename) end
end

function R.add_path(dir)
   local templates = dir .. "/?.lua;" .. dir .. "/?/init.lua;" .. dir .. "/?/?.lua"
   if package.path == nil or package.path == "" then
      package.path = templates
   else
      package.path = templates .. ";" .. package.path
   end
end

function R.reset_path()
   package.path = ""
end

-- Line coverage: which lines of which chunk ran. Lua's line hook is per thread, so
-- code that runs inside a coroutine the test creates is not seen.
local cov = nil
function R.coverage_start()
   cov = {}
   -- The line event is the hot path. One "S" lookup per function (cached by the
   -- function object) instead of per line; a call/return-event stack was measured
   -- slower on a call-heavy suite, since calls are almost as frequent as lines there.
   local srcs = setmetatable({}, { __mode = "k" })
   local getinfo = debug.getinfo
   debug.sethook(function(_, line)
      local fi = getinfo(2, "f")
      local func = fi and fi.func
      if func == nil then return end
      local t = srcs[func]
      if t == nil then
         local si = getinfo(2, "S")
         local src = si and si.source
         t = false
         if src then
            t = cov[src]
            if not t then
               t = {}
               cov[src] = t
            end
         end
         srcs[func] = t
      end
      if t then t[line] = true end
   end, "l")
end

function R.coverage_stop()
   debug.sethook()
   local out = {}
   for src, lines in pairs(cov or {}) do
      local list = {}
      for l in pairs(lines) do list[#list + 1] = l end
      table.sort(list)
      out[#out + 1] = { source = src, lines = list }
   end
   cov = nil
   return out
end

return R
"#;

impl Htl {
    /// New state. Uses `Lua::unsafe_new` so stripped bytecode bundles can be loaded.
    pub fn new() -> Result<Self> {
        // SAFETY: we accept binary chunks only from bundles we produced ourselves.
        let lua = unsafe { Lua::unsafe_new() };
        Self::from_lua(lua)
    }

    /// A fresh program state that borrows `checker`'s compiler instead of loading its
    /// own: modules `checker` has already type-checked and generated are served from
    /// its store, so a run of many programs (the test runner: one state per file)
    /// checks each module once. The program state itself is as isolated as
    /// [`new`](Self::new): nothing but the checker is shared. The checker starts a new
    /// program env for this state (module-name resolution is per program).
    pub fn with_checker(checker: &Htl) -> Result<Self> {
        // SAFETY: as in `new`.
        let lua = unsafe { Lua::unsafe_new() };
        Self::with_checker_lua(checker, lua)
    }

    /// [`with_checker`](Self::with_checker) with the program state supplied.
    ///
    /// This is the constructor for a host that decides what the program state is made of
    /// — which standard libraries it opens (`Lua::unsafe_new_with`), what its allocator
    /// is bounded to (`Lua::set_memory_limit`), what hook counts its instructions
    /// (`Lua::set_global_hook`) — while the checker keeps running on a state of its own,
    /// with whatever it needs. Every such limit is mlua's and is set on `lua` by the
    /// host; htl adds none of its own and puts nothing in the way of them.
    ///
    /// What htl itself needs from `lua`: `package` (the searcher and `preload`) and the
    /// base library's `load`; `debug`, only for [`coverage_start`](Self::coverage_start).
    /// A state that will load bundles has to come from `unsafe_new_with`: mlua's safe
    /// `new_with` refuses binary chunks, which is what a bundle is.
    pub fn with_checker_lua(checker: &Htl, lua: Lua) -> Result<Self> {
        let r: Table = lua
            .load(RUNTIME_PRELUDE)
            .set_name("=htl-runtime")
            .eval()
            .context("loading htl runtime prelude")?;
        lua.set_named_registry_value(RUNTIME_REGISTRY_KEY, r)?;
        lua.set_app_data(CheckerHandle(checker.h.clone()));
        let begin: Function = checker.h.get("begin_program")?;
        begin.call::<()>(())?;
        Ok(Self {
            lua,
            h: checker.h.clone(),
            split: true,
        })
    }

    fn runtime(&self) -> Result<Table> {
        Ok(self
            .lua
            .named_registry_value::<Table>(RUNTIME_REGISTRY_KEY)?)
    }

    /// Put Lua this checker generated for a `.tl` module in front of the searcher, in a
    /// program state.
    ///
    /// Distinct from [`preload`](Self::preload), which registers a source string as a module:
    /// this loads the way the searcher would have, so the module sees the same chunk name and
    /// the same arguments as if it had been generated during the run.
    ///
    /// Without it, a `require` in running code asks the searcher, which checks and generates
    /// the module then and there. With it, the module is already present. The two are the
    /// same thing only if `code` is what this checker would generate now — the caller's
    /// promise, and the reason anything serving this has to invalidate on the module's own
    /// content.
    pub fn preload_generated(&self, name: &str, code: &str, file: &Path) -> Result<()> {
        let f: Function = self.runtime()?.get("preload_generated")?;
        f.call::<()>((name, code, path_str(file)))?;
        Ok(())
    }

    /// Start recording which lines of which chunk run in the program state (a state
    /// made by [`with_checker`](Self::with_checker)). Lua's line hook is per thread:
    /// code inside coroutines the program creates is not seen.
    pub fn coverage_start(&self) -> Result<()> {
        let f: Function = self.runtime()?.get("coverage_start")?;
        f.call::<()>(())?;
        Ok(())
    }

    /// Stop recording; `(chunk source, sorted executed lines)` per chunk. Sources are as
    /// Lua names them: `@<path>` for files loaded by the searcher and the entry.
    pub fn coverage_stop(&self) -> Result<Vec<(String, Vec<usize>)>> {
        let f: Function = self.runtime()?.get("coverage_stop")?;
        let t: Table = f.call(())?;
        let mut out = Vec::new();
        for e in t.sequence_values::<Table>() {
            let e = e?;
            let source: String = e.get("source")?;
            let lines: Table = e.get("lines")?;
            out.push((
                source,
                lines
                    .sequence_values::<usize>()
                    .collect::<mlua::Result<_>>()?,
            ));
        }
        Ok(out)
    }

    /// Statements of a `.tl` file as `(first line, last line)` ranges: what a coverage
    /// report counts as executable. A statement counts as executed when any line of its
    /// range ran (Lua attributes a multi-line statement's instructions to several lines).
    pub fn executable_ranges(&self, file: &Path) -> Result<Vec<(usize, usize)>> {
        Ok(self.coverage_spans(file)?.0)
    }

    /// The statement ranges of [`executable_ranges`](Self::executable_ranges) and the
    /// file's named functions, from one parse: a coverage report wants both, and the
    /// second is what lets it say *which function* the missed statements belong to.
    pub fn coverage_spans(&self, file: &Path) -> Result<CoverageSpans> {
        let f: Function = self.h.get("executable_ranges")?;
        let (ranges, funcs): (Option<Table>, Option<Table>) = f.call(path_str(file))?;
        let Some(ranges) = ranges else {
            return Ok((Vec::new(), Vec::new()));
        };
        let mut out = Vec::new();
        for r in ranges.sequence_values::<Table>() {
            let r = r?;
            out.push((r.get::<usize>(1)?, r.get::<usize>(2)?));
        }
        let mut fns = Vec::new();
        if let Some(funcs) = funcs {
            for f in funcs.sequence_values::<Table>() {
                let f = f?;
                fns.push(FunctionSpan {
                    name: f.get("name")?,
                    line: f.get("y")?,
                    last: f.get("last")?,
                });
            }
        }
        Ok((out, fns))
    }

    /// The checker's `package.path` (what `require` inside `.tl` resolves through).
    pub fn search_path(&self) -> Result<String> {
        let f: Function = self.h.get("get_path")?;
        Ok(f.call(())?)
    }

    /// Restore a checker `package.path` taken with [`search_path`](Self::search_path).
    pub fn set_search_path(&self, path: &str) -> Result<()> {
        let f: Function = self.h.get("set_path")?;
        f.call::<()>(path)?;
        Ok(())
    }

    /// Attach the Teal compiler to an existing Lua state (the host's own `Lua`).
    pub fn from_lua(lua: Lua) -> Result<Self> {
        let tl_loader: Function = lua
            .load(TL_SRC)
            .set_name("=tl.lua")
            .into_function()
            .context("compiling vendored tl.lua")?;
        let lint_loader: Function = lua
            .load(LINT_SRC)
            .set_name("=htl-lint")
            .into_function()
            .context("compiling htl lint.lua")?;
        let package: Table = lua.globals().get("package")?;
        let preload: Table = package.get("preload")?;
        let fmt_loader: Function = lua
            .load(FMT_SRC)
            .set_name("=htl-fmt")
            .into_function()
            .context("compiling htl fmt.lua")?;
        preload.set("tl", tl_loader)?;
        preload.set("htl.lint", lint_loader)?;
        preload.set("htl.fmt", fmt_loader)?;
        let h: Table = lua
            .load(PRELUDE)
            .set_name("=htl-prelude")
            .eval()
            .context("loading htl prelude")?;
        lua.set_named_registry_value(PRELUDE_REGISTRY_KEY, h.clone())?;
        let this = Self {
            lua,
            h,
            split: false,
        };
        // The defaults come from the registry, and this is where a state gets them: the
        // Lua side holds no rule list of its own, so a state nobody configures would
        // otherwise run no lints at all.
        this.select_lints(&lint::Selection::default())?;
        Ok(this)
    }

    /// The Lua state this `Htl` runs programs in.
    ///
    /// Not always the one the checker is in: [`with_checker`](Self::with_checker) makes a
    /// fresh state for the program and leaves the prelude in the checker's. So a value
    /// built from this state must not be handed to a function that came from the other —
    /// that is `Lua instance passed Value created from a different main Lua state`.
    pub fn lua(&self) -> &Lua {
        &self.lua
    }

    /// Type-check one file.
    pub fn check(&self, file: &Path) -> Result<CheckInfo> {
        let f: Function = self.h.get("check")?;
        let t: Table = f.call(path_str(file))?;
        read_checkinfo(&t)
    }

    /// Check what is on disk right now, ignoring the store and not adding to it.
    ///
    /// [`check`](Self::check) serves a module the checker already knows from its store, and
    /// the underlying `tl.check_file` returns early when the environment has the file
    /// loaded. That is what makes checking a project fast, and it is wrong for a caller that
    /// has just written the file: the answer describes the version from before the write.
    /// `htl fix` writes and then measures, and was reverting correct fixes because of it.
    ///
    /// Nothing is stored either, because the caller may be about to put the file back —
    /// leaving the result behind would have the store describing a file that no longer says
    /// that.
    ///
    /// Slower than `check`: a cold environment re-checks the modules this file requires.
    ///
    /// The two options it differs from `check` by are set in the prelude rather than in a
    /// table built here, for the reason [`set_deps`](Self::set_deps) gives: `h` is not
    /// always in `self.lua`, and a table that crossed that line would raise.
    pub fn check_written(&self, file: &Path) -> Result<CheckInfo> {
        let f: Function = self.h.get("check_written")?;
        let t: Table = f.call(path_str(file))?;
        read_checkinfo(&t)
    }

    /// Type-check and generate Lua source. `None` code means errors (see `CheckInfo`).
    pub fn gen_lua(&self, file: &Path) -> Result<(Option<String>, CheckInfo)> {
        let f: Function = self.h.get("gen")?;
        let (code, t): (Option<String>, Table) = f.call(path_str(file))?;
        Ok((code, read_checkinfo(&t)?))
    }

    /// Configure lint rules: `"+no-any,-shadow-local"` on top of the defaults.
    ///
    /// The spec is resolved against [`lint::RULES`], so a name the project layer reports
    /// under is a name this takes; an unknown one is `unknown lint rule: <item>`.
    pub fn configure_lints(&self, spec: &str) -> Result<()> {
        self.select_lints(&lint::Selection::parse(spec)?)
    }

    /// Hand the checker a selection resolved elsewhere — what a caller that also has to
    /// ask about the project-layer rules has in hand ([`lint::Lints`]), so that the file
    /// rules and the project rules of one run come from one resolution of one spec.
    ///
    /// Two selections cross, one per producer on the Lua side: the rules `lint.lua`
    /// implements, which it runs from, and Teal's warning kinds, which the prelude filters
    /// the checker's warnings by as it collects them. Neither keeps defaults of its own.
    ///
    /// Each side crosses as the names that are on and the names that are off, and the
    /// table is built on the other side — for the reason [`set_deps`](Self::set_deps)
    /// gives, and it applies here the harder way: `h` is not always in `self.lua`
    /// ([`with_checker`](Self::with_checker) keeps the prelude in the checker's), and a
    /// table made here and passed there is `Lua instance passed Value created from a
    /// different main Lua state`. Both lists, not just the on ones, because absent and
    /// `false` are not the same answer to the prelude: a Teal warning kind is said unless
    /// its entry is exactly `false`.
    pub fn select_lints(&self, sel: &lint::Selection) -> Result<()> {
        let split = |side| {
            let (mut on, mut off) = (Vec::new(), Vec::new());
            for (name, is_on) in sel.of_side(side) {
                if is_on { &mut on } else { &mut off }.push(name.to_string());
            }
            (on, off)
        };
        let (lua_on, lua_off) = split(lint::Side::Lua);
        let (tl_on, tl_off) = split(lint::Side::Tl);
        let f: Function = self.h.get("set_lints")?;
        f.call::<()>((lua_on, lua_off, tl_on, tl_off))?;
        Ok(())
    }

    /// Tell the checker which dependencies the project installed, by name.
    ///
    /// Read by the rules that are about a library the project has rather than about its own
    /// code — `htlx-available`, which is silent in a project without htl-x — and by nothing
    /// else. Called by [`Htl::apply_project`](crate::pkg::Project) with what the lockfile
    /// linked; a state nobody calls it on has none, which is the answer a run outside a
    /// project should get.
    /// The names cross as a sequence and the set is built on the other side, rather than
    /// as a table built here. `h` is not always in `self.lua` — a split state
    /// ([`with_checker`](Self::with_checker)) keeps the prelude in the checker's — and a
    /// table made in one state and passed to a function in another is
    /// `Lua instance passed Value created from a different main Lua state`. A `Vec` is
    /// converted by the call itself, in the state the function belongs to.
    pub fn set_deps(&self, names: &[String]) -> Result<()> {
        let f: Function = self.h.get("set_deps")?;
        f.call::<()>(names.to_vec())?;
        Ok(())
    }

    /// Names of all lint rules (enabled or not), the project layer's among them.
    pub fn lint_rules(&self) -> Result<Vec<String>> {
        Ok(lint::rule_names().into_iter().map(str::to_string).collect())
    }

    /// The rules `lint.lua` implements, as it knows them. The registry is
    /// [`lint::RULES`]; this is the list to hold it to (`tests/lint_registry.rs`).
    pub fn lua_lint_rules(&self) -> Result<Vec<String>> {
        let f: Function = self.h.get("lint_rules")?;
        let t: Table = f.call(())?;
        Ok(t.sequence_values::<String>().collect::<mlua::Result<_>>()?)
    }

    /// Format a `.tl` file (whitespace-only formatter). Returns the formatted text.
    pub fn format_file(&self, file: &Path, indent: usize) -> Result<String> {
        let f: Function = self.h.get("format")?;
        let (out, err): (Option<String>, Option<String>) = f.call((path_str(file), indent))?;
        out.ok_or_else(|| anyhow!("{}", err.unwrap_or_else(|| "format failed".into())))
    }

    /// Drop Lua's default search path (cwd-relative `./?.lua` etc.) so only directories
    /// passed to [`add_path`](Self::add_path) are consulted by the checker and `require`.
    pub fn reset_search_path(&self) -> Result<()> {
        let f: Function = self.h.get("reset_path")?;
        f.call::<()>(())?;
        if self.split {
            let f: Function = self.runtime()?.get("reset_path")?;
            f.call::<()>(())?;
        }
        Ok(())
    }

    /// Search paths implied by where `file` sits in the scaffold layout, in the order
    /// they are consulted: its own directory first, and for a file under `tests/` then
    /// the project root and `<root>/src` (the test runner's rule, so `htl check tests`
    /// sees what `htl test` sees).
    pub fn add_layout_paths(&self, file: &Path) -> Result<()> {
        let dir = parent_dir(file);
        let mut dirs = vec![dir.clone()];
        if dir.file_name().is_some_and(|n| n == "tests")
            && let Some(root) = dir.parent()
        {
            dirs.push(root.to_path_buf());
            let src = root.join("src");
            if src.is_dir() {
                dirs.push(src);
            }
        }
        self.add_search_paths(&dirs)
    }

    /// Prepend `dir/?.tl;dir/?/init.tl` to `package.path` (Teal resolves requires through it).
    pub fn add_path(&self, dir: &Path) -> Result<()> {
        let f: Function = self.h.get("add_path")?;
        f.call::<()>(path_str(dir))?;
        if self.split {
            // The program state resolves plain `.lua` (and `.d.tl` siblings) itself.
            let f: Function = self.runtime()?.get("add_path")?;
            f.call::<()>(path_str(dir))?;
        }
        Ok(())
    }

    /// Install the strict `.tl` searcher: `require` of a `.tl` with type errors fails.
    pub fn install_searcher(&self) -> Result<()> {
        if self.split {
            // The searcher runs in the program state and asks the checker for code.
            //
            // Both states are in hand here and nothing crosses: `bridge` is built in
            // `self.lua` and handed to `runtime()`, which is a table out of `self.lua`'s
            // own registry. The checker's `gen_fn` is only ever *called* — its arguments
            // and results are Rust values on the way through, which is what a value has to
            // be to pass between two states.
            let gen_fn: Function = self.h.get("gen_for_require")?;
            let bridge = self.lua.create_function(move |_, name: String| {
                let (kind, a, b): (String, Option<String>, Option<String>) = gen_fn.call(name)?;
                Ok((kind, a, b))
            })?;
            let f: Function = self.runtime()?.get("install_searcher")?;
            f.call::<()>(bridge)?;
            return Ok(());
        }
        let f: Function = self.h.get("install_searcher")?;
        f.call::<()>(())?;
        Ok(())
    }

    /// Register generated Lua source under a module name (`package.preload`).
    ///
    /// The chunk is named after the `.tl` a `require` of this name would have found —
    /// `foo.bar` becomes `@foo/bar.tl` — because that name is what a run-time failure
    /// shows, and a reader who has only the output needs something to open. Use
    /// [`Htl::preload_at`] when the source sits somewhere else (`@scripts/util.tl`), or
    /// when there is no file at all and a bare label is the honest answer (`=htl.test`).
    pub fn preload(&self, name: &str, lua_src: &str) -> Result<()> {
        self.preload_at(name, &module_chunk_name(name), lua_src)
    }

    /// [`Htl::preload`] with the chunk name spelled out, the way [`Htl::exec`] takes one.
    /// `@<path>` is a source location and is what a host with a file should pass;
    /// `=<label>` is a literal label, for a module no file backs.
    pub fn preload_at(&self, name: &str, chunk_name: &str, lua_src: &str) -> Result<()> {
        let loader = self
            .lua
            .load(lua_src)
            .set_name(chunk_name)
            .into_function()
            .with_context(|| format!("compiling preloaded module {name}"))?;
        self.preload_table()?.set(name, loader)?;
        Ok(())
    }

    /// Register stripped bytecode (e.g. from `include_tl_bytes!`) under a module name.
    ///
    /// A chunk name is worth less here than it is to [`Htl::preload`], and the reason is
    /// worth knowing before reading a failure from an embedded module: a compiled chunk
    /// carries its own name, given when it was compiled, and `lua_load`'s name is used
    /// only for the messages loading itself produces. Stripping drops the carried name
    /// along with the line numbers, so every frame from a stripped payload reads `?` —
    /// `?: in function 'sample.greet'`. Running the `.tl` under `htl run` or `htl test`
    /// is where those frames are; a bundle keeps them with `htl build --debug`.
    pub fn preload_bytes(&self, name: &str, bytecode: &[u8]) -> Result<()> {
        let loader = self
            .lua
            .load(bytecode)
            .set_name(module_chunk_name(name))
            .set_mode(ChunkMode::Binary)
            .into_function()
            .with_context(|| format!("loading bytecode for module {name}"))?;
        self.preload_table()?.set(name, loader)?;
        Ok(())
    }

    /// Execute stripped bytecode with `...` = args.
    pub fn exec_bytes(&self, bytecode: &[u8], chunk_name: &str, args: &[String]) -> Result<()> {
        let f = self
            .lua
            .load(bytecode)
            .set_name(chunk_name)
            .set_mode(ChunkMode::Binary)
            .into_function()?;
        let va: Variadic<String> = args.iter().cloned().collect();
        f.call::<()>(va)?;
        Ok(())
    }

    /// Register a ready-made value (typically a Rust-built table) as a module.
    pub fn preload_value(&self, name: &str, value: impl mlua::IntoLua) -> Result<()> {
        let value = value.into_lua(&self.lua)?;
        let loader = self.lua.create_function(move |_, ()| Ok(value.clone()))?;
        self.preload_table()?.set(name, loader)?;
        Ok(())
    }

    fn preload_table(&self) -> Result<Table> {
        let package: Table = self.lua.globals().get("package")?;
        Ok(package.get("preload")?)
    }

    /// Set the global `arg` table like the `lua` CLI does.
    pub fn set_arg(&self, script: &str, args: &[String]) -> Result<()> {
        let t = self.lua.create_table()?;
        t.set(0, script)?;
        for (i, a) in args.iter().enumerate() {
            t.set(i + 1, a.as_str())?;
        }
        self.lua.globals().set("arg", t)?;
        Ok(())
    }

    /// Make arithmetic on a string a run-time error instead of a conversion.
    ///
    /// Lua 5.4 reads `"10" + 1` as `11`: the string library's metatable carries `__add`
    /// and the other seven arithmetic metamethods, and each one converts its string
    /// operands and retries. Checked Teal never gets there: the checker refuses the
    /// expression on a `string`, and on an `any` too. It happens in what the checker did
    /// not see — the far side of a cast (`(v as integer) + 1` where `v` came from
    /// `std.json.decode` or `arg` as `"10"`), a function `load` built from a string, Lua
    /// source a host handed to [`exec`](Self::exec) — and there the conversion is
    /// silent. This removes the eight from the string metatable of the program state, so
    /// the same expression fails as `attempt to perform arithmetic on a string value`,
    /// naming the operand.
    ///
    /// What it does not cover, because Lua does those elsewhere: `10 .. ""` (number to
    /// string under concatenation is in the VM, behind Lua's `LUA_NOCVTN2S` build flag,
    /// which is the vendored Lua's to set); `"10" < "9"` (a string comparison, true, and
    /// not a conversion); and `tonumber` / `math.tointeger`, which convert because they
    /// were asked to. `__index` stays, so `s:upper()` and every other string method are
    /// untouched.
    ///
    /// Opt-in, for a host's `preload` beside `install_std`; the CLI does not turn it on,
    /// since `htl run` and `htl test` run Teal the checker has passed. Calling it twice is
    /// the same as once. In a state that also holds the checker (the default; see
    /// [`with_checker`](Self::with_checker) for the split) the checker runs under it too,
    /// which it can: nothing in `tl` adds a string to a number.
    pub fn strict_strings(&self) -> Result<()> {
        self.lua
            .load(
                r#"
local mt = getmetatable("")
for _, k in ipairs { "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__unm", "__idiv" } do
   mt[k] = nil
end
"#,
            )
            .set_name("=strict_strings")
            .exec()
            .context("removing arithmetic metamethods from the string metatable")?;
        Ok(())
    }

    /// Execute Lua source with `...` = args.
    pub fn exec(&self, lua_src: &str, chunk_name: &str, args: &[String]) -> Result<()> {
        let f = self
            .lua
            .load(lua_src)
            .set_name(chunk_name)
            .into_function()?;
        let va: Variadic<String> = args.iter().cloned().collect();
        f.call::<()>(va)?;
        Ok(())
    }

    /// Check + gen + run a `.tl` script. If the check fails the script is not run and the
    /// returned `CheckInfo` carries the errors. Runtime errors come back as `Err`.
    pub fn run_file(&self, file: &Path, args: &[String]) -> Result<CheckInfo> {
        self.add_path(&parent_dir(file))?;
        self.install_searcher()?;
        self.set_arg(&file.to_string_lossy(), args)?;
        let (code, ci) = self.gen_lua(file)?;
        let Some(code) = code else { return Ok(ci) };
        self.exec(&code, &format!("@{}", file.display()), args)?;
        Ok(ci)
    }

    /// Compile Lua source to stripped bytecode (Lua 5.4 format of this build).
    pub fn compile(&self, name: &str, lua_src: &str) -> Result<Vec<u8>> {
        self.compile_with(name, lua_src, true)
    }

    /// Compile to bytecode; `strip` drops debug info (line numbers, local and upvalue
    /// names, and the chunk name: tracebacks then show the name given at load).
    pub fn compile_with(&self, name: &str, lua_src: &str, strip: bool) -> Result<Vec<u8>> {
        let f = self
            .lua
            .load(lua_src)
            .set_name(format!("={name}"))
            .into_function()
            .with_context(|| format!("compiling generated Lua for {name}"))?;
        Ok(f.dump(strip))
    }

    /// The Lua bytecode header this state produces (signature, version, format,
    /// `LUAC_DATA`, sizes of Instruction / Integer / Number, endianness probes): what
    /// another state must match to load this state's bytecode. Lua's own version byte
    /// is the same for every 5.4.x, so bundles carry this instead.
    pub fn fingerprint(&self) -> Result<Vec<u8>> {
        let bc = self.compile_with("fp", "return 0", true)?;
        // 4 signature + 1 version + 1 format + 6 LUAC_DATA + 3 sizes + 8 LUAC_INT + 8 LUAC_NUM
        Ok(bc.iter().take(31).copied().collect())
    }

    /// Literal `require`s of a plain Lua source, resolved through the checker's path.
    pub fn lua_requires(&self, src: &str, file: &Path) -> Result<Vec<RequireSite>> {
        let f: Function = self.h.get("lua_requires")?;
        let t: Table = f.call((src, path_str(file)))?;
        read_requires(&t)
    }

    /// Where `require(name)` resolves for the checker (`.tl`, `.d.tl` or `.lua`), and
    /// where a plain `.lua` implementation sits on the path (a `.d.tl` may only be
    /// typing it). Either may be `None`.
    pub fn resolve_module(&self, name: &str) -> Result<(Option<PathBuf>, Option<PathBuf>)> {
        let f: Function = self.h.get("resolve_module")?;
        let (found, lua): (Option<String>, Option<String>) = f.call(name)?;
        Ok((found.map(PathBuf::from), lua.map(PathBuf::from)))
    }

    /// Every file on the search path that could answer `require(name)`, in the order the
    /// searchers consult them — so the first is the one [`resolve_module`](Self::resolve_module)
    /// answers with, and the rest are what it hides.
    ///
    /// The same walk `declaration_sites` does for the `duplicate-declaration` lint, over
    /// all three kinds rather than declarations alone: a searcher answers with the first
    /// hit and says nothing about the others, and which of two files is read is decided by
    /// a position nobody wrote down. [`contract::resolve`] is what turns this into a report.
    pub fn module_candidates(&self, name: &str) -> Result<Vec<ModuleCandidate>> {
        let f: Function = self.h.get("module_candidates")?;
        let t: Table = f.call(name)?;
        let mut out = Vec::new();
        for c in t.sequence_values::<Table>() {
            let c = c?;
            out.push(ModuleCandidate {
                path: PathBuf::from(c.get::<String>("path")?),
                kind: ModuleKind::of(&c.get::<String>("kind")?),
                dir: PathBuf::from(c.get::<String>("dir")?),
            });
        }
        Ok(out)
    }

    /// The directories the search path consults, in order. One entry per directory,
    /// however many `package.path` templates it contributes.
    pub fn search_path_dirs(&self) -> Result<Vec<PathBuf>> {
        let f: Function = self.h.get("search_dirs")?;
        let t: Table = f.call(())?;
        Ok(t.sequence_values::<String>()
            .collect::<mlua::Result<Vec<_>>>()?
            .into_iter()
            .map(PathBuf::from)
            .collect())
    }

    /// The names each bundle wrote into `package.preload`, keyed by the bundle's entry.
    ///
    /// In the registry rather than in the `Htl`: it is a fact about the Lua state, and a
    /// `&Htl` is shared, so a `RefCell` here would be a second place to keep the same
    /// thing in step with. What it is for is [`replace_bundle`](Self::replace_bundle) — a
    /// bundle can take back the names it installed only if something remembers which
    /// those were, and which belonged to the host all along.
    fn bundle_record(&self) -> Result<Table> {
        if let Value::Table(t) = self
            .lua
            .named_registry_value::<Value>(BUNDLE_REGISTRY_KEY)?
        {
            return Ok(t);
        }
        let t = self.lua.create_table()?;
        self.lua
            .set_named_registry_value(BUNDLE_REGISTRY_KEY, t.clone())?;
        Ok(t)
    }

    /// The two questions asked before a bundle touches the state, so that a caller that
    /// is about to disturb what is already there can ask them first
    /// ([`replace_bundle`](Self::replace_bundle) drops modules, and a refusal after that
    /// would leave the host with neither the old ones nor the new).
    ///
    /// Both are reads. Running it twice — once by the caller, once by
    /// [`install_bundle`](Self::install_bundle), which stays correct on its own — costs a
    /// chunk dump and two table lookups and answers the same either way: the names it
    /// checks for are the host's, and a replace never removes one of those.
    fn check_installable(&self, b: &bundle::Bundle) -> Result<()> {
        // Bytecode from a Lua that disagrees with ours would fail with "bad binary
        // format" somewhere inside the first require; say what differs instead.
        // The header cannot tell one 5.4.x from another, so the htl versions go in the
        // message too: they are the only record of which Lua produced each side.
        if b.modules.iter().any(|m| m.kind == bundle::Kind::Bytecode) && !b.fingerprint.is_empty() {
            let mine = self.fingerprint()?;
            if mine != b.fingerprint {
                let built_by = if b.htl_version.is_empty() {
                    "an htl that did not record its version".to_string()
                } else {
                    format!("htl {}", b.htl_version)
                };
                bail!(
                    "bundle bytecode was compiled for {} by {built_by}, but this host runs {} on htl {}; \
                     rebuild the bundle here, or build it with --source",
                    bundle::describe_fingerprint(&b.fingerprint),
                    bundle::describe_fingerprint(&mine),
                    env!("CARGO_PKG_VERSION")
                );
            }
        }
        // Host-provided modules must already be registered, or the program's first
        // require of them fails with a message that points at the wrong place.
        let package: Table = self.lua.globals().get("package")?;
        let preload: Table = package.get("preload")?;
        let loaded: Table = package.get("loaded")?;
        let missing: Vec<&String> = b
            .host_modules
            .iter()
            .filter(|n| {
                matches!(preload.get::<Value>(n.as_str()), Ok(Value::Nil))
                    && matches!(loaded.get::<Value>(n.as_str()), Ok(Value::Nil))
            })
            .collect();
        if !missing.is_empty() {
            bail!(
                "bundle expects host-provided module(s) {} (declared only by a .d.tl or [build] host at link \
                 time): register them with preload / preload_value / htl_preload before running",
                missing
                    .iter()
                    .map(|m| format!("'{m}'"))
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        Ok(())
    }

    /// Install a searcher serving modules from a bundle.
    ///
    /// Idempotent, and deliberately so: a second call installs nothing, because every
    /// name is taken by the first. Putting a *newer* bundle into a state that is already
    /// running is [`replace_bundle`](Self::replace_bundle).
    pub fn install_bundle(&self, b: &bundle::Bundle) -> Result<()> {
        self.check_installable(b)?;
        let package: Table = self.lua.globals().get("package")?;
        let preload: Table = package.get("preload")?;
        // Bundled modules become `package.preload` entries: the same place a host puts
        // its own modules, so everything that already defers to preload (a `.d.tl`
        // stepping aside for the implementation, mlua-pkg resolvers ahead of Lua's
        // searchers) sees them without knowing about bundles. A name the host preloaded
        // first is left alone: the host wins. Loaders get (modname, ":preload:") as
        // Lua's preload searcher passes them.
        let mut written: Vec<String> = Vec::new();
        for m in &b.modules {
            if !matches!(preload.get::<Value>(m.name.as_str())?, Value::Nil) {
                continue;
            }
            let payload = m.payload.clone();
            let kind = m.kind;
            let name = m.name.clone();
            let loader =
                self.lua
                    .create_function(move |lua, (modname, origin): (String, Value)| {
                        let chunk = lua.load(payload.as_slice()).set_name(format!("={name}"));
                        let f = match kind {
                            bundle::Kind::Bytecode => {
                                chunk.set_mode(ChunkMode::Binary).into_function()?
                            }
                            bundle::Kind::Source => {
                                chunk.set_mode(ChunkMode::Text).into_function()?
                            }
                        };
                        f.call::<Value>((modname, origin))
                    })?;
            preload.set(m.name.as_str(), loader)?;
            written.push(m.name.clone());
        }
        // Only what this call wrote, and added to whatever the entry already had: a name
        // skipped above was the host's and is not this bundle's to take back, and a
        // second install of the same bundle writes nothing and must not erase the record
        // the first one made.
        let record = self.bundle_record()?;
        let names: Table = match record.get::<Value>(b.entry.as_str())? {
            Value::Table(t) => t,
            _ => {
                let t = self.lua.create_table()?;
                record.set(b.entry.as_str(), t.clone())?;
                t
            }
        };
        let already: Vec<String> = names
            .sequence_values::<String>()
            .collect::<mlua::Result<Vec<_>>>()?;
        for name in written {
            if !already.contains(&name) {
                names.push(name)?;
            }
        }
        Ok(())
    }

    /// Put a newer bundle into a state that is already running: the modules the bundle
    /// recorded under the same entry go, `keep`'s loaded values stay, and the host's are
    /// untouched.
    ///
    /// Nothing is evaluated here. A dropped name is gone from `package.preload` and
    /// `package.loaded`, so the next `require` of it runs the new module; a name in
    /// `keep` keeps the value it already evaluated to, which is how a `world` or a `save`
    /// module carries state across the swap. The entry is not re-run either — what to do
    /// with it is the host's, and a frame loop holding a table asks for the entry again
    /// and swaps what it holds.
    ///
    /// A reference already taken is not reached by any of this. `local m = require
    /// "rules"` captured by a closure that is still running keeps the old table until that
    /// closure is gone. That is Lua, and no amount of bookkeeping here changes it.
    ///
    /// The bundle is checked before anything is dropped, so a refusal — a fingerprint
    /// that disagrees, a host module that was never registered — leaves the state as it
    /// was rather than holding neither bundle.
    pub fn replace_bundle(&self, b: &bundle::Bundle, keep: &[&str]) -> Result<Replaced> {
        self.check_installable(b)?;
        let package: Table = self.lua.globals().get("package")?;
        let preload: Table = package.get("preload")?;
        let loaded: Table = package.get("loaded")?;
        let record = self.bundle_record()?;
        let previous: Vec<String> = match record.get::<Value>(b.entry.as_str())? {
            Value::Table(t) => t
                .sequence_values::<String>()
                .collect::<mlua::Result<Vec<_>>>()?,
            _ => Vec::new(),
        };
        let (mut dropped, mut kept) = (Vec::new(), Vec::new());
        for name in &previous {
            // The preload entry goes either way: it is the old bundle's loader, and the
            // new bundle's belongs there. A kept name never reaches it — `package.loaded`
            // answers first — but if anything ever clears that, the next require should
            // find the module this state actually holds.
            preload.set(name.as_str(), Value::Nil)?;
            if keep.contains(&name.as_str()) {
                kept.push(name.clone());
            } else {
                loaded.set(name.as_str(), Value::Nil)?;
                dropped.push(name.clone());
            }
        }
        // Cleared, not merged into: a module the old bundle had and the new one does not
        // is gone, and a record that still named it would offer it to the next replace.
        record.set(b.entry.as_str(), Value::Nil)?;
        self.install_bundle(b)?;
        let added: Vec<String> = match record.get::<Value>(b.entry.as_str())? {
            Value::Table(t) => t
                .sequence_values::<String>()
                .collect::<mlua::Result<Vec<_>>>()?,
            _ => Vec::new(),
        };
        Ok(Replaced {
            dropped,
            kept,
            added,
        })
    }

    /// Install the bundle and run its entry module with `...` = args.
    pub fn run_bundle(&self, b: &bundle::Bundle, args: &[String]) -> Result<()> {
        let entry = b
            .module(&b.entry)
            .cloned()
            .ok_or_else(|| anyhow!("entry module '{}' not in bundle", b.entry))?;
        self.install_bundle(b)?;
        self.set_arg(&b.entry, args)?;
        let chunk = self
            .lua
            .load(entry.payload.as_slice())
            .set_name(format!("={}", b.entry));
        let main: Function = match entry.kind {
            bundle::Kind::Bytecode => chunk.set_mode(ChunkMode::Binary).into_function()?,
            bundle::Kind::Source => chunk.set_mode(ChunkMode::Text).into_function()?,
        };
        let va: Variadic<String> = args.iter().cloned().collect();
        main.call::<()>(va)?;
        Ok(())
    }
}

fn path_str(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

/// The chunk name for a module registered without one: the `.tl` `require` would have
/// looked for, as a `@` source location. `htl.test` becomes `@htl/test.tl`, which is why
/// the test library asks for `=htl.test` instead — it ships inside the binary.
fn module_chunk_name(name: &str) -> String {
    format!("@{}.tl", name.replace('.', "/"))
}

/// A message for the people an embedding host serves: the innermost cause without Lua's
/// `stack traceback:` block. A host function's `Err(e)` surfaces as `e`'s own text; a Lua
/// `error("msg")` surfaces as `file:line: msg`.
///
/// ```text
/// sgen: content/no-date.md: front matter: 'date' is required
/// ```
/// instead of that line followed by `stack traceback: [C]: in method 'pages' ...`.
///
/// This is the answer for a program whose users did not write the Teal and cannot act on
/// its frames — a static site generator telling an author which file is missing a date.
/// It is not the answer for whoever is developing the program: see
/// [`developer_message`], which is what `htl run` and `htl test` print.
pub fn user_message(err: &anyhow::Error) -> String {
    if let Some(e) = err.downcast_ref::<mlua::Error>() {
        return user_message_lua(e);
    }
    strip_traceback(&format!("{err:#}"))
}

/// [`user_message`] for an error already held as mlua's own type, which is how a caller
/// that catches `mlua::Result` (the C ABI in `ffi`, say) has it.
pub fn user_message_lua(e: &mlua::Error) -> String {
    match e {
        mlua::Error::CallbackError { cause, .. } => user_message_lua(cause),
        mlua::Error::ExternalError(ext) => ext.to_string(),
        mlua::Error::WithContext { cause, .. } => user_message_lua(cause),
        other => strip_traceback(&other.to_string()),
    }
}

/// A message for whoever is developing the program: [`user_message`]'s innermost cause,
/// followed by Lua's `stack traceback:` block when the error carries one.
///
/// ```text
/// depth.tl:8: attempt to index a nil value (local 'c')
/// stack traceback:
///     depth.tl:8: in function 'depth.field'
///     depth.tl:12: in function 'depth.describe'
///     boom.tl:3: in main chunk
/// ```
///
/// The innermost line says a value was nil; the frames say which caller passed it, and
/// they name Teal files and Teal lines because a generated chunk is loaded under its
/// source's own name. This is what `htl run` and `htl test` print. The frames are absent
/// only where the debug information is: stripped bytecode, which is what a bundle without
/// `--debug` and `include_tl_bytes!` both hold.
pub fn developer_message(err: &anyhow::Error) -> String {
    let head = user_message(err);
    let full = match err.downcast_ref::<mlua::Error>() {
        Some(e) => e.to_string(),
        None => format!("{err:#}"),
    };
    match traceback_block(&full) {
        Some(tb) => format!("{head}\n{tb}"),
        None => head,
    }
}

/// The `stack traceback:` block of an error text, trimmed, without the newline before it.
fn traceback_block(text: &str) -> Option<&str> {
    let at = text.find("\nstack traceback:")?;
    Some(text[at + 1..].trim_end())
}

/// Remove a trailing Lua `stack traceback:` section from an error text.
pub fn strip_traceback(text: &str) -> String {
    let cut = text.find("\nstack traceback:").unwrap_or(text.len());
    text[..cut].trim_end().to_string()
}

/// Write `text` to `path` only if the content differs. Returns `true` when written.
/// Used by the derive macros to emit `.d.tl` files without churning cargo's fingerprints.
pub fn write_if_changed(path: &Path, text: &str) -> std::io::Result<bool> {
    if let Ok(cur) = std::fs::read_to_string(path)
        && cur == text
    {
        return Ok(false);
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::write(path, text)?;
    Ok(true)
}

/// Everything the libraries inside the binary write under [`lib_dir`]: the path each file
/// takes below that directory, and its source, sorted so that the order the parts are
/// collected in is not part of the answer.
///
/// The feature branch is here rather than in either library because this is the union, and
/// the union is what the directory is named after. Each library owns the half it writes
/// ([`testing::declarations`], [`batteries::declarations`]) and writes exactly that half,
/// so the name and the contents cannot drift apart.
fn bundled_declarations() -> Vec<(String, String)> {
    let mut out = testing::declarations();
    #[cfg(feature = "std")]
    out.extend(batteries::declarations());
    out.sort();
    out
}

/// A directory name for a set of declarations: the first sixteen hex characters of a
/// blake3 over every path and source in it.
///
/// Sixteen because this is read by a person — in `htl resolve`'s searched-order line, in a
/// listing of the temp directory — and sixty-four bits is already far past what telling a
/// handful of builds on one machine apart asks for. Each part is length-prefixed so that
/// two different lists cannot hash alike by running together: `("ab", "c")` and
/// `("a", "bc")` are different keys.
fn declarations_key(decls: &[(String, String)]) -> String {
    let mut h = blake3::Hasher::new();
    for (path, source) in decls {
        for part in [path.as_str(), source.as_str()] {
            h.update(&(part.len() as u64).to_le_bytes());
            h.update(part.as_bytes());
        }
    }
    h.finalize().to_hex()[..16].to_string()
}

/// Where the libraries that ship inside the binary put their `.d.tl` so the checker can see
/// them: `<tmp>/htl-lib-<version>-<key>/`, with `htl/test.d.tl` and, under the `std`
/// feature, `std/*.d.tl` below it. The files are written on demand by the library that owns
/// them, only when their content changes.
///
/// The key is a hash over what this build would write, and not the version,
/// because the version does not tell two builds apart. `CARGO_PKG_VERSION` is the same on
/// the release and on every build from `main` after it, and those differ by exactly what
/// lands here: a binary with `std` writes `std/*.d.tl` that a binary without it cannot
/// preload, and one that found them on its search path type-checked a project against
/// modules it then failed to load (#220). Keyed by content, the two have different
/// directories and neither can see the other's; two builds that would write the same files
/// still share one, which is the case worth sharing.
///
/// The version stays in the name because that is what a person reading the path uses.
pub fn lib_dir() -> PathBuf {
    static DIR: OnceLock<PathBuf> = OnceLock::new();
    DIR.get_or_init(|| {
        let key = declarations_key(&bundled_declarations());
        std::env::temp_dir().join(format!("htl-lib-{}-{key}", env!("CARGO_PKG_VERSION")))
    })
    .clone()
}

/// Parent directory of a file, `.` when the path has none.
pub fn parent_dir(file: &Path) -> PathBuf {
    let dir = file.parent().unwrap_or(Path::new("."));
    if dir.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        dir.to_path_buf()
    }
}

fn read_checkinfo(t: &Table) -> Result<CheckInfo> {
    let seq = |key: &str| -> Result<Vec<String>> {
        let inner: Table = t.get(key)?;
        Ok(inner
            .sequence_values::<String>()
            .collect::<mlua::Result<_>>()?)
    };
    let requires = match t.get::<Table>("requires") {
        Ok(list) => read_requires(&list)?,
        Err(_) => Vec::new(),
    };
    let errors = seq("errors")?;
    let lints = seq("lints")?;
    let error_fixes = read_fixes(t, "error_fixes", errors.len())?;
    let lint_fixes = read_fixes(t, "lint_fixes", lints.len())?;
    let dependency_errors = match t.get::<Table>("dependency_errors") {
        Ok(list) => read_dependency_errors(&list)?,
        Err(_) => Vec::new(),
    };
    Ok(CheckInfo {
        errors,
        warnings: seq("warnings")?,
        deps: seq("deps")?.into_iter().map(PathBuf::from).collect(),
        lints,
        requires,
        error_fixes,
        lint_fixes,
        dependency_errors,
    })
}

fn read_dependency_errors(list: &Table) -> Result<Vec<DependencyError>> {
    let mut out = Vec::new();
    for e in list.sequence_values::<Table>() {
        let e = e?;
        out.push(DependencyError {
            file: PathBuf::from(e.get::<String>("file")?),
            required_by: PathBuf::from(e.get::<String>("required_by")?),
            text: e.get::<String>("text")?,
        });
    }
    Ok(out)
}

/// `fixes[i]` is a fix table or `false`; missing entries are `None`.
fn read_fixes(t: &Table, key: &str, len: usize) -> Result<Vec<Option<Fix>>> {
    let mut out = vec![None; len];
    let Ok(list) = t.get::<Table>(key) else {
        return Ok(out);
    };
    for (i, slot) in out.iter_mut().enumerate() {
        let v: Value = list.get(i + 1)?;
        if let Value::Table(f) = v {
            let applicability = match f.get::<Option<String>>("applicability")?.as_deref() {
                Some("unsafe") => Applicability::Unsafe,
                Some("suggest") => Applicability::Suggest,
                _ => Applicability::Safe,
            };
            let mut edits = Vec::new();
            if let Ok(es) = f.get::<Table>("edits") {
                for e in es.sequence_values::<Table>() {
                    let e = e?;
                    edits.push(Edit {
                        line: e.get("line")?,
                        col: e.get("col")?,
                        end_line: e.get("end_line")?,
                        end_col: e.get("end_col")?,
                        text: e.get::<Option<String>>("text")?.unwrap_or_default(),
                    });
                }
            }
            *slot = Some(Fix {
                applicability,
                edits,
            });
        }
    }
    Ok(out)
}

fn read_requires(list: &Table) -> Result<Vec<RequireSite>> {
    let mut requires = Vec::new();
    for r in list.sequence_values::<Table>() {
        let r = r?;
        requires.push(RequireSite {
            module: r.get::<String>("name")?,
            path: r.get::<Option<String>>("path")?.map(PathBuf::from),
            line: r.get::<Option<usize>>("y")?.unwrap_or(0),
            col: r.get::<Option<usize>>("x")?.unwrap_or(0),
        });
    }
    Ok(requires)
}

/// `true` for `foo.tl` but not `foo.d.tl`.
pub fn is_tl_source(p: &Path) -> bool {
    let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
    p.is_file() && name.ends_with(".tl") && !name.ends_with(".d.tl")
}

/// The note `htl dts` writes beside the declarations it materialises from a dependency
/// crate, in `types/<crate>/`. The module that writes it is `dep_dts`, which the `dts`
/// feature compiles.
pub const DEP_TYPES_NOTE: &str = ".htl-dts";

/// The immediate subdirectories of `types/` holding declarations materialised from a
/// dependency, in name order.
///
/// They go on the search path in their own right, so that a declaration keeps the module
/// name it was written under whatever the crate shipping it is called: `htl-mq`'s
/// `mq.d.tl` is `require("mq")`, not `require("htl-mq.mq")`. A directory a person laid out
/// under `types/` carries no note and goes on meaning what it has always meant — the path
/// below `types/` is the module name, as `socket/http.d.tl` is `require("socket.http")`.
pub fn materialised_types_dirs(types: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(types) else {
        return Vec::new();
    };
    let mut out: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| p.is_dir() && p.join(DEP_TYPES_NOTE).is_file())
        .collect();
    out.sort();
    out
}

/// `true` for `foo.d.tl`: a declaration, with the implementation somewhere else.
pub fn is_declaration(p: &Path) -> bool {
    p.file_name()
        .and_then(|s| s.to_str())
        .is_some_and(|n| n.ends_with(".d.tl"))
}

/// Directories never descended into when collecting sources under a root: build output,
/// installed packages, VCS and tool state. A root passed explicitly is always walked.
pub const SKIP_DIRS: &[&str] = &["target", "node_modules", ".mlua-pkgs", ".git"];

/// `true` for a directory entry that source collection should not enter: a name in
/// [`SKIP_DIRS`], any dot-directory, or one of `extra` — named by path rather than by
/// name, for what the caller knows and a name cannot say.
pub fn is_skipped_dir(path: &Path, extra: &[PathBuf]) -> bool {
    if !path.is_dir() {
        return false;
    }
    let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
    if SKIP_DIRS.contains(&name) || (name.starts_with('.') && name.len() > 1) {
        return true;
    }
    extra.iter().any(|e| same_file(path, e))
}

/// The two paths name the same thing on disk, `..` and symlinks resolved. Falls back to
/// comparing them as written when either cannot be canonicalised (it does not exist).
pub(crate) fn same_file(a: &Path, b: &Path) -> bool {
    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
        (Ok(x), Ok(y)) => x == y,
        _ => a == b,
    }
}

/// Extra directories to skip below `root`, when `root` is inside an `mlua-pkg.toml`
/// project: where it installed its deps, and each copy a `target_dir` dep put in the tree.
///
/// Both hold a dependency's own sources and tests rather than the project's. The copies
/// need saying because they are *in* the repo and committed — nothing about the path tells
/// one apart from the project's own code beside it, and only the manifest knows. `mlua-pkg
/// install` rewrites them every time it runs, so checking one reports someone else's
/// errors, formatting it writes a diff against upstream that the next install undoes, and
/// running its tests runs a dependency's suite. Go settled the same question the same way:
/// `./...` has excluded `vendor/` since 1.9.
///
/// A `patch_dir` dep is the other case and is not here: the project owns that copy, so
/// whether to walk it depends on what the walk is for ([`patched_dirs`]).
#[cfg(feature = "pkg")]
pub fn project_skip_dirs(root: &Path) -> Vec<PathBuf> {
    match pkg::Project::find(root) {
        Some(p) => {
            let mut out = vec![p.pkgs_dir];
            out.extend(p.vendored_copies);
            out
        }
        None => Vec::new(),
    }
}

#[cfg(not(feature = "pkg"))]
pub fn project_skip_dirs(_root: &Path) -> Vec<PathBuf> {
    Vec::new()
}

/// The `patch_dir` deps below `root`: a dependency's source taken into the tree, which the
/// project edits and commits (`htl pkg patch`).
///
/// Not in [`project_skip_dirs`], because whether to walk one depends on what the walk is
/// for. Its errors are the project's to fix, so `htl check` reports them; but the change
/// it holds is a diff against the revision it was taken from, so `htl fmt` would bury that
/// change under a reformatting of every file, and its `*_test.tl` are the dependency's
/// suite rather than the project's. Those two skip it, and pass this to
/// [`collect_tl_skipping`] / [`testing::discover_tests_skipping`] to say so.
#[cfg(feature = "pkg")]
pub fn patched_dirs(root: &Path) -> Vec<PathBuf> {
    match pkg::Project::find(root) {
        Some(p) => p.patch_dirs(),
        None => Vec::new(),
    }
}

#[cfg(not(feature = "pkg"))]
pub fn patched_dirs(_root: &Path) -> Vec<PathBuf> {
    Vec::new()
}

/// The directories a `require` in the project at `root` resolves its deps from: the
/// search directory of each `patch_dir` copy, the entry links under `.htl/modules`, and
/// the parents of `target_dir` copies — what [`Htl::apply_project`] puts on the path, in
/// the same order, listed whether or not they exist yet, for the cache's probes
/// ([`cache::search_dirs`]).
///
/// One list, read by the two that must agree. A patched dependency is the project's own
/// code and a person edits it there, so an entry replayed from the store while the copy
/// has moved on would be the wrong answer to a question the user just changed: the probe
/// over its entry directory is what catches a module appearing in or leaving the copy, as
/// the hash of a file the entry recorded catches a line changing inside one.
#[cfg(feature = "pkg")]
pub fn dependency_dirs(root: &Path) -> Vec<PathBuf> {
    match pkg::Project::find(root) {
        Some(p) => {
            let mut out = p.patch_search_dirs();
            out.push(p.entries);
            out.extend(p.target_dirs);
            out
        }
        None => Vec::new(),
    }
}

#[cfg(not(feature = "pkg"))]
pub fn dependency_dirs(_root: &Path) -> Vec<PathBuf> {
    Vec::new()
}

/// Collect `.tl` sources from files and directories (sorted, recursive). Directories in
/// [`SKIP_DIRS`], dot-directories and the project's package dir are not entered unless
/// given as a root themselves.
pub fn collect_tl(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
    collect_tl_skipping(paths, &[])
}

/// [`collect_tl`], not entering `skip` either — directories named by path rather than by
/// name, for what the caller knows and a name cannot say ([`patched_dirs`]).
pub fn collect_tl_skipping(paths: &[PathBuf], skip: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    for p in paths {
        if p.is_dir() {
            let mut extra = project_skip_dirs(p);
            extra.extend(skip.iter().cloned());
            let root = p.clone();
            let walker = walkdir::WalkDir::new(p)
                .sort_by_file_name()
                .into_iter()
                .filter_entry(move |e| e.path() == root || !is_skipped_dir(e.path(), &extra));
            for e in walker {
                let e = e?;
                if is_tl_source(e.path()) {
                    out.push(e.path().to_path_buf());
                }
            }
        } else if p.is_file() {
            out.push(p.clone());
        } else {
            bail!("no such file or directory: {}", p.display());
        }
    }
    Ok(out)
}

/// `root/foo/bar.tl` -> `foo.bar`, `root/foo/init.tl` -> `foo`.
pub fn module_name(root: &Path, file: &Path) -> Result<String> {
    let rel = file.strip_prefix(root)?.with_extension("");
    let mut parts: Vec<String> = rel
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .collect();
    if parts.last().map(|s| s == "init").unwrap_or(false) {
        parts.pop();
    }
    if parts.is_empty() {
        bail!("cannot derive module name for {}", file.display());
    }
    Ok(parts.join("."))
}

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

    fn decl(path: &str, source: &str) -> (String, String) {
        (path.to_string(), source.to_string())
    }

    /// The reason the key exists: a build carrying one declaration more than another — a
    /// feature set, a newer mlua-batteries — lands somewhere else, so neither finds the
    /// other's files on its search path.
    #[test]
    fn a_different_set_of_declarations_is_a_different_key() {
        let base = vec![decl("htl/test.d.tl", "local record t end\nreturn t\n")];
        let mut more = base.clone();
        more.push(decl(
            "std/json.d.tl",
            "local record json end\nreturn json\n",
        ));
        assert_ne!(declarations_key(&base), declarations_key(&more));

        // And a set of the same size whose content moved.
        let mut edited = base.clone();
        edited[0].1.push('\n');
        assert_ne!(declarations_key(&base), declarations_key(&edited));
    }

    /// And the same set is the same key, so a build uses the directory it used last time
    /// and the files it wrote there are still its own.
    #[test]
    fn the_same_set_is_the_same_key() {
        let decls = vec![
            decl("htl/test.d.tl", "local record t end\nreturn t\n"),
            decl("std/json.d.tl", "local record json end\nreturn json\n"),
        ];
        assert_eq!(declarations_key(&decls), declarations_key(&decls.clone()));
    }

    /// Length-prefixed: moving a character from a path into the source after it is a
    /// different set of files and reads as one.
    #[test]
    fn the_parts_cannot_run_together() {
        assert_ne!(
            declarations_key(&[decl("ab", "c")]),
            declarations_key(&[decl("a", "bc")])
        );
    }

    /// The list is what this build writes: `htl.test`'s declaration whatever the features,
    /// and `std`'s exactly when the feature that installs them is on.
    #[test]
    fn the_list_holds_what_this_build_writes() {
        let decls = bundled_declarations();
        assert!(decls.iter().any(|(p, _)| p == "htl/test.d.tl"), "{decls:?}");
        assert_eq!(
            decls.iter().any(|(p, _)| p.starts_with("std/")),
            cfg!(feature = "std")
        );
    }

    /// What the directory name is made of, and that asking twice gives one answer — the
    /// key is computed once and the path is a constant for the life of the process.
    #[test]
    fn the_directory_carries_the_version_and_the_key() {
        let dir = lib_dir();
        let name = dir.file_name().unwrap().to_string_lossy().into_owned();
        let prefix = format!("htl-lib-{}-", env!("CARGO_PKG_VERSION"));
        assert!(name.starts_with(&prefix), "{name}");
        assert_eq!(
            name[prefix.len()..],
            declarations_key(&bundled_declarations())
        );
        assert_eq!(dir, lib_dir());
    }
}