summaryrefslogtreecommitdiff
path: root/source/Test/Unit/Source.hs
blob: 862ff879663838a13c6c37687c6ecd4548282ad1 (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
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}

module Test.Unit.Source (unitTests) where

import Base
import Checking qualified
import Checking.Backend.Problem qualified as Backend
import Checking.Backend.Reconstruction qualified as Reconstruction
import Checking.Core qualified as Core
import Checking.Facts qualified as Facts
import Checking.Foundation qualified as Foundation
import Checking.Identity qualified as Identity
import Checking.Kernel.Derivation qualified as Derivation
import Checking.Legacy qualified as Legacy
import Checking.Obligation qualified as Obligation
import Checking.Transition qualified as Transition
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.Source
import Felix.Source.Content qualified as Content
import Felix.Source.Graph
import Felix.Store qualified as Store
import Meaning qualified
import Provers qualified
import Report.Location
    ( FileId(..)
    , FileIdAllocator(..)
    , Location(..)
    , LocationRegistrationError(..)
    , pattern Nowhere
    , 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.Internal
import Syntax.Token (runLexer)

import Bound.Scope (toScope)
import Control.Exception (bracket, evaluate, try)
import Control.Monad (foldM)
import Control.Monad.Logger (runNoLoggingT)
import Data.ByteString qualified as ByteString
import Data.HashMap.Strict qualified as HashMap
import Data.IORef
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Vector qualified as Vector
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 "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 "rejects a corrupted cached declaration anchor"
        rejectsCorruptedCachedDeclarationAnchor
    , testCase "parses source-local blocks in graph order" parsesSourceGraph
    , testCase "assigns and reserves dense legacy module positions"
        reservesLegacyModulePositions
    , testCase "admits complete legacy declaration batches"
        admitsLegacyDeclarations
    , testCase "publishes deterministic legacy import views"
        publishesLegacyImportViews
    , testCase "publishes typed signatures and facts through transition modules"
        publishesTransitionSignatures
    , testCase "rejects cached global types from another builder"
        rejectsForeignCachedGlobalType
    , testCase "authorizes exact typed Vampire requests"
        authorizesTypedVampireRequests
    , testCase "enforces and replays direct inductive guards"
        publishesTypedInductive
    , 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 lexer errors before importer errors"
        reportsImportedLexerErrorFirst
    , testCase "returns malformed lexical declarations as typed errors"
        reportsMalformedLexicalDeclaration
    , testCase "validates inductive function patterns during scanning"
        rejectsMalformedInductivePattern
    , testCase "scans, parses, and checks adjective signatures"
        acceptsAdjectiveSignature
    , testCase "rejects unresolved quantified symbolic-signature terms"
        rejectsQuantifiedSymbolicSignatureTerm
    , 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 "rejects duplicate fixed-base semantics during checking"
        rejectsDuplicateFixedBaseSemantics
    , 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))

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)))))
                assignments <-
                    expectRight
                        (Legacy.assignLegacyModuleOrdinals workspace)
                assignment <-
                    case toList assignments of
                        [only] ->
                            pure only
                        actual ->
                            assertFailure
                                ("expected one empty module assignment, got "
                                    <> show (length actual))
                                >> fail "unreachable"
                checkedFoundationValue <-
                    expectRight Foundation.checkedFoundation
                builder <-
                    expectRight
                        (Transition.openTransitionModuleBuilder
                            checkedFoundationValue
                            Checking.initialLegacyCheckingEnvironment
                            assignment
                            [])
                checked <-
                    Checking.runCheckingBlocks
                        []
                        (Checking.initialTransitionCheckingStateWithTaskPreparation
                                Checking.WithoutDumpPremselTraining
                                id
                                builder
                                (\_batch ->
                                    assertFailure
                                        "empty module emitted an obligation"))
                finalBuilder <-
                    expectJust
                        "empty transition builder"
                        (Checking.checkingTransitionModuleBuilder checked)
                void
                    (expectRight
                        (Transition.sealTransitionModule
                            (Checking.checkingStateEnvironment checked)
                            finalBuilder))

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

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

