jlrs 0.23.0

jlrs provides bindings to the Julia C API that enable Julia code to be called from Rust and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
//! Managed type for `DataType`, which provides access to type properties.

use std::{ffi::CStr, marker::PhantomData, ptr::NonNull};

use jl_sys::{
    jl_abstractstring_type, jl_any_type, jl_anytuple_type, jl_argumenterror_type,
    jl_atomicerror_type, jl_bool_type, jl_boundserror_type, jl_char_type, jl_const_type,
    jl_datatype_t, jl_datatype_type, jl_emptytuple_type, jl_errorexception_type, jl_expr_type,
    jl_field_index, jl_float16_type, jl_float32_type, jl_float64_type, jl_floatingpoint_type,
    jl_function_type, jl_has_free_typevars, jl_initerror_type, jl_int8_type, jl_int16_type,
    jl_int32_type, jl_int64_type, jl_loaderror_type, jl_methoderror_type, jl_module_type,
    jl_new_structv, jl_nothing_type, jl_number_type, jl_signed_type, jl_simplevector_type,
    jl_string_type, jl_symbol_type, jl_task_type, jl_tvar_type, jl_typeerror_type, jl_typename_str,
    jl_typename_type, jl_typeofbottom_type, jl_uint8_type, jl_uint16_type, jl_uint32_type,
    jl_uint64_type, jl_undefvarerror_type, jl_unionall_type, jl_uniontype_type, jl_vararg_type,
    jl_voidpointer_type,
};
use jlrs_macros::julia_version;
use jlrs_sys::{
    jlrs_datatype_abstract, jlrs_datatype_align, jlrs_datatype_first_ptr, jlrs_datatype_has_layout,
    jlrs_datatype_instance, jlrs_datatype_isinlinealloc, jlrs_datatype_layout,
    jlrs_datatype_mutable, jlrs_datatype_nfields, jlrs_datatype_parameters, jlrs_datatype_size,
    jlrs_datatype_super, jlrs_datatype_typename, jlrs_datatype_zeroinit, jlrs_field_isptr,
    jlrs_field_offset, jlrs_field_size, jlrs_get_fieldtypes, jlrs_is_concrete_type,
    jlrs_is_primitivetype, jlrs_isbits, jlrs_nparams,
};

use super::{Weak, type_name::TypeName, value::ValueData};
use crate::{
    convert::to_symbol::ToSymbol,
    data::{
        managed::{
            Managed, private::ManagedPriv, simple_vector::SimpleVector, symbol::Symbol,
            type_var::TypeVar, union_all::UnionAll, value::Value,
        },
        types::{construct_type::TypeVarEnv, typecheck::Typecheck},
    },
    impl_julia_typecheck,
    memory::{
        scope::LocalScopeExt,
        target::{Target, TargetResult, unrooted::Unrooted},
    },
    private::Private,
};

/// Julia type information.
///
/// You can access a [`Value`]'s datatype by by calling [`Value::datatype`].
///
/// To call a constructor, convert the `DataType` to a `Value` with [`Managed::as_value`] and call
/// it.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct DataType<'scope>(NonNull<jl_datatype_t>, PhantomData<&'scope ()>);

