forked from APrioriInvestments/typed_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyInstance.cpp
More file actions
1341 lines (1112 loc) · 44.8 KB
/
Copy pathPyInstance.cpp
File metadata and controls
1341 lines (1112 loc) · 44.8 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
#include <Python.h>
#include <numpy/arrayobject.h>
#include <type_traits>
#include "AllTypes.hpp"
#include "_runtime.h"
#include "PyInstance.hpp"
#include "PyDictInstance.hpp"
#include "PyConstDictInstance.hpp"
#include "PyTupleOrListOfInstance.hpp"
#include "PyPointerToInstance.hpp"
#include "PyCompositeTypeInstance.hpp"
#include "PyClassInstance.hpp"
#include "PyHeldClassInstance.hpp"
#include "PyBoundMethodInstance.hpp"
#include "PyAlternativeInstance.hpp"
#include "PyFunctionInstance.hpp"
#include "PyStringInstance.hpp"
#include "PyBytesInstance.hpp"
#include "PyNoneInstance.hpp"
#include "PyRegisterTypeInstance.hpp"
#include "PyValueInstance.hpp"
#include "PyValueInstance.hpp"
#include "PyPythonSubclassInstance.hpp"
#include "PyPythonObjectOfTypeInstance.hpp"
#include "PyOneOfInstance.hpp"
#include "PyForwardInstance.hpp"
// static
bool PyInstance::guaranteeForwardsResolved(Type* t) {
try {
guaranteeForwardsResolvedOrThrow(t);
return true;
} catch(PythonExceptionSet& e) {
return false;
} catch(std::exception& e) {
PyErr_SetString(PyExc_TypeError, e.what());
return false;
}
}
// static
void PyInstance::guaranteeForwardsResolvedOrThrow(Type* t) {
t->guaranteeForwardsResolved([&](PyObject* o) {
PyObjectStealer result(
PyObject_CallFunctionObjArgs(o, NULL)
);
if (!result) {
PyErr_Clear();
throw std::runtime_error("Python type callback threw an exception.");
}
if (!PyType_Check(result)) {
throw std::runtime_error("Python type callback didn't return a type: got " +
std::string(result->ob_type->tp_name));
}
Type* resType = unwrapTypeArgToTypePtr(result);
if (!resType) {
throw std::runtime_error("Python type callback didn't return a native type: got " +
std::string(result->ob_type->tp_name));
}
return resType;
});
}
Type* PyInstance::type() {
return extractTypeFrom(((PyObject*)this)->ob_type);
}
instance_ptr PyInstance::dataPtr() {
return mContainingInstance.data();
}
//static
PyObject* PyInstance::undefinedBehaviorException() {
static PyObject* module = PyImport_ImportModule("typed_python.internals");
static PyObject* t = PyObject_GetAttrString(module, "UndefinedBehaviorException");
return t;
}
// static
PyMethodDef* PyInstance::typeMethods(Type* t) {
return specializeStatic(t->getTypeCategory(), [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
return py_instance_type::typeMethodsConcrete();
});
}
PyMethodDef* PyInstance::typeMethodsConcrete() {
return new PyMethodDef [2] {
{NULL, NULL}
};
}
// static
void PyInstance::tp_dealloc(PyObject* self) {
PyInstance* wrapper = (PyInstance*)self;
if (wrapper->mIsInitialized) {
wrapper->mContainingInstance.~Instance();
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
// static
bool PyInstance::pyValCouldBeOfType(Type* t, PyObject* pyRepresentation) {
guaranteeForwardsResolvedOrThrow(t);
Type* argType = extractTypeFrom(pyRepresentation->ob_type);
if (argType && argType->isBinaryCompatibleWith(argType)) {
return true;
}
return specializeStatic(t->getTypeCategory(), [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
return py_instance_type::pyValCouldBeOfTypeConcrete(
(typename py_instance_type::modeled_type*)t,
pyRepresentation
);
});
}
// static
void PyInstance::copyConstructFromPythonInstance(Type* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) {
guaranteeForwardsResolvedOrThrow(eltType);
Type* argType = extractTypeFrom(pyRepresentation->ob_type);
if (argType && argType->isBinaryCompatibleWith(eltType)) {
//it's already the right kind of instance
eltType->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr());
return;
}
Type::TypeCategory cat = eltType->getTypeCategory();
//dispatch to the appropriate Py[]Instance type
specializeStatic(cat, [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
py_instance_type::copyConstructFromPythonInstanceConcrete(
(typename py_instance_type::modeled_type*)eltType,
tgt,
pyRepresentation,
isExplicit
);
});
}
void PyInstance::copyConstructFromPythonInstanceConcrete(Type* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) {
throw std::logic_error("Couldn't initialize type " + eltType->name() + " from " + pyRepresentation->ob_type->tp_name);
}
// static
void PyInstance::constructFromPythonArguments(uint8_t* data, Type* t, PyObject* args, PyObject* kwargs) {
guaranteeForwardsResolvedOrThrow(t);
//dispatch to the appropriate PyInstance subclass
specializeStatic(t->getTypeCategory(), [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
py_instance_type::constructFromPythonArgumentsConcrete(
(typename py_instance_type::modeled_type*)t,
data,
args,
kwargs
);
});
}
void PyInstance::constructFromPythonArgumentsConcrete(Type* t, uint8_t* data, PyObject* args, PyObject* kwargs) {
if (kwargs == NULL && (args == NULL || PyTuple_Size(args) == 0)) {
if (t->is_default_constructible()) {
t->constructor(data);
return;
}
}
if (kwargs == NULL && PyTuple_Size(args) == 1) {
PyObject* argTuple = PyTuple_GetItem(args, 0);
copyConstructFromPythonInstance(t, data, argTuple, true /* mark isExplicit */);
return;
}
throw std::logic_error("Can't initialize " + t->name() + " with this signature.");
}
/**
* produce the pythonic representation of this object. for values that have a direct python representation,
* such as integers, strings, bools, or None, we return an actual python object. Otherwise,
* we return a pointer to a PyInstance representing the object.
*/
// static
PyObject* PyInstance::extractPythonObject(instance_ptr data, Type* eltType) {
//dispatch to the appropriate Py[]Instance type
PyObject* result = specializeStatic(eltType->getTypeCategory(), [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
return py_instance_type::extractPythonObjectConcrete(
(typename py_instance_type::modeled_type*)eltType,
data
);
});
if (result) {
return result;
}
if (!result && PyErr_Occurred()) {
return NULL;
}
try {
Type* concreteT = eltType->pickConcreteSubclass(data);
return PyInstance::initialize(concreteT, [&](instance_ptr selfData) {
concreteT->copy_constructor(selfData, data);
});
} catch(PythonExceptionSet& e) {
return NULL;
} catch(std::exception& e) {
PyErr_SetString(PyExc_TypeError, e.what());
return NULL;
}
}
PyObject* PyInstance::extractPythonObjectConcrete(Type* eltType, instance_ptr data) {
return NULL;
}
// static
PyObject* PyInstance::tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) {
Type* eltType = extractTypeFrom(subtype);
if (!guaranteeForwardsResolved(eltType)) {
return nullptr;
}
if (isSubclassOfNativeType(subtype)) {
PyInstance* self = (PyInstance*)subtype->tp_alloc(subtype, 0);
try {
self->mIteratorOffset = -1;
self->mIsMatcher = false;
self->initialize([&](instance_ptr data) {
constructFromPythonArguments(data, eltType, args, kwds);
});
return (PyObject*)self;
} catch(PythonExceptionSet& e) {
subtype->tp_dealloc((PyObject*)self);
return NULL;
} catch(std::exception& e) {
subtype->tp_dealloc((PyObject*)self);
PyErr_SetString(PyExc_TypeError, e.what());
return NULL;
}
// not reachable
assert(false);
} else {
instance_ptr tgt = (instance_ptr)malloc(eltType->bytecount());
try {
constructFromPythonArguments(tgt, eltType, args, kwds);
} catch(std::exception& e) {
free(tgt);
PyErr_SetString(PyExc_TypeError, e.what());
return NULL;
} catch(PythonExceptionSet& e) {
free(tgt);
return NULL;
}
PyObject* result = extractPythonObject(tgt, eltType);
eltType->destroy(tgt);
free(tgt);
return result;
}
}
PyObject* PyInstance::pyUnaryOperator(PyObject* lhs, const char* op, const char* opErrRep) {
return specializeForType(lhs, [&](auto& subtype) {
return subtype.pyUnaryOperatorConcrete(op, opErrRep);
});
}
PyObject* PyInstance::pyOperator(PyObject* lhs, PyObject* rhs, const char* op, const char* opErrRep) {
if (extractTypeFrom(lhs->ob_type)) {
return specializeForType(lhs, [&](auto& subtype) {
return subtype.pyOperatorConcrete(rhs, op, opErrRep);
});
}
if (extractTypeFrom(rhs->ob_type)) {
return specializeForType(rhs, [&](auto& subtype) {
return subtype.pyOperatorConcreteReverse(lhs, op, opErrRep);
});
}
PyErr_Format(PyExc_TypeError, "Invalid type arguments of type '%S' and '%S' to binary operator %s",
lhs->ob_type,
rhs->ob_type,
op
);
return NULL;
}
PyObject* PyInstance::pyTernaryOperator(PyObject* lhs, PyObject* rhs, PyObject* thirdArg, const char* op, const char* opErrRep) {
if (extractTypeFrom(lhs->ob_type)) {
return specializeForType(lhs, [&](auto& subtype) {
return subtype.pyTernaryOperatorConcrete(rhs, thirdArg, op, opErrRep);
});
}
PyErr_Format(PyExc_TypeError, "Invalid type arguments of type '%S' and '%S' to binary operator %s",
lhs->ob_type,
rhs->ob_type,
op
);
return NULL;
}
PyObject* PyInstance::pyUnaryOperatorConcrete(const char* op, const char* opErrRep) {
return incref(Py_NotImplemented);
}
PyObject* PyInstance::pyOperatorConcrete(PyObject* rhs, const char* op, const char* opErrRep) {
return incref(Py_NotImplemented);
}
PyObject* PyInstance::pyOperatorConcreteReverse(PyObject* lhs, const char* op, const char* opErrRep) {
return incref(Py_NotImplemented);
}
PyObject* PyInstance::pyTernaryOperatorConcrete(PyObject* rhs, PyObject* third, const char* op, const char* opErrRep) {
return incref(Py_NotImplemented);
}
PyObject* PyInstance::nb_inplace_add(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__iadd__", "+=");
}
PyObject* PyInstance::nb_inplace_subtract(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__isub__", "-=");
}
PyObject* PyInstance::nb_inplace_multiply(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__imul__", "*=");
}
PyObject* PyInstance::nb_inplace_remainder(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__imod__", "%=");
}
PyObject* PyInstance::nb_inplace_power(PyObject* lhs, PyObject* rhs, PyObject* modOrNone) {
return pyOperator(lhs, rhs, "__ipow__", "**=");
}
PyObject* PyInstance::nb_inplace_lshift(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__ilshift__", "<<=");
}
PyObject* PyInstance::nb_inplace_rshift(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__irshift__", ">>=");
}
PyObject* PyInstance::nb_inplace_and(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__iand__", "&=");
}
PyObject* PyInstance::nb_inplace_xor(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__ixor__", "^=");
}
PyObject* PyInstance::nb_inplace_or(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__ior__", "|=");
}
PyObject* PyInstance::nb_floor_divide(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__floordiv__", "//");
}
PyObject* PyInstance::nb_true_divide(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__div__", ".");
}
PyObject* PyInstance::nb_inplace_floor_divide(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__ifloordiv__", "//=");
}
PyObject* PyInstance::nb_inplace_true_divide(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__itruediv__", "/=");
}
PyObject* PyInstance::nb_inplace_matrix_multiply(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__imatmul__", "@=");
}
// static
PyObject* PyInstance::nb_negative(PyObject* lhs) {
return pyUnaryOperator(lhs, "__neg__", "-");
}
// static
PyObject* PyInstance::nb_positive(PyObject* lhs) {
return pyUnaryOperator(lhs, "__pos__", "+");
}
// static
PyObject* PyInstance::nb_absolute(PyObject* lhs) {
return pyUnaryOperator(lhs, "__abs__", "+");
}
// static
PyObject* PyInstance::nb_invert(PyObject* lhs) {
return pyUnaryOperator(lhs, "__invert__", "~");
}
// static
PyObject* PyInstance::nb_int(PyObject* lhs) {
return pyUnaryOperator(lhs, "__int__", "+");
}
// static
PyObject* PyInstance::nb_float(PyObject* lhs) {
return pyUnaryOperator(lhs, "__float__", "+");
}
// static
PyObject* PyInstance::nb_index(PyObject* lhs) {
return pyUnaryOperator(lhs, "__index__", "+");
}
// static
PyObject* PyInstance::nb_matmul(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__matmul__", "@");
}
// static
PyObject* PyInstance::nb_divmod(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "divmod", "divmod");
}
// static
PyObject* PyInstance::nb_power(PyObject* lhs, PyObject* rhs, PyObject* modOrNone) {
return pyTernaryOperator(lhs, rhs, modOrNone, "__pow__", "**");
}
// static
PyObject* PyInstance::nb_and(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__and__", "&");
}
// static
PyObject* PyInstance::nb_xor(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__xor__", "^");
}
// static
PyObject* PyInstance::nb_or(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__or__", "|");
}
// static
PyObject* PyInstance::nb_rshift(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__rshift__", ">>");
}
// static
PyObject* PyInstance::nb_lshift(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__lshift__", "<<");
}
// static
PyObject* PyInstance::nb_add(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__add__", "+");
}
// static
PyObject* PyInstance::nb_subtract(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__sub__", "-");
}
// static
PyObject* PyInstance::nb_multiply(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__mul__", "*");
}
// static
PyObject* PyInstance::nb_remainder(PyObject* lhs, PyObject* rhs) {
return pyOperator(lhs, rhs, "__mod__", "%");
}
// static
PyObject* PyInstance::sq_item(PyObject* o, Py_ssize_t ix) {
return specializeForType(o, [&](auto& subtype) {
return subtype.sq_item_concrete(ix);
});
}
PyObject* PyInstance::sq_item_concrete(Py_ssize_t ix) {
PyErr_Format(PyExc_TypeError, "%S object is not subscriptable", (PyObject*)((PyObject*)this)->ob_type);
return NULL;
}
// static
PyTypeObject* PyInstance::typeObj(Type* inType) {
if (!inType->getTypeRep()) {
inType->setTypeRep(typeObjInternal(inType));
}
return inType->getTypeRep();
}
// static
PySequenceMethods* PyInstance::sequenceMethodsFor(Type* t) {
if ( t->getTypeCategory() == Type::TypeCategory::catTupleOf ||
t->getTypeCategory() == Type::TypeCategory::catListOf ||
t->getTypeCategory() == Type::TypeCategory::catTuple ||
t->getTypeCategory() == Type::TypeCategory::catNamedTuple ||
t->getTypeCategory() == Type::TypeCategory::catString ||
t->getTypeCategory() == Type::TypeCategory::catBytes ||
t->getTypeCategory() == Type::TypeCategory::catDict ||
t->getTypeCategory() == Type::TypeCategory::catConstDict) {
PySequenceMethods* res =
new PySequenceMethods {0,0,0,0,0,0,0,0};
if (t->getTypeCategory() == Type::TypeCategory::catConstDict || t->getTypeCategory() == Type::TypeCategory::catDict) {
res->sq_contains = (objobjproc)PyInstance::sq_contains;
} else {
res->sq_length = (lenfunc)PyInstance::mp_and_sq_length;
res->sq_item = (ssizeargfunc)PyInstance::sq_item;
}
return res;
}
if ( t->getTypeCategory() == Type::TypeCategory::catPointerTo) {
PySequenceMethods* res =
new PySequenceMethods {0,0,0,0,0,0,0,0};
res->sq_item = (ssizeargfunc)PyInstance::sq_item;
return res;
}
return 0;
}
// static
PyNumberMethods* PyInstance::numberMethods(Type* t) {
return new PyNumberMethods {
//only enable this for the types that it operates on. Otherwise it disables the concatenation functions
//we should probably just unify them
nb_add, //binaryfunc nb_add
nb_subtract, //binaryfunc nb_subtract
nb_multiply, //binaryfunc nb_multiply
nb_remainder, //binaryfunc nb_remainder
nb_divmod, //binaryfunc nb_divmod
nb_power, //ternaryfunc nb_power
nb_negative, //unaryfunc nb_negative
nb_positive, //unaryfunc nb_positive
nb_absolute, //unaryfunc nb_absolute
0, //inquiry nb_bool
nb_invert, //unaryfunc nb_invert
nb_lshift, //binaryfunc nb_lshift
nb_rshift, //binaryfunc nb_rshift
nb_and, //binaryfunc nb_and
nb_xor, //binaryfunc nb_xor
nb_or, //binaryfunc nb_or
nb_int, //unaryfunc nb_int
0, //void *nb_reserved
nb_float, //unaryfunc nb_float
nb_inplace_add, //binaryfunc nb_inplace_add
nb_inplace_subtract, //binaryfunc nb_inplace_subtract
nb_inplace_multiply, //binaryfunc nb_inplace_multiply
nb_inplace_remainder, //binaryfunc nb_inplace_remainder
nb_inplace_power, //ternaryfunc nb_inplace_power
nb_inplace_lshift, //binaryfunc nb_inplace_lshift
nb_inplace_rshift, //binaryfunc nb_inplace_rshift
nb_inplace_and, //binaryfunc nb_inplace_and
nb_inplace_xor, //binaryfunc nb_inplace_xor
nb_inplace_or, //binaryfunc nb_inplace_or
nb_floor_divide, //binaryfunc nb_floor_divide
nb_true_divide, //binaryfunc nb_true_divide
nb_inplace_floor_divide, //binaryfunc nb_inplace_floor_divide
nb_inplace_true_divide, //binaryfunc nb_inplace_true_divide
nb_index, //unaryfunc nb_index
nb_matmul, //binaryfunc nb_matrix_multiply
nb_inplace_matrix_multiply //binaryfunc nb_inplace_matrix_multiply
};
}
// static
Py_ssize_t PyInstance::mp_and_sq_length(PyObject* o) {
return specializeForTypeReturningSizeT(o, [&](auto& subtype) {
return subtype.mp_and_sq_length_concrete();
});
}
Py_ssize_t PyInstance::mp_and_sq_length_concrete() {
PyErr_Format(
PyExc_TypeError,
"object of type '%S' has no len()",
(PyObject*)((PyObject*)this)->ob_type
);
return -1;
}
int PyInstance::sq_contains(PyObject* o, PyObject* item) {
return specializeForTypeReturningInt(o, [&](auto& subtype) {
return subtype.sq_contains_concrete(item);
});
}
int PyInstance::sq_contains_concrete(PyObject* item) {
PyErr_Format(PyExc_TypeError, "Argument of type '%S' is not iterable", (PyObject*)((PyObject*)this)->ob_type);
return -1;
}
int PyInstance::mp_ass_subscript(PyObject* o, PyObject* item, PyObject* value) {
return specializeForTypeReturningInt(o, [&](auto& subtype) {
return subtype.mp_ass_subscript_concrete(item, value);
});
}
int PyInstance::mp_ass_subscript_concrete(PyObject* item, PyObject* value) {
PyErr_Format(PyExc_TypeError, "'%S' object does not support item assignment", (PyObject*)((PyObject*)this)->ob_type);
return -1;
}
PyObject* PyInstance::mp_subscript(PyObject* o, PyObject* item) {
return specializeForType(o, [&](auto& subtype) {
return subtype.mp_subscript_concrete(item);
});
}
PyObject* PyInstance::mp_subscript_concrete(PyObject* item) {
PyErr_Format(PyExc_TypeError, "'%S' object is not subscriptable", (PyObject*)((PyObject*)this)->ob_type);
return NULL;
}
// static
PyMappingMethods* PyInstance::mappingMethods(Type* t) {
static PyMappingMethods* res =
new PyMappingMethods {
PyInstance::mp_and_sq_length, //mp_length
PyInstance::mp_subscript, //mp_subscript
PyInstance::mp_ass_subscript //mp_ass_subscript
};
if (t->getTypeCategory() == Type::TypeCategory::catConstDict ||
t->getTypeCategory() == Type::TypeCategory::catDict ||
t->getTypeCategory() == Type::TypeCategory::catTupleOf ||
t->getTypeCategory() == Type::TypeCategory::catListOf ||
t->getTypeCategory() == Type::TypeCategory::catClass) {
return res;
}
return 0;
}
// static
PyBufferProcs* PyInstance::bufferProcs() {
static PyBufferProcs* procs = new PyBufferProcs { 0, 0 };
return procs;
}
/**
Determine if a given PyTypeObject* is one of our types.
We are using pointer-equality with the tp_as_buffer function pointer
that we set on our types. This should be safe because:
- No other type can be pointing to it, and
- All of our types point to the unique instance of PyBufferProcs
*/
// static
inline bool PyInstance::isNativeType(PyTypeObject* typeObj) {
return typeObj->tp_as_buffer == bufferProcs();
}
/**
* Return true if the given PyTypeObject* is a subclass of a NativeType.
* This will return false when called with a native type
*/
// static
bool PyInstance::isSubclassOfNativeType(PyTypeObject* typeObj) {
if (isNativeType(typeObj)) {
return false;
}
while (typeObj) {
if (isNativeType(typeObj)) {
return true;
}
typeObj = typeObj->tp_base;
}
return false;
}
// static
Type* PyInstance::extractTypeFrom(PyTypeObject* typeObj, bool exact /*=false*/) {
if (exact && isSubclassOfNativeType(typeObj)) {
return PythonSubclass::Make(extractTypeFrom(typeObj), typeObj);
}
while (!exact && typeObj->tp_base && !isNativeType(typeObj)) {
typeObj = typeObj->tp_base;
}
if (isNativeType(typeObj)) {
return ((NativeTypeWrapper*)typeObj)->mType;
} else {
return nullptr;
}
}
PyTypeObject* PyInstance::typeObjInternal(Type* inType) {
static std::recursive_mutex mutex;
static std::map<Type*, NativeTypeWrapper*> types;
std::lock_guard<std::recursive_mutex> lock(mutex);
auto it = types.find(inType);
if (it != types.end()) {
return (PyTypeObject*)it->second;
}
types[inType] = new NativeTypeWrapper { {
PyVarObject_HEAD_INIT(NULL, 0) // TYPE (c.f., Type Objects)
.tp_name = (new std::string(inType->name()))->c_str(), // const char*
.tp_basicsize = sizeof(PyInstance), // Py_ssize_t
.tp_itemsize = 0, // Py_ssize_t
.tp_dealloc = PyInstance::tp_dealloc, // destructor
.tp_print = 0, // printfunc
.tp_getattr = 0, // getattrfunc
.tp_setattr = 0, // setattrfunc
.tp_as_async = 0, // PyAsyncMethods*
.tp_repr = tp_repr, // reprfunc
.tp_as_number = numberMethods(inType), // PyNumberMethods*
.tp_as_sequence = sequenceMethodsFor(inType), // PySequenceMethods*
.tp_as_mapping = mappingMethods(inType), // PyMappingMethods*
.tp_hash = tp_hash, // hashfunc
.tp_call = tp_call, // ternaryfunc
.tp_str = tp_str, // reprfunc
.tp_getattro = PyInstance::tp_getattro, // getattrofunc
.tp_setattro = PyInstance::tp_setattro, // setattrofunc
.tp_as_buffer = bufferProcs(), // PyBufferProcs*
.tp_flags = typeCanBeSubclassed(inType) ?
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
: Py_TPFLAGS_DEFAULT, // unsigned long
.tp_doc = 0, // const char*
.tp_traverse = 0, // traverseproc
.tp_clear = 0, // inquiry
.tp_richcompare = tp_richcompare, // richcmpfunc
.tp_weaklistoffset = 0, // Py_ssize_t
.tp_iter = inType->getTypeCategory() == Type::TypeCategory::catConstDict ||
inType->getTypeCategory() == Type::TypeCategory::catDict
?
PyInstance::tp_iter
: 0, // getiterfunc tp_iter;
.tp_iternext = PyInstance::tp_iternext,// iternextfunc
.tp_methods = typeMethods(inType), // struct PyMethodDef*
.tp_members = 0, // struct PyMemberDef*
.tp_getset = 0, // struct PyGetSetDef*
.tp_base = 0, // struct _typeobject*
.tp_dict = PyDict_New(), // PyObject*
.tp_descr_get = 0, // descrgetfunc
.tp_descr_set = 0, // descrsetfunc
.tp_dictoffset = 0, // Py_ssize_t
.tp_init = 0, // initproc
.tp_alloc = 0, // allocfunc
.tp_new = PyInstance::tp_new, // newfunc
.tp_free = 0, // freefunc /* Low-level free-memory routine */
.tp_is_gc = 0, // inquiry /* For PyObject_IS_GC */
.tp_bases = 0, // PyObject*
.tp_mro = 0, // PyObject* /* method resolution order */
.tp_cache = 0, // PyObject*
.tp_subclasses = 0, // PyObject*
.tp_weaklist = 0, // PyObject*
.tp_del = 0, // destructor
.tp_version_tag = 0, // unsigned int
.tp_finalize = 0, // destructor
}, inType
};
// at this point, the dictionary has an entry, so if we recurse back to this function
// we will return the correct entry.
if (inType->getBaseType()) {
types[inType]->typeObj.tp_base = typeObjInternal((Type*)inType->getBaseType());
incref((PyObject*)types[inType]->typeObj.tp_base);
}
PyType_Ready((PyTypeObject*)types[inType]);
PyDict_SetItemString(
types[inType]->typeObj.tp_dict,
"__typed_python_category__",
categoryToPyString(inType->getTypeCategory())
);
PyDict_SetItemString(
types[inType]->typeObj.tp_dict,
"__typed_python_basetype__",
inType->getBaseType() ?
(PyObject*)typeObjInternal(inType->getBaseType())
: Py_None
);
mirrorTypeInformationIntoPyType(inType, &types[inType]->typeObj);
return (PyTypeObject*)types[inType];
}
// static
int PyInstance::tp_setattro(PyObject *o, PyObject* attrName, PyObject* attrVal) {
if (!PyUnicode_Check(attrName)) {
PyErr_Format(
PyExc_AttributeError,
"Cannot set attribute '%S' on instance of type '%S'. Attribute does not resolve to a string",
attrName, o->ob_type
);
return -1;
}
return specializeForTypeReturningInt(o, [&](auto& subtype) {
return subtype.tp_setattr_concrete(attrName, attrVal);
});
}
int PyInstance::tp_setattr_concrete(PyObject* attrName, PyObject* attrVal) {
PyErr_Format(
PyExc_AttributeError,
"Instances of type '%s' do not accept attributes",
attrName,
type()->name().c_str()
);
return -1;
}
// static
PyObject* PyInstance::tp_call(PyObject* o, PyObject* args, PyObject* kwargs) {
return specializeForType(o, [&](auto& subtype) {
return subtype.tp_call_concrete(args, kwargs);
});
}
PyObject* PyInstance::tp_call_concrete(PyObject* args, PyObject* kwargs) {
PyErr_Format(PyExc_TypeError, "'%s' object is not callable", type()->name().c_str());
return 0;
}
PyObject* PyInstance::tp_getattr_concrete(PyObject* pyAttrName, const char* attrName) {
return PyObject_GenericGetAttr((PyObject*)this, pyAttrName);
}
// static
PyObject* PyInstance::tp_getattro(PyObject *o, PyObject* attrName) {
if (!PyUnicode_Check(attrName)) {
PyErr_SetString(PyExc_AttributeError, "attribute is not a string");
return NULL;
}
char *attr_name = PyUnicode_AsUTF8(attrName);
return specializeForType(o, [&](auto& subtype) {
return subtype.tp_getattr_concrete(attrName, attr_name);
});
}
// static
Py_hash_t PyInstance::tp_hash(PyObject *o) {
Type* self_type = extractTypeFrom(o->ob_type);
PyInstance* w = (PyInstance*)o;
int32_t h = self_type->hash32(w->dataPtr());
if (h == -1) {
h = -2;
}
return h;
}
// static
bool PyInstance::compare_to_python(Type* t, instance_ptr self, PyObject* other, bool exact, int pyComparisonOp) {
if (t->getTypeCategory() == Type::TypeCategory::catValue) {
Value* valType = (Value*)t;
return compare_to_python(valType->value().type(), valType->value().data(), other, exact, pyComparisonOp);
}
Type* otherT = extractTypeFrom(other->ob_type);
if (otherT) {
if (otherT < t) {
return cmpResultToBoolForPyOrdering(pyComparisonOp, 1);
}
if (otherT > t) {
return cmpResultToBoolForPyOrdering(pyComparisonOp, -1);
}
return t->cmp(self, ((PyInstance*)other)->dataPtr(), pyComparisonOp);
}
return specializeStatic(t->getTypeCategory(), [&](auto* concrete_null_ptr) {
typedef typename std::remove_reference<decltype(*concrete_null_ptr)>::type py_instance_type;
return py_instance_type::compare_to_python_concrete(
(typename py_instance_type::modeled_type*)t,
self,
other,
exact,
pyComparisonOp
);
});
}
bool PyInstance::compare_to_python_concrete(Type* t, instance_ptr self, PyObject* other, bool exact, int pyComparisonOp) {
return cmpResultToBoolForPyOrdering(pyComparisonOp, -1);
}
int PyInstance::reversePyOpOrdering(int op) {
if (op == Py_LT) {
return Py_GT;
}
if (op == Py_LE) {
return Py_GE;
}
if (op == Py_GT) {
return Py_LT;
}
if (op == Py_GE) {
return Py_LE;
}
return op;
}
// static
PyObject* PyInstance::tp_richcompare(PyObject *a, PyObject *b, int op) {
try {
Type* own = extractTypeFrom(a->ob_type);
Type* other = extractTypeFrom(b->ob_type);
if (!own && !other) {
PyErr_Format(PyExc_TypeError, "Can't call tp_richcompare where neither object is a typed_python object!");
return NULL;
}
if (!own || !other) {
bool cmp;
if (own) {
cmp = compare_to_python(own, ((PyInstance*)a)->dataPtr(), b, false, op);
} else {
cmp = compare_to_python(other, ((PyInstance*)b)->dataPtr(), a, false, reversePyOpOrdering(op));
}
return incref(cmp ? Py_True : Py_False);
} else {
bool result;
if (own < other) {
result = cmpResultToBoolForPyOrdering(op, -1);
} else if (own > other) {
result = cmpResultToBoolForPyOrdering(op, 1);
} else {
result = own->cmp(((PyInstance*)a)->dataPtr(), ((PyInstance*)b)->dataPtr(), op);
}
return incref(result ? Py_True : Py_False);
}
} catch(PythonExceptionSet& e) {
return NULL;
} catch(std::exception& e) {
PyErr_SetString(PyExc_TypeError, e.what());
return NULL;
}
}
// static