reservesLegacyModulePositions :: Assertion
reservesLegacyModulePositions =
    withTemporaryDirectory "felix-legacy-module-stage" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["shared.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        assertEqual "dense imported-first module ordinals"
            [0, 1]
            ( Legacy.legacyModuleOrdinalValue
                . Legacy.assignedLegacyModuleOrdinal
                <$> toList assignments
            )
        assertEqual "assigned source order"
            ["shared.tex", "entry.tex"]
            ( safeRelativePathFilePath
                . sourceAddressRelativePath
                . Parse.parsedModuleAddress
                . Legacy.assignedParsedModule
                <$> toList assignments
            )

        let firstAssignment :| _remainingAssignments =
                assignments
            stage =
                Legacy.openLegacyModuleStage
                    firstAssignment
                    (Legacy.emptyLegacyImportedView
                        Checking.initialLegacyCheckingEnvironment)
            origin = Facts.factOrigin (Location 0) "declaration"
            firstFact =
                Facts.stageFact
                    ("first" :| ["first_alias"])
                    origin
                    (Facts.prepareSemanticFact Top)
            secondFact =
                Facts.stageFact
                    ("second" :| [])
                    origin
                    (Facts.prepareSemanticFact Bottom)
        reservation <-
            expectRight
                (Legacy.reserveLegacyDeclaration
                    (firstFact :| [secondFact])
                    stage)
        assertEqual "dense local fact ordinals"
            [0, 1]
            ( Legacy.legacyLocalFactOrdinalValue
                . Legacy.legacyFactLocalOrdinal
                . Legacy.legacyReservedFactReference
                <$> toList (Legacy.legacyReservedFacts reservation)
            )

        let duplicateAliasFact =
                Facts.stageFact
                    ("first_alias" :| [])
                    origin
                    (Facts.prepareSemanticFact Bottom)
        case Legacy.reserveLegacyDeclaration
                (firstFact :| [duplicateAliasFact])
                stage of
            Left Legacy.LegacyAliasAlreadyBound{} ->
                pure ()
            Left err ->
                assertFailure
                    ("expected alias rejection, got " <> show err)
            Right _ ->
                assertFailure "expected duplicate legacy alias rejection"

admitsLegacyDeclarations :: Assertion
admitsLegacyDeclarations =
    withTemporaryDirectory "felix-legacy-admission" \temp -> do
        writeTheory (temp Posix.</> "entry.tex") [] "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignment :| _ <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        let stage =
                Legacy.openLegacyModuleStage
                    assignment
                    (Legacy.emptyLegacyImportedView
                        Checking.initialLegacyCheckingEnvironment)
            blocks =
                [ BlockAxiom
                    Nowhere
                    "declared"
                    (Axiom [] Top)
                , BlockLemma
                    Nowhere
                    "omitted"
                    (Lemma [] Bottom)
                , BlockProof
                    Nowhere
                    Nowhere
                    (Omitted Nowhere)
                ]
            resolveGapBatch batch = do
                resolved <-
                    traverse
                        (either
                            (ioError . userError . show)
                            pure
                            . Obligation.resolveObligationAsGap)
                        (Obligation.preparedBatchObligations batch)
                either
                    (ioError . userError . show)
                    pure
                    (Obligation.resolveObligationBatch
                        batch
                        resolved)
            initial =
                Checking.initialLegacyCheckingStateWithTaskPreparation
                    Checking.WithoutDumpPremselTraining
                    id
                    stage
                    resolveGapBatch
        checked <-
            Checking.runCheckingBlocks blocks initial
        admittedStage <-
            maybe
                (assertFailure
                    "authoritative checking lost the legacy stage"
                    >> pure stage)
                pure
                (Checking.checkingLegacyModuleStage checked)
        admittedModule <-
            expectRight
                (Legacy.sealLegacyModuleStage
                    (Checking.checkingStateEnvironment checked)
                    admittedStage)
        assertEqual "two sealed local facts"
            2
            (Vector.length
                (Legacy.legacyAdmittedLocalFacts admittedModule))
        assertEqual "one sealed declared assumption"
            1
            (Vector.length
                (Legacy.legacyAdmittedDirectAxiomManifest
                    admittedModule))
        let finalTrust =
                Legacy.legacyFactEntryTrustDependencies
                    (Vector.last
                        (Legacy.legacyAdmittedLocalFacts
                            admittedModule))
        assertEqual "one explicit gap"
            1
            (Set.size
                (Legacy.legacyExplicitGaps finalTrust))
        assertEqual "direct gap needs no legacy finalization rule"
            0
            (Set.size
                (Legacy.trustedLegacyRuleUses finalTrust))

publishesTransitionSignatures :: Assertion
publishesTransitionSignatures =
    withTemporaryDirectory "felix-transition-signatures" \temp -> do
        writeTheory (temp Posix.</> "shared.tex") [] "shared"
        writeTheory
            (temp Posix.</> "entry.tex")
            ["shared.tex"]
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        checkedFoundationValue <-
            expectRight Foundation.checkedFoundation
        case toList assignments of
            [sharedAssignment, entryAssignment] -> do
                shared <-
                    admit
                        checkedFoundationValue
                        sharedAssignment
                        []
                        [ BlockSig
                            Nowhere
                            "shared_signature"
                            []
                            (SignaturePredicate
                                sharedPredicate
                                ("x" :| []))
                        , BlockAxiom
                            Nowhere
                            "shared_atomic_axiom"
                            (Axiom [] sharedAtomicFormula)
                        ]
                let sharedGlobals =
                        Transition.transitionAdmittedGlobals
                            shared
                assertEqual
                    "one shared typed declaration"
                    1
                    (Vector.length sharedGlobals)
                case Vector.toList sharedGlobals of
                    [(symbol, reference, _origin)] -> do
                        assertEqual
                            "shared symbol"
                            (SymbolPredicate sharedPredicate)
                            symbol
                        assertEqual
                            "shared declaration ordinal"
                            0
                            (Transition.localDeclarationOrdinalValue
                                (Transition.opaqueDeclarationOrdinal
                                    (Transition.checkedGlobalReference
                                        reference)))
                        assertEqual
                            "shared predicate type"
                            (Core.TySet
                                `Core.TyArrow`
                                    Core.TyProp)
                            (Transition.checkedGlobalType reference)
                    _ ->
                        assertFailure
                            "expected one shared typed declaration"
                let sharedFacts =
                        Vector.toList
                            (Transition.transitionAdmittedFacts
                                shared)
                    sharedManifest =
                        Vector.toList
                            (Transition.transitionAdmittedTypedDirectAxiomManifest
                                shared)
                (sharedReference, sharedStatement) <-
                    case (sharedFacts, sharedManifest) of
                    ([assumption], [manifestEntry]) -> do
                        assertBool
                            "typed axiom is not a kernel proof"
                            (not
                                (Transition.admittedFactIsKernelProof
                                    assumption))
                        assertEqual
                            "manifest kind"
                            Legacy.DeclaredUserAxiom
                            (Transition.typedDirectAssumptionKind
                                manifestEntry)
                        assertEqual
                            "manifest fact reference"
                            (Just
                                (Transition.typedDirectAssumptionFact
                                    manifestEntry))
                            (Transition.transitionTypedFactReference
                                (Transition.admittedFactReference
                                    assumption))
                        pure
                            ( Transition.admittedFactReference
                                assumption
                            , Transition.typedDirectAssumptionStatement
                                manifestEntry
                            )
                    _ ->
                        fail
                            "expected one manifest-backed typed axiom"

                hiddenBuilder <-
                    expectRight
                        (Transition.openTransitionModuleBuilder
                            checkedFoundationValue
                            Checking.initialLegacyCheckingEnvironment
                            entryAssignment
                            [])
                hiddenTarget <-
                    expectRight
                        (Core.checkCanonicalCore
                            (const Nothing)
                            (Core.CImp
                                Core.CFalsum
                                Core.CFalsum))
                hiddenImport <-
                    expectRight
                        (Transition.transitionDerivationImport
                            sharedReference
                            hiddenTarget)
                case Transition.commitTransitionKernelFactWithImports
                        ("hidden_import" :| [])
                        (Transition.origin
                            Nowhere
                            Nothing
                            (Just "hidden_import"))
                        (Vector.singleton hiddenImport)
                        hiddenTarget
                        (Derivation.importedFactDerivation
                            (Derivation.importIx 0))
                        hiddenBuilder of
                    Left
                        (Transition.TransitionKernelImportNotVisible
                            actualReference) ->
                                assertEqual
                                    "unimported fact reference"
                                    sharedReference
                                    actualReference
                    Left err ->
                        assertFailure
                            ("expected hidden typed import failure, got "
                                <> show err)
                    Right _ ->
                        assertFailure
                            "an unimported typed row authorized replay"

                entryBuilder <-
                    expectRight
                        (Transition.openTransitionModuleBuilder
                            checkedFoundationValue
                            Checking.initialLegacyCheckingEnvironment
                            entryAssignment
                            [shared])
                assertBool
                    "direct import exposes the typed global"
                    (isJust
                        (Transition.lookupTransitionGlobal
                            (SymbolPredicate sharedPredicate)
                            entryBuilder))
                entry <-
                    admitWithBuilder
                        entryBuilder
                        [ BlockAxiom
                            Nowhere
                            "legacy_axiom"
                            (Axiom [] Top)
                        , BlockSig
                            Nowhere
                            "entry_signature"
                            []
                            (SignaturePredicate
                                entryPredicate
                                ("z" :| []))
                        , BlockLemma
                            Nowhere
                            "typed_import_reuse"
                            (Lemma [] sharedAtomicFormula)
                        , BlockLemma
                            Nowhere
                            "typed_reflexivity"
                            (Lemma
                                []
                                (Equals
                                    Nowhere
                                    (EmptySet Nowhere)
                                    (EmptySet Nowhere)))
                        ]
                case Vector.toList
                        (Transition.transitionAdmittedGlobals
                            entry) of
                    [(_symbol, reference, _origin)] ->
                        assertEqual
                            "legacy declaration occupies its source ordinal"
                            1
                            (Transition.localDeclarationOrdinalValue
                                (Transition.opaqueDeclarationOrdinal
                                    (Transition.checkedGlobalReference
                                        reference)))
                    _ ->
                        assertFailure
                            "expected one local entry declaration"
                let facts =
                        Vector.toList
                            (Transition.transitionAdmittedFacts
                                entry)
                assertEqual
                    "imported and local rows retain declaration order"
                    [False, False, True, True]
                    (Transition.admittedFactIsKernelProof
                        <$> facts)
                case facts of
                    [_assumption, _legacy, reused, reflexivity] -> do
                        case Transition.transitionTypedFactReference
                                (Transition.admittedFactReference
                                    reused) of
                            Nothing ->
                                assertFailure
                                    "expected a typed fact reference"
                            Just reference ->
                                assertEqual
                                    "first typed fact ordinal"
                                    0
                                    (Transition.localFactOrdinalValue
                                        (Transition.factReferenceOrdinal
                                            reference))
                        case Transition.transitionTypedFactReference
                                (Transition.admittedFactReference
                                    reflexivity) of
                            Nothing ->
                                assertFailure
                                    "expected a typed reflexivity reference"
                            Just reference ->
                                assertEqual
                                    "second typed fact ordinal"
                                    1
                                    (Transition.localFactOrdinalValue
                                        (Transition.factReferenceOrdinal
                                            reference))
                    _ ->
                        assertFailure
                            "expected imported assumption and three local facts"
                let inheritedAssumptions =
                        Set.toList
                            (Transition.typedDeclaredAssumptionUses
                                (Transition.transitionAdmittedTypedTrustDependencies
                                    entry))
                case inheritedAssumptions of
                    [assumption] -> do
                        assertEqual
                            "the importer retains the owner fact"
                            (Transition.transitionTypedFactReference
                                sharedReference)
                            (Just
                                (Transition.sessionTypedAssumptionFact
                                    assumption))
                        assertEqual
                            "the owner assumption ordinal"
                            0
                            (Transition.localAssumptionOrdinalValue
                                (Transition.sessionTypedAssumptionOrdinal
                                    assumption))
                        assertEqual
                            "the imported assumption statement"
                            sharedStatement
                            (Transition.sessionTypedAssumptionStatement
                                assumption)
                    _ ->
                        assertFailure
                            "expected one inherited typed declared assumption"
                assertEqual
                    "two local replayed kernel proofs"
                    2
                    (Transition.transitionAdmittedKernelProofCount
                        entry)
            actual ->
                assertFailure
                    ("expected two module assignments, got "
                        <> show (length actual))
  where
    sharedPredicate =
        PredicateSymbol "typed_shared_predicate"
    entryPredicate =
        PredicateSymbol "typed_entry_predicate"
    sharedAtomicFormula =
        Atomic
            Nowhere
            sharedPredicate
            [EmptySet Nowhere]

    admit checkedFoundationValue assignment imports blocks = do
        builder <-
            expectRight
                (Transition.openTransitionModuleBuilder
                    checkedFoundationValue
                    Checking.initialLegacyCheckingEnvironment
                    assignment
                    imports)
        admitWithBuilder builder blocks

    admitWithBuilder builder blocks = do
        checked <-
            Checking.runCheckingBlocks
                blocks
                (Checking.initialTransitionCheckingStateWithTaskPreparation
                    Checking.WithoutDumpPremselTraining
                    id
                    builder
                    (\_batch ->
                        assertFailure
                            "typed transition emitted an obligation"))
        finalBuilder <-
            maybe
                (assertFailure
                    "checking lost its transition builder")
                pure
                (Checking.checkingTransitionModuleBuilder
                    checked)
        expectRight
            (Transition.sealTransitionModule
                (Checking.checkingStateEnvironment checked)
                finalBuilder)

rejectsForeignCachedGlobalType :: Assertion
rejectsForeignCachedGlobalType =
    withTemporaryDirectory "felix-transition-global-types" \temp -> do
        writeTheory
            (temp Posix.</> "entry.tex")
            []
            "entry"
        graph <-
            buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        assignment <-
            case toList assignments of
                [only] ->
                    pure only
                actual ->
                    assertFailure
                        ("expected one module assignment, got "
                            <> show (length actual))
                        >> fail "unreachable"
        checkedFoundationValue <-
            expectRight Foundation.checkedFoundation
        builderA0 <-
            expectRight
                (Transition.openTransitionModuleBuilder
                    checkedFoundationValue
                    Checking.initialLegacyCheckingEnvironment
                    assignment
                    [])
        builderB0 <-
            expectRight
                (Transition.openTransitionModuleBuilder
                    checkedFoundationValue
                    Checking.initialLegacyCheckingEnvironment
                    assignment
                    [])
        let symbol =
                SymbolPredicate
                    (PredicateSymbol
                        "same_nominal_global")
            declarationOrigin =
                Transition.origin
                    Nowhere
                    Nothing
                    (Just "same_nominal_global")
        builderA <-
            expectRight
                (Transition.commitTransitionOpaqueGlobal
                    symbol
                    Core.TySet
                    declarationOrigin
                    (Transition.beginTransitionDeclaration
                        builderA0))
        builderB <-
            expectRight
                (Transition.commitTransitionOpaqueGlobal
                    symbol
                    Core.TyProp
                    declarationOrigin
                    (Transition.beginTransitionDeclaration
                        builderB0))
        globalA <-
            maybe
                (assertFailure "builder A lost its global"
                    >> fail "unreachable")
                pure
                (Transition.lookupTransitionGlobal
                    symbol
                    builderA)
        globalB <-
            maybe
                (assertFailure "builder B lost its global"
                    >> fail "unreachable")
                pure
                (Transition.lookupTransitionGlobal
                    symbol
                    builderB)
        operand <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    (Core.CGlobal globalA))
        statement <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    (Core.CEq
                        Core.TySet
                        (Core.CGlobal globalA)
                        (Core.CGlobal globalA)))
        case Transition.commitTransitionKernelFact
                ("foreign_global_type" :| [])
                (Transition.origin
                    Nowhere
                    Nothing
                    (Just "foreign_global_type"))
                statement
                (Derivation.equalityReflexivityDerivation
                    operand)
                (Transition.beginTransitionDeclaration
                    builderB) of
            Left
                (Transition.TransitionGlobalReferenceTypeMismatch
                    actual
                    authoritativeType) -> do
                        assertEqual
                            "cached global reference"
                            globalA
                            actual
                        assertEqual
                            "builder B authoritative type"
                            Core.TyProp
                            authoritativeType
            Left err ->
                assertFailure
                    ("expected cached global type rejection, got "
                        <> show err)
            Right _ ->
                assertFailure
                    "builder B admitted builder A's cached type"
        let remappedOperand =
                Core.mapFrozenGlobals
                    (const globalB)
                    operand
            remappedStatement =
                Core.mapFrozenGlobals
                    (const globalB)
                    statement
        case Transition.commitTransitionKernelFact
                ("stale_term_annotation" :| [])
                (Transition.origin
                    Nowhere
                    Nothing
                    (Just "stale_term_annotation"))
                remappedStatement
                (Derivation.equalityReflexivityDerivation
                    remappedOperand)
                (Transition.beginTransitionDeclaration
                    builderB) of
            Left
                (Transition.TransitionCoreCheckError
                    (Core.EqualityOperandTypeMismatch
                        Core.TySet
                        Core.TyProp)) ->
                pure ()
            Left err ->
                assertFailure
                    ("expected fresh builder-relative core check, got "
                        <> show err)
            Right _ ->
                assertFailure
                    "builder B admitted a stale term annotation"

