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
//! Julia values and functions.
//!
//! When using this crate Julia data will usually be returned as a [`Value`]. A [`Value`] is a
//! "generic" wrapper. Type information will generally be available allowing you to safely convert
//! a [`Value`] to its actual type. Data like arrays and modules can be returned as a [`Value`].
//! These, and other types with a custom implementation in the C API, can be found in the
//! submodules of this module.
//!
//! One special property of a [`Value`] is that it can always be called as a function; there's no
//! way to check if a [`Value`] is actually a function except trying to call it. Multiple
//! [`Value`]s can be created at the same time by using [`Values`].
//!
//! [`Value`]: struct.Value.html
//! [`Values`]: struct.Values.html

#[doc(hidden)]
#[macro_export]
macro_rules! count {
    ($name:expr => $value:expr) => {
        2
    };
    ($name:expr => $value:expr, $($rest:tt)+) => {
        count!(2, $($rest)+)
    };
    ($n:expr, $name:expr => $value:expr) => {
        $n + 1
    };
    ($n:expr, $name:expr => $value:expr, $($rest:tt)+) => {
        count!($n + 1, $($rest)+)
    };
}

/// Create a new named tuple. You will need a named tuple to call functions with keyword
/// arguments.
///
/// Example:
///
/// ```no_run
/// # use jlrs::prelude::*;
/// # fn main() {
/// let mut julia = unsafe { Julia::init(16).unwrap() };
/// // Three slots; two for the inputs and one for the output.
/// julia.frame(3, |global, frame| {
///     // Create the two arguments, each value requires one slot
///     let i = Value::new(frame, 2u64)?;
///     let j = Value::new(frame, 1u32)?;
///
///     let _nt = named_tuple!(frame, "i" => i, "j" => j);
///
///     Ok(())
/// }).unwrap();
/// # }
/// ```
#[macro_export]
macro_rules! named_tuple {
    ($frame:expr, $name:expr => $value:expr) => {
        $crate::value::Value::new_named_tuple($frame, &mut [$name], &mut [$value])
    };
    ($frame:expr, $name:expr => $value:expr, $($rest:tt)+) => {
        {
            let n = $crate::count!($($rest)+);
            let mut names = ::smallvec::SmallVec::<[_; $crate::value::MAX_SIZE]>::with_capacity(n);
            let mut values = ::smallvec::SmallVec::<[_; $crate::value::MAX_SIZE]>::with_capacity(n);

            names.push($name);
            values.push($value);
            $crate::named_tuple!($frame, &mut names, &mut values, $($rest)+)
        }
    };
    ($frame:expr, $names:expr, $values:expr, $name:expr => $value:expr, $($rest:tt)+) => {
        {
            $names.push($name);
            $values.push($value);
            named_tuple!($frame, $names, $values, $($rest)+)
        }
    };
    ($frame:expr, $names:expr, $values:expr, $name:expr => $value:expr) => {
        {
            $names.push($name);
            $values.push($value);
            $crate::value::Value::new_named_tuple($frame, $names, $values)
        }
    };
}

use self::array::{Array, Dimensions};
use self::datatype::{Concrete, DataType};
use self::module::Module;
use self::symbol::Symbol;
use self::type_var::TypeVar;
use self::union_all::UnionAll;
use crate::error::{JlrsError, JlrsResult};
use crate::frame::Output;
use crate::global::Global;
use crate::impl_julia_type;
use crate::traits::{
    private::Internal, valid_layout::ValidLayout, Cast, Frame, IntoJulia, JuliaType,
    JuliaTypecheck, TemporarySymbol,
};
use jl_sys::{
    jl_alloc_array_1d, jl_alloc_array_2d, jl_alloc_array_3d, jl_an_empty_string,
    jl_an_empty_vec_any, jl_any_type, jl_apply_array_type, jl_apply_tuple_type_v, jl_apply_type,
    jl_array_any_type, jl_array_int32_type, jl_array_symbol_type, jl_array_uint8_type,
    jl_bottom_type, jl_call, jl_call0, jl_call1, jl_call2, jl_call3, jl_datatype_t,
    jl_diverror_exception, jl_egal, jl_emptytuple, jl_eval_string, jl_exception_occurred, jl_false,
    jl_field_index, jl_field_isptr, jl_field_names, jl_fieldref, jl_fieldref_noalloc, jl_finalize,
    jl_gc_add_finalizer, jl_gc_wb, jl_get_kwsorter, jl_get_nth_field, jl_get_nth_field_noalloc,
    jl_interrupt_exception, jl_is_kind, jl_isa, jl_memory_exception, jl_new_array,
    jl_new_struct_uninit, jl_new_structv, jl_nfields, jl_nothing, jl_nothing_type, jl_object_id,
    jl_ptr_to_array, jl_ptr_to_array_1d, jl_readonlymemory_exception, jl_set_nth_field,
    jl_stackovf_exception, jl_subtype, jl_svec_data, jl_svec_len, jl_true, jl_type_union,
    jl_type_unionall, jl_typeof, jl_typeof_str, jl_undefref_exception, jl_value_t,
};
use smallvec::SmallVec;
use std::cell::UnsafeCell;
use std::ffi::{CStr, CString};
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::marker::PhantomData;
use std::ptr::null_mut;
use std::slice;

/// In some cases it's necessary to place one or more arguments in front of the arguments a
/// function is called with. Examples include `Value::asynccall` and `WithKeywords::call`. If
/// these functions are called with fewer than `MAX_SIZE` arguments (including the added
/// arguments), no heap allocation is required to store them.
pub const MAX_SIZE: usize = 8;

pub mod array;
pub mod code_instance;
pub mod datatype;
pub mod expr;
pub mod method;
pub mod method_instance;
pub mod method_table;
pub mod module;
pub mod simple_vector;
pub mod string;
pub mod symbol;
pub mod task;
pub mod tuple;
pub mod type_name;
pub mod type_var;
pub mod typemap_entry;
pub mod typemap_level;
pub mod union;
pub mod union_all;
pub mod weak_ref;

thread_local! {
    // Used as a pool to convert dimensions to tuples. Safe because a thread local is initialized
    // when `with` is first called, which happens after `Julia::init` has been called. The C API
    // requires a mutable pointer to this array so an `UnsafeCell` is used to store it.
    static JL_LONG_TYPE: UnsafeCell<[*mut jl_datatype_t; 8]> = unsafe {
        UnsafeCell::new([
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
            usize::julia_type(),
        ])
    };
}

/// This type alias is used to encode the result of a function call: `Ok` indicates the call was
/// successful and contains the function's result, while `Err` indicates an exception was thrown
/// and contains said exception.
pub type CallResult<'frame, 'data, V = Value<'frame, 'data>> = Result<V, Value<'frame, 'data>>;

/// Several values that are allocated consecutively. This can be used in combination with
/// [`Value::call_values`] and [`WithOutput::call_values`].
///
/// [`Value::call_values`]: struct.Value.html#method.call_values
/// [`WithOutput::call_values`]: struct.WithOutput.html#method.call_values
#[derive(Copy, Clone, Debug)]
pub struct Values<'frame>(*mut *mut jl_value_t, usize, PhantomData<&'frame ()>);

impl<'frame> Values<'frame> {
    pub(crate) unsafe fn wrap(ptr: *mut *mut jl_value_t, n: usize) -> Self {
        Values(ptr, n, PhantomData)
    }

    #[doc(hidden)]
    pub unsafe fn ptr(self) -> *mut *mut jl_value_t {
        self.0
    }

    /// Returns the number of `Value`s in this group.
    pub fn len(self) -> usize {
        self.1
    }

    /// Get a specific `Value` in this group. Returns an error if the index is out of bounds.
    pub fn value(self, index: usize) -> JlrsResult<Value<'frame, 'static>> {
        if index >= self.len() {
            return Err(JlrsError::OutOfBounds(index, self.len()).into());
        }

        unsafe { Ok(Value(*(self.ptr().add(index)), PhantomData, PhantomData)) }
    }

    /// Allocate several values of the same type, this type must implement [`IntoJulia`]. The
    /// values will be protected from garbage collection inside the frame used to create them.
    /// This takes as many slots on the GC stack as values that are allocated.
    ///
    /// Returns an error if there is not enough space on the stack.
    ///
    /// [`IntoJulia`]: ../traits/trait.IntoJulia.html
    pub fn new<T, V, F>(frame: &mut F, data: V) -> JlrsResult<Self>
    where
        T: IntoJulia,
        V: AsRef<[T]>,
        F: Frame<'frame>,
    {
        frame
            .create_many(data.as_ref(), Internal)
            .map_err(Into::into)
    }

