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

module Test.Unit.Source (unitTests) where

import Base
import Checking.Foundation qualified as Foundation
import Checking.Identity qualified as Identity
import Checking.Semantic qualified as Semantic
import Felix.Cache.Codec qualified as Cache
import Felix.Module qualified as Module
import Felix.Parse qualified as Parse
import Felix.Parsed.Identity qualified as ParsedIdentity
import Felix.Parsed.Payload qualified as Parsed
import Felix.Prelude qualified as Prelude
import Felix.Source
import Felix.Source.Content qualified as Content
import Felix.Source.Graph
import Felix.Store qualified as Store
import Report.Location
    ( FileId(..)
    , FileIdAllocator(..)
    , Location(..)
    , LocationRegistrationError(..)
    , allocateFileId
    , locColumn
    , locFile
    , locFileId
    , locLine
    , lookupFileIdentityPath
    )
import Syntax.Abstract qualified as Raw
import Syntax.Adapt qualified as Adapt
import Syntax.Interface qualified as Interface
import Syntax.Token (runLexer)

import Control.Exception (bracket, evaluate)
import Data.ByteString qualified as ByteString
import Data.IORef
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Text qualified as Text
import Data.Word (Word8, Word16)
import Database.SQLite.Simple qualified as SQLite
import System.Directory qualified as Directory
import System.FilePath.Posix qualified as Posix
import System.Posix.Files qualified as PosixFiles
import Test.Tasty
import Test.Tasty.HUnit


unitTests :: TestTree
unitTests = testGroup "Source resolution"
    [ testCase "validates mount-root-relative POSIX paths" validatesRelativePaths
    , testCase "rejects duplicate source mount ids" rejectsDuplicateMountIds
    , testCase "rejects duplicate canonical mount roots" rejectsDuplicateMountRoots
    , testCase "permits missing and rejects non-directory mounts"
        validatesMountRootTypes
    , testCase "rejects relative exact roots" rejectsRelativeExactRoots
    , testCase "retains exact root spelling as diagnostic trivia" retainsRootSpelling
    , testCase "searched and exact roots share canonical identity" rootFormsShareIdentity
    , testCase "attributes nested sources to the most specific mount" attributesNestedSources
    , testCase "configured order selects searched candidates" candidateOrderSelectsWinner
    , testCase "rejects a higher-priority special source"
        rejectsHigherPrioritySpecialSource
    , testCase "rejects exact roots outside configured mounts" rejectsOutsideExactRoot
    , testCase "loads source text as strict UTF-8" loadsStrictUtf8
    , testCase "reports malformed UTF-8 sequence starts"
        reportsInvalidUtf8Offsets
    , testCase "reserves the all-ones file identifier"
        preservesReservedFileId
    , testCase "builds an imported-before-importer source graph" buildsSourceGraph
    , testCase "rejects the packaged prelude as ordinary source"
        rejectsPackagedPreludeAsOrdinarySource
    , testCase "orders sibling imports by textual occurrence"
        ordersSiblingImports
    , testCase "orders shared dependencies before their importers"
        ordersSharedDependencies
    , testCase "retains repeated import-edge occurrences" retainsRepeatedImports
    , testCase "deduplicates canonical source nodes" deduplicatesCanonicalNodes
    , testCase "reports missing imports at their source location" reportsMissingImports
    , testCase "rejects unsafe imports at their source location" rejectsUnsafeImports
    , testCase "reports the located import cycle chain" reportsImportCycles
    , testCase "rejects malformed imported source before discovery" rejectsMalformedImportedSource
    , testCase "builds empty modules through the ordinary pipeline"
        buildsEmptyModules
    , testCase "identifies owner-independent parsed modules"
        identifiesOwnerIndependentParsedModules
    , testCase "keys effective direct syntax inputs"
        keysEffectiveDirectSyntaxInputs
    , testCase "reuses exact parsed syntax on a warm pass"
        reusesExactParsedSyntax
    , testCase "invalidates exact parsed inputs transitively"
        invalidatesExactParsedInputs
    , testCase "rebinds relocated parsed artifacts"
        rebindsRelocatedParsedArtifacts
    , testCase "rejects a corrupted cached declaration anchor"
        rejectsCorruptedCachedDeclarationAnchor
    , testCase "parses source-local blocks in graph order" parsesSourceGraph
    , testCase "does not leak syntax between sibling imports"
        rejectsSiblingSyntaxLeakage
    , testCase "parses source fixity levels and grouping"
        parsesSourceFixities
    , testCase "parses cdot and symdiff fixities"
        parsesLibraryFixities
    , testCase "validates source pragma associations"
        validatesSourcePragmaAssociations
    , testCase "rejects fixed-base category mismatches"
        rejectsFixedBaseCategoryMismatch
    , testCase "retains multi-item syntax occurrence order"
        retainsMultiItemSyntaxOccurrences
    , testCase "propagates and coalesces imported syntax"
        propagatesImportedSyntax
    , testCase "rejects unequal imported syntax"
        rejectsUnequalImportedSyntax
    , testCase "qualifies same-display cross-mount collisions"
        distinguishesPhysicalSourceLocations
    , testCase "retains each workspace location display path"
        retainsWorkspaceLocationDisplayPath
    , testCase "reports imported scanner errors before importer tokenizer errors"
        reportsImportedScannerErrorFirst
    , testCase "returns malformed lexical declarations as typed errors"
        reportsMalformedLexicalDeclaration
    , testCase "validates inductive function patterns during scanning"
        rejectsMalformedInductivePattern
    , testCase "scans and parses adjective signatures"
        acceptsAdjectiveSignature
    , testCase "rejects malformed math-led signature heads"
        rejectsMalformedSignatureHead
    , testCase "locates conflicting declarations within one environment"
        reportsSameSourceLexiconCollision
    , testCase "accepts the first source declaration of a built-in pattern"
        acceptsBuiltinSourceDeclaration
    , testCase "keeps the built-in marker for a prefix predicate declaration"
        acceptsBuiltinPrefixPredicateDeclaration
    , testCase "does not rescan repeated canonical imports"
        avoidsAliasImportLexiconCollision
    , testCase "parses loaded sources without rereading files" parsesWithoutRereading
    , testCase "returns source-local failures after prior chunk callbacks"
        returnsSourceParseFailures
    ]

validatesRelativePaths :: Assertion
validatesRelativePaths = do
    assertRight (safeRelativePath "theory/set.tex")
    assertRight (safeRelativePath "theory\\set.tex")
    assertLeft EmptyRelativePath (safeRelativePath "")
    assertLeft AbsoluteRelativePath (safeRelativePath "/theory.tex")
    assertLeft CurrentDirectoryComponent (safeRelativePath "./theory.tex")
    assertLeft ParentDirectoryComponent (safeRelativePath "a/../theory.tex")
    assertLeft EmptyPathComponent (safeRelativePath "a//theory.tex")
    assertLeft EmptyPathComponent (safeRelativePath "a/")
    assertLeft NullPathCharacter (safeRelativePath "a\0b")

rejectsDuplicateMountIds :: Assertion
rejectsDuplicateMountIds =
    withTemporaryDirectory "felix-source-duplicate-id" \temp -> do
        result <- prepareSourceMounts
            [ (sourceMountId "same", temp Posix.</> "one")
            , (sourceMountId "same", temp Posix.</> "two")
            ]
        assertEqual
            "duplicate id"
            (Left (DuplicateSourceMountId (sourceMountId "same")))
            result

rejectsDuplicateMountRoots :: Assertion
rejectsDuplicateMountRoots =
    withTemporaryDirectory "felix-source-duplicate-root" \temp -> do
        result <- prepareSourceMounts
            [ (sourceMountId "one", temp)
            , (sourceMountId "two", temp Posix.</> ".")
            ]
        canonical <- Directory.canonicalizePath temp
        case result of
            Left (DuplicateCanonicalMountRoot root firstId secondId) -> do
                assertEqual "canonical root" canonical (canonicalPathFilePath root)
                assertEqual "first mount id" (sourceMountId "one") firstId
                assertEqual "second mount id" (sourceMountId "two") secondId
            Left err ->
                assertFailure ("expected DuplicateCanonicalMountRoot, got " <> show err)
            Right mounts ->
                assertFailure ("expected duplicate-root rejection, got " <> show mounts)

validatesMountRootTypes :: Assertion
validatesMountRootTypes =
    withTemporaryDirectory "felix-source-mount-type" \temp -> do
        let ident = sourceMountId "project"
            missing = temp Posix.</> "missing"
            regularFile = temp Posix.</> "file"
        assertRight =<< prepareSourceMounts [(ident, missing)]

        writeFile regularFile ""
        result <- prepareSourceMounts [(ident, regularFile)]
        case result of
            Left SourceMountNotDirectory{} ->
                pure ()
            Left err ->
                assertFailure
                    ("expected SourceMountNotDirectory, got " <> show err)
            Right mounts ->
                assertFailure
                    ("expected non-directory rejection, got " <> show mounts)

rejectsRelativeExactRoots :: Assertion
rejectsRelativeExactRoots =
    assertEqual
        "relative exact roots are rejected"
        (Left (ExistingRootNotAbsolute "entry.tex"))
        =<< existingRoot "entry.tex"

retainsRootSpelling :: Assertion
retainsRootSpelling =
    withTemporaryDirectory "felix-source-root-spelling" \temp -> do
        let source = temp Posix.</> "entry.tex"
            alias = temp Posix.</> "entry-alias.tex"
        writeFile source ""
        Directory.createFileLink source alias
        direct <- expectRight =<< existingRoot source
        throughAlias <- expectRight =<< existingRoot alias
        assertEqual "canonical request identity" direct throughAlias
        assertEqual "diagnostic spelling" alias
            (rootRequestSpelling throughAlias)

rootFormsShareIdentity :: Assertion
rootFormsShareIdentity =
    withTemporaryDirectory "felix-source-root-identity" \temp -> do
        let source = temp Posix.</> "entry.tex"
        writeFile source "source"
        mounts <- oneMount "project" temp
        searched <- expectRight (searchedRoot "entry.tex")
        exact <- expectRight =<< existingRoot source
        searchedLoaded <- expectRight =<< resolveAndLoadRoot mounts searched
        exactLoaded <- expectRight =<< resolveAndLoadRoot mounts exact
        assertEqual "loaded source" searchedLoaded exactLoaded
        assertEqual "source mount"
            (resolvedSourceMount (loadedSource searchedLoaded))
            (resolvedSourceMount (loadedSource exactLoaded))
        assertEqual "mount-relative source path"
            (resolvedSourceRelativePath (loadedSource searchedLoaded))
            (resolvedSourceRelativePath (loadedSource exactLoaded))

rejectsPackagedPreludeAsOrdinarySource :: Assertion
rejectsPackagedPreludeAsOrdinarySource = do
    packaged <- expectRight =<< Prelude.loadReservedPreludeSourceInput
    canonical <- expectJust "packaged canonical path"
        (Prelude.reservedPreludeSourceCanonicalPath packaged)
    let path = canonicalPathFilePath canonical
    mounts <- oneMount "packaged" (Posix.takeDirectory path)
    request <- expectRight (searchedRoot (Posix.takeFileName path))
    let validate = Prelude.rejectOrdinaryPreludeSourceGraph packaged
        syntaxInputs = const []
    Parse.parseSourceWorkspaceMeasuredWithSyntaxInputsAndGraphValidation
        mounts request syntaxInputs validate >>= \case
            Left
                (Parse.SourceWorkspaceError
                    (PackagedPreludeSelectedAsOrdinarySource source)) ->
                        assertEqual "authority-free rejected path"
                            canonical
                            (resolvedSourceCanonicalPath source)
            other ->
                assertFailure
                    ("unexpected authority-free result: " <> show other)

    withTemporaryDirectory "felix-reserved-parse-store" \temp -> do
        foundation <- expectRight Foundation.checkedFoundation
        store <- openTestStore
            (temp Posix.</> "store.sqlite")
            (Identity.theoryId foundation)
        Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputsAndGraphValidation
            store mounts request syntaxInputs validate >>= \case
                Left
                    (Parse.ParseExecutionWorkspaceError
                        (Parse.SourceWorkspaceError
                            (PackagedPreludeSelectedAsOrdinarySource source))) ->
                                assertEqual "typed rejected path"
                                    canonical
                                    (resolvedSourceCanonicalPath source)
                other ->
                    assertFailure
                        ("unexpected typed result: " <> show other)
        Store.closeStore store

