jlrs 0.23.0

jlrs provides bindings to the Julia C API that enable Julia code to be called from Rust and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
//! N-dimensional arrays
//!
//! Julia has a generic array type, `Array{T, N}`. These arrays are column-major, N-dimensional
//! arrays that can hold elements of type `T`.
//!
//! jlrs provides a flexible base type that wraps instances of this type, [`ArrayBase`]. This type
//! has two generics: a [type constructor] `T`, and a constant `isize` rank `N`. You shouldn't use
//! this type directly, but use the four available type aliases instead: [`Array`],
//! [`TypedArray`], [`RankedArray`], and [`TypedRankedArray`]. If `Typed` is missing from the
//! name, the element type `T` is set to [`Unknown`], if `Ranked` is missing the the rank `N` is
//! set to `-1`.
//!
//! There are several special aliases: [`Vector`], [`VectorAny`] and [`TypedVector`] (rank 1), and
//! [`Matrix`] and [`TypedMatrix`] (rank 2).
//!
//! ## Converting between array types
//!
//! The methods [`ArrayBase::set_rank`] and [`ArrayBase::set_type`] can be used to set the two
//! generic parameters, [`ArrayBase::forget_rank`] and [`ArrayBase::forget_type`] lets you set
//! them to `-1` and `Unknown` respectively.
//!
//! ## Constructing new arrays
//!
//! Many methods that construct new arrays exist, they can be divided into several groups:
//!
//! - `new`: Constructs a new array whose storage is managed by Julia.
//!
//! - `from_slice`: Constructs a new array whose storage is borrowed from Rust.
//!
//! - `from_vec`: Constructs a new array whose storage is moved from Rust.
//!
//! - `from_slice_cloned`: Constructs a new array whose storage is managed by Julia, the elements
//!   are initialized by cloning a slice.
//!
//! - `from_slice_copied`: Constructs a new array whose storage is managed by Julia, the elements
//!   are initialized by copying a slice.
//!
//! These methods exist as named for typed arrays, the element type is constructed from the
//! provided type parameter. Untyped arrays have `*_for` methods like `new_for` that take the
//! element type as an argument. All these methods have unsafe, unchecked variants like
//! `new_for_unchecked`.
//!
//! One limitation of arrays that are backed by Rust data is that Julia is not able to reallocate
//! this array. Functions that can reallocate, like `push!`, will throw an exception if they are
//! called with such an array.
//!
//! In addition to these generic constructors there are two specialized constructors:
//! [`TypedVector<u8>`] can be constructed with `from_bytes`, which behaves as `from_slice_copied`
//! does. [`VectorAny`] can be constructed with `new_any`, which behaves as `new` does.
//!
//! ## Array data
//!
//! In order to access the content of an array an accessor must be created first. There are
//! several kinds of accessors to account for the different ways the elements can be laid out in
//! memory.
//!
//! Elements are either stored inline in the backing storage or as references. They are stored
//! inline if they are immutable, concrete types. Unions of `isbits` types, i.e. immutable,
//! concrete types which contain no references to other Julia data, are also stored inline. In
//! this last case a type tag is stored for each element after the elements themselves. In all
//!  other cases, the elements are stored as references, i.e. as `Option<WeakValue>`.
//!
//! For several reasons, some more technical than others, it's useful to distinguish between
//! `isbits` and "non-bits" immutable types. Similarly, for elements that are stored as references
//! it can be useful to distinguish between arbitrary `Value`s and more specific managed types.
//! It's also perfectly valid to not make any assumptions about the layout and only work with
//! `Value`s, allocating new Julia data whenever necessary.
//!
//! Putting all of this together, we end up with the following accessors: [`BitsAccessor`],
//! [`InlineAccessor`], [`BitsUnionAccessor`], [`ValueAccessor`], [`ManagedAccessor`], and
//! [`IndeterminateAccessor`]. There are also mutable variants of all of these accessors.
//!
//! Depending on the element type parameter `T` and the traits it implements, it can be possible
//! to infer that a certain accessor must be used. If this is the case, a method to create
//! that accessor without performing any checks will be available. An example is
//! [`ArrayBase::bits_data`], which is only available if `T: IsBits + ConstructType`. If this
//! information can't be inferred from `T`, `try_*` and `*_unchecked` variants are available.
//!
//! ## Tracking
//!
//! It's very easy to accidentally create multiple mutable accessors to the same array. In order
//! to prevent this, you can track an array. You can either track an array exclusively or allow
//! multiple shared references with [`ArrayBase::track_exclusive`] and
//! [`ArrayBase::track_shared`] respectively. This dynamically enforces borrowing rules at
//! runtime, but is limited. While it is thread-safe and even works across multiple packages, the
//! tracking mechanism is unaware of how the data is used inside Julia. It won't protect you from
//! accessing an array that is currently being mutated by some Julia task running in the
//! background. Tracking is also relatively expensive; if you can guarantee you are the only user
//! of an array, e.g. you've just allocated it, you should avoid tracking the array.
//!
//! [type constructor]: crate::data::types::construct_type::ConstructType
//! [`Array::new_for`]: crate::data::managed::array::ArrayBase::new_for
//! [`Array::from_slice_for`]: crate::data::managed::array::ArrayBase::from_slice_for
//! [`Array::from_slice_cloned_for`]: crate::data::managed::array::ArrayBase::from_slice_cloned_for
//! [`Array::from_vec_for`]: crate::data::managed::array::ArrayBase::from_vec_for
//! [`TypedArray::new`]: crate::data::managed::array::ArrayBase::new
//! [`TypedArray:from_slice`]: crate::data::managed::array::ArrayBase::from_slice
//! [`TypedArray:from_slice_cloned`]: crate::data::managed::array::ArrayBase::from_slice_cloned
//! [`TypedArray:from_vec`]: crate::data::managed::array::ArrayBase::from_vec
//! [`RankedArray::new_for`]: crate::data::managed::array::ArrayBase::new_for
//! [`RankedArray::from_slice_for`]: crate::data::managed::array::ArrayBase::from_slice_for
//! [`RankedArray::from_slice_cloned_for`]: crate::data::managed::array::ArrayBase::from_slice_cloned_for
//! [`RankedArray::from_vec_for`]: crate::data::managed::array::ArrayBase::from_vec_for
//! [`TypedArrayRanked::new`]: crate::data::managed::array::ArrayBase::new
//! [`TypedArrayRanked::from_slice`]: crate::data::managed::array::ArrayBase::from_slice
//! [`TypedArrayRanked::from_slice_cloned`]: crate::data::managed::array::ArrayBase::from_slice_cloned
//! [`TypedArrayRanked::from_vec`]: crate::data::managed::array::ArrayBase::from_vec
//! [`TypedVector::from_bytes`]: crate::data::managed::array::ArrayBase::from_bytes
//! [isbits]: crate::data::layout::is_bits
//! [managed type]: crate::data::managed

pub mod data;
pub mod dimensions;
pub mod tracked;

#[julia_version(since = "1.11")]
use std::ptr::null_mut;
use std::{
    ffi::c_void,
    fmt::{Debug, Formatter, Result as FmtResult},
    marker::PhantomData,
    mem::MaybeUninit,
    ptr::NonNull,
};

use jl_sys::{
    jl_alloc_vec_any, jl_apply_array_type, jl_array_eltype, jl_array_rank, jl_array_t,
    jl_array_to_string, jl_gc_add_ptr_finalizer, jl_new_struct_uninit, jl_pchar_to_array,
};
use jlrs_macros::julia_version;
use jlrs_sys::{
    inlined::{jlrs_array_dims_ptr, jlrs_array_ndims_fast},
    jlrs_array_data, jlrs_array_data_owner, jlrs_array_has_pointers, jlrs_array_how,
    jlrs_array_is_pointer_array, jlrs_array_is_union_array, jlrs_array_len,
};

#[julia_version(until = "1.10")]
use self::dimensions::Dims;
use self::{
    data::accessor::{
        BitsAccessor, BitsAccessorMut, BitsUnionAccessor, BitsUnionAccessorMut,
        IndeterminateAccessor, IndeterminateAccessorMut, InlineAccessor, InlineAccessorMut,
        ManagedAccessor, ManagedAccessorMut, ValueAccessor, ValueAccessorMut,
    },
    dimensions::{ArrayDimensions, DimsExt, DimsRankAssert, DimsRankCheck, RankedDims},
    tracked::{TrackedArrayBase, TrackedArrayBaseMut},
};
use super::{
    string::{JuliaString, StringData},
    symbol::static_symbol::{NSym, StaticSymbol, TSym},
    union::Union,
};
use crate::{
    catch::{catch_exceptions, unwrap_exc},
    convert::ccall_types::{CCallArg, CCallReturn},
    data::{
        layout::{
            is_bits::IsBits,
            typed_layout::HasLayout,
            valid_layout::{ValidField, ValidLayout},
        },
        managed::{
            Weak, private::ManagedPriv, type_name::TypeName, type_var::TypeVar, union_all::UnionAll,
        },
        types::{
            abstract_type::AnyType,
            construct_type::{BitsUnionCtor, ConstructType, IfConcreteElse},
            typecheck::Typecheck,
        },
    },
    error::{AccessError, ArrayLayoutError, CANNOT_DISPLAY_TYPE, InstantiationError, TypeError},
    memory::{
        get_tls,
        scope::LocalScopeExt,
        target::{TargetResult, unrooted::Unrooted},
    },
    prelude::{DataType, JlrsResult, LocalScope, Managed, Target, TargetType, Value, ValueData},
    private::Private,
};

// TODO: move to jl-sys
/// How an array has been allocated
#[repr(u8)]
#[derive(PartialEq, Debug)]
pub enum How {
    InlineOrForeign = 0,
    JuliaAllocated = 1,
    MallocAllocated = 2,
    PointerToOwner = 3,
}