    /// Allocate several values of possibly different types, these types must implement
    /// [`IntoJulia`]. The values will be protected from garbage collection inside the frame used
    /// to create them. This takes as many slots on the GC stack as values that are allocated.
    ///
    /// Returns an error if there is not enough space on the stack.
    ///
    /// [`IntoJulia`]: ../traits/trait.IntoJulia.html
    pub fn new_dyn<'v, V, F>(frame: &mut F, data: V) -> JlrsResult<Self>
    where
        V: AsRef<[&'v dyn IntoJulia]>,
        F: Frame<'frame>,
    {
        frame
            .create_many_dyn(data.as_ref(), Internal)
            .map_err(Into::into)
    }
}

/// When working with the Julia C API most data is returned as a raw pointer to a `jl_value_t`.
/// This pointer is similar to a void pointer in the sense that this pointer can point to data of
/// any type. It's up to the user to determine the correct type and cast the pointer. In order to
/// make this possible, data pointed to by a `jl_value_t`-pointer is guaranteed to be preceded in
/// memory by a fixed-size header that contains its type and layout-information.
///
/// A `Value` is a wrapper around the raw pointer to a `jl_value_t` that adds two lifetimes,
/// `'frame` and `'data`. The first is inherited from the frame used to create the `Value`; frames
/// ensure a `Value` is protected from garbage collection as long as the frame used to protect it
/// has not been dropped. As a result, a `Value` can only be used when it can be guaranteed that
/// the garbage collector won't drop it. The second indicates the lifetime of its contents; it's
/// usually `'static`, but if you create a `Value` that borrows array data from Rust it's the
/// lifetime of the borrow. If you call a Julia function the returned `Value` will inherit the
/// `'data`-lifetime of the `Value`s used as arguments. This ensures that a `Value` that
/// (possibly) borrows data from Rust can't be used after that borrow ends. If this restriction is
/// too strict you can forget the second lifetime by calling [`Value::assume_owned`].
///
/// ### Creating new values
///
/// New `Value`s can be created from Rust in several ways. Types that implement [`IntoJulia`] can
/// be converted to a `Value` by calling [`Value::new`]. This trait is implemented by primitive
/// types like `bool`, `char`, `i16`, and `usize`; string types like `String`, `&str`, and `Cow`;
/// [`tuples`]; and you can derive it for your own types by deriving [`IntoJulia`]. You should
/// use `JlrsReflect.jl` rather than doing this manually.
///
/// [`Value`] also has several methods to create an n-dimensional array if the element type
/// implements [`IntoJulia`], this includes primitive types, strings. It is also implemented for
/// bits types with no type parameters when these bindings are generated with `JlrsReflect.jl`. A
/// new array whose data is completely managed by Julia can be created by calling
/// [`Value::new_array`]. You can also transfer the ownership of some `Vec` to Julia and treat it
/// as an n-dimensional array with [`Value::move_array`]. Finally, you can borrow anything that
/// can be borrowed as a mutable slice with [`Value::borrow_array`].
///
/// Functions and other global values defined in a module can be accessed through that module.
/// Please see the documentation for [`Module`] for more information.
///
/// ### Casting values
///
/// A `Value`'s type information can be accessed by calling [`Value::datatype`], this is usually
/// not necessary to determine what kind of data it contains; you can use [`Value::is`] to query
/// properties of the value's type. You can use [`Value::cast`] to convert the value to the
/// appropriate type. If a type implements both [`JuliaTypecheck`] and [`Cast`], which are used by
/// [`Value::is`] and [`Value::cast`] respectively, the former returning `true` when called with
/// that type as generic parameter indicates that the latter will succeed. For example,
/// `value.is::<u8>()` returning true means `value.cast::<u8>()` will succeed. You can derive
/// these traits for custom structs by deriving [`JuliaStruct`].
///
/// The methods that create a new `Value` come in two varieties: `<method>` and `<method>_output`.
/// The first will use a slot in the current frame to protect the value from garbage collection,
/// while the latter uses a slot in another active frame.
///
/// [`Value::assume_owned`]: struct.Value.html#method.assume_owned
/// [`Value`]: struct.Value.html
/// [`Value::move_array`]: struct.Value.html#method.move_array
/// [`Value::new_array`]: struct.Value.html#method.new_array
/// [`Value::borrow_array`]: struct.Value.html#method.borrow_array
/// [`IntoJulia`]: ../traits/trait.IntoJulia.html
/// [`JuliaType`]: ../traits/trait.JuliaType.html
/// [`Value::new`]: struct.Value.html#method.new
/// [`Value::datatype`]: struct.Value.html#method.datatype
/// [`JuliaStruct`]: ../traits/trait.JuliaStruct.html
/// [`tuples`]: ./tuple/index.html
/// [`Module`]: ./module/struct.Module.html
/// [`Value::datatype`]: struct.Value.html#method.datatype
/// [`Value::is`]: struct.Value.html#method.is
/// [`Value::cast`]: struct.Value.html#method.cast
/// [`JuliaTypecheck`]: ../traits/trait.JuliaTypecheck.html
/// [`Cast`]: ../traits/trait.Cast.html
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Value<'frame, 'data>(
    *mut jl_value_t,
    PhantomData<&'frame ()>,
    PhantomData<&'data ()>,
);

impl<'frame, 'data> Value<'frame, 'data> {
    pub(crate) unsafe fn wrap(ptr: *mut jl_value_t) -> Value<'frame, 'static> {
        Value(ptr, PhantomData, PhantomData)
    }

    #[doc(hidden)]
    pub unsafe fn ptr(self) -> *mut jl_value_t {
        self.0
    }
}

/// # Create new `Value`s
impl<'frame, 'data> Value<'frame, 'data> {
    /// Create a new Julia value, any type that implements [`IntoJulia`] can be converted using
    /// this function. The value will be protected from garbage collection inside the frame used
    /// to create it. One free slot on the GC stack is required for this function to succeed,
    /// returns an error if no slot is available.
    ///
    /// [`IntoJulia`]: ../traits/trait.IntoJulia.html
    pub fn new<V, F>(frame: &mut F, value: V) -> JlrsResult<Value<'frame, 'static>>
    where
        V: IntoJulia,
        F: Frame<'frame>,
    {
        unsafe {
            frame
                .protect(value.into_julia(), Internal)
                .map_err(Into::into)
        }
    }

    /// Create a new Julia value using the output to protect it from garbage collection, any type
    /// that implements [`IntoJulia`] can be converted using this function. The value will be
    /// protected from garbage collection until the frame the output belongs to goes out of scope.
    ///
    /// [`IntoJulia`]: ../traits/trait.IntoJulia.html
    pub fn new_output<'output, V, F>(
        frame: &mut F,
        output: Output<'output>,
        value: V,
    ) -> Value<'output, 'static>
    where
        V: IntoJulia,
        F: Frame<'frame>,
    {
        unsafe { frame.assign_output(output, value.into_julia(), Internal) }
    }