attributesNestedSources :: Assertion
attributesNestedSources =
    withTemporaryDirectory "felix-source-nested-mount" \temp -> do
        let nested = temp Posix.</> "library"
            source = nested Posix.</> "entry.tex"
        Directory.createDirectory nested
        writeFile source "source"
        exact <- expectRight =<< existingRoot source
        outerFirst <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "project", temp)
            , (sourceMountId "library", nested)
            ]
        innerFirst <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "library", nested)
            , (sourceMountId "project", temp)
            ]
        searched <- expectRight (searchedRoot "library/entry.tex")
        outerFirstSource <- loadedSource <$> (expectRight =<< resolveAndLoadRoot outerFirst exact)
        innerFirstSource <- loadedSource <$> (expectRight =<< resolveAndLoadRoot innerFirst exact)
        searchedSource <- loadedSource <$> (expectRight =<< resolveAndLoadRoot outerFirst searched)
        assertEqual "order-independent attribution" outerFirstSource innerFirstSource
        assertEqual "root-form-independent attribution" outerFirstSource searchedSource
        assertEqual "most specific mount" (sourceMountId "library") (resolvedSourceMount outerFirstSource)
        assertEqual "mount-relative identity" "entry.tex"
            (safeRelativePathFilePath (resolvedSourceRelativePath outerFirstSource))

candidateOrderSelectsWinner :: Assertion
candidateOrderSelectsWinner =
    withTemporaryDirectory "felix-source-precedence" \temp -> do
        let firstRoot = temp Posix.</> "first"
            secondRoot = temp Posix.</> "second"
            firstSource = firstRoot Posix.</> "entry.tex"
            secondSource = secondRoot Posix.</> "entry.tex"
        Directory.createDirectory firstRoot
        Directory.createDirectory secondRoot
        writeFile firstSource "first"
        writeFile secondSource "second"
        request <- expectRight (searchedRoot "entry.tex")
        firstMounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "first", firstRoot)
            , (sourceMountId "second", secondRoot)
            ]
        secondMounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "second", secondRoot)
            , (sourceMountId "first", firstRoot)
            ]
        firstWinner <- expectRight =<< resolveAndLoadRoot firstMounts request
        secondWinner <- expectRight =<< resolveAndLoadRoot secondMounts request
        assertEqual "first configured source" "first" (loadedText firstWinner)
        assertEqual "reversed configured source" "second" (loadedText secondWinner)

rejectsHigherPrioritySpecialSource :: Assertion
rejectsHigherPrioritySpecialSource =
    withTemporaryDirectory "felix-source-special-precedence" \temp -> do
        let higherRoot = temp Posix.</> "higher"
            lowerRoot = temp Posix.</> "lower"
            higherSource = higherRoot Posix.</> "entry.tex"
            lowerSource = lowerRoot Posix.</> "entry.tex"
        Directory.createDirectory higherRoot
        Directory.createDirectory lowerRoot
        PosixFiles.createNamedPipe higherSource PosixFiles.ownerModes
        writeFile lowerSource "ordinary source"
        mounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "higher", higherRoot)
            , (sourceMountId "lower", lowerRoot)
            ]
        request <- expectRight (searchedRoot "entry.tex")
        result <- resolveRoot mounts request
        case result of
            Left
                (SelectedSourceNotRegular
                    (SearchedRootLookup relative)
                    selectedPath
                    canonical) -> do
                        assertEqual "searched path"
                            "entry.tex"
                            (safeRelativePathFilePath relative)
                        assertEqual "selected higher candidate"
                            higherSource
                            selectedPath
                        canonicalHigher <-
                            Directory.canonicalizePath higherSource
                        assertEqual "selected canonical target"
                            canonicalHigher
                            (canonicalPathFilePath canonical)
            Left err ->
                assertFailure
                    ("expected SelectedSourceNotRegular, got " <> show err)
            Right source ->
                assertFailure
                    ("expected special-source rejection, got " <> show source)

rejectsOutsideExactRoot :: Assertion
rejectsOutsideExactRoot =
    withTemporaryDirectory "felix-source-outside-root" \temp -> do
        let mountRoot = temp Posix.</> "mount"
            outsideRoot = temp Posix.</> "outside"
            source = outsideRoot Posix.</> "entry.tex"
        Directory.createDirectory mountRoot
        Directory.createDirectory outsideRoot
        writeFile source "source"
        mounts <- oneMount "project" mountRoot
        exact <- expectRight =<< existingRoot source
        result <- resolveAndLoadRoot mounts exact
        case result of
            Left (RootOutsideConfiguredMount spelling _canonical) ->
                assertEqual "exact-root diagnostic spelling" source spelling
            Left err ->
                assertFailure ("expected RootOutsideConfiguredMount, got " <> show err)
            Right loaded ->
                assertFailure ("expected outside-root rejection, got " <> show loaded)

loadsStrictUtf8 :: Assertion
loadsStrictUtf8 =
    withTemporaryDirectory "felix-source-utf8" \temp -> do
        let source = temp Posix.</> "unicode.tex"
            bytes =
                ByteString.pack
                    [ 0xCE, 0xB1, 0x20, 0xE2
                    , 0x88, 0x88, 0x20, 0x41
                    ]
        ByteString.writeFile source bytes
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "unicode.tex")
        loaded <- expectRight =<< resolveAndLoadRoot mounts request
        assertEqual "exact bytes" bytes (loadedBytes loaded)
        assertEqual "decoded text" ("α ∈ A" :: Text) (loadedText loaded)
        assertEqual
            "byte count"
            (fromIntegral (ByteString.length bytes))
            (loadedByteCount loaded)
        let identifier =
                Content.sourceContentId loaded
        assertEqual
            "content identity cache round trip"
            (Right identifier)
            (Cache.decodeCache
                Content.getSourceContentIdCache
                (Cache.encodeCache
                    (Content.putSourceContentIdCache
                        identifier)))
        ByteString.writeFile source (bytes <> "\n")
        changed <- expectRight
            =<< loadResolvedSource (loadedSource loaded)
        assertBool
            "exact byte edits change source identity"
            (identifier /= Content.sourceContentId changed)

reportsInvalidUtf8Offsets :: Assertion
reportsInvalidUtf8Offsets =
    withTemporaryDirectory "felix-source-invalid-utf8" \temp -> do
        let source = temp Posix.</> "invalid.tex"
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "invalid.tex")
        let assertOffset label bytes expected = do
                ByteString.writeFile source (ByteString.pack bytes)
                result <- resolveAndLoadRoot mounts request
                case result of
                    Left (SourceDecodeError _source offset) ->
                        assertEqual label expected offset
                    Left err ->
                        assertFailure
                            ("expected SourceDecodeError, got " <> show err)
                    Right loaded ->
                        assertFailure
                            ("expected malformed UTF-8 rejection, got "
                                <> show loaded)
        assertOffset "malformed sequence start" [0x61, 0xC3, 0x28] 1
        assertOffset "incomplete sequence start" [0x61, 0xC3] 1

preservesReservedFileId :: Assertion
preservesReservedFileId =
    case allocateFileId boundaryAllocator of
        Left err ->
            assertFailure
                ("could not allocate last available file id: " <> show err)
        Right (fileId, exhaustedAllocator) -> do
            assertEqual "last available file id"
                (maxBound - 1)
                (unFileId fileId)
            assertBool "allocator returned reserved file id"
                (unFileId fileId /= maxBound)
            assertEqual "allocator reports exhaustion"
                (Left FileIdSpaceExhausted)
                (allocateFileId exhaustedAllocator)
  where
    boundaryAllocator =
        FileIdAllocator
            (fromIntegral (maxBound :: Word16) - 1)

buildsSourceGraph :: Assertion
buildsSourceGraph =
    withTemporaryDirectory "felix-source-graph" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory (temp Posix.</> "entry.tex") ["shared.tex"] "entry"
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        graph <- expectRight =<< buildResolvedSourceGraph mounts request
        assertEqual "two source nodes" 2 (length (sourceGraphNodes graph))
        case sourceGraphImportEdges graph of
            [edge] -> do
                assertEqual "root imports" (sourceGraphRoot graph) (sourceImportingNode edge)
                assertEqual
                    "imported-before-importer order"
                    [sourceImportedNode edge, sourceGraphRoot graph]
                    ( sourceNodeCanonicalPathForTest
                        <$> toList
                            (sourceGraphImportedBeforeImporter graph)
                    )
                assertEqual "import location line" 1
                    (locLine (importLocation (sourceImportReference edge)))
                assertEqual "selected location path" "entry.tex"
                    (locFile (importLocation (sourceImportReference edge)))
            edges ->
                assertFailure ("expected one import edge, got " <> show edges)

