1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
//! Wrapper for arbitrary Julia data.
//!
//! Julia data returned by the C API is often returned as a pointer to `jl_value_t`, which is
//! an opaque type. This pointer is wrapped in jlrs by [`Value`]. The layout of the data that is
//! pointed to depends on its underlying type. Julia guarantees that the data is preceded in
//! memory by a header which contains a pointer to the data's type information, its [`DataType`].
//!
//! For example, if the `DataType` is `UInt8`, the pointer points to a `u8`. If the
//! `DataType` is some Julia array type like `Array{Int, 2}`, the pointer points to
//! Julia's internal array type, `jl_array_t`. In the first case tha value can be unboxed as a
//! `u8`, in the second case it can be cast to [`Array`] or [`TypedArray<isize>`].
//!
//! The `Value` wrapper is very commonly used in jlrs. A `Value` can be called as a Julia
//! function, the arguments such a function takes are all `Value`s, and it will return either a
//! `Value` or an exception which is also a `Value`. This wrapper also provides methods to create
//! new `Value`s, access their fields, cast them to the appropriate pointer wrapper type, and
//! unbox their contents.
//!
//! One special kind of value is the `NamedTuple`. You will need to create values of this type in
//! order to call functions with keyword arguments. The macro [`named_tuple`] is defined in this
//! module which provides an easy way to create values of this type.
//!
//! [`TypedArray<isize>`]: crate::wrappers::ptr::array::TypedArray

#[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:
///
/// ```
/// # use jlrs::prelude::*;
/// # use jlrs::util::JULIA;
/// # fn main() {
/// # JULIA.with(|j| {
/// # let mut julia = j.borrow_mut();
/// // Three slots; two for the inputs and one for the output.
/// julia.scope_with_capacity(3, |global, mut frame| {
///     // Create the two arguments, each value requires one slot
///     let i = Value::new(&mut frame, 2u64)?;
///     let j = Value::new(&mut frame, 1u32)?;
///
///     let _nt = named_tuple!(&mut frame, "i" => i, "j" => j)?;
///
///     Ok(())
/// }).unwrap();
/// # });
/// # }
/// ```
#[macro_export]
macro_rules! named_tuple {
    ($frame:expr, $name:expr => $value:expr) => {
        $crate::wrappers::ptr::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::wrappers::ptr::value::MAX_SIZE]>::with_capacity(n);
            let mut values = ::smallvec::SmallVec::<[_; $crate::wrappers::ptr::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::wrappers::ptr::value::Value::new_named_tuple($frame, $names, $values)
        }
    };
}

use crate::{
    call::{Call, ProvideKeywords, WithKeywords},
    convert::{into_julia::IntoJulia, to_symbol::ToSymbol, unbox::Unbox},
    error::{
        AccessError, IOError, InstantiationError, JlrsError, JlrsResult, JuliaResult,
        JuliaResultRef, TypeError, CANNOT_DISPLAY_TYPE,
    },
    layout::{
        field_index::FieldIndex,
        typecheck::{NamedTuple, Typecheck},
        valid_layout::ValidLayout,
    },
    memory::{
        frame::Frame,
        get_tls,
        global::Global,
        output::Output,
        scope::{PartialScope, Scope},
    },
    private::Private,
    wrappers::ptr::{
        array::Array,
        datatype::DataType,
        datatype::DataTypeRef,
        module::Module,
        private::WrapperPriv,
        string::JuliaString,
        symbol::Symbol,
        union::{nth_union_component, Union},
        union_all::UnionAll,
        Wrapper,
    },
};
use cfg_if::cfg_if;
use jl_sys::{
    jl_an_empty_string, jl_an_empty_vec_any, jl_apply_type, jl_array_any_type, jl_array_int32_type,
    jl_array_symbol_type, jl_array_typetagdata, jl_array_uint8_type, jl_astaggedvalue,
    jl_bottom_type, jl_call, jl_call0, jl_call1, jl_call2, jl_call3, jl_diverror_exception,
    jl_egal, jl_emptytuple, jl_eval_string, jl_exception_occurred, jl_false, jl_field_index,
    jl_field_isptr, jl_gc_add_finalizer, jl_gc_add_ptr_finalizer, jl_get_nth_field,
    jl_get_nth_field_noalloc, jl_interrupt_exception, jl_isa, jl_memory_exception, jl_nothing,
    jl_object_id, jl_readonlymemory_exception, jl_set_nth_field, jl_stackovf_exception,
    jl_stderr_obj, jl_stdout_obj, jl_subtype, jl_true, jl_typeof_str, jl_undefref_exception,
    jl_value_t,
};
use std::{
    ffi::{c_void, CStr, CString},
    marker::PhantomData,
    mem::MaybeUninit,
    path::Path,
    ptr::NonNull,
    sync::atomic::Ordering,
    usize,
};

use super::Ref;

cfg_if! {
    if #[cfg(any(not(feature = "lts"), feature = "all-features-override"))] {
        use jl_sys::{jlrs_lock, jlrs_unlock};

        use std::{
            ptr::null_mut,
            sync::atomic::{AtomicPtr, AtomicU16, AtomicU32, AtomicU64, AtomicU8},
        };
    }
}

/// In some cases it's necessary to place one or more arguments in front of the arguments a
/// function is called with. Examples include the `named_tuple` macro and `Value::call_async`.
/// If they 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;

/// See the [module-level documentation] for more information.
///
/// A `Value` is a wrapper around a non-null pointer to some data owned by the Julia garbage
/// collector, it has two lifetimes: `'scope` and `'data`. The first of these ensures that a
/// `Value` can only be used while it's rooted, the second accounts for data borrowed from Rust.
/// The only way to borrow data from Rust is to create an Julia array that borrows its contents
///  by calling [`Array::from_slice`]; if a Julia function is called with such an array as an
/// argument the result will inherit the second lifetime of the borrowed data to ensure that
/// such a `Value` can only be used while the borrow is active.
#[repr(transparent)]
#[derive(Copy, Clone, Eq)]
pub struct Value<'scope, 'data>(
    NonNull<jl_value_t>,
    PhantomData<&'scope ()>,
    PhantomData<&'data mut ()>,
);

impl PartialEq for Value<'_, '_> {
    fn eq(&self, other: &Value<'_, '_>) -> bool {
        self.egal(*other)
    }
}

/// # Create new `Value`s
///
/// Several methods are available to create new values. The simplest of these is [`Value::new`],
/// which can be used to convert relatively simple data from Rust to Julia. Data that can be
/// converted this way must implement [`IntoJulia`], which is the case for types like the
/// primitive number types. This trait is also automatically derived by JlrsReflect.jl for types
/// that are trivially guaranteed to be bits-types: the type must have no type parameters, no
/// unions, and all fields must be immutable bits-types themselves.
impl Value<'_, '_> {
    /// Create a new Julia value, any type that implements [`IntoJulia`] can be converted using
    /// this function.
    pub fn new<'target, V, S>(scope: S, value: V) -> JlrsResult<Value<'target, 'static>>
    where
        V: IntoJulia,
        S: PartialScope<'target>,
    {
        let global = scope.global();
        let v = value.into_julia(global).ptr();
        debug_assert!(!v.is_null());
        // Safety: value was just allocated so it can't have been freed yet
        unsafe { scope.value(NonNull::new_unchecked(v), Private) }
    }