/// Wrapper type for an array of rank `N` whose element type is `T`.
#[repr(transparent)]
pub struct ArrayBase<'scope, 'data, T, const N: isize>(
    NonNull<jl_array_t>,
    PhantomData<&'scope ()>,
    PhantomData<&'data mut ()>,
    PhantomData<T>,
);

impl<T, const N: isize> Clone for ArrayBase<'_, '_, T, N> {
    #[inline]
    fn clone(&self) -> Self {
        ArrayBase(self.0, PhantomData, PhantomData, PhantomData)
    }
}

impl<T, const N: isize> Copy for ArrayBase<'_, '_, T, N> {}

/// Constructor methods for typed arrays.
pub trait ConstructTypedArray<T: ConstructType, const N: isize> {
    /// Returns the array type for the element type `T` and the rank of the dimensions `dims`.
    fn array_type<'target, D, Tgt>(target: Tgt, dims: &D) -> ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
        D: DimsExt;

    /// Allocate a new Julia array.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold your program will fail to compile.
    /// If an exception is thrown when the array is allocated, it is caught and returned.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 2>(|mut frame| {
    ///     // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///     let array = TypedArray::<u32>::new(&mut frame, [2, 2]);
    ///     assert!(array.is_ok());
    ///
    ///     // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///     let array = TypedRankedArray::<u32, 2>::new(&mut frame, [2, 2]);
    ///     assert!(array.is_ok());
    ///
    ///     // This fails to compile because the rank of the array doesn't match the rank of
    ///     // the dimensions.
    ///     // let array = TypedRankedArray::<u32, 3>::new(&mut frame, [2, 2]);
    /// });
    /// # }
    /// ```
    fn new<'target, D, Tgt>(target: Tgt, dims: D) -> ArrayBaseResult<'target, 'static, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            assert_eq!(N as usize, dims.rank());
        }

        unsafe {
            let callback = || {
                let array_type = Self::array_type(&target, &dims).as_value();
                dims.alloc_array(&target, array_type)
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            target.result_from_ptr(v, Private)
        }
    }

    /// Allocate a new Julia array without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught.
    unsafe fn new_unchecked<'target, D, Tgt>(
        target: Tgt,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let array_type = Self::array_type(&target, &dims).as_value();
            let array = dims.alloc_array(&target, array_type);
            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array that borrows its data from Rust.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `&mut [T]` but `&mut [U]`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLayout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// NB: Because Julia didn't allocate the backing storage, there are some array functions in
    /// Julia that will throw an exception if you call them, e.g. `push!`. The reason is that the
    /// backing storage might need to be reallocated which is not possible.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 3>(|mut frame| {
    ///     let mut data = vec![1u32, 2u32, 3u32, 4u32];
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_mut_slice();
    ///         let array = TypedArray::<u32>::from_slice(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_mut_slice();
    ///         let array = TypedRankedArray::<u32, 2>::from_slice(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_mut_slice();
    ///         // let array = TypedRankedArray::<u32, 3>::from_slice(&mut frame, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_mut_slice();
    ///         let array = TypedArray::<u32>::from_slice(&mut frame, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    fn from_slice<'target, 'data, U, D, Tgt>(
        target: Tgt,
        data: &'data mut [U],
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'data, Tgt, T, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        if dims.size() != data.len() {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: data.len(),
                dim_size: dims.size(),
            })?;
        }

        unsafe {
            let callback = || {
                let array_type = Self::array_type(&target, &dims).as_value();
                dims.alloc_array_with_data(&target, array_type, data.as_ptr() as _)
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            Ok(target.result_from_ptr(v, Private))
        }
    }

    /// Allocate a new Julia array that borrows its data from Rust without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    unsafe fn from_slice_unchecked<'target, 'data, U, D, Tgt>(
        target: Tgt,
        data: &'data mut [U],
        dims: D,
    ) -> ArrayBaseData<'target, 'data, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let array_type = Self::array_type(&target, &dims).as_value();
            let array = dims.alloc_array_with_data(&target, array_type, data.as_ptr() as _);
            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array that takes owenership of a Rust `Vec`.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `Vec<T>` but `Vec<U>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLayout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// NB: Because Julia didn't allocate the backing storage, there are some array functions in
    /// Julia that will throw an exception if you call them, e.g. `push!`. The reason is that the
    /// backing storage might need to be reallocated which is not possible.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 3>(|mut frame| {
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = TypedArray::<u32>::from_vec(&mut frame, data, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = TypedRankedArray::<u32, 2>::from_vec(&mut frame, data, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         // let array = TypedRankedArray::<u32, 3>::from_vec(&mut frame, data, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = TypedArray::<u32>::from_vec(&mut frame, data, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    fn from_vec<'target, U, D, Tgt>(
        target: Tgt,
        data: Vec<U>,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, T, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        if dims.size() != data.len() {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: data.len(),
                dim_size: dims.size(),
            })?;
        }

        let data = Box::leak(data.into_boxed_slice());

        unsafe {
            let callback = || {
                let array_type = Self::array_type(&target, &dims).as_value();
                let array = dims.alloc_array_with_data(&target, array_type, data.as_mut_ptr() as _);

                #[cfg(not(julia_1_10))]
                let mem = jlrs_sys::inlined::jlrs_array_mem(array.ptr().as_ptr());
                #[cfg(julia_1_10)]
                let mem = array.ptr().as_ptr().cast();

                jl_gc_add_ptr_finalizer(get_tls(), mem, droparray::<U> as *mut c_void);

                array
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            Ok(target.result_from_ptr(v, Private))
        }
    }

    /// Allocate a new Julia array that takes owenership of a Rust `Vec` without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    unsafe fn from_vec_unchecked<'target, U, D, Tgt>(
        target: Tgt,
        data: Vec<U>,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let data = Box::leak(data.into_boxed_slice());

            let array_type = Self::array_type(&target, &dims).as_value();
            let array = dims.alloc_array_with_data(&target, array_type, data.as_mut_ptr() as _);
            #[cfg(not(julia_1_10))]
            let mem = jlrs_sys::inlined::jlrs_array_mem(array.ptr().as_ptr());
            #[cfg(julia_1_10)]
            let mem = array.ptr().as_ptr().cast();

            jl_gc_add_ptr_finalizer(get_tls(), mem, droparray::<U> as *mut c_void);

            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array that clones its data from Rust.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 3>(|mut frame| {
    ///     let data = vec![1u32, 2u32, 3u32, 4u32];
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_slice();
    ///         let array = TypedArray::<u32>::from_slice_cloned(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_slice();
    ///         let array = TypedRankedArray::<u32, 2>::from_slice_cloned(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_slice();
    ///         // let array = TypedRankedArray::<u32, 3>::from_slice_cloned(&mut frame, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_slice();
    ///         let array = TypedArray::<u32>::from_slice_cloned(&mut frame, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    fn from_slice_cloned<'target, V, U, D, Tgt>(
        target: Tgt,
        data: V,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, T, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits + Clone,
        V: AsRef<[U]>,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        let data = data.as_ref();
        let len = data.len();
        let dim_size = dims.size();
        if len != dim_size {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: len,
                dim_size: dim_size,
            })?;
        }

        unsafe {
            let arr = match Self::new(&target, dims) {
                Ok(arr) => arr,
                Err(e) => return Ok(Err(e.as_value().root(target))),
            };

            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.clone_from_slice(data);

            Ok(Ok(arr.root(target)))
        }
    }

    /// Allocate a new Julia array that clones its data from Rust without checking any invariants.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    unsafe fn from_slice_cloned_unchecked<'target, V, U, D, Tgt>(
        target: Tgt,
        data: V,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits + Clone,
        V: AsRef<[U]>,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let data = data.as_ref();
            let len = data.len();

            let arr = Self::new_unchecked(&target, dims);
            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.clone_from_slice(data);

            arr.root(target)
        }
    }

    /// Allocate a new Julia array that copies its data from Rust.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 3>(|mut frame| {
    ///     let data = vec![1u32, 2u32, 3u32, 4u32];
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_slice();
    ///         let array = TypedArray::<u32>::from_slice_copied(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_slice();
    ///         let array = TypedRankedArray::<u32, 2>::from_slice_copied(&mut frame, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_slice();
    ///         // let array = TypedRankedArray::<u32, 3>::from_slice_copied(&mut frame, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_slice();
    ///         let array = TypedArray::<u32>::from_slice_copied(&mut frame, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    fn from_slice_copied<'target, V, U, D, Tgt>(
        target: Tgt,
        data: V,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, T, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits + Copy,
        V: AsRef<[U]>,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        let data = data.as_ref();
        let len = data.len();
        let dim_size = dims.size();
        if len != dim_size {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: len,
                dim_size: dim_size,
            })?;
        }

        unsafe {
            let arr = match Self::new(&target, dims) {
                Ok(arr) => arr,
                Err(e) => return Ok(Err(e.as_value().root(target))),
            };

            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.copy_from_slice(data);

            Ok(Ok(arr.root(target)))
        }
    }

    /// Allocate a new Julia array that clones its data from Rust without checking any invariants.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    unsafe fn from_slice_copied_unchecked<'target, V, U, D, Tgt>(
        target: Tgt,
        data: V,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, T, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        T: HasLayout<'static, 'static, Layout = U>,
        U: ValidLayout + ValidField + IsBits + Copy,
        V: AsRef<[U]>,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let data = data.as_ref();
            let len = data.len();

            let arr = Self::new_unchecked(&target, dims);
            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.copy_from_slice(data);

            arr.root(target)
        }
    }
}

impl<T: ConstructType, const N: isize> ConstructTypedArray<T, N> for ArrayBase<'_, '_, T, N> {
    fn array_type<'target, D, Tgt>(target: Tgt, dims: &D) -> ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
        D: DimsExt,
    {
        dims.array_type::<T, _>(target)
    }
}

impl<const N: isize> ArrayBase<'_, '_, Unknown, N> {
    /// Allocate a new Julia array for elements of some provided type.
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 2>(|mut frame| {
    ///     let ty = DataType::uint32_type(&frame).as_value();
    ///
    ///     // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///     let array = Array::new_for(&mut frame, ty, [2, 2]);
    ///     assert!(array.is_ok());
    ///
    ///     // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///     let array = RankedArray::<2>::new_for(&mut frame, ty, [2, 2]);
    ///     assert!(array.is_ok());
    ///
    ///     // This fails to compile because the rank of the array doesn't match the rank of
    ///     // the dimensions.
    ///     // let array = RankedArray::<3>::new_for(&mut frame, ty, [2, 2]);
    /// });
    /// # }
    /// ```
    pub fn new_for<'target, D, Tgt>(
        target: Tgt,
        ty: Value,
        dims: D,
    ) -> ArrayBaseResult<'target, 'static, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
    {
        const {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        }

        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            assert_eq!(N as usize, dims.rank());
        }

        unsafe {
            let callback = || {
                // array_type should be a concrete type.
                let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
                let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
                let array = dims.alloc_array(&target, array_type);
                array
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            target.result_from_ptr(v, Private)
        }
    }

    /// Allocate a new Julia array for elements of some provided type without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught.
    pub unsafe fn new_for_unchecked<'target, D, Tgt>(
        target: Tgt,
        ty: Value,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            // array_type should be a concrete type.
            let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
            let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
            let array = dims.alloc_array(&target, array_type);

            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array that borrows its data from Rust with some provided element
    /// type.
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// The layout of `U` must be a valid layout for `ty`, if this is not true
    /// `AccessError::InvalidLayout` is returned.
    ///
    /// NB: Because Julia didn't allocate the backing storage, there are some array functions in
    /// Julia that will throw an exception if you call them, e.g. `push!`. The reason is that the
    /// backing storage might need to be reallocated which is not possible.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 3>(|mut frame| {
    ///     let mut data = vec![1u32, 2u32, 3u32, 4u32];
    ///     let ty = DataType::uint32_type(&frame).as_value();
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_mut_slice();
    ///         let array = Array::from_slice_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_mut_slice();
    ///         let array = RankedArray::<2>::from_slice_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_mut_slice();
    ///         // let array = RankedArray::<3>::from_slice_for(&mut frame, ty, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_mut_slice();
    ///         let array = Array::from_slice_for(&mut frame, ty, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    ///
    ///     {
    ///         // This fails because the layout of the data is incompatible with `ty`.
    ///         let ty = DataType::uint64_type(&frame).as_value();
    ///         let slice = data.as_mut_slice();
    ///         let array = Array::from_slice_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    pub fn from_slice_for<'target, 'data, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: &'data mut [U],
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'data, Tgt, Unknown, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        if dims.size() != data.len() {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: data.len(),
                dim_size: dims.size(),
            })?;
        }

        if !U::valid_layout(ty) {
            let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
            Err(AccessError::InvalidLayout { value_type })?;
        }

        unsafe {
            let callback = || {
                // array_type should be a concrete type.
                let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
                let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
                let array = dims.alloc_array_with_data(&target, array_type, data.as_ptr() as _);
                array
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            Ok(target.result_from_ptr(v, Private))
        }
    }

    /// Allocate a new Julia array that borrows its data from Rust with some provided element
    /// type without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`.If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`. The layout of
    /// `U` must be a valid layout for `ty`.
    pub unsafe fn from_slice_for_unchecked<'target, 'data, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: &'data mut [U],
        dims: D,
    ) -> ArrayBaseData<'target, 'data, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;

            // array_type should be a concrete type.
            let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
            let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
            let array = dims.alloc_array_with_data(&target, array_type, data.as_ptr() as _);
            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array that takes ownership of a Rust `Vec` with some provided element
    /// type.
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// The layout of `U` must be a valid layout for `ty`, if this is not true
    /// `AccessError::InvalidLayout` is returned.
    ///
    /// NB: Because Julia didn't allocate the backing storage, there are some array functions in
    /// Julia that will throw an exception if you call them, e.g. `push!`. The reason is that the
    /// backing storage might need to be reallocated which is not possible.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 4>(|mut frame| {
    ///     let ty = DataType::uint32_type(&frame).as_value();
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = Array::from_vec_for(&mut frame, ty, data, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = RankedArray::<2>::from_vec_for(&mut frame, ty, data, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         // let array = RankedArray::<3>::from_vec_for(&mut frame, ty, data, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let mut data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let array = Array::from_vec_for(&mut frame, ty, data, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    ///
    ///     {
    ///         // This fails because the layout of the data is incompatible with `ty`.
    ///         let data = vec![1u32, 2u32, 3u32, 4u32];
    ///         let ty = DataType::uint64_type(&frame).as_value();
    ///         let array = Array::from_vec_for(&mut frame, ty, data, [2, 2]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    pub fn from_vec_for<'target, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: Vec<U>,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, Unknown, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        if dims.size() != data.len() {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: data.len(),
                dim_size: dims.size(),
            })?;
        }

        if !U::valid_layout(ty) {
            let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
            Err(AccessError::InvalidLayout { value_type })?;
        }

        let data = Box::leak(data.into_boxed_slice());

        unsafe {
            let callback = || {
                // array_type should be a concrete type.
                let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
                let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
                let array = dims.alloc_array_with_data(&target, array_type, data.as_mut_ptr() as _);
                #[cfg(not(julia_1_10))]
                let mem = jlrs_sys::inlined::jlrs_array_mem(array.ptr().as_ptr());
                #[cfg(julia_1_10)]
                let mem = array.ptr().as_ptr().cast();

                jl_gc_add_ptr_finalizer(get_tls(), mem, droparray::<U> as *mut c_void);

                array
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(arr.ptr()),
                Err(e) => Err(e),
            };

            Ok(target.result_from_ptr(v, Private))
        }
    }

    /// Allocate a new Julia array that takes ownership of a Rust `Vec` with some provided element
    /// type without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`. The layout of
    /// `U` must be a valid layout for `ty`.
    pub unsafe fn from_vec_for_unchecked<'target, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: Vec<U>,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
            let data = Box::leak(data.into_boxed_slice());

            // array_type should be a concrete type.
            let array_type = jl_apply_array_type(ty.unwrap(Private), dims.rank());
            let array_type = Value::wrap_non_null(NonNull::new_unchecked(array_type), Private);
            let array = dims.alloc_array_with_data(&target, array_type, data.as_mut_ptr() as _);
            #[cfg(not(julia_1_10))]
            let mem = jlrs_sys::inlined::jlrs_array_mem(array.ptr().as_ptr());
            #[cfg(julia_1_10)]
            let mem = array.ptr().as_ptr().cast();

            jl_gc_add_ptr_finalizer(get_tls(), mem, droparray::<U> as *mut c_void);

            target.data_from_ptr(array.ptr(), Private)
        }
    }

    /// Allocate a new Julia array with some provided element type that clones its data from Rust.
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 4>(|mut frame| {
    ///     let data = vec![1u32, 2u32, 3u32, 4u32];
    ///     let ty = DataType::uint32_type(&frame).as_value();
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_slice();
    ///         let array = Array::from_slice_cloned_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_slice();
    ///         let array = RankedArray::<2>::from_slice_cloned_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_slice();
    ///         // let array = RankedArray::<3>::from_slice_cloned_for(&mut frame, ty, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_slice();
    ///         let array = Array::from_slice_cloned_for(&mut frame, ty, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    ///
    ///     {
    ///         // This fails because the layout of the data is incompatible with `ty`.
    ///         let slice = data.as_slice();
    ///         let ty = DataType::uint64_type(&frame).as_value();
    ///         let array = Array::from_slice_cloned_for(&mut frame, ty, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    pub fn from_slice_cloned_for<'target, V, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: V,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, Unknown, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits + Clone,
        V: AsRef<[U]>,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        let data = data.as_ref();
        let len = data.len();
        let dim_size = dims.size();
        if len != dim_size {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: len,
                dim_size: dim_size,
            })?;
        }

        if !U::valid_layout(ty) {
            let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
            Err(AccessError::InvalidLayout { value_type })?;
        }

        unsafe {
            match Self::new_for(&target, ty, dims) {
                Ok(arr) => {
                    let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
                    let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
                    array_data_slice.clone_from_slice(data);

                    Ok(Ok(arr.root(target)))
                }
                Err(err) => Ok(Err(err.as_value().root(target))),
            }
        }
    }

    /// Allocate a new Julia array that clones its data from Rust without checking any invariants.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    pub unsafe fn from_slice_cloned_for_unchecked<'target, V, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: V,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits + Clone,
        V: AsRef<[U]>,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;

            let data = data.as_ref();
            let len = data.len();

            let arr = Self::new_for_unchecked(&target, ty, dims);
            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.clone_from_slice(data);

            arr.root(target)
        }
    }

    /// Allocate a new Julia array with some provided element type that copies its data from Rust.
    ///
    /// The element type is `ty`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If this equality doesn't hold `ArrayLayoutError::RankMismatch`
    /// is returned. If an exception is thrown when the array is allocated, it is caught and
    /// returned. The size of the dimensions must be equal to the length of `data`, otherwise
    /// `InstantiationError::ArraySizeMismatch` is returned.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 4>(|mut frame| {
    ///     let data = vec![1u32, 2u32, 3u32, 4u32];
    ///     let ty = DataType::uint32_type(&frame).as_value();
    ///
    ///     {
    ///         // Allocate a 2x2 array of `u32`s with an implicit rank.
    ///         let slice = data.as_slice();
    ///         let array = Array::from_slice_copied_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // Allocate a 4x2 array of `u32`s with an explicit rank.
    ///         let slice = data.as_slice();
    ///         let array = RankedArray::<2>::from_slice_copied_for(&mut frame, ty, slice, [2, 2]);
    ///         assert!(array.is_ok());
    ///         assert!(array.unwrap().is_ok());
    ///     }
    ///
    ///     {
    ///         // This fails to compile because the rank of the array doesn't match the rank
    ///         // of the dimensions.
    ///         // let slice = data.as_slice();
    ///         // let array = RankedArray::<3>::from_slice_copied_for(&mut frame, ty, slice, [2, 2]);
    ///     }
    ///
    ///     {
    ///         // This fails because the size of the dimensions doesn't match the length of
    ///         // the data.
    ///         let slice = data.as_slice();
    ///         let array = Array::from_slice_copied_for(&mut frame, ty, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    ///
    ///     {
    ///         // This fails because the layout of the data is incompatible with `ty`.
    ///         let slice = data.as_slice();
    ///         let ty = DataType::uint64_type(&frame).as_value();
    ///         let array = Array::from_slice_copied_for(&mut frame, ty, slice, [2, 1]);
    ///         assert!(array.is_err());
    ///     }
    /// });
    /// # }
    /// ```
    pub fn from_slice_copied_for<'target, V, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: V,
        dims: D,
    ) -> JlrsResult<ArrayBaseResult<'target, 'static, Tgt, Unknown, N>>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits + Copy,
        V: AsRef<[U]>,
    {
        let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;
        if DimsRankAssert::<D, N>::NEEDS_RUNTIME_RANK_CHECK {
            let expected = N as usize;
            let found = dims.rank();
            if expected != found {
                Err(InstantiationError::ArrayRankMismatch { expected, found })?;
            }
        }

        let data = data.as_ref();
        let len = data.len();
        let dim_size = dims.size();
        if len != dim_size {
            Err(InstantiationError::ArraySizeMismatch {
                vec_size: len,
                dim_size: dim_size,
            })?;
        }

        if !U::valid_layout(ty) {
            let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
            Err(AccessError::InvalidLayout { value_type })?;
        }

        unsafe {
            match Self::new_for(&target, ty, dims) {
                Ok(arr) => {
                    let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
                    let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
                    array_data_slice.copy_from_slice(data);

                    Ok(Ok(arr.root(target)))
                }
                Err(err) => Ok(Err(err.as_value().root(target))),
            }
        }
    }

    /// Allocate a new Julia array that clones its data from Rust without checking any invariants.
    ///
    /// The element type is `T`, the rank follows from the rank of `D`. If `N >= 0`, the rank of
    /// `D` must be equal to `N`. If an exception is thrown when the array is allocated, it is not
    /// caught. The size of the dimensions must be equal to the length of `data`.
    ///
    /// Note that the type of `data` is not `AsRef<[T]>` but `AsRef<[U]>`. The reason is that the
    /// type constructor can have more type parameters than its layout. `U` must implement
    /// `IsBits` and `ValidLayout`, and `T` must implement `HasLamut_yout<Layout = U>` to guarantee
    /// that `U` is a valid representation of instances of `T`.
    pub unsafe fn from_slice_copied_for_unchecked<'target, V, U, D, Tgt>(
        target: Tgt,
        ty: Value,
        data: V,
        dims: D,
    ) -> ArrayBaseData<'target, 'static, Tgt, Unknown, N>
    where
        Tgt: Target<'target>,
        D: DimsExt,
        U: ValidLayout + ValidField + IsBits + Copy,
        V: AsRef<[U]>,
    {
        unsafe {
            let _ = DimsRankAssert::<D, N>::ASSERT_VALID_RANK;

            let data = data.as_ref();
            let len = data.len();

            let arr = Self::new_for_unchecked(&target, ty, dims);
            let array_data = jlrs_array_data(arr.as_managed().unwrap(Private));
            let array_data_slice = std::slice::from_raw_parts_mut(array_data as _, len);
            array_data_slice.copy_from_slice(data);

            arr.root(target)
        }
    }
}

