jon.recoil.org

Source file mode.ml

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
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
(**************************************************************************)
(*                                                                        *)
(*                                 OCaml                                  *)
(*                                                                        *)
(*                    Zesen Qian, Jane Street, London                     *)
(*                                                                        *)
(*   Copyright 2024 Jane Street Group LLC                                 *)
(*                                                                        *)
(*   All rights reserved.  This file is distributed under the terms of    *)
(*   the GNU Lesser General Public License version 2.1, with the          *)
(*   special exception on linking described in the file LICENSE.          *)
(*                                                                        *)
(**************************************************************************)

(* warn on fragile matches *)
[@@@warning "+4"]

open Allowance
open Solver_intf
open Solver
open Mode_intf
module Hint = Mode_hint
module Fmt = Format_doc

module Hint_for_solver (* : Solver_intf.Hint *) = struct
  module Pinpoint = struct
    type t = Hint.pinpoint

    let unknown : t = Location.none, Unknown
  end

  module Morph = struct
    type 'd t = 'd Hint.morph

    let unknown : _ t = Unknown

    let id : _ t = Skip

    let left_adjoint : type l.
        Hint.pinpoint ->
        (l * allowed) t ->
        Hint.pinpoint * (allowed * disallowed) t =
     fun pp t ->
      match t with
      | Skip -> pp, Skip
      | Is_closed_by (Monadic, co) -> co.closure, Close_over (Monadic, co)
      | Is_closed_by (Comonadic, co) -> co.closure, Close_over (Comonadic, co)
      | Captured_by_partial_application ->
        (Location.none, Expression), Adj_captured_by_partial_application
      | Crossing -> pp, Crossing
      | Unknown -> (Location.none, Unknown), Unknown
      | Allocation_r loc -> pp, Allocation_l loc
      | Contains_r (Comonadic, { containing; contained }) ->
        contained, Is_contained_by (Comonadic, { containing; container = pp })
      | Contains_l (Monadic, { containing; contained }) ->
        contained, Is_contained_by (Monadic, { containing; container = pp })
      | Is_contained_by (Comonadic, { containing; container }) ->
        container, Contains_l (Comonadic, { containing; contained = pp })
      | Is_contained_by (Monadic, { containing; container }) ->
        container, Contains_r (Monadic, { containing; contained = pp })

    let right_adjoint : type r.
        Hint.pinpoint ->
        (allowed * r) t ->
        Hint.pinpoint * (disallowed * allowed) t =
     fun pp t ->
      match t with
      | Skip -> pp, Skip
      | Close_over (Monadic, co) -> co.closed, Is_closed_by (Monadic, co)
      | Close_over (Comonadic, co) -> co.closed, Is_closed_by (Comonadic, co)
      | Adj_captured_by_partial_application ->
        (Location.none, Expression), Captured_by_partial_application
      | Crossing -> pp, Crossing
      | Unknown -> (Location.none, Unknown), Unknown
      | Allocation_l loc -> pp, Allocation_r loc
      | Contains_l (Comonadic, { containing; contained }) ->
        contained, Is_contained_by (Comonadic, { containing; container = pp })
      | Contains_r (Monadic, { containing; contained }) ->
        contained, Is_contained_by (Monadic, { containing; container = pp })
      | Is_contained_by (Comonadic, { containing; container }) ->
        container, Contains_r (Comonadic, { containing; contained = pp })
      | Is_contained_by (Monadic, { containing; container }) ->
        container, Contains_l (Monadic, { containing; contained = pp })

    include Magic_allow_disallow (struct
      type (_, _, 'd) sided = 'd t constraint 'd = 'l * 'r

      let allow_left : type l r. (allowed * r) t -> (l * r) t =
       fun (type l r) (h : (allowed * r) t) : (l * r) t ->
        match h with
        | Skip -> Skip
        | Unknown -> Unknown
        | Close_over (Monadic, x) -> Close_over (Monadic, x)
        | Close_over (Comonadic, x) -> Close_over (Comonadic, x)
        | Adj_captured_by_partial_application ->
          Adj_captured_by_partial_application
        | Crossing -> Crossing
        | Allocation_l loc -> Allocation_l loc
        | Contains_l (Comonadic, x) -> Contains_l (Comonadic, x)
        | Contains_r (Monadic, x) -> Contains_r (Monadic, x)
        | Is_contained_by (Comonadic, x) -> Is_contained_by (Comonadic, x)
        | Is_contained_by (Monadic, x) -> Is_contained_by (Monadic, x)

      let allow_right : type l r. (l * allowed) t -> (l * r) t =
       fun (type l r) (h : (l * allowed) t) : (l * r) t ->
        match h with
        | Skip -> Skip
        | Unknown -> Unknown
        | Is_closed_by (Monadic, x) -> Is_closed_by (Monadic, x)
        | Is_closed_by (Comonadic, x) -> Is_closed_by (Comonadic, x)
        | Captured_by_partial_application -> Captured_by_partial_application
        | Crossing -> Crossing
        | Allocation_r loc -> Allocation_r loc
        | Contains_r (Comonadic, x) -> Contains_r (Comonadic, x)
        | Contains_l (Monadic, x) -> Contains_l (Monadic, x)
        | Is_contained_by (Comonadic, x) -> Is_contained_by (Comonadic, x)
        | Is_contained_by (Monadic, x) -> Is_contained_by (Monadic, x)

      let disallow_left : type l r. (l * r) t -> (disallowed * r) t =
       fun (type l r) (h : (l * r) t) : (disallowed * r) t ->
        match h with
        | Skip -> Skip
        | Unknown -> Unknown
        | Close_over (Monadic, x) -> Close_over (Monadic, x)
        | Close_over (Comonadic, x) -> Close_over (Comonadic, x)
        | Is_closed_by (Monadic, x) -> Is_closed_by (Monadic, x)
        | Is_closed_by (Comonadic, x) -> Is_closed_by (Comonadic, x)
        | Captured_by_partial_application -> Captured_by_partial_application
        | Adj_captured_by_partial_application ->
          Adj_captured_by_partial_application
        | Crossing -> Crossing
        | Allocation_r loc -> Allocation_r loc
        | Allocation_l loc -> Allocation_l loc
        | Contains_r (Comonadic, x) -> Contains_r (Comonadic, x)
        | Contains_l (Monadic, x) -> Contains_l (Monadic, x)
        | Is_contained_by (Comonadic, x) -> Is_contained_by (Comonadic, x)
        | Is_contained_by (Monadic, x) -> Is_contained_by (Monadic, x)
        | Contains_r (Monadic, x) -> Contains_r (Monadic, x)
        | Contains_l (Comonadic, x) -> Contains_l (Comonadic, x)

      let disallow_right : type l r. (l * r) t -> (l * disallowed) t =
       fun (type l r) (h : (l * r) t) : (l * disallowed) t ->
        match h with
        | Skip -> Skip
        | Unknown -> Unknown
        | Close_over (Monadic, x) -> Close_over (Monadic, x)
        | Close_over (Comonadic, x) -> Close_over (Comonadic, x)
        | Is_closed_by (Monadic, x) -> Is_closed_by (Monadic, x)
        | Is_closed_by (Comonadic, x) -> Is_closed_by (Comonadic, x)
        | Captured_by_partial_application -> Captured_by_partial_application
        | Adj_captured_by_partial_application ->
          Adj_captured_by_partial_application
        | Crossing -> Crossing
        | Allocation_l loc -> Allocation_l loc
        | Allocation_r loc -> Allocation_r loc
        | Contains_l (Comonadic, x) -> Contains_l (Comonadic, x)
        | Contains_r (Monadic, x) -> Contains_r (Monadic, x)
        | Is_contained_by (Comonadic, x) -> Is_contained_by (Comonadic, x)
        | Is_contained_by (Monadic, x) -> Is_contained_by (Monadic, x)
        | Contains_l (Monadic, x) -> Contains_l (Monadic, x)
        | Contains_r (Comonadic, x) -> Contains_r (Comonadic, x)
    end)
  end

  module Const = struct
    type 'd t = 'd Hint.const

    let unknown : _ t = Unknown

    let max : _ t = Unknown

    let min : _ t = Unknown

    include Magic_allow_disallow (struct
      type (_, _, 'd) sided = 'd t constraint 'd = 'l * 'r

      let allow_left : type l r. (allowed * r) t -> (l * r) t =
       fun (type l r) (h : (allowed * r) t) : (l * r) t ->
        match h with
        | Unknown -> Unknown
        | Legacy x -> Legacy x
        | Stack_expression -> Stack_expression
        | Mutable_read m -> Mutable_read m
        | Mutable_write m -> Mutable_write m
        | Lazy_forced -> Lazy_forced
        | Borrowed (loc, Comonadic) -> Borrowed (loc, Comonadic)
        | Borrowed (loc, Monadic) -> Borrowed (loc, Monadic)
        | Quoted_computation -> Quoted_computation
        | Spliced Monadic -> Spliced Monadic
        | Spliced Comonadic -> Spliced Comonadic
        | Lpoly_inst -> Lpoly_inst

      let allow_right : type l r. (l * allowed) t -> (l * r) t =
       fun (type l r) (h : (l * allowed) t) : (l * r) t ->
        match h with
        | Unknown -> Unknown
        | Legacy x -> Legacy x
        | Toplevel_expression -> Toplevel_expression
        | Lazy_allocated_on_heap -> Lazy_allocated_on_heap
        | Tailcall_function -> Tailcall_function
        | Tailcall_argument -> Tailcall_argument
        | Function_return -> Function_return
        | Module_allocated_on_heap -> Module_allocated_on_heap
        | Is_used_in pp -> Is_used_in pp
        | Always_dynamic x -> Always_dynamic x
        | Branching -> Branching
        | Borrowed (loc, Monadic) -> Borrowed (loc, Monadic)
        | Borrowed (loc, Comonadic) -> Borrowed (loc, Comonadic)
        | Escape_region x -> Escape_region x
        | Spliced Monadic -> Spliced Monadic
        | Spliced Comonadic -> Spliced Comonadic

      let disallow_left : type l r. (l * r) t -> (disallowed * r) t =
       fun (type l r) (h : (l * r) t) : (disallowed * r) t ->
        match h with
        | Unknown -> Unknown
        | Lazy_allocated_on_heap -> Lazy_allocated_on_heap
        | Legacy x -> Legacy x
        | Toplevel_expression -> Toplevel_expression
        | Tailcall_function -> Tailcall_function
        | Tailcall_argument -> Tailcall_argument
        | Mutable_read m -> Mutable_read m
        | Mutable_write m -> Mutable_write m
        | Lazy_forced -> Lazy_forced
        | Function_return -> Function_return
        | Stack_expression -> Stack_expression
        | Module_allocated_on_heap -> Module_allocated_on_heap
        | Is_used_in pp -> Is_used_in pp
        | Always_dynamic x -> Always_dynamic x
        | Branching -> Branching
        | Borrowed (loc, Monadic) -> Borrowed (loc, Monadic)
        | Borrowed (loc, Comonadic) -> Borrowed (loc, Comonadic)
        | Escape_region x -> Escape_region x
        | Quoted_computation -> Quoted_computation
        | Lpoly_inst -> Lpoly_inst
        | Spliced Monadic -> Spliced Monadic
        | Spliced Comonadic -> Spliced Comonadic

      let disallow_right : type l r. (l * r) t -> (l * disallowed) t =
       fun (type l r) (h : (l * r) t) : (l * disallowed) t ->
        match h with
        | Unknown -> Unknown
        | Lazy_allocated_on_heap -> Lazy_allocated_on_heap
        | Legacy x -> Legacy x
        | Toplevel_expression -> Toplevel_expression
        | Tailcall_function -> Tailcall_function
        | Tailcall_argument -> Tailcall_argument
        | Mutable_read m -> Mutable_read m
        | Mutable_write m -> Mutable_write m
        | Lazy_forced -> Lazy_forced
        | Function_return -> Function_return
        | Stack_expression -> Stack_expression
        | Module_allocated_on_heap -> Module_allocated_on_heap
        | Is_used_in pp -> Is_used_in pp
        | Always_dynamic x -> Always_dynamic x
        | Branching -> Branching
        | Borrowed (loc, Monadic) -> Borrowed (loc, Monadic)
        | Borrowed (loc, Comonadic) -> Borrowed (loc, Comonadic)
        | Escape_region x -> Escape_region x
        | Lpoly_inst -> Lpoly_inst
        | Quoted_computation -> Quoted_computation
        | Spliced Monadic -> Spliced Monadic
        | Spliced Comonadic -> Spliced Comonadic
    end)
  end
end

type nonrec allowed = allowed

type nonrec disallowed = disallowed

type nonrec equate_step = equate_step

module type Heyting = sig
  (** Extend the [Lattice] interface with operations of Heyting algebras *)

  include Lattice

  (** A total structural order used for map keys. This is not lattice order:
      [compare_total a b = 0] must agree with semantic equality of [a] and [b].
  *)
  val compare_total : t -> t -> int

  (** [imply c] is the right adjoint of [meet c]; That is, for any [a] and [b],
      [meet c a <= b] iff [a <= imply c b] *)
  val imply : t -> t -> t
end

module type CoHeyting = sig
  (** Extend the [Lattice] interface with operations of co-Heyting algebras *)

  include Lattice

  (** A total structural order used for map keys. This is not lattice order:
      [compare_total a b = 0] must agree with semantic equality of [a] and [b].
  *)
  val compare_total : t -> t -> int

  (** [subtract _ c] is the left adjoint of [join c]. That is, for any [a] and
      [b], [subtract a c <= b] iff [a <= join c b] *)
  val subtract : t -> t -> t
end

(* Even though our lattices are all bi-heyting algebras, that knowledge is
   internal to this module. Externally they are seen as normal lattices. *)
module Lattices = struct
  module Total (L : Total) = struct
    let min = L.min

    let max = L.max

    let le a b = L.ord a <= L.ord b

    let equal a b = L.ord a = L.ord b

    let compare_total a b = Int.compare (L.ord a) (L.ord b)

    let join a b = if L.ord a > L.ord b then a else b

    let meet a b = if L.ord a < L.ord b then a else b

    (* A total lattice has a co-heyting structure.
       Prove the [subtract] below is the left adjoint of [join].
        - If [subtract a c <= b], by the definition of [subtract] below,
          that could mean one of two things:
          - Took the branch [a <= c], and [min <= b]. In this case, we have [a <= c <= join c b].
          - Took the other branch, and [a <= b]. In this case, we have [a <= b <= join c b].

        - In the other direction: Given [a <= join c b], compare [c] and [b]:
          - if [c <= b], then [a <= join c b = b], and:
            - either [a <= c], then [subtract a c = min <= b]
            - or the other branch, then [subtract a c = a <= b]
          - if [b <= c], then [a <= join c b = c], then [subtract a c = min <= b]
    *)
    let subtract a c = if le a c then L.min else a

    (* A total lattice has a heyting structure. The proof for [imply] is dual
       and omitted. *)
    let imply c b = if le c b then L.max else b
  end
  [@@inline]

  module type Diamond = sig
    (** A lattice is a partial order, if for any [a] [b], either:
        - [a <= b] or [b <= a]
        - [a] and [b] are incomparable.

        This interface and the [Diamond] functor below are specialized to
        partial lattices of the form
        {v
            Max
            / \
          Fst Snd
            \ /
            Min
        v}
        where [Fst] and [Snd] are incomparable.

        The [Diamond] functor relies on the representation of immediate variant
        types to efficiently implement bitwise operations over such lattices. *)

    (** This must be an enumeration with four constructors, in the order of
        [min], [fst], [snd], and [max]. Anything else will fail in the [Diamond]
        functor. *)
    type t [@@immediate]

    val min : t

    val fst : t

    val snd : t

    val max : t
  end

  module Diamond (L : Diamond) = struct
    open struct
      external l_to_int : L.t -> int = "%identity"

      external l_of_int : int -> L.t = "%identity"

      let mask = 0b11

      let () =
        assert (l_to_int L.min = 0b00);
        assert (l_to_int L.fst = 0b01);
        assert (l_to_int L.snd = 0b10);
        assert (l_to_int L.max = 0b11)
    end

    let min = L.min

    let max = L.max

    let equal a b = a = b

    let compare_total a b = Int.compare (l_to_int a) (l_to_int b)

    let join a b = l_of_int (l_to_int a lor l_to_int b)

    let meet a b = l_of_int (l_to_int a land l_to_int b)

    let le a b = meet a b = a

    (* We can treat [fst] and [snd] as independent axes.
       0b0 land (lnot 0b0) = 0b0 (min = min => min)
       0b0 land (lnot 0b1) = 0b0 (min < max => min)
       0b1 land (lnot 0b0) = 0b1 (max > min => max)
       0b1 land (lnot 0b1) = 0b0 (max = max => min) *)
    let subtract a c = l_of_int (l_to_int a land lnot (l_to_int c))

    (* We can treat [fst] and [snd] as independent axes.
       (lnot 0b0) lor 0b0 = 0b1 (min = min => max)
       (lnot 0b0) lor 0b1 = 0b1 (min < max => max)
       (lnot 0b1) lor 0b0 = 0b0 (max > min => min)
       (lnot 0b1) lor 0b1 = 0b1 (max = max => max)

       [lnot c lor b] sets the top 61 bits to 1, so we must mask them out. *)
    let imply c b = l_of_int (lnot (l_to_int c) lor l_to_int b land mask)
  end
  [@@inline]

  (* Make the type of [Locality] and [Regionality] below distinguishable,
     so that we can be sure [Comonadic_with] is applied correctly. *)
  module type Areality = sig
    include Const

    include Heyting with type t := t

    val _is_areality : unit
  end

  module Locality = struct
    type t =
      | Global
      | Local

    include Total (struct
      type nonrec t = t

      let min = Global

      let max = Local

      let ord = function Global -> 0 | Local -> 1
    end)

    let legacy = Global

    let print ppf = function
      | Global -> Fmt.fprintf ppf "global"
      | Local -> Fmt.fprintf ppf "local"

    let _is_areality = ()
  end

  module Regionality = struct
    type t =
      | Global
      | Regional
      | Local

    include Total (struct
      type nonrec t = t

      let min = Global

      let max = Local

      let ord = function Global -> 0 | Regional -> 1 | Local -> 2
    end)

    let legacy = Global

    let print ppf = function
      | Global -> Fmt.fprintf ppf "global"
      | Regional -> Fmt.fprintf ppf "regional"
      | Local -> Fmt.fprintf ppf "local"

    let _is_areality = ()
  end

  module Uniqueness = struct
    type t =
      | Unique
      | Aliased

    include Total (struct
      type nonrec t = t

      let min = Unique

      let max = Aliased

      let ord = function Unique -> 0 | Aliased -> 1
    end)

    let legacy = Aliased

    let print ppf = function
      | Aliased -> Fmt.fprintf ppf "aliased"
      | Unique -> Fmt.fprintf ppf "unique"
  end

  module Linearity = struct
    type t =
      | Many
      | Once

    include Total (struct
      type nonrec t = t

      let min = Many

      let max = Once

      let ord = function Many -> 0 | Once -> 1
    end)

    let legacy = Many

    let print ppf = function
      | Once -> Fmt.fprintf ppf "once"
      | Many -> Fmt.fprintf ppf "many"
  end

  module Portability = struct
    (* Changes to this type must consider the implementation of [Diamond]. *)
    type t =
      | Portable (* 0b00 *)
      | Shareable (* 0b01 *)
      | Corruptible (* 0b10 *)
      | Nonportable (* 0b11 *)

    include Diamond (struct
      type nonrec t = t

      let min = Portable

      let fst = Shareable

      let snd = Corruptible

      let max = Nonportable
    end)

    let legacy = Nonportable

    let print ppf = function
      | Portable -> Fmt.fprintf ppf "portable"
      | Shareable -> Fmt.fprintf ppf "shareable"
      | Corruptible -> Fmt.fprintf ppf "corruptible"
      | Nonportable -> Fmt.fprintf ppf "nonportable"
  end

  module Contention = struct
    (* Changes to this type must consider the implementation of [Diamond]. *)
    type t =
      | Uncontended (* 0b00 *)
      | Corrupted (* 0b01 *)
      | Shared (* 0b10 *)
      | Contended (* 0b11 *)

    include Diamond (struct
      type nonrec t = t

      let min = Uncontended

      let fst = Corrupted

      let snd = Shared

      let max = Contended
    end)

    let legacy = Uncontended

    let print ppf = function
      | Contended -> Fmt.fprintf ppf "contended"
      | Corrupted -> Fmt.fprintf ppf "corrupted"
      | Shared -> Fmt.fprintf ppf "shared"
      | Uncontended -> Fmt.fprintf ppf "uncontended"
  end

  module Forkable = struct
    type t =
      | Forkable
      | Unforkable

    include Total (struct
      type nonrec t = t

      let min = Forkable

      let max = Unforkable

      let ord = function Forkable -> 0 | Unforkable -> 1
    end)

    let legacy = Forkable

    let print ppf = function
      | Unforkable -> Fmt.fprintf ppf "unforkable"
      | Forkable -> Fmt.fprintf ppf "forkable"
  end

  module Yielding = struct
    type t =
      | Unyielding
      | Yielding

    include Total (struct
      type nonrec t = t

      let min = Unyielding

      let max = Yielding

      let ord = function Unyielding -> 0 | Yielding -> 1
    end)

    let legacy = Unyielding

    let print ppf = function
      | Yielding -> Fmt.fprintf ppf "yielding"
      | Unyielding -> Fmt.fprintf ppf "unyielding"
  end

  module Statefulness = struct
    (* Changes to this type must consider the implementation of [Diamond]. *)
    type t =
      | Stateless (* 0b00 *)
      | Writing (* 0b01 *)
      | Reading (* 0b10 *)
      | Stateful (* 0b11 *)

    include Diamond (struct
      type nonrec t = t

      let min = Stateless

      let fst = Writing

      let snd = Reading

      let max = Stateful
    end)

    let legacy = Stateful

    let print ppf = function
      | Stateless -> Fmt.fprintf ppf "stateless"
      | Writing -> Fmt.fprintf ppf "writing"
      | Reading -> Fmt.fprintf ppf "reading"
      | Stateful -> Fmt.fprintf ppf "stateful"
  end

  module Visibility = struct
    (* Changes to this type must consider the implementation of [Diamond]. *)
    type t =
      | Read_write (* 0b00 *)
      | Read (* 0b01 *)
      | Write (* 0b10 *)
      | Immutable (* 0b11 *)

    include Diamond (struct
      type nonrec t = t

      let min = Read_write

      let fst = Read

      let snd = Write

      let max = Immutable
    end)

    let legacy = Read_write

    let print ppf = function
      | Immutable -> Fmt.fprintf ppf "immutable"
      | Read -> Fmt.fprintf ppf "read"
      | Write -> Fmt.fprintf ppf "write"
      | Read_write -> Fmt.fprintf ppf "read_write"
  end

  module Staticity = struct
    type t =
      | Static
      | Dynamic

    include Total (struct
      type nonrec t = t

      let min = Static

      let max = Dynamic

      let ord = function Static -> 0 | Dynamic -> 1
    end)

    let legacy = Dynamic

    let print ppf = function
      | Dynamic -> Fmt.fprintf ppf "dynamic"
      | Static -> Fmt.fprintf ppf "static"
  end

  type monadic =
    { uniqueness : Uniqueness.t;
      contention : Contention.t;
      visibility : Visibility.t;
      staticity : Staticity.t
    }

  module Monadic = struct
    type t = monadic

    let min =
      let uniqueness = Uniqueness.min in
      let contention = Contention.min in
      let visibility = Visibility.min in
      let staticity = Staticity.min in
      { uniqueness; contention; visibility; staticity }

    let max =
      let uniqueness = Uniqueness.max in
      let contention = Contention.max in
      let visibility = Visibility.max in
      let staticity = Staticity.max in
      { uniqueness; contention; visibility; staticity }

    let legacy =
      let uniqueness = Uniqueness.legacy in
      let contention = Contention.legacy in
      let visibility = Visibility.legacy in
      let staticity = Staticity.legacy in
      { uniqueness; contention; visibility; staticity }

    let le m1 m2 =
      let { uniqueness = uniqueness1;
            contention = contention1;
            visibility = visibility1;
            staticity = staticity1
          } =
        m1
      in
      let { uniqueness = uniqueness2;
            contention = contention2;
            visibility = visibility2;
            staticity = staticity2
          } =
        m2
      in
      Uniqueness.le uniqueness1 uniqueness2
      && Contention.le contention1 contention2
      && Visibility.le visibility1 visibility2
      && Staticity.le staticity1 staticity2

    let equal m1 m2 =
      let { uniqueness = uniqueness1;
            contention = contention1;
            visibility = visibility1;
            staticity = staticity1
          } =
        m1
      in
      let { uniqueness = uniqueness2;
            contention = contention2;
            visibility = visibility2;
            staticity = staticity2
          } =
        m2
      in
      Uniqueness.equal uniqueness1 uniqueness2
      && Contention.equal contention1 contention2
      && Visibility.equal visibility1 visibility2
      && Staticity.equal staticity1 staticity2

    let compare_total m1 m2 =
      let c = Uniqueness.compare_total m1.uniqueness m2.uniqueness in
      if c <> 0
      then c
      else
        let c = Contention.compare_total m1.contention m2.contention in
        if c <> 0
        then c
        else
          let c = Visibility.compare_total m1.visibility m2.visibility in
          if c <> 0
          then c
          else Staticity.compare_total m1.staticity m2.staticity

    let join m1 m2 =
      let uniqueness = Uniqueness.join m1.uniqueness m2.uniqueness in
      let contention = Contention.join m1.contention m2.contention in
      let visibility = Visibility.join m1.visibility m2.visibility in
      let staticity = Staticity.join m1.staticity m2.staticity in
      { uniqueness; contention; visibility; staticity }

    let meet m1 m2 =
      let uniqueness = Uniqueness.meet m1.uniqueness m2.uniqueness in
      let contention = Contention.meet m1.contention m2.contention in
      let visibility = Visibility.meet m1.visibility m2.visibility in
      let staticity = Staticity.meet m1.staticity m2.staticity in
      { uniqueness; contention; visibility; staticity }

    let subtract m1 m2 =
      let uniqueness = Uniqueness.subtract m1.uniqueness m2.uniqueness in
      let contention = Contention.subtract m1.contention m2.contention in
      let visibility = Visibility.subtract m1.visibility m2.visibility in
      let staticity = Staticity.subtract m1.staticity m2.staticity in
      { uniqueness; contention; visibility; staticity }

    let print ppf m =
      Fmt.fprintf ppf "%a,%a,%a,%a" Uniqueness.print m.uniqueness
        Contention.print m.contention Visibility.print m.visibility
        Staticity.print m.staticity
  end

  type 'areality comonadic_with =
    { areality : 'areality;
      linearity : Linearity.t;
      portability : Portability.t;
      forkable : Forkable.t;
      yielding : Yielding.t;
      statefulness : Statefulness.t
    }

  module Comonadic_with (Areality : Areality) = struct
    type t = Areality.t comonadic_with

    let min =
      let areality = Areality.min in
      let linearity = Linearity.min in
      let portability = Portability.min in
      let forkable = Forkable.min in
      let yielding = Yielding.min in
      let statefulness = Statefulness.min in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let max =
      let areality = Areality.max in
      let linearity = Linearity.max in
      let portability = Portability.max in
      let forkable = Forkable.max in
      let yielding = Yielding.max in
      let statefulness = Statefulness.max in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let legacy =
      let areality = Areality.legacy in
      let linearity = Linearity.legacy in
      let portability = Portability.legacy in
      let forkable = Forkable.legacy in
      let yielding = Yielding.legacy in
      let statefulness = Statefulness.legacy in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let le m1 m2 =
      let { areality = areality1;
            linearity = linearity1;
            portability = portability1;
            forkable = forkable1;
            yielding = yielding1;
            statefulness = statefulness1
          } =
        m1
      in
      let { areality = areality2;
            linearity = linearity2;
            portability = portability2;
            forkable = forkable2;
            yielding = yielding2;
            statefulness = statefulness2
          } =
        m2
      in
      Areality.le areality1 areality2
      && Linearity.le linearity1 linearity2
      && Portability.le portability1 portability2
      && Forkable.le forkable1 forkable2
      && Yielding.le yielding1 yielding2
      && Statefulness.le statefulness1 statefulness2

    let equal m1 m2 =
      let { areality = areality1;
            linearity = linearity1;
            portability = portability1;
            forkable = forkable1;
            yielding = yielding1;
            statefulness = statefulness1
          } =
        m1
      in
      let { areality = areality2;
            linearity = linearity2;
            portability = portability2;
            forkable = forkable2;
            yielding = yielding2;
            statefulness = statefulness2
          } =
        m2
      in
      Areality.equal areality1 areality2
      && Linearity.equal linearity1 linearity2
      && Portability.equal portability1 portability2
      && Forkable.equal forkable1 forkable2
      && Yielding.equal yielding1 yielding2
      && Statefulness.equal statefulness1 statefulness2

    let compare_total m1 m2 =
      let c = Areality.compare_total m1.areality m2.areality in
      if c <> 0
      then c
      else
        let c = Linearity.compare_total m1.linearity m2.linearity in
        if c <> 0
        then c
        else
          let c = Portability.compare_total m1.portability m2.portability in
          if c <> 0
          then c
          else
            let c = Forkable.compare_total m1.forkable m2.forkable in
            if c <> 0
            then c
            else
              let c = Yielding.compare_total m1.yielding m2.yielding in
              if c <> 0
              then c
              else Statefulness.compare_total m1.statefulness m2.statefulness

    let join m1 m2 =
      let areality = Areality.join m1.areality m2.areality in
      let linearity = Linearity.join m1.linearity m2.linearity in
      let portability = Portability.join m1.portability m2.portability in
      let forkable = Forkable.join m1.forkable m2.forkable in
      let yielding = Yielding.join m1.yielding m2.yielding in
      let statefulness = Statefulness.join m1.statefulness m2.statefulness in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let meet m1 m2 =
      let areality = Areality.meet m1.areality m2.areality in
      let linearity = Linearity.meet m1.linearity m2.linearity in
      let portability = Portability.meet m1.portability m2.portability in
      let forkable = Forkable.meet m1.forkable m2.forkable in
      let yielding = Yielding.meet m1.yielding m2.yielding in
      let statefulness = Statefulness.meet m1.statefulness m2.statefulness in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let imply m1 m2 =
      let areality = Areality.imply m1.areality m2.areality in
      let linearity = Linearity.imply m1.linearity m2.linearity in
      let portability = Portability.imply m1.portability m2.portability in
      let forkable = Forkable.imply m1.forkable m2.forkable in
      let yielding = Yielding.imply m1.yielding m2.yielding in
      let statefulness = Statefulness.imply m1.statefulness m2.statefulness in
      { areality; linearity; portability; forkable; yielding; statefulness }

    let print ppf m =
      Fmt.fprintf ppf "%a,%a,%a,%a,%a,%a" Areality.print m.areality
        Linearity.print m.linearity Portability.print m.portability
        Forkable.print m.forkable Yielding.print m.yielding Statefulness.print
        m.statefulness
  end
  [@@inline]

  module Opposite (L : CoHeyting) : Heyting with type t = L.t = struct
    type t = L.t

    let min = L.max

    let max = L.min

    let[@inline] le a b = L.le b a

    let equal = L.equal

    let compare_total = L.compare_total

    let join = L.meet

    let meet = L.join

    let print = L.print

    let imply a b = L.subtract b a
  end
  [@@inline]

  (* Notes on flipping

     Our lattices are split into two opposite fragments: monadic and comonadic.
     Moreover:
     - Morphisms between lattices in the same fragment are always monotone.
     - Morphisms between lattices from opposite fragments are always antitone.

     [Solver_mono] only supports monotone morphisms. Due to this limitation,
     here, we flip all lattices in the monadic fragment, which makes morphisms
     between opposite fragments monotone. We submit this category of lattices
     (original comonadic lattices + flipped monadic lattices) to [Solver_mono].

     The resulted interface given by [Solver_mono] therefore has the monadic
     lattices flipped. We build on top of that and provide an interface to the
     downstream code where monadic lattices are flipped back to its original
     ordering. See [module Monadic_gen] and [module Monadic].
  *)
  module Uniqueness_op = Opposite (Uniqueness)
  module Contention_op = Opposite (Contention)
  module Visibility_op = Opposite (Visibility)
  module Staticity_op = Opposite (Staticity)
  module Monadic_op = Opposite (Monadic)
  module Comonadic_with_locality = Comonadic_with (Locality)
  module Comonadic_with_regionality = Comonadic_with (Regionality)

  type 'a obj =
    | Locality : Locality.t obj
    | Regionality : Regionality.t obj
    | Uniqueness_op : Uniqueness_op.t obj
    | Linearity : Linearity.t obj
    | Portability : Portability.t obj
    | Forkable : Forkable.t obj
    | Yielding : Yielding.t obj
    | Statefulness : Statefulness.t obj
    | Contention_op : Contention_op.t obj
    | Visibility_op : Visibility_op.t obj
    | Staticity_op : Staticity_op.t obj
    | Monadic_op : Monadic_op.t obj
    | Comonadic_with_regionality : Comonadic_with_regionality.t obj
    | Comonadic_with_locality : Comonadic_with_locality.t obj

  let is_opposite : type a. a obj -> bool = function
    | Locality -> false
    | Regionality -> false
    | Uniqueness_op -> true
    | Linearity -> false
    | Portability -> false
    | Forkable -> false
    | Yielding -> false
    | Statefulness -> false
    | Contention_op -> true
    | Visibility_op -> true
    | Staticity_op -> true
    | Monadic_op -> true
    | Comonadic_with_locality -> false
    | Comonadic_with_regionality -> false

  let print_obj : type a. _ -> a obj -> unit =
   fun ppf -> function
    | Locality -> Fmt.fprintf ppf "Locality"
    | Regionality -> Fmt.fprintf ppf "Regionality"
    | Uniqueness_op -> Fmt.fprintf ppf "Uniqueness_op"
    | Linearity -> Fmt.fprintf ppf "Linearity"
    | Portability -> Fmt.fprintf ppf "Portability"
    | Forkable -> Fmt.fprintf ppf "Forkable"
    | Yielding -> Fmt.fprintf ppf "Yielding"
    | Statefulness -> Fmt.fprintf ppf "Statefulness"
    | Contention_op -> Fmt.fprintf ppf "Contention_op"
    | Visibility_op -> Fmt.fprintf ppf "Visibility_op"
    | Staticity_op -> Fmt.fprintf ppf "Staticity_op"
    | Monadic_op -> Fmt.fprintf ppf "Monadic_op"
    | Comonadic_with_locality -> Fmt.fprintf ppf "Comonadic_with_locality"
    | Comonadic_with_regionality -> Fmt.fprintf ppf "Comonadic_with_regionality"

  let min : type a. a obj -> a = function
    | Locality -> Locality.min
    | Regionality -> Regionality.min
    | Uniqueness_op -> Uniqueness_op.min
    | Contention_op -> Contention_op.min
    | Visibility_op -> Visibility_op.min
    | Forkable -> Forkable.min
    | Yielding -> Yielding.min
    | Statefulness -> Statefulness.min
    | Linearity -> Linearity.min
    | Portability -> Portability.min
    | Staticity_op -> Staticity_op.min
    | Monadic_op -> Monadic_op.min
    | Comonadic_with_locality -> Comonadic_with_locality.min
    | Comonadic_with_regionality -> Comonadic_with_regionality.min

  let max : type a. a obj -> a = function
    | Locality -> Locality.max
    | Regionality -> Regionality.max
    | Uniqueness_op -> Uniqueness_op.max
    | Contention_op -> Contention_op.max
    | Visibility_op -> Visibility_op.max
    | Linearity -> Linearity.max
    | Portability -> Portability.max
    | Forkable -> Forkable.max
    | Yielding -> Yielding.max
    | Statefulness -> Statefulness.max
    | Staticity_op -> Staticity_op.max
    | Monadic_op -> Monadic_op.max
    | Comonadic_with_locality -> Comonadic_with_locality.max
    | Comonadic_with_regionality -> Comonadic_with_regionality.max

  let le : type a. a obj -> a -> a -> bool =
   fun obj a b ->
    match obj with
    | Locality -> Locality.le a b
    | Regionality -> Regionality.le a b
    | Uniqueness_op -> Uniqueness_op.le a b
    | Contention_op -> Contention_op.le a b
    | Visibility_op -> Visibility_op.le a b
    | Linearity -> Linearity.le a b
    | Portability -> Portability.le a b
    | Forkable -> Forkable.le a b
    | Yielding -> Yielding.le a b
    | Statefulness -> Statefulness.le a b
    | Staticity_op -> Staticity_op.le a b
    | Monadic_op -> Monadic_op.le a b
    | Comonadic_with_locality -> Comonadic_with_locality.le a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.le a b

  let compare_total : type a. a obj -> a -> a -> int =
   fun obj a b ->
    match obj with
    | Locality -> Locality.compare_total a b
    | Regionality -> Regionality.compare_total a b
    | Uniqueness_op -> Uniqueness_op.compare_total a b
    | Contention_op -> Contention_op.compare_total a b
    | Visibility_op -> Visibility_op.compare_total a b
    | Linearity -> Linearity.compare_total a b
    | Portability -> Portability.compare_total a b
    | Forkable -> Forkable.compare_total a b
    | Yielding -> Yielding.compare_total a b
    | Statefulness -> Statefulness.compare_total a b
    | Staticity_op -> Staticity_op.compare_total a b
    | Monadic_op -> Monadic_op.compare_total a b
    | Comonadic_with_locality -> Comonadic_with_locality.compare_total a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.compare_total a b

  let equal : type a. a obj -> a -> a -> bool =
   fun obj a b ->
    match obj with
    | Locality -> Locality.equal a b
    | Regionality -> Regionality.equal a b
    | Uniqueness_op -> Uniqueness_op.equal a b
    | Contention_op -> Contention_op.equal a b
    | Visibility_op -> Visibility_op.equal a b
    | Linearity -> Linearity.equal a b
    | Portability -> Portability.equal a b
    | Forkable -> Forkable.equal a b
    | Yielding -> Yielding.equal a b
    | Statefulness -> Statefulness.equal a b
    | Staticity_op -> Staticity_op.equal a b
    | Monadic_op -> Monadic_op.equal a b
    | Comonadic_with_locality -> Comonadic_with_locality.equal a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.equal a b

  let join : type a. a obj -> a -> a -> a =
   fun obj a b ->
    match obj with
    | Locality -> Locality.join a b
    | Regionality -> Regionality.join a b
    | Uniqueness_op -> Uniqueness_op.join a b
    | Contention_op -> Contention_op.join a b
    | Visibility_op -> Visibility_op.join a b
    | Linearity -> Linearity.join a b
    | Portability -> Portability.join a b
    | Forkable -> Forkable.join a b
    | Yielding -> Yielding.join a b
    | Statefulness -> Statefulness.join a b
    | Staticity_op -> Staticity_op.join a b
    | Monadic_op -> Monadic_op.join a b
    | Comonadic_with_locality -> Comonadic_with_locality.join a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.join a b

  let meet : type a. a obj -> a -> a -> a =
   fun obj a b ->
    match obj with
    | Locality -> Locality.meet a b
    | Regionality -> Regionality.meet a b
    | Uniqueness_op -> Uniqueness_op.meet a b
    | Contention_op -> Contention_op.meet a b
    | Visibility_op -> Visibility_op.meet a b
    | Linearity -> Linearity.meet a b
    | Portability -> Portability.meet a b
    | Forkable -> Forkable.meet a b
    | Yielding -> Yielding.meet a b
    | Statefulness -> Statefulness.meet a b
    | Staticity_op -> Staticity_op.meet a b
    | Monadic_op -> Monadic_op.meet a b
    | Comonadic_with_locality -> Comonadic_with_locality.meet a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.meet a b

  let imply : type a. a obj -> a -> a -> a =
   fun obj a b ->
    match obj with
    | Locality -> Locality.imply a b
    | Regionality -> Regionality.imply a b
    | Uniqueness_op -> Uniqueness_op.imply a b
    | Contention_op -> Contention_op.imply a b
    | Visibility_op -> Visibility_op.imply a b
    | Linearity -> Linearity.imply a b
    | Portability -> Portability.imply a b
    | Forkable -> Forkable.imply a b
    | Yielding -> Yielding.imply a b
    | Statefulness -> Statefulness.imply a b
    | Staticity_op -> Staticity_op.imply a b
    | Comonadic_with_locality -> Comonadic_with_locality.imply a b
    | Comonadic_with_regionality -> Comonadic_with_regionality.imply a b
    | Monadic_op -> Monadic_op.imply a b

  (* not hotpath, Ok to curry *)
  let print : type a. a obj -> _ -> a -> unit = function
    | Locality -> Locality.print
    | Regionality -> Regionality.print
    | Uniqueness_op -> Uniqueness_op.print
    | Contention_op -> Contention_op.print
    | Visibility_op -> Visibility_op.print
    | Linearity -> Linearity.print
    | Portability -> Portability.print
    | Forkable -> Forkable.print
    | Yielding -> Yielding.print
    | Statefulness -> Statefulness.print
    | Staticity_op -> Staticity_op.print
    | Monadic_op -> Monadic_op.print
    | Comonadic_with_locality -> Comonadic_with_locality.print
    | Comonadic_with_regionality -> Comonadic_with_regionality.print

  let compare_obj : type a b. a obj -> b obj -> int =
   fun a b ->
    match a, b with
    | Locality, Locality -> 0
    | Locality, _ -> -1
    | _, Locality -> 1
    | Regionality, Regionality -> 0
    | Regionality, _ -> -1
    | _, Regionality -> 1
    | Uniqueness_op, Uniqueness_op -> 0
    | Uniqueness_op, _ -> -1
    | _, Uniqueness_op -> 1
    | Linearity, Linearity -> 0
    | Linearity, _ -> -1
    | _, Linearity -> 1
    | Portability, Portability -> 0
    | Portability, _ -> -1
    | _, Portability -> 1
    | Forkable, Forkable -> 0
    | Forkable, _ -> -1
    | _, Forkable -> 1
    | Yielding, Yielding -> 0
    | Yielding, _ -> -1
    | _, Yielding -> 1
    | Statefulness, Statefulness -> 0
    | Statefulness, _ -> -1
    | _, Statefulness -> 1
    | Contention_op, Contention_op -> 0
    | Contention_op, _ -> -1
    | _, Contention_op -> 1
    | Visibility_op, Visibility_op -> 0
    | Visibility_op, _ -> -1
    | _, Visibility_op -> 1
    | Staticity_op, Staticity_op -> 0
    | Staticity_op, _ -> -1
    | _, Staticity_op -> 1
    | Monadic_op, Monadic_op -> 0
    | Monadic_op, _ -> -1
    | _, Monadic_op -> 1
    | Comonadic_with_regionality, Comonadic_with_regionality -> 0
    | Comonadic_with_regionality, _ -> -1
    | _, Comonadic_with_regionality -> 1
    | Comonadic_with_locality, Comonadic_with_locality -> 0

  let equal_obj : type a b. a obj -> b obj -> (a, b) Misc.is_eq =
   fun a b ->
    match a, b with
    | Locality, Locality -> Misc.Is_eq
    | Regionality, Regionality -> Misc.Is_eq
    | Uniqueness_op, Uniqueness_op -> Misc.Is_eq
    | Linearity, Linearity -> Misc.Is_eq
    | Portability, Portability -> Misc.Is_eq
    | Forkable, Forkable -> Misc.Is_eq
    | Yielding, Yielding -> Misc.Is_eq
    | Statefulness, Statefulness -> Misc.Is_eq
    | Contention_op, Contention_op -> Misc.Is_eq
    | Visibility_op, Visibility_op -> Misc.Is_eq
    | Staticity_op, Staticity_op -> Misc.Is_eq
    | Monadic_op, Monadic_op -> Misc.Is_eq
    | Comonadic_with_regionality, Comonadic_with_regionality -> Misc.Is_eq
    | Comonadic_with_locality, Comonadic_with_locality -> Misc.Is_eq
    | ( ( Locality | Regionality | Uniqueness_op | Linearity | Portability
        | Forkable | Yielding | Statefulness | Contention_op | Visibility_op
        | Staticity_op | Monadic_op | Comonadic_with_regionality
        | Comonadic_with_locality ),
        _ ) ->
      Misc.Is_not_eq
end

module Lattices_mono = struct
  include Lattices

  module Axis = struct
    type ('t, 'r) t =
      | Areality : ('a comonadic_with, 'a) t
      | Forkable : ('areality comonadic_with, Forkable.t) t
      | Yielding : ('areality comonadic_with, Yielding.t) t
      | Linearity : ('areality comonadic_with, Linearity.t) t
      | Statefulness : ('areality comonadic_with, Statefulness.t) t
      | Portability : ('areality comonadic_with, Portability.t) t
      | Uniqueness : (Monadic_op.t, Uniqueness_op.t) t
      | Visibility : (Monadic_op.t, Visibility_op.t) t
      | Contention : (Monadic_op.t, Contention_op.t) t
      | Staticity : (Monadic_op.t, Staticity_op.t) t

    let print : type p r. _ -> (p, r) t -> unit =
     fun ppf -> function
      | Areality -> Fmt.fprintf ppf "locality"
      | Linearity -> Fmt.fprintf ppf "linearity"
      | Portability -> Fmt.fprintf ppf "portability"
      | Uniqueness -> Fmt.fprintf ppf "uniqueness"
      | Contention -> Fmt.fprintf ppf "contention"
      | Forkable -> Fmt.fprintf ppf "forkable"
      | Yielding -> Fmt.fprintf ppf "yielding"
      | Statefulness -> Fmt.fprintf ppf "statefulness"
      | Visibility -> Fmt.fprintf ppf "visibility"
      | Staticity -> Fmt.fprintf ppf "staticity"

    let equal : type p r1 r2. (p, r1) t -> (p, r2) t -> (r1, r2) Misc.is_eq =
     fun ax1 ax2 ->
      match ax1, ax2 with
      | Areality, Areality -> Is_eq
      | Linearity, Linearity -> Is_eq
      | Portability, Portability -> Is_eq
      | Uniqueness, Uniqueness -> Is_eq
      | Contention, Contention -> Is_eq
      | Forkable, Forkable -> Is_eq
      | Yielding, Yielding -> Is_eq
      | Statefulness, Statefulness -> Is_eq
      | Visibility, Visibility -> Is_eq
      | Staticity, Staticity -> Is_eq
      | ( ( Areality | Linearity | Uniqueness | Portability | Contention
          | Forkable | Yielding | Statefulness | Visibility | Staticity ),
          _ ) ->
        Is_not_eq

    let ord : type p r. (p, r) t -> int = function
      | Areality -> 0
      | Forkable -> 1
      | Yielding -> 2
      | Linearity -> 3
      | Statefulness -> 4
      | Portability -> 5
      | Uniqueness -> 6
      | Visibility -> 7
      | Contention -> 8
      | Staticity -> 9

    let compare : type p r1 r2. (p, r1) t -> (p, r2) t -> int =
     fun ax1 ax2 -> Int.compare (ord ax1) (ord ax2)

    let proj : type p r. (p, r) t -> p -> r =
     fun ax t ->
      match ax with
      | Areality -> t.areality
      | Linearity -> t.linearity
      | Portability -> t.portability
      | Forkable -> t.forkable
      | Yielding -> t.yielding
      | Statefulness -> t.statefulness
      | Uniqueness -> t.uniqueness
      | Contention -> t.contention
      | Visibility -> t.visibility
      | Staticity -> t.staticity

    let set : type p r. (p, r) t -> r -> p -> p =
     fun ax r t ->
      match ax with
      | Areality -> { t with areality = r }
      | Linearity -> { t with linearity = r }
      | Portability -> { t with portability = r }
      | Forkable -> { t with forkable = r }
      | Yielding -> { t with yielding = r }
      | Statefulness -> { t with statefulness = r }
      | Uniqueness -> { t with uniqueness = r }
      | Contention -> { t with contention = r }
      | Visibility -> { t with visibility = r }
      | Staticity -> { t with staticity = r }
  end

  type ('a, 'b, 'd) morph =
    | Id : ('a, 'a, 'l * 'r) morph  (** identity morphism *)
    | Meet_const : 'a -> ('a, 'a, 'l * 'r) morph
        (** Meet the input with the parameter *)
    | Imply_const : 'a -> ('a, 'a, disallowed * 'r) morph
        (** The right adjoint of [Meet_const] *)
    | Proj : 't obj * ('t, 'r_) Axis.t -> ('t, 'r_, 'l * 'r) morph
        (** Project from a product to an axis *)
    | Max_with : ('t, 'r_) Axis.t -> ('r_, 't, disallowed * 'r) morph
        (** Combine an axis with maxima along other axes *)
    | Min_with : ('t, 'r_) Axis.t -> ('r_, 't, 'l * disallowed) morph
        (** Combine an axis with minima along other axes *)
    | Map_comonadic :
        ('a1, 'a2, 'l * 'r) morph
        -> ('a1 comonadic_with, 'a2 comonadic_with, 'l * 'r) morph
        (** Lift an morphism on areality to a morphism on the comonadic fragment
        *)
    | Monadic_to_comonadic_min :
        (Monadic_op.t, 'a comonadic_with, 'l * disallowed) morph
        (** Dualize the monadic fragment to the comonadic fragment. The areality
            is set to min. *)
    | Comonadic_to_monadic_min :
        'a comonadic_with obj
        -> ('a comonadic_with, Monadic_op.t, 'l * disallowed) morph
        (** Dualize the comonadic fragment to the monadic fragment. The
            staticity_op is set to min. *)
    | Monadic_to_comonadic_max :
        (Monadic_op.t, 'a comonadic_with, disallowed * 'r) morph
        (** Dualize the monadic fragment to the comonadic fragment. The areality
            is set to max. *)
    | Comonadic_to_monadic_max :
        'a comonadic_with obj
        -> ('a comonadic_with, Monadic_op.t, disallowed * 'r) morph
        (** Dualize the comonadic fragment to the monadic fragment. The
            staticity_op is set to max. *)
    (* Following is a chain of adjunction (complete and cannot extend in
       either direction) *)
    | Local_to_regional : (Locality.t, Regionality.t, 'l * disallowed) morph
        (** Maps local to regional, global to global *)
    | Regional_to_local : (Regionality.t, Locality.t, 'l * 'r) morph
        (** Maps regional to local, identity otherwise *)
    | Locality_as_regionality : (Locality.t, Regionality.t, 'l * 'r) morph
        (** Inject locality into regionality *)
    | Regional_to_global : (Regionality.t, Locality.t, 'l * 'r) morph
        (** Maps regional to global, identity otherwise *)
    | Global_to_regional : (Locality.t, Regionality.t, disallowed * 'r) morph
        (** Maps global to regional, local to local *)
    | Compose :
        ('b, 'c, 'l * 'r) morph * ('a, 'b, 'l * 'r) morph
        -> ('a, 'c, 'l * 'r) morph  (** Compoistion of two morphisms *)
    constraint 'd = _ * _
  [@@ocaml.warning "-62"]

  include Magic_allow_disallow (struct
    type ('a, 'b, 'd) sided = ('a, 'b, 'd) morph constraint 'd = 'l * 'r

    let rec allow_left : type a b l r.
        (a, b, allowed * r) morph -> (a, b, l * r) morph = function
      | Id -> Id
      | Proj (src, ax) -> Proj (src, ax)
      | Min_with ax -> Min_with ax
      | Meet_const c -> Meet_const c
      | Compose (f, g) ->
        let f = allow_left f in
        let g = allow_left g in
        Compose (f, g)
      | Monadic_to_comonadic_min -> Monadic_to_comonadic_min
      | Comonadic_to_monadic_min a -> Comonadic_to_monadic_min a
      | Local_to_regional -> Local_to_regional
      | Locality_as_regionality -> Locality_as_regionality
      | Regional_to_local -> Regional_to_local
      | Regional_to_global -> Regional_to_global
      | Map_comonadic f ->
        let f = allow_left f in
        Map_comonadic f

    let rec allow_right : type a b l r.
        (a, b, l * allowed) morph -> (a, b, l * r) morph = function
      | Id -> Id
      | Proj (src, ax) -> Proj (src, ax)
      | Max_with ax -> Max_with ax
      | Meet_const c -> Meet_const c
      | Imply_const c -> Imply_const c
      | Compose (f, g) ->
        let f = allow_right f in
        let g = allow_right g in
        Compose (f, g)
      | Comonadic_to_monadic_max a -> Comonadic_to_monadic_max a
      | Monadic_to_comonadic_max -> Monadic_to_comonadic_max
      | Global_to_regional -> Global_to_regional
      | Locality_as_regionality -> Locality_as_regionality
      | Regional_to_local -> Regional_to_local
      | Regional_to_global -> Regional_to_global
      | Map_comonadic f ->
        let f = allow_right f in
        Map_comonadic f

    let rec disallow_left : type a b l r.
        (a, b, l * r) morph -> (a, b, disallowed * r) morph = function
      | Id -> Id
      | Proj (src, ax) -> Proj (src, ax)
      | Min_with ax -> Min_with ax
      | Max_with ax -> Max_with ax
      | Meet_const c -> Meet_const c
      | Imply_const c -> Imply_const c
      | Compose (f, g) ->
        let f = disallow_left f in
        let g = disallow_left g in
        Compose (f, g)
      | Monadic_to_comonadic_min -> Monadic_to_comonadic_min
      | Comonadic_to_monadic_min a -> Comonadic_to_monadic_min a
      | Monadic_to_comonadic_max -> Monadic_to_comonadic_max
      | Comonadic_to_monadic_max a -> Comonadic_to_monadic_max a
      | Local_to_regional -> Local_to_regional
      | Global_to_regional -> Global_to_regional
      | Locality_as_regionality -> Locality_as_regionality
      | Regional_to_local -> Regional_to_local
      | Regional_to_global -> Regional_to_global
      | Map_comonadic f ->
        let f = disallow_left f in
        Map_comonadic f

    let rec disallow_right : type a b l r.
        (a, b, l * r) morph -> (a, b, l * disallowed) morph = function
      | Id -> Id
      | Proj (src, ax) -> Proj (src, ax)
      | Min_with ax -> Min_with ax
      | Max_with ax -> Max_with ax
      | Meet_const c -> Meet_const c
      | Imply_const c -> Imply_const c
      | Compose (f, g) ->
        let f = disallow_right f in
        let g = disallow_right g in
        Compose (f, g)
      | Monadic_to_comonadic_min -> Monadic_to_comonadic_min
      | Comonadic_to_monadic_min a -> Comonadic_to_monadic_min a
      | Monadic_to_comonadic_max -> Monadic_to_comonadic_max
      | Comonadic_to_monadic_max a -> Comonadic_to_monadic_max a
      | Local_to_regional -> Local_to_regional
      | Global_to_regional -> Global_to_regional
      | Locality_as_regionality -> Locality_as_regionality
      | Regional_to_local -> Regional_to_local
      | Regional_to_global -> Regional_to_global
      | Map_comonadic f ->
        let f = disallow_right f in
        Map_comonadic f
  end)

  let set_areality : type a1 a2. a2 -> a1 comonadic_with -> a2 comonadic_with =
   fun r t -> { t with areality = r }

  let proj_obj : type t r. (t, r) Axis.t -> t obj -> r obj =
   fun ax obj ->
    match ax, obj with
    | Areality, Comonadic_with_locality -> Locality
    | Areality, Comonadic_with_regionality -> Regionality
    | Linearity, Comonadic_with_locality -> Linearity
    | Linearity, Comonadic_with_regionality -> Linearity
    | Portability, Comonadic_with_locality -> Portability
    | Portability, Comonadic_with_regionality -> Portability
    | Forkable, Comonadic_with_locality -> Forkable
    | Forkable, Comonadic_with_regionality -> Forkable
    | Yielding, Comonadic_with_locality -> Yielding
    | Yielding, Comonadic_with_regionality -> Yielding
    | Statefulness, Comonadic_with_locality -> Statefulness
    | Statefulness, Comonadic_with_regionality -> Statefulness
    | Uniqueness, Monadic_op -> Uniqueness_op
    | Contention, Monadic_op -> Contention_op
    | Visibility, Monadic_op -> Visibility_op
    | Staticity, Monadic_op -> Staticity_op

  let comonadic_with_obj : type a. a obj -> a comonadic_with obj =
   fun a0 ->
    match a0 with
    | Locality -> Comonadic_with_locality
    | Regionality -> Comonadic_with_regionality
    | Uniqueness_op | Linearity | Monadic_op | Comonadic_with_regionality
    | Comonadic_with_locality | Contention_op | Visibility_op | Portability
    | Forkable | Yielding | Statefulness | Staticity_op ->
      assert false

  let rec src : type a b l r. b obj -> (a, b, l * r) morph -> a obj =
   fun dst f ->
    match f with
    | Id -> dst
    | Proj (src, _) -> src
    | Max_with ax -> proj_obj ax dst
    | Min_with ax -> proj_obj ax dst
    | Meet_const _ -> dst
    | Imply_const _ -> dst
    | Compose (f, g) ->
      let mid = src dst f in
      src mid g
    | Monadic_to_comonadic_min -> Monadic_op
    | Comonadic_to_monadic_min src -> src
    | Comonadic_to_monadic_max src -> src
    | Monadic_to_comonadic_max -> Monadic_op
    | Local_to_regional -> Locality
    | Locality_as_regionality -> Locality
    | Global_to_regional -> Locality
    | Regional_to_local -> Regionality
    | Regional_to_global -> Regionality
    | Map_comonadic f ->
      let dst0 = proj_obj Areality dst in
      let src0 = src dst0 f in
      comonadic_with_obj src0

  let rec compare_morph : type a1 l1 r1 a2 b l2 r2.
      b obj -> (a1, b, l1 * r1) morph -> (a2, b, l2 * r2) morph -> int =
   fun dst f1 f2 ->
    match f1, f2 with
    | Id, Id -> 0
    | Id, _ -> -1
    | _, Id -> 1
    | Proj (src1, ax1), Proj (src2, ax2) -> (
      let c = compare_obj src1 src2 in
      if c <> 0
      then c
      else
        match equal_obj src1 src2 with
        | Misc.Is_eq -> Axis.compare ax1 ax2
        | Misc.Is_not_eq ->
          Misc.fatal_error
            "Mode.Lattices_mono.compare_morph: inconsistent object equality")
    | Proj _, _ -> -1
    | _, Proj _ -> 1
    | Max_with ax1, Max_with ax2 -> Axis.compare ax1 ax2
    | Max_with _, _ -> -1
    | _, Max_with _ -> 1
    | Min_with ax1, Min_with ax2 -> Axis.compare ax1 ax2
    | Min_with _, _ -> -1
    | _, Min_with _ -> 1
    | Meet_const c1, Meet_const c2 -> compare_total dst c1 c2
    | Meet_const _, _ -> -1
    | _, Meet_const _ -> 1
    | Imply_const c1, Imply_const c2 -> compare_total dst c1 c2
    | Imply_const _, _ -> -1
    | _, Imply_const _ -> 1
    | Monadic_to_comonadic_min, Monadic_to_comonadic_min -> 0
    | Monadic_to_comonadic_min, _ -> -1
    | _, Monadic_to_comonadic_min -> 1
    | Comonadic_to_monadic_min a1, Comonadic_to_monadic_min a2 ->
      compare_obj a1 a2
    | Comonadic_to_monadic_min _, _ -> -1
    | _, Comonadic_to_monadic_min _ -> 1
    | Monadic_to_comonadic_max, Monadic_to_comonadic_max -> 0
    | Monadic_to_comonadic_max, _ -> -1
    | _, Monadic_to_comonadic_max -> 1
    | Comonadic_to_monadic_max a1, Comonadic_to_monadic_max a2 ->
      compare_obj a1 a2
    | Comonadic_to_monadic_max _, _ -> -1
    | _, Comonadic_to_monadic_max _ -> 1
    | Local_to_regional, Local_to_regional -> 0
    | Local_to_regional, _ -> -1
    | _, Local_to_regional -> 1
    | Locality_as_regionality, Locality_as_regionality -> 0
    | Locality_as_regionality, _ -> -1
    | _, Locality_as_regionality -> 1
    | Global_to_regional, Global_to_regional -> 0
    | Global_to_regional, _ -> -1
    | _, Global_to_regional -> 1
    | Regional_to_local, Regional_to_local -> 0
    | Regional_to_local, _ -> -1
    | _, Regional_to_local -> 1
    | Regional_to_global, Regional_to_global -> 0
    | Regional_to_global, _ -> -1
    | _, Regional_to_global -> 1
    | Compose (f1, g1), Compose (f2, g2) -> (
      let c = compare_morph dst f1 f2 in
      if c <> 0
      then c
      else
        match equal_morph dst f1 f2 with
        | Misc.Is_eq -> compare_morph (src dst f1) g1 g2
        | Misc.Is_not_eq ->
          Misc.fatal_error
            "Mode.Lattices_mono.compare_morph: inconsistent equality")
    | Compose _, _ -> -1
    | _, Compose _ -> 1
    | Map_comonadic f, Map_comonadic g ->
      compare_morph (proj_obj Areality dst) f g

  and equal_morph : type a1 l1 r1 a2 b l2 r2.
      b obj ->
      (a1, b, l1 * r1) morph ->
      (a2, b, l2 * r2) morph ->
      (a1, a2) Misc.is_eq =
   fun dst f1 f2 ->
    match f1, f2 with
    | Id, Id -> Misc.Is_eq
    | Proj (src1, ax1), Proj (src2, ax2) -> (
      match equal_obj src1 src2 with
      | Misc.Is_not_eq -> Misc.Is_not_eq
      | Misc.Is_eq -> (
        match Axis.equal ax1 ax2 with
        | Misc.Is_eq -> Misc.Is_eq
        | Misc.Is_not_eq -> Misc.Is_not_eq))
    | Max_with ax1, Max_with ax2 -> Axis.equal ax1 ax2
    | Min_with ax1, Min_with ax2 -> Axis.equal ax1 ax2
    | Meet_const c1, Meet_const c2 ->
      if equal dst c1 c2 then Misc.Is_eq else Misc.Is_not_eq
    | Imply_const c1, Imply_const c2 ->
      if equal dst c1 c2 then Misc.Is_eq else Misc.Is_not_eq
    | Monadic_to_comonadic_min, Monadic_to_comonadic_min -> Misc.Is_eq
    | Comonadic_to_monadic_min a1, Comonadic_to_monadic_min a2 ->
      equal_obj a1 a2
    | Monadic_to_comonadic_max, Monadic_to_comonadic_max -> Misc.Is_eq
    | Comonadic_to_monadic_max a1, Comonadic_to_monadic_max a2 ->
      equal_obj a1 a2
    | Local_to_regional, Local_to_regional -> Misc.Is_eq
    | Locality_as_regionality, Locality_as_regionality -> Misc.Is_eq
    | Global_to_regional, Global_to_regional -> Misc.Is_eq
    | Regional_to_local, Regional_to_local -> Misc.Is_eq
    | Regional_to_global, Regional_to_global -> Misc.Is_eq
    | Compose (f1, g1), Compose (f2, g2) -> (
      match equal_morph dst f1 f2 with
      | Misc.Is_not_eq -> Misc.Is_not_eq
      | Misc.Is_eq -> equal_morph (src dst f1) g1 g2)
    | Map_comonadic f, Map_comonadic g ->
      begin match equal_morph (proj_obj Areality dst) f g with
      | Misc.Is_not_eq -> Misc.Is_not_eq
      | Misc.Is_eq -> Misc.Is_eq
      end
    | ( ( Id | Proj _ | Max_with _ | Min_with _ | Meet_const _ | Imply_const _
        | Monadic_to_comonadic_min | Comonadic_to_monadic_min _
        | Monadic_to_comonadic_max | Comonadic_to_monadic_max _
        | Local_to_regional | Locality_as_regionality | Global_to_regional
        | Regional_to_local | Regional_to_global | Compose _ | Map_comonadic _
          ),
        _ ) ->
      Misc.Is_not_eq

  let rec print_morph : type a b l r.
      b obj -> Fmt.formatter -> (a, b, l * r) morph -> unit =
   fun dst ppf -> function
    | Id -> Fmt.fprintf ppf "id"
    | Meet_const c -> Fmt.fprintf ppf "meet_const(%a)" (print dst) c
    | Imply_const c -> Fmt.fprintf ppf "imply_const(%a)" (print dst) c
    | Proj (_, ax) -> Fmt.fprintf ppf "proj_%a" Axis.print ax
    | Max_with ax -> Fmt.fprintf ppf "max_with_%a" Axis.print ax
    | Min_with ax -> Fmt.fprintf ppf "min_with_%a" Axis.print ax
    | Map_comonadic f ->
      let dst0 = proj_obj Areality dst in
      Fmt.fprintf ppf "map_comonadic(%a)" (print_morph dst0) f
    | Monadic_to_comonadic_min -> Fmt.fprintf ppf "monadic_to_comonadic_min"
    | Comonadic_to_monadic_min _ -> Fmt.fprintf ppf "comonadic_to_monadic_min"
    | Comonadic_to_monadic_max _ -> Fmt.fprintf ppf "comonadic_to_monadic_max"
    | Monadic_to_comonadic_max -> Fmt.fprintf ppf "monadic_to_comonadic_max"
    | Local_to_regional -> Fmt.fprintf ppf "local_to_regional"
    | Regional_to_local -> Fmt.fprintf ppf "regional_to_local"
    | Locality_as_regionality -> Fmt.fprintf ppf "locality_as_regionality"
    | Regional_to_global -> Fmt.fprintf ppf "regional_to_global"
    | Global_to_regional -> Fmt.fprintf ppf "global_to_regional"
    | Compose (f1, f2) ->
      let mid = src dst f1 in
      Fmt.fprintf ppf "%a ∘ %a" (print_morph dst) f1 (print_morph mid) f2

  let id = Id

  let linear_to_unique = function
    | Linearity.Many -> Uniqueness.Aliased
    | Linearity.Once -> Uniqueness.Unique

  let unique_to_linear = function
    | Uniqueness.Unique -> Linearity.Once
    | Uniqueness.Aliased -> Linearity.Many

  let portable_to_contended = function
    | Portability.Portable -> Contention.Contended
    | Portability.Shareable -> Contention.Shared
    | Portability.Corruptible -> Contention.Corrupted
    | Portability.Nonportable -> Contention.Uncontended

  let contended_to_portable = function
    | Contention.Contended -> Portability.Portable
    | Contention.Shared -> Portability.Shareable
    | Contention.Corrupted -> Portability.Corruptible
    | Contention.Uncontended -> Portability.Nonportable

  let local_to_regional = function
    | Locality.Global -> Regionality.Global
    | Locality.Local -> Regionality.Regional

  let regional_to_local = function
    | Regionality.Local -> Locality.Local
    | Regionality.Regional -> Locality.Local
    | Regionality.Global -> Locality.Global

  let locality_as_regionality = function
    | Locality.Local -> Regionality.Local
    | Locality.Global -> Regionality.Global

  let regional_to_global = function
    | Regionality.Local -> Locality.Local
    | Regionality.Regional -> Locality.Global
    | Regionality.Global -> Locality.Global

  let global_to_regional = function
    | Locality.Local -> Regionality.Local
    | Locality.Global -> Regionality.Regional

  let statefulness_to_visibility = function
    | Statefulness.Stateless -> Visibility.Immutable
    | Statefulness.Writing -> Visibility.Write
    | Statefulness.Reading -> Visibility.Read
    | Statefulness.Stateful -> Visibility.Read_write

  let visibility_to_statefulness = function
    | Visibility.Immutable -> Statefulness.Stateless
    | Visibility.Read -> Statefulness.Reading
    | Visibility.Write -> Statefulness.Writing
    | Visibility.Read_write -> Statefulness.Stateful

  let min_with dst ax a = Axis.set ax a (min dst)

  let max_with dst ax a = Axis.set ax a (max dst)

  let monadic_to_comonadic_min : type a.
      a comonadic_with obj -> Monadic_op.t -> a comonadic_with =
   fun obj m ->
    let areality : a =
      match obj with
      | Comonadic_with_locality -> Locality.min
      | Comonadic_with_regionality -> Regionality.min
    in
    let linearity = unique_to_linear m.uniqueness in
    let portability = contended_to_portable m.contention in
    let forkable = Forkable.min in
    let yielding = Yielding.min in
    let statefulness = visibility_to_statefulness m.visibility in
    { areality; linearity; portability; forkable; yielding; statefulness }

  let comonadic_to_monadic_min : type a.
      a comonadic_with obj -> a comonadic_with -> Monadic_op.t =
   fun _ m ->
    let uniqueness = linear_to_unique m.linearity in
    let contention = portable_to_contended m.portability in
    let visibility = statefulness_to_visibility m.statefulness in
    let staticity = Staticity_op.min in
    { uniqueness; contention; visibility; staticity }

  let comonadic_to_monadic_max : type a.
      a comonadic_with obj -> a comonadic_with -> Monadic_op.t =
   fun _ m ->
    let uniqueness = linear_to_unique m.linearity in
    let contention = portable_to_contended m.portability in
    let visibility = statefulness_to_visibility m.statefulness in
    let staticity = Staticity_op.max in
    { uniqueness; contention; visibility; staticity }

  let monadic_to_comonadic_max : type a.
      a comonadic_with obj -> Monadic_op.t -> a comonadic_with =
   fun obj m ->
    let areality : a =
      match obj with
      | Comonadic_with_locality -> Locality.max
      | Comonadic_with_regionality -> Regionality.max
    in
    let linearity = unique_to_linear m.uniqueness in
    let portability = contended_to_portable m.contention in
    let forkable = Forkable.max in
    let yielding = Yielding.max in
    let statefulness = visibility_to_statefulness m.visibility in
    { areality; linearity; portability; forkable; yielding; statefulness }

  let rec apply : type a b l r. b obj -> (a, b, l * r) morph -> a -> b =
   fun dst f a ->
    match f with
    | Compose (f, g) ->
      let mid = src dst f in
      let g' = apply mid g in
      let f' = apply dst f in
      f' (g' a)
    | Id -> a
    | Proj (_, ax) -> Axis.proj ax a
    | Max_with ax -> max_with dst ax a
    | Min_with ax -> min_with dst ax a
    | Meet_const c -> meet dst c a
    | Imply_const c -> imply dst c a
    | Monadic_to_comonadic_min -> monadic_to_comonadic_min dst a
    | Comonadic_to_monadic_min src -> comonadic_to_monadic_min src a
    | Comonadic_to_monadic_max src -> comonadic_to_monadic_max src a
    | Monadic_to_comonadic_max -> monadic_to_comonadic_max dst a
    | Local_to_regional -> local_to_regional a
    | Regional_to_local -> regional_to_local a
    | Locality_as_regionality -> locality_as_regionality a
    | Regional_to_global -> regional_to_global a
    | Global_to_regional -> global_to_regional a
    | Map_comonadic f ->
      let dst0 = proj_obj Areality dst in
      let a0 = Axis.proj Areality a in
      set_areality (apply dst0 f a0) a

  module For_hint = struct
    (** Describes the portion of the input that's responsible for a portion of
        the output of a morphism *)
    type 'a responsible_axis =
      | NoneResponsible : 'a responsible_axis
          (** The input is not responsible for the output; instead, the morphism
              is solely responsible for the output. *)
      | SourceIsSingle : 'a responsible_axis
          (** The input of the morphism is single axis, and is responsible for
              the output. *)
      | Axis : ('a, 'a_x) Axis.t -> 'a responsible_axis
          (** The specified axis of the input object is responsible for the
              output. *)

    (* CR zqian: the following functions are hard to write, and are redundant since all
       the information are already in [apply]. A general and simpler apporach would work
       like this: Say we have [b = f a] on RHS, and we want to figure out which axis of
       [a] is responsible for a specific axis [ax] of [b] being low. We will iterate
       through all axes; for each axis, set that to [max] and get [a'], and calculate [b'
       = f a']. If [b'] is not strictly higher than [b] on [ax], then the current axis of
       [a] is not responsible for the [ax] of [b] being low. The iteration might end with
       no axis of [a] being responsible, in which case the morphism is solely
       respoonsible. *)

    (** Given a morphism either from a single axis to a single axis, or from a
        product object to a single axis, return the portion of the input that's
        responsible for the output. *)
    let rec find_responsible_axis_single : type a b l r.
        (a, b, l * r) morph -> a responsible_axis = function
      | Proj (_a_obj, ax) -> Axis ax
      | Compose (g, f) -> (
        match find_responsible_axis_single g with
        | NoneResponsible -> NoneResponsible
        | SourceIsSingle -> find_responsible_axis_single f
        | Axis c_ax -> find_responsible_axis_prod f c_ax)
      | Id | Meet_const _ | Imply_const _ -> SourceIsSingle
      | Max_with _ | Min_with _ | Map_comonadic _ | Monadic_to_comonadic_min
      | Comonadic_to_monadic_min _ | Monadic_to_comonadic_max
      | Comonadic_to_monadic_max _ ->
        assert false
      | Local_to_regional | Regional_to_local | Locality_as_regionality
      | Regional_to_global | Global_to_regional ->
        SourceIsSingle

    (** Given a morphism either from a single axis to a product, or from a
        product to a product, return the portion of the input that's responsible
        for the specified axis of the output. *)
    and find_responsible_axis_prod : type a b b_ax l r.
        (a, b, l * r) morph -> (b, b_ax) Axis.t -> a responsible_axis =
     fun m ax ->
      let handle_monadic_to_comonadic (type x y)
          (ax : (x comonadic_with, y) Axis.t) =
        (* See [Lattices_mono.monadic_to_comonadic_min] for why these are as they are *)
        match ax with
        | Areality -> NoneResponsible
        | Linearity -> Axis Uniqueness
        | Portability -> Axis Contention
        | Forkable -> NoneResponsible
        | Yielding -> NoneResponsible
        | Statefulness -> Axis Visibility
      in
      let handle_comonadic_to_monadic (type y) (ax : (monadic, y) Axis.t) =
        (* See [Lattices_mono.comonadic_to_monadic_min] for why these are as they are *)
        match ax with
        | Uniqueness -> Axis Linearity
        | Contention -> Axis Portability
        | Visibility -> Axis Statefulness
        | Staticity -> NoneResponsible
      in
      match m, ax with
      | Compose (g, f), ax -> (
        (* Operates similarly to the equivalent branch in [find_responsible_axis_single] *)
        match find_responsible_axis_prod g ax with
        | NoneResponsible -> NoneResponsible
        | SourceIsSingle -> find_responsible_axis_single f
        | Axis c_ax -> find_responsible_axis_prod f c_ax)
      | Id, ax -> Axis ax
      | Meet_const _, ax -> Axis ax
      | Imply_const _, ax -> Axis ax
      | Map_comonadic _, ax -> (
        (* The [Map_comonadic] morphism applies a morphsim to the areality axis and
           the result is put back into the areality axis. See [Lattices_mono.apply] *)
        match ax with
        | Areality -> Axis Areality
        | Forkable -> Axis Forkable
        | Yielding -> Axis Yielding
        | Linearity -> Axis Linearity
        | Statefulness -> Axis Statefulness
        | Portability -> Axis Portability)
      | Max_with m_ax, ax | Min_with m_ax, ax -> (
        match Axis.equal m_ax ax with
        | Is_not_eq -> NoneResponsible
        | Is_eq -> SourceIsSingle)
      | Monadic_to_comonadic_min, ax -> handle_monadic_to_comonadic ax
      | Monadic_to_comonadic_max, ax -> handle_monadic_to_comonadic ax
      | Comonadic_to_monadic_min _, ax -> handle_comonadic_to_monadic ax
      | Comonadic_to_monadic_max _, ax -> handle_comonadic_to_monadic ax
      | Proj _, _
      | Local_to_regional, _
      | Regional_to_local, _
      | Locality_as_regionality, _
      | Regional_to_global, _
      | Global_to_regional, _ ->
        .
  end

  (** Compose m1 after m2. Returns [Some f] if the composition can be
      represented by [f] instead of [Compose m1 m2]. [None] otherwise. *)
  let rec maybe_compose : type a b c l r.
      c obj ->
      (b, c, l * r) morph ->
      (a, b, l * r) morph ->
      (a, c, l * r) morph option =
   fun dst m1 m2 ->
    let is_max c = le dst (max dst) c in
    let is_mid_max c =
      let mid = src dst m1 in
      le mid (max mid) c
    in
    match m1, m2 with
    | Id, m -> Some m
    | m, Id -> Some m
    | Meet_const c1, Meet_const c2 -> Some (Meet_const (meet dst c1 c2))
    | Imply_const c1, Imply_const c2 -> Some (Imply_const (meet dst c1 c2))
    | Imply_const c1, Meet_const c2 when le dst c1 c2 -> Some (Imply_const c1)
    | Meet_const c1, m2 when is_max c1 -> Some m2
    | Imply_const c1, m2 when is_max c1 -> Some m2
    | m2, Meet_const c1 when is_mid_max c1 -> Some m2
    | m2, Imply_const c1 when is_mid_max c1 -> Some m2
    | Compose (f1, f2), g -> (
      let mid = src dst f1 in
      match maybe_compose mid f2 g with
      | Some m -> Some (compose dst f1 m)
      (* the check needed to prevent infinite loop *)
      | None -> None)
    | f, Compose (g1, g2) -> (
      match maybe_compose dst f g1 with
      | Some m -> Some (compose dst m g2)
      | None -> None)
    | Proj (mid, ax), Meet_const c ->
      Some (compose dst (Meet_const (Axis.proj ax c)) (Proj (mid, ax)))
    | Proj (_, ax1), Max_with ax2 -> (
      match Axis.equal ax1 ax2 with Is_not_eq -> None | Is_eq -> Some Id)
    | Proj (_, ax1), Min_with ax2 -> (
      match Axis.equal ax1 ax2 with Is_not_eq -> None | Is_eq -> Some Id)
    | Proj (mid, ax), Map_comonadic f -> (
      let src' = src mid m2 in
      match ax with
      | Areality -> Some (compose dst f (Proj (src', Areality)))
      | Linearity -> Some (Proj (src', Linearity))
      | Portability -> Some (Proj (src', Portability))
      | Forkable -> Some (Proj (src', Forkable))
      | Yielding -> Some (Proj (src', Yielding))
      | Statefulness -> Some (Proj (src', Statefulness)))
    | Proj _, Monadic_to_comonadic_min -> None
    | Proj _, Monadic_to_comonadic_max -> None
    | Proj _, Comonadic_to_monadic_min _ -> None
    | Proj _, Comonadic_to_monadic_max _ -> None
    | Map_comonadic f, Map_comonadic g ->
      let dst0 = proj_obj Areality dst in
      Some (Map_comonadic (compose dst0 f g))
    | Regional_to_local, Local_to_regional -> Some Id
    | Regional_to_local, Global_to_regional ->
      Some (Imply_const Locality.Global)
    | Regional_to_local, Locality_as_regionality -> Some Id
    | Regional_to_local, Meet_const c ->
      Some (compose dst (Meet_const (regional_to_local c)) Regional_to_local)
    | Regional_to_global, Meet_const c ->
      Some (compose dst (Meet_const (regional_to_global c)) Regional_to_global)
    | Local_to_regional, Meet_const c ->
      Some (compose dst (Meet_const (local_to_regional c)) Local_to_regional)
    | Global_to_regional, Meet_const c ->
      Some (compose dst (Meet_const (global_to_regional c)) Global_to_regional)
    | Locality_as_regionality, Meet_const c ->
      Some
        (compose dst
           (Meet_const (locality_as_regionality c))
           Locality_as_regionality)
    | Map_comonadic f, Meet_const c ->
      let dst0 = proj_obj Areality dst in
      let areality = Axis.proj Areality c in
      Some
        (compose dst
           (Meet_const (set_areality (max dst0) c))
           (Map_comonadic (compose dst0 f (Meet_const areality))))
    | Map_comonadic f, Imply_const c ->
      let dst0 = proj_obj Areality dst in
      let areality = Axis.proj Areality c in
      Some
        (compose dst
           (Imply_const (set_areality (max dst0) c))
           (Map_comonadic (compose dst0 f (Imply_const areality))))
    | Regional_to_global, Locality_as_regionality -> Some Id
    | Regional_to_global, Local_to_regional -> Some (Meet_const Locality.Global)
    | Local_to_regional, Regional_to_local -> None
    | Local_to_regional, Regional_to_global -> None
    | Locality_as_regionality, Regional_to_local -> None
    | Locality_as_regionality, Regional_to_global -> None
    | Global_to_regional, Regional_to_local -> None
    | Regional_to_global, Global_to_regional -> Some Id
    | Global_to_regional, Regional_to_global -> None
    | Min_with _, _ -> None
    | Max_with _, _ -> None
    | _, Meet_const _ -> None
    | Meet_const _, _ -> None
    | _, Imply_const _ -> None
    | Imply_const _, _ -> None
    | _, Proj _ -> None
    | Map_comonadic _, _ -> None
    | Monadic_to_comonadic_min, _ -> None
    | Monadic_to_comonadic_max, _ -> None
    | Comonadic_to_monadic_min _, _ -> None
    | Comonadic_to_monadic_max _, _ -> None
    | ( Proj _,
        ( Local_to_regional | Regional_to_local | Locality_as_regionality
        | Regional_to_global | Global_to_regional ) ) ->
      .
    | ( ( Local_to_regional | Regional_to_local | Locality_as_regionality
        | Regional_to_global | Global_to_regional ),
        Min_with _ ) ->
      .
    | ( ( Local_to_regional | Regional_to_local | Locality_as_regionality
        | Regional_to_global | Global_to_regional ),
        Max_with _ ) ->
      .

  and compose : type a b c l r.
      c obj -> (b, c, l * r) morph -> (a, b, l * r) morph -> (a, c, l * r) morph
      =
   fun dst f g ->
    match maybe_compose dst f g with Some m -> m | None -> Compose (f, g)

  let rec left_adjoint : type a b l.
      b obj -> (a, b, l * allowed) morph -> (b, a, allowed * disallowed) morph =
   fun dst f ->
    match f with
    | Id -> Id
    | Proj (_, ax) -> Min_with ax
    | Max_with ax -> Proj (dst, ax)
    | Compose (f, g) ->
      let mid = src dst f in
      let f' = left_adjoint dst f in
      let g' = left_adjoint mid g in
      Compose (g', f')
    | Meet_const _c ->
      (* The downward closure of [Meet_const c]'s image is all [x <= c].
         For those, [x <= meet c y] is equivalent to [x <= y]. *)
      Id
    | Imply_const c -> Meet_const c
    | Comonadic_to_monadic_max _ -> Monadic_to_comonadic_min
    | Monadic_to_comonadic_max -> Comonadic_to_monadic_min dst
    | Global_to_regional -> Regional_to_global
    | Regional_to_global -> Locality_as_regionality
    | Locality_as_regionality -> Regional_to_local
    | Regional_to_local -> Local_to_regional
    | Map_comonadic f ->
      let dst0 = proj_obj Areality dst in
      let f' = left_adjoint dst0 f in
      Map_comonadic f'

  and right_adjoint : type a b r.
      b obj -> (a, b, allowed * r) morph -> (b, a, disallowed * allowed) morph =
   fun dst f ->
    match f with
    | Id -> Id
    | Proj (_, ax) -> Max_with ax
    | Min_with ax -> Proj (dst, ax)
    | Compose (f, g) ->
      let mid = src dst f in
      let f' = right_adjoint dst f in
      let g' = right_adjoint mid g in
      Compose (g', f')
    | Meet_const c -> Imply_const c
    | Comonadic_to_monadic_min _ -> Monadic_to_comonadic_max
    | Monadic_to_comonadic_min -> Comonadic_to_monadic_max dst
    | Local_to_regional -> Regional_to_local
    | Regional_to_local -> Locality_as_regionality
    | Locality_as_regionality -> Regional_to_global
    | Regional_to_global -> Global_to_regional
    | Map_comonadic f ->
      let dst0 = proj_obj Areality dst in
      let f' = right_adjoint dst0 f in
      Map_comonadic f'
end

module C = Lattices_mono
module S = Solver_mono (Hint_for_solver) (C)

let erase_hints () = S.erase_hints ()

type monadic = C.monadic =
  { uniqueness : C.Uniqueness.t;
    contention : C.Contention.t;
    visibility : C.Visibility.t;
    staticity : C.Staticity.t
  }

type 'a comonadic_with = 'a C.comonadic_with =
  { areality : 'a;
    linearity : C.Linearity.t;
    portability : C.Portability.t;
    forkable : C.Forkable.t;
    yielding : C.Yielding.t;
    statefulness : C.Statefulness.t
  }

module Axis = C.Axis

type nonrec 'a simple_error = 'a simple_error

let print_longident =
  ref (fun _ _ -> assert false : Fmt.formatter -> Longident.t -> unit)

module Report = struct
  open Hint

  (** Human-readable mode error hints. Compared to [S.error]:
      - This doesn't contain branch, and thus forms a chain.
      - Each node on the chain talks about a single axis, instead of potentially
        on a product lattice. *)
  type 'd hint =
    | Apply : 'd morph * 'b C.obj * ('b, 'd) ahint -> 'd hint
    | Const : 'd const -> 'd hint
    | Irrelevant : ('l * 'r) hint
        (** The current mode is not responsible for the error (that is, the
            surrounding morphism is solely responsible), and should not be
            printed. *)
    constraint 'd = 'l * 'r
  [@@ocaml.warning "-62"]

  and ('a, 'd) ahint = 'a * 'd hint constraint 'd = 'l * 'r

  (** Human-readible mode error report. *)
  type 'a t =
    { left : loosening * ('a, left_only) ahint;
      right : loosening * ('a, right_only) ahint
    }

  (** Convert Solver error to report. *)
  module Of_solver = struct
    (** Given a branch of two constant bounds on a single axis, choose the the
        one that's responsible for the branch. *)
    let choose_branch_axis : type a l r.
        (l * r) Solver_intf.branch ->
        a C.obj ->
        a ->
        a ->
        other:a ->
        [`First | `Second] =
     fun b a_obj x y ~other ->
      (* CR-someday zqian: in the case where each of [x] and [y] can be
         responsible independently, for not satisfying [~other], we currently
         arbitrarily prioritize `Second. In the future we might want to
         prioritize for better error messages. For example, prioritize the first
         element in a [join]. This requires inspecting the [solver.ml] to ensure
         the ordering in the [join] list is preserved. *)
      match b with
      | Meet ->
        if C.le a_obj other x
        then begin
          assert (not (C.le a_obj other y));
          `Second
        end
        else `First
      | Join ->
        if C.le a_obj x other
        then begin
          assert (not (C.le a_obj y other));
          `Second
        end
        else `First

    type 'd side =
      | Left : left_only side
      | Right : right_only side
      constraint 'd = 'l * 'r
    [@@ocaml.warning "-62"]

    let adjoint : type a b l r.
        a C.obj ->
        (l * r) side ->
        (b, a, l * r) C.morph ->
        (a, b, r * l) C.morph =
     fun obj side morph ->
      match side with
      | Left -> C.right_adjoint obj morph
      | Right -> C.left_adjoint obj morph

    (** Given a solver hint on a product lattice, and an axis in that product
        that we are interested in, returns a human-readible hint.*)
    let rec hint_apply : type a b l r.
        a C.obj ->
        (l * r) side ->
        a ->
        (l * r) morph ->
        (b, a, l * r) C.morph ->
        other:a ->
        (b, l * r) S.ahint ->
        b C.For_hint.responsible_axis ->
        (a, l * r) ahint =
     fun obj side a morph_hint morph ~other ahint res ->
      let src = C.src obj morph in
      match res with
      | NoneResponsible -> a, Irrelevant
      | SourceIsSingle ->
        let morph' = adjoint obj side morph in
        let other = C.apply src morph' other in
        let ahint = hint_axis src side ~other ahint in
        let ma = C.apply obj morph (fst ahint) in
        ma, Apply (morph_hint, src, ahint)
      | Axis ax ->
        let b, hint = ahint in
        let morph' = adjoint obj side morph in
        let other = C.apply src morph' other in
        let x, hint = hint_prod src side ax ~other (b, hint) in
        let b = C.Axis.set ax x b in
        let a = C.apply obj morph b in
        let src = C.proj_obj ax src in
        a, Apply (morph_hint, src, (x, hint))

    and hint_prod : type t a l r.
        t C.obj ->
        (l * r) side ->
        (t, a) Axis.t ->
        other:t ->
        (t, l * r) S.ahint ->
        (a, l * r) ahint =
     fun obj side ax ~other (a, hint) ->
      match hint with
      | Apply (morph_hint, morph, ahint) ->
        let t, hint =
          hint_apply obj side a morph_hint morph ~other ahint
            (C.For_hint.find_responsible_axis_prod morph ax)
        in
        Axis.proj ax t, hint
      | Const c -> Axis.proj ax a, Const c
      | Branch (b, (a1, hint1), (a2, hint2)) ->
        let chosen_ahint =
          let other = Axis.proj ax other in
          let proj1 = Axis.proj ax a1 in
          let proj2 = Axis.proj ax a2 in
          let obj = C.proj_obj ax obj in
          match choose_branch_axis b obj proj1 proj2 ~other with
          | `First -> a1, hint1
          | `Second -> a2, hint2
        in
        hint_prod obj side ax ~other chosen_ahint

    (** Given a solver hint on a single axis lattice, returns a human-readible
        hint. *)
    and hint_axis : type a l r.
        a C.obj ->
        (l * r) side ->
        other:a ->
        (a, l * r) S.ahint ->
        (a, l * r) ahint =
     fun obj side ~other (a, hint) ->
      match hint with
      | Apply (morph_hint, morph, ahint) ->
        hint_apply obj side a morph_hint morph ~other ahint
          (C.For_hint.find_responsible_axis_single morph)
      | Const c -> a, Const c
      | Branch (b, (a1, hint1), (a2, hint2)) ->
        let chosen_ahint =
          match choose_branch_axis b obj a1 a2 ~other with
          | `First -> a1, hint1
          | `Second -> a2, hint2
        in
        hint_axis obj side ~other chosen_ahint

    let hint_prod_loosening : type t a l r.
        t C.obj ->
        (l * r) side ->
        (t, a) Axis.t ->
        other:t ->
        (t, l * r) S.ahint ->
        loosening * (a, l * r) ahint =
     fun obj side ax ~other ((t, _) as ahint) ->
      let axis_obj = C.proj_obj ax obj in
      let a, hint = hint_prod obj side ax ~other ahint in
      let loosening =
        if Misc.Le_result.equal ~le:(C.le axis_obj) a (Axis.proj ax t)
        then Not_loosened
        else Loosened
      in
      loosening, (a, hint)

    let hint_axis_loosening : type a l r.
        a C.obj ->
        (l * r) side ->
        other:a ->
        (a, l * r) S.ahint ->
        loosening * (a, l * r) ahint =
     fun obj side ~other ((original, _) as ahint) ->
      let a, hint = hint_axis obj side ~other ahint in
      let loosening =
        if Misc.Le_result.equal ~le:(C.le obj) a original
        then Not_loosened
        else Loosened
      in
      loosening, (a, hint)

    let error_prod : type r a. r C.obj -> (r, a) Axis.t -> r S.error -> a t =
     fun obj axis { left; right } ->
      let left = hint_prod_loosening obj Left axis ~other:(fst right) left in
      let right =
        hint_prod_loosening obj Right axis
          ~other:(Axis.set axis (fst (snd left)) (fst right))
          right
      in
      { left; right }

    let error_axis : type a. a C.obj -> a S.error -> a t =
     fun obj { left; right } ->
      let left = hint_axis_loosening obj Left ~other:(fst right) left in
      let right = hint_axis_loosening obj Right ~other:(fst (snd left)) right in
      { left; right }
  end

  [@@@warning "-4"]

  type sound =
    | Consonant
    | Vowel

  let print_article_noun ~definite ~capitalize sound s =
    let article =
      match definite, sound with
      | true, _ -> "the"
      | false, Consonant -> "a"
      | false, Vowel -> "an"
    in
    let article =
      if capitalize then String.capitalize_ascii article else article
    in
    Fmt.dprintf "%s %s" article s

  let print_lock_item : lock_item -> _ = function
    | Module -> print_article_noun Consonant "module"
    | Class -> print_article_noun Consonant "class"
    | Value -> print_article_noun Consonant "value"
    | Constructor -> print_article_noun Consonant "constructor"

  let print_structure_item : structure_item -> _ =
   fun (category, id) ~capitalize ->
    Fmt.dprintf "%t %a"
      (print_lock_item ~definite:true ~capitalize category)
      Misc.Style.inline_code (Ident.name id)

  let print_pinpoint_desc : pinpoint_desc -> _ = function
    | Unknown -> None
    | Ident { category; lid } ->
      Some
        (fun ~definite ~capitalize ->
          Fmt.dprintf "%t %a"
            (print_lock_item ~definite ~capitalize category)
            (Misc.Style.as_inline_code !print_longident)
            lid)
    | Function -> Some (print_article_noun Consonant "function")
    | Functor -> Some (print_article_noun Consonant "functor")
    | Lazy -> Some (print_article_noun Consonant "lazy expression")
    | Quote -> Some (print_article_noun Consonant "quoted expression")
    | Expression -> Some (print_article_noun Vowel "expression")
    | Allocation -> Some (print_article_noun Vowel "allocation")
    | Class -> Some (print_article_noun Consonant "class")
    | Object -> Some (print_article_noun Vowel "object")
    | Loop -> Some (print_article_noun Consonant "loop")
    | Letop -> Some (print_article_noun Consonant "letop")
    | Cases_result ->
      Some
        (fun ~definite ~capitalize ->
          Fmt.dprintf "%t of %t"
            (print_article_noun ~definite:true ~capitalize Consonant "result")
            (print_article_noun ~definite ~capitalize:false Consonant "cases"))
    | Pattern -> Some (print_article_noun Consonant "pattern")
    | Module -> Some (print_article_noun Consonant "module")
    | Structure -> Some (print_article_noun Consonant "structure")
    | Structure_item x ->
      Some
        (fun ~definite:_ ~capitalize ->
          Fmt.dprintf "%t in the structure" (print_structure_item ~capitalize x))

  let print_pinpoint : pinpoint -> _ =
   fun (loc, desc) ->
    print_pinpoint_desc desc
    |> Option.map (fun print_desc ~definite ~capitalize ppf ->
        match Location.is_none loc, definite with
        | true, _ -> print_desc ~definite:false ~capitalize ppf
        | false, true ->
          Fmt.fprintf ppf "%t at %a"
            (print_desc ~definite ~capitalize)
            (Location.Doc.loc ~capitalize_first:false)
            loc
        | false, false ->
          Fmt.fprintf ppf "%t (at %a)"
            (print_desc ~definite ~capitalize)
            (Location.Doc.loc ~capitalize_first:false)
            loc)

  let is_known_pinpoint : pinpoint -> bool = function
    | _, Unknown -> false
    | _ -> true

  let print_mutable_part ppf = function
    | Record_field s ->
      Fmt.fprintf ppf "mutable field %a" Misc.Style.inline_code s
    | Array_elements -> Fmt.fprintf ppf "array elements"

  let print_always_dynamic = function
    | Application -> Fmt.dprintf "function applications"
    | Try_with -> Fmt.dprintf "try-with clauses"

  let print_legacy = function
    | Toplevel -> print_article_noun Consonant "top-level clause"
    | Compilation_unit -> print_article_noun Consonant "compilation unit"
    | Class -> print_article_noun Consonant "class"
    | Quoted -> print_article_noun Consonant "quoted expression's result"

  let print_region_desc : region_desc -> _ = function
    | Borrow -> print_article_noun Consonant "borrow region"

  let print_region : capitalize:_ -> region -> _ =
   fun ~capitalize (loc, desc) ->
    Fmt.dprintf "%t at %a"
      (print_region_desc desc ~definite:true ~capitalize)
      (Location.Doc.loc ~capitalize_first:false)
      loc

  (** Given a pinpoint and a const, where the pinpoint has been expressed,
      prints the const to explain the mode on the pinpoint. *)
  let print_const (type l r) ((_, pp_desc) : pinpoint) ppf :
      (l * r) const -> unit = function
    | Unknown -> Misc.fatal_error "Unknown hint should not be printed"
    | Lazy_allocated_on_heap ->
      (match pp_desc with
      | Lazy ->
        (* if we already said it's a lazy, we don't need to emphasize it again. *)
        Fmt.pp_print_string ppf "lazy expressions always need"
      | _ -> Fmt.pp_print_string ppf "it is a lazy expression and thus needs");
      Fmt.pp_print_string ppf " to be allocated on the heap"
    | Legacy m ->
      (match pp_desc, m with
      | ( (Ident { category = Class; _ } | Class | Structure_item (Class, _)),
          Class ) ->
        (* if we already said it's a class, we don't need to emphasize it again. *)
        Fmt.pp_print_string ppf "classes are always"
      | _ ->
        Fmt.fprintf ppf "it is %t and thus always"
          (print_legacy m ~definite:false ~capitalize:false));
      Fmt.pp_print_string ppf " at the legacy modes"
    | Toplevel_expression ->
      Fmt.pp_print_string ppf "it is a top-level expression"
    | Tailcall_function ->
      Fmt.pp_print_string ppf "it is the function in a tail call"
    | Tailcall_argument ->
      Fmt.pp_print_string ppf "it is an argument in a tail call"
    | Mutable_read m ->
      Fmt.fprintf ppf "its %a is being read" print_mutable_part m
    | Mutable_write m ->
      Fmt.fprintf ppf "its %a is being written" print_mutable_part m
    | Lazy_forced -> (
      match pp_desc with
      | Lazy ->
        (* if we already said it's a lazy, we don't need to emphasize it again. *)
        Fmt.pp_print_string ppf "it is being forced"
      | _ -> Fmt.pp_print_string ppf "it is a lazy value being forced")
    | Function_return ->
      Fmt.fprintf ppf
        "it is a function return value.@ Hint: Use exclave_ to return a local \
         value"
    | Stack_expression ->
      Fmt.fprintf ppf "it is %a-allocated" Misc.Style.inline_code "stack_"
    | Module_allocated_on_heap ->
      (match pp_desc with
      | Ident { category = Module; _ }
      | Functor | Module | Structure
      | Structure_item (Module, _) ->
        (* if we already said it's a module, we don't need to emphasize it again. *)
        Fmt.pp_print_string ppf "modules always need"
      | _ -> Fmt.pp_print_string ppf "it is a module and thus needs");
      Fmt.pp_print_string ppf " to be allocated on the heap"
    | Is_used_in pp ->
      let print_pp = print_pinpoint pp |> Option.get in
      Fmt.fprintf ppf "it is used in %t"
        (print_pp ~definite:false ~capitalize:false)
    | Always_dynamic x ->
      Fmt.fprintf ppf "%t are always dynamic" (print_always_dynamic x)
    | Branching -> Fmt.fprintf ppf "it has branches"
    | Borrowed _ -> Fmt.fprintf ppf "it is borrowed"
    | Escape_region reg ->
      Fmt.fprintf ppf "it escapes %t" (print_region ~capitalize:false reg)
    | Quoted_computation -> Fmt.fprintf ppf "it is the quote of a computation"
    | Lpoly_inst ->
      Fmt.pp_print_string ppf
        "it is layout-polymorphic and being instantiated here"
    | Spliced _ -> Fmt.fprintf ppf "it is spliced"

  let print_allocation_l : allocation -> Fmt.formatter -> unit =
   fun { txt; loc } ->
    match txt with
    | Unknown ->
      Fmt.dprintf "is allocated at %a containing data"
        (Location.Doc.loc ~capitalize_first:false)
        loc
    | Optional_argument ->
      Fmt.dprintf
        "is an optional argument wrapper (and thus allocated) of the value at \
         %a"
        (Location.Doc.loc ~capitalize_first:false)
        loc
    | Function_coercion ->
      Fmt.dprintf
        "is a partial application of the function at %a on omittable parameters"
        (Location.Doc.loc ~capitalize_first:false)
        loc
    | Float_projection ->
      Fmt.dprintf
        "is projected (at %a) from a float record (and thus allocated)"
        (Location.Doc.loc ~capitalize_first:false)
        loc
    | Lpoly_captured_environment ->
      Fmt.dprintf "is defined by a layout-polymorphic expression (at %a)"
        (Location.Doc.loc ~capitalize_first:false)
        loc

  let print_allocation_r : allocation -> Fmt.formatter -> unit =
   fun { txt; _ } ->
    match txt with
    | Unknown -> Fmt.dprintf "is an allocation"
    | Optional_argument ->
      Fmt.dprintf
        "is to be put in an optional argument wrapper (and thus an allocation)"
    | Function_coercion ->
      Fmt.dprintf
        "is to omit some parameters by partial application (and thus an \
         allocation)"
    | Float_projection ->
      Fmt.dprintf "is a float-record projection (and thus an allocation)"
    | Lpoly_captured_environment ->
      (* currently not testable *)
      Fmt.dprintf "is a layout-polymorphic expression"

  let modality_if_relevant ~fixpoint pp =
    if
      fixpoint
      (* if the modality doesn't change the bound, we omit the modality and
          print the remaining chain. *)
    then (fun _ppf Modality -> ()), pp
    else
      (* if the modality change the bound, we signal that. Moreover, since each
         axis is total ordering, the modality is solely responsible for the
         bound, and we omit the remaining chain. *)
      (* CR-someday zqian: print the modality on the offending axis. *)
      ( (fun ppf Modality -> Fmt.fprintf ppf " (with some modality)"),
        (Location.none, Unknown : pinpoint) )

  let print_contains :
      fixpoint:bool -> contains -> ((Fmt.formatter -> unit) * pinpoint) option =
   fun ~fixpoint { containing; contained } ->
    print_pinpoint contained
    |> Option.map (fun print_pp ->
        let print_pp = print_pp ~definite:true ~capitalize:false in
        let maybe_modality, contained =
          modality_if_relevant ~fixpoint contained
        in
        let pr =
          match containing with
          | Tuple -> Fmt.dprintf "is a tuple that contains %t" print_pp
          | Record (s, moda) ->
            Fmt.dprintf "is a record whose field %a%a is %t"
              Misc.Style.inline_code s maybe_modality moda print_pp
          | Array moda ->
            Fmt.dprintf "is an array that contains%a %t" maybe_modality moda
              print_pp
          | Constructor (s, moda) ->
            Fmt.dprintf "contains (via constructor %a)%a %t"
              Misc.Style.inline_code s maybe_modality moda print_pp
          | Structure (x, moda) ->
            Fmt.dprintf "contains %t%a defined as %t"
              (print_structure_item ~capitalize:false x)
              maybe_modality moda print_pp
        in
        pr, contained)

  let print_is_contained_by :
      fixpoint:bool -> is_contained_by -> (Fmt.formatter -> unit) * pinpoint =
   fun ~fixpoint { containing; container } ->
    let maybe_modality, pp = modality_if_relevant ~fixpoint container in
    (* CR-someday zqian: Use the full [container] to improve the printing below.
       E.g., insted of printing "the tuple at XXX", we can print "the tuple
       pattern at XXX" or "the tuple expression at XXX". *)
    let container = fst container in
    let pr =
      match containing with
      | Tuple ->
        Fmt.dprintf "is an element of the tuple at %a"
          (Location.Doc.loc ~capitalize_first:false)
          container
      | Record (s, moda) ->
        Fmt.dprintf "is the field %a%a of the record at %a"
          Misc.Style.inline_code s maybe_modality moda
          (Location.Doc.loc ~capitalize_first:false)
          container
      | Array moda ->
        Fmt.dprintf "is an element%a of the array at %a" maybe_modality moda
          (Location.Doc.loc ~capitalize_first:false)
          container
      | Constructor (s, moda) ->
        Fmt.dprintf "is contained (via constructor %a)%a in the value at %a"
          Misc.Style.inline_code s maybe_modality moda
          (Location.Doc.loc ~capitalize_first:false)
          container
      | Structure (x, moda) ->
        Fmt.dprintf "is %t%a in the structure at %a"
          (print_structure_item ~capitalize:false x)
          maybe_modality moda
          (Location.Doc.loc ~capitalize_first:false)
          container
    in
    pr, pp

  (** Given a pinpoint and a morph, where the pinpoint is the destination of the
      morph and have been expressed already, print the morph and return the
      source pinpoint. The source pinpoint could be [Unknown], in which case the
      rest of the chain will not be printed. *)
  let print_morph : type l r.
      fixpoint:bool ->
      pinpoint ->
      (l * r) morph ->
      ((Fmt.formatter -> unit) * pinpoint) option =
   fun ~fixpoint pp -> function
    | Skip -> Misc.fatal_error "Skip hint should not be printed"
    | Unknown -> None
    | Close_over (Comonadic, { closed = pp; _ }) ->
      print_pinpoint pp
      |> Option.map (fun print_pp ->
          ( Fmt.dprintf "closes over %t"
              (print_pp ~definite:true ~capitalize:false),
            pp ))
    | Close_over (Monadic, { closed = pp; _ }) ->
      print_pinpoint pp
      |> Option.map (fun print_pp ->
          ( Fmt.dprintf "contains a usage (of %t)"
              (print_pp ~definite:true ~capitalize:false),
            pp ))
    | Is_closed_by (_, { closure = pp; _ }) ->
      print_pinpoint pp
      |> Option.map (fun print_pp ->
          ( Fmt.dprintf "is used inside %t"
              (print_pp ~definite:true ~capitalize:false),
            pp ))
    | Captured_by_partial_application ->
      Some
        ( Fmt.dprintf "is captured by a partial application",
          (Location.none, Expression) )
    | Adj_captured_by_partial_application ->
      Some
        ( Fmt.dprintf "has a partial application capturing a value",
          (Location.none, Expression) )
    | Crossing -> Some (Fmt.dprintf "crosses with something", pp)
    | Allocation_r alloc -> Some (print_allocation_r alloc, pp)
    | Allocation_l alloc -> Some (print_allocation_l alloc, pp)
    | Contains_l (_, contains) -> print_contains ~fixpoint contains
    | Contains_r (_, contains) -> print_contains ~fixpoint contains
    | Is_contained_by (_, is_contained_by) ->
      Some (print_is_contained_by ~fixpoint is_contained_by)

  let print_mode : type a.
      [`Actual | `Expected] -> a C.obj -> Fmt.formatter -> a -> unit =
   fun side obj ppf x ->
    let mode_printer = Misc.Style.as_inline_code (C.print obj) in
    match side, obj, x with
    | `Actual, Regionality, Regional ->
      Fmt.fprintf ppf "%a to the parent region" mode_printer C.Regionality.Local
      (* CR-someday zqian: treat the following cases generally. *)
    | `Expected, Contention_op, Shared ->
      (* When "shared" is expected, we tell the user that either shared or
         uncontended is expected. *)
      Fmt.fprintf ppf "%a or %a" mode_printer C.Contention.Shared mode_printer
        C.Contention.Uncontended
    | `Expected, Contention_op, Corrupted ->
      Fmt.fprintf ppf "%a or %a" mode_printer C.Contention.Corrupted
        mode_printer C.Contention.Uncontended
    | `Expected, Visibility_op, Read ->
      Fmt.fprintf ppf "%a or %a" mode_printer C.Visibility.Read mode_printer
        C.Visibility.Read_write
    | `Expected, Visibility_op, Write ->
      Fmt.fprintf ppf "%a or %a" mode_printer C.Visibility.Write mode_printer
        C.Visibility.Read_write
    | `Expected, Regionality, Regional ->
      Fmt.fprintf ppf "%a to the parent region or %a" mode_printer
        C.Regionality.Local mode_printer C.Regionality.Global
    | _ -> mode_printer ppf x
  [@@ocaml.warning "-4"]

  let adjust_side : type a. a C.obj -> [`Left | `Right] -> [`Actual | `Expected]
      =
   fun obj side ->
    match C.is_opposite obj, side with
    | true, `Left -> `Expected
    | true, `Right -> `Actual
    | false, `Left -> `Actual
    | false, `Right -> `Expected

  let print_mode_with_side : type a.
      sub:bool -> [`Left | `Right] -> a C.obj -> Fmt.formatter -> a -> unit =
   fun ~sub side obj ppf a ->
    let side = adjust_side obj side in
    if sub
    then (
      Fmt.fprintf ppf "@ which ";
      match side with
      | `Actual -> Fmt.pp_print_string ppf "is "
      | `Expected -> Fmt.pp_print_string ppf "is expected to be ");
    print_mode side obj ppf a

  (** Some morph hints are said to be "non-rigid", because they should be
      printed only when they change modes. *)
  let is_rigid : type l r. (l * r) morph -> bool = function
    | Unknown -> true
    | Close_over _ | Is_closed_by _ | Captured_by_partial_application
    | Contains_l _ | Contains_r _ | Is_contained_by _
    | Adj_captured_by_partial_application ->
      true
    | Allocation_r _ | Allocation_l _ | Skip | Crossing -> false

  let equal_mode : type a b. a C.obj -> b C.obj -> a -> b -> bool =
   fun a_obj b_obj a b ->
    match C.equal_obj a_obj b_obj with
    | Misc.Is_eq -> Misc.Le_result.equal ~le:(C.le a_obj) a b
    | Misc.Is_not_eq -> false

  let rec print_ahint : type a l r.
      ?sub:bool ->
      [`Left | `Right] ->
      pinpoint ->
      a C.obj ->
      Fmt.formatter ->
      (a, l * r) ahint ->
      print_error_result option =
   fun ?(sub = false) side pp (obj : a C.obj) ppf (a, hint) ->
    match hint with
    | Apply (morph_hint, src, ahint) ->
      let fixpoint = equal_mode obj src a (fst ahint) in
      if (not (is_rigid morph_hint)) && fixpoint
      then print_ahint ~sub side pp src ppf ahint
      else (
        print_mode_with_side ~sub side obj ppf a;
        match print_morph ~fixpoint pp morph_hint with
        | None -> Some Mode
        | Some (t, pp) ->
          Fmt.fprintf ppf "@ because it %t" t;
          if is_known_pinpoint pp
          then ignore (print_ahint ~sub:true side pp src ppf ahint);
          Some Mode_with_hint)
    | Const Unknown ->
      print_mode_with_side ~sub side obj ppf a;
      Some Mode
    | Irrelevant ->
      if not sub
      then
        Misc.fatal_error
          "the current mode is not responsible for the error, so must be \
           inside a responsible morphism";
      None
    | Const c ->
      Fmt.fprintf ppf "%a@ because %a"
        (print_mode_with_side ~sub side obj)
        a (print_const pp) c;
      Some Mode_with_hint
  [@@ocaml.warning "-4"]

  let print_ahint_loosening : type a l r.
      [`Left | `Right] ->
      pinpoint ->
      a C.obj ->
      Fmt.formatter ->
      loosening ->
      (a, l * r) ahint ->
      print_error_result option =
   fun side pp obj ppf loosening ahint ->
    (match loosening with
    | Loosened ->
      begin match adjust_side obj side with
      | `Actual -> Fmt.fprintf ppf "weaker than "
      | `Expected -> Fmt.fprintf ppf "stronger than "
      end
    | Not_loosened -> ());
    print_ahint side pp obj ppf ahint

  type 'a ahint_sided =
    | Left of (loosening * ('a, left_only) ahint)
    | Right of (loosening * ('a, right_only) ahint)

  let print_ahint_sided : type a.
      pinpoint ->
      a C.obj ->
      Fmt.formatter ->
      a ahint_sided ->
      print_error_result option =
   fun pp obj ppf ahint_sided ->
    match ahint_sided with
    | Left (loosening, ahint) ->
      print_ahint_loosening `Left pp obj ppf loosening ahint
    | Right (loosening, ahint) ->
      print_ahint_loosening `Right pp obj ppf loosening ahint

  let print : type a. pinpoint -> a C.obj -> a t -> print_error =
   fun pp obj { left; right } ->
    let actual, expected =
      if C.is_opposite obj
      then Right right, Left left
      else Left left, Right right
    in
    let left ppf = Option.get (print_ahint_sided pp obj ppf actual) in
    let right ppf = Option.get (print_ahint_sided pp obj ppf expected) in
    { left; right }
end

let print_pinpoint = Report.print_pinpoint

type changes = S.changes

let undo_changes = S.undo_changes

(* To be filled in by [types.ml] *)
let append_changes : (changes ref -> unit) ref = ref (fun _ -> assert false)

let set_append_changes f = append_changes := f

type ('a, 'd) mode = ('a, 'd) S.mode

module Error = struct
  type 'a t = 'a S.error_raw

  type packed =
    | Product : 'r C.obj * ('r, 'a) Axis.t * 'r t -> packed
    | Axis : 'a C.obj * 'a t -> packed

  let print_product : type r a.
      Hint.pinpoint -> r C.obj -> (r, a) Axis.t -> r t -> print_error =
   fun pp obj ax err ->
    let err = S.populate_error obj err in
    let err = Report.Of_solver.error_prod obj ax err in
    let obj = C.proj_obj ax obj in
    Report.print pp obj err

  let print_axis : type a. Hint.pinpoint -> a C.obj -> a t -> print_error =
   fun pp obj err ->
    let err = S.populate_error obj err in
    let err = Report.Of_solver.error_axis obj err in
    Report.print pp obj err

  let print_packed : Hint.pinpoint -> packed -> print_error =
   fun pp -> function
    | Product (obj, ax, err) -> print_product pp obj ax err
    | Axis (obj, err) -> print_axis pp obj err

  let print_packed_simple_context : Hint.pinpoint -> packed -> Location.error =
   fun pp packed ->
    let open Format_doc in
    let loc, desc = pp in
    let print ppf () =
      let open_box = Fmt.dprintf "@[<hov 2>" in
      let reopen_box = Fmt.dprintf "@]@ %t" open_box in
      let print_desc = Report.print_pinpoint_desc desc in
      (let print_desc =
         match print_desc with
         | None -> Fmt.dprintf "This"
         | Some print_desc -> print_desc ~definite:true ~capitalize:true
       in
       fprintf ppf "%t%t is " open_box print_desc);
      let ({ left; right } : print_error) = print_packed pp packed in
      (match left ppf with
      | Mode_with_hint ->
        let print_desc =
          match print_desc with
          | None -> Fmt.dprintf "the highlighted"
          | Some print_desc ->
            Fmt.dprintf "%t highlighted"
              (print_desc ~definite:true ~capitalize:false)
        in
        fprintf ppf ".%tHowever, %t is expected to be " reopen_box print_desc
      | Mode -> fprintf ppf "%tbut is expected to be " reopen_box);
      ignore (right ppf);
      fprintf ppf ".@]"
    in
    Location.error_of_printer ~loc print ()
end

exception Submode_error_simple_context of Hint.pinpoint * Error.packed

let () =
  Location.register_error_of_exn (function
    | Submode_error_simple_context (pp, err) ->
      Some (Error.print_packed_simple_context pp err)
    | _ -> None)

module type Common_axis_pos = sig
  module Const : Const

  include
    Common_axis
      with module Const := Const
       and type 'd t = (Const.t, 'd pos) mode
       and type 'd hint_const := 'd pos_hint_const
end

module type Common_axis_neg = sig
  module Const : Const

  include
    Common_axis
      with module Const := Const
       and type 'd t = (Const.t, 'd neg) mode
       and type 'd hint_const := 'd neg_hint_const
end

(** Representing a single object *)
module type Obj = sig
  type const

  val obj : const C.obj
end

let try_with_log op =
  let log' = ref S.empty_changes in
  let log = Some log' in
  match op ~log with
  | Ok _ as x ->
    !append_changes log';
    x
  | Error _ as x ->
    S.undo_changes !log';
    x
[@@inline]

let with_log op =
  let log' = ref S.empty_changes in
  let log = Some log' in
  let r = op ~log in
  !append_changes log';
  r
[@@inline]

let equate_from_submode submode_log m1 m2 ~log =
  match submode_log m1 m2 ~log with
  | Error e -> Error (Left_le_right, e)
  | Ok () -> (
    match submode_log m2 m1 ~log with
    | Error e -> Error (Right_le_left, e)
    | Ok () -> Ok ())
[@@inline]

let equate_from_submode' submode m1 m2 =
  match submode m1 m2 with
  | Error e -> Error (Left_le_right, e)
  | Ok () -> (
    match submode m2 m1 with
    | Error e -> Error (Right_le_left, e)
    | Ok () -> Ok ())
[@@inline]

module Comonadic_gen (Obj : Obj) = struct
  open Obj

  type 'd t = (const, 'l * 'r) S.mode constraint 'd = 'l * 'r

  type l = (allowed * disallowed) t

  type r = (disallowed * allowed) t

  type lr = (allowed * allowed) t

  type nonrec simple_error = const simple_error

  type nonrec error = const Error.t

  type equate_error = equate_step * error

  type (_, _, 'd) sided = 'd t

  let disallow_right m = S.disallow_right m

  let disallow_left m = S.disallow_left m

  let allow_left m = S.allow_left m

  let allow_right m = S.allow_right m

  let newvar () = S.newvar obj

  let min = S.min obj

  let max = S.max obj

  let newvar_above m = S.newvar_above obj m

  let newvar_below m = S.newvar_below obj m

  let submode_log ?(pp = (Location.none, Unknown : Hint.pinpoint)) a b ~log =
    S.submode pp obj a b ~log

  let to_simple_error ({ left; right; _ } : error) : simple_error =
    { left; right }

  let submode ?pp a b = try_with_log (submode_log ?pp a b)

  let submode_err pp a b =
    match submode ~pp a b with
    | Ok () -> ()
    | Error e -> raise (Submode_error_simple_context (pp, Axis (obj, e)))

  let print_error pp err = Error.print_axis pp obj err

  let join l = S.join obj l

  let meet l = S.meet obj l

  let submode_exn ?pp m1 m2 = submode ?pp m1 m2 |> Result.get_ok

  let equate a b = try_with_log (equate_from_submode (submode_log ?pp:None) a b)

  let equate_exn m1 m2 = equate m1 m2 |> Result.get_ok

  let print ?verbose () ppf m = S.print ?verbose obj ppf m

  let zap_to_ceil m = with_log (S.zap_to_ceil obj m)

  let zap_to_floor m = with_log (S.zap_to_floor obj m)

  let of_const : type l r. ?hint:(l * r) pos Hint.const -> const -> (l * r) t =
   fun ?hint a -> S.of_const ?hint obj a

  let to_const_exn m = S.to_const_exn obj m

  let unhint = S.Unhint.unhint

  let hint ?hint = S.Unhint.hint obj ?hint

  let wrap ?hint:h f m = m |> unhint |> f |> hint ?hint:h

  let apply_hint hint m = wrap ~hint Fun.id m

  let meet_const_unhint c m = S.Unhint.apply obj (Meet_const c) m

  let meet_const ?hint c m = wrap ?hint (meet_const_unhint c) m

  let imply_const_unhint c m = S.Unhint.apply obj (Imply_const c) m

  let imply_const c m = m |> disallow_left |> wrap (imply_const_unhint c)

  module Guts = struct
    let get_floor m = S.get_floor obj m

    let get_ceil m = S.get_ceil obj m

    let get_loose_floor m = S.get_loose_floor obj m

    let get_loose_ceil m = S.get_loose_ceil obj m
  end
end
[@@inline]

module Monadic_gen (Obj : Obj) = struct
  (* Monadic lattices are flipped. See "Notes on flipping". *)
  open Obj

  type 'd t = (const, 'r * 'l) S.mode constraint 'd = 'l * 'r

  type l = (allowed * disallowed) t

  type r = (disallowed * allowed) t

  type lr = (allowed * allowed) t

  type nonrec simple_error = const simple_error

  type nonrec error = const Error.t

  type equate_error = equate_step * error

  type (_, _, 'd) sided = 'd t

  let disallow_right m = S.disallow_left m

  let disallow_left m = S.disallow_right m

  let allow_left m = S.allow_right m

  let allow_right m = S.allow_left m

  let newvar () = S.newvar obj

  let min = S.max obj

  let max = S.min obj

  let newvar_above m = S.newvar_below obj m

  let newvar_below m = S.newvar_above obj m

  let submode_log ?(pp = (Location.none, Unknown : Hint.pinpoint)) a b ~log =
    S.submode pp obj b a ~log

  let to_simple_error ({ left; right; _ } : error) : simple_error =
    { left = right; right = left }

  let submode ?pp a b = try_with_log (submode_log ?pp a b)

  let submode_err pp a b =
    match submode ~pp a b with
    | Ok () -> ()
    | Error e -> raise (Submode_error_simple_context (pp, Axis (obj, e)))

  let print_error pp err = Error.print_axis pp obj err

  let join l = S.meet obj l

  let meet l = S.join obj l

  let submode_exn ?pp m1 m2 = submode ?pp m1 m2 |> Result.get_ok

  let equate a b = try_with_log (equate_from_submode (submode_log ?pp:None) a b)

  let equate_exn m1 m2 = equate m1 m2 |> Result.get_ok

  let print ?verbose () ppf m = S.print ?verbose obj ppf m

  let zap_to_ceil m = with_log (S.zap_to_floor obj m)

  let zap_to_floor m = with_log (S.zap_to_ceil obj m)

  let of_const : type l r. ?hint:(l * r) neg Hint.const -> const -> (l * r) t =
   fun ?hint a -> S.of_const ?hint obj a

  let to_const_exn m = S.to_const_exn obj m

  let unhint = S.Unhint.unhint

  let hint ?hint = S.Unhint.hint obj ?hint

  let wrap ?hint:h f m = m |> unhint |> f |> hint ?hint:h

  let apply_hint hint m = wrap ~hint Fun.id m

  let join_const_unhint c m = S.Unhint.apply Obj.obj (Meet_const c) m

  let join_const ?hint c m = wrap ?hint (join_const_unhint c) m

  let subtract_const_unhint c m = S.Unhint.apply obj (Imply_const c) m

  let subtract_const c m = m |> disallow_right |> wrap (subtract_const_unhint c)

  module Guts = struct
    let get_ceil m = S.get_floor obj m
  end
end
[@@inline]

module Locality = struct
  module Const = C.Locality

  module Obj = struct
    type const = Const.t

    let obj = C.Locality
  end

  include Comonadic_gen (Obj)

  let global = of_const Global

  let local = of_const Local

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_floor

  module Guts = struct
    let check_const m =
      let floor = Guts.get_floor m in
      let ceil = Guts.get_ceil m in
      if Const.le ceil floor then Some ceil else None

    let check_const_conservative m =
      let floor = Guts.get_loose_floor m in
      let ceil = Guts.get_loose_ceil m in
      if Const.le ceil floor then Some ceil else None
  end
end

module Regionality = struct
  module Const = C.Regionality

  module Obj = struct
    type const = Const.t

    let obj = C.Regionality
  end

  include Comonadic_gen (Obj)

  let local = of_const Const.Local

  let regional = of_const Const.Regional

  let global = of_const Const.Global

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_floor
end

module Linearity = struct
  module Const = C.Linearity

  module Obj = struct
    type const = Const.t

    let obj : _ C.obj = C.Linearity
  end

  include Comonadic_gen (Obj)

  let many = of_const Many

  let once = of_const Once

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_floor
end

module Statefulness = struct
  module Const = C.Statefulness

  module Obj = struct
    type const = Const.t

    let obj = C.Statefulness
  end

  include Comonadic_gen (Obj)

  let stateless = of_const Stateless

  let reading = of_const Reading

  let writing = of_const Writing

  let stateful = of_const Stateful

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_ceil
end

module Visibility = struct
  module Const = C.Visibility

  module Obj = struct
    type const = Const.t

    let obj = C.Visibility_op
  end

  include Monadic_gen (Obj)

  let immutable = of_const Immutable

  let read = of_const Read

  let write = of_const Write

  let read_write = of_const Read_write

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_floor
end

module Portability = struct
  module Const = C.Portability

  module Obj = struct
    type const = Const.t

    let obj : _ C.obj = C.Portability
  end

  include Comonadic_gen (Obj)

  let legacy = of_const Const.legacy

  (* CR dkalinichenko: ideally, [reading] should zap to [shareable]. *)
  let zap_to_legacy ~statefulness =
    match statefulness with
    | Statefulness.Const.Stateful | Statefulness.Const.Reading
    | Statefulness.Const.Writing ->
      zap_to_ceil
    | Statefulness.Const.Stateless -> zap_to_floor
end

module Uniqueness = struct
  module Const = C.Uniqueness

  module Obj = struct
    type const = Const.t

    let obj = C.Uniqueness_op
  end

  include Monadic_gen (Obj)

  let aliased = of_const Aliased

  let unique = of_const Unique

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_ceil
end

module Contention = struct
  module Const = C.Contention

  module Obj = struct
    type const = Const.t

    let obj = C.Contention_op
  end

  include Monadic_gen (Obj)

  let legacy = of_const Const.legacy

  (* CR dkalinichenko: ideally, [read] should zap to [shared]. *)
  let zap_to_legacy ~visibility =
    match visibility with
    | Visibility.Const.Read_write | Visibility.Const.Read
    | Visibility.Const.Write ->
      zap_to_floor
    | Visibility.Const.Immutable -> zap_to_ceil
end

module Forkable = struct
  module Const = C.Forkable

  module Obj = struct
    type const = Const.t

    let obj = C.Forkable
  end

  include Comonadic_gen (Obj)

  let unforkable = of_const Unforkable

  let forkable = of_const Forkable

  let legacy = of_const Const.legacy

  (* [forkable] is the default for [global]s and [unforkable] for [local]
     or [regional] values, so we vary [zap_to_legacy] accordingly. *)
  let zap_to_legacy ~global =
    match global with true -> zap_to_floor | false -> zap_to_ceil
end

module Yielding = struct
  module Const = C.Yielding

  module Obj = struct
    type const = Const.t

    let obj = C.Yielding
  end

  include Comonadic_gen (Obj)

  let yielding = of_const Yielding

  let unyielding = of_const Unyielding

  let legacy = of_const Const.legacy

  (* [unyielding] is the default for [global]s and [yielding] for [local]
     or [regional] values, so we vary [zap_to_legacy] accordingly. *)
  let zap_to_legacy ~global =
    match global with true -> zap_to_floor | false -> zap_to_ceil
end

module Staticity = struct
  module Const = C.Staticity

  type const = Const.t =
    | Static
    | Dynamic

  module Obj = struct
    type const = Const.t

    let obj = C.Staticity_op
  end

  include Monadic_gen (Obj)

  let legacy = of_const Const.legacy

  let zap_to_legacy = zap_to_ceil
end

let regional_to_local m = S.apply Locality.Obj.obj C.Regional_to_local m

let locality_as_regionality m =
  S.apply Regionality.Obj.obj C.Locality_as_regionality m

let regional_to_global m = S.apply Locality.Obj.obj C.Regional_to_global m

module type Areality = sig
  module Const : C.Areality

  module Obj : Obj with type const = Const.t

  val zap_to_legacy : (Const.t, allowed * 'r) S.mode -> Const.t
end

module Lattice_Product (L : Lattice) = struct
  open L

  let min_with ax c = Axis.set ax c min

  let max_with ax c = Axis.set ax c max
end

module Comonadic_with (Areality : Areality) = struct
  module Obj = struct
    type const = Areality.Const.t C.comonadic_with

    let obj = C.comonadic_with_obj Areality.Obj.obj
  end

  include Comonadic_gen (Obj)

  module Axis = struct
    type 'a t = (Obj.const, 'a) Axis.t

    type packed = P : 'a t -> packed

    let print = Axis.print

    let compare = Axis.compare

    let proj = Axis.proj

    let all =
      [ P Areality;
        P Linearity;
        P Portability;
        P Forkable;
        P Yielding;
        P Statefulness ]
      |> List.sort (fun (P ax1) (P ax2) -> compare ax1 ax2)
  end

  let proj_obj ax = (C.proj_obj [@inlined hint]) ax Obj.obj

  module Const = struct
    include C.Comonadic_with (Areality.Const)
    include Lattice_Product (C.Comonadic_with (Areality.Const))

    let proj = Axis.proj

    module Per_axis = struct
      let print ax ppf a =
        let obj = proj_obj ax in
        C.print obj ppf a

      let le ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.le [@inlined hint]) obj a b

      let equal ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.equal [@inlined hint]) obj a b

      let join ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.join [@inlined hint]) obj a b

      let meet ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.meet [@inlined hint]) obj a b

      let max ax =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.max [@inlined hint]) obj

      let min ax =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.min [@inlined hint]) obj

      let compare_obj ax1 ax2 =
        let obj1 = proj_obj ax1 in
        let obj2 = proj_obj ax2 in
        C.compare_obj obj1 obj2

      let equal_obj ax1 ax2 =
        let obj1 = proj_obj ax1 in
        let obj2 = proj_obj ax2 in
        C.equal_obj obj1 obj2

      let print_obj ppf ax =
        let obj = proj_obj ax in
        C.print_obj ppf obj
    end
  end

  let proj ax m = S.apply ~hint:Skip (proj_obj ax) (Proj (Obj.obj, ax)) m

  module Per_axis = struct
    let zap_to_floor ax m =
      let obj = proj_obj ax in
      with_log (S.zap_to_floor obj m)

    let zap_to_ceil ax m =
      let obj = proj_obj ax in
      with_log (S.zap_to_ceil obj m)
  end

  let min_with ax m =
    S.apply ~hint:Skip Obj.obj (Min_with ax) (S.disallow_right m)

  let max_with ax m =
    S.apply ~hint:Skip Obj.obj (Max_with ax) (S.disallow_left m)

  let meet_const_with ax c m = meet_const (Const.max_with ax c) m

  let zap_to_legacy m : Const.t =
    let areality = proj Areality m |> Areality.zap_to_legacy in
    let linearity = proj Linearity m |> Linearity.zap_to_legacy in
    let statefulness = proj Statefulness m |> Statefulness.zap_to_legacy in
    let portability =
      proj Portability m |> Portability.zap_to_legacy ~statefulness
    in
    let global = Areality.Const.(equal areality legacy) in
    let forkable = proj Forkable m |> Forkable.zap_to_legacy ~global in
    let yielding = proj Yielding m |> Yielding.zap_to_legacy ~global in
    { areality; linearity; portability; forkable; yielding; statefulness }

  let legacy = of_const Const.legacy

  type simple_error =
    | Error : 'a Axis.t * 'a Mode_intf.simple_error -> simple_error

  let axis_of_error (actual : Obj.const) (expected : Obj.const) : simple_error =
    List.find_map
      (fun (Axis.P ax) ->
        let left = Const.proj ax actual in
        let right = Const.proj ax expected in
        if Const.Per_axis.le ax left right
        then None
        else Some (Error (ax, { left; right })))
      Axis.all
    |> Option.get

  (* overriding to report the offending axis *)
  let to_simple_error ({ left; right; _ } : error) = axis_of_error left right

  let submode_err pp a b =
    match submode ~pp a b with
    | Ok () -> ()
    | Error e ->
      let (Error (ax, _)) = to_simple_error e in
      raise (Submode_error_simple_context (pp, Product (Obj.obj, ax, e)))

  let print_error pp err =
    let (Error (ax, _)) = to_simple_error err in
    Error.print_product pp Obj.obj ax err
end
[@@inline]

module Monadic = struct
  (* Monadic lattices are flipped. See "Notes on flipping". *)
  module Obj = struct
    type const = C.Monadic_op.t

    let obj = C.Monadic_op
  end

  include Monadic_gen (Obj)

  module Axis = struct
    type 'a t = (Obj.const, 'a) C.Axis.t

    type packed = P : 'a t -> packed

    let compare = Axis.compare

    let print = Axis.print

    let proj = Axis.proj

    let all =
      [P Uniqueness; P Contention; P Visibility; P Staticity]
      |> List.sort (fun (P ax1) (P ax2) -> compare ax1 ax2)
  end

  let proj_obj ax = (C.proj_obj [@inlined hint]) ax Obj.obj

  module Const = struct
    include C.Monadic
    include Lattice_Product (C.Monadic)

    let proj = Axis.proj

    module Per_axis = struct
      let print ax ppf a =
        let obj = proj_obj ax in
        C.print obj ppf a

      (* See "Notes on flipping" *)

      let le ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.le [@inlined hint]) obj b a

      let equal ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.equal [@inlined hint]) obj b a

      let join ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.meet [@inlined hint]) obj a b

      let meet ax a b =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.join [@inlined hint]) obj a b

      let max ax =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.min [@inlined hint]) obj

      let min ax =
        let obj = (proj_obj [@inlined hint]) ax in
        (C.max [@inlined hint]) obj

      let compare_obj ax1 ax2 =
        let obj1 = proj_obj ax1 in
        let obj2 = proj_obj ax2 in
        C.compare_obj obj1 obj2

      let equal_obj ax1 ax2 =
        let obj1 = proj_obj ax1 in
        let obj2 = proj_obj ax2 in
        C.equal_obj obj1 obj2

      let print_obj ppf ax =
        let obj = proj_obj ax in
        C.print_obj ppf obj
    end
  end

  let proj ax m = S.apply ~hint:Skip (proj_obj ax) (Proj (Obj.obj, ax)) m

  module Per_axis = struct
    let zap_to_floor ax m =
      let obj = proj_obj ax in
      with_log (S.zap_to_ceil obj m)

    let zap_to_ceil ax m =
      let obj = proj_obj ax in
      with_log (S.zap_to_floor obj m)
  end

  (* The monadic fragment is inverted. *)

  let join_const_with ax c m = join_const (Const.min_with ax c) m

  let min_with ax m =
    S.apply ~hint:Skip Obj.obj (Max_with ax) (S.disallow_left m)

  let zap_to_legacy m : Const.t =
    let uniqueness = proj Uniqueness m |> Uniqueness.zap_to_legacy in
    let visibility = proj Visibility m |> Visibility.zap_to_legacy in
    let contention =
      proj Contention m |> Contention.zap_to_legacy ~visibility
    in
    let staticity = proj Staticity m |> Staticity.zap_to_legacy in
    { uniqueness; contention; visibility; staticity }

  let legacy = of_const Const.legacy

  type simple_error =
    | Error : 'a Axis.t * 'a Mode_intf.simple_error -> simple_error

  let axis_of_error (actual : Obj.const) (expected : Obj.const) : simple_error =
    List.find_map
      (fun (Axis.P ax) ->
        let left = Const.proj ax actual in
        let right = Const.proj ax expected in
        if Const.Per_axis.le ax left right
        then None
        else Some (Error (ax, { left; right })))
      Axis.all
    |> Option.get

  let to_simple_error ({ left; right; _ } : error) =
    (* monadic fragment is flipped *)
    axis_of_error right left

  let submode_err pp a b =
    match submode ~pp a b with
    | Ok () -> ()
    | Error e ->
      let (Error (ax, _)) = to_simple_error e in
      raise (Submode_error_simple_context (pp, Product (Obj.obj, ax, e)))

  let print_error pp err =
    let (Error (ax, _)) = to_simple_error err in
    Error.print_product pp Obj.obj ax err
end

type ('mo, 'como) monadic_comonadic =
  { monadic : 'mo;
    comonadic : 'como
  }

module Value_with (Areality : Areality) = struct
  module Comonadic = Comonadic_with (Areality)
  module Monadic = Monadic

  type 'd t = ('d Monadic.t, 'd Comonadic.t) monadic_comonadic

  type l = (allowed * disallowed) t

  type r = (disallowed * allowed) t

  type lr = (allowed * allowed) t

  module Axis = struct
    type 'a t =
      | Comonadic : 'a Comonadic.Axis.t -> 'a t
      | Monadic : 'a Monadic.Axis.t -> 'a t

    let compare : type a b. a t -> b t -> int =
     fun t1 t2 ->
      match t1, t2 with
      | Comonadic t1, Comonadic t2 -> Axis.compare t1 t2
      | Comonadic _, _ -> -1
      | _, Comonadic _ -> 1
      | Monadic t1, Monadic t2 -> Axis.compare t1 t2

    type packed = P : 'a t -> packed

    let print (type a) ppf (t : a t) =
      match t with
      | Monadic ax -> Axis.print ppf ax
      | Comonadic ax -> Axis.print ppf ax

    let all =
      List.map (fun (Monadic.Axis.P ax) -> P (Monadic ax)) Monadic.Axis.all
      @ List.map
          (fun (Comonadic.Axis.P ax) -> P (Comonadic ax))
          Comonadic.Axis.all
      |> List.sort (fun (P ax1) (P ax2) -> compare ax1 ax2)
  end

  let proj_obj : type a. a Axis.t -> a C.obj = function
    | Monadic ax -> Monadic.proj_obj ax
    | Comonadic ax -> Comonadic.proj_obj ax

  (* CR-soon zqian: make a functor [Mode.Value.Const.Make] to generalize over any type
     operator applied on each mode constants. *)
  type ('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j) modes =
    { areality : 'a;
      linearity : 'b;
      uniqueness : 'c;
      portability : 'd;
      contention : 'e;
      forkable : 'f;
      yielding : 'g;
      statefulness : 'h;
      visibility : 'i;
      staticity : 'j
    }

  let split
      { areality;
        linearity;
        portability;
        forkable;
        yielding;
        statefulness;
        uniqueness;
        contention;
        visibility;
        staticity
      } =
    let monadic : Monadic.Const.t =
      { uniqueness; contention; visibility; staticity }
    in
    let comonadic : Comonadic.Const.t =
      { areality; linearity; portability; forkable; yielding; statefulness }
    in
    { comonadic; monadic }

  let merge { comonadic; monadic } =
    let ({ areality; linearity; portability; forkable; yielding; statefulness }
          : Comonadic.Const.t) =
      comonadic
    in
    let ({ uniqueness; contention; visibility; staticity } : Monadic.Const.t) =
      monadic
    in
    { areality;
      linearity;
      portability;
      forkable;
      yielding;
      statefulness;
      uniqueness;
      contention;
      visibility;
      staticity
    }

  let print ?verbose () ppf { monadic; comonadic } =
    Fmt.fprintf ppf "%a;%a"
      (Comonadic.print ?verbose ())
      comonadic
      (Monadic.print ?verbose ())
      monadic

  let of_const ?hint_monadic ?hint_comonadic c =
    let { monadic; comonadic } = split c in
    let comonadic = Comonadic.of_const ?hint:hint_comonadic comonadic in
    let monadic = Monadic.of_const ?hint:hint_monadic monadic in
    { comonadic; monadic }

  let to_const_exn m =
    let { comonadic; monadic } = m in
    let comonadic = Comonadic.to_const_exn comonadic in
    let monadic = Monadic.to_const_exn monadic in
    { comonadic; monadic } |> merge

  let unhint { monadic; comonadic } =
    let comonadic = Comonadic.unhint comonadic in
    let monadic = Monadic.unhint monadic in
    { monadic; comonadic }

  let hint ?monadic ?comonadic t =
    let comonadic = Comonadic.hint ?hint:comonadic t.comonadic in
    let monadic = Monadic.hint ?hint:monadic t.monadic in
    { monadic; comonadic }

  let wrap ?monadic ?comonadic f t =
    t |> unhint |> f |> hint ?monadic ?comonadic

  module Const = struct
    let comonadic_to_monadic_min = C.comonadic_to_monadic_min Comonadic.Obj.obj

    module Monadic = Monadic.Const
    module Comonadic = Comonadic.Const

    (* CR-soon zqian: make a functor [Mode.Value.Const.Make] to generalize over any type
       operator applied on each mode constants. *)
    type t =
      ( Areality.Const.t,
        Linearity.Const.t,
        Uniqueness.Const.t,
        Portability.Const.t,
        Contention.Const.t,
        Forkable.Const.t,
        Yielding.Const.t,
        Statefulness.Const.t,
        Visibility.Const.t,
        Staticity.Const.t )
      modes

    let min = merge { comonadic = Comonadic.min; monadic = Monadic.min }

    let max = merge { comonadic = Comonadic.max; monadic = Monadic.max }

    let le m1 m2 =
      let m1 = split m1 in
      let m2 = split m2 in
      Comonadic.le m1.comonadic m2.comonadic && Monadic.le m1.monadic m2.monadic

    let equal m1 m2 =
      let m1 = split m1 in
      let m2 = split m2 in
      Comonadic.equal m1.comonadic m2.comonadic
      && Monadic.equal m1.monadic m2.monadic

    let print ppf m =
      let { monadic; comonadic } = split m in
      Fmt.fprintf ppf "%a,%a" Comonadic.print comonadic Monadic.print monadic

    let legacy =
      merge { comonadic = Comonadic.legacy; monadic = Monadic.legacy }

    let meet m1 m2 =
      let m1 = split m1 in
      let m2 = split m2 in
      let monadic = Monadic.meet m1.monadic m2.monadic in
      let comonadic = Comonadic.meet m1.comonadic m2.comonadic in
      merge { monadic; comonadic }

    let join m1 m2 =
      let m1 = split m1 in
      let m2 = split m2 in
      let monadic = Monadic.join m1.monadic m2.monadic in
      let comonadic = Comonadic.join m1.comonadic m2.comonadic in
      merge { monadic; comonadic }

    module Option = struct
      type some = t

      type t =
        ( Areality.Const.t option,
          Linearity.Const.t option,
          Uniqueness.Const.t option,
          Portability.Const.t option,
          Contention.Const.t option,
          Forkable.Const.t option,
          Yielding.Const.t option,
          Statefulness.Const.t option,
          Visibility.Const.t option,
          Staticity.Const.t option )
        modes

      let none =
        { areality = None;
          uniqueness = None;
          linearity = None;
          portability = None;
          contention = None;
          forkable = None;
          yielding = None;
          statefulness = None;
          visibility = None;
          staticity = None
        }

      let value opt ~default =
        let areality = Option.value opt.areality ~default:default.areality in
        let uniqueness =
          Option.value opt.uniqueness ~default:default.uniqueness
        in
        let linearity = Option.value opt.linearity ~default:default.linearity in
        let portability =
          Option.value opt.portability ~default:default.portability
        in
        let contention =
          Option.value opt.contention ~default:default.contention
        in
        let yielding = Option.value opt.yielding ~default:default.yielding in
        let forkable = Option.value opt.forkable ~default:default.forkable in
        let statefulness =
          Option.value opt.statefulness ~default:default.statefulness
        in
        let visibility =
          Option.value opt.visibility ~default:default.visibility
        in
        let staticity = Option.value opt.staticity ~default:default.staticity in
        { areality;
          uniqueness;
          linearity;
          portability;
          contention;
          forkable;
          yielding;
          statefulness;
          visibility;
          staticity
        }

      let proj (type a) (ax : a Axis.t) (t : t) : a option =
        match ax with
        | Monadic ax -> (
          match ax with
          | Uniqueness -> t.uniqueness
          | Contention -> t.contention
          | Visibility -> t.visibility
          | Staticity -> t.staticity)
        | Comonadic ax -> (
          match ax with
          | Areality -> t.areality
          | Linearity -> t.linearity
          | Portability -> t.portability
          | Forkable -> t.forkable
          | Yielding -> t.yielding
          | Statefulness -> t.statefulness)

      let set (type a) (ax : a Axis.t) (a : a option) (t : t) : t =
        match ax with
        | Monadic ax -> (
          match ax with
          | Uniqueness -> { t with uniqueness = a }
          | Contention -> { t with contention = a }
          | Visibility -> { t with visibility = a }
          | Staticity -> { t with staticity = a })
        | Comonadic ax -> (
          match ax with
          | Areality -> { t with areality = a }
          | Linearity -> { t with linearity = a }
          | Portability -> { t with portability = a }
          | Yielding -> { t with yielding = a }
          | Forkable -> { t with forkable = a }
          | Statefulness -> { t with statefulness = a })

      let print ppf
          { areality;
            uniqueness;
            linearity;
            portability;
            contention;
            forkable;
            yielding;
            statefulness;
            visibility;
            staticity
          } =
        let option_print print ppf = function
          | None -> Fmt.fprintf ppf "None"
          | Some a -> Fmt.fprintf ppf "Some %a" print a
        in
        Fmt.fprintf ppf "%a,%a,%a,%a,%a,%a,%a,%a,%a,%a"
          (option_print Areality.Const.print)
          areality
          (option_print Linearity.Const.print)
          linearity
          (option_print Uniqueness.Const.print)
          uniqueness
          (option_print Portability.Const.print)
          portability
          (option_print Contention.Const.print)
          contention
          (option_print Forkable.Const.print)
          forkable
          (option_print Yielding.Const.print)
          yielding
          (option_print Statefulness.Const.print)
          statefulness
          (option_print Visibility.Const.print)
          visibility
          (option_print Staticity.Const.print)
          staticity
    end

    let diff m1 m2 =
      let diff le a1 a2 = if le a1 a2 && le a2 a1 then None else Some a1 in
      let areality = diff Areality.Const.le m1.areality m2.areality in
      let linearity = diff Linearity.Const.le m1.linearity m2.linearity in
      let uniqueness = diff Uniqueness.Const.le m1.uniqueness m2.uniqueness in
      let portability =
        diff Portability.Const.le m1.portability m2.portability
      in
      let contention = diff Contention.Const.le m1.contention m2.contention in
      let forkable = diff Forkable.Const.le m1.forkable m2.forkable in
      let yielding = diff Yielding.Const.le m1.yielding m2.yielding in
      let statefulness =
        diff Statefulness.Const.le m1.statefulness m2.statefulness
      in
      let visibility = diff Visibility.Const.le m1.visibility m2.visibility in
      let staticity = diff Staticity.Const.le m1.staticity m2.staticity in
      { areality;
        linearity;
        uniqueness;
        portability;
        contention;
        forkable;
        yielding;
        statefulness;
        visibility;
        staticity
      }

    (** See [Alloc.close_over] for explanation. *)
    let close_over m =
      let { monadic; comonadic } = split m in
      Comonadic.join comonadic
        (C.monadic_to_comonadic_min
           (C.comonadic_with_obj Areality.Obj.obj)
           monadic)

    (** See [Alloc.partial_apply] for explanation. *)
    let partial_apply m =
      let { comonadic; _ } = split m in
      comonadic

    let print_axis : type a. a Axis.t -> Fmt.formatter -> a -> unit =
     fun ax ppf a ->
      let obj = proj_obj ax in
      C.print obj ppf a

    let le_axis : type a. a Axis.t -> a -> a -> bool =
     fun ax m1 m2 ->
      match ax with
      | Comonadic ax -> Comonadic.Per_axis.le ax m1 m2
      | Monadic ax -> Monadic.Per_axis.le ax m1 m2

    let min_axis : type a. a Axis.t -> a = function
      | Comonadic ax -> Comonadic.Per_axis.min ax
      | Monadic ax -> Monadic.Per_axis.min ax

    let max_axis : type a. a Axis.t -> a = function
      | Comonadic ax -> Comonadic.Per_axis.max ax
      | Monadic ax -> Monadic.Per_axis.max ax

    let is_max : type a. a Axis.t -> a -> bool =
     fun ax m -> le_axis ax (max_axis ax) m

    let is_min : type a. a Axis.t -> a -> bool =
     fun ax m -> le_axis ax m (min_axis ax)

    let split = split

    let merge = merge
  end

  let min = { comonadic = Comonadic.min; monadic = Monadic.min }

  let max = { comonadic = Comonadic.max; monadic = Monadic.max }

  include Magic_allow_disallow (struct
    type (_, _, 'd) sided = 'd t constraint 'd = 'l * 'r

    let allow_left { monadic; comonadic } =
      let monadic = Monadic.allow_left monadic in
      let comonadic = Comonadic.allow_left comonadic in
      { monadic; comonadic }

    let allow_right { monadic; comonadic } =
      let monadic = Monadic.allow_right monadic in
      let comonadic = Comonadic.allow_right comonadic in
      { monadic; comonadic }

    let disallow_left { monadic; comonadic } =
      let monadic = Monadic.disallow_left monadic in
      let comonadic = Comonadic.disallow_left comonadic in
      { monadic; comonadic }

    let disallow_right { monadic; comonadic } =
      let monadic = Monadic.disallow_right monadic in
      let comonadic = Comonadic.disallow_right comonadic in
      { monadic; comonadic }
  end)

  let newvar () =
    let comonadic = Comonadic.newvar () in
    let monadic = Monadic.newvar () in
    { comonadic; monadic }

  let newvar_above { comonadic; monadic } =
    let comonadic, b1 = Comonadic.newvar_above comonadic in
    let monadic, b2 = Monadic.newvar_above monadic in
    { monadic; comonadic }, b1 || b2

  let newvar_below { comonadic; monadic } =
    let comonadic, b1 = Comonadic.newvar_below comonadic in
    let monadic, b2 = Monadic.newvar_below monadic in
    { monadic; comonadic }, b1 || b2

  type atom = Atom : 'a Axis.t * 'a -> atom

  type error =
    | Monadic of Monadic.error
    | Comonadic of Comonadic.error

  type equate_error = equate_step * error

  type simple_error =
    | Error : 'a Axis.t * 'a Mode_intf.simple_error -> simple_error

  let to_simple_error = function
    | Monadic e ->
      let (Error (ax, e)) = Monadic.to_simple_error e in
      Error (Monadic ax, e)
    | Comonadic e ->
      let (Error (ax, e)) = Comonadic.to_simple_error e in
      Error (Comonadic ax, e)

  let print_error pp = function
    | Monadic e -> Monadic.print_error pp e
    | Comonadic e -> Comonadic.print_error pp e

  let submode_log ?pp { monadic = monadic1; comonadic = comonadic1 }
      { monadic = monadic2; comonadic = comonadic2 } ~log : (_, error) result =
    (* comonadic before monadic, so that locality errors dominate
       (error message backward compatibility) *)
    match Comonadic.submode_log ?pp comonadic1 comonadic2 ~log with
    | Error e -> Error (Comonadic e)
    | Ok () -> (
      match Monadic.submode_log ?pp monadic1 monadic2 ~log with
      | Error e -> Error (Monadic e)
      | Ok () -> Ok ())

  let submode ?pp a b = try_with_log (submode_log ?pp a b)

  let submode_err pp a b =
    Comonadic.submode_err pp a.comonadic b.comonadic;
    Monadic.submode_err pp a.monadic b.monadic

  let equate a b = try_with_log (equate_from_submode (submode_log ?pp:None) a b)

  let submode_exn ?pp m1 m2 =
    match submode ?pp m1 m2 with
    | Ok () -> ()
    | Error _ -> invalid_arg "submode_exn"

  let equate_exn m1 m2 =
    match equate m1 m2 with Ok () -> () | Error _ -> invalid_arg "equate_exn"

  let legacy =
    let comonadic = Comonadic.legacy in
    let monadic = Monadic.legacy in
    { comonadic; monadic }

  let proj_monadic ax { monadic; _ } = Monadic.proj ax monadic

  let proj_comonadic ax { comonadic; _ } = Comonadic.proj ax comonadic

  let max_with_comonadic ax m =
    let comonadic = Comonadic.max_with ax m in
    let monadic = Monadic.max |> Monadic.disallow_left |> Monadic.allow_right in
    { comonadic; monadic }

  let min_with_comonadic ax m =
    let comonadic = Comonadic.min_with ax m in
    let monadic = Monadic.min |> Monadic.disallow_right |> Monadic.allow_left in
    { comonadic; monadic }

  let min_with_monadic ax m =
    let monadic = Monadic.min_with ax m in
    let comonadic =
      Comonadic.min |> Comonadic.disallow_right |> Comonadic.allow_left
    in
    { comonadic; monadic }

  let join_const_with ax c { monadic; comonadic } =
    let monadic = Monadic.join_const_with ax c monadic in
    { monadic; comonadic }

  let meet_const_with ax c { monadic; comonadic } =
    let comonadic = Comonadic.meet_const_with ax c comonadic in
    { comonadic; monadic }

  let join l =
    let como, mo =
      List.fold_left
        (fun (como, mo) { comonadic; monadic } ->
          comonadic :: como, monadic :: mo)
        ([], []) l
    in
    let comonadic = Comonadic.join como in
    let monadic = Monadic.join mo in
    { comonadic; monadic }

  let meet l =
    let como, mo =
      List.fold_left
        (fun (como, mo) { comonadic; monadic } ->
          comonadic :: como, monadic :: mo)
        ([], []) l
    in
    let comonadic = Comonadic.meet como in
    let monadic = Monadic.meet mo in
    { comonadic; monadic }

  let comonadic_to_monadic_min ?hint m =
    S.apply ?hint Monadic.Obj.obj (Comonadic_to_monadic_max Comonadic.Obj.obj)
      (Comonadic.disallow_left m)

  let monadic_to_comonadic_min m =
    S.apply Comonadic.Obj.obj Monadic_to_comonadic_min (Monadic.disallow_left m)

  let monadic_to_comonadic_max m =
    S.apply Comonadic.Obj.obj Monadic_to_comonadic_max
      (Monadic.disallow_right m)

  let meet_const c { comonadic; monadic } =
    let comonadic = Comonadic.meet_const c comonadic in
    { monadic; comonadic }

  let join_const c { comonadic; monadic } =
    let monadic = Monadic.join_const c monadic in
    { monadic; comonadic }

  let zap_to_ceil { comonadic; monadic } =
    let monadic = Monadic.zap_to_ceil monadic in
    let comonadic = Comonadic.zap_to_ceil comonadic in
    merge { monadic; comonadic }

  let zap_to_floor { comonadic; monadic } =
    let monadic = Monadic.zap_to_floor monadic in
    let comonadic = Comonadic.zap_to_floor comonadic in
    merge { monadic; comonadic }

  let zap_to_legacy { comonadic; monadic } =
    let monadic = Monadic.zap_to_legacy monadic in
    let comonadic = Comonadic.zap_to_legacy comonadic in
    merge { monadic; comonadic }

  (** This is about partially applying [A -> B -> C] to [A] and getting
      [B -> C]. [comonadic] and [monadic] constutute the mode of [A], and we
      need to give the lower bound mode of [B -> C]. *)
  let close_over { comonadic; monadic } =
    let comonadic = Comonadic.disallow_right comonadic in
    (* The comonadic of the returned function is constrained by the monadic of the closed argument via the dualizing morphism. *)
    let comonadic1 = monadic_to_comonadic_min monadic in
    (* It's also constrained by the comonadic of the closed argument. *)
    let comonadic = Comonadic.join [comonadic; comonadic1] in
    (* The closure will access [A] at the specified monadic modes, and thus the
       monadic mode of the closure itself is not constrained by it. *)
    let monadic = Monadic.disallow_right Monadic.min in
    { comonadic; monadic }

  (** Similar to above, but we are given the mode of [A -> B -> C], and need to
      give the lower bound mode of [B -> C]. *)
  let partial_apply { comonadic; _ } =
    (* The closure will invoke the original function at the specified monadic
       modes, and thus the monadic mode of the closure itself is not constrained by
       it. *)
    let monadic = Monadic.disallow_right Monadic.min in
    let comonadic = Comonadic.disallow_right comonadic in
    { comonadic; monadic }

  module List = struct
    type nonrec 'd t = 'd t list

    include Magic_allow_disallow (struct
      type (_, _, 'd) sided = 'd t constraint 'd = 'l * 'r

      let allow_left l = List.map allow_left l

      let allow_right l = List.map allow_right l

      let disallow_left l = List.map disallow_left l

      let disallow_right l = List.map disallow_right l
    end)
  end
end
[@@inline]

module Value = Value_with (Regionality)
module Alloc = Value_with (Locality)

module Const = struct
  let alloc_as_value
      ({ areality;
         linearity;
         portability;
         uniqueness;
         contention;
         forkable;
         yielding;
         statefulness;
         visibility;
         staticity
       } :
        Alloc.Const.t) : Value.Const.t =
    let areality = C.locality_as_regionality areality in
    { areality;
      linearity;
      portability;
      uniqueness;
      contention;
      forkable;
      yielding;
      statefulness;
      visibility;
      staticity
    }

  module Axis = struct
    let is_areality (type a) :
        a Alloc.Axis.t ->
        ((a, Locality.Const.t) Misc.eq, a Value.Axis.t) Either.t = function
      | Comonadic Areality -> Left Refl
      | Comonadic Linearity -> Right (Comonadic Linearity)
      | Comonadic Portability -> Right (Comonadic Portability)
      | Comonadic Forkable -> Right (Comonadic Forkable)
      | Comonadic Yielding -> Right (Comonadic Yielding)
      | Comonadic Statefulness -> Right (Comonadic Statefulness)
      | Monadic Uniqueness -> Right (Monadic Uniqueness)
      | Monadic Contention -> Right (Monadic Contention)
      | Monadic Visibility -> Right (Monadic Visibility)
      | Monadic Staticity -> Right (Monadic Staticity)

    let alloc_as_value : Alloc.Axis.packed -> Value.Axis.packed =
     fun (P ax) ->
      match is_areality ax with
      | Left Refl -> P (Comonadic Areality)
      | Right ax -> P ax
  end

  let locality_as_regionality = C.locality_as_regionality
end

(* CR-someday zqian: all the function that converts between [Alloc] and [Value] should
   operate on [Unhint] so they can be composed and assigned hint as a whole. *)

let comonadic_locality_as_regionality comonadic =
  S.Unhint.apply Value.Comonadic.Obj.obj (Map_comonadic Locality_as_regionality)
    comonadic

let comonadic_regional_to_local comonadic =
  S.Unhint.apply Alloc.Comonadic.Obj.obj (Map_comonadic Regional_to_local)
    comonadic

let alloc_as_value_unhint m =
  let { comonadic; monadic } = m in
  let comonadic = comonadic_locality_as_regionality comonadic in
  { comonadic; monadic }

let alloc_as_value m =
  m |> Alloc.unhint |> alloc_as_value_unhint |> Value.hint ~monadic:Skip

let alloc_to_value_l2r_unhint m =
  let { comonadic; monadic } = m in
  let comonadic =
    S.Unhint.apply Value.Comonadic.Obj.obj (Map_comonadic Local_to_regional)
      comonadic
  in
  { comonadic; monadic }

let alloc_to_value_l2r m =
  m |> Alloc.disallow_right |> Alloc.unhint |> alloc_to_value_l2r_unhint
  |> Value.hint ~monadic:Skip

let value_to_alloc_r2g_unhint m =
  let { comonadic; monadic } = m in
  let comonadic =
    S.Unhint.apply Alloc.Comonadic.Obj.obj (Map_comonadic Regional_to_global)
      comonadic
  in
  { comonadic; monadic }

let value_to_alloc_r2g m =
  m |> Value.unhint |> value_to_alloc_r2g_unhint |> Alloc.hint ~monadic:Skip

let value_r2g ?hint m =
  Value.wrap ~monadic:Skip ?comonadic:hint
    (fun m -> m |> value_to_alloc_r2g_unhint |> alloc_as_value_unhint)
    m

let value_to_alloc_r2l_unhint m =
  let { comonadic; monadic } = m in
  let comonadic = comonadic_regional_to_local comonadic in
  { comonadic; monadic }

let value_to_alloc_r2l m =
  m |> Value.unhint |> value_to_alloc_r2l_unhint |> Alloc.hint ~monadic:Skip

module Modality = struct
  (* Inferred modalities

      Similar to constant modalities, an inferred modality maps the mode of a
      record/structure to the mode of a value therein. An inferred modality [f]
      is inferred from the structure/record mode [mm] and the value mode [m]. It
      will only be applied on some [x >= mm]: That is, it will only be applied
      on the original module.

      It should satisfy the following conditions:

      Zapping: [f] should be of the form [join_c] for monadic axes, or [meet_c]
      for comonadic axes.

      Soundness: You should not get a value from a record/structure at a mode
      strictly stronger than how it was put in. That is, for any [x >= mm], [f x
      >= m].

      Completeness: Ideally we also want [f mm <= m].

      Monadic axes

      Soundness condition says [join_c x >= m] for any [x >= mm]. Equivalently,
      [join_c mm >= m]. By adjunction, [c >= subtract_mm m]. We take the lower
      bound [c := subtract_mm m]. Note that this is equivalent to taking [c := m
      >= subtract_mm m]. Proof:

      - [join_m x >= join_(subtract_mm m) x] is trivial since [m >= subtract_mm
        m].
      - [join_m x <= join_(subtract_mm m) x], or equivalently [m <=
      join_(subtract_mm m) x], or equivalently [subtract_x m <= subtract_mm m],
      which is trivial since [x >= mm].

      Taking [c := subtract_mm m] is better for zapping since it's lower and
      thus closer to identity modality. Taking [c := m] is easier for [apply]
      and [sub].

      Comonadic axes

      Soundness condition says [meet_c x >= m] for any [x >= mm]. Equivalently,
      [meet_c mm >= m]. By def. of [meet], we have both [c >= m] and [mm >= m].
      The latter is guaranteed by the user of [infer]. We guarantee the former
      by taking [c := imply_mm m >= m]. One might worry that this is too relaxed
      and will be "less complete" than taking [c := m]; however, note that
      [imply_mm m <= imply_mm m] and thus by adjunction [meet_(imply_mm m) mm <=
      m], which means the chosen [c] is complete.

      Taking [c := m] is easier for [apply] and [sub]. Taking [c := imply_mm m]
      is better for zapping since it's higher and thus closer to identity
      modality. However, note that we DON'T have [meet_m x = meet_(imply_mm m)
      x], which means [apply/sub] and [zap] might behave in a confusing (albeit
      sound) manner.

      CR zqian: once we support binary mode solver, [c := imply_mm m] will be
      used uniformly by [apply] [sub] and [zap].
  *)

  module Monadic = struct
    module Mode = Value.Monadic

    type 'a axis = 'a Mode.Axis.t

    module Atom = struct
      type 'a t = Join_const of 'a [@@unboxed]

      let is_id ax (Join_const c) = Mode.Const.Per_axis.(le ax c (min ax))

      let is_constant ax (Join_const c) = Mode.Const.Per_axis.(le ax (max ax) c)
    end

    type error = Error : 'a axis * 'a Atom.t simple_error -> error

    module Const = struct
      type t = Join_const of Mode.Const.t [@@unboxed]

      let id = Join_const Mode.Const.min

      let is_id t = t = id

      let max = Join_const Mode.Const.max

      let sub left right : (_, error) Result.t =
        match left, right with
        | Join_const c1, Join_const c2 ->
          if Mode.Const.le c1 c2
          then Ok ()
          else
            let (Error (ax, { left; right })) = Mode.axis_of_error c1 c2 in
            Error
              (Error (ax, { left = Join_const left; right = Join_const right }))

      let concat ~then_ t =
        match then_, t with
        | Join_const c1, Join_const c2 -> Join_const (Mode.Const.join c1 c2)

      let apply : type l r.
          ?hint:(l * r) neg Hint.morph -> t -> (l * r) Mode.t -> (l * r) Mode.t
          =
       fun ?(hint = Hint.Unknown) t x ->
        match t with Join_const c -> Mode.join_const ~hint c x

      let proj ax (Join_const c) : _ Atom.t = Join_const (Axis.proj ax c)

      let set ax (Join_const a : _ Atom.t) (Join_const c) =
        Join_const (Axis.set ax a c)

      let print ppf = function
        | Join_const c -> Fmt.fprintf ppf "join_const(%a)" Mode.Const.print c
    end

    type t =
      | Const of Const.t
      | Diff of Mode.lr * Mode.lr  (** See "Inferred modalities" comments *)
      | Undefined

    let sub_log left right ~log : (unit, error) Result.t =
      match left, right with
      | Const c1, Const c2 -> Const.sub c1 c2
      | Diff (mm, m), Const (Join_const c) -> (
        (* Check that for any x >= mm, join(x, m) <= join(x, c), which (by
           definition of join) is equivalent to m <= join(x, c). This has to
           hold for all x >= mm, so we check m <= join(mm, c). *)
        match Mode.submode_log m (Mode.join_const c mm) ~log with
        | Ok () -> Ok ()
        | Error err ->
          let (Error (ax, { left; _ })) = Mode.to_simple_error err in
          Error
            (Error
               ( ax,
                 { left = Join_const left; right = Join_const (Axis.proj ax c) }
               )))
      | Diff (_, _m1), Diff (_, _m2) ->
        (* [m1] is a left mode so it cannot appear on the right. So we can't do
           a proper check. However, this branch is only hit by
           [wrap_constraint_with_shape], in which case LHS and RHS should be
           physically equal. *)
        assert (left == right);
        Ok ()
      | Const _, Diff _ ->
        Misc.fatal_error
          "inferred modality Diff should not be on the RHS of sub."
      | Undefined, _ | _, Undefined ->
        Misc.fatal_error "modality Undefined should not be in sub."

    let apply : type r.
        ?hint:(allowed * r) neg Hint.morph ->
        t ->
        (allowed * r) Mode.t ->
        Mode.l =
     fun ?hint t x ->
      match t with
      | Const c -> Const.apply ?hint c x |> Mode.disallow_right
      | Undefined ->
        Misc.fatal_error "modality Undefined should not be applied."
      | Diff (_, m) -> Mode.join [Mode.allow_right m; x]

    let print ppf = function
      | Const c -> Const.print ppf c
      | Undefined -> Fmt.fprintf ppf "undefined"
      | Diff _ -> Fmt.fprintf ppf "diff"

    (* All zapping functions mutate [mm] and [m] to the degree that's sufficient
       to fix [subtract_mm m], and return it. [subtract] is antitone for [mm]
       and monotone for [m]. *)

    let zap_to_floor = function
      | Const c -> c
      | Undefined -> Misc.fatal_error "modality Undefined should not be zapped."
      | Diff (mm, m) ->
        (* Ideally we will take [c = subtract_mm m] and zap it to floor.
           However, [subtract] requires [mm] to be constant. We get the ceil of
           [mm] to construct the floor of [c]. *)
        let cc = Mode.Guts.get_ceil mm in
        let c = Mode.subtract_const cc m in
        let c = Mode.zap_to_floor c in
        (* Note that we did not mutate [mm] but simply took its ceil, which
           might be mutated later. To satisfy the coherence condition (see the
           comment in the mli), we want to:

           - make it impossible that [subtract_mm m < c], which is trivial since
           [mm <= cc] and thus [subtract_mm m >= subtract_cc m = c].
           - make it impossible that [subtract_mm m > c], which is to ensure
           [subtract_mm m <= c], equivalently [m <= join_mm c], which is
           achieved by the following [submode].
        *)
        Mode.submode_exn m (Mode.join_const c mm);
        Const.Join_const c

    let zap_to_id = zap_to_floor

    let to_const_opt = function
      | Const c -> Some c
      | Undefined ->
        Misc.fatal_error "modality Undefined should not be looked at"
      | Diff _ -> None

    let of_const c = Const c

    let infer ~md_mode ~mode = Diff (md_mode, mode)

    let max = Const Const.max
  end

  module Comonadic = struct
    module Mode = Value.Comonadic

    type 'a axis = 'a Mode.Axis.t

    module Atom = struct
      type 'a t = Meet_const of 'a [@@unboxed]

      let is_id ax (Meet_const c) = Mode.Const.Per_axis.(le ax (max ax) c)

      let is_constant ax (Meet_const c) = Mode.Const.Per_axis.(le ax c (min ax))
    end

    type error = Error : 'a axis * 'a Atom.t simple_error -> error

    module Const = struct
      type t = Meet_const of Mode.Const.t [@@unboxed]

      let id = Meet_const Mode.Const.max

      let is_id t = t = id

      let max = Meet_const Mode.Const.max

      let sub left right : (_, error) Result.t =
        match left, right with
        | Meet_const c1, Meet_const c2 ->
          if Mode.Const.le c1 c2
          then Ok ()
          else
            let (Error (ax, { left; right })) = Mode.axis_of_error c1 c2 in
            Error
              (Error (ax, { left = Meet_const left; right = Meet_const right }))

      let concat ~then_ t =
        match then_, t with
        | Meet_const c1, Meet_const c2 -> Meet_const (Mode.Const.meet c1 c2)

      let apply : type l r.
          ?hint:(l * r) pos Hint.morph -> t -> (l * r) Mode.t -> (l * r) Mode.t
          =
       fun ?(hint = Hint.Unknown) t x ->
        match t with Meet_const c -> Mode.meet_const ~hint c x

      let proj ax (Meet_const c) : _ Atom.t = Meet_const (Axis.proj ax c)

      let set ax (Meet_const a : _ Atom.t) (Meet_const c) =
        Meet_const (Axis.set ax a c)

      let print ppf = function
        | Meet_const c -> Fmt.fprintf ppf "meet_const(%a)" Mode.Const.print c
    end

    type t =
      | Const of Const.t
      | Undefined
      | Exactly of Mode.lr * Mode.lr  (** See "Inferred modalities" comments *)

    let sub_log left right ~log : (unit, error) Result.t =
      match left, right with
      | Const c1, Const c2 -> Const.sub c1 c2
      | Exactly (_mm, m), Const (Meet_const c) -> (
        (* Check for all [x >= mm], [meet_(imply_mm m) x <= meet_c x], or
           equivalently [meet_(imply_mm m) x <= c], or equivalently [meet_(imply_mm
           m) max <= c], or equivalently [imply_mm m <= c]. We can't check this
           without binary mode solver.

           So instead we check [meet_m x <= meet_c x] (See "Inferred modalities"
           comments), which amounts to [m <= c]. *)
        match Mode.submode_log m (Mode.of_const c) ~log with
        | Ok () -> Ok ()
        | Error err ->
          let (Error (ax, { left; _ })) = Mode.to_simple_error err in
          Error
            (Error
               ( ax,
                 { left = Meet_const left; right = Meet_const (Axis.proj ax c) }
               )))
      | Exactly (_, _m1), Exactly (_, _m2) ->
        (* [m1] is a left mode, so there is no good way to check.
           However, this branch only hit by [wrap_constraint_with_shape],
           in which case LHS and RHS should be physically equal. *)
        assert (left == right);
        Ok ()
      | Const _, Exactly _ ->
        Misc.fatal_error
          "inferred modaltiy Exactly should not be on the RHS of sub."
      | Undefined, _ | _, Undefined ->
        Misc.fatal_error "modality Undefined should not be in sub."

    let apply : type r.
        ?hint:(allowed * r) pos Hint.morph ->
        t ->
        (allowed * r) Mode.t ->
        Mode.l =
     fun ?hint t x ->
      match t with
      | Const c -> Const.apply ?hint c x |> Mode.disallow_right
      | Undefined ->
        Misc.fatal_error "modality Undefined should not be applied."
      | Exactly (_mm, m) ->
        (* Ideally want to return [meet_(imply_mm m) x], which we can't do
           without binary mode solver, so instead we return [meet_m x] (See
           "Inferred modalities" comments), which because of [x >= mm >= m] is
           equal to [m]. *)
        Mode.disallow_right m

    let print ppf = function
      | Const c -> Const.print ppf c
      | Undefined -> Fmt.fprintf ppf "undefined"
      | Exactly _ -> Fmt.fprintf ppf "exactly"

    let infer ~md_mode ~mode = Exactly (md_mode, mode)

    let max = Const Const.max

    (* All zapping functions mutate [mm] and [m] to the degree that's sufficient
       to fix [imply_mm m], and return it. [imply] is antitone for [mm] and
       monotone for [m]. *)

    let zap_to_ceil = function
      | Const c -> c
      | Undefined -> Misc.fatal_error "modality Undefined should not be zapped."
      | Exactly (mm, m) ->
        (* Ideally we will take [c = imply_mm m] and zap it to ceil. However,
           [imply] requires [mm] to be constant. We get the floor of [mm] to
           construct the ceil of [c]. *)
        let cc = Mode.Guts.get_floor mm in
        let c = Mode.imply_const cc m in
        let c = Mode.zap_to_ceil c in
        (* Note that we did not mutate [mm] but simply took its floor, which
           might be mutated later. To satisfy the coherence condition (see the
           comment in the mli), we want to:

           - make it impossible that [imply_mm m > c], which is trivial since
           [mm >= cc] and thus [imply_mm m <= imply_cc m = c].
           - make it impossible that [imply_mm m < c], which is to ensure
           [imply_mm m >= c], equivalently [m >= meet_mm c], which is achieved
           by the following [submode].
        *)
        Mode.submode_exn (Mode.meet_const c mm) m;
        Const.Meet_const c

    let zap_to_id = zap_to_ceil

    let zap_to_floor = function
      | Const c -> c
      | Undefined -> Misc.fatal_error "modality Undefined should not be zapped."
      | Exactly (mm, m) ->
        (* The following zaps [mm] to ceil, which might conflict with future
           mode constraints on [mm]. We find constraining [mm] to [legacy] a
           good workaround. *)
        (* CR zqian: Find a better solution *)
        Mode.submode mm Mode.legacy |> ignore;
        let m = Mode.zap_to_floor m in
        let mm = Mode.zap_to_ceil mm in
        let c = Mode.Const.imply mm m in
        Const.Meet_const c

    let to_const_opt = function
      | Const c -> Some c
      | Undefined ->
        Misc.fatal_error "modality Undefined should not be looked at"
      | Exactly _ -> None

    let of_const c = Const c
  end

  module Axis = struct
    type 'a t =
      | Monadic : 'a Monadic.axis -> 'a Monadic.Atom.t t
      | Comonadic : 'a Comonadic.axis -> 'a Comonadic.Atom.t t

    type packed = P : 'a t -> packed

    let of_value : Value.Axis.packed -> packed = function
      | P (Monadic ax) -> P (Monadic ax)
      | P (Comonadic ax) -> P (Comonadic ax)

    let to_value : packed -> Value.Axis.packed = function
      | P (Monadic ax) -> P (Monadic ax)
      | P (Comonadic ax) -> P (Comonadic ax)
  end

  type atom = Atom : 'a Axis.t * 'a -> atom

  module Per_axis = struct
    open struct
      module Monadic = Monadic.Atom
      module Comonadic = Comonadic.Atom
    end

    let is_id : type a. a Axis.t -> a -> bool =
     fun ax t ->
      match ax with
      | Monadic ax -> Monadic.is_id ax t
      | Comonadic ax -> Comonadic.is_id ax t

    let is_constant : type a. a Axis.t -> a -> bool =
     fun ax t ->
      match ax with
      | Monadic ax -> Monadic.is_constant ax t
      | Comonadic ax -> Comonadic.is_constant ax t

    let print (type a) (ax : a Axis.t) ppf (t : a) =
      match ax, t with
      | Comonadic ax, Meet_const t ->
        Value.Comonadic.Const.Per_axis.print ax ppf t
      | Monadic ax, Join_const t -> Value.Monadic.Const.Per_axis.print ax ppf t
  end

  type error = Error : 'a Axis.t * 'a simple_error -> error

  type equate_error = equate_step * error

  module Const = struct
    module Monadic = Monadic.Const
    module Comonadic = Comonadic.Const

    type t = (Monadic.t, Comonadic.t) monadic_comonadic

    let id = { monadic = Monadic.id; comonadic = Comonadic.id }

    let is_id { monadic; comonadic } =
      Monadic.is_id monadic && Comonadic.is_id comonadic

    let sub t1 t2 : (unit, error) Result.t =
      match Monadic.sub t1.monadic t2.monadic with
      | Error (Error (ax, e)) -> Error (Error (Monadic ax, e))
      | Ok () -> (
        match Comonadic.sub t1.comonadic t2.comonadic with
        | Ok () -> Ok ()
        | Error (Error (ax, e)) -> Error (Error (Comonadic ax, e)))

    let equate = equate_from_submode' sub

    let apply ?hint t { monadic; comonadic } =
      let monadic =
        Monadic.apply
          ?hint:(Option.map (fun { monadic; _ } -> monadic) hint)
          t.monadic monadic
      in
      let comonadic =
        Comonadic.apply
          ?hint:(Option.map (fun { comonadic; _ } -> comonadic) hint)
          t.comonadic comonadic
      in
      { monadic; comonadic }

    let concat ~then_ t =
      let monadic = Monadic.concat ~then_:then_.monadic t.monadic in
      let comonadic = Comonadic.concat ~then_:then_.comonadic t.comonadic in
      { monadic; comonadic }

    let proj (type a) (ax : a Axis.t) { monadic; comonadic } : a =
      match ax with
      | Monadic ax -> Monadic.proj ax monadic
      | Comonadic ax -> Comonadic.proj ax comonadic

    let set (type a) (ax : a Axis.t) (a : a) { monadic; comonadic } : t =
      match ax with
      | Monadic ax -> { monadic = Monadic.set ax a monadic; comonadic }
      | Comonadic ax -> { monadic; comonadic = Comonadic.set ax a comonadic }

    let diff t1 t2 =
      List.filter_map
        (fun ax : atom option ->
          let (P ax) = Axis.of_value ax in
          let a1 = proj ax t1 in
          let a2 = proj ax t2 in
          if a1 = a2 then None else Some (Atom (ax, a2)))
        Value.Axis.all

    let print ppf { monadic; comonadic } =
      Fmt.fprintf ppf "%a;%a" Monadic.print monadic Comonadic.print comonadic
  end

  type t = (Monadic.t, Comonadic.t) monadic_comonadic

  let undefined : t = { monadic = Undefined; comonadic = Undefined }

  let is_undefined : t -> bool = function
    | { monadic = Undefined; comonadic = Undefined } -> true
    | _ -> false
  [@@ocaml.warning "-4"]

  let apply ?hint t { monadic; comonadic } =
    let monadic =
      Monadic.apply
        ?hint:(Option.map (fun { monadic; _ } -> monadic) hint)
        t.monadic monadic
    in
    let comonadic =
      Comonadic.apply
        ?hint:(Option.map (fun { comonadic; _ } -> comonadic) hint)
        t.comonadic comonadic
    in
    { monadic; comonadic }

  let sub_log t1 t2 ~log : (unit, error) Result.t =
    match Monadic.sub_log t1.monadic t2.monadic ~log with
    | Error (Error (ax, e)) -> Error (Error (Monadic ax, e))
    | Ok () -> (
      match Comonadic.sub_log t1.comonadic t2.comonadic ~log with
      | Ok () -> Ok ()
      | Error (Error (ax, e)) -> Error (Error (Comonadic ax, e)))

  let sub l r = try_with_log (sub_log l r)

  let equate m1 m2 = try_with_log (equate_from_submode sub_log m1 m2)

  let print ppf ({ monadic; comonadic } : t) =
    Fmt.fprintf ppf "%a;%a" Monadic.print monadic Comonadic.print comonadic

  let infer ~md_mode ~mode : t =
    let comonadic =
      Comonadic.infer ~md_mode:md_mode.comonadic ~mode:mode.comonadic
    in
    let monadic = Monadic.infer ~md_mode:md_mode.monadic ~mode:mode.monadic in
    { monadic; comonadic }

  let zap_to_id t =
    let { monadic; comonadic } = t in
    let comonadic = Comonadic.zap_to_id comonadic in
    let monadic = Monadic.zap_to_id monadic in
    { monadic; comonadic }

  let zap_to_floor t =
    let { monadic; comonadic } = t in
    let comonadic = Comonadic.zap_to_floor comonadic in
    let monadic = Monadic.zap_to_floor monadic in
    { monadic; comonadic }

  let to_const_opt t =
    let { monadic; comonadic } = t in
    Option.bind (Comonadic.to_const_opt comonadic) (fun comonadic ->
        Option.bind (Monadic.to_const_opt monadic) (fun monadic ->
            Some { monadic; comonadic }))

  let to_const_exn t = t |> to_const_opt |> Option.get

  let of_const { monadic; comonadic } =
    let comonadic = Comonadic.of_const comonadic in
    let monadic = Monadic.of_const monadic in
    { monadic; comonadic }

  let max =
    let monadic = Monadic.max in
    let comonadic = Comonadic.max in
    { monadic; comonadic }
end

module Crossing = struct
  (* The mode crossing capability of a type [t] is characterized by a monotone
     function [f] from modes to some lattice [L], in the following way:

     To check [e : t @ m1<= m2], we should instead check [f m1 <= f m2] to
     allow more programs.

     For example, if [f] is the identity function, then [t] does not cross modes
     at all. If [f] maps to the unit lattice (containing only one element), [f
     m1 <= f m2] always succeeds, which means [t] crosses modes fully.

     In practice, during mode checking we usually have either [m1] or [m2], but
     not both. In order to perform mode crossing one-sided, we require [f] to
     have left adjoint [fl] and right adjoint [fr], which gives:

     [f m1 <= f m2] is equivalent to [fl (f m1) <= m2] is equivalent to [m1 <=
     fr (f m2)]

     Therefore, we can perform any of the following for mode crossing:
     - Apply [f] on both [m1] and [m2]
     - Apply [fl ∘ f] on [m1]
     - Apply [fr ∘ f] on [m2]

     Mode crossing forms a lattice: [f1 <= f2] iff [f1] allows more mode
     crossing than [f2]. Concretely:

     [f1 <= f2] iff, for any [m1, m2], if [f2 m1 <= f2 m2],
     then [f1 m1 <= f1 m2].
  *)

  module Monadic = struct
    module Modality = Modality.Monadic
    module Mode = Value.Monadic

    module Atom = struct
      type 'a t = Modality of 'a Modality.Atom.t [@@unboxed]

      (* By the ordering of crossings (see comments above) [join_c1 <= join_c2]
         iff the following holds:
         For all [a,b], if [join_c2 a <= join_c2 b](E1), then [join_c1 a <=
         join_c1 b](E2)

         Case analysis by the relation between [c1] and [c2]:
         - If [c1 >= c2], then [c1] can be written as [join c2 k] for some [k].
           Then apply [join k] to E1 and we get E2 (by monotonicity of join).
         - If [c1 <= c2], take [a := c2] and [b := c1]. E1 holds but E2 doesn't.
         - If neither, then we take [a := c2] and [b := meet a c1]. E1 is
           satisfied:
           [join_c2 a = c2 <= c2 = join_c2 (meet a c1) = join_c2 b]. But E2 is
           not satisfied:
           [join_c1 a = join c1 c2 </= c1 = join_c1 (meet c1 c2) = join_c1 b]

         Therefore, [join_c1 <= join_c2] iff [c1 >= c2]. *)

      let min ax =
        Modality (Join_const ((Mode.Const.Per_axis.max [@inlined hint]) ax))

      let max ax =
        Modality (Join_const ((Mode.Const.Per_axis.min [@inlined hint]) ax))

      let le ax (Modality (Join_const c1)) (Modality (Join_const c2)) =
        (Mode.Const.Per_axis.le [@inlined hint]) ax c2 c1

      let equal ax (Modality (Join_const c1)) (Modality (Join_const c2)) =
        (Mode.Const.Per_axis.equal [@inlined hint]) ax c2 c1

      let join ax (Modality (Join_const c1)) (Modality (Join_const c2)) =
        Modality
          (Join_const ((Mode.Const.Per_axis.meet [@inlined hint]) ax c1 c2))

      let meet ax (Modality (Join_const c1)) (Modality (Join_const c2)) =
        Modality (Join_const (Mode.Const.Per_axis.join ax c1 c2))

      let print ax ppf (Modality (Join_const c)) =
        Mode.Const.Per_axis.print ax ppf c
    end

    type t = Modality of Modality.Const.t [@@unboxed]

    let create ~uniqueness:(Atom.Modality (Join_const uniqueness))
        ~contention:(Atom.Modality (Join_const contention))
        ~visibility:(Atom.Modality (Join_const visibility))
        ~staticity:(Atom.Modality (Join_const staticity)) =
      Modality (Join_const { uniqueness; contention; visibility; staticity })

    let modality m (Modality t) = Modality (Modality.Const.concat ~then_:t m)

    let apply_left (Modality (Join_const c)) m =
      Mode.subtract_const_unhint c (Mode.join_const_unhint c m)

    let apply_right (Modality (Join_const c)) m =
      (* The right adjoint of join is a restriction of identity *)
      Mode.join_const_unhint c m

    let proj (type a) (ax : a Mode.Axis.t) (Modality (Join_const c)) : a Atom.t
        =
      Modality (Join_const ((Axis.proj [@inlined hint]) ax c))

    let set (type a) (ax : a Mode.Axis.t) (Modality (Join_const a) : a Atom.t)
        (Modality (Join_const c)) =
      Modality (Join_const ((Axis.set [@inlined hint]) ax a c))

    let le (Modality (Join_const c1)) (Modality (Join_const c2)) =
      Mode.Const.le c2 c1

    let equal (Modality (Join_const c1)) (Modality (Join_const c2)) =
      Mode.Const.equal c1 c2

    let max = Modality (Join_const Mode.Const.min)

    let min = Modality (Join_const Mode.Const.max)

    let join (Modality (Join_const c1)) (Modality (Join_const c2)) =
      Modality (Join_const (Mode.Const.meet c1 c2))

    let meet (Modality (Join_const c1)) (Modality (Join_const c2)) =
      Modality (Join_const (Mode.Const.join c1 c2))

    let print ppf (Modality m) =
      Fmt.fprintf ppf "Modality %a" Modality.Const.print m
  end

  module Comonadic = struct
    module Modality = Modality.Comonadic
    module Mode = Value.Comonadic

    module Atom = struct
      type 'a t = Modality of 'a Modality.Atom.t [@@unboxed]

      (* The ordering of crossing here is derived similarly to the monadic
         fragment. See comments there. *)

      let min ax =
        Modality (Meet_const ((Mode.Const.Per_axis.min [@inlined hint]) ax))

      let max ax =
        Modality (Meet_const ((Mode.Const.Per_axis.max [@inlined hint]) ax))

      let le ax (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
        (Mode.Const.Per_axis.le [@inlined hint]) ax c1 c2

      let equal ax (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
        (Mode.Const.Per_axis.equal [@inlined hint]) ax c1 c2

      let join ax (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
        Modality
          (Meet_const ((Mode.Const.Per_axis.join [@inlined hint]) ax c1 c2))

      let meet ax (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
        Modality (Meet_const (Mode.Const.Per_axis.meet ax c1 c2))

      let print ax ppf (Modality (Meet_const c)) =
        Mode.Const.Per_axis.print ax ppf c
    end

    type t = Modality of Modality.Const.t [@@unboxed]

    let create ~regionality:(Atom.Modality (Meet_const areality))
        ~linearity:(Atom.Modality (Meet_const linearity))
        ~portability:(Atom.Modality (Meet_const portability))
        ~forkable:(Atom.Modality (Meet_const forkable))
        ~yielding:(Atom.Modality (Meet_const yielding))
        ~statefulness:(Atom.Modality (Meet_const statefulness)) =
      Modality
        (Meet_const
           { areality;
             linearity;
             portability;
             statefulness;
             forkable;
             yielding
           })

    let always_constructed_at c = Modality (Meet_const c)

    let proj (type a) (ax : a Mode.Axis.t) (Modality (Meet_const c)) : a Atom.t
        =
      Modality (Meet_const ((Axis.proj [@inlined hint]) ax c))

    let set (type a) (ax : a Mode.Axis.t) (Modality (Meet_const a) : a Atom.t)
        (Modality (Meet_const c)) =
      Modality (Meet_const ((Axis.set [@inlined hint]) ax a c))

    let modality m (Modality t) = Modality (Modality.Const.concat ~then_:t m)

    let apply_left (Modality (Meet_const c)) m =
      (* The left adjoint of meet is a restriction of identity *)
      Mode.meet_const_unhint c m

    let apply_right (Modality (Meet_const c)) m =
      Mode.imply_const_unhint c (Mode.meet_const_unhint c m)

    let le (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
      Mode.Const.le c1 c2

    let equal (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
      Mode.Const.equal c1 c2

    let max = Modality (Meet_const Mode.Const.max)

    let min = Modality (Meet_const Mode.Const.min)

    let join (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
      Modality (Meet_const (Mode.Const.join c1 c2))

    let meet (Modality (Meet_const c1)) (Modality (Meet_const c2)) =
      Modality (Meet_const (Mode.Const.meet c1 c2))

    let print ppf (Modality m) =
      Fmt.fprintf ppf "Modality %a" Modality.Const.print m
  end

  module Axis = struct
    type 'a t =
      | Monadic : 'a Value.Monadic.Axis.t -> 'a Monadic.Atom.t t
      | Comonadic : 'a Value.Comonadic.Axis.t -> 'a Comonadic.Atom.t t

    type packed = P : 'a t -> packed

    let of_modality : Modality.Axis.packed -> packed = function
      | P (Monadic ax) -> P (Monadic ax)
      | P (Comonadic ax) -> P (Comonadic ax)

    let to_modality : packed -> Modality.Axis.packed = function
      | P (Monadic ax) -> P (Monadic ax)
      | P (Comonadic ax) -> P (Comonadic ax)

    let compare : type a b. a t -> b t -> int =
     fun ax1 ax2 ->
      match ax1, ax2 with
      | Monadic ax1, Monadic ax2 -> Axis.compare ax1 ax2
      | Monadic _, _ -> -1
      | _, Monadic _ -> 1
      | Comonadic ax1, Comonadic ax2 -> Axis.compare ax1 ax2

    let equal : type a b. a t -> b t -> (a, b) Misc.is_eq =
     fun ax1 ax2 ->
      match ax1, ax2 with
      | Monadic ax1, Monadic ax2 -> (
        match Axis.equal ax1 ax2 with Is_eq -> Is_eq | Is_not_eq -> Is_not_eq)
      | Comonadic ax1, Comonadic ax2 -> (
        match Axis.equal ax1 ax2 with Is_eq -> Is_eq | Is_not_eq -> Is_not_eq)
      | (Monadic _ | Comonadic _), _ -> Is_not_eq

    let print : type a. Fmt.formatter -> a t -> unit =
     fun ppf -> function
      | Monadic ax -> Axis.print ppf ax
      | Comonadic ax -> Axis.print ppf ax
  end

  module Per_axis = struct
    open Axis

    let le : type a. a t -> a -> a -> bool =
     fun[@inline available] ax a b ->
      match ax with
      | Monadic ax -> (Monadic.Atom.le [@inlined hint]) ax a b
      | Comonadic ax -> (Comonadic.Atom.le [@inlined hint]) ax a b

    let equal : type a. a t -> a -> a -> bool =
     fun[@inline available] ax a b ->
      match ax with
      | Monadic ax -> (Monadic.Atom.equal [@inlined hint]) ax a b
      | Comonadic ax -> (Comonadic.Atom.equal [@inlined hint]) ax a b

    let min : type a. a t -> a = function[@inline available]
      | Monadic ax -> (Monadic.Atom.min [@inlined hint]) ax
      | Comonadic ax -> (Comonadic.Atom.min [@inlined hint]) ax

    let max : type a. a t -> a = function[@inline available]
      | Monadic ax -> (Monadic.Atom.max [@inlined hint]) ax
      | Comonadic ax -> (Comonadic.Atom.max [@inlined hint]) ax

    let meet : type a. a t -> a -> a -> a =
     fun[@inline available] ax a b ->
      match ax with
      | Monadic ax -> (Monadic.Atom.meet [@inlined hint]) ax a b
      | Comonadic ax -> (Comonadic.Atom.meet [@inlined hint]) ax a b

    let join : type a. a t -> a -> a -> a =
     fun[@inline available] ax a b ->
      match ax with
      | Monadic ax -> (Monadic.Atom.join [@inlined hint]) ax a b
      | Comonadic ax -> (Comonadic.Atom.join [@inlined hint]) ax a b

    let print : type a. a t -> Fmt.formatter -> a -> unit = function
      | Monadic ax -> Monadic.Atom.print ax
      | Comonadic ax -> Comonadic.Atom.print ax

    let print_obj = Axis.print

    let compare_obj = Axis.compare

    let equal_obj = Axis.equal
  end

  type t = (Monadic.t, Comonadic.t) monadic_comonadic

  let modality m { monadic; comonadic } =
    let monadic = Monadic.modality m.monadic monadic in
    let comonadic = Comonadic.modality m.comonadic comonadic in
    { monadic; comonadic }

  let apply_left_unhint t { monadic; comonadic } =
    let monadic = Monadic.apply_left t.monadic monadic in
    let comonadic = Comonadic.apply_left t.comonadic comonadic in
    { monadic; comonadic }

  let apply_left t m =
    m |> Value.disallow_right |> Value.unhint |> apply_left_unhint t
    |> Value.hint ~monadic:Crossing ~comonadic:Crossing

  let apply_right_unhint t { monadic; comonadic } =
    let monadic = Monadic.apply_right t.monadic monadic in
    let comonadic = Comonadic.apply_right t.comonadic comonadic in
    { monadic; comonadic }

  let apply_right t m =
    m |> Value.disallow_left |> Value.unhint |> apply_right_unhint t
    |> Value.hint ~monadic:Crossing ~comonadic:Crossing

  (* Our mode crossing is for [Value] modes, but can be extended to [Alloc]
     modes via [alloc_as_value], defined as follows:

     Given a mode crossing [f] for [Value], and we are to check [Alloc] submoding
     [m1 <= m2], we will instead check
     [f (alloc_as_value m1) <= f (alloc_as_value m2)].

     By adjunction tricks, this is equivalent to
     - [ m1 <= regional_to_global ∘ fr ∘ f ∘ alloc_as_value m2 ]
     - [ regional_to_local ∘ fl ∘ f ∘ alloc_as_value m1 <= m2 ]
     where [regional_to_global] is the right adjoint of [alloc_as_value], and
     [regional_to_local] the left adjoint. *)

  let apply_left_alloc t m =
    m |> Alloc.unhint |> alloc_as_value_unhint |> apply_left_unhint t
    |> value_to_alloc_r2l_unhint
    |> Alloc.hint ~comonadic:Crossing ~monadic:Crossing

  let apply_right_alloc t m =
    m |> Alloc.unhint |> alloc_as_value_unhint |> apply_right_unhint t
    |> value_to_alloc_r2g_unhint
    |> Alloc.hint ~comonadic:Crossing ~monadic:Crossing

  let apply_left_right_alloc t m =
    let { monadic; comonadic } = Alloc.unhint m in
    let monadic = Monadic.apply_right t.monadic monadic in
    let comonadic =
      comonadic |> comonadic_locality_as_regionality
      |> Comonadic.apply_left t.comonadic
      |> comonadic_regional_to_local
      (* the left adjoint of [locality_as_regionality]*)
    in
    Alloc.hint ~monadic:Crossing ~comonadic:Crossing { monadic; comonadic }

  let le t1 t2 =
    Monadic.le t1.monadic t2.monadic && Comonadic.le t1.comonadic t2.comonadic

  let max = { monadic = Monadic.max; comonadic = Comonadic.max }

  let min = { monadic = Monadic.min; comonadic = Comonadic.min }

  let join t1 t2 =
    { monadic = Monadic.join t1.monadic t2.monadic;
      comonadic = Comonadic.join t1.comonadic t2.comonadic
    }

  let meet t1 t2 =
    { monadic = Monadic.meet t1.monadic t2.monadic;
      comonadic = Comonadic.meet t1.comonadic t2.comonadic
    }

  let equal t1 t2 = le t1 t2 && le t2 t1

  let[@inline available] proj (type a) (ax : a Axis.t) { monadic; comonadic } :
      a =
    match ax with
    | Monadic ax -> (Monadic.proj [@inlined hint]) ax monadic
    | Comonadic ax -> (Comonadic.proj [@inlined hint]) ax comonadic

  let[@inline available] set (type a) (ax : a Axis.t) (a : a)
      { monadic; comonadic } : t =
    match ax with
    | Monadic ax ->
      { monadic = (Monadic.set [@inlined hint]) ax a monadic; comonadic }
    | Comonadic ax ->
      { monadic; comonadic = (Comonadic.set [@inlined hint]) ax a comonadic }

  let create ~regionality ~linearity ~uniqueness ~portability ~contention
      ~forkable ~yielding ~statefulness ~visibility ~staticity =
    let comonadic b ax =
      if b then Per_axis.min (Comonadic ax) else Per_axis.max (Comonadic ax)
    in
    let monadic b ax =
      if b then Per_axis.min (Monadic ax) else Per_axis.max (Monadic ax)
    in
    let regionality = comonadic regionality Areality in
    let linearity = comonadic linearity Linearity in
    let uniqueness = monadic uniqueness Uniqueness in
    let portability = comonadic portability Portability in
    let contention = monadic contention Contention in
    let forkable = comonadic forkable Forkable in
    let yielding = comonadic yielding Yielding in
    let statefulness = comonadic statefulness Statefulness in
    let visibility = monadic visibility Visibility in
    let staticity = monadic staticity Staticity in
    let monadic =
      Monadic.create ~uniqueness ~contention ~visibility ~staticity
    in
    let comonadic =
      Comonadic.create ~regionality ~linearity ~portability ~yielding ~forkable
        ~statefulness
    in
    { monadic; comonadic }

  let print ppf t =
    let l =
      List.filter_map
        (fun ax ->
          let (P ax) = ax |> Modality.Axis.of_value |> Axis.of_modality in
          let a = proj ax t in
          if Per_axis.(le ax (max ax) a)
          then None
          else Some (Fmt.asprintf "%a" (Per_axis.print ax) a))
        Value.Axis.all
    in
    Fmt.(pp_print_list ~pp_sep:pp_print_space pp_print_string ppf l)

  let to_modality
      { monadic = Monadic.Modality monadic;
        comonadic = Comonadic.Modality comonadic
      } =
    { monadic; comonadic }
end