-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathnb_type.cpp
2244 lines (1861 loc) · 72.2 KB
/
nb_type.cpp
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
/*
src/nb_type.cpp: libnanobind functionality for binding classes
Copyright (c) 2022 Wenzel Jakob
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include "nb_internals.h"
#if defined(_MSC_VER)
# pragma warning(disable: 4706) // assignment within conditional expression
#endif
#if !defined(Py_tp_vectorcall)
# define Py_tp_vectorcall 82
#endif
NAMESPACE_BEGIN(NB_NAMESPACE)
NAMESPACE_BEGIN(detail)
static PyObject **nb_dict_ptr(PyObject *self) {
PyTypeObject *tp = Py_TYPE(self);
#if defined(Py_LIMITED_API)
Py_ssize_t dictoffset = nb_type_data(tp)->dictoffset;
#else
Py_ssize_t dictoffset = tp->tp_dictoffset;
#endif
return dictoffset ? (PyObject **) ((uint8_t *) self + dictoffset) : nullptr;
}
static PyObject **nb_weaklist_ptr(PyObject *self) {
PyTypeObject *tp = Py_TYPE(self);
#if defined(Py_LIMITED_API)
Py_ssize_t weaklistoffset = nb_type_data(tp)->weaklistoffset;
#else
Py_ssize_t weaklistoffset = tp->tp_weaklistoffset;
#endif
return weaklistoffset ? (PyObject **) ((uint8_t *) self + weaklistoffset) : nullptr;
}
static PyGetSetDef inst_getset[] = {
{ "__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr },
{ nullptr, nullptr, nullptr, nullptr, nullptr }
};
static int inst_clear(PyObject *self) {
PyObject **dict = nb_dict_ptr(self);
if (dict)
Py_CLEAR(*dict);
return 0;
}
static int inst_traverse(PyObject *self, visitproc visit, void *arg) {
PyObject **dict = nb_dict_ptr(self);
if (dict)
Py_VISIT(*dict);
#if PY_VERSION_HEX >= 0x03090000
Py_VISIT(Py_TYPE(self));
#endif
return 0;
}
static int inst_init(PyObject *self, PyObject *, PyObject *) {
const type_data *t = nb_type_data(Py_TYPE(self));
PyErr_Format(PyExc_TypeError, "%s: no constructor defined!", t->name);
return -1;
}
/// Allocate memory for a nb_type instance with internal storage
PyObject *inst_new_int(PyTypeObject *tp, PyObject * /* args */,
PyObject * /*kwd */) {
bool gc = PyType_HasFeature(tp, Py_TPFLAGS_HAVE_GC);
nb_inst *self;
if (NB_LIKELY(!gc))
self = PyObject_New(nb_inst, tp);
else
self = (nb_inst *) PyType_GenericAlloc(tp, 0);
if (NB_LIKELY(self)) {
const type_data *t = nb_type_data(tp);
uint32_t align = (uint32_t) t->align;
bool intrusive = t->flags & (uint32_t) type_flags::intrusive_ptr;
uintptr_t payload = (uintptr_t) (self + 1);
if (NB_UNLIKELY(align > sizeof(void *)))
payload = (payload + align - 1) / align * align;
self->offset = (int32_t) ((intptr_t) payload - (intptr_t) self);
self->direct = 1;
self->internal = 1;
self->state = nb_inst::state_uninitialized;
self->destruct = 0;
self->cpp_delete = 0;
self->clear_keep_alive = 0;
self->intrusive = intrusive;
self->unused = 0;
// Update hash table that maps from C++ to Python instance
nb_shard &shard = internals->shard((void *) payload);
lock_shard guard(shard);
auto [it, success] = shard.inst_c2p.try_emplace((void *) payload, self);
check(success, "nanobind::detail::inst_new_int(): unexpected collision!");
}
return (PyObject *) self;
}
/// Allocate memory for a nb_type instance with external storage
PyObject *inst_new_ext(PyTypeObject *tp, void *value) {
bool gc = PyType_HasFeature(tp, Py_TPFLAGS_HAVE_GC);
nb_inst *self;
if (NB_LIKELY(!gc)) {
self = (nb_inst *) PyObject_Malloc(sizeof(nb_inst));
if (!self)
return PyErr_NoMemory();
PyObject_Init((PyObject *) self, tp);
} else {
self = (nb_inst *) PyType_GenericAlloc(tp, 0);
if (!self)
return nullptr;
}
// Compute offset to instance value
// Use uint64_t because subtracting tagged pointers (e.g., with
// HardwareAddressSanitizer) may overflow, which is undefined behavior for
// signed integers.
int32_t offset = (int32_t) ((uintptr_t) value - (uintptr_t) self);
bool direct = (intptr_t) self + offset == (intptr_t) value;
if (NB_UNLIKELY(!direct)) {
// Location is not representable as signed 32 bit offset
if (!gc) {
/// Allocate memory for an extra pointer
nb_inst *self_2 =
(nb_inst *) PyObject_Realloc(self, sizeof(nb_inst) + sizeof(void *));
if (NB_UNLIKELY(!self_2)) {
PyObject_Free(self);
return PyErr_NoMemory();
}
self = self_2;
}
*(void **) (self + 1) = value;
offset = (int32_t) sizeof(nb_inst);
}
const type_data *t = nb_type_data(tp);
bool intrusive = t->flags & (uint32_t) type_flags::intrusive_ptr;
self->offset = offset;
self->direct = direct;
self->internal = 0;
self->state = nb_inst::state_uninitialized;
self->destruct = 0;
self->cpp_delete = 0;
self->clear_keep_alive = 0;
self->intrusive = intrusive;
self->unused = 0;
nb_shard &shard = internals->shard(value);
lock_shard guard(shard);
// Update hash table that maps from C++ to Python instance
auto [it, success] = shard.inst_c2p.try_emplace(value, self);
if (NB_UNLIKELY(!success)) {
void *entry = it->second;
// Potentially convert the map value into linked list format
if (!nb_is_seq(entry)) {
nb_inst_seq *first = (nb_inst_seq *) PyMem_Malloc(sizeof(nb_inst_seq));
check(first, "nanobind::detail::inst_new_ext(): list element "
"allocation failed!");
first->inst = (PyObject *) entry;
first->next = nullptr;
entry = it.value() = nb_mark_seq(first);
}
nb_inst_seq *seq = nb_get_seq(entry);
while (true) {
check((nb_inst *) seq->inst != self,
"nanobind::detail::inst_new_ext(): duplicate instance!");
if (!seq->next)
break;
seq = seq->next;
}
nb_inst_seq *next = (nb_inst_seq *) PyMem_Malloc(sizeof(nb_inst_seq));
check(next,
"nanobind::detail::inst_new_ext(): list element allocation failed!");
next->inst = (PyObject *) self;
next->next = nullptr;
seq->next = next;
}
return (PyObject *) self;
}
static void inst_dealloc(PyObject *self) {
PyTypeObject *tp = Py_TYPE(self);
const type_data *t = nb_type_data(tp);
bool gc = PyType_HasFeature(tp, Py_TPFLAGS_HAVE_GC);
if (NB_UNLIKELY(gc)) {
PyObject_GC_UnTrack(self);
if (t->flags & (uint32_t) type_flags::has_dynamic_attr) {
PyObject **dict = nb_dict_ptr(self);
if (dict)
Py_CLEAR(*dict);
}
}
if (t->flags & (uint32_t) type_flags::is_weak_referenceable &&
nb_weaklist_ptr(self) != nullptr) {
#if defined(PYPY_VERSION)
PyObject **weaklist = nb_weaklist_ptr(self);
if (weaklist)
Py_CLEAR(*weaklist);
#else
PyObject_ClearWeakRefs(self);
#endif
}
nb_inst *inst = (nb_inst *) self;
void *p = inst_ptr(inst);
if (inst->destruct) {
check(t->flags & (uint32_t) type_flags::is_destructible,
"nanobind::detail::inst_dealloc(\"%s\"): attempted to call "
"the destructor of a non-destructible type!", t->name);
if (t->flags & (uint32_t) type_flags::has_destruct)
t->destruct(p);
}
if (inst->cpp_delete) {
if (NB_LIKELY(t->align <= (uint32_t) __STDCPP_DEFAULT_NEW_ALIGNMENT__))
operator delete(p);
else
operator delete(p, std::align_val_t(t->align));
}
nb_weakref_seq *wr_seq = nullptr;
{
// Enter critical section of shard
nb_shard &shard = internals->shard(p);
lock_shard guard(shard);
if (NB_UNLIKELY(inst->clear_keep_alive)) {
size_t self_hash = ptr_hash()(self);
nb_ptr_map &keep_alive = shard.keep_alive;
nb_ptr_map::iterator it = keep_alive.find(self, self_hash);
check(it != keep_alive.end(),
"nanobind::detail::inst_dealloc(\"%s\"): inconsistent "
"keep_alive information", t->name);
wr_seq = (nb_weakref_seq *) it->second;
keep_alive.erase_fast(it);
}
size_t p_hash = ptr_hash()(p);
// Update hash table that maps from C++ to Python instance
nb_ptr_map &inst_c2p = shard.inst_c2p;
nb_ptr_map::iterator it = inst_c2p.find(p, p_hash);
bool found = false;
if (NB_LIKELY(it != inst_c2p.end())) {
void *entry = it->second;
if (NB_LIKELY(entry == inst)) {
found = true;
inst_c2p.erase_fast(it);
} else if (nb_is_seq(entry)) {
// Multiple objects are associated with this address. Find the right one!
nb_inst_seq *seq = nb_get_seq(entry),
*pred = nullptr;
do {
if ((nb_inst *) seq->inst == inst) {
found = true;
if (pred) {
pred->next = seq->next;
} else {
if (seq->next)
it.value() = nb_mark_seq(seq->next);
else
inst_c2p.erase_fast(it);
}
PyMem_Free(seq);
break;
}
pred = seq;
seq = seq->next;
} while (seq);
}
}
check(found,
"nanobind::detail::inst_dealloc(\"%s\"): attempted to delete an "
"unknown instance (%p)!", t->name, p);
}
while (wr_seq) {
nb_weakref_seq *c = wr_seq;
wr_seq = c->next;
if (c->callback)
c->callback(c->payload);
else
Py_DECREF((PyObject *) c->payload);
PyMem_Free(c);
}
if (NB_UNLIKELY(gc))
PyObject_GC_Del(self);
else
PyObject_Free(self);
Py_DECREF(tp);
}
type_data *nb_type_c2p(nb_internals *internals_,
const std::type_info *type) {
#if defined(NB_FREE_THREADED)
thread_local nb_type_map_fast type_c2p_fast;
#else
nb_type_map_fast &type_c2p_fast = internals_->type_c2p_fast;
#endif
nb_type_map_fast::iterator it_fast = type_c2p_fast.find(type);
if (it_fast != type_c2p_fast.end())
return it_fast->second;
lock_internals guard(internals_);
nb_type_map_slow &type_c2p_slow = internals_->type_c2p_slow;
nb_type_map_slow::iterator it_slow = type_c2p_slow.find(type);
if (it_slow != type_c2p_slow.end()) {
type_data *d = it_slow->second;
#if !defined(NB_FREE_THREADED)
// Maintain a linked list to clean up 'type_c2p_fast' when the type
// expires (see nb_type_unregister). In free-threaded mode, we leak
// these entries until the thread destructs.
nb_alias_chain *chain =
(nb_alias_chain *) PyMem_Malloc(sizeof(nb_alias_chain));
check(chain, "Could not allocate nb_alias_chain entry!");
chain->next = d->alias_chain;
chain->value = type;
d->alias_chain = chain;
#endif
type_c2p_fast[type] = d;
return d;
}
return nullptr;
}
void nb_type_unregister(type_data *t) noexcept {
nb_internals *internals_ = internals;
nb_type_map_slow &type_c2p_slow = internals_->type_c2p_slow;
lock_internals guard(internals_);
size_t n_del_slow = type_c2p_slow.erase(t->type);
#if defined(NB_FREE_THREADED)
// In free-threaded mode, stale type information remains in the
// 'type_c2p_fast' TLS. This data structure is eventually deallocated
// when the thread terminates.
//
// In principle, this is dangerous because the user could delete a type
// binding from a module at runtime, causing the associated
// Python type object to be freed. If a function then attempts to return
// a value with such a de-registered type, nanobind should raise an
// exception, which requires knowing that the entry in 'type_c2p_fast'
// has become invalid in the meantime.
//
// Right now, this problem is avoided because we immortalize type objects in
// ``nb_type_new()`` and ``enum_create()``. However, we may not always
// want to stick with immortalization, which is just a workaround.
//
// In the future, a global version counter modified with acquire/release
// semantics (see https://github.com/wjakob/nanobind/pull/695#discussion_r1761600010)
// might prove to be a similarly efficient but more general solution.
bool fail = n_del_slow != 1;
#else
nb_type_map_fast &type_c2p_fast = internals_->type_c2p_fast;
size_t n_del_fast = type_c2p_fast.erase(t->type);
bool fail = n_del_fast != 1 || n_del_slow != 1;
if (!fail) {
nb_alias_chain *cur = t->alias_chain;
while (cur) {
nb_alias_chain *next = cur->next;
n_del_fast = type_c2p_fast.erase(cur->value);
if (n_del_fast != 1) {
fail = true;
break;
}
PyMem_Free(cur);
cur = next;
}
}
#endif
check(!fail,
"nanobind::detail::nb_type_unregister(\"%s\"): could not "
"find type!", t->name);
}
static void nb_type_dealloc(PyObject *o) {
type_data *t = nb_type_data((PyTypeObject *) o);
if (t->type && (t->flags & (uint32_t) type_flags::is_python_type) == 0)
nb_type_unregister(t);
if (t->flags & (uint32_t) type_flags::has_implicit_conversions) {
PyMem_Free(t->implicit.cpp);
PyMem_Free(t->implicit.py);
}
free((char *) t->name);
NB_SLOT(PyType_Type, tp_dealloc)(o);
}
/// Called when a C++ type is extended from within Python
static int nb_type_init(PyObject *self, PyObject *args, PyObject *kwds) {
if (NB_TUPLE_GET_SIZE(args) != 3) {
PyErr_SetString(PyExc_RuntimeError,
"nb_type_init(): invalid number of arguments!");
return -1;
}
PyObject *bases = NB_TUPLE_GET_ITEM(args, 1);
if (!PyTuple_CheckExact(bases) || NB_TUPLE_GET_SIZE(bases) != 1) {
PyErr_SetString(PyExc_RuntimeError,
"nb_type_init(): invalid number of bases!");
return -1;
}
PyObject *base = NB_TUPLE_GET_ITEM(bases, 0);
if (!PyType_Check(base)) {
PyErr_SetString(PyExc_RuntimeError, "nb_type_init(): expected a base type object!");
return -1;
}
type_data *t_b = nb_type_data((PyTypeObject *) base);
if (t_b->flags & (uint32_t) type_flags::is_final) {
PyErr_Format(PyExc_TypeError, "The type '%s' prohibits subclassing!",
t_b->name);
return -1;
}
int rv = NB_SLOT(PyType_Type, tp_init)(self, args, kwds);
if (rv)
return rv;
type_data *t = nb_type_data((PyTypeObject *) self);
*t = *t_b;
t->flags |= (uint32_t) type_flags::is_python_type;
t->flags &= ~((uint32_t) type_flags::has_implicit_conversions);
PyObject *name = nb_type_name(self);
t->name = strdup_check(PyUnicode_AsUTF8AndSize(name, nullptr));
Py_DECREF(name);
t->type_py = (PyTypeObject *) self;
t->implicit.cpp = nullptr;
t->implicit.py = nullptr;
t->alias_chain = nullptr;
#if defined(Py_LIMITED_API)
t->vectorcall = nullptr;
#else
((PyTypeObject *) self)->tp_vectorcall = nullptr;
#endif
return 0;
}
/// Special case to handle 'Class.property = value' assignments
int nb_type_setattro(PyObject* obj, PyObject* name, PyObject* value) {
nb_internals *int_p = internals;
// Set a flag to avoid infinite recursion during static attribute assignment
#if defined(NB_FREE_THREADED)
PyThread_tss_set(int_p->nb_static_property_disabled, (void *) 1);
#else
int_p->nb_static_property_disabled = true;
#endif
PyObject *cur = PyObject_GetAttr(obj, name);
#if defined(NB_FREE_THREADED)
PyThread_tss_set(int_p->nb_static_property_disabled, (void *) 0);
#else
int_p->nb_static_property_disabled = false;
#endif
if (cur) {
PyTypeObject *tp = int_p->nb_static_property.load_acquire();
// For type.static_prop = value, call the setter.
// For type.static_prop = another_static_prop, replace the descriptor.
if (Py_TYPE(cur) == tp && Py_TYPE(value) != tp) {
int rv = int_p->nb_static_property_descr_set(cur, obj, value);
Py_DECREF(cur);
return rv;
}
Py_DECREF(cur);
const char *cname = PyUnicode_AsUTF8AndSize(name, nullptr);
if (!cname) {
PyErr_Clear(); // probably a non-string attribute name
} else if (cname[0] == '@') {
/* Prevent type attributes starting with an `@` sign from being
rebound or deleted. This is useful to safely stash owning
references. The ``nb::enum_<>`` class, e.g., uses this to ensure
indirect ownership of a borrowed reference in the supplemental
type data. */
PyErr_Format(PyExc_AttributeError,
"internal nanobind attribute '%s' cannot be "
"reassigned or deleted.", cname);
return -1;
}
} else {
PyErr_Clear();
}
return NB_SLOT(PyType_Type, tp_setattro)(obj, name, value);
}
#if NB_TYPE_FROM_METACLASS_IMPL || NB_TYPE_GET_SLOT_IMPL
struct nb_slot {
#if NB_TYPE_GET_SLOT_IMPL
uint8_t indirect_1;
uint8_t indirect_2;
#endif
uint8_t direct;
};
template <size_t I1, size_t I2, size_t Offset1, size_t Offset2> nb_slot constexpr Ei() {
// Compile-time check to ensure that indices and alignment match our expectation
static_assert(I1 == I2 && (Offset1 % sizeof(void *)) == 0 && (Offset2 % sizeof(void *)) == 0,
"nb_slot construction: internal error");
#if NB_TYPE_GET_SLOT_IMPL
size_t o = 0;
switch (Offset1) {
case offsetof(PyHeapTypeObject, as_async): o = offsetof(PyTypeObject, tp_as_async); break;
case offsetof(PyHeapTypeObject, as_number): o = offsetof(PyTypeObject, tp_as_number); break;
case offsetof(PyHeapTypeObject, as_mapping): o = offsetof(PyTypeObject, tp_as_mapping); break;
case offsetof(PyHeapTypeObject, as_sequence): o = offsetof(PyTypeObject, tp_as_sequence); break;
case offsetof(PyHeapTypeObject, as_buffer): o = offsetof(PyTypeObject, tp_as_buffer); break;
default: break;
}
return {
(uint8_t) (o / sizeof(void *)),
(uint8_t) ((Offset2 - Offset1) / sizeof(void *)),
(uint8_t) (Offset2 / sizeof(void *)),
};
#else
return { (uint8_t) (Offset2 / sizeof(void *)) };
#endif
}
// Precomputed mapping from type slot ID to an entry in the data structure
#define E(i1, p1, p2, name) \
Ei<i1, Py_##p2##_##name, \
offsetof(PyHeapTypeObject, p1), \
offsetof(PyHeapTypeObject, p1.p2##_##name)>()
#if PY_VERSION_HEX < 0x03090000
# define Py_bf_getbuffer 1
# define Py_bf_releasebuffer 2
#endif
static constexpr nb_slot type_slots[] {
E(1, as_buffer, bf, getbuffer),
E(2, as_buffer, bf, releasebuffer),
E(3, as_mapping, mp, ass_subscript),
E(4, as_mapping, mp, length),
E(5, as_mapping, mp, subscript),
E(6, as_number, nb, absolute),
E(7, as_number, nb, add),
E(8, as_number, nb, and),
E(9, as_number, nb, bool),
E(10, as_number, nb, divmod),
E(11, as_number, nb, float),
E(12, as_number, nb, floor_divide),
E(13, as_number, nb, index),
E(14, as_number, nb, inplace_add),
E(15, as_number, nb, inplace_and),
E(16, as_number, nb, inplace_floor_divide),
E(17, as_number, nb, inplace_lshift),
E(18, as_number, nb, inplace_multiply),
E(19, as_number, nb, inplace_or),
E(20, as_number, nb, inplace_power),
E(21, as_number, nb, inplace_remainder),
E(22, as_number, nb, inplace_rshift),
E(23, as_number, nb, inplace_subtract),
E(24, as_number, nb, inplace_true_divide),
E(25, as_number, nb, inplace_xor),
E(26, as_number, nb, int),
E(27, as_number, nb, invert),
E(28, as_number, nb, lshift),
E(29, as_number, nb, multiply),
E(30, as_number, nb, negative),
E(31, as_number, nb, or),
E(32, as_number, nb, positive),
E(33, as_number, nb, power),
E(34, as_number, nb, remainder),
E(35, as_number, nb, rshift),
E(36, as_number, nb, subtract),
E(37, as_number, nb, true_divide),
E(38, as_number, nb, xor),
E(39, as_sequence, sq, ass_item),
E(40, as_sequence, sq, concat),
E(41, as_sequence, sq, contains),
E(42, as_sequence, sq, inplace_concat),
E(43, as_sequence, sq, inplace_repeat),
E(44, as_sequence, sq, item),
E(45, as_sequence, sq, length),
E(46, as_sequence, sq, repeat),
E(47, ht_type, tp, alloc),
E(48, ht_type, tp, base),
E(49, ht_type, tp, bases),
E(50, ht_type, tp, call),
E(51, ht_type, tp, clear),
E(52, ht_type, tp, dealloc),
E(53, ht_type, tp, del),
E(54, ht_type, tp, descr_get),
E(55, ht_type, tp, descr_set),
E(56, ht_type, tp, doc),
E(57, ht_type, tp, getattr),
E(58, ht_type, tp, getattro),
E(59, ht_type, tp, hash),
E(60, ht_type, tp, init),
E(61, ht_type, tp, is_gc),
E(62, ht_type, tp, iter),
E(63, ht_type, tp, iternext),
E(64, ht_type, tp, methods),
E(65, ht_type, tp, new),
E(66, ht_type, tp, repr),
E(67, ht_type, tp, richcompare),
E(68, ht_type, tp, setattr),
E(69, ht_type, tp, setattro),
E(70, ht_type, tp, str),
E(71, ht_type, tp, traverse),
E(72, ht_type, tp, members),
E(73, ht_type, tp, getset),
E(74, ht_type, tp, free),
E(75, as_number, nb, matrix_multiply),
E(76, as_number, nb, inplace_matrix_multiply),
E(77, as_async, am, await),
E(78, as_async, am, aiter),
E(79, as_async, am, anext),
E(80, ht_type, tp, finalize),
#if PY_VERSION_HEX >= 0x030A0000 && !defined(PYPY_VERSION)
E(81, as_async, am, send),
#endif
};
#if NB_TYPE_GET_SLOT_IMPL
void *type_get_slot(PyTypeObject *t, int slot_id) {
nb_slot slot = type_slots[slot_id - 1];
if (PyType_HasFeature(t, Py_TPFLAGS_HEAPTYPE)) {
return ((void **) t)[slot.direct];
} else {
if (slot.indirect_1)
return ((void ***) t)[slot.indirect_1][slot.indirect_2];
else
return ((void **) t)[slot.indirect_2];
}
}
#endif
#endif
static PyObject *nb_type_from_metaclass(PyTypeObject *meta, PyObject *mod,
PyType_Spec *spec) {
#if NB_TYPE_FROM_METACLASS_IMPL == 0
// Life is good, PyType_FromMetaclass() is available
return PyType_FromMetaclass(meta, mod, spec, nullptr);
#else
/* The fallback code below emulates PyType_FromMetaclass() on Python prior
to version 3.12. It requires access to CPython-internal structures, which
is why nanobind can only target the stable ABI on version 3.12+. */
const char *name = strrchr(spec->name, '.');
if (name)
name++;
else
name = spec->name;
PyObject *name_o = PyUnicode_InternFromString(name);
if (!name_o)
return nullptr;
const char *name_cstr = PyUnicode_AsUTF8AndSize(name_o, nullptr);
if (!name_cstr) {
Py_DECREF(name_o);
return nullptr;
}
PyHeapTypeObject *ht = (PyHeapTypeObject *) PyType_GenericAlloc(meta, 0);
if (!ht) {
Py_DECREF(name_o);
return nullptr;
}
ht->ht_name = name_o;
ht->ht_qualname = name_o;
Py_INCREF(name_o);
#if PY_VERSION_HEX >= 0x03090000
if (mod) {
Py_INCREF(mod);
ht->ht_module = mod;
}
#else
(void) mod;
#endif
PyTypeObject *tp = &ht->ht_type;
tp->tp_name = name_cstr;
tp->tp_basicsize = spec->basicsize;
tp->tp_itemsize = spec->itemsize;
tp->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
tp->tp_as_async = &ht->as_async;
tp->tp_as_number = &ht->as_number;
tp->tp_as_sequence = &ht->as_sequence;
tp->tp_as_mapping = &ht->as_mapping;
tp->tp_as_buffer = &ht->as_buffer;
PyType_Slot *ts = spec->slots;
bool fail = false;
while (true) {
int slot = ts->slot;
if (slot == 0) {
break;
} else if (slot * sizeof(nb_slot) < (int) sizeof(type_slots)) {
*(((void **) ht) + type_slots[slot - 1].direct) = ts->pfunc;
} else {
PyErr_Format(PyExc_RuntimeError,
"nb_type_from_metaclass(): unhandled slot %i", slot);
fail = true;
break;
}
ts++;
}
// Bring type object into a safe state (before error handling)
const PyMemberDef *members = tp->tp_members;
const char *doc = tp->tp_doc;
tp->tp_members = nullptr;
tp->tp_doc = nullptr;
Py_XINCREF(tp->tp_base);
if (doc && !fail) {
size_t size = strlen(doc) + 1;
/// This code path is only used for Python 3.12, where
/// PyObject_Malloc is the right allocation routine for tp_doc
char *target = (char *) PyObject_Malloc(size);
if (!target) {
PyErr_NoMemory();
fail = true;
} else {
memcpy(target, doc, size);
tp->tp_doc = target;
}
}
if (members && !fail) {
while (members->name) {
if (members->type == T_PYSSIZET && members->flags == READONLY) {
if (strcmp(members->name, "__dictoffset__") == 0)
tp->tp_dictoffset = members->offset;
else if (strcmp(members->name, "__weaklistoffset__") == 0)
tp->tp_weaklistoffset = members->offset;
else if (strcmp(members->name, "__vectorcalloffset__") == 0)
tp->tp_vectorcall_offset = members->offset;
else
fail = true;
} else {
fail = true;
}
if (fail) {
PyErr_Format(
PyExc_RuntimeError,
"nb_type_from_metaclass(): unhandled tp_members entry!");
break;
}
members++;
}
}
if (fail || PyType_Ready(tp) != 0) {
Py_DECREF(tp);
return nullptr;
}
return (PyObject *) tp;
#endif
}
extern int nb_type_setattro(PyObject* obj, PyObject* name, PyObject* value);
static PyTypeObject *nb_type_tp(size_t supplement) noexcept {
object key = steal(PyLong_FromSize_t(supplement));
nb_internals *internals_ = internals;
PyTypeObject *tp =
(PyTypeObject *) dict_get_item_ref_or_fail(internals_->nb_type_dict, key.ptr());
if (NB_UNLIKELY(!tp)) {
// Retry in critical section to avoid races that create the same nb_type
lock_internals guard(internals_);
tp = (PyTypeObject *) dict_get_item_ref_or_fail(internals_->nb_type_dict, key.ptr());
if (tp)
return tp;
#if defined(Py_LIMITED_API)
PyMemberDef members[] = {
{ "__vectorcalloffset__", Py_T_PYSSIZET, 0, Py_READONLY, nullptr },
{ nullptr, 0, 0, 0, nullptr }
};
// Workaround because __vectorcalloffset__ does not support Py_RELATIVE_OFFSET
members[0].offset = internals_->type_data_offset + offsetof(type_data, vectorcall);
#endif
PyType_Slot slots[] = {
{ Py_tp_base, &PyType_Type },
{ Py_tp_dealloc, (void *) nb_type_dealloc },
{ Py_tp_setattro, (void *) nb_type_setattro },
{ Py_tp_init, (void *) nb_type_init },
#if defined(Py_LIMITED_API)
{ Py_tp_members, (void *) members },
#endif
{ 0, nullptr }
};
#if PY_VERSION_HEX >= 0x030C0000
int basicsize = -(int) (sizeof(type_data) + supplement),
itemsize = 0;
#else
int basicsize = (int) (PyType_Type.tp_basicsize + (sizeof(type_data) + supplement)),
itemsize = (int) PyType_Type.tp_itemsize;
#endif
char name[17 + 20 + 1];
snprintf(name, sizeof(name), "nanobind.nb_type_%zu", supplement);
PyType_Spec spec = {
/* .name = */ name,
/* .basicsize = */ basicsize,
/* .itemsize = */ itemsize,
/* .flags = */ Py_TPFLAGS_DEFAULT,
/* .slots = */ slots
};
#if defined(Py_LIMITED_API)
spec.flags |= Py_TPFLAGS_HAVE_VECTORCALL;
#endif
tp = (PyTypeObject *) nb_type_from_metaclass(
internals_->nb_meta, internals_->nb_module, &spec);
maybe_make_immortal((PyObject *) tp);
handle(tp).attr("__module__") = "nanobind";
int rv = 1;
if (tp)
rv = PyDict_SetItem(internals_->nb_type_dict, key.ptr(), (PyObject *) tp);
check(rv == 0, "nb_type type creation failed!");
}
return tp;
}
// This helper function extracts the function/class name from a custom signature attribute
NB_NOINLINE char *extract_name(const char *cmd, const char *prefix, const char *s) {
(void) cmd;
// Move to the last line
const char *p = strrchr(s, '\n');
p = p ? (p + 1) : s;
// Check that the last line starts with the right prefix
size_t prefix_len = strlen(prefix);
check(strncmp(p, prefix, prefix_len) == 0,
"%s(): last line of custom signature \"%s\" must start with \"%s\"!",
cmd, s, prefix);
p += prefix_len;
// Find the opening parenthesis or bracket
const char *p2 = strchr(p, '(');
const char *p3 = strchr(p, '[');
if (p2 == nullptr)
p2 = p3;
else if (p3 != nullptr)
p2 = p2 < p3 ? p2 : p3;
check(p2 != nullptr,
"%s(): last line of custom signature \"%s\" must contain an opening "
"parenthesis (\"(\") or bracket (\"[\")!", cmd, s);
// A few sanity checks
size_t len = strlen(p);
char last = p[len ? (len - 1) : 0];
check(last != ':' && last != ' ',
"%s(): custom signature \"%s\" should not end with \":\" or \" \"!", cmd, s);
check((p2 == p || (p[0] != ' ' && p2[-1] != ' ')),
"%s(): custom signature \"%s\" contains leading/trailing space around name!", cmd, s);
size_t size = p2 - p;
char *result = (char *) malloc_check(size + 1);
memcpy(result, p, size);
result[size] = '\0';
return result;
}
#if PY_VERSION_HEX >= 0x03090000
static PyMethodDef class_getitem_method[] = {
{ "__class_getitem__", Py_GenericAlias, METH_O | METH_CLASS, nullptr },
{ nullptr }
};
#endif
// Implements the vector call protocol directly on type objects to construct
// instances more efficiently.
static PyObject *nb_type_vectorcall(PyObject *self, PyObject *const *args_in,
size_t nargsf,
PyObject *kwargs_in) noexcept {
PyTypeObject *tp = (PyTypeObject *) self;
type_data *td = nb_type_data(tp);
nb_func *func = (nb_func *) td->init;
bool is_init = (td->flags & (uint32_t) type_flags::has_new) == 0;
Py_ssize_t nargs = NB_VECTORCALL_NARGS(nargsf);
if (NB_UNLIKELY(!func)) {
PyErr_Format(PyExc_TypeError, "%s: no constructor defined!", td->name);
return nullptr;
}
if (NB_LIKELY(is_init)) {
self = inst_new_int(tp, nullptr, nullptr);
if (!self)
return nullptr;
} else if (nargs == 0 && !kwargs_in &&
!(td->flags & (uint32_t) type_flags::has_nullary_new)) {
// When the bindings define a custom __new__ operator, nanobind always
// provides a no-argument dummy __new__ constructor to handle unpickling
// via __setstate__. This is an implementation detail that should not be
// exposed. Therefore, only allow argument-less calls if there is an
// actual __new__ overload with a compatible signature. This is
// detected in nb_func.cpp based on whether any __init__ overload can
// accept no arguments.
return func->vectorcall((PyObject *) func, nullptr, 0, nullptr);
}
const size_t buf_size = 5;
PyObject **args, *buf[buf_size], *temp = nullptr;
bool alloc = false;
if (NB_LIKELY(nargsf & NB_VECTORCALL_ARGUMENTS_OFFSET)) {
args = (PyObject **) (args_in - 1);
temp = args[0];
} else {
size_t size = nargs + 1;
if (kwargs_in)
size += NB_TUPLE_GET_SIZE(kwargs_in);
if (size < buf_size) {
args = buf;
} else {