authorizesTypedVampireRequests :: Assertion
authorizesTypedVampireRequests =
    withTemporaryDirectory "felix-typed-vampire" \temp -> do
        let sourcePath =
                temp Posix.</> "entry.tex"
            executablePath =
                temp Posix.</> "vampire"
        writeTheory sourcePath [] "entry"
        graph <-
            buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals
                    workspace)
        assignment <-
            case toList assignments of
                [only] ->
                    pure only
                actual ->
                    assertFailure
                        ("expected one module assignment, got "
                            <> show (length actual))
                        >> fail "unreachable"
        checkedFoundationValue <-
            expectRight Foundation.checkedFoundation
        baseBuilder <-
            expectRight
                (Transition.openTransitionModuleBuilder
                    checkedFoundationValue
                    Checking.initialLegacyCheckingEnvironment
                    assignment
                    [])
        let legacyStage =
                Transition.transitionBuilderLegacyStage
                    baseBuilder
            legacyStaged =
                Facts.stageFact
                    ("legacy_input" :| [])
                    (Facts.factOrigin
                        (Location 0)
                        "legacy_input")
                    (Facts.prepareSemanticFact Top)
        legacyReservation <-
            expectRight
                (Legacy.reserveLegacyDeclaration
                    (legacyStaged :| [])
                    legacyStage)
        let legacyReserved =
                NonEmpty.head
                    (Legacy.legacyReservedFacts
                        legacyReservation)
            legacyAdmitted =
                Legacy.authorizeLegacyDeclaredAssumption
                    legacyStage
                    Legacy.DeclaredUserAxiom
                    legacyReserved
        legacyStage' <-
            expectRight
                (Legacy.appendEstablishedLegacyDeclaration
                    legacyReservation
                    (legacyAdmitted :| [])
                    legacyStage)
        builderWithLegacy <-
            expectRight
                (Transition.transitionBuilderWithLegacyStage
                    legacyStage'
                    baseBuilder)
        target <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    (Core.CImp
                        Core.CFalsum
                        Core.CFalsum))
        claim <-
            expectRight
                (Backend.supportedProposition
                    (Vector.empty
                        :: Vector.Vector
                            (Void, Core.CoreType))
                    (Core.embedClosedCore [] target))
        builderWithFof <-
            expectRight
                (Transition.commitTransitionTypedDeclaredAssumption
                    ("fof_input" :| [])
                    (Transition.origin
                        Nowhere
                        Nothing
                        (Just "fof_input"))
                    Legacy.DeclaredUserAxiom
                    target
                    (Transition.beginTransitionDeclaration
                        builderWithLegacy))
        let higherOrderTarget =
                Core.mapFrozenGlobals
                    absurd
                    (Foundation.foundationAxiomFrozen
                        checkedFoundationValue
                        Foundation.DoubleNegationElim)
        builderWithTh0 <-
            expectRight
                (Transition.commitTransitionTypedDeclaredAssumption
                    ("th0_input" :| [])
                    (Transition.origin
                        Nowhere
                        Nothing
                        (Just "th0_input"))
                    Legacy.DeclaredUserAxiom
                    higherOrderTarget
                    (Transition.beginTransitionDeclaration
                        builderWithFof))
        builder <-
            expectRight
                (Transition.commitTransitionTypedDeclaredAssumption
                    ("second_fof_input" :| [])
                    (Transition.origin
                        Nowhere
                        Nothing
                        (Just "second_fof_input"))
                    Legacy.DeclaredUserAxiom
                    target
                    (Transition.beginTransitionDeclaration
                        builderWithTh0))
        implicitProblem <-
            expectRight
                (Transition.planTransitionTypedProblem
                    builder
                    claim
                    []
                    []
                    Transition.ImplicitFofFacts
                    Backend.FirstOrderLocals)
        let selected =
                Vector.toList
                    (Backend.typedProblemGlobalPremises
                        implicitProblem)
        references <-
            traverse
                ( maybe
                    (assertFailure
                        "implicit planning selected a legacy row"
                        >> fail "unreachable")
                    pure
                    . Transition.transitionTypedFactReference
                    . Backend.typedBackendFactReference
                )
                selected
        assertEqual
            "implicit planning preserves FOF admission order"
            [0, 2]
            ( Transition.localFactOrdinalValue
                . Transition.factReferenceOrdinal
                <$> references
            )
        assertEqual
            "implicit admitted-fact route"
            Backend.RouteFof
            (Backend.typedProblemRoute
                implicitProblem)
        explicitHigherOrder <-
            expectRight
                (Transition.planTransitionTypedProblem
                    builder
                    claim
                    []
                    []
                    (Transition.ExplicitFacts
                        ("th0_input" :| ["th0_input"]))
                    Backend.FirstOrderLocals)
        assertEqual
            "explicit higher-order admitted fact selects TH0"
            Backend.RouteTh0
            (Backend.typedProblemRoute
                explicitHigherOrder)
        assertEqual
            "repeated explicit aliases select one fact"
            1
            (Vector.length
                (Backend.typedProblemGlobalPremises
                    explicitHigherOrder))
        case Transition.planTransitionTypedProblem
                builder
                claim
                []
                []
                (Transition.ExplicitFacts
                    ("legacy_input" :| []))
                Backend.FirstOrderLocals of
            Left
                (Transition.TransitionTypedProblemDependencyNotMigrated
                    reference) ->
                        assertEqual
                            "legacy dependency stays legacy"
                            Nothing
                            (Transition.transitionTypedFactReference
                                reference)
            result' ->
                assertFailure
                    ("expected legacy dependency rejection, got "
                        <> case result' of
                            Left err ->
                                "Left " <> show err
                            Right _problem ->
                                "Right problem")
        problem <-
            expectRight
                (Transition.planTransitionTypedProblem
                    builder
                    claim
                    []
                    [Backend.typedFoundationAuxiliaryInput
                        checkedFoundationValue
                        Foundation.DoubleNegationElim]
                    Transition.NoGlobalFacts
                    Backend.AllLocals)
        prepared <-
            expectRight
                (Provers.prepareTypedProverTask
                    Provers.DirectTask
                    problem)
        mismatched <-
            expectRight
                (Provers.prepareTypedProverTask
                    Provers.IndirectTask
                    problem)
        assertEqual
            "higher-order foundation input selects TH0"
            Provers.VerificationTh0
            (Provers.preparedVerificationDialect
                (Provers.preparedTypedProverRequest
                    prepared))
        writeFile executablePath
            (unlines
                [ "#!/bin/sh"
                , "cat >/dev/null"
                , "printf '%s\\n' '% SZS status Theorem for typed'"
                ])
        permissions <-
            Directory.getPermissions executablePath
        Directory.setPermissions executablePath
            (Directory.setOwnerExecutable
                True
                permissions)
        result <-
            runNoLoggingT
                (Provers.runPreparedTypedProver
                    (Provers.vampire
                        executablePath
                        Provers.defaultTimeLimit
                        Provers.defaultMemoryLimit)
                    prepared)
        accepted <-
            case result of
                Right answer
                    | Just run <-
                        Provers.provedVampireRun answer ->
                            pure run
                _ ->
                    assertFailure
                        ("expected accepted typed Vampire run, got "
                            <> show result)
                        >> fail "unreachable"
        let factOrigin =
                Transition.origin
                    Nowhere
                    Nothing
                    (Just "typed_vampire")
            commit task =
                Transition.commitTransitionTypedVampireFact
                    Reconstruction.defaultReconstructionPolicy
                    ("typed_vampire" :| [])
                    factOrigin
                    target
                    task
                    accepted
                    builder
        case commit mismatched of
            Left Transition.TransitionTypedVampireRequestMismatch ->
                pure ()
            result' ->
                assertFailure
                    ("expected exact-request mismatch, got "
                        <> showResult result')
        committed <-
            expectRight (commit prepared)
        admitted <-
            expectRight
                (Transition.sealTransitionModule
                    Checking.initialLegacyCheckingEnvironment
                    committed)
        let trust =
                Transition.transitionAdmittedTypedTrustDependencies
                    admitted
        assertEqual
            "one typed trusted Vampire row"
            1
            (Transition.transitionAdmittedTypedTrustedVampireCount
                admitted)
        assertEqual
            "one typed Vampire trust occurrence"
            1
            (Set.size
                (Transition.typedTrustedVampireUses
                    trust))
        assertEqual
            "mandatory lowering assumptions"
            Legacy.mandatoryVampireLoweringAssumptions
            (Transition.typedVampireLoweringUses
                trust)
        assertEqual
            "exact foundation input"
            (Set.singleton
                Foundation.DoubleNegationElim)
            (Transition.typedFoundationUses
                trust)
        let atom argument =
                Core.CApp
                    (Core.CApp
                        (Core.CIntrinsic Core.Member)
                        (Core.CIntrinsic Core.Empty))
                    argument
            atomP =
                atom (Core.CIntrinsic Core.Empty)
            atomQ =
                atom (Core.COpaqueInteger 1)
            atomR =
                atom (Core.COpaqueInteger 2)
            declareTyped alias statement current =
                expectRight
                    (Transition.commitTransitionTypedDeclaredAssumption
                        (alias :| [])
                        (Transition.origin
                            Nowhere
                            Nothing
                            (Just alias))
                        Legacy.DeclaredUserAxiom
                        statement
                        (Transition.beginTransitionDeclaration
                            current))
        premiseP <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    atomP)
        premisePtoQ <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    (Core.CImp atomP atomQ))
        premiseQtoR <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    (Core.CImp atomQ atomR))
        reconstructedTarget <-
            expectRight
                (Core.checkCanonicalCore
                    (Just . Transition.checkedGlobalType)
                    atomR)
        builderWithP <-
            declareTyped
                "horn_p"
                premiseP
                builder
        builderWithPtoQ <-
            declareTyped
                "horn_p_to_q"
                premisePtoQ
                builderWithP
        builderWithHornInputs <-
            declareTyped
                "horn_q_to_r"
                premiseQtoR
                builderWithPtoQ
        reconstructedClaim <-
            expectRight
                (Backend.supportedProposition
                    (Vector.empty
                        :: Vector.Vector
                            (Void, Core.CoreType))
                    (Core.embedClosedCore
                        []
                        reconstructedTarget))
        reconstructedProblem <-
            expectRight
                (Transition.planTransitionTypedProblem
                    builderWithHornInputs
                    reconstructedClaim
                    []
                    []
                    (Transition.ExplicitFacts
                        ("horn_p"
                            :| [ "horn_p_to_q"
                               , "horn_q_to_r"
                               ]))
                    Backend.FirstOrderLocals)
        reconstructedPrepared <-
            expectRight
                (Provers.prepareTypedProverTask
                    Provers.DirectTask
                    reconstructedProblem)
        reconstructedResult <-
            runNoLoggingT
                (Provers.runPreparedTypedProver
                    (Provers.vampire
                        executablePath
                        Provers.defaultTimeLimit
                        Provers.defaultMemoryLimit)
                    reconstructedPrepared)
        reconstructedAccepted <-
            case reconstructedResult of
                Right answer
                    | Just run <-
                        Provers.provedVampireRun answer ->
                            pure run
                _ ->
                    assertFailure
                        ("expected accepted Horn Vampire run, got "
                            <> show reconstructedResult)
                        >> fail "unreachable"
        reconstructedBuilder <-
            expectRight
                (Transition.commitTransitionTypedVampireFact
                    Reconstruction.defaultReconstructionPolicy
                    ("horn_result" :| [])
                    (Transition.origin
                        Nowhere
                        Nothing
                        (Just "horn_result"))
                    reconstructedTarget
                    reconstructedPrepared
                    reconstructedAccepted
                    builderWithHornInputs)
        reconstructedModule <-
            expectRight
                (Transition.sealTransitionModule
                    Checking.initialLegacyCheckingEnvironment
                    reconstructedBuilder)
        reconstructedFact <-
            case Vector.unsnoc
                    (Transition.transitionAdmittedFacts
                        reconstructedModule) of
                Just (_earlier, finalFact) ->
                    pure finalFact
                Nothing ->
                    assertFailure
                        "expected a reconstructed admitted fact"
                        >> fail "unreachable"
        assertBool
            "supported accepted task becomes a reconstructed kernel proof"
            (Transition.admittedFactIsReconstructedKernelProof
                reconstructedFact)
        reconstructedTrust <-
            maybe
                (assertFailure
                    "expected typed reconstructed trust")
                pure
                (Transition.admittedFactTypedTrustDependencies
                    reconstructedFact)
        assertEqual
            "reconstruction inherits its three exact assumptions"
            3
            (Set.size
                (Transition.typedDeclaredAssumptionUses
                    reconstructedTrust))
        assertEqual
            "reconstructed run adds no trusted Vampire leaf"
            Set.empty
            (Transition.typedTrustedVampireUses
                reconstructedTrust)
        assertEqual
            "reconstructed run adds no Vampire lowering trust"
            Set.empty
            (Transition.typedVampireLoweringUses
                reconstructedTrust)
        tinyKernelLimits <-
            expectRight
                (Derivation.kernelReplayLimits 1 10)
        let tinyKernelPolicy =
                Reconstruction.reconstructionPolicy
                    (Reconstruction.reconstructionPolicyConnectionLimits
                        Reconstruction.defaultReconstructionPolicy)
                    tinyKernelLimits
        fallbackBuilder <-
            expectRight
                (Transition.commitTransitionTypedVampireFact
                    tinyKernelPolicy
                    ("horn_fallback" :| [])
                    (Transition.origin
                        Nowhere
                        Nothing
                        (Just "horn_fallback"))
                    reconstructedTarget
                    reconstructedPrepared
                    reconstructedAccepted
                    builderWithHornInputs)
        fallbackModule <-
            expectRight
                (Transition.sealTransitionModule
                    Checking.initialLegacyCheckingEnvironment
                    fallbackBuilder)
        fallbackFact <-
            case Vector.unsnoc
                    (Transition.transitionAdmittedFacts
                        fallbackModule) of
                Just (_earlier, finalFact) ->
                    pure finalFact
                Nothing ->
                    assertFailure
                        "expected a kernel-exhaustion fallback fact"
                        >> fail "unreachable"
        assertBool
            "kernel exhaustion retains accepted Vampire authority"
            (Transition.admittedFactIsTrustedVampire
                fallbackFact)
  where
    showResult = \case
        Left err ->
            "Left " <> show err
        Right _builder ->
            "Right builder"