    /// Create a new instance of a value with `DataType` `ty`, using `values` to set the fields.
    /// This is essentially a more powerful version of [`Value::new`] and can instantiate
    /// arbitrary concrete `DataType`s, at the cost that each of its fields must have already been
    /// allocated as a `Value`. This functions returns an error if the given `DataType` is not
    /// concrete. One free slot on the GC stack is required for this function to succeed, returns
    /// an error if no slot is available.
    pub fn instantiate<'value, 'borrow, F, V>(
        frame: &mut F,
        ty: DataType,
        values: V,
    ) -> JlrsResult<Value<'frame, 'borrow>>
    where
        F: Frame<'frame>,
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        ty.instantiate(frame, values)
    }

    /// Create a new instance of a value with `DataType` `ty`, using `values` to set the fields.
    /// This is essentially a more powerful version of [`Value::new`] and can instantiate
    /// arbitrary concrete `DataType`s, at the cost that each of its fields must have already been
    /// allocated as a `Value`. This functions returns an error if the given `DataType` is not
    /// concrete. One free slot on the GC stack is required for this function to succeed, returns
    /// an error if no slot is available.
    pub fn instantiate_output<'output, 'value, 'borrow, F, V>(
        frame: &mut F,
        output: Output<'output>,
        ty: DataType,
        mut values: V,
    ) -> JlrsResult<Value<'output, 'borrow>>
    where
        F: Frame<'frame>,
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        unsafe {
            if !ty.is::<Concrete>() {
                Err(JlrsError::NotConcrete(ty.name().into()))?;
            }

            let values = values.as_mut();
            let value = jl_new_structv(ty.ptr(), values.as_mut_ptr().cast(), values.len() as _);
            Ok(frame.assign_output(output, value, Internal))
        }
    }

    /// Allocates a new n-dimensional array in Julia.
    ///
    /// Creating an an array with 1, 2 or 3 dimensions requires one slot on the GC stack. If you
    /// create an array with more dimensions an extra frame is created with a single slot,
    /// temporarily taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn new_array<T, D, F>(frame: &mut F, dimensions: D) -> JlrsResult<Value<'frame, 'static>>
    where
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        F: Frame<'frame>,
    {
        unsafe {
            let array = new_array::<T, _, _>(frame, dimensions)?;
            frame.protect(array, Internal).map_err(Into::into)
        }
    }

    /// Allocates a new n-dimensional array in Julia using an `Output`.
    ///
    /// Because an `Output` is used, no additional slot in the current frame is used if you create
    /// an array with 1, 2 or 3 dimensions. If you create an array with more dimensions an extra
    // frame is created with a single slot, temporarily taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn new_array_output<'output, T, D, F>(
        frame: &mut F,
        output: Output<'output>,
        dimensions: D,
    ) -> JlrsResult<Value<'output, 'static>>
    where
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        F: Frame<'frame>,
    {
        unsafe {
            let array = new_array::<T, _, _>(frame, dimensions)?;
            Ok(frame.assign_output(output, array, Internal))
        }
    }

    /// Borrows an n-dimensional array from Rust for use in Julia.
    ///
    /// Borrowing an array with one dimension requires one slot on the GC stack. If you borrow an
    /// array with more dimensions, an extra frame is created with a single slot slot, temporarily
    /// taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn borrow_array<T, D, V, F>(
        frame: &mut F,
        data: V,
        dimensions: D,
    ) -> JlrsResult<Value<'frame, 'data>>
    where
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        V: AsMut<[T]> + 'data,
        F: Frame<'frame>,
    {
        unsafe {
            let array = borrow_array(frame, data, dimensions)?;
            frame.protect(array, Internal).map_err(Into::into)
        }
    }

    /// Borrows an n-dimensional array from Rust for use in Julia using an `Output`.
    ///
    /// Because an `Output` is used, no additional slot in the current frame is used for the array
    /// itself. If you borrow an array with more than 1 dimension an extra frame is created with a
    /// single slot, temporarily taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn borrow_array_output<'output, 'borrow, T, D, V, F>(
        frame: &mut F,
        output: Output<'output>,
        data: V,
        dimensions: D,
    ) -> JlrsResult<Value<'output, 'borrow>>
    where
        'borrow: 'output,
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        V: AsMut<[T]> + 'borrow,
        F: Frame<'frame>,
    {
        unsafe {
            let array = borrow_array(frame, data, dimensions)?;
            Ok(frame.assign_output(output, array, Internal))
        }
    }

    /// Moves an n-dimensional array from Rust to Julia.
    ///
    /// Moving an array with one dimension requires one slot on the GC stack. If you move an array
    /// with more dimensions, an extra frame is created with a single slot slot, temporarily
    /// taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn move_array<T, D, F>(
        frame: &mut F,
        data: Vec<T>,
        dimensions: D,
    ) -> JlrsResult<Value<'frame, 'static>>
    where
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        F: Frame<'frame>,
    {
        unsafe {
            let array = move_array(frame, data, dimensions)?;
            frame
                .protect(array, Internal)
                .map(|v| {
                    let g = frame.global();
                    v.add_finalizer(
                        Module::main(g)
                            .submodule("Jlrs")
                            .unwrap()
                            .function("clean")
                            .unwrap(),
                    );
                    v
                })
                .map_err(Into::into)
        }
    }

    /// Moves an n-dimensional array from Rust to Julia using an output.
    ///
    /// Because an `Output` is used, no additional slot in the current frame is used for the array
    /// itself. If you move an array with more dimensions, an extra frame is created with a single
    /// slot slot, temporarily taking 3 additional slots.
    ///
    /// This function returns an error if there are not enough slots available.
    pub fn move_array_output<'output, T, D, F>(
        frame: &mut F,
        output: Output<'output>,
        data: Vec<T>,
        dimensions: D,
    ) -> JlrsResult<Value<'output, 'static>>
    where
        T: IntoJulia + JuliaType,
        D: Into<Dimensions>,
        F: Frame<'frame>,
    {
        unsafe {
            let array = move_array(frame, data, dimensions)?;
            let v = frame.assign_output(output, array, Internal);
            let g = frame.global();
            v.add_finalizer(
                Module::main(g)
                    .submodule("Jlrs")
                    .unwrap()
                    .function("clean")
                    .unwrap(),
            );
            Ok(v)
        }
    }

    /// Returns the union of all types in `types`. For each of these types, [`Value::is_kind`]
    /// must return `true`. TNote that the result is not necessarily a [`Union`], for example the
    /// union of a single [`DataType`] is that type, not a `Union` with a single variant. One free
    /// slot on the GC stack is required for this function to succeed, returns an error if no slot is available.
    ///
    /// [`Value::is_kind`]: struct.Value.html#method.is_kind
    /// [`Union`]: union/struct.Union.html
    /// [`DataType`]: datatype/struct.DataType.html
    pub fn new_union<F>(frame: &mut F, types: &mut [Value]) -> JlrsResult<Self>
    where
        F: Frame<'frame>,
    {
        unsafe {
            if let Some(v) = types
                .iter()
                .find_map(|v| if v.is_kind() { None } else { Some(v) })
            {
                Err(JlrsError::NotAKind(v.type_name().into()))?;
            }

            let un = jl_type_union(types.as_mut_ptr().cast(), types.len());
            frame.protect(un, Internal).map_err(Into::into)
        }
    }

    /// Create a new `UnionAll`. One free slot on the GC stack is required for this function to
    /// succeed, returns an error if no slot is available.
    pub fn new_unionall<F>(frame: &mut F, tvar: TypeVar, body: Value) -> JlrsResult<Self>
    where
        F: Frame<'frame>,
    {
        if !body.is_type() && !body.is::<TypeVar>() {
            Err(JlrsError::InvalidBody(body.type_name().into()))?;
        }

        unsafe {
            let ua = jl_type_unionall(tvar.ptr(), body.ptr());
            frame.protect(ua, Internal).map_err(Into::into)
        }
    }

    /// Create a new named tuple, you can use the `named_tuple` macro instead of this method.
    pub fn new_named_tuple<'value, 'borrow, F, S, T, V>(
        frame: &mut F,
        mut field_names: S,
        mut values: V,
    ) -> JlrsResult<Value<'frame, 'borrow>>
    where
        F: Frame<'frame>,
        S: AsMut<[T]>,
        T: TemporarySymbol,
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        let output = frame.output()?;
        frame.frame(4, |frame| unsafe {
            let global = frame.global();
            let field_names = field_names.as_mut();
            let values_m = values.as_mut();

            let n_field_names = field_names.len();
            let n_values = values_m.len();

            if n_field_names != n_values {
                Err(JlrsError::NamedTupleSizeMismatch(n_field_names, n_values))?;
            }

            let symbol_ty = DataType::symbol_type(global).as_value();
            let mut symbol_type_vec = vec![symbol_ty; n_field_names];

            let mut field_names_vec = field_names
                .iter()
                .map(|name| name.temporary_symbol(Internal).as_value())
                .collect::<Vec<_>>();

            let names = DataType::anytuple_type(global)
                .as_value()
                .apply_type(frame, &mut symbol_type_vec)?
                .cast::<DataType>()?
                .instantiate(frame, &mut field_names_vec)?;

            let mut field_types_vec = values_m
                .iter()
                .copied()
                .map(|val| {
                    val.datatype()
                        .unwrap_or(DataType::nothing_type(global))
                        .as_value()
                })
                .collect::<Vec<_>>();

            let field_type_tup = DataType::anytuple_type(global)
                .as_value()
                .apply_type(frame, &mut field_types_vec)?;

            UnionAll::namedtuple_type(global)
                .as_value()
                .apply_type(frame, &mut [names, field_type_tup])?
                .cast::<DataType>()?
                .instantiate_output(frame, output, values)
        })
    }

    /// Apply the given types to `self`.
    ///
    /// If `self` is the [`DataType`] `anytuple_type`, calling this function will return a new
    /// tuple type with the given types as its field types. If it is the [`DataType`]
    /// `uniontype_type`, calling this function is equivalent to calling [`Value::new_union`]. If
    /// the value is a `UnionAll`, the given types will be applied and the resulting type is
    /// returned.
    ///
    /// If the types cannot be applied to `self` your program will abort.
    ///
    /// One free slot on the GC stack is required for this function to succeed, returns an error
    /// if no slot is available.
    pub fn apply_type<'fr, 'value, 'borrow, F, V>(
        self,
        frame: &mut F,
        mut types: V,
    ) -> JlrsResult<Value<'fr, 'borrow>>
    where
        F: Frame<'fr>,
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        unsafe {
            let types = types.as_mut();
            let applied = jl_apply_type(self.ptr(), types.as_mut_ptr().cast(), types.len());
            frame.protect(applied, Internal).map_err(Into::into)
        }
    }
}

