Repository navigation
Expand file tree
/
Copy pathtype.rs
More file actions
2140 lines (1890 loc) · 74.1 KB
/
Copy pathtype.rs
File metadata and controls
2140 lines (1890 loc) · 74.1 KB
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
use super::{
PyClassMethod, PyDictRef, PyList, PyStr, PyStrInterned, PyStrRef, PyTupleRef, PyWeak,
mappingproxy::PyMappingProxy, object, union_,
};
use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
builtins::{
PyBaseExceptionRef,
descriptor::{
MemberGetter, MemberKind, MemberSetter, PyDescriptorOwned, PyMemberDef,
PyMemberDescriptor,
},
function::PyCellRef,
tuple::{IntoPyTuple, PyTuple},
},
class::{PyClassImpl, StaticType},
common::{
ascii,
borrow::BorrowedValue,
lock::{PyRwLock, PyRwLockReadGuard},
},
convert::ToPyResult,
function::{FuncArgs, KwArgs, OptionalArg, PyMethodDef, PySetterValue},
object::{Traverse, TraverseFn},
protocol::{PyIterReturn, PyNumberMethods},
types::{
AsNumber, Callable, Constructor, GetAttr, Initializer, PyTypeFlags, PyTypeSlots,
Representable, SLOT_DEFS, SetAttr, TypeDataRef, TypeDataRefMut, TypeDataSlot,
},
};
use core::{any::Any, borrow::Borrow, ops::Deref, pin::Pin, ptr::NonNull};
use indexmap::{IndexMap, map::Entry};
use itertools::Itertools;
use num_traits::ToPrimitive;
use std::collections::HashSet;
#[pyclass(module = false, name = "type", traverse = "manual")]
pub struct PyType {
pub base: Option<PyTypeRef>,
pub bases: PyRwLock<Vec<PyTypeRef>>,
pub mro: PyRwLock<Vec<PyTypeRef>>,
pub subclasses: PyRwLock<Vec<PyRef<PyWeak>>>,
pub attributes: PyRwLock<PyAttributes>,
pub slots: PyTypeSlots,
pub heaptype_ext: Option<Pin<Box<HeapTypeExt>>>,
}
unsafe impl crate::object::Traverse for PyType {
fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn<'_>) {
self.base.traverse(tracer_fn);
self.bases.traverse(tracer_fn);
// mro contains self as mro[0], so skip traversing to avoid circular reference
// self.mro.traverse(tracer_fn);
self.subclasses.traverse(tracer_fn);
self.attributes
.read_recursive()
.iter()
.map(|(_, v)| v.traverse(tracer_fn))
.count();
}
}
// PyHeapTypeObject in CPython
pub struct HeapTypeExt {
pub name: PyRwLock<PyStrRef>,
pub qualname: PyRwLock<PyStrRef>,
pub slots: Option<PyRef<PyTuple<PyStrRef>>>,
pub type_data: PyRwLock<Option<TypeDataSlot>>,
}
pub struct PointerSlot<T>(NonNull<T>);
unsafe impl<T> Sync for PointerSlot<T> {}
unsafe impl<T> Send for PointerSlot<T> {}
impl<T> PointerSlot<T> {
pub const unsafe fn borrow_static(&self) -> &'static T {
unsafe { self.0.as_ref() }
}
}
impl<T> Clone for PointerSlot<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for PointerSlot<T> {}
impl<T> From<&'static T> for PointerSlot<T> {
fn from(x: &'static T) -> Self {
Self(NonNull::from(x))
}
}
impl<T> AsRef<T> for PointerSlot<T> {
fn as_ref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
pub type PyTypeRef = PyRef<PyType>;
cfg_if::cfg_if! {
if #[cfg(feature = "threading")] {
unsafe impl Send for PyType {}
unsafe impl Sync for PyType {}
}
}
/// For attributes we do not use a dict, but an IndexMap, which is an Hash Table
/// that maintains order and is compatible with the standard HashMap This is probably
/// faster and only supports strings as keys.
pub type PyAttributes = IndexMap<&'static PyStrInterned, PyObjectRef, ahash::RandomState>;
unsafe impl Traverse for PyAttributes {
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
self.values().for_each(|v| v.traverse(tracer_fn));
}
}
impl core::fmt::Display for PyType {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(&self.name(), f)
}
}
impl core::fmt::Debug for PyType {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "[PyType {}]", &self.name())
}
}
impl PyPayload for PyType {
#[inline]
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.type_type
}
}
fn downcast_qualname(value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
match value.downcast::<PyStr>() {
Ok(value) => Ok(value),
Err(value) => Err(vm.new_type_error(format!(
"can only assign string to __qualname__, not '{}'",
value.class().name()
))),
}
}
fn is_subtype_with_mro(a_mro: &[PyTypeRef], a: &Py<PyType>, b: &Py<PyType>) -> bool {
if a.is(b) {
return true;
}
for item in a_mro {
if item.is(b) {
return true;
}
}
false
}
impl PyType {
pub fn new_simple_heap(
name: &str,
base: &Py<PyType>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
Self::new_heap(
name,
vec![base.to_owned()],
Default::default(),
Default::default(),
Self::static_type().to_owned(),
ctx,
)
}
pub fn new_heap(
name: &str,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
// TODO: ensure clean slot name
// assert_eq!(slots.name.borrow(), "");
// Set HEAPTYPE flag for heap-allocated types
slots.flags |= PyTypeFlags::HEAPTYPE;
let name = ctx.new_str(name);
let heaptype_ext = HeapTypeExt {
name: PyRwLock::new(name.clone()),
qualname: PyRwLock::new(name),
slots: None,
type_data: PyRwLock::new(None),
};
let base = bases[0].clone();
Self::new_heap_inner(base, bases, attrs, slots, heaptype_ext, metaclass, ctx)
}
/// Equivalent to CPython's PyType_Check macro
/// Checks if obj is an instance of type (or its subclass)
pub(crate) fn check(obj: &PyObject) -> Option<&Py<Self>> {
obj.downcast_ref::<Self>()
}
fn resolve_mro(bases: &[PyRef<Self>]) -> Result<Vec<PyTypeRef>, String> {
// Check for duplicates in bases.
let mut unique_bases = HashSet::new();
for base in bases {
if !unique_bases.insert(base.get_id()) {
return Err(format!("duplicate base class {}", base.name()));
}
}
let mros = bases
.iter()
.map(|base| base.mro_map_collect(|t| t.to_owned()))
.collect();
linearise_mro(mros)
}
/// Inherit SEQUENCE and MAPPING flags from base classes
/// Check all bases in order and inherit the first SEQUENCE or MAPPING flag found
fn inherit_patma_flags(slots: &mut PyTypeSlots, bases: &[PyRef<Self>]) {
const COLLECTION_FLAGS: PyTypeFlags = PyTypeFlags::from_bits_truncate(
PyTypeFlags::SEQUENCE.bits() | PyTypeFlags::MAPPING.bits(),
);
// If flags are already set, don't override
if slots.flags.intersects(COLLECTION_FLAGS) {
return;
}
// Check each base in order and inherit the first collection flag found
for base in bases {
let base_flags = base.slots.flags & COLLECTION_FLAGS;
if !base_flags.is_empty() {
slots.flags |= base_flags;
return;
}
}
}
/// Check for __abc_tpflags__ and set the appropriate flags
/// This checks in attrs and all base classes for __abc_tpflags__
fn check_abc_tpflags(
slots: &mut PyTypeSlots,
attrs: &PyAttributes,
bases: &[PyRef<Self>],
ctx: &Context,
) {
const COLLECTION_FLAGS: PyTypeFlags = PyTypeFlags::from_bits_truncate(
PyTypeFlags::SEQUENCE.bits() | PyTypeFlags::MAPPING.bits(),
);
// Don't override if flags are already set
if slots.flags.intersects(COLLECTION_FLAGS) {
return;
}
// First check in our own attributes
let abc_tpflags_name = ctx.intern_str("__abc_tpflags__");
if let Some(abc_tpflags_obj) = attrs.get(abc_tpflags_name)
&& let Some(int_obj) = abc_tpflags_obj.downcast_ref::<crate::builtins::int::PyInt>()
{
let flags_val = int_obj.as_bigint().to_i64().unwrap_or(0);
let abc_flags = PyTypeFlags::from_bits_truncate(flags_val as u64);
slots.flags |= abc_flags & COLLECTION_FLAGS;
return;
}
// Then check in base classes
for base in bases {
if let Some(abc_tpflags_obj) = base.find_name_in_mro(abc_tpflags_name)
&& let Some(int_obj) = abc_tpflags_obj.downcast_ref::<crate::builtins::int::PyInt>()
{
let flags_val = int_obj.as_bigint().to_i64().unwrap_or(0);
let abc_flags = PyTypeFlags::from_bits_truncate(flags_val as u64);
slots.flags |= abc_flags & COLLECTION_FLAGS;
return;
}
}
}
#[allow(clippy::too_many_arguments)]
fn new_heap_inner(
base: PyRef<Self>,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
heaptype_ext: HeapTypeExt,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
let mro = Self::resolve_mro(&bases)?;
// Inherit HAS_DICT from any base in MRO that has it
// (not just the first base, as any base with __dict__ means subclass needs it too)
if mro
.iter()
.any(|b| b.slots.flags.has_feature(PyTypeFlags::HAS_DICT))
{
slots.flags |= PyTypeFlags::HAS_DICT
}
// Inherit SEQUENCE and MAPPING flags from base classes
Self::inherit_patma_flags(&mut slots, &bases);
// Check for __abc_tpflags__ from ABCMeta (for collections.abc.Sequence, Mapping, etc.)
Self::check_abc_tpflags(&mut slots, &attrs, &bases, ctx);
if slots.basicsize == 0 {
slots.basicsize = base.slots.basicsize;
}
Self::inherit_readonly_slots(&mut slots, &base);
if let Some(qualname) = attrs.get(identifier!(ctx, __qualname__))
&& !qualname.fast_isinstance(ctx.types.str_type)
{
return Err(format!(
"type __qualname__ must be a str, not {}",
qualname.class().name()
));
}
let new_type = PyRef::new_ref(
Self {
base: Some(base),
bases: PyRwLock::new(bases),
mro: PyRwLock::new(mro),
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: Some(Pin::new(Box::new(heaptype_ext))),
},
metaclass,
None,
);
new_type.mro.write().insert(0, new_type.clone());
new_type.init_slots(ctx);
let weakref_type = super::PyWeak::static_type();
for base in new_type.bases.read().iter() {
base.subclasses.write().push(
new_type
.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(new_type)
}
pub fn new_static(
base: PyRef<Self>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
metaclass: PyRef<Self>,
) -> Result<PyRef<Self>, String> {
if base.slots.flags.has_feature(PyTypeFlags::HAS_DICT) {
slots.flags |= PyTypeFlags::HAS_DICT
}
// Inherit SEQUENCE and MAPPING flags from base class
// For static types, we only have a single base
Self::inherit_patma_flags(&mut slots, core::slice::from_ref(&base));
if slots.basicsize == 0 {
slots.basicsize = base.slots.basicsize;
}
Self::inherit_readonly_slots(&mut slots, &base);
let bases = PyRwLock::new(vec![base.clone()]);
let mro = base.mro_map_collect(|x| x.to_owned());
let new_type = PyRef::new_ref(
Self {
base: Some(base),
bases,
mro: PyRwLock::new(mro),
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: None,
},
metaclass,
None,
);
new_type.mro.write().insert(0, new_type.clone());
// Note: inherit_slots is called in PyClassImpl::init_class after
// slots are fully initialized by make_slots()
Self::set_new(&new_type.slots, &new_type.base);
let weakref_type = super::PyWeak::static_type();
for base in new_type.bases.read().iter() {
base.subclasses.write().push(
new_type
.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(new_type)
}
pub(crate) fn init_slots(&self, ctx: &Context) {
// Inherit slots from MRO (mro[0] is self, so skip it)
let mro: Vec<_> = self.mro.read()[1..].to_vec();
for base in mro.iter() {
self.inherit_slots(base);
}
// Wire dunder methods to slots
#[allow(clippy::mutable_key_type)]
let mut slot_name_set = std::collections::HashSet::new();
// mro[0] is self, so skip it; self.attributes is checked separately below
for cls in self.mro.read()[1..].iter() {
for &name in cls.attributes.read().keys() {
if name.as_bytes().starts_with(b"__") && name.as_bytes().ends_with(b"__") {
slot_name_set.insert(name);
}
}
}
for &name in self.attributes.read().keys() {
if name.as_bytes().starts_with(b"__") && name.as_bytes().ends_with(b"__") {
slot_name_set.insert(name);
}
}
// Sort for deterministic iteration order (important for slot processing)
let mut slot_names: Vec<_> = slot_name_set.into_iter().collect();
slot_names.sort_by_key(|name| name.as_str());
for attr_name in slot_names {
self.update_slot::<true>(attr_name, ctx);
}
Self::set_new(&self.slots, &self.base);
}
fn set_new(slots: &PyTypeSlots, base: &Option<PyTypeRef>) {
if slots.flags.contains(PyTypeFlags::DISALLOW_INSTANTIATION) {
slots.new.store(None)
} else if slots.new.load().is_none() {
slots.new.store(
base.as_ref()
.map(|base| base.slots.new.load())
.unwrap_or(None),
)
}
}
/// Inherit readonly slots from base type at creation time.
/// These slots are not AtomicCell and must be set before the type is used.
fn inherit_readonly_slots(slots: &mut PyTypeSlots, base: &Self) {
if slots.as_buffer.is_none() {
slots.as_buffer = base.slots.as_buffer;
}
}
/// Inherit slots from base type. inherit_slots
pub(crate) fn inherit_slots(&self, base: &Self) {
// Use SLOT_DEFS to iterate all slots
// Note: as_buffer is handled in inherit_readonly_slots (not AtomicCell)
for def in SLOT_DEFS {
def.accessor.copyslot_if_none(self, base);
}
}
// This is used for class initialization where the vm is not yet available.
pub fn set_str_attr<V: Into<PyObjectRef>>(
&self,
attr_name: &str,
value: V,
ctx: impl AsRef<Context>,
) {
let ctx = ctx.as_ref();
let attr_name = ctx.intern_str(attr_name);
self.set_attr(attr_name, value.into())
}
pub fn set_attr(&self, attr_name: &'static PyStrInterned, value: PyObjectRef) {
self.attributes.write().insert(attr_name, value);
}
/// This is the internal get_attr implementation for fast lookup on a class.
pub fn get_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
flame_guard!(format!("class_get_attr({:?})", attr_name));
self.get_direct_attr(attr_name)
.or_else(|| self.get_super_attr(attr_name))
}
pub fn get_direct_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
self.attributes.read().get(attr_name).cloned()
}
/// Equivalent to CPython's find_name_in_mro
/// Look in tp_dict of types in MRO - bypasses descriptors and other attribute access machinery
fn find_name_in_mro(&self, name: &'static PyStrInterned) -> Option<PyObjectRef> {
// mro[0] is self, so we just iterate through the entire MRO
for cls in self.mro.read().iter() {
if let Some(value) = cls.attributes.read().get(name) {
return Some(value.clone());
}
}
None
}
/// Equivalent to CPython's _PyType_LookupRef
/// Looks up a name through the MRO without setting an exception
pub fn lookup_ref(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> Option<PyObjectRef> {
// Get interned name for efficient lookup
let interned_name = vm.ctx.interned_str(name)?;
// Use find_name_in_mro which matches CPython's behavior
// This bypasses descriptors and other attribute access machinery
self.find_name_in_mro(interned_name)
}
pub fn get_super_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
self.mro.read()[1..]
.iter()
.find_map(|class| class.attributes.read().get(attr_name).cloned())
}
// This is the internal has_attr implementation for fast lookup on a class.
pub fn has_attr(&self, attr_name: &'static PyStrInterned) -> bool {
self.attributes.read().contains_key(attr_name)
|| self.mro.read()[1..]
.iter()
.any(|c| c.attributes.read().contains_key(attr_name))
}
pub fn get_attributes(&self) -> PyAttributes {
// Gather all members here:
let mut attributes = PyAttributes::default();
// mro[0] is self, so we iterate through the entire MRO in reverse
for bc in self.mro.read().iter().map(|cls| -> &Self { cls }).rev() {
for (name, value) in bc.attributes.read().iter() {
attributes.insert(name.to_owned(), value.clone());
}
}
attributes
}
// bound method for every type
pub(crate) fn __new__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let (subtype, args): (PyRef<Self>, FuncArgs) = args.bind(vm)?;
if !subtype.fast_issubclass(&zelf) {
return Err(vm.new_type_error(format!(
"{zelf}.__new__({subtype}): {subtype} is not a subtype of {zelf}",
zelf = zelf.name(),
subtype = subtype.name(),
)));
}
call_slot_new(zelf, subtype, args, vm)
}
fn name_inner<'a, R: 'a>(
&'a self,
static_f: impl FnOnce(&'static str) -> R,
heap_f: impl FnOnce(&'a HeapTypeExt) -> R,
) -> R {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
static_f(self.slots.name)
} else {
heap_f(self.heaptype_ext.as_ref().unwrap())
}
}
pub fn slot_name(&self) -> BorrowedValue<'_, str> {
self.name_inner(
|name| name.into(),
|ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(),
)
}
pub fn name(&self) -> BorrowedValue<'_, str> {
self.name_inner(
|name| name.rsplit_once('.').map_or(name, |(_, name)| name).into(),
|ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(),
)
}
// Type Data Slot API - CPython's PyObject_GetTypeData equivalent
/// Initialize type data for this type. Can only be called once.
/// Returns an error if the type is not a heap type or if data is already initialized.
pub fn init_type_data<T: Any + Send + Sync + 'static>(&self, data: T) -> Result<(), String> {
let ext = self
.heaptype_ext
.as_ref()
.ok_or_else(|| "Cannot set type data on non-heap types".to_string())?;
let mut type_data = ext.type_data.write();
if type_data.is_some() {
return Err("Type data already initialized".to_string());
}
*type_data = Some(TypeDataSlot::new(data));
Ok(())
}
/// Get a read guard to the type data.
/// Returns None if the type is not a heap type, has no data, or the data type doesn't match.
pub fn get_type_data<T: Any + 'static>(&self) -> Option<TypeDataRef<'_, T>> {
self.heaptype_ext
.as_ref()
.and_then(|ext| TypeDataRef::try_new(ext.type_data.read()))
}
/// Get a write guard to the type data.
/// Returns None if the type is not a heap type, has no data, or the data type doesn't match.
pub fn get_type_data_mut<T: Any + 'static>(&self) -> Option<TypeDataRefMut<'_, T>> {
self.heaptype_ext
.as_ref()
.and_then(|ext| TypeDataRefMut::try_new(ext.type_data.write()))
}
/// Check if this type has type data of the given type.
pub fn has_type_data<T: Any + 'static>(&self) -> bool {
self.heaptype_ext.as_ref().is_some_and(|ext| {
ext.type_data
.read()
.as_ref()
.is_some_and(|slot| slot.get::<T>().is_some())
})
}
}
impl Py<PyType> {
pub(crate) fn is_subtype(&self, other: &Self) -> bool {
is_subtype_with_mro(&self.mro.read(), self, other)
}
/// Equivalent to CPython's PyType_CheckExact macro
/// Checks if obj is exactly a type (not a subclass)
pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Self> {
obj.downcast_ref_if_exact::<PyType>(vm)
}
/// Determines if `subclass` is actually a subclass of `cls`, this doesn't call __subclasscheck__,
/// so only use this if `cls` is known to have not overridden the base __subclasscheck__ magic
/// method.
pub fn fast_issubclass(&self, cls: &impl Borrow<PyObject>) -> bool {
self.as_object().is(cls.borrow()) || self.mro.read()[1..].iter().any(|c| c.is(cls.borrow()))
}
pub fn mro_map_collect<F, R>(&self, f: F) -> Vec<R>
where
F: Fn(&Self) -> R,
{
self.mro.read().iter().map(|x| x.deref()).map(f).collect()
}
pub fn mro_collect(&self) -> Vec<PyRef<PyType>> {
self.mro
.read()
.iter()
.map(|x| x.deref())
.map(|x| x.to_owned())
.collect()
}
pub fn iter_base_chain(&self) -> impl Iterator<Item = &Self> {
core::iter::successors(Some(self), |cls| cls.base.as_deref())
}
pub fn extend_methods(&'static self, method_defs: &'static [PyMethodDef], ctx: &Context) {
for method_def in method_defs {
let method = method_def.to_proper_method(self, ctx);
self.set_attr(ctx.intern_str(method_def.name), method);
}
}
}
#[pyclass(
with(
Py,
Constructor,
Initializer,
GetAttr,
SetAttr,
Callable,
AsNumber,
Representable
),
flags(BASETYPE)
)]
impl PyType {
#[pygetset]
fn __bases__(&self, vm: &VirtualMachine) -> PyTupleRef {
vm.ctx.new_tuple(
self.bases
.read()
.iter()
.map(|x| x.as_object().to_owned())
.collect(),
)
}
#[pygetset(setter, name = "__bases__")]
fn set_bases(zelf: &Py<Self>, bases: Vec<PyTypeRef>, vm: &VirtualMachine) -> PyResult<()> {
// TODO: Assigning to __bases__ is only used in typing.NamedTupleMeta.__new__
// Rather than correctly re-initializing the class, we are skipping a few steps for now
if zelf.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__bases__' attribute of immutable type '{}'",
zelf.name()
)));
}
if bases.is_empty() {
return Err(vm.new_type_error(format!(
"can only assign non-empty tuple to %s.__bases__, not {}",
zelf.name()
)));
}
// TODO: check for mro cycles
// TODO: Remove this class from all subclass lists
// for base in self.bases.read().iter() {
// let subclasses = base.subclasses.write();
// // TODO: how to uniquely identify the subclasses to remove?
// }
*zelf.bases.write() = bases;
// Recursively update the mros of this class and all subclasses
fn update_mro_recursively(cls: &PyType, vm: &VirtualMachine) -> PyResult<()> {
let mut mro =
PyType::resolve_mro(&cls.bases.read()).map_err(|msg| vm.new_type_error(msg))?;
// Preserve self (mro[0]) when updating MRO
mro.insert(0, cls.mro.read()[0].to_owned());
*cls.mro.write() = mro;
for subclass in cls.subclasses.write().iter() {
let subclass = subclass.upgrade().unwrap();
let subclass: &Py<PyType> = subclass.downcast_ref().unwrap();
update_mro_recursively(subclass, vm)?;
}
Ok(())
}
update_mro_recursively(zelf, vm)?;
// TODO: do any old slots need to be cleaned up first?
zelf.init_slots(&vm.ctx);
// Register this type as a subclass of its new bases
let weakref_type = super::PyWeak::static_type();
for base in zelf.bases.read().iter() {
base.subclasses.write().push(
zelf.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(())
}
#[pygetset]
fn __base__(&self) -> Option<PyTypeRef> {
self.base.clone()
}
#[pygetset]
const fn __flags__(&self) -> u64 {
self.slots.flags.bits()
}
#[pygetset]
fn __basicsize__(&self) -> usize {
crate::object::SIZEOF_PYOBJECT_HEAD + self.slots.basicsize
}
#[pygetset]
fn __itemsize__(&self) -> usize {
self.slots.itemsize
}
#[pygetset]
pub fn __name__(&self, vm: &VirtualMachine) -> PyStrRef {
self.name_inner(
|name| {
vm.ctx
.interned_str(name.rsplit_once('.').map_or(name, |(_, name)| name))
.unwrap_or_else(|| {
panic!(
"static type name must be already interned but {} is not",
self.slot_name()
)
})
.to_owned()
},
|ext| ext.name.read().clone(),
)
}
#[pygetset]
pub fn __qualname__(&self, vm: &VirtualMachine) -> PyObjectRef {
if let Some(ref heap_type) = self.heaptype_ext {
heap_type.qualname.read().clone().into()
} else {
// For static types, return the name
vm.ctx.new_str(self.name().deref()).into()
}
}
#[pygetset(setter)]
fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
// TODO: we should replace heaptype flag check to immutable flag check
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__qualname__' attribute of immutable type '{}'",
self.name()
)));
};
let value = value.ok_or_else(|| {
vm.new_type_error(format!(
"cannot delete '__qualname__' attribute of immutable type '{}'",
self.name()
))
})?;
let str_value = downcast_qualname(value, vm)?;
let heap_type = self
.heaptype_ext
.as_ref()
.expect("HEAPTYPE should have heaptype_ext");
// Use std::mem::replace to swap the new value in and get the old value out,
// then drop the old value after releasing the lock
let _old_qualname = {
let mut qualname_guard = heap_type.qualname.write();
core::mem::replace(&mut *qualname_guard, str_value)
};
// old_qualname is dropped here, outside the lock scope
Ok(())
}
#[pygetset]
fn __annotations__(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_attribute_error(format!(
"type object '{}' has no attribute '__annotations__'",
self.name()
)));
}
let __annotations__ = identifier!(vm, __annotations__);
let annotations = self.attributes.read().get(__annotations__).cloned();
let annotations = if let Some(annotations) = annotations {
annotations
} else {
let annotations: PyObjectRef = vm.ctx.new_dict().into();
let removed = self
.attributes
.write()
.insert(__annotations__, annotations.clone());
debug_assert!(removed.is_none());
annotations
};
Ok(annotations)
}
#[pygetset(setter)]
fn set___annotations__(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__annotations__' attribute of immutable type '{}'",
self.name()
)));
}
let __annotations__ = identifier!(vm, __annotations__);
if let Some(value) = value {
self.attributes.write().insert(__annotations__, value);
} else {
self.attributes
.read()
.get(__annotations__)
.cloned()
.ok_or_else(|| {
vm.new_attribute_error(format!(
"'{}' object has no attribute '__annotations__'",
self.name()
))
})?;
}
Ok(())
}
#[pygetset]
pub fn __module__(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __module__))
.cloned()
// We need to exclude this method from going into recursion:
.and_then(|found| {
if found.fast_isinstance(vm.ctx.types.getset_type) {
None
} else {
Some(found)
}
})
.unwrap_or_else(|| vm.ctx.new_str(ascii!("builtins")).into())
}
#[pygetset(setter)]
fn set___module__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_set_special_type_attr(identifier!(vm, __module__), vm)?;
self.attributes
.write()
.insert(identifier!(vm, __module__), value);
Ok(())
}
#[pyclassmethod]
fn __prepare__(
_cls: PyTypeRef,
_name: OptionalArg<PyObjectRef>,
_bases: OptionalArg<PyObjectRef>,
_kwargs: KwArgs,
vm: &VirtualMachine,
) -> PyDictRef {
vm.ctx.new_dict()
}
#[pymethod]
fn __subclasses__(&self) -> PyList {
let mut subclasses = self.subclasses.write();
subclasses.retain(|x| x.upgrade().is_some());
PyList::from(
subclasses
.iter()
.map(|x| x.upgrade().unwrap())
.collect::<Vec<_>>(),
)
}
pub fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(other, zelf, vm)
}
pub fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(zelf, other, vm)
}
#[pygetset]
fn __dict__(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf)
}
#[pygetset(setter)]
fn set___dict__(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
Err(vm.new_not_implemented_error(
"Setting __dict__ attribute on a type isn't yet implemented",
))
}
fn check_set_special_type_attr(
&self,
name: &PyStrInterned,
vm: &VirtualMachine,
) -> PyResult<()> {
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '{}' attribute of immutable type '{}'",
name,
self.slot_name()
)));
}
Ok(())
}
#[pygetset(setter)]
fn set___name__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_set_special_type_attr(identifier!(vm, __name__), vm)?;
let name = value.downcast::<PyStr>().map_err(|value| {
vm.new_type_error(format!(
"can only assign string to {}.__name__, not '{}'",
self.slot_name(),
value.class().slot_name(),
))