impl<'scope> DataType<'scope> {
    /// Returns the `TypeName` of this type.
    #[inline]
    pub fn type_name(self) -> TypeName<'scope> {
        // Safety: the pointer points to valid data, and the typename of a type never changes
        unsafe {
            let name = jlrs_datatype_typename(self.unwrap(Private));
            debug_assert!(!name.is_null());
            TypeName::wrap_non_null(NonNull::new_unchecked(name), Private)
        }
    }

    /// Returns the super-type of this type.
    #[inline]
    pub fn super_type(self) -> DataType<'scope> {
        // Safety: the pointer points to valid data, and the super-type of a type never changes
        unsafe {
            let super_ty = jlrs_datatype_super(self.unwrap(Private));
            debug_assert!(!super_ty.is_null());
            DataType::wrap_non_null(NonNull::new_unchecked(super_ty), Private)
        }
    }

    /// Returns the type parameters of this type.
    #[inline]
    pub fn parameters(self) -> SimpleVector<'scope> {
        // Safety: the pointer points to valid data and this data is const
        unsafe {
            let parameters = jlrs_datatype_parameters(self.unwrap(Private));
            debug_assert!(!parameters.is_null());
            SimpleVector::wrap_non_null(NonNull::new_unchecked(parameters), Private)
        }
    }

    /// Returns the number of type parameters.
    #[inline]
    pub fn n_parameters(self) -> usize {
        // Safety: the pointer points to valid data, the parameters field is never null
        unsafe { jlrs_nparams(self.unwrap(Private)) }
    }

    /// Returns the type parameter at position `idx`, or `None` if the index is out of bounds.
    #[inline]
    pub fn parameter(self, idx: usize) -> Option<Value<'scope, 'static>> {
        // Safety: the pointer points to valid data, the parameters field is never null
        unsafe {
            let unrooted = Unrooted::new();
            Some(self.parameters().data().get(unrooted, idx)?.as_value())
        }
    }

    /// Returns the type parameter at position `idx`.
    ///
    /// Safety: `idx` must be in-bounds and the parameter must not be a null pointer.
    #[inline]
    pub unsafe fn parameter_unchecked(self, idx: usize) -> Value<'scope, 'static> {
        unsafe {
            let unrooted = Unrooted::new();
            self.parameters()
                .data()
                .get(unrooted, idx)
                .unwrap_unchecked()
                .as_value()
        }
    }

    /// Returns `true` if this type has free type parameters.
    #[inline]
    pub fn has_free_type_vars(self) -> bool {
        unsafe { jl_has_free_typevars(self.unwrap(Private).cast()) != 0 }
    }

    /// Returns the field types of this type.
    #[inline]
    pub fn field_types(self) -> SimpleVector<'scope> {
        // Safety: the pointer points to valid data, the C API function is called with a valid argument
        unsafe {
            let field_types = jlrs_get_fieldtypes(self.unwrap(Private));
            debug_assert!(!field_types.is_null());
            SimpleVector::wrap_non_null(NonNull::new_unchecked(field_types), Private)
        }
    }

    /// Returns the field type of the field at position `idx`, or `None` if the index is out of
    /// bounds.
    #[inline]
    pub fn field_type(self, idx: usize) -> Option<Value<'scope, 'static>> {
        // Safety: the pointer points to valid data, the field_types field is never null
        unsafe {
            let unrooted = Unrooted::new();
            Some(self.field_types().data().get(unrooted, idx)?.as_value())
        }
    }

    /// Returns the field type of the field at position `idx` without performing a bounds check.
    ///
    /// Safety: `idx` must be in-bounds.
    #[inline]
    pub unsafe fn field_type_unchecked(self, idx: usize) -> Value<'scope, 'static> {
        unsafe {
            let unrooted = Unrooted::new();
            self.field_types()
                .data()
                .get(unrooted, idx)
                .unwrap_unchecked()
                .as_value()
        }
    }

    /// Returns the field names of this type.
    #[inline]
    pub fn field_names(self) -> SimpleVector<'scope> {
        // Safety: the pointer points to valid data, so it must have a TypeName.
        self.type_name().names()
    }

    /// Returns the name of the field at position `idx`.
    pub fn field_name(self, idx: usize) -> Option<Symbol<'scope>> {
        // Safety: the pointer points to valid data, so it must have a TypeName.
        unsafe {
            let unrooted = Unrooted::new();
            self.field_names()
                .typed_data_unchecked::<Symbol>()
                .get(unrooted, idx)
                .map(|s| s.as_managed())
        }
    }

    /// Returns the index of the field with the name `field_name`.
    pub fn field_index<N: ToSymbol>(self, field_name: N) -> Option<usize> {
        // Safety: the pointer points to valid data, the C API function is called with valid data
        let idx = unsafe {
            let sym = field_name.to_symbol_priv(Private);
            jl_field_index(self.unwrap(Private), sym.unwrap(Private), 0)
        };

        if idx < 0 {
            return None;
        }

        Some(idx as usize)
    }

    /// Returns the index of the field with the name `field_name`, if the field doesn't exist the
    /// result is `-1`.
    pub fn field_index_unchecked<N: ToSymbol>(self, field_name: N) -> i32 {
        // Safety: the pointer points to valid data, the C API function is called with valid data
        unsafe {
            let sym = field_name.to_symbol_priv(Private);
            jl_field_index(self.unwrap(Private), sym.unwrap(Private), 0)
        }
    }

    /// Returns the name of the field at position `idx`.
    #[inline]
    pub fn field_name_str(self, idx: usize) -> Option<&'scope str> {
        if let Some(sym) = self.field_name(idx) {
            return sym.as_str().ok();
        }

        None
    }

    /// Returns the instance if this type is a singleton.
    #[inline]
    pub fn instance(self) -> Option<Value<'scope, 'static>> {
        // Safety: the pointer points to valid data
        unsafe {
            let instance = jlrs_datatype_instance(self.unwrap(Private));
            if instance.is_null() {
                None
            } else {
                Some(Value::wrap_non_null(
                    NonNull::new_unchecked(instance),
                    Private,
                ))
            }
        }
    }

    /// Returns the size of a value of this type in bytes.
    #[inline]
    pub fn size(self) -> Option<u32> {
        unsafe {
            let t = self.unwrap(Private);
            if jlrs_datatype_has_layout(t) == 0 || jlrs_datatype_layout(t).is_null() {
                return None;
            }

            Some(jlrs_datatype_size(t))
        }
    }

    /// Returns true if this is an abstract type.
    #[inline]
    pub fn is_abstract(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_datatype_abstract(self.unwrap(Private)) != 0 }
    }

    /// Returns true if this is a mutable type.
    #[inline]
    pub fn mutable(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_datatype_mutable(self.unwrap(Private)) != 0 }
    }

    /// Returns true if this type can have instances
    #[inline]
    pub fn is_concrete_type(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_is_concrete_type(self.as_value().unwrap(Private)) != 0 }
    }

    /// Returns true if this type is a bits-type.
    #[inline]
    pub fn is_bits(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_isbits(self.unwrap(Private).cast()) != 0 }
    }

    /// Returns true if values of this type are zero-initialized.
    #[inline]
    pub fn zero_init(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_datatype_zeroinit(self.unwrap(Private)) != 0 }
    }

    /// Returns true if a value of this type stores its data inline.
    #[inline]
    pub fn is_inline_alloc(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_datatype_isinlinealloc(self.unwrap(Private)) != 0 }
    }

    /// Whether this is declared with 'primitive type' keyword (sized, no fields, and immutable)
    #[inline]
    pub fn is_primitive_type(self) -> bool {
        // Safety: the pointer points to valid data
        unsafe { jlrs_is_primitivetype(self.unwrap(Private).cast()) != 0 }
    }

    /// Performs the given typecheck on this type.
    #[inline]
    pub fn is<T: Typecheck>(self) -> bool {
        T::typecheck(self)
    }

    /// Returns the alignment of a value of this type in bytes.
    #[inline]
    pub fn align(self) -> Option<u16> {
        // Safety: the pointer points to valid data, if the layout is null the code
        // panics.
        if !self.has_layout() {
            return None;
        }

        unsafe { Some(jlrs_datatype_align(self.unwrap(Private))) }
    }

    /// Returns `true` if this type has a layout.
    #[inline]
    pub fn has_layout(self) -> bool {
        unsafe {
            jlrs_datatype_has_layout(self.unwrap(Private)) != 0
                && !jlrs_datatype_layout(self.unwrap(Private).cast()).is_null()
        }
    }

    /// Returns the size of a value of this type in bits.
    #[inline]
    pub fn n_bits(self) -> Option<u32> {
        Some(self.size()? * 8)
    }

    /// Returns the number of fields of a value of this type.
    #[inline]
    pub fn n_fields(self) -> Option<u32> {
        if !self.has_layout() {
            return None;
        }

        unsafe { Some(jlrs_datatype_nfields(self.unwrap(Private))) }
    }

    /// Returns the name of this type.
    #[inline]
    pub fn name(self) -> &'scope str {
        // Safety: the pointer points to valid data, so it must have a name. If it's not
        // a valid UTF-8 encoded string the code panics.
        unsafe {
            let name = jl_typename_str(self.unwrap(Private).cast());
            CStr::from_ptr(name).to_str().unwrap()
        }
    }

    /// Returns the size of the field at position `idx` in this type.
    pub fn field_size(self, idx: usize) -> Option<u32> {
        let n_fields = self.n_fields()?;
        if idx >= n_fields as usize {
            return None;
        }

        // Safety: the pointer points to valid data, and the field exists
        unsafe { Some(jlrs_field_size(self.unwrap(Private), idx as _)) }
    }

    /// Returns the size of the field at position `idx` in this type.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    #[inline]
    pub unsafe fn field_size_unchecked(self, idx: usize) -> u32 {
        unsafe { jlrs_field_size(self.unwrap(Private), idx as _) }
    }

    /// Returns the offset where the field at position `idx` is stored.
    pub fn field_offset(self, idx: usize) -> Option<u32> {
        let n_fields = self.n_fields()?;

        if idx >= n_fields as usize {
            return None;
        }

        // Safety: the pointer points to valid data, and the field exists
        unsafe { Some(jlrs_field_offset(self.unwrap(Private), idx as _)) }
    }

    /// Returns the offset where the field at position `idx` is stored.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    #[inline]
    pub unsafe fn field_offset_unchecked(self, idx: usize) -> u32 {
        unsafe { jlrs_field_offset(self.unwrap(Private), idx as _) }
    }

    /// Returns true if the field at position `idx` is stored as a pointer.
    pub fn is_pointer_field(self, idx: usize) -> Option<bool> {
        let n_fields = self.n_fields()?;
        if idx >= n_fields as usize {
            return None;
        }

        // Safety: the pointer points to valid data, and the field exists
        unsafe { Some(jlrs_field_isptr(self.unwrap(Private), idx as _) != 0) }
    }

    /// Returns true if the field at position `idx` is stored as a pointer.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    #[inline]
    pub unsafe fn is_pointer_field_unchecked(self, idx: usize) -> bool {
        unsafe { jlrs_field_isptr(self.unwrap(Private), idx as _) != 0 }
    }

    /// Returns true if the field at position `idx` is an atomic field.
    pub fn is_atomic_field(self, idx: usize) -> Option<bool> {
        let n_fields = self.n_fields()?;

        if idx >= n_fields as usize {
            return None;
        }

        // Safety: the pointer points to valid data, and the field exists
        unsafe { Some(self.is_atomic_field_unchecked(idx)) }
    }

    /// Returns true if the field at position `idx` is an atomic field.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    #[inline]
    pub unsafe fn is_atomic_field_unchecked(self, idx: usize) -> bool {
        unsafe {
            /*
                const uint32_t *atomicfields = st->name->atomicfields;
                if (atomicfields != NULL) {
                    if (atomicfields[i / 32] & (1 << (i % 32)))
                        return 1;
                }
                return 0;
            */
            let atomicfields = self.type_name().atomicfields();
            if atomicfields.is_null() {
                return false;
            }

            let isatomic = (*atomicfields.add(idx / 32)) & (1 << (idx % 32));
            isatomic != 0
        }
    }

    /// Returns true if the field at position `idx` is a constant field.
    pub fn is_const_field(self, idx: usize) -> Option<bool> {
        let n_fields = self.n_fields()?;

        if idx >= n_fields as usize {
            return None;
        }

        // Safety: the pointer points to valid data, and the field exists
        unsafe { Some(self.is_const_field_unchecked(idx)) }
    }

    /// Returns true if the field at position `idx` is a constant field.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function.
    #[inline]
    pub unsafe fn is_const_field_unchecked(self, idx: usize) -> bool {
        unsafe {
            /*
            jl_typename_t *tn = st->name;
            if (!tn->mutabl)
                return 1;
            const uint32_t *constfields = tn->constfields;
            if (constfields != NULL) {
                if (constfields[i / 32] & (1 << (i % 32)))
                    return 1;
            }
            return 0;
            */
            let tn = self.type_name();
            if !tn.is_mutable() {
                return true;
            }

            let constfields = tn.constfields();
            if constfields.is_null() {
                return false;
            }

            let isconst = (*constfields.add(idx / 32)) & (1 << (idx % 32));
            isconst != 0
        }
    }

    /// Create a new instance of this `DataType`, using `values` to set the fields.
    ///
    /// This method calls the function's `new` function, and throws an exception if the
    /// type cannot be instantiated.
    ///
    /// To call a constructor of the type, convert it to a `Value` and call it as a function.
    ///
    /// Safety: an exception must not be thrown if this method is called from a `ccall`ed
    /// function. Only `new` is called, not a constructor.
    #[deprecated(
        note = "This method will become private in the future, call the type's constructor instead by converting it to a `Value` and calling it as a function.",
        since = "0.23.0"
    )]
    #[inline]
    pub unsafe fn instantiate_unchecked<'target, 'value, 'data, V, Tgt>(
        self,
        target: Tgt,
        values: V,
    ) -> ValueData<'target, 'data, Tgt>
    where
        Tgt: Target<'target>,
        V: AsRef<[Value<'value, 'data>]>,
    {
        unsafe {
            let values = values.as_ref();
            let value = jl_new_structv(
                self.unwrap(Private),
                values.as_ptr() as *mut _,
                values.len() as _,
            );

            target.data_from_ptr(NonNull::new_unchecked(value), Private)
        }
    }

    #[inline]
    pub(crate) unsafe fn instantiate_unchecked_priv<'target, 'value, 'data, V, Tgt>(
        self,
        target: Tgt,
        values: V,
    ) -> ValueData<'target, 'data, Tgt>
    where
        Tgt: Target<'target>,
        V: AsRef<[Value<'value, 'data>]>,
    {
        unsafe {
            let values = values.as_ref();
            let value = jl_new_structv(
                self.unwrap(Private),
                values.as_ptr() as *mut _,
                values.len() as _,
            );

            target.data_from_ptr(NonNull::new_unchecked(value), Private)
        }
    }

    /// Returns `true` if this type has pointer fields.
    pub fn has_pointer_fields(self) -> Option<bool> {
        if !self.has_layout() {
            return None;
        }

        unsafe { Some(jlrs_datatype_first_ptr(self.unwrap(Private)) != -1) }
    }

    /// Wraps this type as a `UnionAll` if it has free `TypeVar`s, returns `self` otherwise.
    #[inline]
    pub fn rewrap<'target, Tgt: Target<'target>>(
        self,
        target: Tgt,
    ) -> ValueData<'target, 'static, Tgt> {
        UnionAll::rewrap(target, self)
    }
}

