File: py.ml

package info (click to toggle)
pyml 20231101-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 592 kB
  • sloc: ml: 7,043; ansic: 1,802; makefile: 317; sh: 13
file content (3068 lines) | stat: -rw-r--r-- 89,913 bytes parent folder | download
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
module Stdlib_printexc = Printexc
(* Workaround for opaque Printexc bug in Stdcompat 9 *)

open Stdcompat

type pyobject = Pytypes.pyobject

type input = Pytypes.input = Single | File | Eval

let string_of_input input =
  match input with
  | File -> "exec"
  | Eval -> "eval"
  | Single -> "single"

type 'a file = 'a Pytypes.file = Filename of string | Channel of 'a

type compare = Pytypes.compare = LT | LE | EQ | NE | GT | GE

type ucs = UCSNone | UCS2 | UCS4

type closure =
    WithoutKeywords of (pyobject -> pyobject)
  | WithKeywords of (pyobject -> pyobject -> pyobject)

external load_library: string option -> bool option -> unit = "py_load_library"
external is_debug_build: unit -> bool = "py_is_debug_build"
external unsetenv: string -> unit = "py_unsetenv"
external finalize_library: unit -> unit = "py_finalize_library"
external pywrap_closure: string option -> string -> closure -> pyobject
    = "pyml_wrap_closure"
external pynull: unit -> pyobject = "PyNull_wrapper"
external pynone: unit -> pyobject = "PyNone_wrapper"
external pytrue: unit -> pyobject = "PyTrue_wrapper"
external pyfalse: unit -> pyobject = "PyFalse_wrapper"
external pytuple_empty: unit -> pyobject = "PyTuple_Empty_wrapper"
external pyobject_callfunctionobjargs: pyobject -> pyobject array -> pyobject
    = "PyObject_CallFunctionObjArgs_wrapper"
external pyobject_callmethodobjargs: pyobject -> pyobject -> pyobject array
  -> pyobject = "PyObject_CallMethodObjArgs_wrapper"
external pyerr_fetch_internal: unit -> pyobject * pyobject * pyobject
    = "PyErr_Fetch_wrapper"
external pyerr_restore_internal: pyobject -> pyobject -> pyobject -> unit
    = "PyErr_Restore_wrapper"
external pystring_asstringandsize: pyobject -> string option
    = "PyString_AsStringAndSize_wrapper"
external pyobject_ascharbuffer: pyobject -> string option
    = "PyObject_AsCharBuffer_wrapper"
external pyobject_asreadbuffer: pyobject -> string option
    = "PyObject_AsReadBuffer_wrapper"
external pyobject_aswritebuffer: pyobject -> string option
    = "PyObject_AsWriteBuffer_wrapper"
external pylong_fromstring: string -> int -> pyobject * int
    = "PyLong_FromString_wrapper"
external pycapsule_isvalid: Pytypes.pyobject -> string -> int
      = "Python27_PyCapsule_IsValid_wrapper"
external pycapsule_check: Pytypes.pyobject -> int
      = "pyml_capsule_check"
external pyframe_new : string -> string -> int -> Pytypes.pyobject
      = "pyml_pyframe_new"

external ucs: unit -> ucs = "py_get_UCS"
(* Avoid warning 32. *)
let () = ignore (UCSNone, UCS2, UCS4)

let initialized = ref false

let is_initialized () = !initialized

let assert_initialized () =
  if not !initialized then
    failwith "Py.assert_initialized: run 'Py.initialize ()' first"

let version_value = ref ""

let version_major_value = ref 0

let version_minor_value = ref 0

let program_name = ref Sys.argv.(0)

let set_program_name s =
  program_name := s;
  if !initialized then
    if !version_major_value <= 2 then
      Pywrappers.Python2.py_setprogramname s
    else
      Pywrappers.Python3.py_setprogramname s

let python_home = ref None

let pythonpaths = ref []

let set_python_home s =
  python_home := (Some s);
  if !initialized then
    if !version_major_value <= 2 then
      Pywrappers.Python2.py_setpythonhome s
    else
      Pywrappers.Python3.py_setpythonhome s

let add_python_path path =
  pythonpaths := path :: !pythonpaths

let extract_version version_line =
  let before =
    try String.index version_line ' '
    with Not_found ->
      let msg =
        Printf.sprintf "Py.extract_version: cannot parse the version line '%s'"
          version_line in
      failwith msg in
  Pyutils.split_left_on_char ~from:(succ before) ' ' version_line

let extract_version_major_minor version =
  try
    if String.length version >= 3 && version.[1] = '.' then
      let major = int_of_string (String.sub version 0 1) in
      let minor =
        if String.length version = 3 || version.[3] = '.' then
          int_of_string (String.sub version 2 1)
        else if String.length version >= 5 && version.[4] = '.' then
          int_of_string (String.sub version 2 2)
        else
          raise Exit in
      (major, minor)
    else
      raise Exit
  with Exit | Failure _ ->
    let msg =
      Printf.sprintf
        "Py.extract_version_major_minor:\
          unable to parse the version number '%s'"
        version in
    failwith msg

let run_command ?(input = "") command read_stderr =
  let (input_channel, output, error) =
    Unix.open_process_full command (Unix.environment ()) in
  let result =
    try
      output_string output input;
      close_out output;
      Pyutils.input_lines (if read_stderr then error else input_channel)
    with _ ->
      begin
        try
          ignore (Unix.close_process_full (input_channel, output, error))
        with _ ->
          ()
      end;
      let msg =
        Printf.sprintf "Py.run_command: unable to read the result of '%s'"
          command in
      failwith msg in
  if Unix.close_process_full
       (input_channel, output, error) <> Unix.WEXITED 0 then
    begin
      let msg = Printf.sprintf "Py.run_command: unable to run '%s'" command in
      failwith msg;
    end;
  result

let run_command_opt ?input command read_stderr =
  try Some (run_command ?input command read_stderr)
  with Failure _ -> None

let parent_dir filename =
  let dirname = Filename.dirname filename in
  Filename.concat dirname Filename.parent_dir_name

let has_putenv = ref false

let has_set_pythonpath = ref None

let init_pythonhome verbose pythonhome =
  pythonhome <> "" &&
    try
      ignore (Sys.getenv "PYTHONHOME");
      false
    with Not_found ->
      if verbose then
        begin
          Printf.eprintf "Temporary set PYTHONHOME=\"%s\".\n" pythonhome;
          flush stderr;
        end;
      Unix.putenv "PYTHONHOME" pythonhome;
      has_putenv := true;
      true

let uninit_pythonhome () =
  if !has_putenv then
    begin
      unsetenv "PYTHONHOME";
      has_putenv := false
    end

let uninit_pythonpath () =
  match !has_set_pythonpath with
    None -> ()
  | Some old_pythonpath ->
      begin
        has_set_pythonpath := None;
        match old_pythonpath with
          None -> unsetenv "PYTHONPATH"
        | Some old_pythonpath' -> Unix.putenv "PYTHONPATH" old_pythonpath'
      end

let ldd executable =
  let command =
    match Pyml_arch.os with
    | Pyml_arch.Mac -> Printf.sprintf "otool -L %s" executable
    | _ -> Printf.sprintf "ldd %s" executable in
  match run_command_opt command false with
    None -> []
  | Some lines ->
     let extract_line line =
       String.trim
         (Pyutils.split_left_on_char '('
            (Pyutils.split_right_on_char '>' line)) in
     List.map extract_line lines

let ldconfig () =
  match run_command_opt "ldconfig -p" false with
    None -> []
  | Some lines ->
     let extract_line line =
       String.trim (Pyutils.split_right_on_char '>' line) in
     List.map extract_line lines

let libpython_from_interpreter python_full_path =
  let lines = ldd python_full_path in
  let is_libpython line =
    let basename = Filename.basename line in
    Stdcompat.String.starts_with ~prefix:"libpython" basename in
  List.find_opt is_libpython lines

let libpython_from_ldconfig major minor =
  let lines = ldconfig () in
  let prefix =
    match major, minor with
      None, _ -> "libpython"
    | Some major', None -> Printf.sprintf "libpython%d" major'
    | Some major', Some minor' ->
        Printf.sprintf "libpython%d.%d" major' minor' in
  let is_libpython line =
    let basename = Filename.basename line in
    Stdcompat.String.starts_with ~prefix:prefix basename in
  List.find_opt is_libpython lines

let parse_python_list list =
  let length = String.length list in
  let buffer = Buffer.create 17 in
  let rec parse_item accu index =
    if index < length then
      match list.[index] with
        '\'' ->
        begin
          let item = Buffer.contents buffer in
          let accu = item :: accu in
          if index + 1 < length then
            match list.[index + 1] with
              ']' ->
              if index + 2 = length then
                Some (List.rev accu)
              else
                None
            | ',' ->
               if list.[index + 2] = ' ' && list.[index + 3] = '\'' then
                 begin
                   Buffer.clear buffer;
                   parse_item accu (index + 4)
                 end
               else
                 None
            | _ ->
               None
          else
            None
        end
      | '\\' ->
         if index + 1 < length then
           begin
             match list.[index + 1] with
               '\n' -> parse_item accu (index + 2)
             | '0' .. '9' ->
                if index + 3 < length then
                  begin
                    let octal_number = String.sub list (index + 1) 3 in
                    let c = char_of_int (Pyutils.int_of_octal octal_number) in
                    Buffer.add_char buffer c;
                    parse_item accu (index + 4)
                  end
                else
                  None
             | 'x' ->
                if index + 2 < length then
                  begin
                    let hexa_number = String.sub list (index + 1) 2 in
                    let c = char_of_int (Pyutils.int_of_hex hexa_number) in
                    Buffer.add_char buffer c;
                    parse_item accu (index + 3)
                  end
                else
                  None
             | c ->
                begin
                  match
                    try
                      let c' =
                        match c with
                          '\\' -> '\\'
                        | '\'' -> '\''
                        | '"' -> '"'
                        | 'a' -> '\007'
                        | 'b' -> '\b'
                        | 'f' -> '\012'
                        | 'n' -> '\n'
                        | 'r' -> '\r'
                        | 't' -> '\t'
                        | 'v' -> '\011'
                        | _ -> raise Not_found in
                      Some c'
                    with Not_found -> None
                  with
                    None -> None
                  | Some c' ->
                     Buffer.add_char buffer c';
                    parse_item accu (index + 2)
                end
           end
         else
           None
      | c ->
         Buffer.add_char buffer c;
         parse_item accu (index + 1)
    else
      None in
  if length >= 2 && list.[0] == '[' then
    match list.[1] with
      '\'' ->
        Buffer.clear buffer;
        parse_item [] 2
    | ']' when length = 2 -> Some []
    | _ -> None
  else
    None

let pythonpaths_from_interpreter python_full_path =
  let command = "\
import sys
print(sys.path)
" in
  match
    try run_command ~input:command python_full_path false
    with Failure _ -> []
  with
    [path_line] ->
      begin
        match parse_python_list path_line with
          None -> []
        | Some paths -> paths
      end
  | _ -> []

let concat_library_filenames library_paths library_filenames =
  let expand_filepaths filename =
    filename ::
    List.map (fun path -> Filename.concat path filename) library_paths in
  List.concat (List.map expand_filepaths library_filenames)

let library_suffix =
  match Pyml_arch.os with
  | Pyml_arch.Mac -> ".dylib"
  | _ -> ".so"