impl TypedVector<'_, '_, u8> {
    /// Convert a slice of bytes to a `TypedVector<u8>`.
    ///
    /// The bytes are copied from Rust to Julia. If an exception is thrown, it is caught and
    /// returned.
    pub fn from_bytes<'target, B, Tgt>(
        target: Tgt,
        bytes: B,
    ) -> ArrayBaseResult<'target, 'static, Tgt, u8, 1>
    where
        Tgt: Target<'target>,
        B: AsRef<[u8]>,
    {
        unsafe {
            let callback = || {
                let bytes = bytes.as_ref();
                jl_pchar_to_array(bytes.as_ptr() as *const _ as _, bytes.len())
            };

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(NonNull::new_unchecked(arr)),
                Err(e) => Err(e),
            };

            target.result_from_ptr(v, Private)
        }
    }

    /// Convert a slice of bytes to a `TypedVector<u8>` without catching exceptions.
    ///
    /// The bytes are copied from Rust to Julia.
    ///
    /// Safety:
    ///
    /// If an exception is thrown, it is not caught.
    pub unsafe fn from_bytes_unchecked<'target, B, Tgt>(
        target: Tgt,
        bytes: B,
    ) -> ArrayBaseData<'target, 'static, Tgt, u8, 1>
    where
        Tgt: Target<'target>,
        B: AsRef<[u8]>,
    {
        unsafe {
            let bytes = bytes.as_ref();
            let array = jl_pchar_to_array(bytes.as_ptr() as *const _ as _, bytes.len());
            target.data_from_ptr(NonNull::new_unchecked(array), Private)
        }
    }

    /// Convert this array to a [`JuliaString`].
    pub fn to_jl_string<'target, Tgt>(self, target: Tgt) -> StringData<'target, Tgt>
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let s = jl_array_to_string(self.unwrap(Private));
            let s = JuliaString::wrap_non_null(NonNull::new_unchecked(s.cast()), Private);
            s.root(target)
        }
    }
}