impl DataType<'_> {
    /// Returns `true` if the type depends on a type parameter outside its parameter list.
    pub fn has_indirect_typevar(self, tvar: TypeVar) -> bool {
        let params = self.parameters();
        let svec = params.data();
        unsafe {
            let unrooted = Unrooted::new();

            for pidx in 0..svec.len() {
                let param = svec.get(unrooted, pidx);
                let param = param.expect("encountered null param").as_value();
                if param.is::<TypeVar>() {
                    let param = param.cast_unchecked::<TypeVar>();
                    if param.has_indirect_typevar(tvar) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Wrap this type with an environment.
    pub fn wrap_with_env<'target, Tgt>(
        self,
        target: Tgt,
        env: &TypeVarEnv,
    ) -> ValueData<'target, 'static, Tgt>
    where
        Tgt: Target<'target>,
    {
        let svec = env.to_svec();
        let tvars = svec.data();
        target.with_local_scope::<_, 1>(|target, mut frame| {
            let mut reusable_slot = frame.reusable_slot();
            unsafe {
                let mut out = self.root(&mut reusable_slot).as_value();

                for tidx in (0..tvars.len()).rev() {
                    let Some(tv) = tvars.get(&reusable_slot, tidx) else {
                        continue;
                    };

                    let tv = tv.as_value();

                    // rooted via env
                    debug_assert!(tv.is::<TypeVar>());
                    let tv = tv.cast_unchecked::<TypeVar>();

                    if self.as_value().has_typevar(tv) {
                        out = UnionAll::new_unchecked(&mut reusable_slot, tv, out).as_value();
                    } else if self.has_indirect_typevar(tv) {
                        out = UnionAll::new_unchecked(&mut reusable_slot, tv, out).as_value();
                    }
                }

                out.root(target)
            }
        })
    }

    /// Returns `true` if this type depends on the `TypeVar` `tvar`.
    pub fn depends_on(&self, tvar: TypeVar) -> bool {
        let parameters = self.parameters();
        unsafe {
            let data = parameters.data();
            let slice = data.as_atomic_slice().assume_immutable_non_null();
            slice.iter().any(|v| v.depends_on(tvar))
        }
    }
}

impl<'target> DataType<'target> {
    /// The type of the bottom type, `Union{}`.
    #[inline]
    pub fn typeofbottom_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_typeofbottom_type), Private) }
    }

    /// The type `DataType`.
    #[inline]
    pub fn datatype_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_datatype_type), Private) }
    }

    /// The type `Union`.
    #[inline]
    pub fn uniontype_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_uniontype_type), Private) }
    }

    /// The type `UnionAll`.
    #[inline]
    pub fn unionall_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_unionall_type), Private) }
    }

    /// The type `TypeVar`.
    #[inline]
    pub fn tvar_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_tvar_type), Private) }
    }

    /// The type `Any`.
    #[inline]
    pub fn any_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_any_type), Private) }
    }

    /// The type `TypeName`.
    #[inline]
    pub fn typename_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_typename_type), Private) }
    }

    /// The type `Symbol`.
    #[inline]
    pub fn symbol_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_symbol_type), Private) }
    }

    /// The type `Core.Const`
    #[inline]
    pub fn const_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_const_type), Private) }
    }

    /// The type `SimpleVector`.
    #[inline]
    pub fn simplevector_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_simplevector_type), Private) }
    }

    /// The type `Tuple`.
    #[inline]
    pub fn anytuple_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_anytuple_type), Private) }
    }

    /// The type of an empty tuple.
    #[inline]
    pub fn emptytuple_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_emptytuple_type), Private) }
    }

    /// The type `Tuple`.
    #[inline]
    pub fn tuple_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_anytuple_type), Private) }
    }

    /// The type `Vararg`.
    #[inline]
    pub fn vararg_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { DataType::wrap_non_null(NonNull::new_unchecked(jl_vararg_type), Private) }
    }

    /// The type `Function`.
    #[inline]
    pub fn function_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_function_type), Private) }
    }

    /// The type `Module`.
    #[inline]
    pub fn module_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_module_type), Private) }
    }

    /// The type `AbstractString`.
    #[inline]
    pub fn abstractstring_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_abstractstring_type), Private) }
    }

    /// The type `String`.
    #[inline]
    pub fn string_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_string_type), Private) }
    }

    /// The type `ErrorException`.
    #[inline]
    pub fn errorexception_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_errorexception_type), Private) }
    }

    /// The type `ArgumentError`.
    #[inline]
    pub fn argumenterror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_argumenterror_type), Private) }
    }

    /// The type `LoadError`.
    #[inline]
    pub fn loaderror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_loaderror_type), Private) }
    }

    /// The type `InitError`.
    #[inline]
    pub fn initerror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_initerror_type), Private) }
    }

    /// The type `TypeError`.
    #[inline]
    pub fn typeerror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_typeerror_type), Private) }
    }

    /// The type `MethodError`.
    #[inline]
    pub fn methoderror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_methoderror_type), Private) }
    }

    /// The type `UndefVarError`.
    #[inline]
    pub fn undefvarerror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_undefvarerror_type), Private) }
    }

    /// The type `Core.AtomicError`.
    #[inline]
    pub fn atomicerror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_atomicerror_type), Private) }
    }

    /// The type `BoundsError`.
    #[inline]
    pub fn boundserror_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_boundserror_type), Private) }
    }

    /// The type `Bool`.
    #[inline]
    pub fn bool_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_bool_type), Private) }
    }

    /// The type `Char`.
    #[inline]
    pub fn char_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_char_type), Private) }
    }

    /// The type `Int8`.
    #[inline]
    pub fn int8_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_int8_type), Private) }
    }

    /// The type `UInt8`.
    #[inline]
    pub fn uint8_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_uint8_type), Private) }
    }

    /// The type `Int16`.
    #[inline]
    pub fn int16_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_int16_type), Private) }
    }

    /// The type `UInt16`.
    #[inline]
    pub fn uint16_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_uint16_type), Private) }
    }

    /// The type `Int32`.
    #[inline]
    pub fn int32_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_int32_type), Private) }
    }

    /// The type `UInt32`.
    #[inline]
    pub fn uint32_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_uint32_type), Private) }
    }

    /// The type `Int64`.
    #[inline]
    pub fn int64_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_int64_type), Private) }
    }

    /// The type `UInt64`.
    #[inline]
    pub fn uint64_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_uint64_type), Private) }
    }

    /// The type `Float16`.
    #[inline]
    pub fn float16_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_float16_type), Private) }
    }

    /// The type `Float32`.
    #[inline]
    pub fn float32_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_float32_type), Private) }
    }

    /// The type `Float64`.
    #[inline]
    pub fn float64_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_float64_type), Private) }
    }

    /// The type `AbstractFloat`.
    #[inline]
    pub fn floatingpoint_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_floatingpoint_type), Private) }
    }

    /// The type `Number`.
    #[inline]
    pub fn number_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_number_type), Private) }
    }

    /// The type `Nothing`.
    #[inline]
    pub fn nothing_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_nothing_type), Private) }
    }

    /// The type `Signed`.
    #[inline]
    pub fn signed_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_signed_type), Private) }
    }

    /// The type `Ptr{Nothing}`.
    #[inline]
    pub fn voidpointer_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_voidpointer_type), Private) }
    }

    /// The type `Task`.
    #[inline]
    pub fn task_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_task_type), Private) }
    }

    /// The type `Expr`.
    #[inline]
    pub fn expr_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_expr_type), Private) }
    }

    #[julia_version(since = "1.11")]
    /// The type `BFloat16`.
    #[inline]
    pub fn bfloat16_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe { Self::wrap_non_null(NonNull::new_unchecked(jl_sys::jl_bfloat16_type), Private) }
    }

    /// The type `Ptr{UInt8}`.
    #[inline]
    pub fn uint8pointer_type<Tgt>(_: &Tgt) -> Self
    where
        Tgt: Target<'target>,
    {
        // Safety: global constant
        unsafe {
            Self::wrap_non_null(
                NonNull::new_unchecked(jl_sys::jl_uint8pointer_type),
                Private,
            )
        }
    }
}