let libpython_from_pkg_config version_major version_minor =
  let command =
    Printf.sprintf "pkg-config --libs python-%d.%d" version_major
      version_minor in
  match run_command_opt command false with
    Some (words :: _) ->
      let word_list = String.split_on_char ' ' words in
      let unable_to_parse () =
        let msg = Printf.sprintf
        "Py.find_library_path: unable to parse the output of pkg-config '%s'"
            words in
        failwith msg in
      let parse_word (library_paths, library_filename) word =
        if String.length word > 2 then
          match String.sub word 0 2 with
            "-L" ->
              let word' =
                Pyutils.substring_between word 2 (String.length word) in
              (word' :: library_paths, library_filename)
          | "-l" ->
              let word' =
                Pyutils.substring_between word 2 (String.length word) in
              if library_filename <> None then
                unable_to_parse ();
              let library_filename =
                Printf.sprintf "lib%s%s" word' library_suffix in
              (library_paths, Some library_filename)
          | _ -> (library_paths, library_filename)
        else (library_paths, library_filename) in
      let (library_paths, library_filename) =
        List.fold_left parse_word ([], None) word_list in
      let library_filename =
        match library_filename with
          None -> unable_to_parse ()
        | Some library_filename -> library_filename in
      Some (concat_library_filenames library_paths [library_filename])
  | _ -> None

let library_patterns : (int -> int -> string) list =
  match Pyml_arch.os with
  | Pyml_arch.Windows ->
      [Printf.sprintf "python%d%dm.dll"; Printf.sprintf "python%d%d.dll"]
  | Pyml_arch.Mac ->
      [Printf.sprintf "libpython%d.%dm.dylib";
        Printf.sprintf "libpython%d.%d.dylib"]
  | Pyml_arch.Unix ->
      [Printf.sprintf "libpython%d.%dm.so";
        Printf.sprintf "libpython%d.%d.so"]

let library_filenames_from_paths version_major version_minor paths =
  let library_filenames =
    List.map
      (fun format -> format version_major version_minor)
      library_patterns in
  concat_library_filenames paths library_filenames

let libpython_from_python_config version_major version_minor =
  let command =
    Printf.sprintf "python%d.%d-config --ldflags" version_major version_minor in
  match run_command_opt command false with
  | Some (words :: _) ->
      let word_list = String.split_on_char ' ' words in
      let parse_word library_paths word =
        if String.length word > 2 then
          match String.sub word 0 2 with
            "-L" ->
              let word' =
                Pyutils.substring_between word 2 (String.length word) in
              word' :: library_paths
          | _ -> library_paths
        else library_paths in
      let library_paths =
        List.fold_left parse_word [] word_list in
      Some (library_filenames_from_paths version_major version_minor library_paths)
  | _ -> None

let libpython_from_python_config_prefix version_major version_minor =
  let command =
    Printf.sprintf "python%d.%d-config --prefix" version_major version_minor in
  match run_command_opt command false with
  | Some (prefix :: _) ->
      let library_paths = [Filename.concat prefix "lib"] in
      Some (library_filenames_from_paths version_major version_minor library_paths)
  | _ -> None

let getenv_opt var =
  try Some (Sys.getenv var)
  with Not_found -> None

let libpython_from_pythonhome version_major version_minor python_full_path =
  let library_paths =
    match
      match getenv_opt "PYTHONHOME" with
      | Some python_home -> Some (Pyutils.split_left_on_char ':' python_home)
      | None ->
        match python_full_path with
        | Some python_full_path -> Some (parent_dir python_full_path)
        | None -> None
    with
      None -> failwith "Unable to find libpython!"
    | Some dir ->
        [Filename.concat dir "lib"] in
  library_filenames_from_paths version_major version_minor library_paths

let libpython_from_pythonpath version_major version_minor =
  match getenv_opt "PYTHONPATH" with
  | None -> None
  | Some pythonpath ->
    let paths = String.split_on_char ':' pythonpath in
    let python_zip = Printf.sprintf "python%d%d.zip" version_major version_minor in
    let is_python_zip filename =
      Filename.basename filename = python_zip in
    match List.find_opt is_python_zip paths with
    | None -> None
    | Some filename ->
      let dir = Filename.dirname filename in
      Some (library_filenames_from_paths version_major version_minor [dir])

let find_library_path version_major version_minor python_full_path =
  let heuristics = [
    (fun () ->
      Option.bind python_full_path (fun path ->
        Option.map (fun path -> [path]) (libpython_from_interpreter path)));
    (fun () ->
      Option.map (fun path -> [path])
        (libpython_from_ldconfig version_major version_minor));
    (fun () ->
      Option.bind version_major (fun version_major ->
        Option.bind version_minor (fun version_minor ->
          libpython_from_pkg_config version_major version_minor)));
    (fun () ->
      Option.bind version_major (fun version_major ->
        Option.bind version_minor (fun version_minor ->
          libpython_from_python_config_prefix version_major version_minor)));
    (fun () ->
      Option.bind version_major (fun version_major ->
        Option.bind version_minor (fun version_minor ->
          libpython_from_python_config version_major version_minor)));
    (fun () ->
      Option.bind version_major (fun version_major ->
        Option.bind version_minor (fun version_minor ->
          Some (libpython_from_pythonhome version_major version_minor
            python_full_path))));
    (fun () ->
      Option.bind version_major (fun version_major ->
        Option.bind version_minor (fun version_minor ->
          libpython_from_pythonpath version_major version_minor)));
  ] in
  List.concat (List.map (fun f -> Option.value ~default:[] (f ())) heuristics)

let python_version_from_interpreter interpreter =
  let version_line =
    let python_version_cmd = Printf.sprintf "\"%s\" --version" interpreter in
    try List.hd (run_command python_version_cmd false)
    with Failure _ -> List.hd (run_command python_version_cmd true) in
  extract_version version_line

let library_filename = ref None

let load_library filename =
  library_filename := filename;
  load_library filename None

let get_library_filename () = !library_filename

let find_library ~verbose ~version_major ~version_minor ~debug_build:_
    python_full_path =
  try
    load_library None
  with Failure _ ->
    let library_filenames =
      find_library_path version_major version_minor python_full_path in
    let errors = Buffer.create 17 in
    let rec try_load_library library_filenames =
      match library_filenames with
        [] ->
          let msg =
            Printf.sprintf
              "Py.find_library: unable to find the Python library%s"
              (Buffer.contents errors) in
          failwith msg
      | filename :: others ->
          begin
(*
            let pythonhome_set =
              not (Filename.is_implicit filename) &&
                init_pythonhome verbose (parent_dir filename) in
*)
            try
              if verbose then
                begin
                  Printf.eprintf "Trying to load \"%s\".\n" filename;
                  flush stderr;
                end;
              load_library (Some filename);
            with Failure msg ->
(*
              if pythonhome_set then
                uninit_pythonhome ();
*)
              if verbose then
                begin
                  Printf.eprintf "Failed: \"%s\".\n" msg;
                  flush stderr;
                end;
              Printf.bprintf errors " [%s returned %s]" filename msg;
              try_load_library others
          end in
    try_load_library library_filenames

let initialize_library ~verbose ~version_major ~version_minor
    ~debug_build python_full_path =
  begin
    match !python_home with
      None -> ()
    | Some s -> ignore (init_pythonhome verbose s)
  end;
  find_library ~verbose ~version_major ~version_minor ~debug_build
    python_full_path;
(*
  begin
    match python_full_path with
      None -> ()
    | Some python_full_path' ->
        let pythonhome =
          let dirname = Filename.dirname python_full_path' in
          if Filename.basename dirname = "bin" then
            Filename.concat dirname Filename.parent_dir_name
          else
            dirname in
        ignore (init_pythonhome verbose pythonhome);
  end;
*)
  set_program_name !program_name;
  begin
    match !python_home with
      None -> ()
    | Some s -> set_python_home s
  end

let get_version = Pywrappers.py_getversion

let which_command =
  match Pyml_arch.os with
  | Pyml_arch.Windows -> "where"
  | _ -> "command -v"

let which program =
  let exe =
    match Pyml_arch.os with
    | Pyml_arch.Windows ->
        if Filename.check_suffix program ".exe" then
          program
        else
          program ^ ".exe"
    | _ -> program in
  let command = Printf.sprintf "%s \"%s\"" which_command exe in
  match run_command_opt command false with
    Some (path :: _) -> Some path
  | _ -> None

let find_interpreter interpreter version minor =
  match interpreter with
    Some interpreter' ->
      if String.contains interpreter' '/' then
        Some interpreter'
      else
        which interpreter'
  | None ->
      match
        Option.bind version
           (fun version' ->
             match
               Option.bind minor
                 (fun minor' ->
                   which (Printf.sprintf "python%d.%d" version' minor'))
             with
             | Some result -> Some result
             | None -> which (Printf.sprintf "python%d" version'))
      with
      | Some result -> Some result
      | None ->
          match which "python" with
          | Some result -> Some result
          | None ->
              match which "python3" with
              | Some result -> Some result
              | None -> None

let version_mismatch interpreter found expected =
  Printf.sprintf
    "Version mismatch: %s is version %s but version %s is expected"
    interpreter found expected

let build_version_string major minor =
  Printf.sprintf "%d.%d" major minor

let path_separator =
  match Pyml_arch.os with
  | Pyml_arch.Windows -> ";"
  | _ -> ":"

(* Preserve signal behavior for sigint (Ctrl+C)
   (Reported by Arulselvan Madhavan,
    see https://github.com/thierry-martinez/pyml/issues/83)

   pythonlib changes the handling of sigint, making programs
   uninterruptible when the library is loaded.

   The following function restores sigint handling and `initialize`
   uses it except if ~python_sigint:true is passed.
 *)

let keep_sigint f =
  let previous_signal_behavior = Sys.signal Sys.sigint Sys.Signal_ignore in
  Sys.set_signal Sys.sigint previous_signal_behavior;
  Stdcompat.Fun.protect f
    ~finally:(fun () -> Sys.set_signal Sys.sigint previous_signal_behavior)

let initialize ?library_name ?interpreter ?version
    ?minor ?(verbose = false) ?debug_build ?(python_sigint = false) () =
  if !initialized then
    failwith "Py.initialize: already initialized";
  let do_initialize () =
    match library_name with
    | Some library_name ->
        load_library (Some library_name);
    | None ->
        try
          let python_full_path = find_interpreter interpreter version minor in
          let interpreter_pythonpaths =
            match python_full_path with
              None -> []
            | Some python_full_path' ->
                pythonpaths_from_interpreter python_full_path' in
          let new_pythonpaths =
            List.rev_append !pythonpaths interpreter_pythonpaths in
          if new_pythonpaths <> [] then
            begin
              let former_pythonpath = Sys.getenv_opt "PYTHONPATH" in
              has_set_pythonpath := Some former_pythonpath;
              let all_paths =
                match former_pythonpath with
                  None -> new_pythonpaths
                | Some former_pythonpath' ->
                    former_pythonpath' :: new_pythonpaths in
              let pythonpath = String.concat path_separator all_paths in
              if verbose then
                begin
                  Printf.eprintf "Temporary set PYTHONPATH=\"%s\".\n" pythonpath;
                  flush stderr;
                end;
              Unix.putenv "PYTHONPATH" pythonpath
          end;
          let (version_major, version_minor) =
            match python_full_path with
              Some python_full_path' ->
                let version_string =
                  python_version_from_interpreter python_full_path' in
                let (version_major, version_minor) =
                  extract_version_major_minor version_string in
                begin
                  match version with
                    None -> ()
                  | Some version_major' ->
                      if version_major <> version_major' then
                        failwith
                          (version_mismatch
                             python_full_path' (string_of_int version_major)
                             (string_of_int version_major'));
                      match minor with
                        None -> ()
                      | Some version_minor' ->
                          if version_minor <> version_minor' then
                            let expected =
                              build_version_string version_major version_minor in
                            let got =
                              build_version_string version_major' version_minor' in
                            failwith
                              (version_mismatch python_full_path' expected got);
                end;
                (Some version_major, Some version_minor)
            | _ -> version, minor in
          initialize_library ~verbose ~version_major ~version_minor ~debug_build
            python_full_path;
        with e ->
          uninit_pythonhome ();
          uninit_pythonpath ();
          raise e in
  if python_sigint then
    do_initialize ()
  else
    keep_sigint do_initialize;
  let version = get_version () in
  let (version_major, version_minor) =
    extract_version_major_minor version in
  version_value := version;
  version_major_value := version_major;
  version_minor_value := version_minor;
  initialized := true

let on_finalize_list = ref []

let on_finalize f = on_finalize_list := f :: !on_finalize_list

let finalize () =
  assert_initialized ();
  List.iter (fun f -> f ()) !on_finalize_list;
  Gc.full_major ();
  finalize_library ();
  uninit_pythonhome ();
  uninit_pythonpath ();
  initialized := false

let version () =
  assert_initialized ();
  !version_value

let version_major () =
  assert_initialized ();
  !version_major_value

let version_minor () =
  assert_initialized ();
  !version_minor_value

let version_pair () =
  assert_initialized ();
  (!version_major_value, !version_minor_value)

let null =
  pynull ()

let is_null v =
  v == null

let none =
  pynone ()

let is_none v =
  v == none

exception E of pyobject * pyobject

let create_ref_to_python_object () =
  let result = ref None in
  on_finalize (fun () -> result := None);
  result

let fetched_exception = create_ref_to_python_object ()

let ocaml_exception_class = create_ref_to_python_object ()

let ocaml_exception_capsule = create_ref_to_python_object ()

let python_exception () =
  let ptype, pvalue, ptraceback = pyerr_fetch_internal () in
  if
    match !ocaml_exception_class with
    | None -> false
    | Some ocaml_exception_class ->
        Lazy.is_val ocaml_exception_class &&
        Lazy.force ocaml_exception_class = ptype
  then
    begin
      let args = Pywrappers.pyobject_getattrstring pvalue "args" in
      assert (args <> null);
      let capsule = Pywrappers.pysequence_getitem args 0 in
      assert (capsule <> null);
      let exc, bt = snd (Option.get !ocaml_exception_capsule) capsule in
      Printexc.raise_with_backtrace exc bt
    end
  else
    begin
      fetched_exception := Some (ptype, pvalue, ptraceback);
      raise (E (ptype, pvalue))
    end

let check_not_null result =
  if result = null then
    python_exception ();
  result

let check_some s =
  match s with
    None -> python_exception ()
  | Some s -> s

let check_error () =
  if Pywrappers.pyerr_occurred () <> null then
    python_exception ()

let check_int result =
  if result = -1 then
    python_exception ()
  else
    result

let check_int64 result =
  if result = -1L then
    python_exception ()
  else
    result

let assert_int_success result =
  if result = -1 then
    python_exception ()

let bool_of_int i = check_int i <> 0

let get_program_name () =
  if !initialized then
    if !version_major_value <= 2 then
      Pywrappers.Python2.py_getprogramname ()
    else
      Pywrappers.Python3.py_getprogramname ()
  else
    !program_name

let get_python_home () =
  if !initialized then
    if !version_major_value <= 2 then
      Pywrappers.Python2.py_getpythonhome ()
    else
      Pywrappers.Python3.py_getpythonhome ()
  else
    match !python_home with
      None -> ""
    | Some s -> s

let get_program_full_path () =
  if version_major () <= 2 then
    Pywrappers.Python2.py_getprogramfullpath ()
  else
    Pywrappers.Python3.py_getprogramfullpath ()

let get_prefix () =
  if version_major () <= 2 then
    Pywrappers.Python2.py_getprogramfullpath ()
  else
    Pywrappers.Python3.py_getprogramfullpath ()

let get_exec_prefix () =
  if version_major () <= 2 then
    Pywrappers.Python2.py_getexecprefix ()
  else
    Pywrappers.Python3.py_getexecprefix ()

let get_path () =
  if version_major () <= 2 then
    Pywrappers.Python2.py_getpath ()
  else
    Pywrappers.Python3.py_getpath ()

let get_platform = Pywrappers.py_getplatform

let get_copyright = Pywrappers.py_getcopyright

let get_compiler = Pywrappers.py_getcompiler

let get_build_info = Pywrappers.py_getbuildinfo

let option result =
  if result = null then
    begin
      check_error ();
      None
    end
  else
    Some result

let check_found result =
  if result = null then
    begin
      check_error ();
      raise Not_found
    end
  else
    result

let option_of_error result =
  if result = null then
    begin
      let _ = pyerr_fetch_internal () in
      None
    end
  else
    Some result

let assert_not_null function_name obj =
  if is_null obj then
    invalid_arg (function_name ^ ": unallowed null argument")

module Eval = struct
  let call_object_with_keywords func arg keyword =
    assert_not_null "call_object_with_keywords(!, _, _)" func;
    assert_not_null "call_object_with_keywords(_, !, _)" arg;
    check_not_null (Pywrappers.pyeval_callobjectwithkeywords func arg keyword)

  let call_object func arg =
    call_object_with_keywords func arg null

  let get_builtins () = check_not_null (Pywrappers.pyeval_getbuiltins ())

  let get_globals () = check_not_null (Pywrappers.pyeval_getglobals ())

  let get_locals () = check_not_null (Pywrappers.pyeval_getlocals ())
end

let object_repr obj = check_not_null (Pywrappers.pyobject_repr obj)

module String_ = struct
  let as_UTF8_string s =
    assert_not_null "as_UTF8_string" s;
    let f =
      match ucs () with
        UCS2 -> Pywrappers.UCS2.pyunicodeucs2_asutf8string
      | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_asutf8string
      | UCSNone ->
          if !version_major_value >= 3 then
            Pywrappers.Python3.pyunicode_asutf8string
          else
            failwith "String.as_UTF8_string: unavailable" in
    check_not_null (f s)

  let of_string s =
    let len = String.length s in
    if !version_major_value >= 3 then
      check_not_null (Pywrappers.Python3.pyunicode_fromstringandsize s len)
    else
      check_not_null (Pywrappers.Python2.pystring_fromstringandsize s len)

  let of_bytes s =
    of_string (Bytes.unsafe_to_string s)
end

module Tuple_ = struct
  let create size =
    check_not_null (Pywrappers.pytuple_new size)

  let set_item s index value =
    assert_int_success (Pywrappers.pytuple_setitem s index value)

  let set = set_item

  let init size f =
    let result = create size in
    for index = 0 to size - 1 do
      let v = f index in
      assert_not_null "init" v;
      set_item result index v
    done;
    result

  let of_array array = init (Array.length array) (Array.get array)

  let of_list list = of_array (Array.of_list list)
end

let id x = x

module Dict_ = struct
  let create () =
    check_not_null (Pywrappers.pydict_new ())

  let set_item dict key value =
    assert_not_null "set_item(!, _)" dict;
    assert_not_null "set_item(_, !)" key;
    assert_int_success (Pywrappers.pydict_setitem dict key value)

  let of_bindings_map fkey fvalue list =
    let result = create () in
    List.iter begin fun (key, value) ->
      set_item result (fkey key) (fvalue value);
    end list;
    result

  let of_bindings = of_bindings_map id id

  let of_bindings_string = of_bindings_map String_.of_string id

  let set_item_string dict name value =
    assert_not_null "set_item_string" dict;
    assert_int_success (Pywrappers.pydict_setitemstring dict name value)
end

module Object_ = struct
  let call_function_obj_args callable args =
    check_not_null (pyobject_callfunctionobjargs callable args)
end

module Type = struct
  (* We rely on physical equality to check if an object is none as
     [pyml_wrap] ensures that the same ocaml value is always used
     to represent [None]. *)
  let is_none v = v == none

  let none = None

  type t =
      Unknown
    | Bool
    | Bytes
    | Callable
    | Capsule
    | Closure
    | Dict
    | Float
    | List
    | Int
    | Long
    | Module
    | None
    | Null
    | Tuple
    | Type
    | Unicode
    | Iter
    | Set

  external get: pyobject -> t = "pytype"

  let is_subtype a b =
    assert_not_null "of_tuple5(!, _)" a;
    assert_not_null "of_tuple5(_, !)" b;
    bool_of_int (Pywrappers.pytype_issubtype a b)

  let name t =
    match t with
      Unknown -> "Unknown"
    | Bool -> "Bool"
    | Bytes -> "Bytes"
    | Callable -> "Callable"
    | Capsule -> "Capsule"
    | Closure -> "Closure"
    | Dict -> "Dict"
    | Float -> "Float"
    | List -> "List"
    | Int -> "Int"
    | Long -> "Long"
    | Module -> "Module"
    | None -> "None"
    | Null -> "Null"
    | Tuple -> "Tuple"
    | Type -> "Type"
    | Unicode -> "Unicode"
    | Iter -> "Iter"
    | Set -> "Set"

  let to_string s =
    match get s with
      Bytes -> Some (pystring_asstringandsize s)
    | Unicode -> Some (pystring_asstringandsize (String_.as_UTF8_string s))
    | _ -> none

  let string_of_repr item =
    match to_string (object_repr item) with
      Some repr -> check_some repr
    | _ (* None *) -> failwith "Py.Object.string_of_repr"

  let mismatch t o =
    failwith
      (Printf.sprintf "Type mismatch: %s expected. Got: %s (%s)"
         t (name (get o)) (string_of_repr o))

  let create classname parents dict =
    let ty = Pywrappers.pytype_type () in
    let classname = String_.of_string classname in
    let parents = Tuple_.of_list parents in
    let dict = Dict_.of_bindings_string dict in
    Object_.call_function_obj_args ty [| classname; parents; dict |]
end

module Capsule = struct
  type 'a t = {
    wrap : 'a -> pyobject;
    unwrap : pyobject -> 'a;
  }

  let is_valid v name  = pycapsule_isvalid v name <> 0

  let check v = is_valid v "ocaml-capsule"

  let table = Hashtbl.create 17

  let () = on_finalize (fun () -> Hashtbl.clear table)

  external unsafe_wrap_value: 'a -> pyobject = "pyml_wrap_value"

  external unsafe_unwrap_value: pyobject -> 'a = "pyml_unwrap_value"

  let make name =
    try
      Hashtbl.find table name;
      failwith
        (Printf.sprintf "Py.Capsule.make: capsule of type %s already defined"
           name)
    with Not_found ->
      Hashtbl.add table name ();
      let wrap v = unsafe_wrap_value (name, v) in
      let unwrap x =
        if pycapsule_check x = 0 then
          Type.mismatch "capsule" x;
        let name', v = unsafe_unwrap_value x in
        if name <> name' then
          failwith
            (Printf.sprintf
               "Py.Capsule: capsule of type %s, but type %s expected"
               name' name);
        v in
      (wrap, unwrap)

  let create name =
    let wrap, unwrap = make name in
    { wrap; unwrap }

  let type_of x =
    if pycapsule_check x = 0 then
      Type.mismatch "capsule" x;
    fst (unsafe_unwrap_value x)
end

module Mapping = struct
  let check v = Pywrappers.pymapping_check v <> 0

  let get_item_string mapping key =
    option (Pywrappers.pymapping_getitemstring mapping key)

  let find_string mapping key =
    check_found (Pywrappers.pymapping_getitemstring mapping key)

  let find_string_opt = get_item_string

  let has_key mapping key = Pywrappers.pymapping_haskey mapping key <> 0

  let has_key_string mapping key =
    Pywrappers.pymapping_haskeystring mapping key <> 0

  let length mapping = check_int (Pywrappers.pymapping_length mapping)

  let set_item_string mapping key value =
    assert_int_success (Pywrappers.pymapping_setitemstring mapping key value)

  let size mapping = check_int (Pywrappers.pymapping_size mapping)
end

module Method = struct
  let create func self cl =
    assert_not_null "create(!, _, _)" func;
    assert_not_null "create(_, !, _)" self;
    assert_not_null "create(_, _, !)" cl;
    check_not_null (Pywrappers.pymethod_new func self cl)

  let get_function m =
    assert_not_null "get_function" m;
    check_not_null (Pywrappers.pymethod_function m)

  let self m =
    assert_not_null "self" m;
    option (Pywrappers.pymethod_self m)
end

module Bool = struct
  let t = pytrue ()

  let is_true v =
    v == t

  let f = pyfalse ()

  let is_false v =
    v == f

  let check v = v = t || v = f

  let of_bool b = if b then t else f

  let to_bool v =
    if v = t then true
    else if v = f then false
    else Type.mismatch "True or False" v
end

module Float = struct
  let check o = Type.get o = Type.Float

  let of_float = Pywrappers.pyfloat_fromdouble

  let to_float v =
    let result = Pywrappers.pyfloat_asdouble v in
    if result = -1.0 then
      check_error ();
    result
end

type byteorder =
    LittleEndian
  | BigEndian

let string_length = String.length

module String__ = struct
  include String_

  let check_bytes s =
    Type.get s = Type.Bytes

  let check_unicode s =
    Type.get s = Type.Unicode

  let check s =
    match Type.get s with
      Type.Bytes | Type.Unicode -> true
    | _ -> false

  let decode_UTF8 ?errors ?size s =
    let size' =
      match size with
        None -> String.length s
      | Some size' -> size' in
    let f =
      match ucs () with
        UCS2 -> Pywrappers.UCS2.pyunicodeucs2_decodeutf8
      | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_decodeutf8
      | UCSNone ->
          if !version_major_value >= 3 then
            Pywrappers.Python3.pyunicode_decodeutf8
          else
            failwith "Py.String.decode_UTF8: unavailable" in
    check_not_null (f s size' errors)

  let decode_UTF16_32 decode_ucs2 decode_ucs4 decode_python3 errors size
      byteorder s =
    let size' =
      match size with
        None -> String.length s
      | Some size' -> size' in
    let byteorder' =
      match byteorder with
        None -> 0
      | Some LittleEndian -> -1
      | Some BigEndian -> 1 in
    let byteorder_ref = ref byteorder' in
    let f =
      match ucs () with
        UCS2 -> decode_ucs2
      | UCS4 -> decode_ucs4
      | UCSNone ->
          if !version_major_value >= 3 then
            decode_python3
          else
            failwith "Py.String.decode_UTF16/32: unavailable" in
    let decoded_string = check_not_null (f s size' errors byteorder_ref) in
    let decoded_byteorder =
      match !byteorder_ref with
        -1 -> LittleEndian
      | 1 -> BigEndian
      | _ -> failwith "Py.String.decode_UTF16/32: unknown endianess value" in
    (decoded_string, decoded_byteorder)

  let decode_UTF16 ?errors ?size ?byteorder s =
    decode_UTF16_32 Pywrappers.UCS2.pyunicodeucs2_decodeutf16
      Pywrappers.UCS4.pyunicodeucs4_decodeutf16
      Pywrappers.Python3.pyunicode_decodeutf16 errors size byteorder s

  let decode_UTF32 ?errors ?size ?byteorder s =
    decode_UTF16_32 Pywrappers.UCS2.pyunicodeucs2_decodeutf32
      Pywrappers.UCS4.pyunicodeucs4_decodeutf32
      Pywrappers.Python3.pyunicode_decodeutf32 errors size byteorder s

  let of_unicode ?size int_array =
    let size' =
      match size with
        None -> Array.length int_array
      | Some size' -> size' in
    let f =
      match ucs () with
        UCS2 -> Pywrappers.UCS2.pyunicodeucs2_fromunicode
      | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_fromunicode
      | UCSNone ->
          if !version_major_value >= 3 then
            Pywrappers.Python3.pyunicode_fromkindanddata 4
          else
            failwith "Py.String.of_unicode: unavailable" in
    check_not_null (f int_array size')

  let to_unicode s =
    assert_not_null "to_unicode" s;
    let f =
      match ucs () with
        UCS2 -> Pywrappers.UCS2.pyunicodeucs2_asunicode
      | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_asunicode
      | UCSNone ->
          if !version_major_value >= 3 then
            Pywrappers.Python3.pyunicode_asucs4copy
          else
            failwith "Py.String.to_unicode: unavailable" in
    check_some (f s)

  let string_type_mismatch obj = Type.mismatch "String or Unicode" obj

  let format fmt args =
    match Type.get fmt with
      Type.Unicode ->
        let f =
          match ucs () with
            UCS2 -> Pywrappers.UCS2.pyunicodeucs2_format
          | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_format
          | UCSNone ->
              if !version_major_value >= 3 then
                Pywrappers.Python3.pyunicode_format
              else
                failwith "Py.String.format: unavailable" in
        check_not_null (f fmt args)
    | Type.Bytes ->
        if !version_major_value >= 3 then
          failwith "No format on Bytes in Python 3"
        else
          check_not_null (Pywrappers.Python2.pystring_format fmt args)
    | _ -> string_type_mismatch fmt

  let length s =
    match Type.get s with
      Type.Unicode ->
        let f =
          match ucs () with
            UCS2 -> Pywrappers.UCS2.pyunicodeucs2_getsize
          | UCS4 -> Pywrappers.UCS4.pyunicodeucs4_getsize
          | UCSNone ->
              if !version_major_value >= 3 then
                Pywrappers.Python3.pyunicode_getlength
              else
                failwith "Py.String.length: unavailable" in
        f s
    | Type.Bytes ->
        if !version_major_value >= 3 then
          Pywrappers.Python3.pybytes_size s
        else
          Pywrappers.Python2.pystring_size s
    | _ -> string_type_mismatch s

  let to_string s =
    match Type.to_string s with
      None -> string_type_mismatch s
    | Some s -> check_some s

  let to_bytes s =
    Bytes.unsafe_of_string (to_string s)
end

module Bytes = struct
  include String__

  let of_string s =
    let len = String.length s in
    if !version_major_value >= 3 then
      check_not_null (Pywrappers.Python3.pybytes_fromstringandsize s len)
    else
      check_not_null (Pywrappers.Python2.pystring_fromstringandsize s len)

  let of_bytes s =
    of_string (Bytes.unsafe_to_string s)
end

module String = String__

module Err = struct
  type t =
    Exception
  | StandardError
  | ArithmeticError
  | LookupError
  | AssertionError
  | AttributeError
  | EOFError
  | EnvironmentError
  | FloatingPointError
  | IOError
  | ImportError
  | IndexError
  | KeyError
  | KeyboardInterrupt
  | MemoryError
  | NameError
  | NotImplementedError
  | OSError
  | OverflowError
  | ReferenceError
  | RuntimeError
  | SyntaxError
  | SystemExit
  | TypeError
  | ValueError
  | ZeroDivisionError
  | StopIteration

  let clear () =
    Pywrappers.pyerr_clear ();
    fetched_exception := None

  let exception_matches exc = Pywrappers.pyerr_exceptionmatches exc <> 0

  let fetch () =
    let (ptype, pvalue, ptraceback) = pyerr_fetch_internal () in
    if ptype = null then
      None
    else
      Some (ptype, pvalue, ptraceback)

  let fetched () = !fetched_exception

  let given_exception_matches given exc =
    Pywrappers.pyerr_givenexceptionmatches given exc <> 0

  let occurred () = option (Pywrappers.pyerr_occurred ())

  let print () =
    Pywrappers.pyerr_print ()

  let print_ex i =
    Pywrappers.pyerr_printex i

  let restore = pyerr_restore_internal

  let restore_tuple (ptype, pvalue, ptraceback) =
    restore ptype pvalue ptraceback

  let restore_fetch () =
    match fetch () with
      Some tuple -> restore_tuple tuple
    | None -> failwith "restore_fetch"

  let restore_fetched () =
    match fetched () with
      Some tuple -> restore_tuple tuple
    | None -> failwith "restore_fetched"

  let set_none = Pywrappers.pyerr_setnone

  let set_string = Pywrappers.pyerr_setstring

  let set_object = Pywrappers.pyerr_setobject

  let of_error = function
      Exception -> Pywrappers.pyexc_exception ()
    | StandardError ->
        if !version_major_value <= 2 then
          Pywrappers.Python2.pyexc_standarderror ()
        else
          Pywrappers.pyexc_exception ()
    | ArithmeticError -> Pywrappers.pyexc_arithmeticerror ()
    | LookupError -> Pywrappers.pyexc_lookuperror ()
    | AssertionError -> Pywrappers.pyexc_assertionerror ()
    | AttributeError -> Pywrappers.pyexc_attributeerror ()
    | EOFError -> Pywrappers.pyexc_eoferror ()
    | EnvironmentError -> Pywrappers.pyexc_environmenterror ()
    | FloatingPointError -> Pywrappers.pyexc_floatingpointerror ()
    | IOError -> Pywrappers.pyexc_ioerror ()
    | ImportError -> Pywrappers.pyexc_importerror ()
    | IndexError -> Pywrappers.pyexc_indexerror ()
    | KeyError -> Pywrappers.pyexc_keyerror ()
    | KeyboardInterrupt -> Pywrappers.pyexc_keyboardinterrupt ()
    | MemoryError -> Pywrappers.pyexc_memoryerror ()
    | NameError -> Pywrappers.pyexc_nameerror ()
    | NotImplementedError -> Pywrappers.pyexc_notimplementederror ()
    | OSError -> Pywrappers.pyexc_oserror ()
    | OverflowError -> Pywrappers.pyexc_overflowerror ()
    | ReferenceError -> Pywrappers.pyexc_referenceerror ()
    | RuntimeError -> Pywrappers.pyexc_runtimeerror ()
    | SyntaxError -> Pywrappers.pyexc_syntaxerror ()
    | SystemExit -> Pywrappers.pyexc_systemerror ()
    | TypeError -> Pywrappers.pyexc_typeerror ()
    | ValueError -> Pywrappers.pyexc_valueerror ()
    | ZeroDivisionError -> Pywrappers.pyexc_zerodivisionerror ()
    | StopIteration -> Pywrappers.pyexc_stopiteration ()

  let set_error error msg =
    set_object (of_error error) (String.of_string msg)

  let set_interrupt () =
    Pywrappers.pyerr_setinterrupt ()

  let set_interrupt_ex signal =
    if version_pair () < (3, 10) then
      failwith "set_interrupt_ex: only available with Python >= 3.10";
    Pywrappers.pyerr_setinterruptex signal
end

exception Err of Err.t * string

let attribute_error = "AttributeError"

let check_found_catch error result =
  try
    check_found result
  with E (ty, _)
  when
    String.to_string (check_found (Pywrappers.pyobject_getattrstring ty "__name__")) = error ->
    raise Not_found

module Object = struct
  include Object_

  type t = Pytypes.pyobject

  let del_item obj item =
    assert_not_null "del_item(!, _)" obj;
    assert_not_null "del_item(_, !)" item;
    assert_int_success (Pywrappers.pyobject_delitem obj item)

  let del_item_string obj item =
    assert_int_success (Pywrappers.pyobject_delitemstring obj item)

  let get_attr obj attr =
    assert_not_null "get_attr(!, _)" obj;
    assert_not_null "get_attr(_, !)" attr;
    option (Pywrappers.pyobject_getattr obj attr)

  let find_attr_string obj attr =
    assert_not_null "find_attr_string" obj;
    check_found_catch attribute_error (Pywrappers.pyobject_getattrstring obj attr)

  let find_attr_string_err obj attr =
    assert_not_null "find_attr_string" obj;
    check_not_null (Pywrappers.pyobject_getattrstring obj attr)

  let get_attr_string obj attr =
    assert_not_null "find_attr_string" obj;
    option_of_error (Pywrappers.pyobject_getattrstring obj attr)

  let find_attr obj attr =
    assert_not_null "find_attr(!, _)" obj;
    assert_not_null "find_attr(_, !)" attr;
    check_found_catch attribute_error (Pywrappers.pyobject_getattr obj attr)

  let find_attr_err obj attr =
    assert_not_null "find_attr(!, _)" obj;
    assert_not_null "find_attr(_, !)" attr;
    check_not_null (Pywrappers.pyobject_getattr obj attr)

  let find_attr_opt = get_attr

  let find_attr_string_opt = get_attr_string

  let get_item obj key =
    option (Pywrappers.pyobject_getitem obj key)

  let find obj attr =
    check_found_catch "KeyError" (Pywrappers.pyobject_getitem obj attr)

  let find_err obj attr =
    check_not_null (Pywrappers.pyobject_getitem obj attr)

  let find_opt = get_item

  let get_item_string obj key = get_item obj (String.of_string key)

  let find_string obj key = find obj (String.of_string key)

  let find_string_err obj key = find_err obj (String.of_string key)

  let find_string_opt = get_item_string

  let get_iter obj =
    assert_not_null "get_iter" obj;
    check_not_null (Pywrappers.pyobject_getiter obj)

  let get_type obj =
    assert_not_null "get_type" obj;
    check_not_null (Pywrappers.pyobject_type obj)

  let has_attr obj attr =
    assert_not_null "has_attr(!, _)" obj;
    assert_not_null "has_attr(_, !)" attr;
    bool_of_int (Pywrappers.pyobject_hasattr obj attr)

  let has_attr_string obj attr =
    assert_not_null "has_attr_string" obj;
    bool_of_int (Pywrappers.pyobject_hasattrstring obj attr)

  let hash obj =
    assert_not_null "hash" obj;
    check_int64 (Pywrappers.pyobject_hash obj)

  let is_true obj =
    assert_not_null "is_true" obj;
    bool_of_int (Pywrappers.pyobject_istrue obj)

  let not obj =
    assert_not_null "not" obj;
    bool_of_int (Pywrappers.pyobject_istrue obj)

  let is_instance obj cls =
    assert_not_null "is_instance" obj;
    bool_of_int (Pywrappers.pyobject_isinstance obj cls)

  let is_subclass cls1 cls2 =
    assert_not_null "is_subclass(!, _)" cls1;
    assert_not_null "is_subclass(_, !)" cls2;
    bool_of_int (Pywrappers.pyobject_issubclass cls1 cls2)

  let print obj out_channel =
    assert_int_success
      (Pywrappers.pyobject_print obj
         (Pytypes.file_map Unix.descr_of_out_channel out_channel) 1)

  let repr = object_repr

  let rich_compare a b cmp =
    check_not_null (Pywrappers.pyobject_richcompare a b cmp)

  let rich_compare_bool a b cmp =
    bool_of_int (Pywrappers.pyobject_richcomparebool a b cmp)

  let set_attr obj attr value =
    assert_not_null "set_attr(!, _, _)" obj;
    assert_not_null "set_attr(_, !, _)" attr;
    assert_int_success (Pywrappers.pyobject_setattr obj attr value)

  let set_attr_string obj attr value =
    assert_not_null "set_attr_string" obj;
    assert_int_success (Pywrappers.pyobject_setattrstring obj attr value)

  let del_attr obj attr = set_attr obj attr null

  let del_attr_string obj attr = set_attr_string obj attr null

  let set_item obj key value =
    assert_int_success (Pywrappers.pyobject_setitem obj key value)

  let set_item_string obj key value = set_item obj (String.of_string key) value

  let str obj = check_not_null (Pywrappers.pyobject_str obj)

  let string_of_repr = Type.string_of_repr

  let to_string item = String.to_string (str item)

  let as_char_buffer obj = check_some (pyobject_ascharbuffer obj)

  let as_read_buffer obj = check_some (pyobject_asreadbuffer obj)

  let as_write_buffer obj = check_some (pyobject_aswritebuffer obj)

  external reference_count: pyobject -> int = "pyrefcount"

  let repr_or_string repr v =
    if repr then string_of_repr v
    else to_string v

  let robust_to_string repr v =
    if !initialized then
      try
        try
          repr_or_string repr v
        with E (_ty, _value) ->
          repr_or_string (Stdlib.not repr) v
      with E (ty, value) ->
        Printf.sprintf "[ERROR] %s: %s" (to_string ty) (to_string value)
    else
      "<python value: run 'Py.initialize ()' to print it>"

  let format fmt v =
    Format.pp_print_string fmt (robust_to_string false v)

  let format_repr fmt v =
    Format.pp_print_string fmt (robust_to_string true v)

  let call_method_obj_args obj name args =
    assert_not_null "call_method_obj_args(!, _, _)" obj;
    assert_not_null "call_method_obj_args(_, !, _)" name;
    check_not_null (pyobject_callmethodobjargs obj name args)

  let call_method obj name args =
    call_method_obj_args obj (String.of_string name) args

  let call callable args kw =
    assert_not_null "call(!, _, _)" callable;
    assert_not_null "call(_, !, _)" args;
    check_not_null (Pywrappers.pyobject_call callable args kw)

  let size obj =
    assert_not_null "size" obj;
    check_int (Pywrappers.pyobject_size obj)

  let dir obj =
    assert_not_null "dir" obj;
    check_not_null (Pywrappers.pyobject_dir obj)
end

let exception_printer exn =
  match exn with
    E (ty, value) when !initialized ->
      Some (
      Printf.sprintf "E (%s, %s)" (Object.to_string ty)
        (Object.to_string value))
  | _ -> None

let () = Stdlib_printexc.register_printer exception_printer

module Long = struct
  let check o = Type.get o = Type.Long

  let of_int64 v =
    check_not_null (Pywrappers.pylong_fromlong v)

  let to_int64 v =
    let result = Pywrappers.pylong_aslong v in
    check_error ();
    result

  let of_int v = of_int64 (Int64.of_int v)

  let to_int v = Int64.to_int (to_int64 v)

  let from_string str base =
    let result = pylong_fromstring str base in
    ignore (check_not_null (fst result));
    result

  let of_string ?(base = 0) s =
    let value, len = from_string s base in
    if len <> string_length s then
      failwith "Py.Long.of_string";
    value

  let to_string = Object.to_string
end

module Int = struct
  let check o = Type.get o = Type.Long

  let of_int64 v =
    if version_major () >= 3 then
      Long.of_int64 v
    else
      check_not_null (Pywrappers.Python2.pyint_fromlong v)

  let to_int64 v =
    if version_major () >= 3 then
      Long.to_int64 v
    else
      let result = Pywrappers.Python2.pyint_aslong v in
      check_error ();
      result

  let of_int v = of_int64 (Int64.of_int v)

  let to_int v = Int64.to_int (to_int64 v)

  let of_string = Long.of_string

  let to_string = Long.to_string
end

module Number = struct
  let absolute v = check_not_null (Pywrappers.pynumber_absolute v)

  let add v0 v1 =
    assert_not_null "add(!, _)" v0;
    assert_not_null "add(_, !)" v1;
    check_not_null (Pywrappers.pynumber_add v0 v1)

  let number_and v0 v1 =
    assert_not_null "number_and(!, _)" v0;
    assert_not_null "number_and(_, !)" v1;
    check_not_null (Pywrappers.pynumber_and v0 v1)

  let _check v = Pywrappers.pynumber_check v <> 0

  let divmod v0 v1 =
    assert_not_null "divmod(!, _)" v0;
    assert_not_null "divmod(_, !)" v1;
    check_not_null (Pywrappers.pynumber_divmod v0 v1)

  let float v = check_not_null (Pywrappers.pynumber_float v)

  let floor_divide v0 v1 =
    assert_not_null "floor_divide(!, _)" v0;
    assert_not_null "floor_divide(_, !)" v1;
    check_not_null (Pywrappers.pynumber_floordivide v0 v1)

  let in_place_add v0 v1 =
    assert_not_null "in_place_add(!, _)" v0;
    assert_not_null "in_place_add(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplaceadd v0 v1)

  let in_place_and v0 v1 =
    assert_not_null "in_place_and(!, _)" v0;
    assert_not_null "in_place_and(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplaceand v0 v1)

  let in_place_floor_divide v0 v1 =
    assert_not_null "in_place_floor_divide(!, _)" v0;
    assert_not_null "in_place_floor_divide(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacefloordivide v0 v1)

  let in_place_lshift v0 v1 =
    assert_not_null "in_place_lshift(!, _)" v0;
    assert_not_null "in_place_lshift(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacelshift v0 v1)

  let in_place_multiply v0 v1 =
    assert_not_null "in_place_multiply(!, _)" v0;
    assert_not_null "in_place_multiply(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacemultiply v0 v1)

  let in_place_or v0 v1 =
    assert_not_null "in_place_or(!, _)" v0;
    assert_not_null "in_place_or(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplaceor v0 v1)

  let in_place_power ?(modulo = none) v0 v1 =
    assert_not_null "in_place_power(?modulo:!, _, _)" modulo;
    assert_not_null "in_place_power(?modulo:_, !, _)" v0;
    assert_not_null "in_place_power(?modulo:_, _, _)" v1;
    check_not_null (Pywrappers.pynumber_inplacepower v0 v1 modulo)

  let in_place_remainder v0 v1 =
    assert_not_null "in_place_remainder(!, _)" v0;
    assert_not_null "in_place_remainder(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplaceremainder v0 v1)

  let in_place_rshift v0 v1 =
    assert_not_null "in_place_rshift(!, _)" v0;
    assert_not_null "in_place_rshift(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacershift v0 v1)

  let in_place_subtract v0 v1 =
    assert_not_null "in_place_substract(!, _)" v0;
    assert_not_null "in_place_substract(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacesubtract v0 v1)

  let in_place_true_divide v0 v1 =
    assert_not_null "in_place_true_divide(!, _)" v0;
    assert_not_null "in_place_true_divide(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacetruedivide v0 v1)

  let in_place_xor v0 v1 =
    assert_not_null "in_place_xor(!, _)" v0;
    assert_not_null "in_place_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_inplacexor v0 v1)

  let invert v =
    assert_not_null "invert" v;
    check_not_null (Pywrappers.pynumber_invert v)

  let lshift v0 v1 =
    assert_not_null "in_place_xor(!, _)" v0;
    assert_not_null "in_place_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_lshift v0 v1)

  let multiply v0 v1 =
    assert_not_null "in_place_xor(!, _)" v0;
    assert_not_null "in_place_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_multiply v0 v1)

  let negative v =
    assert_not_null "negative" v;
    check_not_null (Pywrappers.pynumber_negative v)

  let number_or v0 v1 =
    assert_not_null "in_place_xor(!, _)" v0;
    assert_not_null "in_place_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_or v0 v1)

  let positive v =
    assert_not_null "positive" v;
    check_not_null (Pywrappers.pynumber_positive v)

  let power ?(modulo = none) v0 v1 =
    assert_not_null "in_place_power(?modulo:!, _, _)" modulo;
    assert_not_null "in_place_power(?modulo:_, !, _)" v0;
    assert_not_null "in_place_power(?modulo:_, _, _)" v1;
    check_not_null (Pywrappers.pynumber_power v0 v1 modulo)

  let remainder v0 v1 =
    assert_not_null "remainder(!, _)" v0;
    assert_not_null "remainder(_, !)" v1;
    check_not_null (Pywrappers.pynumber_remainder v0 v1)

  let rshift v0 v1 =
    assert_not_null "rshift(!, _)" v0;
    assert_not_null "rshift(_, !)" v1;
    check_not_null (Pywrappers.pynumber_rshift v0 v1)

  let subtract v0 v1 =
    assert_not_null "substract(!, _)" v0;
    assert_not_null "substract(_, !)" v1;
    check_not_null (Pywrappers.pynumber_subtract v0 v1)

  let true_divide v0 v1 =
    assert_not_null "true_divide_xor(!, _)" v0;
    assert_not_null "true_divide_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_truedivide v0 v1)

  let number_xor v0 v1 =
    assert_not_null "number_xor(!, _)" v0;
    assert_not_null "number_xor(_, !)" v1;
    check_not_null (Pywrappers.pynumber_xor v0 v1)

  let check v =
    match Type.get v with
      Type.Float
    | Type.Long -> true
    | _ -> false

  let of_int i = Int.of_int i

  let of_int64 i = Int.of_int64 i

  let of_float f = Float.of_float f

  let to_float v =
    match Type.get v with
      Type.Float -> Float.to_float v
    | Type.Long -> Int64.to_float (Long.to_int64 v)
    | _ -> Type.mismatch "Long or Float" v

  let ( + ) = add

  let ( - ) = subtract

  let ( * ) = multiply

  let ( / ) = true_divide

  let ( ** ) x y = power x y

  let ( land ) = number_and

  let ( lor ) = number_or

  let ( lxor ) = number_xor

  let ( lsl ) = lshift

  let ( lsr ) = rshift

  let ( ~- ) = negative
end

module Iter_ = struct
  let check o = Type.get o = Type.Iter

  let next i =
    assert_not_null "next" i;
    option (Pywrappers.pyiter_next i)

  let rec iter f i =
    match next i with
      None -> ()
    | Some item ->
        f item;
        iter f i

  let rec fold_left f v i =
    match next i with
      None -> v
    | Some item -> fold_left f (f v item) i

  let rec fold_right f i v =
    match next i with
      None -> v
    | Some item -> f item (fold_right f i v)

  let to_list i = List.rev (fold_left (fun list item -> item :: list) [] i)

  let to_list_map f i =
    List.rev (fold_left (fun list item -> f item :: list) [] i)

  let rec for_all p i =
    match next i with
      None -> true
    | Some item -> p item && for_all p i

  let rec exists p i =
    match next i with
      None -> false
    | Some item -> p item || exists p i

  let unsafe_to_seq_map f i =
    let rec seq () =
      match next i with
      | None -> Seq.Nil
      | Some item ->
          Seq.Cons (f item, seq) in
    seq
end

(* From stdcompat *)
let vec_to_seq length get v =
  let length = length v in
  let rec aux i () =
    if i = length then Seq.Nil
    else
      let x = get v i in
      Seq.Cons (x, aux (i + 1)) in
  aux 0

let vec_to_seqi length get v =
  let length = length v in
  let rec aux i () =
    if i = length then Seq.Nil
    else
      let x = get v i in
      Seq.Cons ((i, x), aux (i + 1)) in
  aux 0

module Sequence = struct
  let check obj = bool_of_int (Pywrappers.pysequence_check obj)

  let concat s s' = check_not_null (Pywrappers.pysequence_concat s s')

  let contains s value =
    assert_not_null "contains(!, _)" s;
    assert_not_null "contains(_, !)" value;
    bool_of_int (Pywrappers.pysequence_contains s value)

  let count s value = check_int (Pywrappers.pysequence_count s value)

  let del_item s index =
    assert_not_null "del_item" s;
    assert_int_success (Pywrappers.pysequence_delitem s index)

  let fast s msg = check_not_null (Pywrappers.pysequence_fast s msg)

  let get_item sequence index = Pywrappers.pysequence_getitem sequence index

  let get = get_item

  let get_slice s i0 i1 =
    check_not_null (Pywrappers.pysequence_getslice s i0 i1)

  let index s value = check_int (Pywrappers.pysequence_index s value)

  let in_place_concat s s' =
    check_not_null (Pywrappers.pysequence_inplaceconcat s s')

  let in_place_repeat s count =
    check_not_null (Pywrappers.pysequence_inplacerepeat s count)

  let length s = check_int (Pywrappers.pysequence_length s)

  let list sequence =
    check_not_null (Pywrappers.pysequence_list sequence)

  let repeat s count = check_not_null (Pywrappers.pysequence_repeat s count)

  let set_item s index value =
    assert_int_success (Pywrappers.pysequence_setitem s index value)

  let set = set_item

  let set_slice s i0 i1 value =
    assert_int_success (Pywrappers.pysequence_setslice s i0 i1 value)

  let size s =
    assert_not_null "size" s;
    check_int (Pywrappers.pysequence_size s)

  let tuple sequence = check_not_null (Pywrappers.pysequence_tuple sequence)

  let to_array sequence = Array.init (size sequence) (get_item sequence)

  let to_array_map f sequence =
    Array.init (size sequence) (fun index -> f (get_item sequence index))

  let rec fold_right_upto f upto sequence v =
    if upto > 0 then
      let i = pred upto in
      fold_right_upto f i sequence (f (get_item sequence i) v)
    else
      v

  let fold_right f sequence v =
    fold_right_upto f (length sequence) sequence v

  let to_list sequence =
    fold_right (fun item list -> item :: list) sequence []

  let to_list_map f sequence =
    fold_right (fun item list -> f item :: list) sequence []

  let fold_left f v sequence =
    Iter_.fold_left f v (Object.get_iter sequence)

  let for_all p sequence =
    Iter_.for_all p (Object.get_iter sequence)

  let exists p sequence =
    Iter_.exists p (Object.get_iter sequence)

  let to_seq = vec_to_seq size get

  let to_seqi = vec_to_seqi size get
end

module Tuple = struct
  include Sequence

  include Tuple_

  let check o = Type.get o = Type.Tuple

  let empty = pytuple_empty ()

  let is_empty v =
    v == empty

  let get_slice tuple i0 i1 =
    check_not_null (Pywrappers.pytuple_getslice tuple i0 i1)

  let size tuple = check_int (Pywrappers.pytuple_size tuple)

  let of_array_map f array =
    init (Array.length array) (fun i -> f (Array.get array i))

  let of_list_map f list = of_array_map f (Array.of_list list)

  let of_sequence = Sequence.tuple

  let of_seq s = of_array (Array.of_seq s)

  let of_tuple1 v0 =
    init 1 (function _ -> v0)

  let of_tuple2 (v0, v1) =
    init 2 (function 0 -> v0 | _ -> v1)

  let of_tuple3 (v0, v1, v2) =
    init 3 (function 0 -> v0 | 1 -> v1 | _ -> v2)

  let of_tuple4 (v0, v1, v2, v3) =
    init 4 (function 0 -> v0 | 1 -> v1 | 2 -> v2 | _ -> v3)

  let of_tuple5 (v0, v1, v2, v3, v4) =
    init 5 (function 0 -> v0 | 1 -> v1 | 2 -> v2 | 3 -> v3 | _ -> v4)

  let to_tuple1 v = get_item v 0

  let to_tuple2 v = (get_item v 0, get_item v 1)

  let to_tuple3 v = (get_item v 0, get_item v 1, get_item v 2)

  let to_tuple4 v = (get_item v 0, get_item v 1, get_item v 2, get_item v 3)

  let to_tuple5 v =
    (get_item v 0, get_item v 1, get_item v 2, get_item v 3, get_item v 4)

  let singleton = of_tuple1

  let to_singleton = to_tuple1

  let of_pair = of_tuple2

  let to_pair = to_tuple2
end

module Dict = struct
  include Dict_

  let check o = Type.get o = Type.Dict

  let clear o =
    assert_not_null "clear" o;
    Pywrappers.pydict_clear o

  let copy v = check_not_null (Pywrappers.pydict_copy v)

  let del_item dict item =
    assert_not_null "del_item(!, _)" dict;
    assert_not_null "del_item(_, !)" item;
    assert_int_success (Pywrappers.pydict_delitem dict item)

  let del_item_string dict name =
    assert_not_null "del_item_string" dict;
    assert_int_success (Pywrappers.pydict_delitemstring dict name)

  let get_item dict key =
    assert_not_null "get_item(!, _)" dict;
    assert_not_null "get_item(_, !)" key;
    option (Pywrappers.pydict_getitem dict key)

  let find dict key =
    assert_not_null "get_item(!, _)" dict;
    assert_not_null "get_item(_, !)" key;
    check_found (Pywrappers.pydict_getitem dict key)

  let find_opt = get_item

  let get_item_string dict name =
    assert_not_null "get_item_string" dict;
    option (Pywrappers.pydict_getitemstring dict name)

  let find_string dict key =
    assert_not_null "get_item_string" dict;
    check_found (Pywrappers.pydict_getitemstring dict key)

  let find_string_opt = get_item_string

  let keys dict = check_not_null (Pywrappers.pydict_keys dict)

  let items dict = check_not_null (Pywrappers.pydict_items dict)

  let size dict =
    let sz = Pywrappers.pydict_size dict in
    assert_int_success sz;
    sz

  let values dict =
    check_not_null (Pywrappers.pydict_values dict)

  let iter f dict =
    Iter_.iter begin fun pair ->
      let (key, value) = Tuple.to_pair pair in
      f key value
    end (Object.get_iter (items dict))

  let fold f dict v =
    Iter_.fold_left begin fun v pair ->
      let (key, value) = Tuple.to_pair pair in
      f key value v
    end v (Object.get_iter (items dict))

  let for_all p dict =
    Iter_.for_all begin fun pair ->
      let (key, value) = Tuple.to_pair pair in
      p key value
    end (Object.get_iter (items dict))

  let exists p dict =
    Iter_.exists begin fun pair ->
      let (key, value) = Tuple.to_pair pair in
      p key value
    end (Object.get_iter (items dict))

  let to_bindings_seq_map fkey fvalue dict =
    Iter_.unsafe_to_seq_map
      (fun pair ->
        let (key, value) = Tuple.to_pair pair in
        (fkey key, fvalue value))
      (Object.get_iter (items dict))

  let to_bindings_seq = to_bindings_seq_map id id

  let to_bindings_string_seq = to_bindings_seq_map String.to_string id

  let to_bindings_map fkey fvalue dict =
    Iter_.to_list_map begin fun pair ->
      let (key, value) = Tuple.to_pair pair in
      (fkey key, fvalue value)
    end (Object.get_iter (items dict))

  let to_bindings = to_bindings_map id id

  let to_bindings_string = to_bindings_map String.to_string id

  let singleton key value =
    assert_not_null "singleton(!, _)" key;
    assert_not_null "singleton(_, !)" value;
    of_bindings [(key, value)]

  let singleton_string key value =
    assert_not_null "singleton_string" value;
    of_bindings_string [(key, value)]
end

module Set = struct
  let check o = Type.get o = Type.Set

  let clear o =
    assert_not_null "clear" o;
    assert_int_success (Pywrappers.pyset_clear o)

  let copy v = check_not_null (Pywrappers.pyset_new v)

  let create () = check_not_null (Pywrappers.pyset_new null)

  let size set =
    assert_not_null "size" set;
    let sz = Pywrappers.pyset_size set in
    assert_int_success sz;
    sz

  let add set value =
    assert_not_null "add(!, _)" set;
    assert_not_null "add(_, !)" value;
    assert_int_success (Pywrappers.pyset_add set value)

  let contains set value =
    assert_not_null "contains(!, _)" set;
    assert_not_null "contains(_, !)" value;
    bool_of_int (Pywrappers.pyset_contains set value)

  let discard set value =
    assert_not_null "discard(!, _)" set;
    assert_not_null "discard(_, !)" value;
    assert_int_success (Pywrappers.pyset_discard set value)

  let to_list_map f set =
    assert_not_null "to_list_map" set;
    Iter_.to_list_map f (Object.get_iter set)

  let to_list = to_list_map id

  let of_list_map f list =
    let result = create () in
    List.iter begin fun value ->
      add result (f value)
    end list;
    result

  let of_list = of_list_map id
end

module Traceback = struct
  type frame =
    { filename : string
    ; function_name : string
    ; line_number : int
    }

  let create_frame { filename; function_name; line_number } =
    check_not_null (pyframe_new filename function_name line_number)

  type t = frame list

  let create t =
    let types_module = check_not_null (Pywrappers.pyimport_importmodule "types") in
    let tb_type = Object.find_attr_string types_module "TracebackType" in
    List.fold_left
      (fun acc frame ->
        let args =
          Tuple.of_array [| acc; create_frame frame; Int.of_int 0; Int.of_int frame.line_number |]
        in
        Object.call tb_type args null)
      none
      t
end

exception Err_with_traceback of Err.t * string * Traceback.t

module Class = struct
  let init ?(parents = []) ?(fields = []) ?(methods = []) classname =
    if version_major () >= 3 then
      let methods = List.rev_map (fun (name, closure) ->
        (name, Pywrappers.Python3.pyinstancemethod_new closure)) methods in
      Type.create classname parents (List.rev_append methods fields)
    else
      let classname = String.of_string classname in
      let dict = Dict_.of_bindings_string fields in
      let c =
        check_not_null (Pywrappers.Python2.pyclass_new (Tuple_.of_list parents)
          dict classname) in
      let add_method (name, closure) =
        let m = check_not_null (Pywrappers.pymethod_new closure null c) in
        Dict_.set_item_string dict name m in
      List.iter add_method methods;
      c
end

let () =
  ocaml_exception_class :=
    Some (lazy (Class.init ~parents:[Pywrappers.pyexc_baseexception ()]
      "ocaml exception"))

let () =
  ocaml_exception_capsule :=
    Some (Capsule.make "ocaml_exception_capsule")

module Callable = struct
  let check v = Pywrappers.pycallable_check v <> 0

  let handle_errors f arg =
    try f arg with
      E (errtype, errvalue) ->
        Err.set_object errtype errvalue;
        null
    | Err (errtype, msg)
    | Err_with_traceback (errtype, msg, []) ->
        Err.set_error errtype msg;
        null
    | Err_with_traceback (errtype, msg, traceback) ->
        let () =
          (* Traceback objects can only be created since Python 3.7. *)
          if !version_major_value <= 2 || (!version_major_value == 3 && !version_minor_value < 7)
          then
            Err.set_error errtype msg
          else
            let traceback = Traceback.create traceback in
            Err.restore (Err.of_error errtype) (String.of_string msg) traceback;
        in
        null
    | e ->
        let err =
          fst (Option.get !ocaml_exception_capsule)
            (e, Printexc.get_raw_backtrace ()) in
        Err.set_object (Lazy.force (Option.get !ocaml_exception_class)) err;
        null

  let of_function_as_tuple ?name ?(docstring = "Anonymous closure") f =
    check_not_null (pywrap_closure name docstring
      (WithoutKeywords (handle_errors f)))

  let of_function_as_tuple_and_dict ?name ?(docstring = "Anonymous closure") f =
    check_not_null (pywrap_closure name docstring
      (WithKeywords (fun args -> handle_errors (f args))))

  let of_function ?name ?docstring f =
    of_function_as_tuple ?name ?docstring (fun args -> f (Tuple.to_array args))

  let of_function_with_keywords ?name ?docstring f =
    of_function_as_tuple_and_dict ?name ?docstring
      (fun args dict -> f (Tuple.to_array args) dict)

  let to_function_as_tuple c =
    if not (check c) then
      Type.mismatch "Callable" c;
    function args ->
      Object.call c args null

  let to_function_as_tuple_and_dict c =
    if not (check c) then
      Type.mismatch "Callable" c;
    fun args keywords ->
      Object.call c args keywords

  let to_function c =
    let f = to_function_as_tuple c in
    fun args -> f (Tuple.of_array args)

  let to_function_with_keywords c =
    let f = to_function_as_tuple_and_dict c in
    fun args keywords ->
      f (Tuple.of_array args) (Dict.of_bindings_string keywords)
end

type optimize = Default | Debug | Normal | RemoveDocstrings

let int_of_optimize opt =
  match opt with
  | Default -> -1
  | Debug -> 0
  | Normal -> 1
  | RemoveDocstrings -> 2

module Import = struct
(* This function has been removed from Python 3.9, and was marked
  "for internal use only" before.
  let cleanup = Pywrappers.pyimport_cleanup
*)

  let add_module name = check_not_null (Pywrappers.pyimport_addmodule name)

  let main () = add_module "__main__"

  let builtins () = Object.find_attr_string (main ()) "__builtins__"

  let compile ~source ~filename ?(dont_inherit = false)
      ?(optimize = Default) mode =
    let compile =
      Callable.to_function_with_keywords
        (Object.find_attr_string (builtins ()) "compile") in
    let source = String.of_string source in
    let filename = String.of_string filename in
    let mode = String.of_string (string_of_input mode) in
    let dont_inherit = Bool.of_bool dont_inherit in
    let args = ["dont_inherit", dont_inherit] in
    let args =
      if !version_minor_value <= 2 then
        args
      else
        begin
          let optimize = Int.of_int (int_of_optimize optimize) in
          ["optimize", optimize]
        end in
    compile [| source; filename; mode |] args

  let exec_code_module name obj =
    assert_not_null "exec_code_module" obj;
    check_not_null (Pywrappers.pyimport_execcodemodule name obj)

  let exec_code_module_ex name obj pathname =
    assert_not_null "exec_code_module_ex" obj;
    check_not_null (Pywrappers.pyimport_execcodemoduleex name obj pathname)

  let exec_code_module_from_string ~name ?(filename = name)
        ?dont_inherit ?optimize source =
    let obj = compile ~source ~filename ?dont_inherit ?optimize File in
    exec_code_module name obj

  let get_magic_number = Pywrappers.pyimport_getmagicnumber

  let get_module_dict () =
    check_not_null (Pywrappers.pyimport_getmoduledict ())

  let import_frozen_module name =
    bool_of_int (Pywrappers.pyimport_importfrozenmodule name)

  let import_module name =
    check_not_null (Pywrappers.pyimport_importmodule name)

  let import_module_opt name =
    try
      Some (check_not_null (Pywrappers.pyimport_importmodule name))
    with E (e, _msg)
        when
          let ty = Object.to_string e in
          ty = "<class 'ModuleNotFoundError'>" || (* Python >=3.6*)
          ty = "<class 'ImportError'>" || (* Python <3.6 *)
          ty = "<type 'exceptions.ImportError'>" (* Python 2 *) ->
      None

  let try_import_module = import_module_opt

  let import_module_level name globals locals fromlist level =
    check_not_null
      (Pywrappers.pyimport_importmodulelevel name globals locals fromlist level)

  let import_module_ex name globals locals fromlist =
    import_module_level name globals locals fromlist (-1)

  let reload_module obj =
    check_not_null (Pywrappers.pyimport_reloadmodule obj)
end

let import = Import.import_module

let import_opt = Import.import_module_opt

module Module = struct
  let check o = Type.get o = Type.Module

  let create name =
    check_not_null (Pywrappers.pymodule_new name)

  let get_dict m =
    assert_not_null "get_dict" m;
    check_not_null (Pywrappers.pymodule_getdict m)

  let get_filename m =
    assert_not_null "get_filename" m;
    check_some (Pywrappers.pymodule_getfilename m)

  let get_name m =
    assert_not_null "get_name" m;
    check_some (Pywrappers.pymodule_getname m)

  let get = Object.find_attr_string_err

  let get_opt = Object.find_attr_string_opt

  let set = Object.set_attr_string

  let get_function m name = Callable.to_function (get m name)

  let get_function_opt m name = Option.map Callable.to_function (get_opt m name)

  let get_function_with_keywords m name =
    Callable.to_function_with_keywords (get m name)

  let get_function_with_keywords_opt m name =
    Option.map Callable.to_function_with_keywords (get_opt m name)

  let set_function m name f = set m name (Callable.of_function f)

  let set_function_with_keywords m name f =
    set m name (Callable.of_function_with_keywords f)

  let remove = Object.del_attr_string

  let main = Import.main

  let sys () = Import.import_module "sys"

  let builtins () = get (main ()) "__builtins__"

  let compile = Import.compile

  let set_docstring m doc =
    Pywrappers.pymodule_setdocstring m doc
    |> assert_int_success
end

module Iter = struct
  include Iter_

  let create next =
    let next_name =
      if version_major () >= 3 then "__next__"
      else "next" in
    let next' _args =
      match next () with
        None -> raise (Err (Err.StopIteration, ""))
      | Some item -> item in
    let iter_fn = Callable.of_function (function
      | [||] -> failwith "__iter__ expects at least one argument"
      | array -> array.(0)) in
    let methods =
      [next_name, Callable.of_function next'; "__iter__", iter_fn] in
    Object.call_function_obj_args
      (Class.init ~methods "iterator") [| |]

  let of_seq s =
    let s = ref s in
    let next () =
      match !s () with
      | Seq.Nil -> None
      | Seq.Cons (head, tail) ->
          s := tail;
          Some head in
    create next

  let of_seq_map f s =
    let s = ref s in
    let next () =
      match !s () with
      | Seq.Nil -> None
      | Seq.Cons (head, tail) ->
          s := tail;
          Some (f head) in
    create next

  let to_seq i =
    let rec seq lazy_next () =
      match Lazy.force lazy_next with
      | None -> Seq.Nil
      | Some item ->
          Seq.Cons (item, seq (lazy (next i))) in
    seq (lazy (next i))

  let to_seq_map f i =
    let rec seq lazy_next () =
      match Lazy.force lazy_next with
      | None -> Seq.Nil
      | Some item ->
          Seq.Cons (f item, seq (lazy (next i))) in
    seq (lazy (next i))

  let unsafe_to_seq i =
    let rec seq () =
      match next i with
      | None -> Seq.Nil
      | Some item ->
          Seq.Cons (item, seq) in
    seq

  let of_list l =
    let l = ref l in
    let next () =
      match !l with
      | [] -> None
      | head :: tail ->
          l := tail;
          Some head in
    create next

  let of_list_map f l =
    let l = ref l in
    let next () =
      match !l with
      | [] -> None
      | head :: tail ->
          l := tail;
          Some (f head) in
    create next

  let seq_iter seq =
    check_not_null (Pywrappers.pyseqiter_new seq)

  let call_iter call sentinel =
    assert_not_null "call_iter(!, _)" call;
    assert_not_null "call_iter(_, !)" sentinel;
    check_not_null (Pywrappers.pycalliter_new call sentinel)

  (* As a sentinel we use a function so that there is no collision risk.
     Only one such capsule is ever allocated.
  *)
  let sentinel = lazy (Callable.of_function_as_tuple (fun x -> x))

  let create_call next =
    let sentinel = Lazy.force sentinel in
    let call =
      Callable.of_function_as_tuple (fun _pyobject ->
        match next () with
        | None -> sentinel
        | Some value -> value)
    in
    call_iter call sentinel
end

module List = struct
  include Sequence

  let check v = Type.get v = Type.List

  let create size = check_not_null (Pywrappers.pylist_new size)

  let size list =
    assert_not_null "size" list;
    check_int (Pywrappers.pylist_size list)

  let length = size

  let set_item list index value =
    assert_int_success (Pywrappers.pylist_setitem list index value)

  let set = set_item

  let init size f =
    let result = create size in
    for index = 0 to size - 1 do
      set result index (f index)
    done;
    result

  let of_array array = init (Array.length array) (Array.get array)

  let of_array_map f array =
    init (Array.length array) (fun i -> f (Array.get array i))

  let of_list list = of_array (Array.of_list list)

  let of_list_map f list = of_array_map f (Array.of_list list)

  let of_sequence = Sequence.list

  let singleton v =
    assert_not_null "singleton" v;
    init 1 (fun _ -> v)

  let of_seq s = of_array (Array.of_seq s)
end

module Marshal = struct
  let version () =
    let marshal_module = Import.import_module "marshal" in
    Long.to_int (Module.get marshal_module "version")

  let read_object_from_file file =
    let fd = Pytypes.file_map Unix.descr_of_in_channel file in
    check_not_null (Pywrappers.pymarshal_readobjectfromfile fd)

  let load = read_object_from_file

  let read_last_object_from_file file =
    let fd = Pytypes.file_map Unix.descr_of_in_channel file in
    check_not_null (Pywrappers.pymarshal_readlastobjectfromfile fd)

  let read_object_from_string s len =
    check_not_null (Pywrappers.pymarshal_readobjectfromstring s len)

  let loads s = read_object_from_string s (string_length s)

  let write_object_to_file v file version =
    let fd = Pytypes.file_map Unix.descr_of_out_channel file in
    Pywrappers.pymarshal_writeobjecttofile v fd version

  let dump ?(version = version ()) v file =
    write_object_to_file v file version

  let write_object_to_string v version =
    check_not_null (Pywrappers.pymarshal_writeobjecttostring v version)

  let dumps ?(version = version ()) v =
    String.to_string (write_object_to_string v version)
end

module Array = struct
  let of_indexed_structure getter setter length =
    let methods =
      ["__len__",
       Callable.of_function_as_tuple (fun _tuple -> Int.of_int length);
       "__getitem__", Callable.of_function_as_tuple (fun tuple ->
         let (_self, key) = Tuple.to_tuple2 tuple in
         getter (Long.to_int key));
       "__setitem__", Callable.of_function_as_tuple (fun tuple ->
         let (_self, key, value) = Tuple.to_tuple3 tuple in
         setter (Long.to_int key) value;
         none);
       "__iter__", Callable.of_function_as_tuple (fun _tuple ->
         let cursor = ref 0 in
         let next () =
           let index = !cursor in
           if index < length then
             begin
               cursor := succ index;
               Some (getter index)
             end
           else
             None in
         Iter.create next);
       "__repr__", Callable.of_function_as_tuple (fun tuple ->
         let (self) = Tuple.to_tuple1 tuple in
         Object.repr (Sequence.list self))] in
    Object.call_function_obj_args (Class.init ~methods "array") [| |]

  let of_array getter setter a =
    of_indexed_structure (fun i -> getter a.(i)) (fun i v -> a.(i) <- setter v)
      (Array.length a)

  type numpy_info = {
      numpy_api: Object.t;
      array_pickle: floatarray -> Object.t;
      array_unpickle: Object.t -> floatarray;
      pyarray_subtype: Object.t;
    }

  let numpy_info = ref None

  let () = on_finalize (fun () -> numpy_info := None)

  external get_pyarray_type: Object.t -> Object.t = "get_pyarray_type"

  external pyarray_of_floatarray: Object.t -> Object.t
    -> floatarray
    -> Object.t = "pyarray_of_floatarray_wrapper"

  external pyarray_move_floatarray: Object.t -> floatarray
    -> unit = "pyarray_move_floatarray_wrapper"

  let get_numpy_info () =
    match !numpy_info with
      Some info -> info
    | None ->
        let numpy_api =
          let numpy = Import.import_module "numpy.core.multiarray" in
          Object.find_attr_string numpy "_ARRAY_API" in
        let array_pickle, array_unpickle = Capsule.make "floatarray" in
        let pyarray_subtype =
          let pyarray_type = get_pyarray_type numpy_api in
          Type.create "ocamlarray" [pyarray_type] [("ocamlarray", none)] in
        let info =
          { numpy_api; array_pickle; array_unpickle;
            pyarray_subtype } in
        numpy_info := Some info;
        info

  let numpy_api () =
    (get_numpy_info ()).numpy_api

  let pyarray_type () =
    get_pyarray_type (numpy_api ())

  let numpy_get_array a =
    let info = get_numpy_info () in
    info.array_unpickle (Object.find_attr_string a "ocamlarray")

  let clean_weak_ref weak_ref alarm_ref () =
    match Weak.get weak_ref 0 with
    | None ->
        begin
          match !alarm_ref with
          | None -> ()
          | Some alarm ->
              Gc.delete_alarm alarm;
              alarm_ref := None
        end
    | Some numpy_array ->
        let array = numpy_get_array numpy_array in
        pyarray_move_floatarray numpy_array array

  let numpy a =
    let info = get_numpy_info () in
    let result = pyarray_of_floatarray info.numpy_api info.pyarray_subtype a in
    let result = check_not_null result in
    Object.set_attr_string result "ocamlarray" (info.array_pickle a);
    let weak_ref = Weak.create 1 in
    Weak.set weak_ref 0 (Some result);
    let alarm_ref = ref None in
    alarm_ref := Some (Gc.create_alarm (clean_weak_ref weak_ref alarm_ref));
    result
end

module Run = struct
  let any_file file filename =
    assert_int_success
      (Pywrappers.pyrun_anyfileexflags
         (Pytypes.file_map Unix.descr_of_in_channel file) filename 1 None)

  let file file filename start globals locals =
    let fd = Pytypes.file_map Unix.descr_of_in_channel file in
    check_not_null
      (Pywrappers.pyrun_fileexflags fd filename start globals locals 1 None)

  let interactive_one channel name =
    let fd = Channel (Unix.descr_of_in_channel channel) in
    assert_int_success (Pywrappers.pyrun_interactiveoneflags fd name None)

  let interactive_loop channel name =
    let fd = Channel (Unix.descr_of_in_channel channel) in
    assert_int_success (Pywrappers.pyrun_interactiveloopflags fd name None)

  let simple_file channel name =
    let fd = Pytypes.file_map Unix.descr_of_in_channel channel in
    assert_int_success (Pywrappers.pyrun_simplefileexflags fd name 1 None)

  let simple_string string =
    Pywrappers.pyrun_simplestringflags string None = 0

  let string s start globals locals =
    check_not_null
      (Pywrappers.pyrun_stringflags s start globals locals None)

  let eval ?(start = Eval) ?(globals = Module.get_dict (Module.main ()))
      ?(locals = globals) s =
    string s start globals locals

  let load ?(start = File) ?(globals = Module.get_dict (Module.main ()))
      ?(locals = globals) chan filename =
    file chan filename start globals locals

  let interactive () =
    interactive_loop stdin "<stdin>"

  let frame f arg =
    let m = Import.add_module "_pyml" in
    let result = ref None in
    let callback =
      (Callable.of_function (fun _ -> result := Some (f arg); pynone ())) in
    Module.set m "callback" callback;
    ignore (eval ~start:File "
from _pyml import callback
callback()
");
    match !result with
      None -> failwith "frame"
    | Some result -> result

(*
  let ipython () =
    ignore
      (eval ~start:File "
try:
  from IPython import embed
  embed()
except ImportError:
  from IPython.Shell import IPShellEmbed
  ipshell = IPShellEmbed(argv=[''])
  ipshell()
")
 *)

  let make_frame = frame

  let ipython ?(frame=true) () =
    let f () =
      let f =
        try
          Module.get_function (Import.import_module "IPython") "embed"
        with E _ ->
          let shell = Import.import_module "IPython.Shell" in
          let arg = [("argv", List.of_list [String.of_string ""])] in
          let f' =
            Module.get_function_with_keywords shell "IPShellEmbed" [| |] arg in
          Callable.to_function f' in
        ignore (f [| |]) in
    if frame then make_frame f ()
    else f ()
end

module Gil = struct
  type t = int
  let ensure = Pywrappers.pygilstate_ensure
  let release = Pywrappers.pygilstate_release
  let check () = Pywrappers.pygilstate_check () <> 0

  let with_lock f =
    let t = ensure () in
    Fun.protect f ~finally:(fun () -> release t)
end

let set_argv argv =
  Module.set (Module.sys ()) "argv" (List.of_array_map String.of_string argv)

let last_value () = Module.get (Module.builtins ()) "_"

let compile ~source ~filename ?dont_inherit ?optimize mode =
  let mode =
    match mode with
    | `Exec -> File
    | `Eval -> Eval
    | `Single -> Single in
  let optimize =
    Stdcompat.Option.map (function
        | `Default -> Default
        | `Debug -> Debug
        | `Normal -> Normal
        | `RemoveDocstrings -> RemoveDocstrings)
      optimize in
  Module.compile ~source ~filename ?dont_inherit ?optimize mode