/// # Properties
impl<'frame, 'data> Value<'frame, 'data> {
    /// Returns the `DataType` of this value, or `None` if the value is a null pointer.
    pub fn datatype(self) -> Option<DataType<'frame>> {
        unsafe {
            if self.is_null() {
                return None;
            }

            Some(DataType::wrap(jl_typeof(self.ptr()).cast()))
        }
    }

    /// Returns the type name of this value.
    pub fn type_name(self) -> &'frame str {
        unsafe {
            if self.ptr().is_null() {
                return "null";
            }
            let type_name = jl_typeof_str(self.ptr());
            let type_name_ref = CStr::from_ptr(type_name);
            type_name_ref.to_str().unwrap()
        }
    }

    /// Returns the object id of this value.
    pub fn object_id(self) -> usize {
        unsafe { jl_object_id(self.ptr()) }
    }

    pub fn isa(self, other: Value) -> bool {
        unsafe { jl_isa(self.ptr(), other.ptr()) != 0 }
    }
}

/// # Type checking
impl<'frame, 'data> Value<'frame, 'data> {
    /// Returns true if the value is `nothing`. Note that the Julia C API often returns a null
    /// pointer instead of `nothing`, this method return false if the given value is a null
    /// pointer.
    pub fn is_nothing(self) -> bool {
        unsafe { !self.is_null() && jl_typeof(self.ptr()) == jl_nothing_type.cast() }
    }

    /// Returns true if the value is a null pointer.
    pub fn is_null(self) -> bool {
        unsafe { self.ptr() == null_mut() }
    }

    /// Performs the given type check. For types that represent Julia data, this check comes down
    /// to checking if the data has that type. This works for primitive types, for example:
    ///
    /// ```no_run
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = unsafe { Julia::init(16).unwrap() };
    /// julia.frame(1, |_global, frame| {
    ///     let i = Value::new(frame, 2u64)?;
    ///     assert!(i.is::<u64>());
    ///     Ok(())
    /// }).unwrap();
    /// # }
    /// ```
    ///
    /// "Special" types in Julia that are defined in C, like [`Array`], [`Module`] and
    /// [`DataType`], are also supported:
    ///
    /// ```no_run
    /// # use jlrs::prelude::*;
    /// # fn main() {
    /// # let mut julia = unsafe { Julia::init(16).unwrap() };
    /// julia.frame(1, |_global, frame| {
    ///     let arr = Value::new_array::<f64, _, _>(frame, (3, 3))?;
    ///     assert!(arr.is::<Array>());
    ///     Ok(())
    /// }).unwrap();
    /// # }
    /// ```
    ///
    /// If you derive [`JuliaStruct`] for some type, that type will be supported by this method. A
    /// full list of supported checks can be found [here].
    ///
    /// [`Array`]: array/struct.Array.html
    /// [`DataType`]: datatype/struct.DataType.html
    /// [`Module`]: module/struct.Module.html
    /// [`Symbol`]: symbol/struct.Symbol.html
    /// [`JuliaStruct`]: ../traits/trait.JuliaStruct.html
    /// [here]: ../traits/trait.JuliaTypecheck.html#implementors
    pub fn is<T: JuliaTypecheck>(self) -> bool {
        if self.is_nothing() {
            return false;
        }

        self.datatype().unwrap().is::<T>()
    }

    /// Returns true if the value is an array with elements of type `T`.
    pub fn is_array_of<T: ValidLayout>(self) -> bool {
        match self.cast::<Array>() {
            Ok(arr) => arr.contains::<T>(),
            Err(_) => false,
        }
    }

    /// Returns true if `self` is a subtype of `sup`.
    pub fn subtype(self, sup: Value) -> bool {
        unsafe { jl_subtype(self.ptr(), sup.ptr()) != 0 }
    }

    /// Returns true if `self` is the type of a `DataType`, `UnionAll`, `Union`, or `Union{}` (the
    /// bottom type).
    pub fn is_kind(self) -> bool {
        unsafe { jl_is_kind(self.ptr()) }
    }

    /// Returns true if the value is a type, ie a `DataType`, `UnionAll`, `Union`, or `Union{}`
    /// (the bottom type).
    pub fn is_type(self) -> bool {
        if let Some(dt) = self.datatype() {
            Value::is_kind(dt.into())
        } else {
            false
        }
    }
}

/// # Lifetime management
impl<'frame, 'data> Value<'frame, 'data> {
    /// If you call a function with one or more borrowed arrays as arguments, its result can only
    /// be used when all the borrows are active. If this result doesn't reference any borrowed
    /// data this function can be used to relax its second lifetime to `'static`.
    ///
    /// Safety: The value must not contain a reference any borrowed data.
    pub unsafe fn assume_owned(self) -> Value<'frame, 'static> {
        Value::wrap(self.ptr())
    }

    /// Extend the `Value`'s lifetime to the `Output's lifetime. The original value will still be
    /// valid after calling this method, the data will be protected from garbage collection until
    /// the `Output`'s frame goes out of scope.
    pub fn extend<'output, F>(self, frame: &mut F, output: Output<'output>) -> Value<'output, 'data>
    where
        F: Frame<'frame>,
    {
        unsafe { frame.assign_output(output, self.ptr().cast(), Internal) }
    }
}

/// # Casting to Rust
impl<'frame, 'data> Value<'frame, 'data> {
    /// Cast the contents of this value into a compatible Rust type. Any type which implements
    /// `Cast` can be used as a target, by default this includes primitive types like `u8`, `f32`
    /// and `bool`, and builtin types like [`Array`], [`JuliaString`] and [`Symbol`]. You can
    /// implement this trait for custom types by deriving [`JuliaStruct`].
    ///
    /// [`Array`]: array/struct.Array.html
    /// [`JuliaString`]: string/struct.JuliaString.html
    /// [`Symbol`]: symbol/struct.Symbol.html
    /// [`JuliaStruct`]: ../traits/trait.JuliaStruct.html
    pub fn cast<T: Cast<'frame, 'data>>(self) -> JlrsResult<<T as Cast<'frame, 'data>>::Output> {
        T::cast(self)
    }

    /// Cast the contents of this value into a compatible Rust type without checking if the layout is valid.
    ///
    /// Safety:
    ///
    /// You must guarantee `self.is::<T>()` would have returned `true`.
    pub unsafe fn cast_unchecked<T: Cast<'frame, 'data>>(
        self,
    ) -> <T as Cast<'frame, 'data>>::Output {
        T::cast_unchecked(self)
    }
}

