forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyobject.rs
More file actions
1387 lines (1184 loc) · 39 KB
/
pyobject.rs
File metadata and controls
1387 lines (1184 loc) · 39 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 std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use indexmap::IndexMap;
use num_bigint::BigInt;
use num_complex::Complex64;
use num_traits::{One, ToPrimitive, Zero};
use crate::bytecode;
use crate::dictdatatype::DictKey;
use crate::exceptions::{self, PyBaseExceptionRef};
use crate::function::{IntoPyNativeFunc, PyFuncArgs};
use crate::obj::objbuiltinfunc::{PyBuiltinFunction, PyBuiltinMethod};
use crate::obj::objbytearray;
use crate::obj::objbytes;
use crate::obj::objclassmethod::PyClassMethod;
use crate::obj::objcode;
use crate::obj::objcode::PyCodeRef;
use crate::obj::objcomplex::PyComplex;
use crate::obj::objdict::{PyDict, PyDictRef};
use crate::obj::objfloat::PyFloat;
use crate::obj::objfunction::{PyBoundMethod, PyFunction};
use crate::obj::objgetset::{IntoPyGetterFunc, IntoPySetterFunc, PyGetSet};
use crate::obj::objint::{PyInt, PyIntRef};
use crate::obj::objiter;
use crate::obj::objlist::PyList;
use crate::obj::objnamespace::PyNamespace;
use crate::obj::objnone::{PyNone, PyNoneRef};
use crate::obj::objobject;
use crate::obj::objset::PySet;
use crate::obj::objstaticmethod::PyStaticMethod;
use crate::obj::objstr;
use crate::obj::objtuple::{PyTuple, PyTupleRef};
use crate::obj::objtype::{self, PyClass, PyClassRef};
use crate::scope::Scope;
use crate::slots::PyTpFlags;
use crate::types::{create_type, initialize_types, TypeZoo};
use crate::vm::VirtualMachine;
/* Python objects and references.
Okay, so each python object itself is an class itself (PyObject). Each
python object can have several references to it (PyObjectRef). These
references are Rc (reference counting) rust smart pointers. So when
all references are destroyed, the object itself also can be cleaned up.
Basically reference counting, but then done by rust.
*/
/*
* Good reference: https://github.com/ProgVal/pythonvm-rust/blob/master/src/objects/mod.rs
*/
/// The `PyObjectRef` is one of the most used types. It is a reference to a
/// python object. A single python object can have multiple references, and
/// this reference counting is accounted for by this type. Use the `.clone()`
/// method to create a new reference and increment the amount of references
/// to the python object by 1.
pub type PyObjectRef = Arc<PyObject<dyn PyObjectPayload>>;
/// Use this type for functions which return a python object or an exception.
/// Both the python object and the python exception are `PyObjectRef` types
/// since exceptions are also python objects.
pub type PyResult<T = PyObjectRef> = Result<T, PyBaseExceptionRef>; // A valid value, or an exception
/// For attributes we do not use a dict, but a hashmap. This is probably
/// faster, unordered, and only supports strings as keys.
/// TODO: class attributes should maintain insertion order (use IndexMap here)
pub type PyAttributes = HashMap<String, PyObjectRef>;
impl fmt::Display for PyObject<dyn PyObjectPayload> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(PyClass { ref name, .. }) = self.payload::<PyClass>() {
let type_name = self.class().name.clone();
// We don't have access to a vm, so just assume that if its parent's name
// is type, it's a type
if type_name == "type" {
return write!(f, "type object '{}'", name);
} else {
return write!(f, "'{}' object", type_name);
}
}
write!(f, "'{}' object", self.class().name)
}
}
const INT_CACHE_POOL_MIN: i32 = -5;
const INT_CACHE_POOL_MAX: i32 = 256;
#[derive(Debug)]
pub struct PyContext {
pub true_value: PyIntRef,
pub false_value: PyIntRef,
pub none: PyNoneRef,
pub empty_tuple: PyTupleRef,
pub ellipsis_type: PyClassRef,
pub ellipsis: PyEllipsisRef,
pub not_implemented: PyNotImplementedRef,
pub types: TypeZoo,
pub exceptions: exceptions::ExceptionZoo,
pub int_cache_pool: Vec<PyObjectRef>,
tp_new_wrapper: PyObjectRef,
}
pub type PyNotImplementedRef = PyRef<PyNotImplemented>;
#[derive(Debug)]
pub struct PyNotImplemented;
impl PyValue for PyNotImplemented {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.not_implemented().class()
}
}
pub type PyEllipsisRef = PyRef<PyEllipsis>;
#[derive(Debug)]
pub struct PyEllipsis;
impl PyValue for PyEllipsis {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.ellipsis_type.clone()
}
}
// Basic objects:
impl PyContext {
pub fn new() -> Self {
flame_guard!("init PyContext");
let types = TypeZoo::new();
let exceptions = exceptions::ExceptionZoo::new(&types.type_type, &types.object_type);
fn create_object<T: PyObjectPayload + PyValue>(payload: T, cls: &PyClassRef) -> PyRef<T> {
PyRef::from_obj_unchecked(PyObject::new(payload, cls.clone(), None))
}
let none_type = create_type("NoneType", &types.type_type, &types.object_type);
let none = create_object(PyNone, &none_type);
let ellipsis_type = create_type("EllipsisType", &types.type_type, &types.object_type);
let ellipsis = create_object(PyEllipsis, &ellipsis_type);
let not_implemented_type =
create_type("NotImplementedType", &types.type_type, &types.object_type);
let not_implemented = create_object(PyNotImplemented, ¬_implemented_type);
let int_cache_pool = (INT_CACHE_POOL_MIN..=INT_CACHE_POOL_MAX)
.map(|v| create_object(PyInt::new(BigInt::from(v)), &types.int_type).into_object())
.collect();
let true_value = create_object(PyInt::new(BigInt::one()), &types.bool_type);
let false_value = create_object(PyInt::new(BigInt::zero()), &types.bool_type);
let empty_tuple = create_object(PyTuple::from(vec![]), &types.tuple_type);
let tp_new_wrapper = create_object(
PyBuiltinFunction::new(objtype::tp_new_wrapper.into_func()),
&types.builtin_function_or_method_type,
)
.into_object();
let context = PyContext {
true_value,
false_value,
not_implemented,
none,
empty_tuple,
ellipsis,
ellipsis_type,
types,
exceptions,
int_cache_pool,
tp_new_wrapper,
};
initialize_types(&context);
exceptions::init(&context);
context
}
pub fn bytearray_type(&self) -> PyClassRef {
self.types.bytearray_type.clone()
}
pub fn bytearrayiterator_type(&self) -> PyClassRef {
self.types.bytearrayiterator_type.clone()
}
pub fn bytes_type(&self) -> PyClassRef {
self.types.bytes_type.clone()
}
pub fn bytesiterator_type(&self) -> PyClassRef {
self.types.bytesiterator_type.clone()
}
pub fn code_type(&self) -> PyClassRef {
self.types.code_type.clone()
}
pub fn complex_type(&self) -> PyClassRef {
self.types.complex_type.clone()
}
pub fn dict_type(&self) -> PyClassRef {
self.types.dict_type.clone()
}
pub fn float_type(&self) -> PyClassRef {
self.types.float_type.clone()
}
pub fn frame_type(&self) -> PyClassRef {
self.types.frame_type.clone()
}
pub fn int_type(&self) -> PyClassRef {
self.types.int_type.clone()
}
pub fn list_type(&self) -> PyClassRef {
self.types.list_type.clone()
}
pub fn listiterator_type(&self) -> PyClassRef {
self.types.listiterator_type.clone()
}
pub fn listreverseiterator_type(&self) -> PyClassRef {
self.types.listreverseiterator_type.clone()
}
pub fn striterator_type(&self) -> PyClassRef {
self.types.striterator_type.clone()
}
pub fn strreverseiterator_type(&self) -> PyClassRef {
self.types.strreverseiterator_type.clone()
}
pub fn module_type(&self) -> PyClassRef {
self.types.module_type.clone()
}
pub fn namespace_type(&self) -> PyClassRef {
self.types.namespace_type.clone()
}
pub fn set_type(&self) -> PyClassRef {
self.types.set_type.clone()
}
pub fn range_type(&self) -> PyClassRef {
self.types.range_type.clone()
}
pub fn rangeiterator_type(&self) -> PyClassRef {
self.types.rangeiterator_type.clone()
}
pub fn slice_type(&self) -> PyClassRef {
self.types.slice_type.clone()
}
pub fn frozenset_type(&self) -> PyClassRef {
self.types.frozenset_type.clone()
}
pub fn bool_type(&self) -> PyClassRef {
self.types.bool_type.clone()
}
pub fn memoryview_type(&self) -> PyClassRef {
self.types.memoryview_type.clone()
}
pub fn tuple_type(&self) -> PyClassRef {
self.types.tuple_type.clone()
}
pub fn tupleiterator_type(&self) -> PyClassRef {
self.types.tupleiterator_type.clone()
}
pub fn iter_type(&self) -> PyClassRef {
self.types.iter_type.clone()
}
pub fn enumerate_type(&self) -> PyClassRef {
self.types.enumerate_type.clone()
}
pub fn filter_type(&self) -> PyClassRef {
self.types.filter_type.clone()
}
pub fn map_type(&self) -> PyClassRef {
self.types.map_type.clone()
}
pub fn zip_type(&self) -> PyClassRef {
self.types.zip_type.clone()
}
pub fn str_type(&self) -> PyClassRef {
self.types.str_type.clone()
}
pub fn super_type(&self) -> PyClassRef {
self.types.super_type.clone()
}
pub fn function_type(&self) -> PyClassRef {
self.types.function_type.clone()
}
pub fn builtin_function_or_method_type(&self) -> PyClassRef {
self.types.builtin_function_or_method_type.clone()
}
pub fn method_descriptor_type(&self) -> PyClassRef {
self.types.method_descriptor_type.clone()
}
pub fn property_type(&self) -> PyClassRef {
self.types.property_type.clone()
}
pub fn readonly_property_type(&self) -> PyClassRef {
self.types.readonly_property_type.clone()
}
pub fn getset_type(&self) -> PyClassRef {
self.types.getset_type.clone()
}
pub fn classmethod_type(&self) -> PyClassRef {
self.types.classmethod_type.clone()
}
pub fn staticmethod_type(&self) -> PyClassRef {
self.types.staticmethod_type.clone()
}
pub fn generator_type(&self) -> PyClassRef {
self.types.generator_type.clone()
}
pub fn bound_method_type(&self) -> PyClassRef {
self.types.bound_method_type.clone()
}
pub fn weakref_type(&self) -> PyClassRef {
self.types.weakref_type.clone()
}
pub fn weakproxy_type(&self) -> PyClassRef {
self.types.weakproxy_type.clone()
}
pub fn traceback_type(&self) -> PyClassRef {
self.types.traceback_type.clone()
}
pub fn type_type(&self) -> PyClassRef {
self.types.type_type.clone()
}
pub fn none(&self) -> PyObjectRef {
self.none.clone().into_object()
}
pub fn ellipsis(&self) -> PyObjectRef {
self.ellipsis.clone().into_object()
}
pub fn not_implemented(&self) -> PyObjectRef {
self.not_implemented.clone().into_object()
}
pub fn object(&self) -> PyClassRef {
self.types.object_type.clone()
}
#[inline]
pub fn new_int<T: Into<BigInt> + ToPrimitive>(&self, i: T) -> PyObjectRef {
if let Some(i) = i.to_i32() {
if i >= INT_CACHE_POOL_MIN && i <= INT_CACHE_POOL_MAX {
let inner_idx = (i - INT_CACHE_POOL_MIN) as usize;
return self.int_cache_pool[inner_idx].clone();
}
}
PyObject::new(PyInt::new(i), self.int_type(), None)
}
#[inline]
pub fn new_bigint(&self, i: &BigInt) -> PyObjectRef {
if let Some(i) = i.to_i32() {
if i >= INT_CACHE_POOL_MIN && i <= INT_CACHE_POOL_MAX {
let inner_idx = (i - INT_CACHE_POOL_MIN) as usize;
return self.int_cache_pool[inner_idx].clone();
}
}
PyObject::new(PyInt::new(i.clone()), self.int_type(), None)
}
pub fn new_float(&self, value: f64) -> PyObjectRef {
PyObject::new(PyFloat::from(value), self.float_type(), None)
}
pub fn new_complex(&self, value: Complex64) -> PyObjectRef {
PyObject::new(PyComplex::from(value), self.complex_type(), None)
}
pub fn new_str<S>(&self, s: S) -> PyObjectRef
where
objstr::PyString: std::convert::From<S>,
{
PyObject::new(objstr::PyString::from(s), self.str_type(), None)
}
pub fn new_bytes(&self, data: Vec<u8>) -> PyObjectRef {
PyObject::new(objbytes::PyBytes::new(data), self.bytes_type(), None)
}
pub fn new_bytearray(&self, data: Vec<u8>) -> PyObjectRef {
PyObject::new(
objbytearray::PyByteArray::new(data),
self.bytearray_type(),
None,
)
}
#[inline]
pub fn new_bool(&self, b: bool) -> PyObjectRef {
let value = if b {
&self.true_value
} else {
&self.false_value
};
value.clone().into_object()
}
pub fn new_tuple(&self, elements: Vec<PyObjectRef>) -> PyObjectRef {
if elements.is_empty() {
self.empty_tuple.clone().into_object()
} else {
PyObject::new(PyTuple::from(elements), self.tuple_type(), None)
}
}
pub fn new_list(&self, elements: Vec<PyObjectRef>) -> PyObjectRef {
PyObject::new(PyList::from(elements), self.list_type(), None)
}
pub fn new_set(&self) -> PyObjectRef {
// Initialized empty, as calling __hash__ is required for adding each object to the set
// which requires a VM context - this is done in the objset code itself.
PyObject::new(PySet::default(), self.set_type(), None)
}
pub fn new_dict(&self) -> PyDictRef {
PyObject::new(PyDict::default(), self.dict_type(), None)
.downcast()
.unwrap()
}
pub fn new_class(&self, name: &str, base: PyClassRef) -> PyClassRef {
create_type(name, &self.type_type(), &base)
}
pub fn new_namespace(&self) -> PyObjectRef {
PyObject::new(PyNamespace, self.namespace_type(), Some(self.new_dict()))
}
pub fn new_function<F, T, R, VM>(&self, f: F) -> PyObjectRef
where
F: IntoPyNativeFunc<T, R, VM>,
{
PyObject::new(
PyBuiltinFunction::new(f.into_func()),
self.builtin_function_or_method_type(),
None,
)
}
pub fn new_function_named<F, T, R, VM>(&self, f: F, module: String, name: String) -> PyObjectRef
where
F: IntoPyNativeFunc<T, R, VM>,
{
let stringref = |s| PyRef::new_ref(objstr::PyString::from(s), self.str_type(), None);
PyObject::new(
PyBuiltinFunction::new_with_name(f.into_func(), stringref(module), stringref(name)),
self.builtin_function_or_method_type(),
None,
)
}
pub fn new_method<F, T, R, VM>(&self, f: F) -> PyObjectRef
where
F: IntoPyNativeFunc<T, R, VM>,
{
PyObject::new(
PyBuiltinMethod::new(f.into_func()),
self.method_descriptor_type(),
None,
)
}
pub fn new_classmethod<F, T, R, VM>(&self, f: F) -> PyObjectRef
where
F: IntoPyNativeFunc<T, R, VM>,
{
PyObject::new(
PyClassMethod::new(self.new_method(f)),
self.classmethod_type(),
None,
)
}
pub fn new_staticmethod<F, T, R, VM>(&self, f: F) -> PyObjectRef
where
F: IntoPyNativeFunc<T, R, VM>,
{
PyObject::new(
PyStaticMethod::new(self.new_method(f)),
self.staticmethod_type(),
None,
)
}
pub fn new_readonly_getset<F, T>(&self, name: impl Into<String>, f: F) -> PyObjectRef
where
F: IntoPyGetterFunc<T>,
{
PyObject::new(PyGetSet::with_get(name.into(), f), self.getset_type(), None)
}
pub fn new_getset<G, S, T, U>(&self, name: impl Into<String>, g: G, s: S) -> PyObjectRef
where
G: IntoPyGetterFunc<T>,
S: IntoPySetterFunc<U>,
{
PyObject::new(
PyGetSet::with_get_set(name.into(), g, s),
self.getset_type(),
None,
)
}
pub fn new_code_object(&self, code: bytecode::CodeObject) -> PyCodeRef {
PyObject::new(objcode::PyCode::new(code), self.code_type(), None)
.downcast()
.unwrap()
}
pub fn new_pyfunction(
&self,
code_obj: PyCodeRef,
scope: Scope,
defaults: Option<PyTupleRef>,
kw_only_defaults: Option<PyDictRef>,
) -> PyObjectRef {
PyObject::new(
PyFunction::new(code_obj, scope, defaults, kw_only_defaults),
self.function_type(),
Some(self.new_dict()),
)
}
pub fn new_bound_method(&self, function: PyObjectRef, object: PyObjectRef) -> PyObjectRef {
PyObject::new(
PyBoundMethod::new(object, function),
self.bound_method_type(),
None,
)
}
pub fn new_base_object(&self, class: PyClassRef, dict: Option<PyDictRef>) -> PyObjectRef {
PyObject {
typ: class.into_typed_pyobj(),
dict: dict.map(Mutex::new),
payload: objobject::PyBaseObject,
}
.into_ref()
}
pub fn unwrap_constant(&self, value: &bytecode::Constant) -> PyObjectRef {
match *value {
bytecode::Constant::Integer { ref value } => self.new_bigint(value),
bytecode::Constant::Float { ref value } => self.new_float(*value),
bytecode::Constant::Complex { ref value } => self.new_complex(*value),
bytecode::Constant::String { ref value } => self.new_str(value.clone()),
bytecode::Constant::Bytes { ref value } => self.new_bytes(value.clone()),
bytecode::Constant::Boolean { value } => self.new_bool(value),
bytecode::Constant::Code { ref code } => {
self.new_code_object(*code.clone()).into_object()
}
bytecode::Constant::Tuple { ref elements } => {
let elements = elements
.iter()
.map(|value| self.unwrap_constant(value))
.collect();
self.new_tuple(elements)
}
bytecode::Constant::None => self.none(),
bytecode::Constant::Ellipsis => self.ellipsis(),
}
}
pub fn add_tp_new_wrapper(&self, ty: &PyClassRef) {
if !ty.attributes.read().unwrap().contains_key("__new__") {
let new_wrapper =
self.new_bound_method(self.tp_new_wrapper.clone(), ty.clone().into_object());
ty.set_str_attr("__new__", new_wrapper);
}
}
pub fn is_tp_new_wrapper(&self, obj: &PyObjectRef) -> bool {
obj.payload::<PyBoundMethod>()
.map_or(false, |bound| bound.function.is(&self.tp_new_wrapper))
}
}
impl Default for PyContext {
fn default() -> Self {
PyContext::new()
}
}
/// This is an actual python object. It consists of a `typ` which is the
/// python class, and carries some rust payload optionally. This rust
/// payload can be a rust float or rust int in case of float and int objects.
pub struct PyObject<T>
where
T: ?Sized + PyObjectPayload,
{
pub typ: Arc<PyObject<PyClass>>,
// TODO: make this RwLock once PyObjectRef is Send + Sync
pub(crate) dict: Option<Mutex<PyDictRef>>, // __dict__ member
pub payload: T,
}
impl PyObject<dyn PyObjectPayload> {
/// Attempt to downcast this reference to a subclass.
///
/// If the downcast fails, the original ref is returned in as `Err` so
/// another downcast can be attempted without unnecessary cloning.
pub fn downcast<T: PyObjectPayload>(self: Arc<Self>) -> Result<PyRef<T>, PyObjectRef> {
if self.payload_is::<T>() {
Ok(PyRef {
obj: self,
_payload: PhantomData,
})
} else {
Err(self)
}
}
/// Downcast this PyObjectRef to an `Arc<PyObject<T>>`. The [`downcast`](#method.downcast) method
/// is generally preferred, as the `PyRef<T>` it returns implements `Deref<Target=T>`, and
/// therefore can be used similarly to an `&T`.
pub fn downcast_generic<T: PyObjectPayload>(
self: Arc<Self>,
) -> Result<Arc<PyObject<T>>, PyObjectRef> {
if self.payload_is::<T>() {
let ptr = Arc::into_raw(self) as *const PyObject<T>;
let ret = unsafe { Arc::from_raw(ptr) };
Ok(ret)
} else {
Err(self)
}
}
}
/// A reference to a Python object.
///
/// Note that a `PyRef<T>` can only deref to a shared / immutable reference.
/// It is the payload type's responsibility to handle (possibly concurrent)
/// mutability with locks or concurrent data structures if required.
///
/// A `PyRef<T>` can be directly returned from a built-in function to handle
/// situations (such as when implementing in-place methods such as `__iadd__`)
/// where a reference to the same object must be returned.
#[derive(Debug)]
#[repr(transparent)]
pub struct PyRef<T> {
// invariant: this obj must always have payload of type T
obj: PyObjectRef,
_payload: PhantomData<T>,
}
impl<T> Clone for PyRef<T> {
fn clone(&self) -> Self {
Self {
obj: self.obj.clone(),
_payload: PhantomData,
}
}
}
impl<T: PyValue> PyRef<T> {
#[allow(clippy::new_ret_no_self)]
pub fn new_ref(payload: T, typ: PyClassRef, dict: Option<PyDictRef>) -> Self {
Self::from_obj_unchecked(PyObject::new(payload, typ, dict))
}
fn from_obj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
if obj.payload_is::<T>() {
Ok(Self::from_obj_unchecked(obj))
} else {
Err(vm.new_runtime_error(format!(
"Unexpected payload for type {:?}",
obj.class().name
)))
}
}
pub(crate) fn from_obj_unchecked(obj: PyObjectRef) -> Self {
PyRef {
obj,
_payload: PhantomData,
}
}
pub fn as_object(&self) -> &PyObjectRef {
&self.obj
}
pub fn into_object(self) -> PyObjectRef {
self.obj
}
pub fn typ(&self) -> PyClassRef {
self.obj.class()
}
pub fn into_typed_pyobj(self) -> Arc<PyObject<T>> {
self.into_object().downcast_generic().unwrap()
}
}
impl<T> Deref for PyRef<T>
where
T: PyValue,
{
type Target = T;
fn deref(&self) -> &T {
self.obj.payload().expect("unexpected payload for type")
}
}
impl<T> TryFromObject for PyRef<T>
where
T: PyValue,
{
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
if objtype::isinstance(&obj, &T::class(vm)) {
PyRef::from_obj(obj, vm)
} else {
let class = T::class(vm);
let expected_type = vm.to_pystr(&class)?;
let actual_type = vm.to_pystr(&obj.class())?;
Err(vm.new_type_error(format!(
"Expected type {}, not {}",
expected_type, actual_type,
)))
}
}
}
impl<'a, T: PyValue> From<&'a PyRef<T>> for &'a PyObjectRef {
fn from(obj: &'a PyRef<T>) -> Self {
obj.as_object()
}
}
impl<T: PyValue> From<PyRef<T>> for PyObjectRef {
fn from(obj: PyRef<T>) -> Self {
obj.into_object()
}
}
impl<T: fmt::Display> fmt::Display for PyRef<T>
where
T: PyValue + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let value: &T = self.obj.payload().expect("unexpected payload for type");
fmt::Display::fmt(value, f)
}
}
#[derive(Clone, Debug)]
pub struct PyCallable {
obj: PyObjectRef,
}
impl PyCallable {
#[inline]
pub fn invoke(&self, args: impl Into<PyFuncArgs>, vm: &VirtualMachine) -> PyResult {
vm.invoke(&self.obj, args)
}
#[inline]
pub fn into_object(self) -> PyObjectRef {
self.obj
}
}
impl TryFromObject for PyCallable {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
if vm.is_callable(&obj) {
Ok(PyCallable { obj })
} else {
Err(vm.new_type_error(format!("'{}' object is not callable", obj.class().name)))
}
}
}
pub trait IdProtocol {
fn get_id(&self) -> usize;
fn is<T>(&self, other: &T) -> bool
where
T: IdProtocol,
{
self.get_id() == other.get_id()
}
}
#[derive(Debug)]
enum Never {}
impl PyValue for Never {
fn class(_vm: &VirtualMachine) -> PyClassRef {
unreachable!()
}
}
impl<T: ?Sized + PyObjectPayload> IdProtocol for PyObject<T> {
fn get_id(&self) -> usize {
self as *const _ as *const PyObject<Never> as usize
}
}
impl<T: ?Sized + IdProtocol> IdProtocol for Arc<T> {
fn get_id(&self) -> usize {
(**self).get_id()
}
}
impl<T: PyObjectPayload> IdProtocol for PyRef<T> {
fn get_id(&self) -> usize {
self.obj.get_id()
}
}
pub trait TypeProtocol {
fn class(&self) -> PyClassRef;
}
impl TypeProtocol for PyObjectRef {
fn class(&self) -> PyClassRef {
(**self).class()
}
}
impl<T> TypeProtocol for PyObject<T>
where
T: ?Sized + PyObjectPayload,
{
fn class(&self) -> PyClassRef {
self.typ.clone().into_pyref()
}
}
impl<T> TypeProtocol for PyRef<T> {
fn class(&self) -> PyClassRef {
self.obj.class()
}
}
impl<T: TypeProtocol> TypeProtocol for &'_ T {
fn class(&self) -> PyClassRef {
(&**self).class()
}
}
/// The python item protocol. Mostly applies to dictionaries.
/// Allows getting, setting and deletion of keys-value pairs.
pub trait ItemProtocol {
fn get_item<T: IntoPyObject + DictKey + Copy>(&self, key: T, vm: &VirtualMachine) -> PyResult;
fn set_item<T: IntoPyObject + DictKey + Copy>(
&self,
key: T,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult;
fn del_item<T: IntoPyObject + DictKey + Copy>(&self, key: T, vm: &VirtualMachine) -> PyResult;
}
impl ItemProtocol for PyObjectRef {
fn get_item<T: IntoPyObject>(&self, key: T, vm: &VirtualMachine) -> PyResult {
vm.call_method(self, "__getitem__", key.into_pyobject(vm)?)
}
fn set_item<T: IntoPyObject>(
&self,
key: T,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult {
vm.call_method(self, "__setitem__", vec![key.into_pyobject(vm)?, value])
}
fn del_item<T: IntoPyObject>(&self, key: T, vm: &VirtualMachine) -> PyResult {
vm.call_method(self, "__delitem__", key.into_pyobject(vm)?)
}
}
pub trait BufferProtocol {
fn readonly(&self) -> bool;
}
impl BufferProtocol for PyObjectRef {
fn readonly(&self) -> bool {
match self.class().name.as_str() {
"bytes" => false,
"bytearray" | "memoryview" => true,
_ => panic!("Bytes-Like type expected not {:?}", self),
}
}
}
impl fmt::Debug for PyObject<dyn PyObjectPayload> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[PyObj {:?}]", &self.payload)
}
}
/// An iterable Python object.
///
/// `PyIterable` implements `FromArgs` so that a built-in function can accept
/// an object that is required to conform to the Python iterator protocol.
///
/// PyIterable can optionally perform type checking and conversions on iterated
/// objects using a generic type parameter that implements `TryFromObject`.
pub struct PyIterable<T = PyObjectRef> {
method: PyObjectRef,
_item: std::marker::PhantomData<T>,
}
impl<T> PyIterable<T> {
pub fn from_method(method: PyObjectRef) -> Self {
PyIterable {
method,
_item: std::marker::PhantomData,
}
}
/// Returns an iterator over this sequence of objects.
///
/// This operation may fail if an exception is raised while invoking the
/// `__iter__` method of the iterable object.
pub fn iter<'a>(&self, vm: &'a VirtualMachine) -> PyResult<PyIterator<'a, T>> {
let method = &self.method;
let iter_obj = vm.invoke(
method,
PyFuncArgs {
args: vec![],
kwargs: IndexMap::new(),
},
)?;
Ok(PyIterator {
vm,
obj: iter_obj,
_item: std::marker::PhantomData,
})
}
}
pub struct PyIterator<'a, T> {
vm: &'a VirtualMachine,
obj: PyObjectRef,
_item: std::marker::PhantomData<T>,
}
impl<'a, T> Iterator for PyIterator<'a, T>
where
T: TryFromObject,
{