ordersSiblingImports :: Assertion
ordersSiblingImports =
    withTemporaryDirectory "felix-source-sibling-order" \temp -> do
        writeTheory (temp Posix.</> "a.tex") [] "a"
        writeTheory (temp Posix.</> "b.tex") [] "b"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["a.tex", "b.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        order <- sourceGraphOrderPaths graph
        assertEqual "DFS completion order"
            ["a.tex", "b.tex", "entry.tex"]
            order

ordersSharedDependencies :: Assertion
ordersSharedDependencies =
    withTemporaryDirectory "felix-source-shared-order" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory (temp Posix.</> "a.tex") ["shared.tex"] "a"
        writeTheory (temp Posix.</> "b.tex") ["shared.tex"] "b"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["a.tex", "b.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        order <- sourceGraphOrderPaths graph
        assertEqual "shared dependency occurs once before both importers"
            ["shared.tex", "a.tex", "b.tex", "entry.tex"]
            order

retainsRepeatedImports :: Assertion
retainsRepeatedImports =
    withTemporaryDirectory "felix-source-repeated-import" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["shared.tex", "shared.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        assertEqual "canonical node count" 2 (length (sourceGraphNodes graph))
        assertEqual "repeated edge count" 2 (length (sourceGraphImportEdges graph))

deduplicatesCanonicalNodes :: Assertion
deduplicatesCanonicalNodes =
    withTemporaryDirectory "felix-source-canonical-dedup" \temp -> do
        let shared = temp Posix.</> "shared.tex"
            alias = temp Posix.</> "alias.tex"
        writeTheory shared [] "shared"
        Directory.createFileLink shared alias
        writeTheory
            (temp Posix.</> "entry.tex")
            ["shared.tex", "alias.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        assertEqual "one node for symlink aliases" 2 (length (sourceGraphNodes graph))
        case sourceGraphImportEdges graph of
            [firstEdge, secondEdge] ->
                assertEqual
                    "both occurrences reach one node"
                    (sourceImportedNode firstEdge)
                    (sourceImportedNode secondEdge)
            edges ->
                assertFailure ("expected two import edges, got " <> show edges)

reportsMissingImports :: Assertion
reportsMissingImports =
    withTemporaryDirectory "felix-source-missing-import" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "% heading"
                , "\\import{missing.tex}"
                , theoryBlock "entry"
                ])
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        result <- buildResolvedSourceGraph mounts request
        case result of
            Left (SourceNotFound (ImportedSourceLookup _ reference) _candidates) -> do
                assertEqual "missing import line" 2 (locLine (importLocation reference))
                assertEqual "missing import source" "entry.tex"
                    (locFile (importLocation reference))
            Left err ->
                assertFailure ("expected located SourceNotFound, got " <> show err)
            Right graph ->
                assertFailure ("expected missing-import rejection, got " <> show graph)

rejectsUnsafeImports :: Assertion
rejectsUnsafeImports =
    withTemporaryDirectory "felix-source-unsafe-import" \temp -> do
        writeTheory (temp Posix.</> "entry.tex") ["./shared.tex"] "entry"
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        result <- buildResolvedSourceGraph mounts request
        case result of
            Left (InvalidImportPath _source location raw CurrentDirectoryComponent) -> do
                assertEqual "raw import" "./shared.tex" raw
                assertEqual "unsafe import line" 1 (locLine location)
                assertEqual "unsafe import source" "entry.tex" (locFile location)
            Left err ->
                assertFailure ("expected InvalidImportPath, got " <> show err)
            Right graph ->
                assertFailure ("expected unsafe-import rejection, got " <> show graph)

reportsImportCycles :: Assertion
reportsImportCycles =
    withTemporaryDirectory "felix-source-cycle" \temp -> do
        writeTheory (temp Posix.</> "a.tex") ["b.tex"] "a"
        writeTheory (temp Posix.</> "b.tex") ["a.tex"] "b"
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "a.tex")
        result <- buildResolvedSourceGraph mounts request
        case result of
            Left (SourceImportCycle steps) -> do
                assertEqual "cycle length" 2 (length steps)
                assertEqual
                    "cycle importer sequence"
                    ["a.tex", "b.tex"]
                    [ safeRelativePathFilePath
                        (resolvedSourceRelativePath (cycleImporter step))
                    | step <- toList steps
                    ]
                assertEqual
                    "cycle import locations"
                    ["a.tex", "b.tex"]
                    [ locFile (importLocation (cycleImport step))
                    | step <- toList steps
                    ]
            Left err ->
                assertFailure ("expected SourceImportCycle, got " <> show err)
            Right graph ->
                assertFailure ("expected cycle rejection, got " <> show graph)

rejectsMalformedImportedSource :: Assertion
rejectsMalformedImportedSource =
    withTemporaryDirectory "felix-source-import-utf8" \temp -> do
        writeTheory (temp Posix.</> "entry.tex") ["bad.tex"] "entry"
        ByteString.writeFile
            (temp Posix.</> "bad.tex")
            (ByteString.pack [0x61, 0xFF])
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        result <- buildResolvedSourceGraph mounts request
        case result of
            Left (SourceDecodeError source offset) -> do
                assertEqual "bad source" "bad.tex"
                    (safeRelativePathFilePath (resolvedSourceRelativePath source))
                assertEqual "bad byte offset" 1 offset
            Left err ->
                assertFailure ("expected SourceDecodeError, got " <> show err)
            Right graph ->
                assertFailure ("expected malformed-source rejection, got " <> show graph)

buildsEmptyModules :: Assertion
buildsEmptyModules =
    withTemporaryDirectory "felix-source-empty" \temp ->
        forM_
            [ ("empty.tex", "")
            , ("comments.tex", "% heading\n% body")
            ]
            \(relative, contents) -> do
                writeFile (temp Posix.</> relative) contents
                graph <- buildSearchedGraph temp relative
                assertEqual
                    "one ordinary graph node"
                    1
                    (length (sourceGraphNodes graph))
                emittedRef <- newIORef (0 :: Int)
                workspace <-
                    expectRight
                        =<< Parse.parseResolvedSourceGraphWith
                            graph
                            (\_source _block ->
                                modifyIORef' emittedRef (+ 1))
                assertEqual
                    "no block callbacks"
                    0
                    =<< readIORef emittedRef
                assertEqual
                    "empty parsed projection"
                    []
                    (Parse.importedBeforeImporterBlocks workspace)
                assertBool
                    "empty syntax declarations"
                    (null
                        (Interface.canonicalSyntaxDeltaEntries
                            (Interface.moduleSyntaxLocalDelta
                                (Parse.parsedModuleSyntaxInterface
                                    (Parse.parsedWorkspaceRootModule
                                        workspace)))))

identifiesOwnerIndependentParsedModules :: Assertion
identifiesOwnerIndependentParsedModules =
    withTemporaryDirectory "felix-parsed-identity" \temp -> do
        let firstRoot = temp Posix.</> "first"
            secondRoot = temp Posix.</> "second"
            bytes = axiomBlock "same" "x = x"
        Directory.createDirectory firstRoot
        Directory.createDirectory secondRoot
        writeFile (firstRoot Posix.</> "entry.tex") bytes
        writeFile (secondRoot Posix.</> "entry.tex") bytes
        firstWorkspace <- expectRight
            =<< Parse.parseResolvedSourceGraph
            =<< buildSearchedGraph firstRoot "entry.tex"
        secondWorkspace <- expectRight
            =<< Parse.parseResolvedSourceGraph
            =<< buildSearchedGraph secondRoot "entry.tex"
        let first = Parse.parsedWorkspaceRootModule firstWorkspace
            second = Parse.parsedWorkspaceRootModule secondWorkspace
        assertBool
            "logical owners remain distinct"
            ( Module.moduleName (Parse.parsedModuleAddress first)
                /= Module.moduleName (Parse.parsedModuleAddress second)
            )
        assertEqual
            "equal bytes retain one content identity"
            (Parse.parsedModuleSourceContentId first)
            (Parse.parsedModuleSourceContentId second)
        assertEqual
            "physical source registration is outside parsed identity"
            (Parse.parsedModuleId first)
            (Parse.parsedModuleId second)
        assertEqual
            "canonical payload is owner-independent"
            (Parse.parsedModulePayload first)
            (Parse.parsedModulePayload second)
        let payload = Parse.parsedModulePayload first
        assertEqual
            "canonical parsed payload cache round trip"
            (Right payload)
            (Cache.decodeCache
                Parsed.getCanonicalParsedPayloadCache
                (Cache.encodeCache
                    (Parsed.putCanonicalParsedPayloadCache payload)))
        rebound <- expectRight
            (Parsed.decodeCanonicalParsedPayload
                (FileId 123)
                payload)
        case Parsed.decodedParsedBlocks rebound of
            Raw.BlockAxiom location _title _marker _axiom : _ ->
                assertEqual
                    "decoded locations bind only to the current live file"
                    (Just (FileId 123))
                    (locFileId location)
            blocks ->
                assertFailure
                    ("expected decoded axiom, got " <> show blocks)
        writeFile
            (secondRoot Posix.</> "entry.tex")
            (bytes <> "% content identity change\n")
        changedWorkspace <- expectRight
            =<< Parse.parseResolvedSourceGraph
            =<< buildSearchedGraph secondRoot "entry.tex"
        assertBool
            "exact source changes parsed identity"
            ( Parse.parsedModuleId first
                /= Parse.parsedModuleId
                    (Parse.parsedWorkspaceRootModule changedWorkspace)
            )

keysEffectiveDirectSyntaxInputs :: Assertion
keysEffectiveDirectSyntaxInputs =
    withTemporaryDirectory "felix-parsed-syntax-input" \temp -> do
        let firstRoot = temp Posix.</> "first"
            secondRoot = temp Posix.</> "second"
            rootBytes = "\\import{notation.tex}\n"
        Directory.createDirectory firstRoot
        Directory.createDirectory secondRoot
        writeFile (firstRoot Posix.</> "entry.tex") rootBytes
        writeFile (secondRoot Posix.</> "entry.tex") rootBytes
        writeFile
            (firstRoot Posix.</> "notation.tex")
            (syntaxFunctionDefinition
                "first_notation"
                "firstop"
                (Just "%! infixl 1"))
        writeFile
            (secondRoot Posix.</> "notation.tex")
            (syntaxFunctionDefinition
                "second_notation"
                "secondop"
                (Just "%! infixl 1"))
        firstWorkspace <- expectRight
            =<< Parse.parseResolvedSourceGraph
            =<< buildSearchedGraph firstRoot "entry.tex"
        secondWorkspace <- expectRight
            =<< Parse.parseResolvedSourceGraph
            =<< buildSearchedGraph secondRoot "entry.tex"
        let first = Parse.parsedWorkspaceRootModule firstWorkspace
            second = Parse.parsedWorkspaceRootModule secondWorkspace
        assertEqual
            "root source bytes are unchanged"
            (Parse.parsedModuleSourceContentId first)
            (Parse.parsedModuleSourceContentId second)
        assertBool
            "effective syntax changes the parsed key"
            (Parse.parsedModuleKey first /= Parse.parsedModuleKey second)
        assertBool
            "effective syntax changes parsed identity"
            (Parse.parsedModuleId first /= Parse.parsedModuleId second)

reusesExactParsedSyntax :: Assertion
reusesExactParsedSyntax =
    withTemporaryDirectory "felix-parsed-warm" \temp -> do
        let datatype = unlines
                [ "\\begin{datatype}\\label{multi_item}"
                , "  Define $\\itemkind$ inductively as follows."
                , "  \\begin{enumerate}"
                , "    \\item $\\itemzero \\in \\itemkind$."
                , "    \\item $\\itemsucc{x} \\in \\itemkind$ for $x \\in \\itemkind$."
                , "  \\end{enumerate}"
                , "\\end{datatype}"
                ]
        writeFile
            (temp Posix.</> "entry.tex")
            (builtinZeroDefinition "source_zero" <> datatype)
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        foundation <- expectRight Foundation.checkedFoundation
        store <- openTestStore
            (temp Posix.</> "store.sqlite")
            (Identity.theoryId foundation)
        coldCallbacks <- newIORef (0 :: Int)
        cold <- expectParseExecution
            =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputsAndCallback
                store mounts request (const [])
                (\_source _block -> modifyIORef' coldCallbacks (+ 1))
        warmCallbacks <- newIORef (0 :: Int)
        warm <- expectParseExecution
            =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputsAndCallback
                store mounts request (const [])
                (\_source _block -> modifyIORef' warmCallbacks (+ 1))
        let coldRoot = Parse.parsedWorkspaceRootModule (fst cold)
            warmRoot = Parse.parsedWorkspaceRootModule (fst warm)
            coldMeasurements = snd cold
            warmMeasurements = snd warm
        assertEqual "cold parsed misses" 1
            (Parse.parseMeasurementParsedMissCount coldMeasurements)
        assertEqual "cold parser tables" 1
            (Parse.parseMeasurementParserTableMaterializationCount
                coldMeasurements)
        assertEqual "warm parsed hits" 1
            (Parse.parseMeasurementParsedHitCount warmMeasurements)
        assertEqual "warm parsed misses" 0
            (Parse.parseMeasurementParsedMissCount warmMeasurements)
        assertEqual "warm tokenization" 0
            (Parse.parseMeasurementTokenizationNanoseconds warmMeasurements)
        assertEqual "warm scanning" 0
            (Parse.parseMeasurementScanningNanoseconds warmMeasurements)
        assertEqual "warm parsing" 0
            (Parse.parseMeasurementParsingNanoseconds warmMeasurements)
        assertEqual "warm parser tables" 0
            (Parse.parseMeasurementParserTableMaterializationCount
                warmMeasurements)
        let expectedChunkCount =
                length (Parse.parsedModuleBlocks warmRoot)
        assertBool "fixture has source chunks" (expectedChunkCount > 0)
        assertEqual "cold structural chunks" expectedChunkCount
            (Parse.parseMeasurementChunkCount coldMeasurements)
        assertEqual "warm structural chunks" expectedChunkCount
            (Parse.parseMeasurementChunkCount warmMeasurements)
        assertEqual "warm blocks" (Parse.parsedModuleBlocks coldRoot)
            (Parse.parsedModuleBlocks warmRoot)
        assertEqual "warm occurrences"
            (Parse.parsedModuleSyntaxOccurrences coldRoot)
            (Parse.parsedModuleSyntaxOccurrences warmRoot)
        assertEqual "warm syntax interface"
            (Parse.parsedModuleSyntaxInterface coldRoot)
            (Parse.parsedModuleSyntaxInterface warmRoot)
        assertEqual "warm parsed identity"
            (Parse.parsedModuleId coldRoot)
            (Parse.parsedModuleId warmRoot)
        case Parse.parsedModuleSyntaxOccurrences warmRoot of
            first : second : third : fourth : [] -> do
                assertEqual "fixed source marker" "source_zero"
                    (Parse.parsedSyntaxOccurrenceMarker first)
                case Parse.parsedSyntaxOccurrenceEntry first of
                    Interface.CanonicalExpressionFunction
                            _pattern marker _fixity ->
                        assertEqual "fixed authoritative marker" "zero" marker
                    entry ->
                        assertFailure
                            ("unexpected fixed cached entry: " <> show entry)
                assertEqual "multi-item block order" [1, 1, 1]
                    (Parse.parsedSyntaxOccurrenceBlockIndex
                        <$> [second, third, fourth])
                assertEqual "multi-item scanner order"
                    ["multi_item", "itemzero", "itemsucc"]
                    (Parse.parsedSyntaxOccurrenceMarker
                        <$> [second, third, fourth])
                case drop 1 (Parse.parsedModuleBlocks warmRoot) of
                    block : _ ->
                        case block of
                            Raw.BlockData _location _title marker _datatype ->
                                assertEqual "cached declaration-head anchor"
                                    marker
                                    (Parse.parsedSyntaxOccurrenceMarker second)
                            other ->
                                assertFailure
                                    ("expected cached datatype block, got "
                                        <> show other)
                    [] ->
                        assertFailure "cached datatype block is absent"
            occurrences ->
                assertFailure
                    ("unexpected cached syntax occurrences: "
                        <> show occurrences)
        assertEqual "cold callback projection" 2
            =<< readIORef coldCallbacks
        assertEqual "warm callback projection" 2
            =<< readIORef warmCallbacks
        Store.closeStore store

invalidatesExactParsedInputs :: Assertion
invalidatesExactParsedInputs =
    withTemporaryDirectory "felix-parsed-invalidation" \temp -> do
        let notationPath = temp Posix.</> "notation.tex"
            entryPath = temp Posix.</> "entry.tex"
            notation associativity level =
                syntaxFunctionDefinition
                    "join"
                    "join"
                    (Just
                        ("%! " <> associativity <> " " <> show level))
            entry suffix =
                "\\import{notation.tex}\n"
                    <> axiomBlock
                        "imported_syntax_use"
                        "a\\join b\\join c = a"
                    <> suffix
        writeFile notationPath (notation "infixl" (1 :: Int))
        writeFile entryPath (entry "")
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        foundation <- expectRight Foundation.checkedFoundation
        store <- openTestStore
            (temp Posix.</> "store.sqlite")
            (Identity.theoryId foundation)
        let parse =
                expectParseExecution
                    =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputs
                        store mounts request (const [])
        (coldWorkspace, coldMeasurements) <- parse
        (warmWorkspace, warmMeasurements) <- parse
        assertEqual "cold graph misses" 2
            (Parse.parseMeasurementParsedMissCount coldMeasurements)
        assertEqual "unchanged graph hits" 2
            (Parse.parseMeasurementParsedHitCount warmMeasurements)
        assertEqual "unchanged graph builds no parser table" 0
            (Parse.parseMeasurementParserTableMaterializationCount
                warmMeasurements)
        coldNotation <- findParsedModule "notation.tex" coldWorkspace
        warmNotation <- findParsedModule "notation.tex" warmWorkspace
        let coldRoot = Parse.parsedWorkspaceRootModule coldWorkspace
            warmRoot = Parse.parsedWorkspaceRootModule warmWorkspace
        assertEqual "unchanged import identity"
            (Parse.parsedModuleId coldNotation)
            (Parse.parsedModuleId warmNotation)
        assertEqual "unchanged importer identity"
            (Parse.parsedModuleId coldRoot)
            (Parse.parsedModuleId warmRoot)

        writeFile entryPath (entry "% formatting-only edit\n")
        (editedWorkspace, editedMeasurements) <- parse
        editedNotation <- findParsedModule "notation.tex" editedWorkspace
        let editedRoot = Parse.parsedWorkspaceRootModule editedWorkspace
        assertEqual "unchanged import hits" 1
            (Parse.parseMeasurementParsedHitCount editedMeasurements)
        assertEqual "edited importer misses" 1
            (Parse.parseMeasurementParsedMissCount editedMeasurements)
        assertEqual "edited importer builds one parser table" 1
            (Parse.parseMeasurementParserTableMaterializationCount
                editedMeasurements)
        assertEqual "cached import retains identity"
            (Parse.parsedModuleId warmNotation)
            (Parse.parsedModuleId editedNotation)
        assertBool "exact source edit changes importer key"
            (Parse.parsedModuleKey warmRoot
                /= Parse.parsedModuleKey editedRoot)
        assertEqual "formatting retains parsed projection"
            (Parse.parsedModulePayload warmRoot)
            (Parse.parsedModulePayload editedRoot)

        writeFile notationPath (notation "infixr" (2 :: Int))
        (syntaxWorkspace, syntaxMeasurements) <- parse
        syntaxNotation <- findParsedModule "notation.tex" syntaxWorkspace
        let syntaxRoot = Parse.parsedWorkspaceRootModule syntaxWorkspace
        assertEqual "syntax edit invalidates both modules" 0
            (Parse.parseMeasurementParsedHitCount syntaxMeasurements)
        assertEqual "syntax edit reparses both modules" 2
            (Parse.parseMeasurementParsedMissCount syntaxMeasurements)
        assertEqual "syntax edit builds both parser tables" 2
            (Parse.parseMeasurementParserTableMaterializationCount
                syntaxMeasurements)
        assertBool "local syntax identity changes"
            ( Interface.moduleSyntaxAssertedId
                (Parse.parsedModuleSyntaxInterface editedNotation)
                /= Interface.moduleSyntaxAssertedId
                    (Parse.parsedModuleSyntaxInterface syntaxNotation)
            )
        assertEqual "importer source is unchanged"
            (Parse.parsedModuleSourceContentId editedRoot)
            (Parse.parsedModuleSourceContentId syntaxRoot)
        assertBool "direct syntax invalidates importer key"
            (Parse.parsedModuleKey editedRoot
                /= Parse.parsedModuleKey syntaxRoot)
        Store.closeStore store

rebindsRelocatedParsedArtifacts :: Assertion
rebindsRelocatedParsedArtifacts =
    withTemporaryDirectory "felix-parsed-relocation" \temp -> do
        let firstRoot = temp Posix.</> "first"
            secondRoot = temp Posix.</> "second"
            sourceBytes = axiomBlock "same" "x = x"
        Directory.createDirectory firstRoot
        Directory.createDirectory secondRoot
        writeFile (firstRoot Posix.</> "entry.tex") sourceBytes
        writeFile (secondRoot Posix.</> "entry.tex") sourceBytes
        firstMounts <- oneMount "first" firstRoot
        secondMounts <- oneMount "second" secondRoot
        request <- expectRight (searchedRoot "entry.tex")
        foundation <- expectRight Foundation.checkedFoundation
        let theory = Identity.theoryId foundation
        store <- openTestStore (temp Posix.</> "store.sqlite") theory
        (firstWorkspace, firstMeasurements) <- expectParseExecution
            =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputs
                store firstMounts request (const [])
        (secondWorkspace, secondMeasurements) <- expectParseExecution
            =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputs
                store secondMounts request (const [])
        let first = Parse.parsedWorkspaceRootModule firstWorkspace
            second = Parse.parsedWorkspaceRootModule secondWorkspace
            firstSource = Parse.parsedModuleResolved first
            secondSource = Parse.parsedModuleResolved second
        assertEqual "first owner misses" 1
            (Parse.parseMeasurementParsedMissCount firstMeasurements)
        assertEqual "relocated owner hits" 1
            (Parse.parseMeasurementParsedHitCount secondMeasurements)
        assertEqual "relocated owner builds no parser table" 0
            (Parse.parseMeasurementParserTableMaterializationCount
                secondMeasurements)
        assertEqual "relocation retains parsed identity"
            (Parse.parsedModuleId first)
            (Parse.parsedModuleId second)
        assertEqual "relocation retains canonical payload"
            (Parse.parsedModulePayload first)
            (Parse.parsedModulePayload second)
        assertBool "relocation rebinds the physical source"
            (resolvedSourceCanonicalPath firstSource
                /= resolvedSourceCanonicalPath secondSource)
        assertBool "relocation rebinds the logical owner"
            (Parse.parsedModuleAddress first
                /= Parse.parsedModuleAddress second)
        firstFileId <- expectJust "first location file id"
            (locFileId (onlyAxiomLocation first))
        secondFileId <- expectJust "second location file id"
            (locFileId (onlyAxiomLocation second))
        assertBool "relocation rebinds locations"
            (firstFileId /= secondFileId)
        firstArtifactKey <- expectRight
            (Semantic.moduleArtifactKey
                (Module.moduleName (Parse.parsedModuleAddress first))
                (Parse.parsedModuleId first)
                []
                theory)
        secondArtifactKey <- expectRight
            (Semantic.moduleArtifactKey
                (Module.moduleName (Parse.parsedModuleAddress second))
                (Parse.parsedModuleId second)
                []
                theory)
        assertBool "module artifact remains owner-dependent"
            (Semantic.moduleArtifactId firstArtifactKey
                /= Semantic.moduleArtifactId secondArtifactKey)
        Store.closeStore store

rejectsCorruptedCachedDeclarationAnchor :: Assertion
rejectsCorruptedCachedDeclarationAnchor =
    withTemporaryDirectory "felix-parsed-corrupt-anchor" \temp -> do
        writeBuiltinZeroDefinition
            (temp Posix.</> "entry.tex")
            "source_zero"
        mounts <- oneMount "project" temp
        request <- expectRight (searchedRoot "entry.tex")
        foundation <- expectRight Foundation.checkedFoundation
        let storePath = temp Posix.</> "store.sqlite"
            theory = Identity.theoryId foundation
        store <- openTestStore storePath theory
        (cold, _measurements) <- expectParseExecution
            =<< Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputs
                store mounts request (const [])
        let parsed = Parse.parsedWorkspaceRootModule cold
            key = Parse.parsedModuleKey parsed
        fileId <- case Parse.parsedModuleSyntaxOccurrences parsed of
            occurrence : _ ->
                expectJust
                    "parsed occurrence file id"
                    (locFileId
                        (Parse.parsedSyntaxOccurrenceLocation occurrence))
            [] ->
                assertFailure "parsed fixed occurrence is absent"
                    >> fail "unreachable"
        decoded <- expectRight
            (Parsed.decodeCanonicalParsedPayload
                fileId
                (Parse.parsedModulePayload parsed))
        Store.closeStore store
        let corruptedOccurrences = case Parsed.decodedParsedOccurrences decoded of
                (blockIndex, location, _marker, entry) : rest ->
                    (blockIndex, location, "corrupted_anchor", entry) : rest
                [] ->
                    []
            corruptedPayload =
                Parsed.canonicalParsedPayload
                    (Parsed.decodedParsedImports decoded)
                    (Parsed.decodedParsedBlocks decoded)
                    corruptedOccurrences
                    (Parsed.decodedParsedSyntaxInterface decoded)
            corruptedId =
                ParsedIdentity.parsedModuleId
                    key
                    (Parsed.canonicalParsedPayloadBytes corruptedPayload)
        connection <- SQLite.open storePath
        SQLite.execute connection
            "UPDATE parsed_artifacts \
            \SET parsed_module_id = ?, payload = ? \
            \WHERE parsed_module_key = ?"
            ( Cache.cacheDigestBytes
                (ParsedIdentity.parsedModuleIdDigest corruptedId)
            , Parsed.canonicalParsedPayloadBytes corruptedPayload
            , Cache.cacheDigestBytes
                (ParsedIdentity.parsedModuleKeyDigest key)
            )
        SQLite.close connection
        current <- openTestStore storePath theory
        callbacks <- newIORef (0 :: Int)
        Parse.parseSourceWorkspaceMeasuredWithStoreAndSyntaxInputsAndCallback
            current mounts request (const [])
            (\_source _block -> modifyIORef' callbacks (+ 1)) >>= \case
                Left
                    (Parse.ParseExecutionArtifactIntegrityFailure
                        _source
                        (Parse.ParsedArtifactAssociationFailure
                            Parse.SyntaxOccurrenceMarkerMismatch{})) ->
                            pure ()
                other ->
                    assertFailure
                        ("unexpected corrupted parsed result: " <> show other)
        assertEqual "corrupt hit invokes no parse callback" 0
            =<< readIORef callbacks
        Store.closeStore current

openTestStore :: FilePath -> Identity.TheoryId -> IO Store.Store
openTestStore path theory =
    Store.openStore path theory >>= \case
        Left failure ->
            assertFailure (show failure) >> fail "unreachable"
        Right (_startup, store) ->
            pure store

expectParseExecution
    :: Either Parse.ParseExecutionError value
    -> IO value
expectParseExecution = \case
    Left failure ->
        assertFailure (show failure) >> fail "unreachable"
    Right value ->
        pure value

parsesSourceGraph :: Assertion
parsesSourceGraph =
    withTemporaryDirectory "felix-source-parse" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory (temp Posix.</> "entry.tex") ["shared.tex"] "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        emittedRef <- newIORef []
        workspace <- expectRight =<<
            Parse.parseResolvedSourceGraphWith graph
                (\source _block ->
                    modifyIORef'
                        emittedRef
                        (safeRelativePathFilePath
                            (resolvedSourceRelativePath source) :))
        assertEqual "two parsed source nodes" 2
            (length (Parse.parsedWorkspaceModules workspace))
        assertEqual "one source-local block per node" [1, 1]
            (toList
                (length . Parse.parsedModuleBlocks
                    <$> Parse.parsedWorkspaceImportedBeforeImporter workspace))
        assertEqual "imported-before-importer source order"
            ["shared.tex", "entry.tex"]
            (toList
                (safeRelativePathFilePath
                    . resolvedSourceRelativePath
                    . Parse.parsedModuleResolved
                    <$> Parse.parsedWorkspaceImportedBeforeImporter workspace))
        assertEqual "flattened block view" 2
            (length (Parse.importedBeforeImporterBlocks workspace))
        emitted <- reverse <$> readIORef emittedRef
        assertEqual "streamed block order"
            ["shared.tex", "entry.tex"]
            emitted

rejectsSiblingSyntaxLeakage :: Assertion
rejectsSiblingSyntaxLeakage =
    withTemporaryDirectory "felix-source-syntax-world" \temp -> do
        writeFile
            (temp Posix.</> "use.tex")
            (unlines
                [ "\\begin{axiom}\\label{use}"
                , "  $x$ is special."
                , "\\end{axiom}"
                ])
        writeAdjectiveDefinition
            (temp Posix.</> "declare.tex")
            "shared_special"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["use.tex", "declare.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        result <- Parse.parseResolvedSourceGraph graph
        case result of
            Left (Parse.SourceParseError source _parseError) ->
                assertEqual
                    "syntax consumer fails in its own module"
                    "use.tex"
                    (safeRelativePathFilePath
                        (resolvedSourceRelativePath source))
            Left err ->
                assertFailure
                    ("expected a source-local parse error, got "
                        <> show err)
            Right workspace ->
                assertFailure
                    ("sibling syntax leaked into use.tex: "
                        <> show workspace)

parsesSourceFixities :: Assertion
parsesSourceFixities =
    withTemporaryDirectory "felix-source-fixity" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            ( syntaxFunctionDefinition
                "loose"
                "loose"
                (Just "%! infixl 0")
              <> syntaxFunctionDefinition
                "tight"
                "tight"
                (Just "%! infixr 7")
              <> axiomBlock
                "loose_associativity"
                "a\\loose b\\loose c = a"
              <> axiomBlock
                "tight_associativity"
                "a\\tight b\\tight c = a"
              <> axiomBlock
                "mixed_precedence"
                "a\\loose b\\tight c = a"
              <> axiomBlock
                "parenthesized_precedence"
                "(a\\loose b)\\tight c = a"
            )
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        let root =
                Parse.parsedWorkspaceRootModule workspace
            localEntries =
                Interface.canonicalSyntaxDeltaEntries
                    (Interface.moduleSyntaxLocalDelta
                        (Parse.parsedModuleSyntaxInterface root))
        assertExpressionFixity
            "loose"
            Raw.LeftAssoc
            0
            localEntries
        assertExpressionFixity
            "tight"
            Raw.RightAssoc
            7
            localEntries
        assertEqual
            "source declaration occurrences"
            [0, 1]
            (Parse.parsedSyntaxOccurrenceBlockIndex
                <$> Parse.parsedModuleSyntaxOccurrences root)
        case drop 2 (Parse.parsedModuleBlocks root) of
            [ looseAssociativity
              , tightAssociativity
              , mixedPrecedence
              , parenthesizedPrecedence
              ] -> do
                    assertAxiomLeftShape
                        "left associativity"
                        "loose(loose(a,b),c)"
                        looseAssociativity
                    assertAxiomLeftShape
                        "right associativity"
                        "tight(a,tight(b,c))"
                        tightAssociativity
                    assertAxiomLeftShape
                        "mixed precedence"
                        "loose(a,tight(b,c))"
                        mixedPrecedence
                    assertAxiomLeftShape
                        "parentheses override precedence"
                        "tight(loose(a,b),c)"
                        parenthesizedPrecedence
            blocks ->
                assertFailure
                    ("expected four fixity axioms, got "
                        <> show blocks)

parsesLibraryFixities :: Assertion
parsesLibraryFixities =
    withTemporaryDirectory "felix-source-library-fixity" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            ( syntaxFunctionDefinition
                "cdot"
                "cdot"
                (Just "%! infixl 4")
              <> syntaxFunctionDefinition
                "symdiff"
                "symdiff"
                (Just "%! infixl 1")
              <> axiomBlock
                "cdot_associativity"
                "a\\cdot b\\cdot c = a"
              <> axiomBlock
                "symdiff_associativity"
                "a\\symdiff b\\symdiff c = a"
              <> axiomBlock
                "library_mixed_precedence"
                "a\\symdiff b\\cdot c = a"
              <> axiomBlock
                "library_parentheses"
                "(a\\symdiff b)\\cdot c = a"
            )
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        case drop 2
                (Parse.parsedModuleBlocks
                    (Parse.parsedWorkspaceRootModule workspace)) of
            [ cdotAssociativity
              , symdiffAssociativity
              , mixedPrecedence
              , parenthesizedPrecedence
              ] -> do
                    assertAxiomLeftShape
                        "cdot left associativity"
                        "cdot(cdot(a,b),c)"
                        cdotAssociativity
                    assertAxiomLeftShape
                        "symdiff left associativity"
                        "symdiff(symdiff(a,b),c)"
                        symdiffAssociativity
                    assertAxiomLeftShape
                        "cdot binds tighter than symdiff"
                        "symdiff(a,cdot(b,c))"
                        mixedPrecedence
                    assertAxiomLeftShape
                        "library parentheses override precedence"
                        "cdot(symdiff(a,b),c)"
                        parenthesizedPrecedence
            blocks ->
                assertFailure
                    ("expected four library-fixity axioms, got "
                        <> show blocks)

validatesSourcePragmaAssociations :: Assertion
validatesSourcePragmaAssociations =
    forM_ cases \(description, contents, checkProblem) ->
        withTemporaryDirectory
            ("felix-source-pragma-" <> description)
            \temp -> do
                writeFile
                    (temp Posix.</> "entry.tex")
                    contents
                graph <- buildSearchedGraph temp "entry.tex"
                result <- Parse.parseResolvedSourceGraph graph
                case result of
                    Left
                        (Parse.SourceSyntaxDeclarationError
                            source
                            problem) -> do
                                assertEqual
                                    "pragma source"
                                    "entry.tex"
                                    (safeRelativePathFilePath
                                        (resolvedSourceRelativePath source))
                                checkProblem problem
                    Left err ->
                        assertFailure
                            ("expected source pragma error, got "
                                <> show err)
                    Right workspace ->
                        assertFailure
                            ("expected source pragma rejection, got "
                                <> show workspace)
  where
    cases
        :: [ ( String
             , String
             , Parse.SyntaxDeclarationError -> Assertion
             )
           ]
    cases =
        [ ( "outside"
          , "%! infixl 1\n" <> theoryBlock "outside"
          , \case
                Parse.SyntaxPragmaOutsideDeclaration{} ->
                    pure ()
                problem ->
                    unexpected "outside-declaration pragma" problem
          )
        , ( "inside-nonsyntax"
          , unlines
                [ "\\begin{axiom}\\label{inside_nonsyntax}"
                , "  %! infixl 1"
                , "  $x = x$."
                , "\\end{axiom}"
                ]
          , \case
                Parse.SyntaxPragmaOutsideDeclaration location ->
                    assertEqual
                        "pragma in non-syntax chunk"
                        2
                        (locLine location)
                problem ->
                    unexpected "non-syntax declaration pragma" problem
          )
        , ( "missing"
          , syntaxFunctionDefinition
                "missing"
                "missing"
                Nothing
          , \case
                Parse.MissingSyntaxPragma{} ->
                    pure ()
                problem ->
                    unexpected "missing pragma" problem
          )
        , ( "duplicate"
          , unlines
                [ "\\begin{abbreviation}\\label{duplicate}"
                , "  %! infixl 1"
                , "  %! infixl 1"
                , "  $x\\duplicate y = x$."
                , "\\end{abbreviation}"
                ]
          , \case
                Parse.DuplicateSyntaxPragma{} ->
                    pure ()
                problem ->
                    unexpected "duplicate pragma" problem
          )
        , ( "irrelevant"
          , unlines
                [ "\\begin{definition}\\label{irrelevant}"
                , "  %! infixl 1"
                , "  $x$ is irrelevant iff $x = x$."
                , "\\end{definition}"
                ]
          , \case
                Parse.IrrelevantSyntaxPragma{} ->
                    pure ()
                problem ->
                    unexpected "irrelevant pragma" problem
          )
        , ( "multiple-without-pragma"
          , unlines
                [ "\\begin{datatype}\\label{multiple_patterns}"
                , "  Define $\\patternkind$ inductively as follows."
                , "  \\begin{enumerate}"
                , "    \\item $(x \\firstpattern y) \\in \\patternkind$."
                , "    \\item $(x \\secondpattern y) \\in \\patternkind$."
                , "  \\end{enumerate}"
                , "\\end{datatype}"
                ]
          , \case
                problem@(Parse.MultipleNewSyntaxPatternsWithoutPragma
                        location
                        patterns) -> do
                            assertEqual
                                "first new pattern location"
                                4
                                (locLine location)
                            assertEqual
                                "new pattern count"
                                2
                                (NonEmpty.length patterns)
                            assertBool
                                "accurate multiple-pattern message"
                                ("several new eligible patterns that V1 cannot select between"
                                    `List.isInfixOf` show problem)
                            assertBool
                                "message requires an unambiguous declaration"
                                ("make the declaration unambiguous"
                                    `List.isInfixOf` show problem)
                problem ->
                    unexpected "multiple unannotated patterns" problem
          )
        , ( "fixed"
          , unlines
                [ "\\begin{abbreviation}\\label{local_addition}"
                , "  %! infixl 1"
                , "  $x + y = x$."
                , "\\end{abbreviation}"
                ]
          , \case
                Parse.SyntaxPragmaOnFixedReuse{} ->
                    pure ()
                problem ->
                    unexpected "fixed-base pragma" problem
          )
        ]

    unexpected expected problem =
        assertFailure
            ("expected " <> expected <> ", got " <> show problem)

rejectsFixedBaseCategoryMismatch :: Assertion
rejectsFixedBaseCategoryMismatch =
    withTemporaryDirectory "felix-source-fixed-category" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{definition}\\label{local_add_relation}"
                , "  $x + y$ iff $x = y$."
                , "\\end{definition}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        collision <- expectLexiconCollision
            =<< Parse.parseResolvedSourceGraph graph
        assertEqual
            "fixed collision pattern"
            (Raw.HoleCons
                (Raw.TokenCons
                    (Raw.Symbol "+")
                    (Raw.HoleCons Raw.End)))
            (Parse.lexiconCollisionPattern collision)
        case toList (Parse.lexiconCollisionOrigins collision) of
            [ Parse.FixedLexiconOrigin
                    Interface.CanonicalExpressionFunction{}
              , Parse.SourceLexiconOrigin
                    Interface.CanonicalRelation{}
                    source
                    location
              ] -> do
                    assertEqual
                        "local collision source"
                        "entry.tex"
                        (safeRelativePathFilePath
                            (resolvedSourceRelativePath source))
                    assertLocation
                        "local collision declaration"
                        "entry.tex"
                        1
                        location
            origins ->
                assertFailure
                    ("expected fixed/source category origins, got "
                        <> show origins)

retainsMultiItemSyntaxOccurrences :: Assertion
retainsMultiItemSyntaxOccurrences =
    withTemporaryDirectory "felix-source-multi-item-syntax" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{datatype}\\label{multi_item}"
                , "  Define $\\itemkind$ inductively as follows."
                , "  \\begin{enumerate}"
                , "    \\item $\\itemzero \\in \\itemkind$."
                , "    \\item $\\itemsucc{x} \\in \\itemkind$ for $x \\in \\itemkind$."
                , "  \\end{enumerate}"
                , "\\end{datatype}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        let root =
                Parse.parsedWorkspaceRootModule workspace
            occurrences =
                Parse.parsedModuleSyntaxOccurrences root
            summarize occurrence =
                case Parse.parsedSyntaxOccurrenceEntry occurrence of
                    Interface.CanonicalExpressionFunction
                            _pattern
                            marker
                            _fixity ->
                        Right
                            ( Parse.parsedSyntaxOccurrenceBlockIndex
                                occurrence
                            , locLine
                                (Parse.parsedSyntaxOccurrenceLocation
                                    occurrence)
                            , Parse.parsedSyntaxOccurrenceMarker occurrence
                            , marker
                            )
                    entry ->
                        Left entry
        case traverse summarize occurrences of
            Right summaries ->
                assertEqual
                    "block association and scanner order"
                    [ (0, 2, "multi_item", "multi_item")
                    , (0, 4, "itemzero", "itemzero")
                    , (0, 5, "itemsucc", "itemsucc")
                    ]
                    summaries
            Left entry ->
                assertFailure
                    ("expected an expression occurrence, got "
                        <> show entry)
        case (Parse.parsedModuleBlocks root, occurrences) of
            ( Raw.BlockData _location _title blockMarker _datatype : _
              , firstOccurrence : _
              ) ->
                assertEqual
                    "first occurrence is the declaration-head anchor"
                    blockMarker
                    (Parse.parsedSyntaxOccurrenceMarker firstOccurrence)
            _ ->
                assertFailure "expected a datatype block and its occurrences"

propagatesImportedSyntax :: Assertion
propagatesImportedSyntax =
    withTemporaryDirectory "felix-source-syntax-diamond" \temp -> do
        writeFile
            (temp Posix.</> "base.tex")
            (syntaxFunctionDefinition
                "star"
                "star"
                (Just "%! infixl 3"))
        writeFile
            (temp Posix.</> "left.tex")
            ("\\import{base.tex}\n"
                <> syntaxFunctionDefinition
                    "star"
                    "star"
                    Nothing)
        writeTheory
            (temp Posix.</> "right.tex")
            ["base.tex"]
            "right"
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\import{left.tex}"
                , "\\import{right.tex}"
                ]
                <> axiomBlock
                    "imported_use"
                    "a\\star b\\star c = a")
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        baseModule <- findParsedModule "base.tex" workspace
        leftModule <- findParsedModule "left.tex" workspace
        rightModule <- findParsedModule "right.tex" workspace
        let root =
                Parse.parsedWorkspaceRootModule workspace
            interface =
                Parse.parsedModuleSyntaxInterface
            localEntries parsed =
                Interface.canonicalSyntaxDeltaEntries
                    (Interface.moduleSyntaxLocalDelta
                        (interface parsed))
        assertEqual "base exports one syntax entry"
            1
            (length (localEntries baseModule))
        assertEqual "imported reuse emits no local entry"
            []
            (localEntries leftModule)
        assertEqual "imported reuse retains its occurrence"
            1
            (length
                (Parse.parsedModuleSyntaxOccurrences leftModule))
        assertEqual "empty diamond branch has no occurrence"
            []
            (Parse.parsedModuleSyntaxOccurrences rightModule)
        assertEqual "equal diamond interfaces"
            (Interface.moduleSyntaxAssertedId
                (interface leftModule))
            (Interface.moduleSyntaxAssertedId
                (interface rightModule))
        assertEqual "root coalesces equal direct interfaces"
            1
            (length
                (Interface.moduleSyntaxDirectInputs
                    (interface root)))
        case Parse.parsedModuleBlocks root of
            [block] ->
                assertAxiomLeftShape
                    "imported left associativity"
                    "star(star(a,b),c)"
                    block
            blocks ->
                assertFailure
                    ("expected one imported-syntax axiom, got "
                        <> show blocks)
        writeFile
            (temp Posix.</> "left.tex")
            ("\\import{base.tex}\n"
                <> syntaxFunctionDefinition
                    "star"
                    "star"
                    (Just "%! infixl 3"))
        reuseGraph <- buildSearchedGraph temp "left.tex"
        reuseResult <-
            Parse.parseResolvedSourceGraph reuseGraph
        case reuseResult of
            Left
                (Parse.SourceSyntaxDeclarationError
                    _source
                    Parse.SyntaxPragmaOnImportedReuse{}) ->
                        pure ()
            Left err ->
                assertFailure
                    ("expected imported-reuse pragma rejection, got "
                        <> show err)
            Right reused ->
                assertFailure
                    ("expected imported-reuse pragma rejection, got "
                        <> show reused)

rejectsUnequalImportedSyntax :: Assertion
rejectsUnequalImportedSyntax =
    forM_ cases \(description, leftDefinition, rightDefinition) ->
        withTemporaryDirectory
            ("felix-source-imported-collision-" <> description)
            \temp -> do
                writeFile
                    (temp Posix.</> "a.tex")
                    leftDefinition
                writeFile
                    (temp Posix.</> "b.tex")
                    rightDefinition
                writeTheory
                    (temp Posix.</> "entry.tex")
                    ["a.tex", "b.tex"]
                    "entry"
                graph <- buildSearchedGraph temp "entry.tex"
                collision <- expectLexiconCollision
                    =<< Parse.parseResolvedSourceGraph graph
                (firstLocation, secondLocation) <-
                    expectTwoCollisionLocations collision
                assertLocation
                    "first imported declaration"
                    "a.tex"
                    1
                    firstLocation
                assertLocation
                    "second imported declaration"
                    "b.tex"
                    1
                    secondLocation
  where
    cases =
        [ ( "marker"
          , syntaxFunctionDefinition
                "clash_left"
                "clash"
                (Just "%! infixl 2")
          , syntaxFunctionDefinition
                "clash_right"
                "clash"
                (Just "%! infixl 2")
          )
        , ( "fixity"
          , syntaxFunctionDefinition
                "clash"
                "clash"
                (Just "%! infixl 2")
          , syntaxFunctionDefinition
                "clash"
                "clash"
                (Just "%! infixr 2")
          )
        ]

distinguishesPhysicalSourceLocations :: Assertion
distinguishesPhysicalSourceLocations =
    withTemporaryDirectory "felix-source-location-identity" \temp -> do
        let projectRoot = temp Posix.</> "project"
            libraryRoot = temp Posix.</> "library"
            projectEntry = projectRoot Posix.</> "entry.tex"
            libraryEntry = libraryRoot Posix.</> "entry.tex"
        Directory.createDirectory projectRoot
        Directory.createDirectory libraryRoot
        writeFile projectEntry
            ("\\import{entry.tex}\n"
                <> adjectiveDefinition "project_adjective")
        writeNounDefinition libraryEntry "library_noun"
        mounts <- expectRight =<< prepareSourceMounts
            [ (sourceMountId "library", libraryRoot)
            , (sourceMountId "project", projectRoot)
            ]
        request <- expectRight =<< existingRoot projectEntry
        graph <- expectRight =<< buildResolvedSourceGraph mounts request
        collision <- expectLexiconCollision
            =<< Parse.parseResolvedSourceGraph graph
        assertEqual "normalized cross-category pattern"
            (Raw.TokenCons (Raw.Word "special") Raw.End)
            (Parse.lexiconCollisionPattern collision)
        (libraryLocation, projectLocation) <-
            expectTwoCollisionLocations collision
        assertEqual "accepted display path"
            "entry.tex"
            (locFile libraryLocation)
        assertEqual "accepted declaration line"
            1
            (locLine libraryLocation)
        assertEqual "colliding display path"
            "entry.tex"
            (locFile projectLocation)
        assertEqual "colliding declaration line"
            2
            (locLine projectLocation)
        canonicalProject <- Directory.canonicalizePath projectEntry
        canonicalLibrary <- Directory.canonicalizePath libraryEntry
        let rendered = show collision
            quotedLibrary = show canonicalLibrary
            quotedProject = show canonicalProject
        assertBool "rendered error includes accepted canonical path"
            (quotedLibrary `List.isInfixOf` rendered)
        assertBool "rendered error includes colliding canonical path"
            (quotedProject `List.isInfixOf` rendered)
        assertBool "canonical locations render in declaration order"
            (substringIndex quotedLibrary rendered
                < substringIndex quotedProject rendered)

retainsWorkspaceLocationDisplayPath :: Assertion
retainsWorkspaceLocationDisplayPath =
    withTemporaryDirectory "felix-source-location-display" \temp -> do
        let nested = temp Posix.</> "nested"
            entry = nested Posix.</> "entry.tex"
        Directory.createDirectory nested
        writeTheory entry [] "entry"
        outerMounts <- oneMount "project" temp
        outerRequest <- expectRight (searchedRoot "nested/entry.tex")
        outerGraph <- expectRight =<<
            buildResolvedSourceGraph outerMounts outerRequest
        outerWorkspace <- expectRight =<<
            Parse.parseResolvedSourceGraph outerGraph
        innerMounts <- oneMount "library" nested
        innerRequest <- expectRight (searchedRoot "entry.tex")
        innerGraph <- expectRight =<<
            buildResolvedSourceGraph innerMounts innerRequest
        innerWorkspace <- expectRight =<<
            Parse.parseResolvedSourceGraph innerGraph
        let outerLocation =
                onlyAxiomLocation
                    (Parse.parsedWorkspaceRootModule outerWorkspace)
            innerLocation =
                onlyAxiomLocation
                    (Parse.parsedWorkspaceRootModule innerWorkspace)
        assertEqual "outer-mount display path"
            "nested/entry.tex"
            (locFile outerLocation)
        assertEqual "more-specific-mount display path"
            "entry.tex"
            (locFile innerLocation)
        outerFileId <- expectJust "outer workspace file id"
            (locFileId outerLocation)
        innerFileId <- expectJust "inner workspace file id"
            (locFileId innerLocation)
        assertBool "distinct display registrations use distinct file ids"
            (outerFileId /= innerFileId)
        canonicalEntry <- Directory.canonicalizePath entry
        assertEqual "outer physical location key"
            (Just canonicalEntry)
            (lookupFileIdentityPath outerFileId)
        assertEqual "inner physical location key"
            (Just canonicalEntry)
            (lookupFileIdentityPath innerFileId)

reportsImportedScannerErrorFirst :: Assertion
reportsImportedScannerErrorFirst =
    withTemporaryDirectory "felix-source-lexer-error-order" \temp -> do
        let scannerFailure = unlines
                [ "\\begin{abbreviation}\\label{malformed_function}"
                , "  $x = \\emptyset$."
                , "\\end{abbreviation}"
                ]
            tokenizerFailure = unlines
                [ "\\begin{axiom}"
                , "#"
                , "\\end{axiom}"
                ]
        writeFile
            (temp Posix.</> "imported.tex")
            scannerFailure
        writeFile
            (temp Posix.</> "entry.tex")
            ("\\import{imported.tex}\n" <> tokenizerFailure)
        graph <- buildSearchedGraph temp "entry.tex"
        result <- Parse.parseResolvedSourceGraph graph
        case result of
            Left
                (Parse.SourceParseError
                    source
                    (Parse.LexicalScanFailure
                        Adapt.InvalidFunctionPattern{})) ->
                            assertEqual
                                "dependency scanner error"
                                "imported.tex"
                                (safeRelativePathFilePath
                                    (resolvedSourceRelativePath source))
            Left err ->
                assertFailure
                    ("expected imported scanner error, got " <> show err)
            Right workspace ->
                assertFailure
                    ("expected imported scanner error, got "
                        <> show workspace)

reportsMalformedLexicalDeclaration :: Assertion
reportsMalformedLexicalDeclaration =
    withTemporaryDirectory "felix-source-malformed-lexical" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{abbreviation}\\label{malformed_function}"
                , "  $x = \\emptyset$."
                , "\\end{abbreviation}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        result <- Parse.parseResolvedSourceGraph graph
        void (evaluate (length (show result)))
        case result of
            Left
                (Parse.SourceParseError
                    source
                    (Parse.LexicalScanFailure
                        (Adapt.InvalidFunctionPattern
                            location
                            Adapt.FunctionPatternBareVariable))) -> do
                                assertEqual "malformed source"
                                    "entry.tex"
                                    (safeRelativePathFilePath
                                        (resolvedSourceRelativePath source))
                                assertLocation
                                    "malformed declaration"
                                    "entry.tex"
                                    1
                                    location
            Left err ->
                assertFailure
                    ("expected typed lexical scan failure, got " <> show err)
            Right workspace ->
                assertFailure
                    ("expected typed lexical scan failure, got "
                        <> show workspace)

rejectsMalformedInductivePattern :: Assertion
rejectsMalformedInductivePattern =
    case runLexer (FileId 0) "inductive.tex" source of
        Left err ->
            assertFailure ("could not tokenize fixture: " <> show err)
        Right (_imports, [chunk]) ->
            case Adapt.scanChunk chunk of
                Left
                    (Adapt.InvalidFunctionPattern
                        _location
                        Adapt.FunctionPatternBareVariable) ->
                            pure ()
                Left err ->
                    assertFailure
                        ("expected bare-variable scan failure, got "
                            <> show err)
                Right scans ->
                    assertFailure
                        ("expected bare-variable scan failure, got "
                            <> show scans)
        Right (_imports, chunks) ->
            assertFailure
                ("expected one lexical chunk, got " <> show (length chunks))
  where
    source =
        Text.pack
            (unlines
            [ "\\begin{inductive}\\label{malformed_inductive}"
            , "  Define $x\\subseteq\\pow{x}$ inductively."
            , "\\end{inductive}"
            ])

acceptsAdjectiveSignature :: Assertion
acceptsAdjectiveSignature =
    withTemporaryDirectory "felix-source-signature-adjective" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{signature}\\label{reflexive_signature}"
                , "  Suppose $A$ is a set."
                , "  Then $x$ can be reflexive."
                , "\\end{signature}"
                , "\\begin{axiom}\\label{reflexive_use}"
                , "  $x$ is reflexive."
                , "\\end{axiom}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        let blocks = Parse.importedBeforeImporterBlocks workspace
        case blocks of
            [ Raw.BlockSig
                    _signatureLocation
                    _signatureTitle
                    _signatureMarker
                    [_signatureAssumption]
                    (Raw.SignatureAdj
                        _variable
                        (Raw.Adj _adjectiveLocation declaredAdjective []))
              , Raw.BlockAxiom{}
              ] -> do
                    assertEqual
                        "signature marker enters the lexicon"
                        "reflexive_signature"
                        (Raw.lexicalItemMarker declaredAdjective)
            _ ->
                assertFailure
                    ("unexpected adjective-signature blocks: " <> show blocks)

rejectsMalformedSignatureHead :: Assertion
rejectsMalformedSignatureHead = do
    case runLexer
        (FileId 49)
        "malformed-signature.tex"
        (Text.unlines
            [ "\\begin{signature}\\label{bad_signature}"
            , "  $x$ can be."
            , "\\end{signature}"
            ]) of
        Left err ->
            assertFailure ("unexpected token error: " <> show err)
        Right (_imports, [chunk]) ->
            case Adapt.scanChunk chunk of
                Left
                    (Adapt.InvalidFunctionPattern
                        location
                        Adapt.FunctionPatternBareVariable) -> do
                            assertEqual "error line" 1 (locLine location)
                            assertEqual "error column" 1 (locColumn location)
                Left err ->
                    assertFailure
                        ("expected malformed signature error, got " <> show err)
                Right scans ->
                    assertFailure
                        ("expected malformed signature rejection, got "
                            <> show scans)
        Right (_imports, chunks) ->
            assertFailure
                ("expected one malformed signature chunk, got "
                    <> show (length chunks))

reportsSameSourceLexiconCollision :: Assertion
reportsSameSourceLexiconCollision =
    withTemporaryDirectory "felix-source-local-lexicon-collision" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{struct}\\label{duplicate_operations}"
                , "  A \\duplicateop $X$ is equipped with"
                , "  \\begin{enumerate}"
                , "    \\item $\\duplicateop$"
                , "  \\end{enumerate}"
                , "\\end{struct}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        collision <- expectLexiconCollision
            =<< Parse.parseResolvedSourceGraph graph
        (firstLocation, secondLocation) <-
            expectTwoCollisionLocations collision
        assertEqual "first declaration file"
            "entry.tex"
            (locFile firstLocation)
        assertEqual "first declaration line" 1 (locLine firstLocation)
        assertEqual "colliding declaration file"
            "entry.tex"
            (locFile secondLocation)
        assertEqual "colliding declaration line" 4 (locLine secondLocation)
        assertBool "declarations have distinct locations"
            (firstLocation /= secondLocation)

acceptsBuiltinSourceDeclaration :: Assertion
acceptsBuiltinSourceDeclaration =
    withTemporaryDirectory "felix-source-builtin-declaration" \temp -> do
        writeBuiltinZeroDefinition
            (temp Posix.</> "entry.tex")
            "source_zero"
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        let root =
                Parse.parsedWorkspaceRootModule workspace
        assertEqual
            "fixed reuse emits no local syntax"
            []
            (Interface.canonicalSyntaxDeltaEntries
                (Interface.moduleSyntaxLocalDelta
                    (Parse.parsedModuleSyntaxInterface root)))
        case Parse.parsedModuleBlocks root of
            [Raw.BlockAbbr
                    _location
                    _title
                    blockMarker
                    (Raw.AbbreviationEq
                        (Raw.SymbolPattern
                            (Raw.MixfixItem
                                _pattern
                                symbolMarker
                                _associativity)
                            [])
                        _expression)] -> do
                assertEqual
                    "declaration label remains independent"
                    "source_zero"
                    blockMarker
                assertEqual
                    "built-in marker remains authoritative"
                    "zero"
                    symbolMarker
                case Parse.parsedModuleSyntaxOccurrences root of
                    [occurrence] ->
                        case Parse.parsedSyntaxOccurrenceEntry occurrence of
                            Interface.CanonicalExpressionFunction
                                    _pattern
                                    occurrenceMarker
                                    _fixity -> do
                                        assertEqual
                                            "occurrence retains source marker"
                                            "source_zero"
                                            (Parse.parsedSyntaxOccurrenceMarker
                                                occurrence)
                                        assertEqual
                                            "occurrence uses fixed marker"
                                            "zero"
                                            occurrenceMarker
                                        fileId <- expectJust
                                            "fixed occurrence file id"
                                            (locFileId
                                                (Parse.parsedSyntaxOccurrenceLocation
                                                    occurrence))
                                        decoded <- expectRight
                                            (Parsed.decodeCanonicalParsedPayload
                                                fileId
                                                (Parse.parsedModulePayload root))
                                        case Parsed.decodedParsedOccurrences decoded of
                                            [ ( _blockIndex
                                              , _location
                                              , storedMarker
                                              , Interface.CanonicalExpressionFunction
                                                    _storedPattern
                                                    storedEntryMarker
                                                    _storedFixity
                                              )
                                              ] -> do
                                                    assertEqual
                                                        "payload source marker"
                                                        "source_zero"
                                                        storedMarker
                                                    assertEqual
                                                        "payload authoritative marker"
                                                        "zero"
                                                        storedEntryMarker
                                            stored ->
                                                assertFailure
                                                    ("unexpected decoded fixed occurrence: "
                                                        <> show stored)
                            entry ->
                                assertFailure
                                    ("unexpected fixed occurrence: "
                                        <> show entry)
                    occurrences ->
                        assertFailure
                            ("unexpected fixed occurrences: "
                                <> show occurrences)
            blocks ->
                assertFailure
                    ("unexpected built-in declaration parse: "
                        <> show blocks)

acceptsBuiltinPrefixPredicateDeclaration :: Assertion
acceptsBuiltinPrefixPredicateDeclaration =
    withTemporaryDirectory "felix-source-builtin-prefix" \temp -> do
        writeBuiltinCongDefinition
            (temp Posix.</> "entry.tex")
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        case Parse.parsedModuleBlocks
            (Parse.parsedWorkspaceRootModule workspace) of
                [Raw.BlockDefn
                    _location
                    _title
                    _blockMarker
                    (Raw.Defn
                        _assumptions
                        (Raw.DefnSymbolicPredicate
                            predicate
                            predicateMarker
                            _variables)
                        _statement)] -> do
                            assertEqual "built-in prefix predicate"
                                (Raw.PrefixPredicate "Cong" 4)
                                predicate
                            assertEqual
                                "built-in prefix marker remains authoritative"
                                "cong"
                                predicateMarker
                blocks ->
                    assertFailure
                        ("unexpected built-in prefix declaration parse: "
                            <> show blocks)

avoidsAliasImportLexiconCollision :: Assertion
avoidsAliasImportLexiconCollision =
    withTemporaryDirectory "felix-source-alias-lexicon" \temp -> do
        let shared = temp Posix.</> "shared.tex"
            alias = temp Posix.</> "alias.tex"
        writeAdjectiveDefinition shared "shared_special"
        Directory.createFileLink shared alias
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\import{shared.tex}"
                , "\\import{shared.tex}"
                , "\\import{alias.tex}"
                , "\\begin{axiom}\\label{root}"
                , "  $x$ is special."
                , "\\end{axiom}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        assertEqual "canonical source is parsed once"
            ["shared.tex", "entry.tex"]
            (toList
                ( safeRelativePathFilePath
                    . resolvedSourceRelativePath
                    . Parse.parsedModuleResolved
                    <$> Parse.parsedWorkspaceImportedBeforeImporter workspace
                ))

parsesWithoutRereading :: Assertion
parsesWithoutRereading =
    withTemporaryDirectory "felix-source-no-reread" \temp -> do
        let shared = temp Posix.</> "shared.tex"
            entry = temp Posix.</> "entry.tex"
        writeTheory shared [] "shared"
        writeTheory entry ["shared.tex"] "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        Directory.removeFile entry
        Directory.removeFile shared
        firstWorkspace <- expectRight =<< Parse.parseResolvedSourceGraph graph
        secondWorkspace <- expectRight =<< Parse.parseResolvedSourceGraph graph
        assertEqual "first flat projection" 2
            (length (Parse.importedBeforeImporterBlocks firstWorkspace))
        assertEqual "repeated downstream projection" 2
            (length (Parse.importedBeforeImporterBlocks secondWorkspace))

returnsSourceParseFailures :: Assertion
returnsSourceParseFailures =
    withTemporaryDirectory "felix-source-parse-error" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (theoryBlock "accepted"
                <> "\\begin{axiom}\\label{late_failure}\n")
        graph <- buildSearchedGraph temp "entry.tex"
        emittedRef <- newIORef []
        result <-
            Parse.parseResolvedSourceGraphWith graph
                (\_source block ->
                    case block of
                        Raw.BlockAxiom _location _title marker _axiom ->
                            modifyIORef' emittedRef (marker :)
                        _ ->
                            assertFailure
                                ("unexpected emitted block: " <> show block))
        case result of
            Left (Parse.SourceParseError source _err) -> do
                assertEqual "failed source" "entry.tex"
                    (safeRelativePathFilePath
                        (resolvedSourceRelativePath source))
                emitted <- reverse <$> readIORef emittedRef
                assertEqual "completed callbacks before later failure"
                    ["accepted"]
                    emitted
            Left err ->
                assertFailure ("expected SourceParseError, got " <> show err)
            Right workspace ->
                assertFailure ("expected parse failure, got " <> show workspace)

buildSearchedGraph :: FilePath -> FilePath -> IO ResolvedSourceGraph
buildSearchedGraph root path = do
    mounts <- oneMount "project" root
    request <- expectRight (searchedRoot path)
    expectRight =<< buildResolvedSourceGraph mounts request

sourceGraphOrderPaths :: ResolvedSourceGraph -> IO [FilePath]
sourceGraphOrderPaths graph =
    pure
        [ safeRelativePathFilePath
            (resolvedSourceRelativePath (sourceNodeResolved node))
        | node <- toList (sourceGraphImportedBeforeImporter graph)
        ]

sourceNodeCanonicalPathForTest :: SourceNode -> CanonicalPath
sourceNodeCanonicalPathForTest =
    resolvedSourceCanonicalPath . sourceNodeResolved

onlyAxiomLocation :: Parse.ParsedModule -> Location
onlyAxiomLocation node =
    case Parse.parsedModuleBlocks node of
        [Raw.BlockAxiom location _title _marker _axiom] ->
            location
        blocks ->
            error ("expected one axiom block, got " <> show blocks)

syntaxFunctionDefinition
    :: String
    -> String
    -> Maybe String
    -> String
syntaxFunctionDefinition marker command pragma =
    unlines
        ( [ "\\begin{abbreviation}\\label{" <> marker <> "}"
          ]
          <> maybe [] (\line -> ["  " <> line]) pragma
          <> [ "  $x\\" <> command <> " y = x$."
             , "\\end{abbreviation}"
             ]
        )

axiomBlock :: String -> String -> String
axiomBlock marker statement =
    unlines
        [ "\\begin{axiom}\\label{" <> marker <> "}"
        , "  $" <> statement <> "$."
        , "\\end{axiom}"
        ]

assertExpressionFixity
    :: Text
    -> Raw.Associativity
    -> Word8
    -> [Interface.CanonicalLexicalEntry]
    -> Assertion
assertExpressionFixity marker associativity level entries =
    case
        [ fixity
        | Interface.CanonicalExpressionFunction
                _pattern
                (Raw.Marker candidate)
                fixity <-
            entries
        , candidate == marker
        ] of
        [Interface.Fixity actualAssociativity actualLevel] -> do
            assertEqual
                (Text.unpack marker <> " associativity")
                associativity
                actualAssociativity
            assertEqual
                (Text.unpack marker <> " level")
                level
                (Interface.mixfixLevelValue actualLevel)
        actual ->
            assertFailure
                ("expected one fixity for "
                    <> Text.unpack marker
                    <> ", got "
                    <> show actual)

assertAxiomLeftShape
    :: String
    -> String
    -> Raw.Block
    -> Assertion
assertAxiomLeftShape description expected block =
    case block of
        Raw.BlockAxiom
            _location
            _title
            _marker
            (Raw.Axiom
                _assumptions
                (Raw.StmtFormula
                    (Raw.FormulaChain
                        (Raw.ChainBase
                            (expression :| [])
                            _sign
                            _relation
                            _right)))) ->
                                assertEqual
                                    description
                                    expected
                                    (expressionShape expression)
        _ ->
            assertFailure
                ("expected an axiom with one left expression, got "
                    <> show block)

expressionShape :: Raw.Expr -> String
expressionShape = \case
    Raw.ExprVar (Raw.NamedVarAt _location name) ->
        Text.unpack name
    Raw.ExprOp
            _location
            symbol
            arguments ->
        let Raw.Marker marker =
                Raw.mixfixMarker symbol
        in
            Text.unpack marker
                <> "("
                <> List.intercalate ","
                    (expressionShape <$> arguments)
                <> ")"
    expression ->
        show expression

findParsedModule
    :: FilePath
    -> Parse.ParsedSourceWorkspace
    -> IO Parse.ParsedModule
findParsedModule relative workspace =
    case List.find hasPath
            (Parse.parsedWorkspaceModules workspace) of
        Just parsed ->
            pure parsed
        Nothing ->
            assertFailure
                ("could not find parsed module " <> relative)
  where
    hasPath parsed =
        safeRelativePathFilePath
            (resolvedSourceRelativePath
                (Parse.parsedModuleResolved parsed))
            == relative

writeAdjectiveDefinition :: FilePath -> String -> IO ()
writeAdjectiveDefinition path marker =
    writeFile path (adjectiveDefinition marker)

adjectiveDefinition :: String -> String
adjectiveDefinition marker =
    unlines
        [ "\\begin{definition}\\label{" <> marker <> "}"
        , "  $x$ is special iff $x = x$."
        , "\\end{definition}"
        ]

writeNounDefinition :: FilePath -> String -> IO ()
writeNounDefinition path marker =
    writeFile path
        (unlines
            [ "\\begin{definition}\\label{" <> marker <> "}"
            , "  $x$ is a special iff $x = x$."
            , "\\end{definition}"
            ])

writeBuiltinZeroDefinition :: FilePath -> String -> IO ()
writeBuiltinZeroDefinition path marker =
    writeFile path (builtinZeroDefinition marker)

builtinZeroDefinition :: String -> String
builtinZeroDefinition marker =
    unlines
        [ "\\begin{abbreviation}\\label{" <> marker <> "}"
        , "  $\\zero = \\emptyset$."
        , "\\end{abbreviation}"
        ]

writeBuiltinCongDefinition :: FilePath -> IO ()
writeBuiltinCongDefinition path =
    writeFile path
        (unlines
            [ "\\begin{definition}\\label{source_cong}"
            , "  $\\Cong{x}{y}{z}{w}$ iff $x = x$."
            , "\\end{definition}"
            ])

writeTheory :: FilePath -> [FilePath] -> String -> IO ()
writeTheory path imports label =
    writeFile path
        (unlines
            (["\\import{" <> imported <> "}" | imported <- imports]
                <> [theoryBlock label]))

theoryBlock :: String -> String
theoryBlock label =
    unlines
        [ "\\begin{axiom}\\label{" <> label <> "}"
        , "  $x = x$."
        , "\\end{axiom}"
        ]

oneMount :: Text -> FilePath -> IO SourceMounts
oneMount ident root =
    expectRight =<< prepareSourceMounts [(sourceMountId ident, root)]

withTemporaryDirectory :: String -> (FilePath -> IO a) -> IO a
withTemporaryDirectory template =
    bracket create Directory.removePathForcibly
  where
    create = do
        systemTemp <- Directory.getTemporaryDirectory
        (path, handle) <- openTempFile systemTemp template
        hClose handle
        Directory.removeFile path
        Directory.createDirectory path
        pure path

assertRight :: (Show e, HasCallStack) => Either e a -> Assertion
assertRight = void . expectRight

expectRight :: (Show e, HasCallStack) => Either e a -> IO a
expectRight = \case
    Left err ->
        assertFailure ("expected Right, got Left " <> show err)
    Right value ->
        pure value

expectJust :: HasCallStack => String -> Maybe a -> IO a
expectJust description = \case
    Nothing ->
        assertFailure ("expected " <> description)
    Just value ->
        pure value

expectLexiconCollision
    :: Either Parse.ParseWorkspaceError a
    -> IO Parse.LexiconCollision
expectLexiconCollision = \case
    Left (Parse.SourceLexiconCollision collision) ->
        pure collision
    Left err ->
        assertFailure
            ("expected SourceLexiconCollision, got " <> show err)
    Right _value ->
        assertFailure "expected SourceLexiconCollision, got Right"

expectTwoCollisionLocations
    :: Parse.LexiconCollision
    -> IO (Location, Location)
expectTwoCollisionLocations collision =
    case Parse.lexiconCollisionDeclarations collision of
        firstLocation : secondLocation : _ ->
            pure (firstLocation, secondLocation)
        locations ->
            assertFailure
                ("expected two source collision locations, got "
                    <> show locations)

assertLocation :: String -> FilePath -> Int -> Location -> Assertion
assertLocation description expectedFile expectedLine location = do
    assertEqual (description <> " file")
        expectedFile
        (locFile location)
    assertEqual (description <> " line")
        expectedLine
        (locLine location)
    assertEqual (description <> " column")
        1
        (locColumn location)

substringIndex :: String -> String -> Int
substringIndex needle haystack =
    fromMaybe maxBound
        (List.findIndex
            (List.isPrefixOf needle)
            (List.tails haystack))

assertLeft :: (Eq e, Eq a, Show e, Show a, HasCallStack) => e -> Either e a -> Assertion
assertLeft expected actual =
    assertEqual "expected Left value" (Left expected) actual