/// # Fields
impl<'frame, 'data> Value<'frame, 'data> {
    /// Returns the field names of this value as a slice of `Symbol`s. These symbols can be used
    /// to access their fields with [`Value::get_field`].
    ///
    /// [`Value::get_field`]: struct.Value.html#method.get_field
    pub fn field_names(self) -> &'frame [Symbol<'frame>] {
        if self.is_nothing() {
            return &[];
        }

        unsafe {
            let tp = jl_typeof(self.ptr());
            let field_names = jl_field_names(tp.cast());
            let len = jl_svec_len(field_names);
            let items: *mut Symbol = jl_svec_data(field_names).cast();
            slice::from_raw_parts(items.cast(), len)
        }
    }

    /// Returns the number of fields the underlying Julia value has. These fields can be accessed
    /// with [`Value::get_field_n`].
    ///
    /// [`Value::get_field_n`]: struct.Value.html#method.get_field_n
    pub fn n_fields(self) -> usize {
        if self.is_nothing() {
            return 0;
        }

        unsafe { jl_nfields(self.ptr()) as _ }
    }

    /// Returns the field at index `idx` if it exists. If it does not exist
    /// `JlrsError::OutOfBounds` is returned. This function assumes the field must be protected
    /// from garbage collection, so calling this function will take a single slot on the GC stack.
    /// If there is no slot available `JlrsError::AllocError` is returned.
    pub fn get_nth_field<'fr, F>(self, frame: &mut F, idx: usize) -> JlrsResult<Value<'fr, 'data>>
    where
        F: Frame<'fr>,
    {
        unsafe {
            if idx >= self.n_fields() {
                return Err(JlrsError::OutOfBounds(idx, self.n_fields()).into());
            }

            frame
                .protect(jl_fieldref(self.ptr(), idx), Internal)
                .map_err(Into::into)
        }
    }

    /// Returns the field at index `idx` if it exists. If it does not exist
    /// `JlrsError::OutOfBounds` is returned. This function assumes the field must be protected
    /// from garbage collection and uses the provided output to do so.
    pub fn get_nth_field_output<'output, 'fr, F>(
        self,
        frame: &mut F,
        output: Output<'output>,
        idx: usize,
    ) -> JlrsResult<Value<'output, 'data>>
    where
        F: Frame<'fr>,
    {
        unsafe {
            if idx >= self.n_fields() {
                return Err(JlrsError::OutOfBounds(idx, self.n_fields()).into());
            }

            Ok(frame.assign_output(output, jl_fieldref(self.ptr(), idx), Internal))
        }
    }

    /// Returns the field at index `idx` if it exists and no allocation is required to return it.
    /// Allocation is not required if the field is a pointer to another value.
    ///
    /// If the field does not exist `JlrsError::NoSuchField` is returned. If allocating is
    /// required to return the field, `JlrsError::NotAPointerField` is returned.
    ///
    /// This function is unsafe because the value returned as a result will only be valid as long
    /// as the field is not changed.
    pub unsafe fn get_nth_field_noalloc(self, idx: usize) -> JlrsResult<Value<'frame, 'data>> {
        if self.is_nothing() {
            Err(JlrsError::Nothing)?;
        }

        if idx >= self.n_fields() {
            Err(JlrsError::OutOfBounds(idx, self.n_fields()))?
        }

        if !jl_field_isptr(self.datatype().unwrap().ptr(), idx as _) {
            Err(JlrsError::NotAPointerField(idx))?;
        }

        Ok(Value::wrap(jl_fieldref_noalloc(self.ptr(), idx)))
    }

    /// Returns the field with the name `field_name` if it exists. If it does not exist
    /// `JlrsError::NoSuchField` is returned. This function assumes the field must be protected
    /// from garbage collection, so calling this function will take a single slot on the GC stack.
    /// If there is no slot available `JlrsError::AllocError` is returned.
    pub fn get_field<'fr, N, F>(self, frame: &mut F, field_name: N) -> JlrsResult<Value<'fr, 'data>>
    where
        N: TemporarySymbol,
        F: Frame<'fr>,
    {
        unsafe {
            let symbol = field_name.temporary_symbol(Internal);

            if self.is_nothing() {
                Err(JlrsError::Nothing)?;
            }

            let jl_type = jl_typeof(self.ptr()).cast();
            let idx = jl_field_index(jl_type, symbol.ptr(), 0);

            if idx < 0 {
                return Err(JlrsError::NoSuchField(symbol.into()).into());
            }

            frame
                .protect(jl_get_nth_field(self.ptr(), idx as _), Internal)
                .map_err(Into::into)
        }
    }

    /// Returns the field with the name `field_name` if it exists. If it does not exist
    /// `JlrsError::NoSuchField` is returned. This function assumes the field must be protected
    /// from garbage collection and uses the provided output to do so.
    pub fn get_field_output<'output, 'fr, N, F>(
        self,
        frame: &mut F,
        output: Output<'output>,
        field_name: N,
    ) -> JlrsResult<Value<'output, 'data>>
    where
        N: TemporarySymbol,
        F: Frame<'fr>,
    {
        unsafe {
            let symbol = field_name.temporary_symbol(Internal);

            if self.is_nothing() {
                Err(JlrsError::Nothing)?;
            }

            let jl_type = jl_typeof(self.ptr()).cast();
            let idx = jl_field_index(jl_type, symbol.ptr(), 0);

            if idx < 0 {
                return Err(JlrsError::NoSuchField(symbol.into()).into());
            }

            Ok(frame.assign_output(output, jl_get_nth_field(self.ptr(), idx as _), Internal))
        }
    }

    /// Returns the field with the name `field_name` if it exists and no allocation is required
    /// to return it. Allocation is not required if the field is a pointer to another value.
    ///
    /// If the field does not exist `JlrsError::NoSuchField` is returned. If allocating is
    /// required to return the field, `JlrsError::NotAPointerField` is returned.
    ///
    /// This function is unsafe because the value returned as a result will only be valid as long
    /// as the field is not changed.
    pub unsafe fn get_field_noalloc<N>(self, field_name: N) -> JlrsResult<Value<'frame, 'data>>
    where
        N: TemporarySymbol,
    {
        let symbol = field_name.temporary_symbol(Internal);

        if self.is_nothing() {
            Err(JlrsError::Nothing)?;
        }

        let jl_type = jl_typeof(self.ptr()).cast();
        let idx = jl_field_index(jl_type, symbol.ptr(), 0);

        if idx < 0 {
            return Err(JlrsError::NoSuchField(symbol.into()).into());
        }

        if !jl_field_isptr(self.datatype().unwrap().ptr(), idx) {
            Err(JlrsError::NotAPointerField(idx as _))?;
        }

        Ok(Value::wrap(jl_get_nth_field_noalloc(self.ptr(), idx as _)))
    }

    /// Set the value of the field at `idx`. Returns an error if this value is immutable or if the
    /// type of `value` is not a subtype of the field type. This is unsafe because the previous
    /// value of this field can become unrooted if you're directly using it from Rust.
    pub unsafe fn set_nth_field(self, idx: usize, value: Value) -> JlrsResult<()> {
        if !self.is::<datatype::Mutable>() {
            Err(JlrsError::Immutable)?
        }

        let field_type = self.datatype().unwrap().field_types()[idx];
        if let Some(dt) = value.datatype() {
            if Value::subtype(dt.into(), field_type) {
                jl_set_nth_field(self.ptr(), idx, value.ptr());
                jl_gc_wb(self.ptr(), value.ptr());
                return Ok(());
            } else {
                Err(JlrsError::NotSubtype)?
            }
        }

        Err(JlrsError::Nothing)?
    }
}