    /// Create a new Julia value, any type that implements [`IntoJulia`] can be converted using
    /// this function. Unlike [`Value::new`] this method doesn't root the allocated value.
    pub fn new_unrooted<'global, V>(global: Global<'global>, value: V) -> ValueRef<'global, 'static>
    where
        V: IntoJulia,
    {
        value.into_julia(global)
    }

    /// Create a new named tuple, you should use the `named_tuple` macro rather than this method.
    pub fn new_named_tuple<'target, 'current, 'value, 'data, S, F, N, T, V>(
        scope: S,
        field_names: N,
        values: V,
    ) -> JlrsResult<Value<'target, 'data>>
    where
        S: Scope<'target, 'current, F>,
        F: Frame<'current>,
        N: AsRef<[T]>,
        T: ToSymbol,
        V: AsRef<[Value<'value, 'data>]>,
    {
        let global = scope.global();
        let (output, scope) = scope.split()?;
        scope.scope_with_capacity(4, |mut frame| {
            let field_names = field_names.as_ref();
            let values_m = values.as_ref();

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

            if n_names != n_values {
                Err(InstantiationError::NamedTupleSizeMismatch { n_names, n_values })?;
            }

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

            // Safety: this method can only be called from a thread known to Julia. The
            // unchecked methods are used because it can be guaranteed they won't throw
            // an exception for the given arguments.
            unsafe {
                let mut field_names_vec = field_names
                    .iter()
                    .map(|name| name.to_symbol_priv(Private).as_value())
                    .collect::<smallvec::SmallVec<[_; MAX_SIZE]>>();

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

                let mut field_types_vec = values_m
                    .iter()
                    .copied()
                    .map(|val| val.datatype().as_value())
                    .collect::<smallvec::SmallVec<[_; MAX_SIZE]>>();

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

                let ty = UnionAll::namedtuple_type(global)
                    .as_value()
                    .apply_type_unchecked(&mut frame, &mut [names, field_type_tup])?
                    .cast::<DataType>()?;

                ty.instantiate_unchecked(output, values)
            }
        })
    }

    /// Apply the given types to `self`.
    ///
    /// If `self` is the [`DataType`] `anytuple_type`, calling this method will return a new
    /// tuple type with the given types as its field types. If it is the [`DataType`]
    /// `uniontype_type`, calling this method is equivalent to calling [`Union::new`]. If
    /// the value is a `UnionAll`, the given types will be applied and the resulting type is
    /// returned.
    ///
    /// If the types can't be applied to `self` this methods catches and returns the exception.
    ///
    /// [`Union::new`]: crate::wrappers::ptr::union::Union::new
    #[cfg(not(all(target_os = "windows", feature = "lts")))]
    pub fn apply_type<'target, 'value, 'data, V, S>(
        self,
        scope: S,
        types: V,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
        V: AsRef<[Value<'value, 'data>]>,
    {
        use crate::catch::catch_exceptions;

        // Safety: if an exception is thrown it's caught, the result is immediately rooted
        unsafe {
            let types = types.as_ref();

            let mut callback = |result: &mut MaybeUninit<*mut jl_value_t>| {
                let res =
                    jl_apply_type(self.unwrap(Private), types.as_ptr() as *mut _, types.len());
                result.write(res);
                Ok(())
            };

            match catch_exceptions(&mut callback)? {
                Ok(ptr) => Ok(Ok(scope.value(NonNull::new_unchecked(ptr), Private)?)),
                Err(e) => Ok(Err(e.root(scope)?)),
            }
        }
    }

    /// Apply the given types to `self`.
    ///
    /// If `self` is the [`DataType`] `anytuple_type`, calling this method will return a new
    /// tuple type with the given types as its field types. If it is the [`DataType`]
    /// `uniontype_type`, calling this method is equivalent to calling [`Union::new`]. If
    /// the value is a `UnionAll`, the given types will be applied and the resulting type is
    /// returned.
    ///
    /// If an exception is thrown it isn't caught
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    ///
    /// [`Union::new`]: crate::wrappers::ptr::union::Union::new
    pub unsafe fn apply_type_unchecked<'target, 'value, 'data, S, V>(
        self,
        scope: S,
        types: V,
    ) -> JlrsResult<Value<'target, 'data>>
    where
        S: PartialScope<'target>,
        V: AsRef<[Value<'value, 'data>]>,
    {
        let types = types.as_ref();
        let applied = jl_apply_type(self.unwrap(Private), types.as_ptr() as *mut _, types.len());
        scope.value(NonNull::new_unchecked(applied), Private)
    }
}

/// # Type information
///
/// Every value is guaranteed to have a [`DataType`]. This contains all of the value's type
/// information.
impl<'scope, 'data> Value<'scope, 'data> {
    /// Returns the `DataType` of this value.
    pub fn datatype(self) -> DataType<'scope> {
        // Safety: the pointer points to valid data, every value can be converted to a tagged
        // value.
        unsafe {
            let header = NonNull::new_unchecked(jl_astaggedvalue(self.unwrap(Private)))
                .as_ref()
                .__bindgen_anon_1
                .header;
            let ptr = (header & !15usize) as *mut jl_value_t;
            DataType::wrap(ptr.cast(), Private)
        }
    }

    /// Returns the name of this value's [`DataType`] as a string slice.
    pub fn datatype_name(self) -> JlrsResult<&'scope str> {
        // Safety: the pointer points to valid data, the C API function
        // is called with a valid argument.
        unsafe {
            let type_name = jl_typeof_str(self.unwrap(Private));
            let type_name_ref = CStr::from_ptr(type_name);
            Ok(type_name_ref.to_str().map_err(JlrsError::other)?)
        }
    }
}

/// # Type checking
///
/// Many properties of Julia types can be checked, including whether instances of the type are
/// mutable, if the value is an array, and so on. The method [`Value::is`] can be used to perform
/// these checks. All these checks implement the [`Typecheck`] trait. If the type that implements
/// this trait also implements [`ValidLayout`], the typecheck indicates whether or not the value
/// can be cast to or unboxed as that type.
impl Value<'_, '_> {
    /// Performs the given typecheck:
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # use jlrs::util::JULIA;
    /// # fn main() {
    /// # JULIA.with(|j| {
    /// # let mut julia = j.borrow_mut();
    /// julia.scope(|_global, mut frame| {
    ///     let i = Value::new(&mut frame, 2u64)?;
    ///     assert!(i.is::<u64>());
    ///     Ok(())
    /// }).unwrap();
    /// # });
    /// # }
    /// ```
    ///
    /// A full list of supported checks can be found [here].
    ///
    /// [`JuliaStruct`]: crate::wrappers::ptr::traits::julia_struct::JuliaStruct
    /// [here]: ../../../layout/typecheck/trait.Typecheck.html#implementors
    pub fn is<T: Typecheck>(self) -> bool {
        self.datatype().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 {
        // Safety: the pointers point to valid data, the C API function
        // is called with valid arguments.
        unsafe { jl_subtype(self.unwrap(Private), sup.unwrap(Private)) != 0 }
    }

    /// Returns true if `self` is the type of a `DataType`, `UnionAll`, `Union`, or `Union{}` (the
    /// bottom type).
    pub fn is_kind(self) -> bool {
        // Safety: this method can only be called from a thread known to Julia, its lifetime is
        // never used
        let global = unsafe { Global::new() };

        let ptr = self.unwrap(Private);
        ptr == DataType::datatype_type(global).unwrap(Private).cast()
            || ptr == DataType::unionall_type(global).unwrap(Private).cast()
            || ptr == DataType::uniontype_type(global).unwrap(Private).cast()
            || ptr == DataType::typeofbottom_type(global).unwrap(Private).cast()
    }

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

    /// Returns true if `self` is of type `ty`.
    pub fn isa(self, ty: Value) -> bool {
        // Safety: the pointers point to valid data, the C API function
        // is called with valid arguments.
        unsafe { jl_isa(self.unwrap(Private), ty.unwrap(Private)) != 0 }
    }
}

/// # Lifetime management
///
/// Values have two lifetimes, `'scope` and `'data`. The first ensures that a value can only be
/// used while it's rooted, the second ensures that values that (might) borrow array data from
/// Rust are also restricted by the lifetime of that borrow. This second restriction can be
/// relaxed with [`Value::assume_owned`] if it doesn't borrow any data from Rust.
impl<'scope, 'data> Value<'scope, 'data> {
    /// If you call a Julia 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 contain any borrowed
    /// data this function can be used to relax its second lifetime to `'static`.
    ///
    /// Safety: The value must not contain any data borrowed from Rust.
    pub unsafe fn assume_owned(self) -> Value<'scope, 'static> {
        Value::wrap_non_null(self.unwrap_non_null(Private), Private)
    }

    /// Use the `Output` to extend the lifetime of this data.
    pub fn root<'target>(self, output: Output<'target>) -> Value<'target, 'data> {
        // Safety: the pointer points to valid data
        unsafe {
            let ptr = self.unwrap_non_null(Private);
            output.set_root::<Value>(ptr);
            Value::wrap_non_null(ptr, Private)
        }
    }
}