impl<'scope, 'data> VectorAny<'_, '_> {
    /// Allocate a new Julia array, the element type is the `Any` type and rank is 1.
    ///
    /// Examples
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = Builder::new().start_local().unwrap();
    /// julia.local_scope::<_, 2>(|mut frame| {
    ///     let array = VectorAny::new_any(&mut frame, 2);
    ///     assert!(array.is_ok());
    ///
    ///     let array = VectorAny::new_any(&mut frame, usize::MAX);
    ///     assert!(array.is_err());
    /// });
    /// # }
    /// ```
    pub fn new_any<'target, Tgt>(target: Tgt, size: usize) -> VectorAnyResult<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let callback = || jl_alloc_vec_any(size);

            let v = match catch_exceptions(callback, unwrap_exc) {
                Ok(arr) => Ok(NonNull::new_unchecked(arr)),
                Err(e) => Err(e),
            };
            target.result_from_ptr(v, Private)
        }
    }

    /// Allocate a new Julia array, the element type is the `Any` type and rank is 1 without
    /// checking any invariants.
    ///
    /// Safety: if an exception is thrown, it's not caught.
    pub unsafe fn new_any_unchecked<'target, Tgt>(
        target: Tgt,
        size: usize,
    ) -> VectorAnyData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        unsafe {
            let arr = jl_alloc_vec_any(size);
            target.data_from_ptr(NonNull::new_unchecked(arr), Private)
        }
    }
}

impl<T, const N: isize> ArrayBase<'_, '_, T, N> {
    /// Returns the rank of this array.
    pub fn rank(self) -> i32 {
        unsafe { jl_array_rank(self.unwrap(Private).cast()) }
    }

    // Returns `true` if `N != -1`.
    pub const fn has_rank(self) -> bool {
        N != -1
    }

    // Returns `true` if `N != -1`.
    pub const fn has_rank_s() -> bool {
        N != -1
    }
}

impl<const N: isize> ArrayBase<'_, '_, Unknown, N> {
    // Returns `false` because the the element type is `Unknown`.
    pub const fn has_constrained_type(self) -> bool {
        false
    }

    // Returns `false` because the the element type is `Unknown`.
    pub const fn has_constrained_type_s() -> bool {
        false
    }
}

impl<T: ConstructType, const N: isize> ArrayBase<'_, '_, T, N> {
    // Returns `true` because the the element type implements `ConstructType`.
    pub const fn has_constrained_type(self) -> bool {
        true
    }

    // Returns `true` because the the element type implements `ConstructType`.
    pub const fn has_constrained_type_s() -> bool {
        true
    }
}