/// # Call Julia.
///
/// Several methods are available to call Julia. Raw commands can be executed with `eval_string`
/// and `eval_cstring`, but these can't take any arguments. In order to call functions that take
/// arguments, you must use one of the `call` methods which will call that value as a function
/// with any number of arguments. One of these, `call_keywords`, lets you call functions with
/// keyword arguments.
impl<'fr, 'data> Value<'fr, 'data> {
    /// Wraps a `Value` so that a function call will not require a slot in the current frame but
    /// uses the one that was allocated for the output.
    pub fn with_output<'output>(self, output: Output<'output>) -> WithOutput<'output, Self> {
        WithOutput {
            value: self,
            output,
        }
    }

    /// Provide keywords to this function.
    ///
    /// Functions that can take keyword arguments can be called in two major ways, either with or
    /// without keyword arguments. The normal call-methods take care of the frst case, this one
    /// takes care of the second.
    ///
    /// Example:
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # use jlrs::util::JULIA;
    /// # fn main() {
    /// # JULIA.with(|j| {
    /// # let mut julia = j.borrow_mut();
    ///   julia.frame(4, |global, frame| {
    ///       let a_value = Value::new(frame, 1isize)?;
    ///       let b_value = Value::new(frame, 10isize)?;
    ///       // `funcwithkw` takes a single positional argument of type `Int`, one keyword
    ///       // argument named `b` of the same type, and returns `a` + `b`.
    ///       let func = Module::main(global)
    ///           .submodule("JlrsTests")?
    ///           .function("funcwithkw")?;
    ///
    ///       let kw = named_tuple!(frame, "b" => b_value)?;
    ///       let res = func.with_keywords(kw)
    ///           .call1(frame, a_value)?
    ///           .unwrap()
    ///           .cast::<isize>()?;
    ///  
    ///       assert_eq!(res, 11);
    ///       Ok(())
    ///   }).unwrap();
    /// # });
    /// # }
    /// ```
    pub fn with_keywords<'kws, 'borrow>(
        self,
        keywords: Value<'kws, 'borrow>,
    ) -> WithKeywords<'fr, 'data, 'kws, 'borrow> {
        WithKeywords {
            func: self,
            kws: keywords,
        }
    }

    /// Execute a Julia command `cmd`, for example
    ///
    /// `Value::eval_string(frame, "sqrt(2)")`.
    pub fn eval_string<'frame, F, S>(
        frame: &mut F,
        cmd: S,
    ) -> JlrsResult<CallResult<'frame, 'static>>
    where
        F: Frame<'frame>,
        S: AsRef<str>,
    {
        unsafe {
            let cmd = cmd.as_ref();
            let cmd_cstring = CString::new(cmd).map_err(JlrsError::other)?;
            let cmd_ptr = cmd_cstring.as_ptr();
            let res = jl_eval_string(cmd_ptr);
            try_protect(frame, res)
        }
    }

    /// Execute a Julia command `cmd`. This is equivalent to `Value::eval_string`, but uses a
    /// null-terminated string.
    pub fn eval_cstring<'frame, F, S>(
        frame: &mut F,
        cmd: S,
    ) -> JlrsResult<CallResult<'frame, 'static>>
    where
        F: Frame<'frame>,
        S: AsRef<CStr>,
    {
        unsafe {
            let cmd = cmd.as_ref();
            let cmd_ptr = cmd.as_ptr();
            let res = jl_eval_string(cmd_ptr);
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes zero arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call0<'frame, F>(self, frame: &mut F) -> JlrsResult<CallResult<'frame, 'static>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let res = jl_call0(self.ptr());
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes zero arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call0_unprotected<'base>(self, _: Global<'base>) -> CallResult<'base, 'static> {
        let res = jl_call0(self.ptr());
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes one argument, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call1<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let res = jl_call1(self.ptr().cast(), arg.ptr());
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes one argument and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call1_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let res = jl_call1(self.ptr().cast(), arg.ptr());
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes two arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call2<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let res = jl_call2(self.ptr().cast(), arg0.ptr(), arg1.ptr());
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes two arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call2_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let res = jl_call2(self.ptr().cast(), arg0.ptr(), arg1.ptr());
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes three arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call3<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
        arg2: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let res = jl_call3(self.ptr().cast(), arg0.ptr(), arg1.ptr(), arg2.ptr());
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes three arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call3_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
        arg2: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let res = jl_call3(self.ptr().cast(), arg0.ptr(), arg1.ptr(), arg2.ptr());
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes several arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call<'frame, 'value, 'borrow, V, F>(
        self,
        frame: &mut F,
        mut args: V,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
        F: Frame<'frame>,
    {
        unsafe {
            let args = args.as_mut();
            let n = args.len();
            let res = jl_call(self.ptr().cast(), args.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes several arguments and don't protect the result
    /// from garbage collection. This is safe if you won't use the result or if you can guarantee
    /// it's a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call_unprotected<'base, 'value, 'borrow, V, F>(
        self,
        _: Global<'base>,
        mut args: V,
    ) -> CallResult<'base, 'borrow>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        let args = args.as_mut();
        let n = args.len();
        let res = jl_call(self.ptr().cast(), args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes keyword arguments, any number of positional
    /// arguments and don't protect the result from garbage collection. This is safe if you won't
    /// use the result or if you can guarantee it's a global value in Julia, e.g. `nothing` or a
    /// [`Module`].
    pub unsafe fn call_keywords_unprotected<'base, 'value, 'borrow, V, F>(
        self,
        _: Global<'base>,
        mut args: V,
    ) -> CallResult<'base, 'borrow>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        let func = jl_get_kwsorter(self.datatype().expect("").ptr().cast());
        let args = args.as_mut();
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this value as a function that takes several arguments and execute it on another
    /// thread in Julia created with `Base.@spawn`, this takes two slots on the GC stack. Returns
    /// the result of this function call if no exception is thrown, the exception if one is, or an
    /// error if no space is left on the stack.
    ///
    /// This function can only be called with an `AsyncFrame`, while you're waiting for this
    /// function to complete, other tasks are able to progress.
    #[cfg(all(feature = "async", target_os = "linux"))]
    pub async fn call_async<'frame, 'value, 'borrow, V>(
        self,
        frame: &mut crate::frame::AsyncFrame<'frame>,
        args: V,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        unsafe { Ok(crate::julia_future::JuliaFuture::new(frame, self, args)?.await) }
    }

    /// Call this value as a function that takes several arguments in a single `Values`, this
    /// takes one slot on the GC stack. Returns the result of this function call if no exception
    /// is thrown, the exception if one is, or an error if no space is left on the stack.
    pub fn call_values<'frame, F>(
        self,
        frame: &mut F,
        args: Values,
    ) -> JlrsResult<CallResult<'frame, 'static>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let res = jl_call(self.ptr().cast(), args.ptr(), args.len() as _);
            try_protect(frame, res)
        }
    }

    /// Call this value as a function that takes several arguments in a single `Values` and don't
    /// protect the result from garbage collection. This is safe if you won't use the result or if
    /// you can guarantee it's a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call_values_unprotected<'base>(
        self,
        _: Global<'base>,
        args: Values,
    ) -> CallResult<'base, 'static> {
        let res = jl_call(self.ptr().cast(), args.ptr(), args.len() as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Returns an anonymous function that wraps this value in a try-catch block. Calling this
    /// anonymous function with some arguments will call the value as a function with those
    /// arguments and return its result, or catch the exception, print the stackstrace, and
    /// rethrow that exception. This takes one slot on the GC stack.
    pub fn tracing_call<'frame, F>(self, frame: &mut F) -> JlrsResult<CallResult<'frame, 'data>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let global = frame.global();
            let func = Module::main(global)
                .submodule("Jlrs")?
                .function("tracingcall")?;
            let res = jl_call1(func.ptr(), self.ptr());
            try_protect(frame, res)
        }
    }

    /// Returns an anonymous function that wraps this value in a try-catch block. Calling this
    /// anonymous function with some arguments will call the value as a function with those
    /// arguments and return its result, or catch the exception and throw a new one with two
    /// fields, `exc` and `stacktrace`, containing the original exception and the stacktrace
    /// respectively. This takes one slot on the GC stack.
    pub fn attach_stacktrace<'frame, F>(
        self,
        frame: &mut F,
    ) -> JlrsResult<CallResult<'frame, 'data>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let global = frame.global();
            let func = Module::main(global)
                .submodule("Jlrs")?
                .function("attachstacktrace")?;
            let res = jl_call1(func.ptr(), self.ptr());
            try_protect(frame, res)
        }
    }
}

/// # Equality
impl Value<'_, '_> {
    /// Returns true if `self` and `other` are equal.
    pub fn egal(self, other: Value) -> bool {
        unsafe { jl_egal(self.ptr(), other.ptr()) != 0 }
    }
}

/// # Finalization
impl Value<'_, '_> {
    /// Add a finalizer `f` to this value. The finalizer must be a Julia function, it will be
    /// called when this value is about to be freed by the garbage collector.
    pub unsafe fn add_finalizer(self, f: Value) {
        jl_gc_add_finalizer(self.ptr(), f.ptr())
    }

    /// Call all finalizers.
    pub unsafe fn finalize(self) {
        jl_finalize(self.ptr())
    }
}

/// Constant values.
impl<'base> Value<'base, 'static> {
    /// `Core.Union{}`.
    pub fn bottom_type(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_bottom_type) }
    }

    /// `Core.StackOverflowError`.
    pub fn stackovf_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_stackovf_exception) }
    }

    /// `Core.OutOfMemoryError`.
    pub fn memory_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_memory_exception) }
    }

    /// `Core.ReadOnlyMemoryError`.
    pub fn readonlymemory_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_readonlymemory_exception) }
    }

    /// `Core.DivideError`.
    pub fn diverror_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_diverror_exception) }
    }

    /// `Core.UndefRefError`.
    pub fn undefref_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_undefref_exception) }
    }

    /// `Core.InterruptException`.
    pub fn interrupt_exception(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_interrupt_exception) }
    }

    /// An empty `Core.Array{Any, 1}.
    ///
    /// Safety: never mutate this vec.
    pub unsafe fn an_empty_vec_any(_: Global<'base>) -> Self {
        Value::wrap(jl_an_empty_vec_any)
    }

    /// An empty immutable String, "".
    pub fn an_empty_string(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_an_empty_string) }
    }

    /// `Core.Array{UInt8, 1}`
    pub fn array_uint8_type(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_array_uint8_type) }
    }

    /// `Core.Array{Any, 1}`
    pub fn array_any_type(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_array_any_type) }
    }

    /// `Core.Array{Symbol, 1}`
    pub fn array_symbol_type(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_array_symbol_type) }
    }

    /// `Core.Array{Int32, 1}`
    pub fn array_int32_type(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_array_int32_type) }
    }

    /// The empty tuple, `()`.
    pub fn emptytuple(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_emptytuple) }
    }

    /// The instance of `true`.
    pub fn true_v(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_true) }
    }

    /// The instance of `false`.
    pub fn false_v(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_false) }
    }

    /// The instance of `Core.Nothing`, `nothing`.
    pub fn nothing(_: Global<'base>) -> Self {
        unsafe { Value::wrap(jl_nothing) }
    }
}

