forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype.rs
More file actions
1317 lines (1171 loc) · 42.2 KB
/
type.rs
File metadata and controls
1317 lines (1171 loc) · 42.2 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::{
mappingproxy::PyMappingProxy, object, union_, PyClassMethod, PyDictRef, PyList, PyStaticMethod,
PyStr, PyStrInterned, PyStrRef, PyTuple, PyTupleRef, PyWeak,
};
use crate::common::{
ascii,
borrow::BorrowedValue,
lock::{PyRwLock, PyRwLockReadGuard},
};
use crate::{
builtins::{
descriptor::{
DescrObject, MemberDef, MemberDescrObject, MemberGetter, MemberKind, MemberSetter,
},
function::PyCellRef,
tuple::{IntoPyTuple, PyTupleTyped},
PyBaseExceptionRef,
},
class::{PyClassImpl, StaticType},
convert::ToPyObject,
function::{FuncArgs, KwArgs, OptionalArg, PySetterValue},
identifier,
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
types::{Callable, GetAttr, PyTypeFlags, PyTypeSlots, SetAttr},
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
};
use indexmap::{map::Entry, IndexMap};
use itertools::Itertools;
use std::{borrow::Borrow, collections::HashSet, fmt, ops::Deref, pin::Pin, ptr::NonNull};
#[pyclass(module = false, name = "type")]
pub struct PyType {
pub base: Option<PyTypeRef>,
pub bases: Vec<PyTypeRef>,
pub mro: Vec<PyTypeRef>,
pub subclasses: PyRwLock<Vec<PyRef<PyWeak>>>,
pub attributes: PyRwLock<PyAttributes>,
pub slots: PyTypeSlots,
pub heaptype_ext: Option<Pin<Box<HeapTypeExt>>>,
}
#[derive(Default)]
pub struct HeapTypeExt {
pub slots: Option<PyTupleTyped<PyStrRef>>,
pub number_methods: PyNumberMethods,
pub sequence_methods: PySequenceMethods,
pub mapping_methods: PyMappingMethods,
}
pub struct PointerSlot<T>(NonNull<T>);
impl<T> PointerSlot<T> {
pub unsafe fn borrow_static(&self) -> &'static T {
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() }
}
}
impl<T> PointerSlot<T> {
pub unsafe fn from_heaptype<F>(typ: &PyType, f: F) -> Option<Self>
where
F: FnOnce(&HeapTypeExt) -> &T,
{
typ.heaptype_ext
.as_ref()
.map(|ext| Self(NonNull::from(f(ext))))
}
}
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>;
impl fmt::Display for PyType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.name(), f)
}
}
impl fmt::Debug for PyType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[PyType {}]", &self.name())
}
}
impl PyPayload for PyType {
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
vm.ctx.types.type_type
}
}
impl PyType {
pub fn new_simple_ref(
name: &str,
base: &PyTypeRef,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
Self::new_ref(
name,
vec![base.clone()],
Default::default(),
Default::default(),
Self::static_type().to_owned(),
ctx,
)
}
pub fn new_ref(
name: &str,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
slots: PyTypeSlots,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
Self::new_verbose_ref(
name,
bases[0].clone(),
bases,
attrs,
slots,
HeapTypeExt::default(),
metaclass,
ctx,
)
}
#[allow(clippy::too_many_arguments)]
fn new_verbose_ref(
name: &str,
base: PyRef<Self>,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
heaptype_ext: HeapTypeExt,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, 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(|x| x.iter_mro().map(|x| x.to_owned()).collect())
.collect();
let mro = linearise_mro(mros)?;
if base.slots.flags.has_feature(PyTypeFlags::HAS_DICT) {
slots.flags |= PyTypeFlags::HAS_DICT
}
*slots.name.get_mut() = Some(String::from(name));
#[allow(clippy::mutable_key_type)]
let mut slot_name_set = HashSet::new();
for cls in mro.iter() {
for &name in cls.attributes.read().keys() {
if name != identifier!(ctx, __new__)
&& name.as_str().starts_with("__")
&& name.as_str().ends_with("__")
{
slot_name_set.insert(name);
}
}
}
for &name in attrs.keys() {
if name.as_str().starts_with("__") && name.as_str().ends_with("__") {
slot_name_set.insert(name);
}
}
let new_type = PyRef::new_ref(
PyType {
base: Some(base),
bases,
mro,
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: Some(Pin::new(Box::new(heaptype_ext))),
},
metaclass,
None,
);
for attr_name in slot_name_set {
new_type.update_slot::<true>(attr_name, ctx);
}
let weakref_type = super::PyWeak::static_type();
for base in &new_type.bases {
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_bare_ref(
name: &str,
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
}
*slots.name.get_mut() = Some(String::from(name));
let bases = vec![base.clone()];
let mro = base.iter_mro().map(|x| x.to_owned()).collect();
let new_type = PyRef::new_ref(
PyType {
base: Some(base),
bases,
mro,
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: None,
},
metaclass,
None,
);
let weakref_type = super::PyWeak::static_type();
for base in &new_type.bases {
base.subclasses.write().push(
new_type
.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(new_type)
}
pub fn slot_name(&self) -> String {
self.slots.name.read().as_ref().unwrap().to_string()
}
pub fn iter_mro(&self) -> impl Iterator<Item = &PyType> + DoubleEndedIterator {
std::iter::once(self).chain(self.mro.iter().map(|cls| -> &PyType { cls }))
}
pub(crate) fn mro_find_map<F, R>(&self, f: F) -> Option<R>
where
F: Fn(&Self) -> Option<R>,
{
// the hot path will be primitive types which usually hit the result from itself.
// try std::intrinsics::likely once it is stablized
if let Some(r) = f(self) {
Some(r)
} else {
self.mro.iter().find_map(|cls| f(cls))
}
}
// This is used for class initialisation 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 attr_name = ctx.as_ref().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()
}
pub fn get_super_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
self.mro
.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
.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();
for bc in self.iter_mro().rev() {
for (name, value) in bc.attributes.read().iter() {
attributes.insert(name.to_owned(), value.clone());
}
}
attributes
}
}
impl Py<PyType> {
/// 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<crate::PyObject>) -> bool {
self.as_object().is(cls.borrow()) || self.mro.iter().any(|c| c.is(cls.borrow()))
}
pub fn iter_mro(&self) -> impl Iterator<Item = &Py<PyType>> + DoubleEndedIterator {
std::iter::once(self).chain(self.mro.iter().map(|x| x.deref()))
}
pub fn iter_base_chain(&self) -> impl Iterator<Item = &Py<PyType>> {
std::iter::successors(Some(self), |cls| cls.base.as_deref())
}
}
#[pyclass(with(GetAttr, SetAttr, Callable), flags(BASETYPE))]
impl PyType {
// 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)
}
#[pygetset(name = "__mro__")]
fn get_mro(zelf: PyRef<Self>) -> PyTuple {
let elements: Vec<PyObjectRef> =
zelf.iter_mro().map(|x| x.as_object().to_owned()).collect();
PyTuple::new_unchecked(elements.into_boxed_slice())
}
#[pygetset(magic)]
fn bases(&self, vm: &VirtualMachine) -> PyTupleRef {
vm.ctx.new_tuple(
self.bases
.iter()
.map(|x| x.as_object().to_owned())
.collect(),
)
}
#[pygetset(magic)]
fn base(&self) -> Option<PyTypeRef> {
self.base.clone()
}
#[pygetset(magic)]
fn flags(&self) -> u64 {
self.slots.flags.bits()
}
#[pymethod(magic)]
fn dir(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyList {
let attributes: Vec<PyObjectRef> = zelf
.get_attributes()
.into_iter()
.map(|(k, _)| k.to_object())
.collect();
PyList::from(attributes)
}
#[pymethod(magic)]
fn instancecheck(zelf: PyRef<Self>, obj: PyObjectRef) -> bool {
obj.fast_isinstance(&zelf)
}
#[pymethod(magic)]
fn subclasscheck(zelf: PyRef<Self>, subclass: PyTypeRef) -> bool {
subclass.fast_issubclass(&zelf)
}
#[pyclassmethod(magic)]
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pygetset]
fn __name__(&self) -> String {
self.name().to_string()
}
pub fn name(&self) -> BorrowedValue<str> {
PyRwLockReadGuard::map(self.slots.name.read(), |slot_name| {
let name = slot_name.as_ref().unwrap();
if self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
name.as_str()
} else {
name.rsplit('.').next().unwrap()
}
})
.into()
}
#[pymethod(magic)]
fn repr(&self, vm: &VirtualMachine) -> String {
let module = self.module(vm);
let module = module.downcast_ref::<PyStr>().map(|m| m.as_str());
match module {
Some(module) if module != "builtins" => {
let name = self.name();
format!(
"<class '{}.{}'>",
module,
self.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str())
.unwrap_or_else(|| &name)
)
}
_ => format!("<class '{}'>", self.slot_name()),
}
}
#[pygetset(magic)]
pub fn qualname(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __qualname__))
.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(self.name().deref()).into())
}
#[pygetset(magic, 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()
))
})?;
if !value.class().fast_issubclass(vm.ctx.types.str_type) {
return Err(vm.new_type_error(format!(
"can only assign string to {}.__qualname__, not '{}'",
self.name(),
value.class().name()
)));
}
self.attributes
.write()
.insert(identifier!(vm, __qualname__), value);
Ok(())
}
#[pygetset(magic)]
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(magic, 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(magic)]
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(magic, setter)]
fn set_module(&self, value: PyObjectRef, vm: &VirtualMachine) {
self.attributes
.write()
.insert(identifier!(vm, __module__), value);
}
#[pyclassmethod(magic)]
fn prepare(
_cls: PyTypeRef,
_name: OptionalArg<PyObjectRef>,
_bases: OptionalArg<PyObjectRef>,
_kwargs: KwArgs,
vm: &VirtualMachine,
) -> PyDictRef {
vm.ctx.new_dict()
}
#[pymethod(magic)]
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<_>>(),
)
}
#[pymethod]
fn mro(zelf: PyRef<Self>) -> Vec<PyObjectRef> {
zelf.iter_mro().map(|cls| cls.to_owned().into()).collect()
}
#[pymethod(magic)]
pub fn ror(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(other, zelf, vm)
}
#[pymethod(magic)]
pub fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(zelf, other, vm)
}
#[pyslot]
fn slot_new(metatype: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type.__new__ {:?}", args);
let is_type_type = metatype.is(vm.ctx.types.type_type);
if is_type_type && args.args.len() == 1 && args.kwargs.is_empty() {
return Ok(args.args[0].class().to_owned().into());
}
if args.args.len() != 3 {
return Err(vm.new_type_error(if is_type_type {
"type() takes 1 or 3 arguments".to_owned()
} else {
format!(
"type.__new__() takes exactly 3 arguments ({} given)",
args.args.len()
)
}));
}
let (name, bases, dict, kwargs): (PyStrRef, PyTupleRef, PyDictRef, KwArgs) =
args.clone().bind(vm)?;
if name.as_str().contains(char::from(0)) {
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
}
let (metatype, base, bases) = if bases.is_empty() {
let base = vm.ctx.types.object_type.to_owned();
(metatype, base.clone(), vec![base])
} else {
let bases = bases
.iter()
.map(|obj| {
obj.clone().downcast::<PyType>().or_else(|obj| {
if vm
.get_attribute_opt(obj, identifier!(vm, __mro_entries__))?
.is_some()
{
Err(vm.new_type_error(
"type() doesn't support MRO entry resolution; \
use types.new_class()"
.to_owned(),
))
} else {
Err(vm.new_type_error("bases must be types".to_owned()))
}
})
})
.collect::<PyResult<Vec<_>>>()?;
// Search the bases for the proper metatype to deal with this:
let winner = calculate_meta_class(metatype.clone(), &bases, vm)?;
let metatype = if !winner.is(&metatype) {
if let Some(ref slot_new) = winner.slots.new.load() {
// Pass it to the winner
return slot_new(winner, args, vm);
}
winner
} else {
metatype
};
let base = best_base(&bases, vm)?;
(metatype, base, bases)
};
let mut attributes = dict.to_attributes(vm);
if let Some(f) = attributes.get_mut(identifier!(vm, __new__)) {
if f.class().is(vm.ctx.types.function_type) {
*f = PyStaticMethod::from(f.clone()).into_pyobject(vm);
}
}
if let Some(f) = attributes.get_mut(identifier!(vm, __init_subclass__)) {
if f.class().is(vm.ctx.types.function_type) {
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
}
}
if let Some(f) = attributes.get_mut(identifier!(vm, __class_getitem__)) {
if f.class().is(vm.ctx.types.function_type) {
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
}
}
if let Some(current_frame) = vm.current_frame() {
let entry = attributes.entry(identifier!(vm, __module__));
if matches!(entry, Entry::Vacant(_)) {
let module_name = vm.unwrap_or_none(
current_frame
.globals
.get_item_opt(identifier!(vm, __name__), vm)?,
);
entry.or_insert(module_name);
}
}
attributes
.entry(identifier!(vm, __qualname__))
.or_insert_with(|| vm.ctx.new_str(name.as_str()).into());
// All *classes* should have a dict. Exceptions are *instances* of
// classes that define __slots__ and instances of built-in classes
// (with exceptions, e.g function)
let __dict__ = identifier!(vm, __dict__);
attributes.entry(__dict__).or_insert_with(|| {
vm.ctx
.new_getset(
"__dict__",
vm.ctx.types.object_type,
subtype_get_dict,
subtype_set_dict,
)
.into()
});
// TODO: Flags is currently initialized with HAS_DICT. Should be
// updated when __slots__ are supported (toggling the flag off if
// a class has __slots__ defined).
let heaptype_slots: Option<PyTupleTyped<PyStrRef>> =
if let Some(x) = attributes.get(identifier!(vm, __slots__)) {
Some(if x.to_owned().class().is(vm.ctx.types.str_type) {
PyTupleTyped::<PyStrRef>::try_from_object(
vm,
vec![x.to_owned()].into_pytuple(vm).into(),
)?
} else {
let iter = x.to_owned().get_iter(vm)?;
let elements = {
let mut elements = Vec::new();
while let PyIterReturn::Return(element) = iter.next(vm)? {
elements.push(element);
}
elements
};
PyTupleTyped::<PyStrRef>::try_from_object(vm, elements.into_pytuple(vm).into())?
})
} else {
None
};
let base_member_count = base.slots.member_count;
let member_count: usize =
base.slots.member_count + heaptype_slots.as_ref().map(|x| x.len()).unwrap_or(0);
let flags = PyTypeFlags::heap_type_flags() | PyTypeFlags::HAS_DICT;
let heaptype_ext = HeapTypeExt {
slots: heaptype_slots.to_owned(),
..HeapTypeExt::default()
};
let slots = PyTypeSlots {
member_count,
..PyTypeSlots::from_flags(flags)
};
let typ = Self::new_verbose_ref(
name.as_str(),
base,
bases,
attributes,
slots,
heaptype_ext,
metatype,
&vm.ctx,
)
.map_err(|e| vm.new_type_error(e))?;
if let Some(ref slots) = heaptype_slots {
let mut offset = base_member_count;
for member in slots.as_slice() {
let member_def = MemberDef {
name: member.to_string(),
kind: MemberKind::ObjectEx,
getter: MemberGetter::Offset(offset),
setter: MemberSetter::Offset(offset),
doc: None,
};
let member_descriptor: PyRef<MemberDescrObject> = vm.new_pyref(MemberDescrObject {
common: DescrObject {
typ: typ.to_owned(),
name: member.to_string(),
qualname: PyRwLock::new(None),
},
member: member_def,
});
let attr_name = vm.ctx.intern_str(member.to_string());
if !typ.has_attr(attr_name) {
typ.set_attr(attr_name, member_descriptor.into());
}
offset += 1;
}
}
if let Some(cell) = typ.attributes.write().get(identifier!(vm, __classcell__)) {
let cell = PyCellRef::try_from_object(vm, cell.clone()).map_err(|_| {
vm.new_type_error(format!(
"__classcell__ must be a nonlocal cell, not {}",
cell.class().name()
))
})?;
cell.set(Some(typ.clone().to_pyobject(vm)));
};
// avoid deadlock
let attributes = typ
.attributes
.read()
.iter()
.filter_map(|(name, obj)| {
vm.get_method(obj.clone(), identifier!(vm, __set_name__))
.map(|res| res.map(|meth| (obj.clone(), name.to_owned(), meth)))
})
.collect::<PyResult<Vec<_>>>()?;
for (obj, name, set_name) in attributes {
vm.invoke(&set_name, (typ.clone(), name.to_owned()))
.map_err(|e| {
let err = vm.new_runtime_error(format!(
"Error calling __set_name__ on '{}' instance {} in '{}'",
obj.class().name(),
name,
typ.name()
));
err.set_cause(Some(e));
err
})?;
}
if let Some(initter) = typ.get_super_attr(identifier!(vm, __init_subclass__)) {
let initter = vm
.call_get_descriptor_specific(initter.clone(), None, Some(typ.clone().into()))
.unwrap_or(Ok(initter))?;
vm.invoke(&initter, kwargs)?;
};
Ok(typ.into())
}
#[pygetset(magic)]
fn dict(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf)
}
#[pygetset(magic, 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".to_owned(),
))
}
#[pygetset(magic, setter)]
fn set_name(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_type_error(format!(
"cannot set '{}' attribute of immutable type '{}'",
"__name__",
self.name()
)));
}
let name = value.downcast_ref::<PyStr>().ok_or_else(|| {
vm.new_type_error(format!(
"can only assign string to {}.__name__, not '{}'",
self.name(),
value.class().name()
))
})?;
if name.as_str().contains(char::from(0)) {
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
}
*self.slots.name.write() = Some(name.as_str().to_string());
Ok(())
}
#[pygetset(magic)]
fn text_signature(&self) -> Option<String> {
self.slots
.doc
.and_then(|doc| get_text_signature_from_internal_doc(&self.name(), doc))
.map(|signature| signature.to_string())
}
}
const SIGNATURE_END_MARKER: &str = ")\n--\n\n";
fn get_signature(doc: &str) -> Option<&str> {
doc.find(SIGNATURE_END_MARKER).map(|index| &doc[..=index])
}
fn find_signature<'a>(name: &str, doc: &'a str) -> Option<&'a str> {
let name = name.rsplit('.').next().unwrap();
let doc = doc.strip_prefix(name)?;
if !doc.starts_with('(') {
None
} else {
Some(doc)
}
}
pub(crate) fn get_text_signature_from_internal_doc<'a>(
name: &str,
internal_doc: &'a str,
) -> Option<&'a str> {
find_signature(name, internal_doc).and_then(get_signature)
}
impl GetAttr for PyType {
fn getattro(zelf: &Py<Self>, name_str: PyStrRef, vm: &VirtualMachine) -> PyResult {
#[cold]
fn attribute_error(
zelf: &Py<PyType>,
name: &str,
vm: &VirtualMachine,
) -> PyBaseExceptionRef {
vm.new_attribute_error(format!(
"type object '{}' has no attribute '{}'",
zelf.slot_name(),
name,
))
}
let Some(name) = vm.ctx.interned_str(&*name_str) else {
return Err(attribute_error(zelf, name_str.as_str(), vm));
};
vm_trace!("type.__getattribute__({:?}, {:?})", zelf, name);
let mcl = zelf.class();
let mcl_attr = mcl.get_attr(name);
if let Some(ref attr) = mcl_attr {
let attr_class = attr.class();
let has_descr_set = attr_class
.mro_find_map(|cls| cls.slots.descr_set.load())
.is_some();
if has_descr_set {
let descr_get = attr_class.mro_find_map(|cls| cls.slots.descr_get.load());
if let Some(descr_get) = descr_get {
let mcl = mcl.to_owned().into();
return descr_get(attr.clone(), Some(zelf.to_owned().into()), Some(mcl), vm);
}
}
}
let zelf_attr = zelf.get_attr(name);
if let Some(ref attr) = zelf_attr {
let descr_get = attr.class().mro_find_map(|cls| cls.slots.descr_get.load());
if let Some(descr_get) = descr_get {
return descr_get(attr.clone(), None, Some(zelf.to_owned().into()), vm);
}
}
if let Some(cls_attr) = zelf_attr {
Ok(cls_attr)
} else if let Some(attr) = mcl_attr {
vm.call_if_get_descriptor(attr, zelf.to_owned().into())
} else {
return Err(attribute_error(zelf, name_str.as_str(), vm));
}
}
}