-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPyObject.hpp
More file actions
835 lines (716 loc) · 31 KB
/
Copy pathPyObject.hpp
File metadata and controls
835 lines (716 loc) · 31 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
#pragma once
#include "../utilities.hpp"
#include "Value.hpp"
#include "concepts.hpp"
#include "forward.hpp"
#include "memory/GarbageCollector.hpp"
#include "runtime/forward.hpp"
#include "vm/VM.hpp"
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <spdlog/fmt/fmt.h>
namespace py {
enum class RichCompare {
Py_LT = 0,// <
Py_LE = 1,// <=
Py_EQ = 2,// ==
Py_NE = 3,// !=
Py_GT = 4,// >
Py_GE = 5,// >=
};
class PyObject;
class MethodFlags
{
std::bitset<10> m_flags;
public:
enum class Flag {
VARARGS = 0,
KEYWORDS = 1,
NOARGS = 2,
O = 3,
CLASSMETHOD = 4,
STATICMETHOD = 5,
COEXIST = 6,
FASTCALL = 7,
STACKLESS = 8,
METHOD = 9,
};
public:
template<typename... Args> static MethodFlags create(Args... args)
{
MethodFlags f;
(f.m_flags.set(static_cast<uint8_t>(args)), ...);
return f;
}
bool is_set(Flag f) const { return m_flags.test(static_cast<size_t>(f)); }
const std::bitset<10> &flags() const { return m_flags; }
};
struct MethodDefinition
{
std::string name;
std::function<PyResult<PyObject *>(PyObject * /* self or cls */,
PyTuple * /* args */,
PyDict * /* kwargs */)>
method;
MethodFlags flags;
std::string doc;
};
struct MemberDefinition
{
std::string name;
std::function<PyResult<PyObject *>(PyObject *)> member_accessor;
std::function<PyResult<std::monostate>(PyObject *, PyObject *)> member_setter;
};
struct PropertyDefinition
{
std::string name;
std::optional<std::function<PyResult<PyObject *>(PyObject *)>> member_getter;
std::optional<std::function<PyResult<std::monostate>(PyObject *, PyObject *)>> member_setter;
};
using CallSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyTuple *, PyDict *)>;
using StrSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *)>;
using NewSlotFunctionType =
std::function<PyResult<PyObject *>(const PyType *, PyTuple *, PyDict *)>;
using InitSlotFunctionType = std::function<PyResult<int32_t>(PyObject *, PyTuple *, PyDict *)>;
using GetAttroFunctionType = std::function<PyResult<PyObject *>(const PyObject *, PyObject *)>;
using SetAttroFunctionType =
std::function<PyResult<std::monostate>(PyObject *, PyObject *, PyObject *)>;
using DelAttroFunctionType = std::function<PyResult<std::monostate>(PyObject *, PyObject *)>;
using GetSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, PyObject *, PyObject *)>;
using SetSlotFunctionType =
std::function<PyResult<std::monostate>(PyObject *, PyObject *, PyObject *)>;
using DeleteSlotFunctionType = std::function<PyResult<std::monostate>(PyObject *, PyObject *)>;
using GetItemSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using SetItemSlotFunctionType =
std::function<PyResult<std::monostate>(PyObject *, PyObject *, PyObject *)>;
using DelItemSlotFunctionType = std::function<PyResult<std::monostate>(PyObject *, PyObject *)>;
using RepeatSequenceSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, size_t)>;
using GetItemSequenceSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, int64_t)>;
using SetItemSequenceSlotFunctionType =
std::function<PyResult<std::monostate>(PyObject *, int64_t, PyObject *)>;
using DelItemSequenceSlotFunctionType =
std::function<PyResult<std::monostate>(PyObject *, int64_t)>;
using LenSlotFunctionType = std::function<PyResult<size_t>(const PyObject *)>;
using BoolSlotFunctionType = std::function<PyResult<bool>(const PyObject *)>;
using ContainsSlotFunctionType = std::function<PyResult<bool>(PyObject *, PyObject *)>;
using ReprSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using IterSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using NextSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *)>;
using AbsSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using NegSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using PosSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using InvertSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *)>;
using AddSlotFunctionType = std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using SubtractSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using MultiplySlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using PowSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *, const PyObject *)>;
using FloorDivSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using TrueDivSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using LeftShiftSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using RightShiftSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using ModuloSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using DivmodSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using AndSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using OrSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using XorSlotFunctionType = std::function<PyResult<PyObject *>(PyObject *, PyObject *)>;
using HashSlotFunctionType = std::function<PyResult<int64_t>(const PyObject *)>;
using CompareSlotFunctionType =
std::function<PyResult<PyObject *>(const PyObject *, const PyObject *)>;
using TraverseFunctionType = std::function<void(PyObject *, Cell::Visitor &)>;
struct NumberTypePrototype
{
};
struct MappingTypePrototype
{
std::optional<std::variant<LenSlotFunctionType, PyObject *>> __len__;
std::optional<std::variant<GetItemSlotFunctionType, PyObject *>> __getitem__;
std::optional<std::variant<SetItemSlotFunctionType, PyObject *>> __setitem__;
std::optional<std::variant<DelItemSlotFunctionType, PyObject *>> __delitem__;
};
struct SequenceTypePrototype
{
std::optional<std::variant<LenSlotFunctionType, PyObject *>> __len__;
std::optional<std::variant<AddSlotFunctionType, PyObject *>> __concat__;
std::optional<std::variant<RepeatSequenceSlotFunctionType, PyObject *>> __repeat__;
std::optional<std::variant<GetItemSequenceSlotFunctionType, PyObject *>> __getitem__;
std::optional<std::variant<SetItemSequenceSlotFunctionType, PyObject *>> __setitem__;
std::optional<std::variant<DelItemSequenceSlotFunctionType, PyObject *>> __delitem__;
std::optional<std::variant<ContainsSlotFunctionType, PyObject *>> __contains__;
};
template<typename T> struct OwningStorage;
template<typename T> struct NonOwningStorage;
struct Storage
{
virtual ~Storage() = default;
virtual void *get_buffer() = 0;
virtual void set_buffer(void *) = 0;
virtual std::unique_ptr<Storage> view() = 0;
};
template<typename T> struct OwningStorage : Storage
{
OwningStorage(T *buffer) : m_storage(buffer) {}
~OwningStorage()
{
if (m_storage) { delete m_storage; }
}
void *get_buffer() final { return static_cast<void *>(m_storage); }
void set_buffer(void *ptr) final { m_storage = static_cast<T *>(ptr); }
std::unique_ptr<Storage> view() final
{
return std::make_unique<NonOwningStorage<T>>(m_storage);
}
T *m_storage;
};
template<typename T> struct NonOwningStorage : Storage
{
NonOwningStorage(T *buffer) : m_storage(buffer) {}
~NonOwningStorage() = default;
void *get_buffer() final { return static_cast<void *>(m_storage); }
void set_buffer(void *ptr) final { m_storage = static_cast<T *>(ptr); }
std::unique_ptr<Storage> view() final
{
return std::make_unique<NonOwningStorage<T>>(m_storage);
}
T *m_storage;
};
struct PyBuffer
{
std::unique_ptr<Storage> buf;
PyObject *obj;
int64_t len;
int64_t itemsize;
int readonly;
int ndim;
std::string format;
std::vector<int64_t> shape;
std::vector<int64_t> strides;
std::vector<int64_t> suboffsets;
void *internal;
bool is_ccontiguous() const { return len == 0 || strides.empty(); }
bool is_contiguous(char order) const
{
if (!suboffsets.empty()) return false;
if (order == 'C') {
return is_ccontiguous();
} else {
TODO();
}
return false;
}
};
struct PyBufferProcs
{
std::function<PyResult<std::monostate>(PyObject *, PyBuffer &, int)> getbuffer;
std::function<PyResult<std::monostate>(PyObject *, PyBuffer &)> releasebuffer;
};
struct TypePrototype
{
private:
TypePrototype(const TypePrototype &) = default;
TypePrototype &operator=(const TypePrototype &) = default;
public:
TypePrototype() = default;
std::unique_ptr<TypePrototype> clone() const
{
return std::unique_ptr<TypePrototype>(new TypePrototype{ *this });
}
public:
std::string __name__;
size_t basicsize;
PyType *__base__{ nullptr };
std::vector<PyType *> __bases__{ nullptr };
std::function<PyResult<PyObject *>(PyType *)> __alloc__;
std::optional<std::variant<NewSlotFunctionType, PyObject *>> __new__;
std::optional<std::variant<InitSlotFunctionType, PyObject *>> __init__;
PyType *__class__{ nullptr };
std::optional<std::string> __doc__;
std::optional<NumberTypePrototype> number_type_protocol;
std::optional<MappingTypePrototype> mapping_type_protocol;
std::optional<SequenceTypePrototype> sequence_type_protocol;
std::optional<std::variant<GetAttroFunctionType, PyObject *>> __getattribute__;
std::optional<std::variant<SetAttroFunctionType, PyObject *>> __setattribute__;
std::optional<std::variant<DelAttroFunctionType, PyObject *>> __delattribute__;
std::optional<std::variant<GetSlotFunctionType, PyObject *>> __get__;
std::optional<std::variant<SetSlotFunctionType, PyObject *>> __set__;
std::optional<std::variant<DeleteSlotFunctionType, PyObject *>> __delete__;
std::optional<std::variant<AddSlotFunctionType, PyObject *>> __add__;
std::optional<std::variant<SubtractSlotFunctionType, PyObject *>> __sub__;
std::optional<std::variant<MultiplySlotFunctionType, PyObject *>> __mul__;
std::optional<std::variant<PowSlotFunctionType, PyObject *>> __pow__;
std::optional<std::variant<TrueDivSlotFunctionType, PyObject *>> __truediv__;
std::optional<std::variant<FloorDivSlotFunctionType, PyObject *>> __floordiv__;
std::optional<std::variant<LeftShiftSlotFunctionType, PyObject *>> __lshift__;
std::optional<std::variant<RightShiftSlotFunctionType, PyObject *>> __rshift__;
std::optional<std::variant<ModuloSlotFunctionType, PyObject *>> __mod__;
std::optional<std::variant<DivmodSlotFunctionType, PyObject *>> __divmod__;
std::optional<std::variant<AndSlotFunctionType, PyObject *>> __and__;
std::optional<std::variant<OrSlotFunctionType, PyObject *>> __or__;
std::optional<std::variant<XorSlotFunctionType, PyObject *>> __xor__;
std::optional<std::variant<AbsSlotFunctionType, PyObject *>> __abs__;
std::optional<std::variant<NegSlotFunctionType, PyObject *>> __neg__;
std::optional<std::variant<PosSlotFunctionType, PyObject *>> __pos__;
std::optional<std::variant<InvertSlotFunctionType, PyObject *>> __invert__;
std::optional<std::variant<CallSlotFunctionType, PyObject *>> __call__;
std::optional<std::variant<StrSlotFunctionType, PyObject *>> __str__;
std::optional<std::variant<BoolSlotFunctionType, PyObject *>> __bool__;
std::optional<std::variant<ReprSlotFunctionType, PyObject *>> __repr__;
std::optional<std::variant<IterSlotFunctionType, PyObject *>> __iter__;
std::optional<std::variant<NextSlotFunctionType, PyObject *>> __next__;
std::optional<std::variant<HashSlotFunctionType, PyObject *>> __hash__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __eq__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __gt__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __ge__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __le__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __lt__;
std::optional<std::variant<CompareSlotFunctionType, PyObject *>> __ne__;
std::optional<PyBufferProcs> as_buffer;
std::vector<MemberDefinition> __members__;
std::vector<PropertyDefinition> __getset__;
std::vector<MethodDefinition> __methods__;
PyDict *__dict__{ nullptr };
std::optional<TraverseFunctionType> traverse;
bool is_ready{ false };
bool is_heaptype{ false };
bool is_type{ false };
template<typename Type, typename... Args>
static std::unique_ptr<TypePrototype> create(std::string_view name, Args &&...);
void add_member(MemberDefinition &&member) { __members__.push_back(std::move(member)); }
void add_property(PropertyDefinition &&property) { __getset__.push_back(std::move(property)); }
void add_method(MethodDefinition &&method) { __methods__.push_back(std::move(method)); }
void visit_graph(::Cell::Visitor &visitor);
};
template<typename T, typename... U>
size_t get_address(const std::variant<std::function<T(U...)>, PyObject *> &f)
{
// adapted from https://stackoverflow.com/a/35920804
if (std::holds_alternative<std::function<T(U...)>>(f)) {
using FunctionType = T (*)(U...);
auto fn_ptr = std::get<std::function<T(U...)>>(f).template target<FunctionType>();
return bit_cast<size_t>(*fn_ptr);
} else {
// FIXME: is it valid to take this path? Is there use case?
return bit_cast<size_t>(std::get<PyObject *>(f));
}
}
enum class LookupAttrResult { NOT_FOUND = 0, FOUND = 1 };
class PyMappingWrapper
{
PyObject *m_object;
public:
PyMappingWrapper(PyObject *object) : m_object(object) {}
PyResult<size_t> len();
PyResult<PyObject *> getitem(PyObject *);// mp_subscript
PyResult<std::monostate> setitem(PyObject *, PyObject *);// mp_ass_subscript
PyResult<std::monostate> delitem(PyObject *);// mp_ass_subscript
};
struct PySequence
{
};
class PySequenceWrapper
{
PyObject *m_object;
public:
PySequenceWrapper(PyObject *object) : m_object(object) {}
PyResult<size_t> len();
PyResult<PyObject *> concat(PyObject *other);
PyResult<PyObject *> getitem(int64_t);// sq_item
PyResult<std::monostate> setitem(int64_t, PyObject *);// sq_ass_item
PyResult<std::monostate> delitem(int64_t);// sq_ass_item
PyResult<bool> contains(PyObject *);
PyResult<PyObject *> repeat(const PyObject *);
};
class PyObject : public Cell
{
friend class ::Heap;
friend PyMappingWrapper;
friend PySequenceWrapper;
friend class PyType;
protected:
std::variant<std::reference_wrapper<const TypePrototype>, PyType *> m_type;
PyDict *m_attributes{ nullptr };
public:
PyObject() = delete;
PyObject(const TypePrototype &type);
PyObject(PyType *type);
virtual ~PyObject() = default;
virtual PyType *static_type() const;
PyType *type() const;
template<typename T> static PyResult<PyObject *> from(const T &value);
void visit_graph(Visitor &) override;
PyResult<PyMappingWrapper> as_mapping();
PyResult<PySequenceWrapper> as_sequence();
PyResult<PyBufferProcs> as_buffer();
// TODO: add strongly typed flags
PyResult<std::monostate> get_buffer(PyBuffer &, int flags);
PyResult<PyObject *> getattribute(PyObject *attribute) const;
PyResult<std::monostate> setattribute(PyObject *attribute, PyObject *value);
PyResult<std::monostate> delattribute(PyObject *attribute);
PyResult<PyObject *> get(PyObject *instance, PyObject *owner) const;
PyResult<PyObject *> add(const PyObject *other) const;
PyResult<PyObject *> subtract(const PyObject *other) const;
PyResult<PyObject *> multiply(const PyObject *other) const;
PyResult<PyObject *> pow(const PyObject *other, const PyObject *modulo) const;
PyResult<PyObject *> floordiv(PyObject *);
PyResult<PyObject *> truediv(PyObject *);
PyResult<PyObject *> lshift(const PyObject *other) const;
PyResult<PyObject *> rshift(const PyObject *other) const;
PyResult<PyObject *> modulo(const PyObject *other) const;
PyResult<PyObject *> divmod(PyObject *other);
PyResult<PyObject *> and_(PyObject *other);
PyResult<PyObject *> or_(PyObject *other);
PyResult<PyObject *> xor_(PyObject *other);
PyResult<bool> contains(PyObject *value);
PyResult<std::monostate> delete_item(PyObject *key);
PyResult<PyObject *> neg() const;
PyResult<PyObject *> pos() const;
PyResult<PyObject *> abs() const;
PyResult<PyObject *> invert() const;
PyResult<PyString *> repr() const;
PyResult<PyString *> str();
PyResult<int64_t> hash() const;
PyResult<PyObject *> richcompare(const PyObject *other, RichCompare) const;
PyResult<PyObject *> eq(const PyObject *other) const;
PyResult<PyObject *> ge(const PyObject *other) const;
PyResult<PyObject *> gt(const PyObject *other) const;
PyResult<PyObject *> le(const PyObject *other) const;
PyResult<PyObject *> lt(const PyObject *other) const;
PyResult<PyObject *> ne(const PyObject *other) const;
virtual PyResult<bool> true_();
PyResult<PyObject *> iter() const;
PyResult<PyObject *> next();
PyResult<PyObject *> call(PyTuple *args, PyDict *kwargs);
virtual PyResult<PyObject *> new_(PyTuple *args, PyDict *kwargs) const;
PyResult<int32_t> init(PyTuple *args, PyDict *kwargs);
PyResult<PyObject *> getitem(PyObject *key);
PyResult<PyObject *> getitem(size_t index);
PyResult<std::monostate> setitem(PyObject *key, PyObject *value);
PyResult<std::monostate> delitem(PyObject *key);
static PyResult<PyObject *> __new__(const PyType *type, PyTuple *args, PyDict *kwargs);
PyResult<int32_t> __init__(PyTuple *args, PyDict *kwargs);
PyResult<PyObject *> __getattribute__(PyObject *attribute) const;
PyResult<std::monostate> __setattribute__(PyObject *attribute, PyObject *value);
PyResult<std::monostate> __delattribute__(PyObject *attribute);
PyResult<PyObject *> __eq__(const PyObject *other) const;
PyResult<PyObject *> __ne__(const PyObject *other) const;
PyResult<PyObject *> __repr__() const;
PyResult<int64_t> __hash__() const;
PyResult<PyObject *> __str__();
bool is_pyobject() const override { return true; }
bool is_callable() const;
const std::string &name() const;
const TypePrototype &type_prototype() const;
const PyDict *attributes() const { return m_attributes; }
PyDict *attributes() { return m_attributes; }
PyResult<PyObject *> get_method(PyObject *name) const;
PyResult<PyObject *> get_attribute(PyObject *name) const;
std::tuple<PyResult<PyObject *>, LookupAttrResult> lookup_attribute(PyObject *name) const;
static std::function<std::unique_ptr<TypePrototype>()> type_factory();
std::string to_string() const override;
};
// avoid explicit specialization after instantiations
template<> PyResult<PyObject *> PyObject::from(PyObject *const &value);
template<> PyResult<PyObject *> PyObject::from(const Number &value);
template<> PyResult<PyObject *> PyObject::from(const int64_t &value);
template<> PyResult<PyObject *> PyObject::from(const String &value);
template<> PyResult<PyObject *> PyObject::from(const Bytes &value);
template<> PyResult<PyObject *> PyObject::from(const Ellipsis &value);
template<> PyResult<PyObject *> PyObject::from(const NameConstant &value);
template<> PyResult<PyObject *> PyObject::from(const Value &value);
// repr() of a (possibly unboxed) Value. Inline values are boxed first so their
// repr matches PyObject elements (e.g. strings are quoted) — used by container
// repr/str so str(["a"]) and str(("a",)) both render 'a' with quotes.
PyResult<PyString *> repr_value(const Value &value);
BaseException *memory_error(size_t failed_allocation_size);
namespace detail {
size_t slot_count(PyType *);
}
namespace detail {
// Lazy-initialize the optional protocol structs that hold mapping /
// sequence / buffer slots, returning a reference to the live one.
inline MappingTypePrototype &ensure_mapping_proto(TypePrototype &tp)
{
if (!tp.mapping_type_protocol.has_value()) {
tp.mapping_type_protocol = MappingTypePrototype{};
}
return *tp.mapping_type_protocol;
}
inline SequenceTypePrototype &ensure_sequence_proto(TypePrototype &tp)
{
if (!tp.sequence_type_protocol.has_value()) {
tp.sequence_type_protocol = SequenceTypePrototype{};
}
return *tp.sequence_type_protocol;
}
inline PyBufferProcs &ensure_buffer_proto(TypePrototype &tp)
{
if (!tp.as_buffer.has_value()) { tp.as_buffer = PyBufferProcs{}; }
return *tp.as_buffer;
}
}// namespace detail
// Slot-installer macros. Each one expands to the same shape:
// if constexpr (concepts::Concept<Type>) { <slot> = +[](sig){ cast(self)->method(args...); }; }
// The macro names encode the trampoline signature so picking the right one
// is mechanical. Defined here as local macros for TypePrototype::create only
// and #undef'd at the end of the function so they don't leak.
#define PYC_SLOT_UNARY_CONST_PYOBJ(Concept, Slot, Method) \
if constexpr (concepts::Concept<Type>) { \
type_prototype->Slot = +[](const PyObject *self) -> PyResult<PyObject *> { \
return static_cast<const Type *>(self)->Method(); \
}; \
}
#define PYC_SLOT_UNARY_PYOBJ(Concept, Slot, Method) \
if constexpr (concepts::Concept<Type>) { \
type_prototype->Slot = +[](PyObject *self) -> PyResult<PyObject *> { \
return static_cast<Type *>(self)->Method(); \
}; \
}
#define PYC_SLOT_BINARY_CONST_PYOBJ(Concept, Slot, Method) \
if constexpr (concepts::Concept<Type>) { \
type_prototype->Slot = \
+[](const PyObject *self, const PyObject *other) -> PyResult<PyObject *> { \
return static_cast<const Type *>(self)->Method(other); \
}; \
}
#define PYC_SLOT_BINARY_PYOBJ(Concept, Slot, Method) \
if constexpr (concepts::Concept<Type>) { \
type_prototype->Slot = +[](PyObject *self, PyObject *other) -> PyResult<PyObject *> { \
return static_cast<Type *>(self)->Method(other); \
}; \
}
template<typename Type, typename... Args>
std::unique_ptr<TypePrototype> TypePrototype::create(std::string_view name, Args &&...args)
{
auto type_prototype = std::make_unique<TypePrototype>();
type_prototype->__name__ = std::string(name);
type_prototype->__bases__ = std::vector<PyType *>{ args... };
type_prototype->basicsize = sizeof(Type);
type_prototype->__alloc__ = [](PyType *t) -> PyResult<PyObject *> {
auto *obj = [t]() -> Type * {
if (const auto nslots = py::detail::slot_count(t); nslots > 0) {
return VirtualMachine::the().heap().allocate_with_extra_bytes<Type>(
nslots * sizeof(PyObject *), t);
} else {
return VirtualMachine::the().heap().allocate<Type>(t);
};
}();
if (!obj) { return Err(memory_error(sizeof(Type))); }
return Ok(obj);
};
// Plain slots that follow the standard `cast(self)->__x__(args)` shape.
PYC_SLOT_UNARY_CONST_PYOBJ(HasRepr, __repr__, __repr__)
PYC_SLOT_UNARY_CONST_PYOBJ(HasIter, __iter__, __iter__)
PYC_SLOT_UNARY_PYOBJ(HasNext, __next__, __next__)
PYC_SLOT_UNARY_PYOBJ(HasStr, __str__, __str__)
PYC_SLOT_UNARY_CONST_PYOBJ(HasAbs, __abs__, __abs__)
PYC_SLOT_UNARY_CONST_PYOBJ(HasNeg, __neg__, __neg__)
PYC_SLOT_UNARY_CONST_PYOBJ(HasPos, __pos__, __pos__)
PYC_SLOT_UNARY_CONST_PYOBJ(HasInvert, __invert__, __invert__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasLt, __lt__, __lt__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasLe, __le__, __le__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasEq, __eq__, __eq__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasNe, __ne__, __ne__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasGt, __gt__, __gt__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasGe, __ge__, __ge__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasSub, __sub__, __sub__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasLshift, __lshift__, __lshift__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasRshift, __rshift__, __rshift__)
PYC_SLOT_BINARY_CONST_PYOBJ(HasModulo, __mod__, __mod__)
PYC_SLOT_BINARY_PYOBJ(HasTrueDiv, __truediv__, __truediv__)
PYC_SLOT_BINARY_PYOBJ(HasFloorDiv, __floordiv__, __floordiv__)
PYC_SLOT_BINARY_PYOBJ(HasDivmod, __divmod__, __divmod__)
PYC_SLOT_BINARY_PYOBJ(HasAnd, __and__, __and__)
PYC_SLOT_BINARY_PYOBJ(HasOr, __or__, __or__)
PYC_SLOT_BINARY_PYOBJ(HasXor, __xor__, __xor__)
// Slots whose trampoline shape doesn't match the generic macros.
if constexpr (concepts::HasCall<Type>) {
type_prototype->__call__ =
+[](PyObject *self, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
return static_cast<Type *>(self)->__call__(args, kwargs);
};
}
if constexpr (concepts::HasNew<Type>) {
type_prototype->__new__ =
+[](const PyType *type, PyTuple *args, PyDict *kwargs) -> PyResult<PyObject *> {
return Type::__new__(type, args, kwargs);
};
}
if constexpr (concepts::HasInit<Type>) {
type_prototype->__init__ =
+[](PyObject *self, PyTuple *args, PyDict *kwargs) -> PyResult<int32_t> {
return static_cast<Type *>(self)->__init__(args, kwargs);
};
}
if constexpr (concepts::HasDoc<Type>) { type_prototype->__doc__ = Type::__doc__; }
if constexpr (concepts::HasHash<Type>) {
type_prototype->__hash__ = +[](const PyObject *self) -> PyResult<int64_t> {
return static_cast<const Type *>(self)->__hash__();
};
}
if constexpr (concepts::HasBool<Type>) {
type_prototype->__bool__ = +[](const PyObject *self) -> PyResult<bool> {
return static_cast<const Type *>(self)->__bool__();
};
}
if constexpr (concepts::HasPow<Type>) {
type_prototype->__pow__ = +[](const PyObject *self,
const PyObject *other,
const PyObject *modulo) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__pow__(other, modulo);
};
}
if constexpr (concepts::HasGetAttro<Type>) {
type_prototype->__getattribute__ =
+[](const PyObject *self, PyObject *attr) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__getattribute__(attr);
};
}
if constexpr (concepts::HasSetAttro<Type>) {
type_prototype->__setattribute__ =
+[](PyObject *self, PyObject *attr, PyObject *value) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__setattribute__(attr, value);
};
}
if constexpr (concepts::HasDelAttro<Type>) {
type_prototype->__delattribute__ =
+[](PyObject *self, PyObject *attr) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__delattribute__(attr);
};
}
if constexpr (concepts::HasGet<Type>) {
type_prototype->__get__ =
+[](const PyObject *self, PyObject *instance, PyObject *owner) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__get__(instance, owner);
};
}
if constexpr (concepts::HasSet<Type>) {
type_prototype->__set__ =
+[](PyObject *self, PyObject *attribute, PyObject *value) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__set__(attribute, value);
};
}
if constexpr (concepts::HasDelete<Type>) {
type_prototype->__delete__ =
+[](PyObject *self, PyObject *attribute) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__delete__(attribute);
};
}
// mapping_type_protocol slots — the protocol struct is created lazily.
if constexpr (concepts::HasLength<Type>) {
detail::ensure_mapping_proto(*type_prototype).__len__ =
+[](const PyObject *self) -> PyResult<size_t> {
return static_cast<const Type *>(self)->__len__();
};
}
if constexpr (concepts::HasGetItem<Type>) {
detail::ensure_mapping_proto(*type_prototype).__getitem__ =
+[](PyObject *self, PyObject *name) -> PyResult<PyObject *> {
return static_cast<Type *>(self)->__getitem__(name);
};
}
if constexpr (concepts::HasSetItem<Type>) {
detail::ensure_mapping_proto(*type_prototype).__setitem__ =
+[](PyObject *self, PyObject *name, PyObject *value) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__setitem__(name, value);
};
}
if constexpr (concepts::HasDelItem<Type>) {
detail::ensure_mapping_proto(*type_prototype).__delitem__ =
+[](PyObject *self, PyObject *name) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__delitem__(name);
};
}
// sequence_type_protocol slots.
if constexpr (concepts::HasContains<Type>) {
detail::ensure_sequence_proto(*type_prototype).__contains__ =
+[](PyObject *self, PyObject *value) -> PyResult<bool> {
return static_cast<Type *>(self)->__contains__(value);
};
}
if constexpr (concepts::HasSequenceGetItem<Type>) {
detail::ensure_sequence_proto(*type_prototype).__getitem__ =
+[](PyObject *self, int64_t index) -> PyResult<PyObject *> {
return static_cast<Type *>(self)->__getitem__(index);
};
}
if constexpr (concepts::HasSequenceSetItem<Type>) {
detail::ensure_sequence_proto(*type_prototype).__setitem__ =
+[](PyObject *self, int64_t index, PyObject *value) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__setitem__(index, value);
};
}
if constexpr (concepts::HasSequenceDelItem<Type>) {
detail::ensure_sequence_proto(*type_prototype).__delitem__ =
+[](PyObject *self, int64_t index) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__delitem__(index);
};
}
// PySequence subtypes route __add__/__mul__ through the sequence
// __concat__/__repeat__ slots; everyone else gets the binary operators.
if constexpr (std::is_base_of_v<PySequence, Type> && concepts::HasAdd<Type>) {
detail::ensure_sequence_proto(*type_prototype).__concat__ =
+[](const PyObject *self, const PyObject *value) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__add__(value);
};
} else if constexpr (concepts::HasAdd<Type>) {
type_prototype->__add__ =
+[](const PyObject *self, const PyObject *other) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__add__(other);
};
}
if constexpr (std::is_base_of_v<PySequence, Type> && concepts::HasRepeat<Type>) {
detail::ensure_sequence_proto(*type_prototype).__repeat__ =
+[](const PyObject *self, size_t count) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__mul__(count);
};
} else if constexpr (concepts::HasMul<Type>) {
type_prototype->__mul__ =
+[](const PyObject *self, const PyObject *other) -> PyResult<PyObject *> {
return static_cast<const Type *>(self)->__mul__(other);
};
}
// Buffer protocol.
if constexpr (concepts::HasGetBuffer<Type>) {
detail::ensure_buffer_proto(*type_prototype).getbuffer =
+[](PyObject *self, PyBuffer &view, int flags) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__getbuffer__(view, flags);
};
}
if constexpr (concepts::HasReleaseBuffer<Type>) {
detail::ensure_buffer_proto(*type_prototype).releasebuffer =
+[](PyObject *self, PyBuffer &view) -> PyResult<std::monostate> {
return static_cast<Type *>(self)->__releasebuffer__(view);
};
}
type_prototype->traverse =
+[](PyObject *self, Cell::Visitor &visitor) { self->visit_graph(visitor); };
return type_prototype;
}
#undef PYC_SLOT_UNARY_CONST_PYOBJ
#undef PYC_SLOT_UNARY_PYOBJ
#undef PYC_SLOT_BINARY_CONST_PYOBJ
#undef PYC_SLOT_BINARY_PYOBJ
class PyBaseObject : public PyObject
{
public:
PyBaseObject(const TypePrototype &type) : PyObject(type) {}
PyBaseObject(PyType *type) : PyObject(type) {}
};
struct ValueHash
{
size_t operator()(const Value &value) const;
};
struct ValueEq
{
bool operator()(const Value &lhs, const Value &rhs) const;
};
}// namespace py