/// # Conversions
///
/// There are two ways to convert a [`Value`] to some other type. The first is casting, which is
/// used to convert a [`Value`] to the appropriate pointer wrapper type. For example, if the
/// [`Value`] is a Julia array it can be cast to [`Array`]. Because this only involves a pointer
/// cast it's always possible to convert a wrapper to a [`Value`] by calling
/// [`Wrapper::as_value`]. The second way is unboxing, which is used to copy the data the
/// [`Value`] points to to Rust. If a [`Value`] is a `UInt8`, it can be unboxed as a `u8`. By
/// default, jlrs can unbox the default primitive types and Julia strings, but the [`Unbox`] trait
/// can be implemented for other types. It's recommended that you use JlrsReflect.jl to do so.
/// Unlike casting, unboxing dereferences the pointer. As a result it loses its header, so an
/// unboxed value can't be used as a [`Value`] again without reallocating it.
impl<'scope, 'data> Value<'scope, 'data> {
    /// Cast the value to a pointer wrapper type `T`. Returns an error if the conversion is
    /// invalid.
    pub fn cast<T: Wrapper<'scope, 'data> + Typecheck>(self) -> JlrsResult<T> {
        if self.is::<T>() {
            // Safety: self.is::<T>() returning true guarantees this is safe
            unsafe { Ok(T::cast(self, Private)) }
        } else {
            Err(AccessError::InvalidLayout {
                value_type_str: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }
    }

    /// Cast the value to a pointer wrapper type `T` without checking if this conversion is valid.
    ///
    /// Safety: You must guarantee `self.is::<T>()` would have returned `true`.
    pub unsafe fn cast_unchecked<T: Wrapper<'scope, 'data>>(self) -> T {
        T::cast(self, Private)
    }

    /// Unbox the contents of the value as the output type associated with `T`. Returns an error
    /// if the layout of `T::Output` is incompatible with the layout of the type in Julia.
    pub fn unbox<T: Unbox + Typecheck>(self) -> JlrsResult<T::Output> {
        if !self.is::<T>() {
            Err(AccessError::InvalidLayout {
                value_type_str: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        // Safety: self.is::<T>() returning true guarantees this is safe
        unsafe { Ok(T::unbox(self)) }
    }

    /// Unbox the contents of the value as the output type associated with `T` without checking
    /// if the layout of `T::Output` is compatible with the layout of the type in Julia.
    ///
    /// Safety: You must guarantee `self.is::<T>()` would have returned `true`.
    pub unsafe fn unbox_unchecked<T: Unbox>(self) -> T::Output {
        T::unbox(self)
    }

    /// Returns a pointer to the data, this is useful when the output type of `Unbox` is different
    /// than the implementation type and you have to write a custom unboxing function. It's your
    /// responsibility this pointer is used correctly.
    pub fn data_ptr(self) -> NonNull<c_void> {
        self.unwrap_non_null(Private).cast()
    }
}

/// # Fields
///
/// Most Julia values have fields. For example, if the value is an instance of this struct:
///
/// ```julia
/// struct Example
///    fielda
///    fieldb::UInt32
/// end
/// ```
///
/// it will have two fields, `fielda` and `fieldb`. The first field is a pointer field, the second
/// is stored inline as a `u32`. It's possible to safely access the raw contents of these fields
/// with the method [`Value::field_accessor`]. The first field can be accessed as a [`ValueRef`],
/// the second as a `u32`.
impl<'scope, 'data> Value<'scope, 'data> {
    /// Returns the field names of this value as a slice of `Symbol`s.
    pub fn field_names(self) -> &'scope [Symbol<'scope>] {
        // Symbol and SymbolRef have the same layout, and this data is non-null. Symbols are
        // globally rooted.
        unsafe {
            std::mem::transmute(
                self.datatype()
                    .field_names()
                    .wrapper_unchecked()
                    .unrestricted_data()
                    .as_slice(),
            )
        }
    }

    /// Returns the number of fields the underlying Julia value has.
    pub fn n_fields(self) -> usize {
        self.datatype().n_fields() as _
    }

    /// Returns an accessor to access the contents of this value without allocating temporary Julia data.
    pub fn field_accessor<'current, 'borrow, F: Frame<'current>>(
        self,
        _frame: &'borrow F,
    ) -> FieldAccessor<'scope, 'data, 'borrow> {
        FieldAccessor {
            value: self.as_ref(),
            current_field_type: self.datatype().as_ref(),
            offset: 0,
            #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
            buffer: AtomicBuffer::new(),
            state: ViewState::Unlocked,
            _frame: PhantomData,
        }
    }

    /// Roots the field at index `idx` if it exists and returns it, or a
    /// `JlrsError::AccessError` if the index is out of bounds.
    pub fn get_nth_field<'target, S>(
        self,
        scope: S,
        idx: usize,
    ) -> JlrsResult<Value<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        if idx >= self.n_fields() {
            Err(AccessError::OutOfBoundsField {
                idx,
                n_fields: self.n_fields(),
                value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        // Safety: the bounds check succeeded, the pointer points to valid data. The result is
        // rooted immediately.
        unsafe {
            let fld_ptr = jl_get_nth_field(self.unwrap(Private), idx as _);
            if fld_ptr.is_null() {
                Err(AccessError::UndefRef)?;
            }

            scope.value(NonNull::new_unchecked(fld_ptr), Private)
        }
    }

    /// Returns the field at index `idx` if it's a pointer field.
    ///
    /// If the field doesn't exist or if the field can't be referenced because its data is stored
    /// inline, a `JlrsError::AccessError` is returned.
    pub fn get_nth_field_ref(self, idx: usize) -> JlrsResult<ValueRef<'scope, 'data>> {
        let ty = self.datatype();
        if idx >= ty.n_fields() as _ {
            Err(AccessError::OutOfBoundsField {
                idx,
                n_fields: self.n_fields(),
                value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        // Safety: the bounds check succeeded, the pointer points to valid data. All C API
        // functions are called with valid arguments. The result is rooted immediately.
        unsafe {
            if !jl_field_isptr(ty.unwrap(Private), idx as _) {
                let value_type_str = ty.display_string_or(CANNOT_DISPLAY_TYPE);

                let field_name = if let Some(field_name) = self.field_names().get(idx) {
                    field_name
                        .as_str()
                        .unwrap_or("<Cannot display field name>")
                        .to_string()
                } else {
                    format!("{}", idx)
                };

                Err(AccessError::NotAPointerField {
                    value_type: value_type_str,
                    field_name,
                })?
            }

            Ok(ValueRef::wrap(jl_get_nth_field_noalloc(
                self.unwrap(Private),
                idx,
            )))
        }
    }

    /// Returns the field at index `idx` if it exists as a `ValueRef`. If the field is an inline
    /// field a new value is allocated which is left unrooted.
    ///
    /// If the field doesn't exist `JlrsError::OutOfBoundsField` is returned.
    pub fn get_nth_field_unrooted(self, idx: usize) -> JlrsResult<ValueRef<'scope, 'data>> {
        if idx >= self.n_fields() {
            Err(AccessError::OutOfBoundsField {
                idx,
                n_fields: self.n_fields(),
                value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        // Safety: the bounds check succeeded, the pointer points to valid data.
        unsafe { Ok(ValueRef::wrap(jl_get_nth_field(self.unwrap(Private), idx))) }
    }

    /// Roots the field with the name `field_name` if it exists and returns it, or a
    /// `JlrsError::AccessError` if there's no field with that name.
    pub fn get_field<'target, N, S>(
        self,
        scope: S,
        field_name: N,
    ) -> JlrsResult<Value<'target, 'data>>
    where
        N: ToSymbol,
        S: PartialScope<'target>,
    {
        // Safety: the pointer points to valid data, the C API function is called with valid
        // arguments, the result is rooted immediately.
        unsafe {
            let symbol = field_name.to_symbol_priv(Private);
            let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);

            if idx < 0 {
                Err(AccessError::NoSuchField {
                    type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
                })?
            }

            let fld_ptr = jl_get_nth_field(self.unwrap(Private), idx as _);
            if fld_ptr.is_null() {
                Err(AccessError::UndefRef)?;
            }

            scope.value(NonNull::new_unchecked(fld_ptr), Private)
        }
    }

    /// Returns the field with the name `field_name` if it's a pointer field.
    ///
    /// If the field doesn't exist or if the field can't be referenced because its data is stored
    /// inline, a `JlrsError::AccessError` is returned.
    pub fn get_field_ref<N>(self, field_name: N) -> JlrsResult<ValueRef<'scope, 'data>>
    where
        N: ToSymbol,
    {
        // Safety: the pointer points to valid data. All C API functions are called with valid
        // arguments.
        unsafe {
            let symbol = field_name.to_symbol_priv(Private);
            let ty = self.datatype();
            let idx = jl_field_index(ty.unwrap(Private), symbol.unwrap(Private), 0);

            if idx < 0 {
                Err(AccessError::NoSuchField {
                    type_name: ty.display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
                })?
            }

            if !jl_field_isptr(ty.unwrap(Private), idx as _) {
                let idx = idx as usize;
                let value_type_str = ty.display_string_or(CANNOT_DISPLAY_TYPE);

                let field_name = self.field_names()[idx]
                    .as_str()
                    .unwrap_or("<Cannot display field name>")
                    .to_string();

                Err(AccessError::NotAPointerField {
                    value_type: value_type_str,
                    field_name,
                })?
            }

            Ok(ValueRef::wrap(jl_get_nth_field_noalloc(
                self.unwrap(Private),
                idx as _,
            )))
        }
    }

    /// Returns the field with the name `field_name` if it exists. If the field is an inline field
    /// a new value is allocated which is left unrooted.
    ///
    /// If the field doesn't exist a `JlrsError::AccessError` is returned.
    pub fn get_field_unrooted<N>(self, field_name: N) -> JlrsResult<ValueRef<'scope, 'data>>
    where
        N: ToSymbol,
    {
        // Safety: the pointer points to valid data. All C API functions are called with valid
        // arguments.
        unsafe {
            let symbol = field_name.to_symbol_priv(Private);
            let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);

            if idx < 0 {
                Err(AccessError::NoSuchField {
                    type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
                })?
            }

            Ok(ValueRef::wrap(jl_get_nth_field(
                self.unwrap(Private),
                idx as _,
            )))
        }
    }

    /// Set the value of the field at `idx`. If Julia throws an exception it's caught, rooted in
    /// the frame, and returned. If the index is out of bounds or the value is not a subtype of
    /// the field an error is returned,
    ///
    /// Safety: Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is not prevented.
    #[cfg(not(all(target_os = "windows", feature = "lts")))]
    pub unsafe fn set_nth_field<'frame, F>(
        self,
        frame: &mut F,
        idx: usize,
        value: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'frame, 'data, ()>>
    where
        F: Frame<'frame>,
    {
        use crate::catch::catch_exceptions;

        let n_fields = self.n_fields();
        if n_fields <= idx {
            Err(AccessError::OutOfBoundsField {
                idx,
                n_fields,
                value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        let field_type = self
            .datatype()
            .field_types()
            .wrapper_unchecked()
            .unrestricted_data()
            .as_slice()[idx as usize]
            .value_unchecked();
        let dt = value.datatype();

        if !Value::subtype(dt.as_value(), field_type) {
            Err(TypeError::NotASubtype {
                field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
                value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        let mut callback = |result: &mut MaybeUninit<()>| {
            jl_set_nth_field(self.unwrap(Private), idx, value.unwrap(Private));
            result.write(());
            Ok(())
        };

        match catch_exceptions(&mut callback)? {
            Ok(_) => Ok(Ok(())),
            Err(e) => Ok(Err(e.root(frame)?)),
        }
    }

    /// Set the value of the field at `idx`. If Julia throws an exception it's caught and
    /// returned but not rooted. If the index is out of bounds or the value is not a subtype of
    /// the field an error is returned,
    ///
    /// Safety: Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is not prevented.
    #[cfg(not(all(target_os = "windows", feature = "lts")))]
    pub unsafe fn set_nth_field_unrooted(
        self,
        idx: usize,
        value: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResultRef<'scope, 'data, ()>> {
        use crate::catch::catch_exceptions;

        let n_fields = self.n_fields();
        if n_fields <= idx {
            Err(AccessError::OutOfBoundsField {
                idx,
                n_fields,
                value_type: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        let field_type = self
            .datatype()
            .field_types()
            .wrapper_unchecked()
            .unrestricted_data()
            .as_slice()[idx as usize]
            .value_unchecked();
        let dt = value.datatype();

        if !Value::subtype(dt.as_value(), field_type) {
            Err(TypeError::NotASubtype {
                field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
                value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        let mut callback = |result: &mut MaybeUninit<()>| {
            jl_set_nth_field(self.unwrap(Private), idx, value.unwrap(Private));
            result.write(());
            Ok(())
        };

        match catch_exceptions(&mut callback)? {
            Ok(_) => Ok(Ok(())),
            Err(e) => Ok(Err(e)),
        }
    }

    /// Set the value of the field at `idx`. If Julia throws an exception the process aborts.
    ///
    /// Safety: this method doesn't check if the type of the value is a subtype of the field's
    /// type. Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is also not prevented.
    pub unsafe fn set_nth_field_unchecked(self, idx: usize, value: Value<'_, 'data>) {
        jl_set_nth_field(self.unwrap(Private), idx, value.unwrap(Private))
    }

    /// Set the value of the field with the name `field_name`. If Julia throws an exception it's
    /// caught, rooted in the frame, and returned. If there's no field with the given name or the
    /// value is not a subtype of the field an error is returned.
    ///
    /// Safety: Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is not prevented.
    #[cfg(not(all(target_os = "windows", feature = "lts")))]
    pub unsafe fn set_field<'frame, F, N>(
        self,
        frame: &mut F,
        field_name: N,
        value: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'frame, 'data, ()>>
    where
        F: Frame<'frame>,
        N: ToSymbol,
    {
        use crate::catch::catch_exceptions;

        let symbol = field_name.to_symbol_priv(Private);
        let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);

        if idx < 0 {
            Err(AccessError::NoSuchField {
                type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
                field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
            })?
        }

        let field_type = self
            .datatype()
            .field_types()
            .wrapper_unchecked()
            .unrestricted_data()
            .as_slice()[idx as usize]
            .value_unchecked();
        let dt = value.datatype();

        if !Value::subtype(dt.as_value(), field_type) {
            Err(TypeError::NotASubtype {
                field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
                value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        let mut callback = |result: &mut MaybeUninit<()>| {
            jl_set_nth_field(self.unwrap(Private), idx as usize, value.unwrap(Private));
            result.write(());
            Ok(())
        };

        match catch_exceptions(&mut callback)? {
            Ok(_) => Ok(Ok(())),
            Err(e) => Ok(Err(e.root(frame)?)),
        }
    }

    /// Set the value of the field with the name `field_name`. If Julia throws an exception it's
    /// caught, and returned but not rooted. If there's no field with the given name or the value
    /// is not a subtype of the field an error is returned.
    ///
    /// Safety: Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is not prevented.
    #[cfg(not(all(target_os = "windows", feature = "lts")))]
    pub unsafe fn set_field_unrooted<N>(
        self,
        field_name: N,
        value: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResultRef<'scope, 'data, ()>>
    where
        N: ToSymbol,
    {
        use crate::catch::catch_exceptions;

        let symbol = field_name.to_symbol_priv(Private);
        let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);

        if idx < 0 {
            Err(AccessError::NoSuchField {
                type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
                field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
            })?
        }

        let field_type = self
            .datatype()
            .field_types()
            .wrapper_unchecked()
            .unrestricted_data()
            .as_slice()[idx as usize]
            .value_unchecked();
        let dt = value.datatype();

        if !Value::subtype(dt.as_value(), field_type) {
            Err(TypeError::NotASubtype {
                field_type: field_type.display_string_or(CANNOT_DISPLAY_TYPE),
                value_type: value.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
            })?
        }

        let mut callback = |result: &mut MaybeUninit<()>| {
            jl_set_nth_field(self.unwrap(Private), idx as usize, value.unwrap(Private));
            result.write(());
            Ok(())
        };

        match catch_exceptions(&mut callback)? {
            Ok(_) => Ok(Ok(())),
            Err(e) => Ok(Err(e)),
        }
    }

    /// Set the value of the field with the name `field_name`. If Julia throws an exception the
    /// process aborts. If there's no field with the given name an error is returned.
    ///
    /// Safety: this method doesn't check if the type of the value is a subtype of the field's
    /// type. Mutating things that should absolutely not be mutated, like the fields of a
    /// `DataType`, is also not prevented.
    pub unsafe fn set_field_unchecked<N>(
        self,
        field_name: N,
        value: Value<'_, 'data>,
    ) -> JlrsResult<()>
    where
        N: ToSymbol,
    {
        let symbol = field_name.to_symbol_priv(Private);
        let idx = jl_field_index(self.datatype().unwrap(Private), symbol.unwrap(Private), 0);

        if idx < 0 {
            Err(AccessError::NoSuchField {
                type_name: self.datatype().display_string_or(CANNOT_DISPLAY_TYPE),
                field_name: symbol.as_str().unwrap_or("<Non-UTF8 symbol>").into(),
            })?
        }
        Ok(jl_set_nth_field(
            self.unwrap(Private),
            idx as usize,
            value.unwrap(Private),
        ))
    }
}

/// # Evaluate Julia code
///
/// The easiest way to call Julia from Rust is by evaluating some Julia code directly. This can be
/// used to call simple functions without any arguments provided from Rust and to execute
/// using-statements.
impl Value<'_, '_> {
    /// Execute a Julia command `cmd`, for example `Value::eval_string(&mut *frame, "sqrt(2)")` or
    /// `Value::eval_string(&mut *frame, "using LinearAlgebra")`.
    ///
    /// Safety: The command can't be checked for correctness, nothing prevents you from causing a
    /// segmentation fault with a command like `unsafe_load(Ptr{Float64}(C_NULL))`.
    pub unsafe fn eval_string<'target, C, S>(
        scope: S,
        cmd: C,
    ) -> JlrsResult<JuliaResult<'target, 'static>>
    where
        C: AsRef<str>,
        S: PartialScope<'target>,
    {
        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);
        let exc = jl_exception_occurred();
        let output = if exc.is_null() {
            Ok(NonNull::new_unchecked(res))
        } else {
            Err(NonNull::new_unchecked(exc))
        };
        scope.call_result(output, Private)
    }

    /// Execute a Julia command `cmd`. This is equivalent to `Value::eval_string`, but uses a
    /// null-terminated string.
    ///
    /// Safety: The command can't be checked for correctness, nothing prevents you from causing a
    /// segmentation fault with a command like `unsafe_load(Ptr{Float64}(C_NULL))`.
    pub unsafe fn eval_cstring<'target, C, S>(
        scope: S,
        cmd: C,
    ) -> JlrsResult<JuliaResult<'target, 'static>>
    where
        C: AsRef<CStr>,
        S: PartialScope<'target>,
    {
        let cmd = cmd.as_ref();
        let cmd_ptr = cmd.as_ptr();
        let res = jl_eval_string(cmd_ptr);
        let exc = jl_exception_occurred();
        let output = if exc.is_null() {
            Ok(NonNull::new_unchecked(res))
        } else {
            Err(NonNull::new_unchecked(exc))
        };
        scope.call_result(output, Private)
    }

    /// Calls `include` in the `Main` module in Julia, which evaluates the file's contents in that
    /// module. This has the same effect as calling `include` in the Julia REPL.
    ///
    /// Safety: The content of the file can't be checked for correctness, nothing prevents you
    /// from causing a segmentation fault with code like `unsafe_load(Ptr{Float64}(C_NULL))`.
    pub unsafe fn include<'target, 'current, P, S, F>(
        scope: S,
        path: P,
    ) -> JlrsResult<JuliaResult<'target, 'static>>
    where
        P: AsRef<Path>,
        S: Scope<'target, 'current, F>,
        F: Frame<'current>,
    {
        if path.as_ref().exists() {
            let global = scope.global();
            let (output, scope) = scope.split()?;
            return scope.scope(|mut frame| {
                let path_jl_str = JuliaString::new(&mut frame, path.as_ref().to_string_lossy())?;
                let include_func = Module::main(global)
                    .function_ref("include")?
                    .wrapper_unchecked();

                let scope = output.into_scope(&mut frame);
                include_func.call1(scope, path_jl_str.as_value())
            });
        }

        Err(IOError::NotFound {
            path: path.as_ref().to_string_lossy().into(),
        })?
    }
}

/// # Equality
impl Value<'_, '_> {
    /// Returns the object id of this value.
    pub fn object_id(self) -> usize {
        // Safety: the pointer points to valid data, the C API
        // functions is called with a valid argument.
        unsafe { jl_object_id(self.unwrap(Private)) }
    }

    /// Returns true if `self` and `other` are equal.
    pub fn egal(self, other: Value) -> bool {
        // Safety: the pointer points to valid data, the C API
        // functions is called with a valid argument.
        unsafe { jl_egal(self.unwrap(Private), other.unwrap(Private)) != 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.
    ///
    /// Safety: the finalizer must be compatible with the data.
    pub unsafe fn add_finalizer(self, f: Value<'_, 'static>) {
        jl_gc_add_finalizer(self.unwrap(Private), f.unwrap(Private))
    }

    /// Add a finalizer `f` to this value. The finalizer must be an `extern "C"` function that
    /// takes one argument, the value as a void pointer.
    ///
    /// Safety: the finalizer must be compatible with the data.
    pub unsafe fn add_ptr_finalizer(self, f: unsafe extern "C" fn(*mut c_void) -> ()) {
        jl_gc_add_ptr_finalizer(get_tls(), self.unwrap(Private), f as *mut c_void)
    }
}

/// # Constant values.
impl<'scope> Value<'scope, 'static> {
    /// `Union{}`.
    pub fn bottom_type(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_bottom_type), Private) }
    }

    /// `StackOverflowError`.
    pub fn stackovf_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stackovf_exception), Private) }
    }

    /// `OutOfMemoryError`.
    pub fn memory_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_memory_exception), Private) }
    }

    /// `ReadOnlyMemoryError`.
    pub fn readonlymemory_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe {
            Value::wrap_non_null(NonNull::new_unchecked(jl_readonlymemory_exception), Private)
        }
    }

    /// `DivideError`.
    pub fn diverror_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_diverror_exception), Private) }
    }

    /// `UndefRefError`.
    pub fn undefref_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_undefref_exception), Private) }
    }

    /// `InterruptException`.
    pub fn interrupt_exception(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_interrupt_exception), Private) }
    }

    /// An empty `Array{Any, 1}.
    pub fn an_empty_vec_any(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_an_empty_vec_any), Private) }
    }

    /// An empty immutable String, "".
    pub fn an_empty_string(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_an_empty_string), Private) }
    }

    /// `Array{UInt8, 1}`
    pub fn array_uint8_type(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_uint8_type), Private) }
    }

    /// `Array{Any, 1}`
    pub fn array_any_type(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_any_type), Private) }
    }

    /// `Array{Symbol, 1}`
    pub fn array_symbol_type(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_symbol_type), Private) }
    }

    /// `Array{Int32, 1}`
    pub fn array_int32_type(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_array_int32_type), Private) }
    }

    /// The empty tuple, `()`.
    pub fn emptytuple(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_emptytuple), Private) }
    }

    /// The instance of `true`.
    pub fn true_v(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_true), Private) }
    }

    /// The instance of `false`.
    pub fn false_v(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_false), Private) }
    }

    /// The instance of `Nothing`, `nothing`.
    pub fn nothing(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_nothing), Private) }
    }

    /// The handle to `stdout` as a Julia value.
    pub fn stdout(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stdout_obj()), Private) }
    }

    /// The handle to `stderr` as a Julia value.
    pub fn stderr(_: Global<'scope>) -> Self {
        // Safety: global constant
        unsafe { Value::wrap_non_null(NonNull::new_unchecked(jl_stderr_obj()), Private) }
    }
}