// Fields and flags
impl<'scope, 'data, T, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Returns the element size in bytes.
    pub fn element_size(self) -> usize {
        unsafe {
            let t = self.as_value().datatype().parameter_unchecked(0);

            if t.is::<DataType>() {
                t.cast_unchecked::<DataType>()
                    .size()
                    .map(|sz| sz as usize)
                    .unwrap_or(std::mem::size_of::<Value>())
            } else if t.is::<Union>() {
                let u = t.cast_unchecked::<Union>();

                let mut sz = 0;
                let mut align = 0;
                if u.isbits_size_align(&mut sz, &mut align) {
                    return sz;
                }

                std::mem::size_of::<Value>()
            } else {
                std::mem::size_of::<Value>()
            }
        }
    }

    /// Returns the element type.
    pub fn element_type(self) -> Value<'scope, 'static> {
        unsafe {
            Value::wrap_non_null(
                NonNull::new_unchecked(jl_array_eltype(self.unwrap(Private).cast()).cast()),
                Private,
            )
        }
    }

    /// Returns `true` if `L` is a valid layout for the element type.
    pub fn contains<L: ValidField>(self) -> bool {
        L::valid_field(self.element_type())
    }

    /// Returns the length of this array.
    pub fn length(self) -> usize {
        unsafe { jlrs_array_len(self.unwrap(Private)) }
    }

    /// Returns how the array has been allocated.
    pub fn how(self) -> How {
        let how = unsafe { jlrs_array_how(self.unwrap(Private)) };
        match how {
            0 => How::InlineOrForeign,
            1 => How::JuliaAllocated,
            2 => How::MallocAllocated,
            3 => How::PointerToOwner,
            _ => unreachable!(),
        }
    }

    /// Returns the number of dimensions (i.e. the rank) of this array.
    #[inline]
    pub fn n_dims(self) -> usize {
        if N != -1 {
            N as usize
        } else {
            unsafe { jlrs_array_ndims_fast(self.unwrap(Private)) }
        }
    }

    /// Returns the const parameter, `N`.
    #[inline]
    pub const fn generic_rank(self) -> isize {
        N
    }

    /// Returns `true` if the elements are stored as pointers, i.e. `Option<WeakValue>`.
    #[inline]
    pub fn ptr_array(self) -> bool {
        unsafe { jlrs_array_is_pointer_array(self.unwrap(Private)) != 0 }
    }

    /// Returns `true` if the elements are stored inline and contain references to managed data.
    #[inline]
    pub fn has_ptr(self) -> bool {
        unsafe { jlrs_array_has_pointers(self.unwrap(Private)) != 0 }
    }

    #[inline]
    pub fn union_array(self) -> bool {
        unsafe { jlrs_array_is_union_array(self.unwrap(Private)) != 0 }
    }

    /// Returns the dimensions of this array.
    #[inline]
    pub fn dimensions<'borrow>(&'borrow self) -> ArrayDimensions<'borrow, N> {
        unsafe {
            let ptr = jlrs_array_dims_ptr(self.unwrap(Private));
            let n = self.n_dims() as usize;
            let dims = std::slice::from_raw_parts_mut(ptr.cast(), n);

            ArrayDimensions::new(dims)
        }
    }

    /// Returns a pointer to this array's data.
    #[inline]
    pub unsafe fn data_ptr(self) -> *mut c_void {
        unsafe { jlrs_array_data(self.unwrap(Private)) }
    }

    /// Returns the owner of the array data.
    pub fn owner(self) -> Option<Value<'scope, 'data>> {
        if self.how() == How::PointerToOwner {
            unsafe {
                return Some(Value::wrap_non_null(
                    NonNull::new_unchecked(jlrs_array_data_owner(self.unwrap(Private))),
                    Private,
                ));
            }
        }
        None
    }

    /// Returns true if the elements are zero-initialized.
    pub fn zero_init(&self) -> bool {
        let ty = self.element_type();
        if ty.is::<DataType>() {
            unsafe {
                let ty = ty.cast_unchecked::<DataType>();
                ty.zero_init()
            }
        } else {
            true
        }
    }
}

// Tracking
impl<'scope, 'data, T, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Track this array, allowing shared access.
    pub fn track_shared(self) -> JlrsResult<TrackedArrayBase<'scope, 'data, T, N>> {
        TrackedArrayBase::track_shared(self)
    }

    /// Track this array, enforcing exclusive access.
    pub fn track_exclusive(self) -> JlrsResult<TrackedArrayBaseMut<'scope, 'data, T, N>> {
        TrackedArrayBaseMut::track_exclusive(self)
    }
}

// Layout checks
impl<'scope, 'data, T, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Returns `true` if the elements are stored inline and the element type is an isbits type.
    pub fn has_bits_layout(self) -> bool {
        self.has_inline_layout() && !self.has_ptr()
    }

    /// Returns `true` if the elements are stored inline.
    pub fn has_inline_layout(self) -> bool {
        !self.ptr_array() && !self.union_array()
    }

    /// Returns `true` if the elements are stored inline and the elements contain references to
    /// other Julia data.
    pub fn has_inline_with_refs_layout(self) -> bool {
        !self.ptr_array() && !self.has_union_layout() && self.has_ptr()
    }

    /// Returns `true` if the elements are stored inline and the element type is a union.
    pub fn has_union_layout(self) -> bool {
        self.union_array()
    }

    /// Returns `true` if the elements are stored as references to Julia data.
    pub fn has_value_layout(self) -> bool {
        self.ptr_array()
    }

    /// Returns `true` if the elements are stored as references to managed data.
    pub fn has_managed_layout<M: Managed<'scope, 'data> + Typecheck>(self) -> bool {
        if self.ptr_array() {
            let elty = self.element_type();
            if elty.is::<DataType>() {
                unsafe { elty.cast_unchecked::<DataType>().is::<M>() }
            } else {
                elty.is::<M>()
            }
        } else {
            false
        }
    }
}

// Accessors
impl<'scope, 'data, T, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Create an accessor for `isbits` data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn bits_data<'borrow>(&'borrow self) -> BitsAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField + IsBits,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout
            BitsAccessor::new(self)
        }
    }

    /// Create an accessor for `isbits` data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn bits_data_with_layout<'borrow, L>(
        &'borrow self,
    ) -> BitsAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'static, 'static, Layout = L>,
        L: IsBits + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout and L is the layout of T
            BitsAccessor::new(self)
        }
    }

    /// Try to create an accessor for `isbits` data with layout `L`.
    ///
    /// If the array doesn't have an isbits layout `ArrayLayoutError::NotBits` is returned. If `L`
    /// is not a valid field layout for the element type `TypeError::InvalidLayout` is returned.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn try_bits_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<BitsAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: IsBits + ValidField,
    {
        unsafe {
            if !self.has_bits_layout() {
                Err(ArrayLayoutError::NotBits {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsAccessor::new(self))
        }
    }

    /// Create an accessor for `isbits` data with layout `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist. The element type must be an isbits type, and
    /// `L` must be a valid field layout of the element type.
    #[inline]
    pub unsafe fn bits_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> BitsAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: IsBits + ValidField,
    {
        unsafe { BitsAccessor::new(self) }
    }

    /// Create a mutable accessor for `isbits` data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn bits_data_mut<'borrow>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField + IsBits,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout
            BitsAccessorMut::new(self)
        }
    }

    /// Create a mutable accessor for `isbits` data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn bits_data_mut_with_layout<'borrow, L>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'static, 'static, Layout = L>,
        L: IsBits + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout and L is the layout of T
            BitsAccessorMut::new(self)
        }
    }

    /// Try to create a mutable accessor for `isbits` data with layout `L`.
    ///
    /// If the array doesn't have an isbits layout `ArrayLayoutError::NotBits` is returned. If `L`
    /// is not a valid field layout for the element type `TypeError::InvalidLayout` is returned.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn try_bits_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: IsBits + ValidField,
    {
        unsafe {
            if !self.has_bits_layout() {
                Err(ArrayLayoutError::NotBits {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsAccessorMut::new(self))
        }
    }

    /// Create a mutable accessor for `isbits` data with layout `L` without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist. The element type must be an isbits type, and
    /// `L` must be a valid field layout of the element type.
    #[inline]
    pub unsafe fn bits_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: IsBits + ValidField,
    {
        unsafe { BitsAccessorMut::new(self) }
    }

    /// Create an accessor for inline data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn inline_data<'borrow>(
        &'borrow self,
    ) -> InlineAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            InlineAccessor::new(self)
        }
    }

    /// Create an accessor for inline data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn inline_data_with_layout<'borrow, L>(
        &'borrow self,
    ) -> InlineAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'scope, 'data, Layout = L>,
        L: ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout and L is the layout of T
            InlineAccessor::new(self)
        }
    }

    /// Try to create an accessor for inline data with layout `L`.
    ///
    /// If the array doesn't have an inline layout `ArrayLayoutError::NotInline` is returned. If
    /// `L` is not a valid field layout for the element type `TypeError::InvalidLayout` is
    /// returned.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn try_inline_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<InlineAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: ValidField,
    {
        unsafe {
            if !self.has_inline_layout() {
                Err(ArrayLayoutError::NotInline {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(InlineAccessor::new(self))
        }
    }

    /// Create an accessor for inline data with layout `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist. The elements must be stored inline, and `L`
    /// must be a valid field layout of the element type.
    #[inline]
    pub unsafe fn inline_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> InlineAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: ValidField,
    {
        unsafe { InlineAccessor::new(self) }
    }

    /// Create a mutable accessor for inline data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn inline_data_mut<'borrow>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            InlineAccessorMut::new(self)
        }
    }

    /// Create a mutable accessor for inline data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn inline_data_mut_with_layout<'borrow, L>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'scope, 'data, Layout = L>,
        L: ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout and L is the layout of T
            InlineAccessorMut::new(self)
        }
    }

    /// Try to create a mutable accessor for inline data with layout `L`.
    ///
    /// If the array doesn't have an inline layout `ArrayLayoutError::NotInline` is returned. If
    /// `L` is not a valid field layout for the element type `TypeError::InvalidLayout` is
    /// returned.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn try_inline_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: ValidField,
    {
        unsafe {
            if !self.has_inline_layout() {
                Err(ArrayLayoutError::NotInline {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(InlineAccessorMut::new(self))
        }
    }

    /// Create a mutable  accessor for inline data with layout `L` without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist. The elements must be stored inline, and `L`
    /// must be a valid field layout of the element type.
    #[inline]
    pub unsafe fn inline_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: ValidField,
    {
        unsafe { InlineAccessorMut::new(self) }
    }

    /// Create an accessor for unions of isbits types.
    ///
    /// This function panics if the array doesn't have a union layout.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn union_data<'borrow>(
        &'borrow self,
    ) -> BitsUnionAccessor<'borrow, 'scope, 'data, T, N>
    where
        T: BitsUnionCtor,
    {
        unsafe {
            assert!(
                self.has_union_layout(),
                "Array does not have a union layout"
            );
            BitsUnionAccessor::new(self)
        }
    }

    /// Try to create an accessor for unions of isbits types.
    ///
    /// If the element type is not a union of isbits types `ArrayLayoutError::NotUnion` is
    /// returned.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn try_union_data<'borrow>(
        &'borrow self,
    ) -> JlrsResult<BitsUnionAccessor<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_union_layout() {
                Err(ArrayLayoutError::NotUnion {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsUnionAccessor::new(self))
        }
    }

    /// Create an accessor for unions of isbits types without checking any invariants.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist. The element type must be a union of isbits
    /// types.
    #[inline]
    pub unsafe fn union_data_unchecked<'borrow>(
        &'borrow self,
    ) -> BitsUnionAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { BitsUnionAccessor::new(self) }
    }

    /// Create a mutable accessor for unions of isbits types.
    ///
    /// This function panics if the array doesn't have a union layout.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn union_data_mut<'borrow>(
        &'borrow mut self,
    ) -> BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N>
    where
        T: BitsUnionCtor,
    {
        unsafe {
            assert!(
                self.has_union_layout(),
                "Array does not have a union layout"
            );
            BitsUnionAccessorMut::new(self)
        }
    }

    /// Try to create a mutable accessor for unions of isbits types.
    ///
    /// If the element type is not a union of isbits types `ArrayLayoutError::NotUnion` is
    /// returned.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn try_union_data_mut<'borrow>(
        &'borrow mut self,
    ) -> JlrsResult<BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_union_layout() {
                Err(ArrayLayoutError::NotUnion {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsUnionAccessorMut::new(self))
        }
    }

    /// Create a mutable accessor for unions of isbits types without checking any invariants.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist. The element type must be a union of isbits
    /// types.
    #[inline]
    pub unsafe fn union_data_mut_unchecked<'borrow>(
        &'borrow mut self,
    ) -> BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { BitsUnionAccessorMut::new(self) }
    }

    /// Create an accessor for managed data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<T>>`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn managed_data<'borrow>(
        &'borrow self,
    ) -> ManagedAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have correct layout
            ManagedAccessor::new(self)
        }
    }

    /// Try to create an accessor for managed data of type `L`.
    ///
    /// If the element type is incompatible with `L` `ArrayLayoutError::NotManaged` is returned.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn try_managed_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<ManagedAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: Managed<'scope, 'data> + Typecheck,
    {
        unsafe {
            if !self.has_managed_layout::<L>() {
                Err(ArrayLayoutError::NotManaged {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                    name: L::NAME.into(),
                })?;
            }

            Ok(ManagedAccessor::new(self))
        }
    }

    /// Create an accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist. The element type must be compatible with
    /// `L`.
    #[inline]
    pub unsafe fn managed_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> ManagedAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: Managed<'scope, 'data>,
    {
        unsafe { ManagedAccessor::new(self) }
    }

    /// Create a mutable accessor for managed data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<T>>`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn managed_data_mut<'borrow>(
        &'borrow mut self,
    ) -> ManagedAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have correct layout
            ManagedAccessorMut::new(self)
        }
    }

    /// Try to create a mutable accessor for managed data of type `L`.
    ///
    /// If the element type is incompatible with `L` `ArrayLayoutError::NotManaged` is returned.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn try_managed_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<ManagedAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: Managed<'scope, 'data> + Typecheck,
    {
        unsafe {
            if !self.has_managed_layout::<L>() {
                Err(ArrayLayoutError::NotManaged {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                    name: L::NAME.into(),
                })?;
            }

            Ok(ManagedAccessorMut::new(self))
        }
    }

    /// Create a mutable accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist. The element type must be compatible with
    /// `L`.
    #[inline]
    pub unsafe fn managed_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> ManagedAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: Managed<'scope, 'data>,
    {
        unsafe { ManagedAccessorMut::new(self) }
    }

    /// Create an accessor for value data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<Value>>`s.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn value_data<'borrow>(&'borrow self) -> ValueAccessor<'borrow, 'scope, 'data, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            ValueAccessor::new(self)
        }
    }

    /// Try to create an accessor for value data.
    ///
    /// If the elements are stored inline `ArrayLayoutError::NotPointer` is returned.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    pub unsafe fn try_value_data<'borrow>(
        &'borrow self,
    ) -> JlrsResult<ValueAccessor<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_value_layout() {
                Err(ArrayLayoutError::NotPointer {
                    element_type: self.element_type().error_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(ValueAccessor::new(self))
        }
    }

    /// Create an accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist. The elements must not be stored inline.
    #[inline]
    pub unsafe fn value_data_unchecked<'borrow>(
        &'borrow self,
    ) -> ValueAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { ValueAccessor::new(self) }
    }

    /// Create a mutable accessor for value data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<Value>>`s.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn value_data_mut<'borrow>(
        &'borrow mut self,
    ) -> ValueAccessorMut<'borrow, 'scope, 'data, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            ValueAccessorMut::new(self)
        }
    }

    /// Try to create a mutable accessor for value data.
    ///
    /// If the elements are stored inline `ArrayLayoutError::NotPointer` is returned.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    pub unsafe fn try_value_data_mut<'borrow>(
        &'borrow mut self,
    ) -> JlrsResult<ValueAccessorMut<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_value_layout() {
                Err(ArrayLayoutError::NotPointer {
                    element_type: self.element_type().error_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(ValueAccessorMut::new(self))
        }
    }

    /// Create a mutable accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist. The elements must not be stored inline.
    #[inline]
    pub unsafe fn value_data_mut_unchecked<'borrow>(
        &'borrow mut self,
    ) -> ValueAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { ValueAccessorMut::new(self) }
    }

    /// Create an accessor for indeterminate data.
    ///
    /// Safety:
    ///
    /// No mutable accessors to this data must exist.
    #[inline]
    pub unsafe fn indeterminate_data<'borrow>(
        &'borrow self,
    ) -> IndeterminateAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { IndeterminateAccessor::new(self) }
    }

    /// Create a mutable accessor for indeterminate data.
    ///
    /// Safety:
    ///
    /// No other accessors to this data must exist.
    #[inline]
    pub unsafe fn indeterminate_data_mut<'borrow>(
        &'borrow mut self,
    ) -> IndeterminateAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { IndeterminateAccessorMut::new(self) }
    }
}