impl<'frame, 'data> Debug for Value<'frame, 'data> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.debug_tuple("Value").field(&self.type_name()).finish()
    }
}

impl_julia_type!(Value<'frame, 'data>, jl_any_type, 'frame, 'data);

unsafe impl<'frame, 'data> ValidLayout for Value<'frame, 'data> {
    unsafe fn valid_layout(v: Value) -> bool {
        if let Ok(dt) = v.cast::<DataType>() {
            !dt.isinlinealloc()
        } else if v.cast::<union_all::UnionAll>().is_ok() {
            true
        } else if let Ok(u) = v.cast::<union::Union>() {
            !u.isbitsunion()
        } else {
            false
        }
    }
}

/// A function with keyword arguments
pub struct WithKeywords<'func, 'funcdata, 'kw, 'data> {
    func: Value<'func, 'funcdata>,
    kws: Value<'kw, 'data>,
}

impl<'func, 'funcdata, 'kw, 'kwdata> WithKeywords<'func, 'funcdata, 'kw, 'kwdata> {
    /// Call this function with keywords with no arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call0<'frame, F>(self, frame: &mut F) -> JlrsResult<CallResult<'frame, 'static>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
            let args = &mut [self.kws, self.func];
            let n = args.len();

            let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this function with keywords with no arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call0_unprotected<'base>(self, _: Global<'base>) -> CallResult<'base, 'static> {
        let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
        let args = &mut [self.kws, self.func];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this function with keywords with one argument, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call1<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
            let args = &mut [self.kws, self.func, arg];
            let n = args.len();

            let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this function with keywords with one argument and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call1_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
        let args = &mut [self.kws, self.func, arg];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this function with keywords with two arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call2<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
            let args = &mut [self.kws, self.func, arg0, arg1];
            let n = args.len();

            let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this function with keywords with two arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call2_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
        let args = &mut [self.kws, self.func, arg0, arg1];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this function with keywords with three arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call3<'frame, 'borrow, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
        arg2: Value<'_, 'borrow>,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        F: Frame<'frame>,
    {
        unsafe {
            let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
            let args = &mut [self.kws, self.func, arg0, arg1, arg2];
            let n = args.len();

            let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this function with keywords with three arguments and don't protect the result from
    /// garbage collection. This is safe if you won't use the result or if you can guarantee it's
    /// a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call3_unprotected<'base, 'borrow>(
        self,
        _: Global<'base>,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
        arg2: Value<'_, 'borrow>,
    ) -> CallResult<'base, 'borrow> {
        let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
        let args = &mut [self.kws, self.func, arg0, arg1, arg2];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }

    /// Call this function with keywords with several arguments, this takes one slot on the GC
    /// stack. Returns the result of this function call if no exception is thrown, the exception
    /// if one is, or an error if no space is left on the stack.
    pub fn call<'frame, 'value, 'borrow, V, F>(
        self,
        frame: &mut F,
        mut args: V,
    ) -> JlrsResult<CallResult<'frame, 'borrow>>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
        F: Frame<'frame>,
    {
        unsafe {
            let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
            let args = args.as_mut();
            let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(2 + args.len());
            vals.push(self.kws);
            vals.push(self.func);

            for arg in args.iter().copied() {
                vals.push(arg);
            }

            let n = vals.len();
            let res = jl_call(func, vals.as_mut_ptr().cast(), n as _);
            try_protect(frame, res)
        }
    }

    /// Call this function with keywords with several arguments and don't protect the result
    /// from garbage collection. This is safe if you won't use the result or if you can guarantee
    /// it's a global value in Julia, e.g. `nothing` or a [`Module`].
    pub unsafe fn call_unprotected<'base, 'value, 'borrow, V, F>(
        self,
        _: Global<'base>,
        mut args: V,
    ) -> CallResult<'base, 'borrow>
    where
        V: AsMut<[Value<'value, 'borrow>]>,
    {
        let func = jl_get_kwsorter(self.func.datatype().expect("").ptr().cast());
        let args = args.as_mut();
        let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(2 + args.len());
        vals.push(self.kws);
        vals.push(self.func);

        for arg in args.iter().copied() {
            vals.push(arg);
        }

        let n = vals.len();
        let res = jl_call(func, vals.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(Value::wrap(res))
        } else {
            Err(Value::wrap(exc))
        }
    }
}

/// A wrapper that will let you call a `Value` as a function and store the result using an
/// `Output`. The function call will not require a slot in the current frame but uses the one
/// that was allocated for the output. You can create this by calling [`Value::with_output`].
///
/// Because the result of a function call is stored in an already allocated slot, calling a
/// function usually returns the `CallResult` directly rather than wrapping it in a `JlrsResult`.
///
/// [`Value::with_output`]: Value.html#method.with_output
pub struct WithOutput<'output, V> {
    value: V,
    output: Output<'output>,
}

impl<'output, 'frame, 'data> WithOutput<'output, Value<'frame, 'data>> {
    /// Call the value as a function that takes zero arguments and use the `Output` to extend the
    /// result's lifetime. This takes no space on the GC stack. Returns the result of this
    /// function call if no exception is thrown or the exception if one is.
    pub fn call0<'fr, F>(self, frame: &mut F) -> CallResult<'output, 'static>
    where
        F: Frame<'fr>,
    {
        unsafe {
            let res = jl_call0(self.value.ptr());
            assign(frame, self.output, res)
        }
    }

    /// Call the value as a function that takes one argument and use the `Output` to extend the
    /// result's lifetime. This takes no space on the GC stack. Returns the result of this
    /// function call if no exception is thrown or the exception if one is.
    pub fn call1<'borrow, 'fr, F>(
        self,
        frame: &mut F,
        arg: Value<'_, 'borrow>,
    ) -> CallResult<'output, 'borrow>
    where
        'borrow: 'output,
        F: Frame<'fr>,
    {
        unsafe {
            let res = jl_call1(self.value.ptr().cast(), arg.ptr());
            assign(frame, self.output, res)
        }
    }