impl<'data> Call<'data> for Value<'_, 'data> {
    #[inline(always)]
    unsafe fn call0<'target, S>(self, scope: S) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let res = match self.call0_unrooted(Global::new()) {
            Ok(v) => Ok(NonNull::new_unchecked(v.ptr())),
            Err(e) => Err(NonNull::new_unchecked(e.ptr())),
        };
        scope.call_result(res, Private)
    }

    #[inline(always)]
    unsafe fn call1<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let res = match self.call1_unrooted(Global::new(), arg0) {
            Ok(v) => Ok(NonNull::new_unchecked(v.ptr())),
            Err(e) => Err(NonNull::new_unchecked(e.ptr())),
        };
        scope.call_result(res, Private)
    }

    #[inline(always)]
    unsafe fn call2<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let res = match self.call2_unrooted(Global::new(), arg0, arg1) {
            Ok(v) => Ok(NonNull::new_unchecked(v.ptr())),
            Err(e) => Err(NonNull::new_unchecked(e.ptr())),
        };
        scope.call_result(res, Private)
    }

    #[inline(always)]
    unsafe fn call3<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let res = match self.call3_unrooted(Global::new(), arg0, arg1, arg2) {
            Ok(v) => Ok(NonNull::new_unchecked(v.ptr())),
            Err(e) => Err(NonNull::new_unchecked(e.ptr())),
        };
        scope.call_result(res, Private)
    }

    #[inline(always)]
    unsafe fn call<'target, 'value, V, S>(
        self,
        scope: S,
        args: V,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        V: AsRef<[Value<'value, 'data>]>,
        S: PartialScope<'target>,
    {
        let res = match self.call_unrooted(Global::new(), args) {
            Ok(v) => Ok(NonNull::new_unchecked(v.ptr())),
            Err(e) => Err(NonNull::new_unchecked(e.ptr())),
        };
        scope.call_result(res, Private)
    }

    #[inline(always)]
    unsafe fn call0_unrooted<'target>(self, _: Global<'target>) -> JuliaResultRef<'target, 'data> {
        let res = jl_call0(self.unwrap(Private));
        let exc = jl_exception_occurred();

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

    #[inline(always)]
    unsafe fn call1_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let res = jl_call1(self.unwrap(Private), arg0.unwrap(Private));
        let exc = jl_exception_occurred();

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

    #[inline(always)]
    unsafe fn call2_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let res = jl_call2(
            self.unwrap(Private),
            arg0.unwrap(Private),
            arg1.unwrap(Private),
        );
        let exc = jl_exception_occurred();

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

    #[inline(always)]
    unsafe fn call3_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let res = jl_call3(
            self.unwrap(Private),
            arg0.unwrap(Private),
            arg1.unwrap(Private),
            arg2.unwrap(Private),
        );
        let exc = jl_exception_occurred();

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

    #[inline(always)]
    unsafe fn call_unrooted<'target, 'value, V>(
        self,
        _: Global<'target>,
        args: V,
    ) -> JuliaResultRef<'target, 'data>
    where
        V: AsRef<[Value<'value, 'data>]>,
    {
        let args = args.as_ref();
        let n = args.len();
        let res = jl_call(self.unwrap(Private).cast(), args.as_ptr() as *mut _, n as _);
        let exc = jl_exception_occurred();

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

impl<'value, 'data> ProvideKeywords<'value, 'data> for Value<'value, 'data> {
    fn provide_keywords(
        self,
        kws: Value<'value, 'data>,
    ) -> JlrsResult<WithKeywords<'value, 'data>> {
        if !kws.is::<NamedTuple>() {
            let type_str = kws.datatype().display_string_or(CANNOT_DISPLAY_TYPE);
            Err(TypeError::NotANamedTuple { type_str })?
        }
        Ok(WithKeywords::new(self, kws))
    }
}

impl_debug!(Value<'_, '_>);

impl<'scope, 'data> WrapperPriv<'scope, 'data> for Value<'scope, 'data> {
    type Wraps = jl_value_t;
    const NAME: &'static str = "Value";

    // Safety: `inner` must not have been freed yet, the result must never be
    // used after the GC might have freed it.
    unsafe fn wrap_non_null(inner: NonNull<Self::Wraps>, _: Private) -> Self {
        Self(inner, PhantomData, PhantomData)
    }

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

/// While jlrs generally enforces that Julia data can only exist and be used while a frame is
/// active, it's possible to leak global values: [`Symbol`]s, [`Module`]s, and globals defined in
/// those modules.
#[derive(Copy, Clone)]
pub struct LeakedValue(Value<'static, 'static>);

impl LeakedValue {
    // Safety: ptr must point to valid Julia data
    pub(crate) unsafe fn wrap(ptr: *mut jl_value_t) -> Self {
        LeakedValue(Value::wrap(ptr, Private))
    }

    // Safety: ptr must point to valid Julia data
    pub(crate) unsafe fn wrap_non_null(ptr: NonNull<jl_value_t>) -> Self {
        LeakedValue(Value::wrap_non_null(ptr, Private))
    }

    /// Convert this [`LeakedValue`] back to a [`Value`]. This requires a [`Global`], so this
    /// method can only be called inside a closure taken by one of the `scope`-methods.
    ///
    /// Safety: you must guarantee this value has not been freed by the garbage collector. While
    /// `Symbol`s are never garbage collected, modules and their contents can be redefined.
    #[inline(always)]
    pub unsafe fn as_value<'scope>(self, _: Global<'scope>) -> Value<'scope, 'static> {
        self.0
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
#[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
union AtomicBuffer {
    bytes: [MaybeUninit<u8>; 8],
    ptr: *mut jl_value_t,
}

#[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
impl AtomicBuffer {
    fn new() -> Self {
        AtomicBuffer { ptr: null_mut() }
    }
}

#[derive(Copy, Clone, PartialEq)]
enum ViewState {
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    Locked,
    Unlocked,
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    AtomicBuffer,
    Array,
}

/// Access the raw contents of a Julia value.
///
/// A `FieldAccessor` for a value can be created with [`Value::field_accessor`]. By chaining calls
/// to the `field` and `atomic_field` methods you can access deeply nested fields without
/// allocating temporary Julia data. These two methods support three kinds of field identifiers:
/// field names, numerical field indices, and n-dimensional array indices. The first two can be
/// used with types that have named fields, the second must be used with tuples, and the last one
/// with arrays.
pub struct FieldAccessor<'scope, 'data, 'borrow> {
    value: ValueRef<'scope, 'data>,
    current_field_type: DataTypeRef<'scope>,
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    buffer: AtomicBuffer,
    offset: u32,
    state: ViewState,
    _frame: PhantomData<&'borrow ()>,
}

impl<'scope, 'data> FieldAccessor<'scope, 'data, '_> {
    /// Access the field the accessor is currenty pointing to as a value of type `T`.
    ///
    /// This method accesses the field using its concrete type. If the concrete type of the field
    /// has a matching pointer wrapper type it can be accessed as a `ValueRef` or a `Ref` of to
    /// that pointer wrapper type. For example, a field that contains a `Module` can be accessed
    /// as a `ModuleRef`. In all other cases an inline wrapper type must be used. For example, an
    /// untyped field that currently holds a `Float64` must be accessed as `f64`.
    pub fn access<T: ValidLayout>(self) -> JlrsResult<T> {
        if self.current_field_type.is_undefined() {
            Err(AccessError::UndefRef)?;
        }

        // Safety: in this block, the first check ensures that T is correct
        // for the data that is accessed. If the data is in the atomic buffer
        // it's read from there. If T is as Ref, the pointer is converted. If
        // it's an array, the element at the desired position is read.
        // Otherwise, the field is read at the offset where it has been determined
        // to be stored.
        unsafe {
            let ty = self.current_field_type.value_unchecked();
            if !T::valid_layout(ty) {
                let value_type_str = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
                Err(AccessError::InvalidLayout { value_type_str })?;
            }

            #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
            if self.state == ViewState::AtomicBuffer {
                debug_assert!(!T::IS_REF);
                debug_assert!(std::mem::size_of::<T>() <= 8);
                return Ok(std::ptr::read(
                    self.buffer.bytes[self.offset as usize..].as_ptr() as *const T,
                ));
            }

            if T::IS_REF {
                Ok(std::mem::transmute_copy(&self.value))
            } else if self.state == ViewState::Array {
                Ok(self
                    .value
                    .value_unchecked()
                    .cast_unchecked::<Array>()
                    .data_ptr()
                    .cast::<u8>()
                    .add(self.offset as usize)
                    .cast::<T>()
                    .read())
            } else {
                Ok(self
                    .value
                    .ptr()
                    .cast::<u8>()
                    .add(self.offset as usize)
                    .cast::<T>()
                    .read())
            }
        }
    }

    /// Returns `true` if `self.access::<T>()` will succeed, `false` if it will fail.
    pub fn can_access_as<T: ValidLayout>(&self) -> bool {
        if self.current_field_type.is_undefined() {
            return false;
        }

        // Safety: the current_field_type field is not undefined.
        let ty = unsafe { self.current_field_type.value_unchecked() };
        if !T::valid_layout(ty) {
            return false;
        }

        true
    }

    /// Update the accessor to point to `field`.
    ///
    /// Three kinds of field indices exist: field names, numerical field indices, and
    /// n-dimensional array indices. The first two can be used with types that have named fields,
    /// the second must be used with tuples, and the last one with arrays.
    ///
    /// If `field` is an invalid identifier an error is returned. Calls to `field` can be chained
    /// to access nested fields.
    ///
    /// If the field is an atomic field the same ordering is used as Julia uses by default:
    /// `Relaxed` for pointer fields, `SeqCst` for small inline fields, and a lock for large
    /// inline fields.
    pub fn field<F: FieldIndex>(mut self, field: F) -> JlrsResult<Self> {
        if self.value.is_undefined() {
            Err(AccessError::UndefRef)?
        }

        if self.current_field_type.is_undefined() {
            Err(AccessError::UndefRef)?
        }

        // Safety: how to access the next field depends on the current view. If an array
        // is accessed the view is updated to the requested element. Otherwise, the offset
        // is adjusted to target the requested field. Because the starting point is assumed
        // to be rooted, all pointer fields are either reachablle or undefined. If a field is
        // atomic, atomic accesses (or locks for large atomic fields) are used.
        unsafe {
            let current_field_type = self.current_field_type.wrapper_unchecked();
            if self.state == ViewState::Array && current_field_type.is::<Array>() {
                let arr = self.value.value_unchecked().cast_unchecked::<Array>();
                // accessing an array, find the offset of the requested element
                let index = field.array_index(arr, Private)?;
                self.get_array_field(arr, index);
                return Ok(self);
            }

            let index = field.field_index(current_field_type, Private)?;

            let next_field_type = current_field_type.field_type_unchecked(index);
            if next_field_type.is_undefined() {
                Err(AccessError::UndefRef)?
            }

            let next_field_type = next_field_type.wrapper_unchecked();
            let is_pointer_field = current_field_type.is_pointer_field_unchecked(index);
            let field_offset = current_field_type.field_offset_unchecked(index);
            self.offset += field_offset;

            match self.state {
                ViewState::Array => {
                    self.get_inline_array_field(is_pointer_field, next_field_type)?
                }
                ViewState::Unlocked => self.get_unlocked_inline_field(
                    is_pointer_field,
                    current_field_type,
                    next_field_type,
                    index,
                    Ordering::Relaxed,
                    Ordering::SeqCst,
                ),
                #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
                ViewState::Locked => {
                    self.get_locked_inline_field(is_pointer_field, next_field_type)
                }
                #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
                ViewState::AtomicBuffer => {
                    self.get_atomic_buffer_field(is_pointer_field, next_field_type)
                }
            }
        }

        Ok(self)
    }

    /// Update the accessor to point to `field`.
    ///
    /// If the field is a small atomic field `ordering` is used to read it. The ordering is
    /// ignored for non-atomic fields and fields that require a lock to access. See
    /// [`FieldAccessor::field`] for more information.
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    pub fn atomic_field<F: FieldIndex>(mut self, field: F, ordering: Ordering) -> JlrsResult<Self> {
        if self.value.is_undefined() {
            Err(AccessError::UndefRef)?
        }

        if self.current_field_type.is_undefined() {
            Err(AccessError::UndefRef)?
        }

        // Safety: how to access the next field depends on the current view. If an array
        // is accessed the view is updated to the requested element. Otherwise, the offset
        // is adjusted to target the requested field. Because the starting point is assumed
        // to be rooted, all pointer fields are either reachablle or undefined. If a field is
        // atomic, atomic accesses (or locks for large atomic fields) are used.
        unsafe {
            let current_field_type = self.current_field_type.wrapper_unchecked();
            if self.state == ViewState::Array && current_field_type.is::<Array>() {
                let arr = self.value.value_unchecked().cast_unchecked::<Array>();
                // accessing an array, find the offset of the requested element
                let index = field.array_index(arr, Private)?;
                self.get_array_field(arr, index);
                return Ok(self);
            }

            let index = field.field_index(current_field_type, Private)?;

            let next_field_type = current_field_type.field_type_unchecked(index);
            if next_field_type.is_undefined() {
                Err(AccessError::UndefRef)?
            }

            let next_field_type = next_field_type.wrapper_unchecked();
            let is_pointer_field = current_field_type.is_pointer_field_unchecked(index);
            let field_offset = current_field_type.field_offset_unchecked(index);
            self.offset += field_offset;

            match self.state {
                ViewState::Array => {
                    self.get_inline_array_field(is_pointer_field, next_field_type)?
                }
                ViewState::Unlocked => self.get_unlocked_inline_field(
                    is_pointer_field,
                    current_field_type,
                    next_field_type,
                    index,
                    ordering,
                    ordering,
                ),
                ViewState::Locked => {
                    self.get_locked_inline_field(is_pointer_field, next_field_type)
                }
                ViewState::AtomicBuffer => {
                    self.get_atomic_buffer_field(is_pointer_field, next_field_type)
                }
            }
        }

        Ok(self)
    }

    /// Try to clone this accessor and its state.
    ///
    /// If the current value this accessor is accessing is locked an error is returned.
    pub fn try_clone(&self) -> JlrsResult<Self> {
        #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
        if self.state == ViewState::Locked {
            Err(AccessError::Locked)?;
        }

        Ok(FieldAccessor {
            value: self.value,
            current_field_type: self.current_field_type,
            offset: self.offset,
            #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
            buffer: self.buffer.clone(),
            state: self.state,
            _frame: PhantomData,
        })
    }

    /// Returns `true` if the current value the accessor is accessing is locked.
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    pub fn is_locked(&self) -> bool {
        self.state == ViewState::Locked
    }

    /// Returns `true` if the current value the accessor is accessing is locked.
    #[cfg(all(feature = "lts", not(feature = "all-features-override")))]
    pub fn is_locked(&self) -> bool {
        false
    }

    /// Returns the type of the field the accessor is currently pointing at.
    pub fn current_field_type(&self) -> DataTypeRef<'scope> {
        self.current_field_type
    }

    /// Returns the value the accessor is currently inspecting.
    pub fn value(&self) -> ValueRef<'scope, 'data> {
        self.value
    }

    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    // Safety: the view state must be ViewState::AtomicBuffer
    unsafe fn get_atomic_buffer_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) {
        if is_pointer_field {
            debug_assert_eq!(self.offset, 0);
            self.value = ValueRef::wrap(self.buffer.ptr);
            self.state = ViewState::Unlocked;
            if self.value.is_undefined() {
                if let Ok(ty) = next_field_type.cast::<DataType>() {
                    if ty.is_concrete_type() {
                        self.current_field_type = ty.as_ref();
                    } else {
                        self.current_field_type = DataTypeRef::undefined_ref();
                    }
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                }
            } else {
                self.current_field_type = self.value.wrapper_unchecked().datatype().as_ref();
            }
        } else {
            debug_assert!(next_field_type.is::<DataType>());
            self.current_field_type = next_field_type.cast_unchecked::<DataType>().as_ref();
        }
    }

    // Safety: the view state must be ViewState::Unlocked
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    unsafe fn get_unlocked_inline_field(
        &mut self,
        is_pointer_field: bool,
        current_field_type: DataType<'scope>,
        next_field_type: Value<'scope, 'data>,
        index: usize,
        pointer_ordering: Ordering,
        inline_ordering: Ordering,
    ) {
        let is_atomic_field = current_field_type.is_atomic_field_unchecked(index);
        if is_pointer_field {
            if is_atomic_field {
                self.get_atomic_pointer_field(next_field_type, pointer_ordering);
            } else {
                self.get_pointer_field(false, next_field_type);
            }
        } else if let Ok(un) = next_field_type.cast::<Union>() {
            self.get_bits_union_field(un);
        } else {
            debug_assert!(next_field_type.is::<DataType>());
            self.current_field_type = next_field_type.cast_unchecked::<DataType>().as_ref();

            if is_atomic_field {
                self.lock_or_copy_atomic(inline_ordering);
            }
        }
    }

    // Safety: the view state must be ViewState::Unlocked
    #[cfg(all(feature = "lts", not(feature = "all-features-override")))]
    unsafe fn get_unlocked_inline_field(
        &mut self,
        is_pointer_field: bool,
        _current_field_type: DataType<'scope>,
        next_field_type: Value<'scope, 'data>,
        _index: usize,
        _pointer_ordering: Ordering,
        _inline_ordering: Ordering,
    ) {
        if is_pointer_field {
            self.get_pointer_field(false, next_field_type);
        } else if let Ok(un) = next_field_type.cast::<Union>() {
            self.get_bits_union_field(un);
        } else {
            debug_assert!(next_field_type.is::<DataType>());
            self.current_field_type = next_field_type.cast_unchecked::<DataType>().as_ref();
        }
    }

    // Safety: the view state must be ViewState::Locked
    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    unsafe fn get_locked_inline_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) {
        if is_pointer_field {
            self.get_pointer_field(true, next_field_type);
        } else if let Ok(un) = next_field_type.cast::<Union>() {
            self.get_bits_union_field(un);
        } else {
            debug_assert!(next_field_type.is::<DataType>());
            self.current_field_type = next_field_type.cast_unchecked::<DataType>().as_ref();
        }
    }

    // Safety: the view state must be ViewState::Array
    unsafe fn get_inline_array_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) -> JlrsResult<()> {
        // Inline field of the current array
        if is_pointer_field {
            self.value = self
                .value
                .value_unchecked()
                .cast::<Array>()?
                .data_ptr()
                .cast::<MaybeUninit<u8>>()
                .add(self.offset as usize)
                .cast::<ValueRef>()
                .read();

            self.offset = 0;
            self.state = ViewState::Unlocked;

            if self.value.is_undefined() {
                if let Ok(ty) = next_field_type.cast::<DataType>() {
                    if ty.is_concrete_type() {
                        self.current_field_type = ty.as_ref();
                    } else {
                        self.current_field_type = DataTypeRef::undefined_ref();
                    }
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                }
            } else {
                self.current_field_type = self.value.value_unchecked().datatype().as_ref();
            }
        } else {
            self.current_field_type = next_field_type.cast::<DataType>()?.as_ref();
        }

        Ok(())
    }

    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    // Safety: must only be used to read an atomic field
    unsafe fn lock_or_copy_atomic(&mut self, ordering: Ordering) {
        let ptr = self
            .value
            .ptr()
            .cast::<MaybeUninit<u8>>()
            .add(self.offset as usize);

        match self.current_field_type.wrapper_unchecked().size() {
            0 => (),
            1 => {
                let atomic = &*ptr.cast::<AtomicU8>();
                let v = atomic.load(ordering);
                let dst_ptr = self.buffer.bytes.as_mut_ptr();
                std::ptr::copy_nonoverlapping(&v as *const _ as *const u8, dst_ptr as _, 1);
                self.state = ViewState::AtomicBuffer;
                self.offset = 0;
            }
            2 => {
                let atomic = &*ptr.cast::<AtomicU16>();
                let v = atomic.load(ordering);
                let dst_ptr = self.buffer.bytes.as_mut_ptr();
                std::ptr::copy_nonoverlapping(&v as *const _ as *const u8, dst_ptr as _, 2);
                self.state = ViewState::AtomicBuffer;
                self.offset = 0;
            }
            sz if sz <= 4 => {
                let atomic = &*ptr.cast::<AtomicU32>();
                let v = atomic.load(ordering);
                let dst_ptr = self.buffer.bytes.as_mut_ptr();
                std::ptr::copy_nonoverlapping(
                    &v as *const _ as *const u8,
                    dst_ptr as _,
                    sz as usize,
                );
                self.state = ViewState::AtomicBuffer;
                self.offset = 0;
            }
            sz if sz <= 8 => {
                let atomic = &*ptr.cast::<AtomicU64>();
                let v = atomic.load(ordering);
                let dst_ptr = self.buffer.bytes.as_mut_ptr();
                std::ptr::copy_nonoverlapping(
                    &v as *const _ as *const u8,
                    dst_ptr as _,
                    sz as usize,
                );
                self.state = ViewState::AtomicBuffer;
                self.offset = 0;
            }
            _ => {
                jlrs_lock(self.value.ptr());
                self.state = ViewState::Locked;
            }
        }
    }

    // Safety: must only be used to read an array element
    unsafe fn get_array_field(&mut self, arr: Array<'scope, 'data>, index: usize) {
        debug_assert!(self.state == ViewState::Array);
        let el_size = arr.element_size();
        self.offset = (index * el_size) as u32;

        if arr.is_value_array() {
            self.value = arr.data_ptr().cast::<ValueRef>().add(index).read();
            self.offset = 0;
            if self.value.is_undefined() {
                if let Ok(ty) = arr.element_type().cast::<DataType>() {
                    if ty.is_concrete_type() {
                        self.current_field_type = ty.as_ref();
                    } else {
                        self.current_field_type = DataTypeRef::undefined_ref();
                    }

                    if !ty.is::<Array>() {
                        self.state = ViewState::Unlocked;
                    }
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                    self.state = ViewState::Unlocked;
                }
            } else {
                let ty = self.value.value_unchecked().datatype();
                self.current_field_type = ty.as_ref();
                if !ty.is::<Array>() {
                    self.state = ViewState::Unlocked;
                }
            }
        } else if arr.is_union_array() {
            let mut tag = *jl_array_typetagdata(arr.unwrap(Private)).add(index) as i32;
            let component = nth_union_component(arr.element_type(), &mut tag);
            debug_assert!(component.is_some());
            let ty = component.unwrap_unchecked();
            debug_assert!(ty.is::<DataType>());
            let ty = ty.cast_unchecked::<DataType>();
            debug_assert!(ty.is_concrete_type());
            self.current_field_type = ty.as_ref();
        } else {
            let ty = arr.element_type();
            debug_assert!(ty.is::<DataType>());
            self.current_field_type = ty.cast_unchecked::<DataType>().as_ref();
        }
    }

    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    // Safety: must only be used to read an pointer field
    unsafe fn get_pointer_field(&mut self, locked: bool, next_field_type: Value<'scope, 'data>) {
        let value = self
            .value
            .ptr()
            .cast::<u8>()
            .add(self.offset as usize)
            .cast::<ValueRef>()
            .read();

        if locked {
            jlrs_unlock(self.value.ptr());
            self.state = ViewState::Unlocked;
        }

        self.value = value;
        self.offset = 0;

        if self.value.is_undefined() {
            if let Ok(ty) = next_field_type.cast::<DataType>() {
                if ty.is_concrete_type() {
                    self.current_field_type = ty.as_ref();
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                }
            } else {
                self.current_field_type = DataTypeRef::undefined_ref();
            }
        } else {
            let value = self.value.value_unchecked();
            self.current_field_type = value.datatype().as_ref();
            if value.is::<Array>() {
                self.state = ViewState::Array;
            }
        }
    }

    #[cfg(all(feature = "lts", not(feature = "all-features-override")))]
    // Safety: must only be used to read an pointer field
    unsafe fn get_pointer_field(&mut self, _locked: bool, next_field_type: Value<'scope, 'data>) {
        let value = self
            .value
            .ptr()
            .cast::<u8>()
            .add(self.offset as usize)
            .cast::<ValueRef>()
            .read();

        self.value = value;
        self.offset = 0;

        if self.value.is_undefined() {
            if let Ok(ty) = next_field_type.cast::<DataType>() {
                if ty.is_concrete_type() {
                    self.current_field_type = ty.as_ref();
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                }
            } else {
                self.current_field_type = DataTypeRef::undefined_ref();
            }
        } else {
            let value = self.value.value_unchecked();
            self.current_field_type = value.datatype().as_ref();
            if value.is::<Array>() {
                self.state = ViewState::Array;
            }
        }
    }

    #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
    // Safety: must only be used to read an atomic pointer field
    unsafe fn get_atomic_pointer_field(
        &mut self,
        next_field_type: Value<'scope, 'data>,
        ordering: Ordering,
    ) {
        let v = &*self
            .value
            .ptr()
            .cast::<u8>()
            .add(self.offset as usize)
            .cast::<AtomicPtr<jl_value_t>>();

        let ptr = v.load(ordering);
        self.value = ValueRef::wrap(ptr);
        self.offset = 0;

        if self.value.is_undefined() {
            if let Ok(ty) = next_field_type.cast::<DataType>() {
                if ty.is_concrete_type() {
                    self.current_field_type = ty.as_ref();
                } else {
                    self.current_field_type = DataTypeRef::undefined_ref();
                }
            } else {
                self.current_field_type = DataTypeRef::undefined_ref();
            }
        } else {
            let value = self.value.value_unchecked();
            self.current_field_type = value.datatype().as_ref();
            if value.is::<Array>() {
                self.state = ViewState::Array;
            }
        }
    }

    // Safety: must only be used to read a bits union field
    unsafe fn get_bits_union_field(&mut self, union: Union<'scope>) {
        let mut size = 0;
        let isbits = union.isbits_size_align(&mut size, &mut 0);
        debug_assert!(isbits);
        let flag_offset = self.offset as usize + size;
        let mut flag = self.value.ptr().cast::<u8>().add(flag_offset).read() as i32;

        let active_ty = nth_union_component(union.as_value(), &mut flag);
        debug_assert!(active_ty.is_some());
        let active_ty = active_ty.unwrap_unchecked();
        debug_assert!(active_ty.is::<DataType>());

        let ty = active_ty.cast_unchecked::<DataType>();
        debug_assert!(ty.is_concrete_type());
        self.current_field_type = ty.as_ref();
    }
}

impl Drop for FieldAccessor<'_, '_, '_> {
    fn drop(&mut self) {
        #[cfg(any(not(feature = "lts"), feature = "all-features-override"))]
        if self.state == ViewState::Locked {
            debug_assert!(!self.value.is_undefined());
            // Safety: the value is currently locked.
            unsafe { jlrs_unlock(self.value.ptr()) }
        }
    }
}

impl_root!(Value, 2);

/// A reference to a [`Value`] that has not been explicitly rooted.
pub type ValueRef<'scope, 'data> = Ref<'scope, 'data, Value<'scope, 'data>>;

unsafe impl ValidLayout for ValueRef<'_, '_> {
    fn valid_layout(v: Value) -> bool {
        if let Ok(dt) = v.cast::<DataType>() {
            !dt.is_inline_alloc()
        } else if v.cast::<UnionAll>().is_ok() {
            true
        } else if let Ok(u) = v.cast::<Union>() {
            !u.is_bits_union()
        } else {
            false
        }
    }

    const IS_REF: bool = true;
}

impl_ref_root!(Value, ValueRef, 2);