// Conversions
impl<'scope, 'data, T> ArrayBase<'scope, 'data, T, -1> {
    /// Sets the rank of this array to `N` if `N` is equal to the rank of `self` at runtime.
    pub fn set_rank<const N: isize>(self) -> JlrsResult<ArrayBase<'scope, 'data, T, N>> {
        if self.n_dims() as isize != N {
            Err(ArrayLayoutError::RankMismatch {
                found: self.n_dims() as _,
                provided: N,
            })?;
        }

        unsafe { Ok(self.set_rank_unchecked()) }
    }

    /// Sets the rank of this array to `N`.
    ///
    /// Safety:
    ///
    /// The rank at runtime must be equal to `N`.
    #[inline]
    pub unsafe fn set_rank_unchecked<const N: isize>(self) -> ArrayBase<'scope, 'data, T, N> {
        ArrayBase(
            self.unwrap_non_null(Private),
            PhantomData,
            PhantomData,
            PhantomData,
        )
    }
}

impl<'scope, 'data, const N: isize> ArrayBase<'scope, 'data, Unknown, N> {
    /// Sets the element type of this array to `T` if the cosntructed type of `T` is equal to the
    /// element type of `self` at runtime.
    pub fn set_type<T: ConstructType>(self) -> JlrsResult<ArrayBase<'scope, 'data, T, N>> {
        unsafe {
            let unrooted = Unrooted::new();

            let constructed = T::construct_type(unrooted).as_value();
            let elem_ty = self.element_type();
            if constructed != elem_ty {
                Err(TypeError::IncompatibleType {
                    element_type: constructed.display_string_or(CANNOT_DISPLAY_TYPE),
                    value_type: elem_ty.display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(self.set_type_unchecked())
        }
    }

    /// Sets the element type of this array to `T`.
    ///
    /// Safety:
    ///
    /// The element at runtime must be equal to the constructed type of `T`.
    #[inline]
    pub unsafe fn set_type_unchecked<T: ConstructType>(self) -> ArrayBase<'scope, 'data, T, N> {
        ArrayBase(
            self.unwrap_non_null(Private),
            PhantomData,
            PhantomData,
            PhantomData,
        )
    }
}

impl<'scope, 'data, T, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Forget the rank of this array.
    #[inline]
    pub fn forget_rank(self) -> ArrayBase<'scope, 'data, T, -1> {
        ArrayBase(
            self.unwrap_non_null(Private),
            PhantomData,
            PhantomData,
            PhantomData,
        )
    }

    /// Forget the element type of this array.
    #[inline]
    pub fn forget_type(self) -> ArrayBase<'scope, 'data, Unknown, N> {
        ArrayBase(
            self.unwrap_non_null(Private),
            PhantomData,
            PhantomData,
            PhantomData,
        )
    }

    /// Asserts that the rank is correct.
    #[inline]
    pub fn assert_rank(self) {
        if N == -1 {
            return;
        }

        let rank = self.rank();
        assert!(rank as isize == N);
    }
}

impl<'scope, 'data, T: ConstructType, const N: isize> ArrayBase<'scope, 'data, T, N> {
    /// Asserts that the element type of `self` is equal to the type constructed by `T`.
    ///
    /// Panics if the element type of `self`is not equal to the type constructed by `T`.
    pub fn assert_type(self) {
        unsafe {
            let unrooted = Unrooted::new();
            unrooted.local_scope::<_, 1>(|mut frame| {
                let ty = T::construct_type(&mut frame);
                assert_eq!(ty, self.element_type());
            });
        }
    }
}

/// Marker type used to indicate the element type of an array is unknown.
pub enum Unknown {}

/// `Array` or `WeakArray`, depending on the target type `T`.
pub type ArrayBaseData<'target, 'data, Tgt, T, const N: isize> =
    <Tgt as TargetType<'target>>::Data<'data, ArrayBase<'target, 'data, T, N>>;

/// `JuliaResult<Array>` or `WeakJuliaResult<WeakArray>`, depending on the target type `T`.
pub type ArrayBaseResult<'target, 'data, Tgt, T, const N: isize> =
    TargetResult<'target, 'data, ArrayBase<'target, 'data, T, N>, Tgt>;

/// An array with an unknown element type and unknown rank.
pub type Array<'scope, 'data> = ArrayBase<'scope, 'data, Unknown, -1>;
pub type WeakArray<'scope, 'data> = Weak<'scope, 'data, Array<'scope, 'data>>;
pub type ArrayRet = WeakArray<'static, 'static>;
pub type ArrayData<'target, 'data, Tgt> =
    <Tgt as TargetType<'target>>::Data<'data, Array<'target, 'data>>;
pub type ArrayResult<'target, 'data, Tgt> =
    TargetResult<'target, 'data, Array<'target, 'data>, Tgt>;

/// An array with an unknown element type of rank 1.
pub type Vector<'scope, 'data> = ArrayBase<'scope, 'data, Unknown, 1>;
pub type WeakVector<'scope, 'data> = Weak<'scope, 'data, Vector<'scope, 'data>>;
pub type VectorRet = WeakVector<'static, 'static>;
pub type VectorData<'target, 'data, Tgt> =
    <Tgt as TargetType<'target>>::Data<'data, Vector<'target, 'data>>;
pub type VectorResult<'target, 'data, Tgt> =
    TargetResult<'target, 'data, Vector<'target, 'data>, Tgt>;

/// An array with an unknown element type of rank 1.
pub type VectorAny<'scope, 'data> = ArrayBase<'scope, 'data, Value<'scope, 'data>, 1>;
pub type WeakVectorAny<'scope, 'data> = Weak<'scope, 'data, VectorAny<'scope, 'data>>;
pub type VectorAnyRet = WeakVectorAny<'static, 'static>;
pub type VectorAnyData<'target, 'data, Tgt> =
    <Tgt as TargetType<'target>>::Data<'data, VectorAny<'target, 'data>>;
pub type VectorAnyResult<'target, 'data, Tgt> =
    TargetResult<'target, 'data, VectorAny<'target, 'data>, Tgt>;

/// An array with an unknown element type of rank 2.
pub type Matrix<'scope, 'data> = ArrayBase<'scope, 'data, Unknown, 2>;
pub type WeakMatrix<'scope, 'data> = Weak<'scope, 'data, Matrix<'scope, 'data>>;
pub type MatrixRet = WeakMatrix<'static, 'static>;
pub type MatrixData<'target, 'data, Tgt> =
    <Tgt as TargetType<'target>>::Data<'data, Matrix<'target, 'data>>;
pub type MatrixResult<'target, 'data, Tgt> =
    TargetResult<'target, 'data, Matrix<'target, 'data>, Tgt>;

/// An array with a known element type and unknown rank.
pub type TypedArray<'scope, 'data, T> = ArrayBase<'scope, 'data, T, -1>;
pub type WeakTypedArray<'scope, 'data, T> = Weak<'scope, 'data, TypedArray<'scope, 'data, T>>;
pub type TypedArrayRet<T> = WeakTypedArray<'static, 'static, T>;
pub type TypedArrayData<'target, 'data, Tgt, T> =
    <Tgt as TargetType<'target>>::Data<'data, TypedArray<'target, 'data, T>>;
pub type TypedArrayResult<'target, 'data, Tgt, T> =
    TargetResult<'target, 'data, TypedArray<'target, 'data, T>, Tgt>;

/// An array with a known element type of rank 1.
pub type TypedVector<'scope, 'data, T> = ArrayBase<'scope, 'data, T, 1>;
pub type WeakTypedVector<'scope, 'data, T> = Weak<'scope, 'data, TypedVector<'scope, 'data, T>>;
pub type TypedVectorRet<T> = WeakTypedVector<'static, 'static, T>;
pub type TypedVectorData<'target, 'data, Tgt, T> =
    <Tgt as TargetType<'target>>::Data<'data, TypedVector<'target, 'data, T>>;
pub type TypedVectorResult<'target, 'data, Tgt, T> =
    TargetResult<'target, 'data, TypedVector<'target, 'data, T>, Tgt>;

/// An array with a known element type of rank 2.
pub type TypedMatrix<'scope, 'data, T> = ArrayBase<'scope, 'data, T, 2>;
pub type WeakTypedMatrix<'scope, 'data, T> = Weak<'scope, 'data, TypedMatrix<'scope, 'data, T>>;
pub type TypedMatrixRet<T> = WeakTypedMatrix<'static, 'static, T>;
pub type TypedMatrixData<'target, 'data, Tgt, T> =
    <Tgt as TargetType<'target>>::Data<'data, TypedMatrix<'target, 'data, T>>;
pub type TypedMatrixResult<'target, 'data, Tgt, T> =
    TargetResult<'target, 'data, TypedMatrix<'target, 'data, T>, Tgt>;

/// An array with an unknown element type and known rank.
pub type RankedArray<'scope, 'data, const N: isize> = ArrayBase<'scope, 'data, Unknown, N>;
pub type WeakRankedArray<'scope, 'data, const N: isize> =
    Weak<'scope, 'data, RankedArray<'scope, 'data, N>>;
pub type RankedArrayRet<const N: isize> = WeakRankedArray<'static, 'static, N>;
pub type RankedArrayData<'target, 'data, Tgt, const N: isize> =
    <Tgt as TargetType<'target>>::Data<'data, RankedArray<'target, 'data, N>>;
pub type RankedArrayResult<'target, 'data, Tgt, const N: isize> =
    TargetResult<'target, 'data, RankedArray<'target, 'data, N>, Tgt>;

/// An array with a known element type and known rank.
pub type TypedRankedArray<'scope, 'data, T, const N: isize> = ArrayBase<'scope, 'data, T, N>;
pub type WeakTypedRankedArray<'scope, 'data, T, const N: isize> =
    Weak<'scope, 'data, TypedRankedArray<'scope, 'data, T, N>>;
pub type TypedRankedArrayRet<T, const N: isize> = WeakTypedRankedArray<'static, 'static, T, N>;
pub type TypedRankedArrayData<'target, 'data, Tgt, T, const N: isize> =
    <Tgt as TargetType<'target>>::Data<'data, TypedRankedArray<'target, 'data, T, N>>;
pub type TypedRankedArrayResult<'target, 'data, Tgt, T, const N: isize> =
    TargetResult<'target, 'data, TypedRankedArray<'target, 'data, T, N>, Tgt>;

unsafe impl<'scope, 'data, const N: isize> Typecheck for ArrayBase<'scope, 'data, Unknown, N> {
    fn typecheck(ty: DataType) -> bool {
        let unrooted = ty.unrooted_target();

        // Datatype must be an array type
        if ty.type_name().unwrap(Private) != TypeName::of_array(&unrooted).unwrap(Private) {
            return false;
        }

        if N >= 0 {
            // Casting to RankedArray, check if the rank is correct
            unsafe {
                let param = ty.parameter_unchecked(1);

                if !param.is::<isize>() || param.unbox_unchecked::<isize>() != N {
                    return false;
                }
            }
        }

        true
    }
}

unsafe impl<'scope, 'data, T: ConstructType, const N: isize> Typecheck
    for ArrayBase<'scope, 'data, T, N>
{
    fn typecheck(ty: DataType) -> bool {
        let unrooted = ty.unrooted_target();

        // Datatype must be an array type
        if ty.type_name().unwrap(Private) != TypeName::of_array(&unrooted).unwrap(Private) {
            return false;
        }

        if N >= 0 {
            // Casting to RankedArray, check if the rank is correct
            unsafe {
                let param = ty.parameter_unchecked(1);

                if !param.is::<isize>() || param.unbox_unchecked::<isize>() != N {
                    return false;
                }
            }
        }

        unrooted.local_scope::<_, 1>(|mut frame| {
            // Safety: elem_ty is reachable from ty
            let elem_ty = unsafe { ty.parameter_unchecked(0) };
            let constructed_ty = T::construct_type(&mut frame);
            if elem_ty.is::<TypeVar>() && constructed_ty.is::<TypeVar>() {
                unsafe {
                    let et = elem_ty.cast_unchecked::<TypeVar>();
                    let ct = constructed_ty.cast_unchecked::<TypeVar>();
                    return et.name() == ct.name()
                        && et.lower_bound(&frame).as_value() == ct.lower_bound(&frame).as_value()
                        && et.upper_bound(&frame).as_value() == ct.upper_bound(&frame).as_value();
                }
            }
            elem_ty == constructed_ty
        })
    }
}

impl<T, const N: isize> Debug for ArrayBase<'_, '_, T, N> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self.display_string() {
            Ok(s) => write!(f, "{}", s),
            Err(e) => write!(f, "<Cannot display value: {}>", e),
        }
    }
}