publishesTypedInductive :: Assertion
publishesTypedInductive =
    withTemporaryDirectory "felix-transition-inductive" \temp -> do
        writeTheory
            (temp Posix.</> "entry.tex")
            []
            "entry"
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals
                    workspace)
        assignment <-
            case toList assignments of
                [only] ->
                    pure only
                actual ->
                    assertFailure
                        ("expected one module assignment, got "
                            <> show (length actual))
                        >> fail "unreachable"
        checkedFoundationValue <-
            expectRight Foundation.checkedFoundation
        builder <-
            expectRight
                (Transition.openTransitionModuleBuilder
                    checkedFoundationValue
                    Checking.initialLegacyCheckingEnvironment
                    assignment
                    [])
        let unprovedCarrier =
                TermOp Nowhere unprovedInductiveSymbol []
            unprovedBlocks =
                [ BlockInductive
                    Nowhere
                    "unproved_inductive"
                    Inductive
                        { inductiveSymbol =
                            unprovedInductiveSymbol
                        , inductiveParams = []
                        , inductiveDomain =
                            EmptySet Nowhere
                        , inductiveIntros =
                            IntroRule
                                []
                                ( EmptySet Nowhere
                                    `isElementOf`
                                        unprovedCarrier
                                )
                                :| []
                        }
                ]
        unproved <-
            try
                (Checking.runCheckingBlocks
                    unprovedBlocks
                    (Checking.initialTransitionCheckingStateWithTaskPreparation
                        Checking.WithoutDumpPremselTraining
                        id
                        builder
                        (\_batch ->
                            assertFailure
                                "unproved inductive emitted a legacy obligation")))
                :: IO
                    (Either
                        Checking.CheckingError
                        Checking.CheckingState)
        case unproved of
            Left checkingError ->
                assertBool
                    "missing exact guard is reported"
                    ("has no authorized typed fact"
                        `Text.isInfixOf`
                            Text.pack (show checkingError))
            Right _checked ->
                assertFailure
                    "inductive with an unproved domain guard was admitted"
        unchanged <-
            expectRight
                (Transition.sealTransitionModule
                    Checking.initialLegacyCheckingEnvironment
                    builder)
        assertEqual
            "failed inductive publishes no global"
            0
            (Vector.length
                (Transition.transitionAdmittedGlobals
                    unchanged))
        assertEqual
            "failed inductive publishes no fact"
            0
            (Vector.length
                (Transition.transitionAdmittedFacts
                    unchanged))
        let parameter =
                NamedVar "domain"
            domain =
                TermOp
                    Nowhere
                    cumulSymbol
                    [TermVar parameter]
            carrier =
                TermOp
                    Nowhere
                    typedInductiveSymbol
                    [TermVar parameter]
            blocks =
                [ BlockInductive
                    Nowhere
                    "typed_inductive"
                    Inductive
                        { inductiveSymbol =
                            typedInductiveSymbol
                        , inductiveParams = [parameter]
                        , inductiveDomain = domain
                        , inductiveIntros =
                            IntroRule
                                []
                                (TermVar parameter
                                    `isElementOf`
                                        carrier)
                                :| []
                        }
                ]
        checked <-
            Checking.runCheckingBlocks
                blocks
                (Checking.initialTransitionCheckingStateWithTaskPreparation
                    Checking.WithoutDumpPremselTraining
                    id
                    builder
                    (\_batch ->
                        assertFailure
                            "typed inductive emitted a legacy obligation"))
        finalBuilder <-
            maybe
                (assertFailure
                    "checking lost its transition builder"
                    >> fail "unreachable")
                pure
                (Checking.checkingTransitionModuleBuilder
                    checked)
        admitted <-
            expectRight
                (Transition.sealTransitionModule
                    (Checking.checkingStateEnvironment
                        checked)
                    finalBuilder)
        assertEqual
            "one transparent carrier"
            1
            (Vector.length
                (Transition.transitionAdmittedGlobals
                    admitted))
        assertEqual
            "four derived facts"
            [True, True, True, True]
            ( Transition.admittedFactIsKernelProof
                <$> Vector.toList
                    (Transition.transitionAdmittedFacts
                        admitted)
            )
        assertEqual
            "four replayed inductive facts"
            4
            (Transition.transitionAdmittedKernelProofCount
                admitted)
        assertBool
            "foundation guard dependency is retained"
            (Foundation.UnivOfContains
                `Set.member`
                    Transition.typedFoundationUses
                        (Transition.transitionAdmittedTypedTrustDependencies
                            admitted))
  where
    typedInductiveSymbol =
        mkMixfixItem
            [ Just (Command "typedfin")
            , Just InvisibleBraceL
            , Nothing
            , Just InvisibleBraceR
            ]
            "typed_inductive"
            NonAssoc

    cumulSymbol =
        mkMixfixItem
            [ Just (Command "cumul")
            , Just InvisibleBraceL
            , Nothing
            , Just InvisibleBraceR
            ]
            "cumul"
            NonAssoc

    unprovedInductiveSymbol =
        mkMixfixItem
            [Just (Command "unprovedfin")]
            "unproved_inductive"
            NonAssoc