impl<'scope> PartialEq for DataType<'scope> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_value() == other.as_value()
    }
}

impl<'scope, 'data> PartialEq<Value<'scope, 'data>> for DataType<'scope> {
    #[inline]
    fn eq(&self, other: &Value<'scope, 'data>) -> bool {
        self.as_value() == *other
    }
}

impl<'scope> Eq for DataType<'scope> {}
impl_debug!(DataType<'_>);
impl_julia_typecheck!(DataType<'frame>, jl_datatype_type, 'frame);

impl<'scope> ManagedPriv<'scope, '_> for DataType<'scope> {
    type Wraps = jl_datatype_t;
    type WithLifetimes<'target, 'da> = DataType<'target>;
    const NAME: &'static str = "DataType";

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

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

impl_construct_type_managed!(DataType, 1, jl_datatype_type);

/// A [`DataType`] that has not been explicitly rooted.
pub type WeakDataType<'scope> = Weak<'scope, 'static, DataType<'scope>>;

/// A [`WeakDataType`] with static lifetimes. This is a useful shorthand for signatures of
/// `ccall`able functions that return a [`DataType`].
pub type DataTypeRet = WeakDataType<'static>;

impl_valid_layout!(WeakDataType, DataType, jl_datatype_type);

use crate::memory::target::TargetType;

/// `DataType` or `WeakDataType`, depending on the target type `Tgt`.
pub type DataTypeData<'target, Tgt> =
    <Tgt as TargetType<'target>>::Data<'static, DataType<'target>>;

/// `JuliaResult<DataType>` or `WeakJuliaResult<WeakDataType>`, depending on the target type `Tgt`.
pub type DataTypeResult<'target, Tgt> = TargetResult<'target, 'static, DataType<'target>, Tgt>;

impl_ccall_arg_managed!(DataType, 1);
impl_into_typed!(DataType);