impl<'scope, 'data, T, const N: isize> ManagedPriv<'scope, 'data>
    for ArrayBase<'scope, 'data, T, N>
{
    type Wraps = jl_array_t;

    type WithLifetimes<'target, 'da> = ArrayBase<'target, 'da, T, N>;

    const NAME: &'static str = "Array";

    unsafe fn wrap_non_null(inner: NonNull<Self::Wraps>, _: crate::private::Private) -> Self {
        ArrayBase(inner, PhantomData, PhantomData, PhantomData)
    }

    fn unwrap_non_null(self, _: crate::private::Private) -> NonNull<Self::Wraps> {
        self.0
    }
}

unsafe impl<const N: isize> ValidField for Option<WeakRankedArray<'_, '_, N>> {
    fn valid_field(v: Value) -> bool {
        if v.is::<DataType>() {
            let dt = unsafe { v.cast_unchecked::<DataType>() };
            let is_array = dt.is::<Array>();

            if !is_array {
                return false;
            }

            let parameters = dt.parameters();
            let parameters = parameters.data();
            if N != -1 {
                unsafe {
                    let unrooted = Unrooted::new();
                    let rank_param = parameters.get(unrooted, 1).unwrap_unchecked().as_value();
                    if !rank_param.is::<isize>() || rank_param.unbox_unchecked::<isize>() != N {
                        return false;
                    }
                }
            }

            true
        } else if v.is::<UnionAll>() {
            let ua = unsafe { v.cast_unchecked::<UnionAll>() };
            let dt = ua.base_type();

            if !dt.is::<Array>() {
                return false;
            }
            let parameters = dt.parameters();
            let parameters = parameters.data();
            if N != -1 {
                unsafe {
                    let unrooted = Unrooted::new();
                    let rank_param = parameters.get(unrooted, 1).unwrap_unchecked().as_value();
                    if !rank_param.is::<isize>() || rank_param.unbox_unchecked::<isize>() != N {
                        return false;
                    }
                }
            }

            true
        } else {
            false
        }
    }
}