publishesLegacyImportViews :: Assertion
publishesLegacyImportViews =
    withTemporaryDirectory "felix-legacy-import-view" \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"
        workspace <-
            expectRight
                =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        case toList assignments of
            [ sharedAssignment
                , aAssignment
                , bAssignment
                , entryAssignment
                ] -> do
                    shared <-
                        admitOne
                            sharedAssignment
                            (Legacy.emptyLegacyImportedView
                                Checking.initialLegacyCheckingEnvironment)
                            "shared_fact"
                            Bottom
                            (Location 1)
                    sharedView <-
                        expectRight
                            (Legacy.legacyImportedView
                                Checking.initialLegacyCheckingEnvironment
                                [shared])
                    a <-
                        admitOne
                            aAssignment
                            sharedView
                            "a_fact"
                            Top
                            (Location 2)
                    b <-
                        admitOne
                            bAssignment
                            sharedView
                            "b_fact"
                            Top
                            (Location 3)
                    diamondView <-
                        expectRight
                            (Legacy.legacyImportedView
                                Checking.initialLegacyCheckingEnvironment
                                [a, b])
                    entry <-
                        expectRight
                            (Legacy.sealLegacyModuleStage
                                (Legacy.legacyImportedCheckingEnvironment
                                    diamondView)
                                (Legacy.openLegacyModuleStage
                                    entryAssignment
                                    diamondView))
                    assertEqual
                        "direct imports retain textual order"
                        [1, 2]
                        ( Legacy.legacyModuleOrdinalValue
                            <$> Vector.toList
                                (Legacy.legacyAdmittedDirectImports
                                    entry)
                        )
                    assertEqual
                        "diamond facts retain imported source order"
                        [0, 1, 2]
                        ( Legacy.legacyModuleOrdinalValue
                            . Legacy.legacyFactModule
                            . Legacy.legacyFactEntryReference
                            <$> Vector.toList
                                (Legacy.legacyAdmittedVisibleFacts
                                    entry)
                        )
                    assertEqual
                        "equal statements at different references remain"
                        3
                        (Vector.length
                            (Legacy.legacyAdmittedVisibleFacts entry))
                    let environmentSymbol =
                            SymbolMixfix
                                (mkMixfixItem
                                    [Just
                                        (Command
                                            "module_environment")]
                                    "module_environment"
                                    NonAssoc)
                        environmentWith body =
                            Legacy.legacyCheckingEnvironment
                                (HashMap.insert
                                    environmentSymbol
                                    (toScope body)
                                    (Legacy.legacyEnvironmentAbbreviations
                                        Checking.initialLegacyCheckingEnvironment))
                                (Legacy.legacyEnvironmentPredicateDefinitions
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentDependencies
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentOwnedSymbols
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentOwnedSymbolMarkers
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentFrozenSymbols
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentStructs
                                    Checking.initialLegacyCheckingEnvironment)
                                (Legacy.legacyEnvironmentDefinedMarkers
                                    Checking.initialLegacyCheckingEnvironment)
                    environmentA <-
                        admitEnvironment
                            aAssignment
                            (Legacy.emptyLegacyImportedView
                                Checking.initialLegacyCheckingEnvironment)
                            (environmentWith Top)
                    environmentView <-
                        expectRight
                            (Legacy.legacyImportedView
                                Checking.initialLegacyCheckingEnvironment
                                [environmentA])
                    assertEqual
                        "admitted semantic environment is imported"
                        (Just (toScope Top))
                        (HashMap.lookup
                            environmentSymbol
                            (Legacy.legacyEnvironmentAbbreviations
                                (Legacy.legacyImportedCheckingEnvironment
                                    environmentView)))
                    environmentB <-
                        admitEnvironment
                            bAssignment
                            (Legacy.emptyLegacyImportedView
                                Checking.initialLegacyCheckingEnvironment)
                            (environmentWith Bottom)
                    case Legacy.legacyImportedView
                            Checking.initialLegacyCheckingEnvironment
                            [environmentA, environmentB] of
                        Left Legacy.LegacyImportedEnvironmentConflict{} ->
                            pure ()
                        Left err ->
                            assertFailure
                                ("expected imported environment conflict, got "
                                    <> show err)
                        Right _ ->
                            assertFailure
                                "expected imported environment conflict"

                    conflictingA <-
                        admitOne
                            aAssignment
                            (Legacy.emptyLegacyImportedView
                                Checking.initialLegacyCheckingEnvironment)
                            "conflicting"
                            Top
                            (Location 4)
                    conflictingB <-
                        admitOne
                            bAssignment
                            (Legacy.emptyLegacyImportedView
                                Checking.initialLegacyCheckingEnvironment)
                            "conflicting"
                            Bottom
                            (Location 5)
                    case Legacy.legacyImportedView
                            Checking.initialLegacyCheckingEnvironment
                            [conflictingA, conflictingB] of
                        Left Legacy.LegacyImportedAliasConflict{} ->
                            pure ()
                        Left err ->
                            assertFailure
                                ("expected imported alias conflict, got "
                                    <> show err)
                        Right _ ->
                            assertFailure
                                "expected imported alias conflict"
            actual ->
                assertFailure
                    ("expected four module assignments, got "
                        <> show (length actual))
  where
    admitOne assignment imported alias statement location = do
        let stage =
                Legacy.openLegacyModuleStage
                    assignment
                    imported
            staged =
                Facts.stageFact
                    (alias :| [])
                    (Facts.factOrigin location alias)
                    (Facts.prepareSemanticFact statement)
        reservation <-
            expectRight
                (Legacy.reserveLegacyDeclaration
                    (staged :| [])
                    stage)
        let reserved =
                NonEmpty.head
                    (Legacy.legacyReservedFacts reservation)
            admitted =
                Legacy.authorizeLegacyDeclaredAssumption
                    stage
                    Legacy.DeclaredUserAxiom
                    reserved
        stage' <-
            expectRight
                (Legacy.appendEstablishedLegacyDeclaration
                    reservation
                    (admitted :| [])
                    stage)
        expectRight
            (Legacy.sealLegacyModuleStage
                (Legacy.legacyImportedCheckingEnvironment imported)
                stage')

    admitEnvironment assignment imported finalEnvironment =
        expectRight
            (Legacy.sealLegacyModuleStage
                finalEnvironment
                (Legacy.openLegacyModuleStage assignment imported))

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)