    /// Call the value as a function that takes two arguments and use the `Output` to extend the
    /// result's lifetime. This takes no space on the GC stack. Returns the result of this
    /// function call if no exception is thrown or the exception if one is.
    pub fn call2<'borrow, 'fr, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
    ) -> CallResult<'output, 'borrow>
    where
        'borrow: 'output,
        F: Frame<'fr>,
    {
        unsafe {
            let res = jl_call2(self.value.ptr().cast(), arg0.ptr(), arg1.ptr());
            assign(frame, self.output, res)
        }
    }

    /// Call the value as a function that takes three arguments and use the `Output` to extend
    /// the result's lifetime. This takes no space on the GC stack. Returns the result of this
    /// function call if no exception is thrown or the exception if one is.
    pub fn call3<'borrow, 'fr, F>(
        self,
        frame: &mut F,
        arg0: Value<'_, 'borrow>,
        arg1: Value<'_, 'borrow>,
        arg2: Value<'_, 'borrow>,
    ) -> CallResult<'output, 'borrow>
    where
        'borrow: 'output,
        F: Frame<'fr>,
    {
        unsafe {
            let res = jl_call3(self.value.ptr().cast(), arg0.ptr(), arg1.ptr(), arg2.ptr());
            assign(frame, self.output, res)
        }
    }

    /// Call the value as a function that takes several arguments and use the `Output` to extend
    /// the result's lifetime. This takes no space on the GC stack. Returns the result of this
    /// function call if no exception is thrown or the exception if one is.
    pub fn call<'value, 'borrow, 'fr, V, F>(
        self,
        frame: &mut F,
        mut args: V,
    ) -> CallResult<'output, 'borrow>
    where
        'borrow: 'output,
        V: AsMut<[Value<'value, 'borrow>]>,
        F: Frame<'fr>,
    {
        unsafe {
            let args = args.as_mut();
            let n = args.len();
            let res = jl_call(self.value.ptr().cast(), args.as_mut_ptr().cast(), n as _);
            assign(frame, self.output, res)
        }
    }

    /// Call the value as a function that takes several arguments in a single `Values` and use
    /// the `Output` to extend the result's lifetime. This takes no space on the GC stack. Returns
    /// the result of this function call if no exception is thrown or the exception if one is.
    pub fn call_values<'fr, F>(self, frame: &mut F, args: Values) -> CallResult<'output, 'static>
    where
        F: Frame<'fr>,
    {
        unsafe {
            let res = jl_call(self.value.ptr().cast(), args.ptr(), args.len() as _);
            assign(frame, self.output, res)
        }
    }

    /// Returns an anonymous function that wraps the value in a try-catch block. Calling this
    /// anonymous function with some arguments will call the value as a function with those
    /// arguments and return its result, or catch the exception, print the stackstrace, and
    /// rethrow that exception. The output is used to protect the result.
    pub fn tracing_call<'fr, F>(self, frame: &mut F) -> JlrsResult<CallResult<'output, 'data>>
    where
        F: Frame<'fr>,
    {
        unsafe {
            let global = frame.global();
            let func = Module::main(global)
                .submodule("Jlrs")?
                .function("tracingcall")?;
            let res = jl_call1(func.ptr(), self.value.ptr());
            Ok(assign(frame, self.output, res))
        }
    }

    /// Returns an anonymous function that wraps the value in a try-catch block. Calling this
    /// anonymous function with some arguments will call the value as a function with those
    /// arguments and return its result, or catch the exception and throw a new one with two
    /// fields, `exc` and `stacktrace`, containing the original exception and the stacktrace
    /// respectively. The output is used to protect the result.
    pub fn attach_stacktrace<'fr, F>(self, frame: &mut F) -> JlrsResult<CallResult<'output, 'data>>
    where
        F: Frame<'fr>,
    {
        unsafe {
            let global = frame.global();
            let func = Module::main(global)
                .submodule("Jlrs")?
                .function("attachstacktrace")?;
            let res = jl_call1(func.ptr(), self.value.ptr());
            Ok(assign(frame, self.output, res))
        }
    }
}

unsafe fn new_array<'frame, T, D, F>(frame: &mut F, dimensions: D) -> JlrsResult<*mut jl_value_t>
where
    T: IntoJulia + JuliaType,
    D: Into<Dimensions>,
    F: Frame<'frame>,
{
    let dims = dimensions.into();
    let array_type = jl_apply_array_type(T::julia_type().cast(), dims.n_dimensions());

    match dims.n_dimensions() {
        1 => Ok(jl_alloc_array_1d(array_type, dims.n_elements(0)).cast()),
        2 => Ok(jl_alloc_array_2d(array_type, dims.n_elements(0), dims.n_elements(1)).cast()),
        3 => Ok(jl_alloc_array_3d(
            array_type,
            dims.n_elements(0),
            dims.n_elements(1),
            dims.n_elements(2),
        )
        .cast()),
        n if n <= 8 => frame.frame(1, |frame| {
            let tuple = small_dim_tuple(frame, &dims)?;
            Ok(jl_new_array(array_type, tuple.ptr()).cast())
        }),
        _ => frame.frame(1, |frame| {
            let tuple = large_dim_tuple(frame, &dims)?;
            Ok(jl_new_array(array_type, tuple.ptr()).cast())
        }),
    }
}

unsafe fn borrow_array<'data, 'frame, T, D, V, F>(
    frame: &mut F,
    mut data: V,
    dimensions: D,
) -> JlrsResult<*mut jl_value_t>
where
    T: IntoJulia + JuliaType,
    D: Into<Dimensions>,
    V: AsMut<[T]> + 'data,
    F: Frame<'frame>,
{
    let dims = dimensions.into();
    let array_type = jl_apply_array_type(T::julia_type().cast(), dims.n_dimensions());

    match dims.n_dimensions() {
        1 => Ok(jl_ptr_to_array_1d(
            array_type,
            data.as_mut().as_mut_ptr().cast(),
            dims.n_elements(0),
            0,
        )
        .cast()),
        n if n <= 8 => frame.frame(1, |frame| {
            let tuple = small_dim_tuple(frame, &dims)?;

            Ok(jl_ptr_to_array(
                array_type,
                data.as_mut().as_mut_ptr().cast(),
                tuple.ptr(),
                0,
            )
            .cast())
        }),
        _ => frame.frame(1, |frame| {
            let tuple = large_dim_tuple(frame, &dims)?;

            Ok(jl_ptr_to_array(
                array_type,
                data.as_mut().as_mut_ptr().cast(),
                tuple.ptr(),
                0,
            )
            .cast())
        }),
    }
}

unsafe fn move_array<'frame, T, D, F>(
    frame: &mut F,
    data: Vec<T>,
    dimensions: D,
) -> JlrsResult<*mut jl_value_t>
where
    T: IntoJulia + JuliaType,
    D: Into<Dimensions>,
    F: Frame<'frame>,
{
    let dims = dimensions.into();
    let array_type = jl_apply_array_type(T::julia_type().cast(), dims.n_dimensions());

    match dims.n_dimensions() {
        1 => Ok(jl_ptr_to_array_1d(
            array_type,
            Box::into_raw(data.into_boxed_slice()).cast(),
            dims.n_elements(0),
            1,
        )
        .cast()),
        n if n <= 8 => frame.frame(1, |frame| {
            let tuple = small_dim_tuple(frame, &dims)?;

            Ok(jl_ptr_to_array(
                array_type,
                Box::into_raw(data.into_boxed_slice()).cast(),
                tuple.ptr(),
                1,
            )
            .cast())
        }),
        _ => frame.frame(1, |frame| {
            let tuple = large_dim_tuple(frame, &dims)?;

            Ok(jl_ptr_to_array(
                array_type,
                Box::into_raw(data.into_boxed_slice()).cast(),
                tuple.ptr(),
                1,
            )
            .cast())
        }),
    }
}

unsafe fn try_protect<'frame, F>(
    frame: &mut F,
    res: *mut jl_value_t,
) -> JlrsResult<CallResult<'frame, 'static>>
where
    F: Frame<'frame>,
{
    let exc = jl_exception_occurred();

    if !exc.is_null() {
        match frame.protect(exc, Internal) {
            Ok(exc) => Ok(Err(exc)),
            Err(a) => Err(a.into()),
        }
    } else {
        match frame.protect(res, Internal) {
            Ok(v) => Ok(Ok(v)),
            Err(a) => Err(a.into()),
        }
    }
}

unsafe fn assign<'output, 'frame, F>(
    frame: &mut F,
    output: Output<'output>,
    res: *mut jl_value_t,
) -> CallResult<'output, 'static>
where
    F: Frame<'frame>,
{
    let exc = jl_exception_occurred();

    if !exc.is_null() {
        Err(frame.assign_output(output, exc, Internal))
    } else {
        Ok(frame.assign_output(output, res, Internal))
    }
}

unsafe fn small_dim_tuple<'frame, F>(
    frame: &mut F,
    dims: &Dimensions,
) -> JlrsResult<Value<'frame, 'static>>
where
    F: Frame<'frame>,
{
    let n = dims.n_dimensions();
    assert!(n <= 8);
    let elem_types = JL_LONG_TYPE.with(|longs| longs.get());
    let tuple_type = jl_apply_tuple_type_v(elem_types.cast(), n);
    let tuple = jl_new_struct_uninit(tuple_type);
    let v = try_protect(frame, tuple)?.unwrap();

    let usize_ptr: *mut usize = v.ptr().cast();
    std::ptr::copy_nonoverlapping(dims.as_slice().as_ptr(), usize_ptr, n);

    Ok(v)
}

unsafe fn large_dim_tuple<'frame, F>(
    frame: &mut F,
    dims: &Dimensions,
) -> JlrsResult<Value<'frame, 'static>>
where
    F: Frame<'frame>,
{
    let n = dims.n_dimensions();
    let mut elem_types = vec![usize::julia_type(); n];
    let tuple_type = jl_apply_tuple_type_v(elem_types.as_mut_ptr().cast(), n);
    let tuple = jl_new_struct_uninit(tuple_type);
    let v = try_protect(frame, tuple)?.unwrap();

    let usize_ptr: *mut usize = v.ptr().cast();
    std::ptr::copy_nonoverlapping(dims.as_slice().as_ptr(), usize_ptr, n);

    Ok(v)
}