unsafe impl<T: ConstructType, const N: isize> ValidField
    for Option<WeakTypedRankedArray<'_, '_, T, N>>
{
    fn valid_field(v: Value) -> bool {
        if v.is::<DataType>() {
            let dt = unsafe { v.cast_unchecked::<DataType>() };
            if !dt.is::<Array>() {
                return false;
            }

            let parameters = dt.parameters();
            let parameters = parameters.data();
            if N != -1 {
                unsafe {
                    let unrooted = Unrooted::new();
                    let rank_param = parameters.get(unrooted, 1).unwrap_unchecked().as_value();
                    if !rank_param.is::<isize>() || rank_param.unbox_unchecked::<isize>() != N {
                        return false;
                    }
                }
            }

            unsafe {
                let unrooted = Unrooted::new();
                unrooted.local_scope::<_, 1>(|mut frame| {
                    let ty = T::construct_type(&mut frame);
                    let elem_ty = parameters.get(unrooted, 0).unwrap_unchecked().as_value();
                    ty == elem_ty
                })
            }
        } else {
            false
        }
    }
}

unsafe impl<'scope, 'data, T: ConstructType, const N: isize> ConstructType
    for TypedRankedArray<'scope, 'data, T, N>
{
    type Static = TypedRankedArray<'static, 'static, T::Static, N>;

    fn construct_type_uncached<'target, Tgt>(
        target: Tgt,
    ) -> crate::prelude::ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        let ty = UnionAll::array_type(&target);

        if N == -1 {
            target.with_local_scope::<_, 2>(|target, mut frame| unsafe {
                let elty = T::construct_type(&mut frame);
                let tn_n = ty.body().cast_unchecked::<UnionAll>().var();
                let applied = ty.apply_types_unchecked(&mut frame, [elty, tn_n.as_value()]);

                UnionAll::rewrap(target, applied.cast_unchecked::<DataType>())
            })
        } else {
            target.with_local_scope::<_, 3>(|target, mut frame| unsafe {
                let elty = T::construct_type(&mut frame);
                let n = Value::new(&mut frame, N);
                let applied = ty.apply_types_unchecked(&mut frame, [elty, n]);

                UnionAll::rewrap(target, applied.cast_unchecked::<DataType>())
            })
        }
    }

    fn base_type<'target, Tgt>(target: &Tgt) -> Option<Value<'target, 'static>>
    where
        Tgt: Target<'target>,
    {
        Some(UnionAll::array_type(target).as_value())
    }

    fn construct_type_with_env_uncached<'target, Tgt>(
        target: Tgt,
        env: &crate::data::types::construct_type::TypeVarEnv,
    ) -> ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        let ty = UnionAll::array_type(&target);

        if N == -1 {
            let n_sym = NSym::get_symbol(&target);
            let n_param = match env.get(n_sym) {
                Some(n_param) => n_param.as_value(),
                _ => ty.base_type().parameter(1).unwrap(),
            };

            target.with_local_scope::<_, 2>(|target, mut frame| unsafe {
                let t = T::construct_type_with_env(&mut frame, env);
                let applied = ty.apply_types_unchecked(&mut frame, [t, n_param]);
                assert!(applied.is::<DataType>());
                applied
                    .cast_unchecked::<DataType>()
                    .wrap_with_env(target, env)
            })
        } else {
            target.with_local_scope::<_, 3>(|target, mut frame| unsafe {
                let t = T::construct_type_with_env(&mut frame, env);
                let n = Value::new(&mut frame, N);
                let applied = ty.apply_types_unchecked(&mut frame, [t, n]);
                assert!(applied.is::<DataType>());
                applied
                    .cast_unchecked::<DataType>()
                    .wrap_with_env(target, env)
            })
        }
    }
}

unsafe impl<'scope, 'data, const N: isize> ConstructType for RankedArray<'scope, 'data, N> {
    type Static = RankedArray<'static, 'static, N>;

    fn construct_type_uncached<'target, Tgt>(
        target: Tgt,
    ) -> crate::prelude::ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        let ty = UnionAll::array_type(&target);

        if N == -1 {
            ty.as_value().root(target)
        } else {
            target.with_local_scope::<_, 3>(|target, mut frame| unsafe {
                let tn_t = TypeVar::new_unchecked(&mut frame, "T", None, None);
                let n = Value::new(&mut frame, N);
                let applied = ty.apply_types_unchecked(&mut frame, [tn_t.as_value(), n]);

                UnionAll::rewrap(target, applied.cast_unchecked::<DataType>())
            })
        }
    }

    #[inline]
    fn base_type<'target, Tgt>(target: &Tgt) -> Option<Value<'target, 'static>>
    where
        Tgt: Target<'target>,
    {
        Some(UnionAll::array_type(target).as_value())
    }

    fn construct_type_with_env_uncached<'target, Tgt>(
        target: Tgt,
        env: &crate::data::types::construct_type::TypeVarEnv,
    ) -> ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        let ty = UnionAll::array_type(&target);
        let t_sym = TSym::get_symbol(&target);
        let t_param = env.get(t_sym).expect("TypeVar T is not in env");

        if N == -1 {
            let n_sym = NSym::get_symbol(&target);
            let n_param = match env.get(n_sym) {
                Some(n_param) => n_param.as_value(),
                _ => unsafe {
                    ty.body()
                        .cast_unchecked::<UnionAll>()
                        .body()
                        .cast_unchecked::<DataType>()
                        .parameter(1)
                        .unwrap()
                },
            };

            unsafe { ty.apply_types_unchecked(target, [t_param.as_value(), n_param]) }
        } else {
            target.with_local_scope::<_, 1>(|target, mut frame| unsafe {
                let n = Value::new(&mut frame, N);
                let applied = ty.apply_types_unchecked(target, [t_param.as_value(), n]);
                applied
            })
        }
    }
}

unsafe impl<'scope, 'data, const N: isize> CCallArg for RankedArray<'scope, 'data, N> {
    type CCallArgType = AnyType;
    type FunctionArgType = Self;
}

unsafe impl<const N: isize> CCallReturn for RankedArrayRet<N> {
    type CCallReturnType = AnyType;
    type FunctionReturnType = RankedArray<'static, 'static, N>;
    type ReturnAs = Self;

    #[inline]
    unsafe fn return_or_throw(self) -> Self::ReturnAs {
        self
    }
}

unsafe impl<'scope, 'data, T: ConstructType, const N: isize> CCallArg
    for TypedRankedArray<'scope, 'data, T, N>
{
    type CCallArgType = IfConcreteElse<Self, AnyType>;
    type FunctionArgType = Self;
}

unsafe impl<T: ConstructType, const N: isize> CCallReturn for TypedRankedArrayRet<T, N> {
    type CCallReturnType = IfConcreteElse<TypedRankedArray<'static, 'static, T, N>, AnyType>;
    type FunctionReturnType = TypedRankedArray<'static, 'static, T, N>;
    type ReturnAs = Self;

    #[inline]
    unsafe fn return_or_throw(self) -> Self::ReturnAs {
        self
    }
}

#[inline]
pub(crate) fn sized_dim_tuple<'target, D, Tgt>(
    target: Tgt,
    dims: &D,
) -> ValueData<'target, 'static, Tgt>
where
    D: RankedDims,
    Tgt: Target<'target>,
{
    unsafe {
        let dims_type = dims.dimension_object(&target).as_managed();
        let tuple = jl_new_struct_uninit(dims_type.unwrap(Private));

        {
            let slice =
                std::slice::from_raw_parts_mut(tuple as *mut MaybeUninit<usize>, D::RANK as _);
            dims.fill_tuple(slice, Private);
        }

        Value::wrap_non_null(NonNull::new_unchecked(tuple), Private).root(target)
    }
}

#[inline]
pub(crate) fn unsized_dim_tuple<'target, D, Tgt>(
    target: Tgt,
    dims: &D,
) -> ValueData<'target, 'static, Tgt>
where
    D: DimsExt,
    Tgt: Target<'target>,
{
    unsafe {
        let dims_type = dims.dimension_object(&target).as_managed();
        let tuple = jl_new_struct_uninit(dims_type.unwrap(Private));

        {
            let slice =
                std::slice::from_raw_parts_mut(tuple as *mut MaybeUninit<usize>, dims.rank());
            dims.fill_tuple(slice, Private);
        }

        Value::wrap_non_null(NonNull::new_unchecked(tuple), Private).root(target)
    }
}

// Safety: must be used as a finalizer when moving array data from Rust to Julia
// to ensure it's freed correctly.
#[julia_version(until = "1.10")]
unsafe extern "C" fn droparray<T>(a: Array) {
    unsafe {
        let sz = a.dimensions().size();
        let data_ptr = a.data_ptr().cast::<T>();

        let data = Vec::from_raw_parts(data_ptr, sz, sz);
        std::mem::drop(data);
    }
}

#[julia_version(since = "1.11")]
unsafe extern "C" fn droparray<T>(a: *mut c_void) {
    unsafe {
        #[repr(C)]
        struct GenericMemory<T> {
            length: usize,
            ptr: *mut T,
        }

        let a = NonNull::new_unchecked(a as *mut GenericMemory<T>).as_mut();
        let v = Vec::from_raw_parts(a.ptr as *mut T, a.length, a.length);
        a.ptr = null_mut();
        a.length = 0;
        std::mem::drop(v);
    }
}