reportsImportedLexerErrorFirst :: Assertion
reportsImportedLexerErrorFirst =
    withTemporaryDirectory "felix-source-lexer-error-order" \temp -> do
        let malformedSource = unlines
                [ "\\begin{axiom}"
                , "#"
                , "\\end{axiom}"
                ]
        writeFile
            (temp Posix.</> "imported.tex")
            malformedSource
        writeFile
            (temp Posix.</> "entry.tex")
            ("\\import{imported.tex}\n" <> malformedSource)
        graph <- buildSearchedGraph temp "entry.tex"
        result <- Parse.parseResolvedSourceGraph graph
        case result of
            Left (Parse.SourceParseError source (Parse.TokenError _err)) ->
                assertEqual "first lexer error" "imported.tex"
                    (safeRelativePathFilePath
                        (resolvedSourceRelativePath source))
            Left err ->
                assertFailure ("expected lexer error, got " <> show err)
            Right workspace ->
                assertFailure ("expected lexer 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)
        semanticBlocks <- expectRight (Meaning.meaning blocks)
        void
            (Checking.check
                Checking.WithoutDumpPremselTraining
                semanticBlocks)

rejectsQuantifiedSymbolicSignatureTerm :: Assertion
rejectsQuantifiedSymbolicSignatureTerm =
    withTemporaryDirectory "felix-source-signature-quantified-term" \temp -> do
        writeFile
            (temp Posix.</> "entry.tex")
            (unlines
                [ "\\begin{definition}\\label{bridge}"
                , "  $z$ is a bridge from $A$ to $B$ iff $z = z$ and $A = A$ and $B = B$."
                , "\\end{definition}"
                , "\\begin{signature}\\label{bridge_signature}"
                , "  $\\foo{A}$ is a bridge from every set $x$ to $x$."
                , "\\end{signature}"
                ])
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        case Meaning.meaning
                (Parse.importedBeforeImporterBlocks workspace) of
            Left (Meaning.QuantifiedTermRequiresResolvedContext location) -> do
                assertEqual "quantified term file"
                    "entry.tex"
                    (locFile location)
                assertEqual "quantified term line"
                    5
                    (locLine location)
                assertEqual "quantified term column"
                    30
                    (locColumn location)
            Left err ->
                assertFailure
                    ("expected quantified-term context error, got "
                        <> show err)
            Right blocks ->
                assertFailure
                    ("expected quantified-term context rejection, got "
                        <> 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)

rejectsDuplicateFixedBaseSemantics :: Assertion
rejectsDuplicateFixedBaseSemantics =
    withTemporaryDirectory "felix-source-builtin-collision" \temp -> do
        writeBuiltinZeroDefinition
            (temp Posix.</> "a.tex")
            "source_zero_a"
        writeFile
            (temp Posix.</> "entry.tex")
            ("\\import{a.tex}\n"
                <> builtinZeroDefinition "source_zero_b")
        graph <- buildSearchedGraph temp "entry.tex"
        workspace <- expectRight
            =<< Parse.parseResolvedSourceGraph graph
        assignments <-
            expectRight
                (Legacy.assignLegacyModuleOrdinals workspace)
        case toList assignments of
            [acceptedAssignment, collidingAssignment] -> do
                let acceptedParsed =
                        Legacy.assignedParsedModule acceptedAssignment
                    collidingParsed =
                        Legacy.assignedParsedModule collidingAssignment
                acceptedLocation <-
                    onlySyntaxOccurrenceLocation acceptedParsed
                collidingLocation <-
                    onlySyntaxOccurrenceLocation collidingParsed
                assertLocation
                    "accepted declaration"
                    "a.tex"
                    1
                    acceptedLocation
                assertLocation
                    "colliding declaration"
                    "entry.tex"
                    2
                    collidingLocation
                assertEqual
                    "fixed reuses emit no syntax delta"
                    [[], []]
                    [ Interface.canonicalSyntaxDeltaEntries
                        (Interface.moduleSyntaxLocalDelta
                            (Parse.parsedModuleSyntaxInterface parsed))
                    | parsed <- [acceptedParsed, collidingParsed]
                    ]

                checkedFoundationValue <-
                    expectRight Foundation.checkedFoundation
                (acceptedBlocks, glossState) <-
                    glossParsedBlocks
                        Meaning.initialGlossState
                        acceptedParsed
                acceptedBuilder <-
                    expectRight
                        (Transition.openTransitionModuleBuilder
                            checkedFoundationValue
                            Checking.initialLegacyCheckingEnvironment
                            acceptedAssignment
                            [])
                acceptedState <-
                    Checking.runCheckingBlocks
                        acceptedBlocks
                        (checkingState acceptedBuilder)
                finalAcceptedBuilder <-
                    expectJust
                        "accepted transition builder"
                        (Checking.checkingTransitionModuleBuilder
                            acceptedState)
                acceptedModule <-
                    expectRight
                        (Transition.sealTransitionModule
                            (Checking.checkingStateEnvironment
                                acceptedState)
                            finalAcceptedBuilder)

                (collidingBlocks, _finalGlossState) <-
                    glossParsedBlocks glossState collidingParsed
                collidingBuilder <-
                    expectRight
                        (Transition.openTransitionModuleBuilder
                            checkedFoundationValue
                            Checking.initialLegacyCheckingEnvironment
                            collidingAssignment
                            [acceptedModule])
                result <-
                    try
                        (Checking.runCheckingBlocks
                            collidingBlocks
                            (checkingState collidingBuilder))
                        :: IO
                            (Either
                                Checking.CheckingError
                                Checking.CheckingState)
                case result of
                    Left
                        (Checking.CheckingError
                            message
                            location
                            marker) -> do
                                assertEqual
                                    "semantic collision location"
                                    collidingLocation
                                    location
                                assertEqual
                                    "semantic collision marker"
                                    "source_zero_b"
                                    marker
                                assertBool
                                    "accepted owner is identified"
                                    ("already owned by abbreviation source_zero_a"
                                        `Text.isInfixOf` message)
                    Left err ->
                        assertFailure
                            ("expected located ownership collision, got "
                                <> show err)
                    Right _checked ->
                        assertFailure
                            "duplicate fixed-base semantics were accepted"
            actual ->
                assertFailure
                    ("expected two module assignments, got "
                        <> show (length actual))
  where
    checkingState builder =
        Checking.initialTransitionCheckingStateWithTaskPreparation
            Checking.WithoutDumpPremselTraining
            id
            builder
            (\_batch ->
                assertFailure
                    "fixed-base abbreviation emitted an obligation")

    glossParsedBlocks initialState parsed =
        fmap
            (\(reversed, finalState) ->
                (reverse reversed, finalState))
            (foldM
                glossOne
                ([], initialState)
                (Parse.parsedModuleBlocks parsed))

    glossOne (reversed, state) raw = do
        (block, nextState) <-
            expectRight (Meaning.glossStep state raw)
        pure (block : reversed, nextState)

    onlySyntaxOccurrenceLocation parsed =
        case Parse.parsedModuleSyntaxOccurrences parsed of
            [occurrence] ->
                pure
                    (Parse.parsedSyntaxOccurrenceLocation
                        occurrence)
            occurrences ->
                assertFailure
                    ("expected one fixed-base occurrence, got "
                        <> show occurrences)

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