forked from wjakob/nanobind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnb_func.cpp
1442 lines (1195 loc) · 49.5 KB
/
nb_func.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_func.cpp: nanobind function type
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"
#include "buffer.h"
/// Maximum number of arguments supported by 'nb_vectorcall_simple'
#define NB_MAXARGS_SIMPLE 8
#if defined(__GNUG__)
# include <cxxabi.h>
#endif
#if defined(_MSC_VER)
# pragma warning(disable: 4706) // assignment within conditional expression
# pragma warning(disable: 6255) // _alloca indicates failure by raising a stack overflow exception
#endif
NAMESPACE_BEGIN(NB_NAMESPACE)
NAMESPACE_BEGIN(detail)
// Forward/external declarations
extern Buffer buf;
static PyObject *nb_func_vectorcall_simple(PyObject *, PyObject *const *,
size_t, PyObject *) noexcept;
static PyObject *nb_func_vectorcall_complex(PyObject *, PyObject *const *,
size_t, PyObject *) noexcept;
static uint32_t nb_func_render_signature(const func_data *f,
bool nb_signature_mode = false) noexcept;
int nb_func_traverse(PyObject *self, visitproc visit, void *arg) {
size_t size = (size_t) Py_SIZE(self);
if (size) {
func_data *f = nb_func_data(self);
for (size_t i = 0; i < size; ++i) {
if (f->flags & (uint32_t) func_flags::has_args) {
for (size_t j = 0; j < f->nargs; ++j) {
Py_VISIT(f->args[j].value);
}
}
++f;
}
}
return 0;
}
int nb_func_clear(PyObject *self) {
size_t size = (size_t) Py_SIZE(self);
if (size) {
func_data *f = nb_func_data(self);
for (size_t i = 0; i < size; ++i) {
if (f->flags & (uint32_t) func_flags::has_args) {
for (size_t j = 0; j < f->nargs; ++j) {
Py_CLEAR(f->args[j].value);
}
}
++f;
}
}
return 0;
}
/// Free a function overload chain
void nb_func_dealloc(PyObject *self) {
PyObject_GC_UnTrack(self);
size_t size = (size_t) Py_SIZE(self);
if (size) {
func_data *f = nb_func_data(self);
// Delete from registered function list
#if !defined(NB_FREE_THREADED)
size_t n_deleted = internals->funcs.erase(self);
check(n_deleted == 1,
"nanobind::detail::nb_func_dealloc(\"%s\"): function not found!",
((f->flags & (uint32_t) func_flags::has_name) ? f->name
: "<anonymous>"));
#endif
for (size_t i = 0; i < size; ++i) {
if (f->flags & (uint32_t) func_flags::has_free)
f->free_capture(f->capture);
if (f->flags & (uint32_t) func_flags::has_args) {
for (size_t j = 0; j < f->nargs; ++j) {
const arg_data &arg = f->args[j];
Py_XDECREF(arg.value);
Py_XDECREF(arg.name_py);
free((char *) arg.signature);
}
}
if (f->flags & (uint32_t) func_flags::has_doc)
free((char *) f->doc);
free((char *) f->name);
free(f->args);
free((char *) f->descr);
free(f->descr_types);
free(f->signature);
++f;
}
}
PyObject_GC_Del(self);
}
int nb_bound_method_traverse(PyObject *self, visitproc visit, void *arg) {
nb_bound_method *mb = (nb_bound_method *) self;
Py_VISIT((PyObject *) mb->func);
Py_VISIT(mb->self);
return 0;
}
int nb_bound_method_clear(PyObject *self) {
nb_bound_method *mb = (nb_bound_method *) self;
Py_CLEAR(mb->func);
Py_CLEAR(mb->self);
return 0;
}
void nb_bound_method_dealloc(PyObject *self) {
nb_bound_method *mb = (nb_bound_method *) self;
PyObject_GC_UnTrack(self);
Py_DECREF((PyObject *) mb->func);
Py_DECREF(mb->self);
PyObject_GC_Del(self);
}
static arg_data method_args[2] = {
{ "self", nullptr, nullptr, nullptr, 0 },
{ nullptr, nullptr, nullptr, nullptr, 0 }
};
static bool set_builtin_exception_status(builtin_exception &e) {
PyObject *o;
switch (e.type()) {
case exception_type::runtime_error: o = PyExc_RuntimeError; break;
case exception_type::stop_iteration: o = PyExc_StopIteration; break;
case exception_type::index_error: o = PyExc_IndexError; break;
case exception_type::key_error: o = PyExc_KeyError; break;
case exception_type::value_error: o = PyExc_ValueError; break;
case exception_type::type_error: o = PyExc_TypeError; break;
case exception_type::buffer_error: o = PyExc_BufferError; break;
case exception_type::import_error: o = PyExc_ImportError; break;
case exception_type::attribute_error: o = PyExc_AttributeError; break;
case exception_type::next_overload: return false;
default:
check(false, "nanobind::detail::set_builtin_exception_status(): "
"invalid exception type!");
}
PyErr_SetString(o, e.what());
return true;
}
void *malloc_check(size_t size) {
void *ptr = malloc(size);
if (!ptr)
fail("nanobind: malloc() failed!");
return ptr;
}
char *strdup_check(const char *s) {
char *result;
#if defined(_WIN32)
result = _strdup(s);
#else
result = strdup(s);
#endif
if (!result)
fail("nanobind: strdup() failed!");
return result;
}
/**
* \brief Wrap a C++ function into a Python function object
*
* This is an implementation detail of nanobind::cpp_function.
*/
PyObject *nb_func_new(const void *in_) noexcept {
func_data_prelim<0> *f = (func_data_prelim<0> *) in_;
arg_data *args_in = std::launder((arg_data *) f->args);
bool has_scope = f->flags & (uint32_t) func_flags::has_scope,
has_name = f->flags & (uint32_t) func_flags::has_name,
has_args = f->flags & (uint32_t) func_flags::has_args,
has_var_args = f->flags & (uint32_t) func_flags::has_var_kwargs,
has_var_kwargs = f->flags & (uint32_t) func_flags::has_var_args,
has_keep_alive = f->flags & (uint32_t) func_flags::has_keep_alive,
has_doc = f->flags & (uint32_t) func_flags::has_doc,
has_signature = f->flags & (uint32_t) func_flags::has_signature,
is_implicit = f->flags & (uint32_t) func_flags::is_implicit,
is_method = f->flags & (uint32_t) func_flags::is_method,
return_ref = f->flags & (uint32_t) func_flags::return_ref,
is_constructor = false,
is_init = false,
is_new = false,
is_setstate = false;
PyObject *name = nullptr;
PyObject *func_prev = nullptr;
char *name_cstr;
if (has_signature) {
name_cstr = extract_name("nanobind::detail::nb_func_new", "def ", f->name);
has_name = *name_cstr != '\0';
} else {
name_cstr = strdup_check(has_name ? f->name : "");
}
// Check for previous overloads
nb_internals *internals_ = internals;
if (has_scope && has_name) {
name = PyUnicode_InternFromString(name_cstr);
check(name, "nb::detail::nb_func_new(\"%s\"): invalid name.", name_cstr);
func_prev = PyObject_GetAttr(f->scope, name);
if (func_prev) {
if (Py_TYPE(func_prev) == internals_->nb_func ||
Py_TYPE(func_prev) == internals_->nb_method) {
func_data *fp = nb_func_data(func_prev);
check((fp->flags & (uint32_t) func_flags::is_method) ==
(f->flags & (uint32_t) func_flags::is_method),
"nb::detail::nb_func_new(\"%s\"): mismatched static/"
"instance method flags in function overloads!",
name_cstr);
/* Never append a method to an overload chain of a parent class;
instead, hide the parent's overloads in this case */
if (fp->scope != f->scope)
Py_CLEAR(func_prev);
} else if (name_cstr[0] == '_') {
Py_CLEAR(func_prev);
} else {
check(false,
"nb::detail::nb_func_new(\"%s\"): cannot overload "
"existing non-function object of the same name!", name_cstr);
}
} else {
PyErr_Clear();
}
is_init = strcmp(name_cstr, "__init__") == 0;
is_new = strcmp(name_cstr, "__new__") == 0;
is_setstate = strcmp(name_cstr, "__setstate__") == 0;
// Is this method a constructor that takes a class binding as first parameter?
is_constructor = is_method && (is_init || is_setstate) &&
strncmp(f->descr, "({%}", 4) == 0;
// Don't use implicit conversions in copy constructors (causes infinite recursion)
// Notes:
// f->nargs = C++ argument count.
// f->descr_types = zero-terminated array of bound types among them.
// Hence of size >= 2 for constructors, where f->descr_types[1] my be null.
// f->args = array of Python arguments (nb::arg). Non-empty if has_args.
// By contrast, fc->args below has size f->nargs.
if (is_constructor && f->nargs == 2 && f->descr_types[0] &&
f->descr_types[0] == f->descr_types[1]) {
if (has_args) {
f->args[0].flag &= ~(uint8_t) cast_flags::convert;
} else {
args_in = method_args + 1;
has_args = true;
}
}
}
// Create a new function and destroy the old one
Py_ssize_t prev_overloads = func_prev ? Py_SIZE(func_prev) : 0;
nb_func *func = (nb_func *) PyType_GenericAlloc(
is_method ? internals_->nb_method : internals_->nb_func, prev_overloads + 1);
check(func, "nb::detail::nb_func_new(\"%s\"): alloc. failed (1).",
name_cstr);
maybe_make_immortal((PyObject *) func);
// Check if the complex dispatch loop is needed
bool complex_call = has_keep_alive || has_var_kwargs || has_var_args ||
f->nargs >= NB_MAXARGS_SIMPLE;
if (has_args) {
for (size_t i = is_method; i < f->nargs; ++i) {
arg_data &a = args_in[i - is_method];
complex_call |= a.name != nullptr || a.value != nullptr ||
a.flag != cast_flags::convert;
}
}
uint32_t max_nargs = f->nargs;
const char *prev_doc = nullptr;
if (func_prev) {
nb_func *nb_func_prev = (nb_func *) func_prev;
complex_call |= nb_func_prev->complex_call;
max_nargs = std::max(max_nargs, nb_func_prev->max_nargs);
func_data *cur = nb_func_data(func),
*prev = nb_func_data(func_prev);
if (nb_func_prev->doc_uniform)
prev_doc = prev->doc;
memcpy(cur, prev, sizeof(func_data) * prev_overloads);
memset(prev, 0, sizeof(func_data) * prev_overloads);
((PyVarObject *) func_prev)->ob_size = 0;
#if !defined(NB_FREE_THREADED)
size_t n_deleted = internals_->funcs.erase(func_prev);
check(n_deleted == 1,
"nanobind::detail::nb_func_new(): internal update failed (1)!");
#endif
Py_CLEAR(func_prev);
}
func->max_nargs = max_nargs;
func->complex_call = complex_call;
func->vectorcall = complex_call ? nb_func_vectorcall_complex
: nb_func_vectorcall_simple;
#if !defined(NB_FREE_THREADED)
// Register the function
auto [it, success] = internals_->funcs.try_emplace(func, nullptr);
check(success,
"nanobind::detail::nb_func_new(): internal update failed (2)!");
#endif
func_data *fc = nb_func_data(func) + prev_overloads;
memcpy(fc, f, sizeof(func_data_prelim<0>));
if (has_doc) {
if (fc->doc[0] == '\n')
fc->doc++;
if (fc->doc[0] == '\0') {
fc->doc = nullptr;
fc->flags &= ~(uint32_t) func_flags::has_doc;
has_doc = false;
} else {
fc->doc = strdup_check(fc->doc);
}
}
// Detect when an entire overload chain has the dame docstring
func->doc_uniform =
(has_doc && ((prev_overloads == 0) ||
(prev_doc && strcmp(fc->doc, prev_doc) == 0)));
if (is_constructor)
fc->flags |= (uint32_t) func_flags::is_constructor;
if (has_args)
fc->flags |= (uint32_t) func_flags::has_args;
fc->name = name_cstr;
fc->signature = has_signature ? strdup_check(f->name) : nullptr;
if (is_implicit) {
check(fc->flags & (uint32_t) func_flags::is_constructor,
"nb::detail::nb_func_new(\"%s\"): nanobind::is_implicit() "
"should only be specified for constructors.",
name_cstr);
check(f->nargs == 2,
"nb::detail::nb_func_new(\"%s\"): implicit constructors "
"should only have one argument.",
name_cstr);
if (f->descr_types[1])
implicitly_convertible(f->descr_types[1], f->descr_types[0]);
}
for (size_t i = 0;; ++i) {
if (!f->descr[i]) {
fc->descr = (char *) malloc_check(sizeof(char) * (i + 1));
memcpy((char *) fc->descr, f->descr, (i + 1) * sizeof(char));
break;
}
}
for (size_t i = 0;; ++i) {
if (!f->descr_types[i]) {
fc->descr_types = (const std::type_info **)
malloc_check(sizeof(const std::type_info *) * (i + 1));
memcpy(fc->descr_types, f->descr_types,
(i + 1) * sizeof(const std::type_info *));
break;
}
}
if (has_args) {
fc->args = (arg_data *) malloc_check(sizeof(arg_data) * f->nargs);
if (is_method) // add implicit 'self' argument annotation
fc->args[0] = method_args[0];
for (size_t i = is_method; i < fc->nargs; ++i)
fc->args[i] = args_in[i - is_method];
for (size_t i = 0; i < fc->nargs; ++i) {
arg_data &a = fc->args[i];
if (a.name) {
a.name_py = PyUnicode_InternFromString(a.name);
a.name = PyUnicode_AsUTF8AndSize(a.name_py, nullptr);
} else {
a.name_py = nullptr;
}
if (a.value == Py_None)
a.flag |= (uint8_t) cast_flags::accepts_none;
a.signature = a.signature ? strdup_check(a.signature) : nullptr;
Py_XINCREF(a.value);
}
}
// Fast path for vector call object construction
if (((is_init && is_method) || (is_new && !is_method)) &&
nb_type_check(f->scope)) {
type_data *td = nb_type_data((PyTypeObject *) f->scope);
bool has_new = td->flags & (uint32_t) type_flags::has_new;
if (is_init && !has_new) {
td->init = func;
} else if (is_new) {
td->init = func;
td->flags |= (uint32_t) type_flags::has_new;
}
}
if (has_scope && name) {
int rv = PyObject_SetAttr(f->scope, name, (PyObject *) func);
check(rv == 0, "nb::detail::nb_func_new(\"%s\"): setattr. failed.",
name_cstr);
}
Py_XDECREF(name);
if (return_ref) {
return (PyObject *) func;
} else {
Py_DECREF(func);
return nullptr;
}
}
/// Used by nb_func_vectorcall: generate an error when overload resolution fails
static NB_NOINLINE PyObject *
nb_func_error_overload(PyObject *self, PyObject *const *args_in,
size_t nargs_in, PyObject *kwargs_in) noexcept {
uint32_t count = (uint32_t) Py_SIZE(self);
func_data *f = nb_func_data(self);
if (f->flags & (uint32_t) func_flags::is_operator)
return not_implemented().release().ptr();
// The buffer 'buf' is protected by 'internals.mutex'
lock_internals guard(internals);
buf.clear();
buf.put_dstr(f->name);
buf.put("(): incompatible function arguments. The following argument types "
"are supported:\n");
// Mask default __new__ overload created by nb::new_()
if (strcmp(f->name, "__new__") == 0 && count > 1 && f->nargs == 1) {
count -= 1;
f += 1;
}
for (uint32_t i = 0; i < count; ++i) {
buf.put(" ");
buf.put_uint32(i + 1);
buf.put(". ");
nb_func_render_signature(f + i);
buf.put('\n');
}
buf.put("\nInvoked with types: ");
for (size_t i = 0; i < nargs_in; ++i) {
str name = steal<str>(nb_inst_name(args_in[i]));
buf.put_dstr(name.c_str());
if (i + 1 < nargs_in)
buf.put(", ");
}
if (kwargs_in) {
if (nargs_in)
buf.put(", ");
buf.put("kwargs = { ");
size_t nkwargs_in = (size_t) NB_TUPLE_GET_SIZE(kwargs_in);
for (size_t j = 0; j < nkwargs_in; ++j) {
PyObject *key = NB_TUPLE_GET_ITEM(kwargs_in, j),
*value = args_in[nargs_in + j];
const char *key_cstr = PyUnicode_AsUTF8AndSize(key, nullptr);
buf.put_dstr(key_cstr);
buf.put(": ");
str name = steal<str>(nb_inst_name(value));
buf.put_dstr(name.c_str());
buf.put(", ");
}
buf.rewind(2);
buf.put(" }");
}
PyErr_SetString(PyExc_TypeError, buf.get());
return nullptr;
}
/// Used by nb_func_vectorcall: generate an error when result conversion fails
static NB_NOINLINE PyObject *nb_func_error_noconvert(PyObject *self,
PyObject *const *, size_t,
PyObject *) noexcept {
if (PyErr_Occurred())
return nullptr;
func_data *f = nb_func_data(self);
// The buffer 'buf' is protected by 'internals.mutex'
lock_internals guard(internals);
buf.clear();
buf.put("Unable to convert function return value to a Python "
"type! The signature was\n ");
nb_func_render_signature(f);
PyErr_SetString(PyExc_TypeError, buf.get());
return nullptr;
}
/// Used by nb_func_vectorcall: convert a C++ exception into a Python error
static NB_NOINLINE void nb_func_convert_cpp_exception() noexcept {
std::exception_ptr e = std::current_exception();
for (nb_translator_seq *cur = &internals->translators; cur;
cur = cur->next) {
try {
// Try exception translator & forward payload
cur->translator(e, cur->payload);
return;
} catch (...) {
e = std::current_exception();
}
}
PyErr_SetString(PyExc_SystemError,
"nanobind::detail::nb_func_error_except(): exception "
"could not be translated!");
}
/// Dispatch loop that is used to invoke functions created by nb_func_new
static PyObject *nb_func_vectorcall_complex(PyObject *self,
PyObject *const *args_in,
size_t nargsf,
PyObject *kwargs_in) noexcept {
const size_t count = (size_t) Py_SIZE(self),
nargs_in = (size_t) NB_VECTORCALL_NARGS(nargsf),
nkwargs_in = kwargs_in ? (size_t) NB_TUPLE_GET_SIZE(kwargs_in) : 0;
func_data *fr = nb_func_data(self);
const bool is_method = fr->flags & (uint32_t) func_flags::is_method,
is_constructor = fr->flags & (uint32_t) func_flags::is_constructor;
PyObject *result = nullptr,
*self_arg = (is_method && nargs_in > 0) ? args_in[0] : nullptr;
/* The following lines allocate memory on the stack, which is very efficient
but also potentially dangerous since it can be used to generate stack
overflows. We refuse unrealistically large number of 'kwargs' (the
'max_nargs' value is fine since it is specified by the bindings) */
if (nkwargs_in > 1024) {
PyErr_SetString(PyExc_TypeError,
"nanobind::detail::nb_func_vectorcall(): too many (> "
"1024) keyword arguments.");
return nullptr;
}
// Handler routine that will be invoked in case of an error condition
PyObject *(*error_handler)(PyObject *, PyObject *const *, size_t,
PyObject *) noexcept = nullptr;
// Small array holding temporaries (implicit conversion/*args/**kwargs)
cleanup_list cleanup(self_arg);
// Preallocate stack memory for function dispatch
size_t max_nargs = ((nb_func *) self)->max_nargs;
PyObject **args = (PyObject **) alloca(max_nargs * sizeof(PyObject *));
uint8_t *args_flags = (uint8_t *) alloca(max_nargs * sizeof(uint8_t));
bool *kwarg_used = (bool *) alloca(nkwargs_in * sizeof(bool));
// Ensure that keyword argument names are interned. That makes it faster
// to compare them against pre-interned argument names in the overload chain.
// Normal function calls will have their keyword arguments already interned,
// but we can't rely on that; it fails for things like fn(**json.loads(...)).
PyObject **kwnames = nullptr;
#if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
bool kwnames_interned = true;
for (size_t i = 0; i < nkwargs_in; ++i) {
PyObject *key = NB_TUPLE_GET_ITEM(kwargs_in, i);
kwnames_interned &= ((PyASCIIObject *) key)->state.interned != 0;
}
if (kwargs_in && NB_LIKELY(kwnames_interned)) {
kwnames = ((PyTupleObject *) kwargs_in)->ob_item;
goto traverse_overloads;
}
#endif
kwnames = (PyObject **) alloca(nkwargs_in * sizeof(PyObject *));
for (size_t i = 0; i < nkwargs_in; ++i) {
PyObject *key = NB_TUPLE_GET_ITEM(kwargs_in, i);
Py_INCREF(key);
kwnames[i] = key;
PyUnicode_InternInPlace(&kwnames[i]);
PyObject *key_interned = kwnames[i];
if (NB_LIKELY(key == key_interned)) // string was already interned
Py_DECREF(key);
else
cleanup.append(key_interned);
}
#if !defined(PYPY_VERSION) && !defined(Py_LIMITED_API)
traverse_overloads:
#endif
/* The logic below tries to find a suitable overload using two passes
of the overload chain (or 1, if there are no overloads). The first pass
is strict and permits no implicit conversions, while the second pass
allows them.
The following is done per overload during a pass
1. Copy individual arguments while checking that named positional
arguments weren't *also* specified as kwarg. Substitute missing
entries using keyword arguments or default argument values provided
in the bindings, if available.
3. Ensure that either all keyword arguments were "consumed", or that
the function takes a kwargs argument to accept unconsumed kwargs.
4. Any positional arguments still left get put into a tuple (for args),
and any leftover kwargs get put into a dict.
5. Pack everything into a vector; if we have nb::args or nb::kwargs, they are an
extra tuple or dict at the end of the positional arguments.
6. Call the function call dispatcher (func_data::impl)
If one of these fail, move on to the next overload and keep trying
until we get a result other than NB_NEXT_OVERLOAD.
*/
for (size_t pass = (count > 1) ? 0 : 1; pass < 2; ++pass) {
for (size_t k = 0; k < count; ++k) {
const func_data *f = fr + k;
const bool has_args = f->flags & (uint32_t) func_flags::has_args,
has_var_args = f->flags & (uint32_t) func_flags::has_var_args,
has_var_kwargs = f->flags & (uint32_t) func_flags::has_var_kwargs;
// Number of C++ parameters eligible to be filled from individual
// Python positional arguments
size_t nargs_pos = f->nargs_pos;
// Number of C++ parameters in total, except for a possible trailing
// nb::kwargs. All of these are eligible to be filled from individual
// Python arguments (keyword always, positional until index nargs_pos)
// except for a potential nb::args, which exists at index nargs_pos
// if has_var_args is true. We'll skip that one in the individual-args
// loop, and go back and fill it later with the unused positionals.
size_t nargs_step1 = f->nargs - has_var_kwargs;
if (nargs_in > nargs_pos && !has_var_args)
continue; // Too many positional arguments given for this overload
if (nargs_in < nargs_pos && !has_args)
continue; // Not enough positional arguments, insufficient
// keyword/default arguments to fill in the blanks
memset(kwarg_used, 0, nkwargs_in * sizeof(bool));
// 1. Copy individual arguments, potentially substitute kwargs/defaults
size_t i = 0;
for (; i < nargs_step1; ++i) {
if (has_var_args && i == nargs_pos)
continue; // skip nb::args parameter, will be handled below
PyObject *arg = nullptr;
uint8_t arg_flag = 1;
// If i >= nargs_pos, then this is a keyword-only parameter.
// (We skipped any *args parameter using the test above,
// and we set the bounds of nargs_step1 to not include any
// **kwargs parameter.) In that case we don't want to take
// a positional arg (which might validly exist and be
// destined for the *args) but we do still want to look for
// a matching keyword arg.
if (i < nargs_in && i < nargs_pos)
arg = args_in[i];
if (has_args) {
const arg_data &ad = f->args[i];
if (kwargs_in && ad.name_py) {
PyObject *hit = nullptr;
for (size_t j = 0; j < nkwargs_in; ++j) {
if (kwnames[j] == ad.name_py) {
hit = args_in[nargs_in + j];
kwarg_used[j] = true;
break;
}
}
if (hit) {
if (arg)
break; // conflict between keyword and positional arg.
arg = hit;
}
}
if (!arg)
arg = ad.value;
arg_flag = ad.flag;
}
if (!arg || (arg == Py_None && (arg_flag & cast_flags::accepts_none) == 0))
break;
// Implicit conversion only active in the 2nd pass
args_flags[i] = arg_flag & ~uint8_t(pass == 0);
args[i] = arg;
}
// Skip this overload if any arguments were unavailable
if (i != nargs_step1)
continue;
// Deal with remaining positional arguments
if (has_var_args) {
PyObject *tuple = PyTuple_New(
nargs_in > nargs_pos ? (Py_ssize_t) (nargs_in - nargs_pos) : 0);
for (size_t j = nargs_pos; j < nargs_in; ++j) {
PyObject *o = args_in[j];
Py_INCREF(o);
NB_TUPLE_SET_ITEM(tuple, j - nargs_pos, o);
}
args[nargs_pos] = tuple;
args_flags[nargs_pos] = 0;
cleanup.append(tuple);
}
// Deal with remaining keyword arguments
if (has_var_kwargs) {
PyObject *dict = PyDict_New();
for (size_t j = 0; j < nkwargs_in; ++j) {
PyObject *key = kwnames[j];
if (!kwarg_used[j])
PyDict_SetItem(dict, key, args_in[nargs_in + j]);
}
args[nargs_step1] = dict;
args_flags[nargs_step1] = 0;
cleanup.append(dict);
} else if (kwargs_in) {
bool success = true;
for (size_t j = 0; j < nkwargs_in; ++j)
success &= kwarg_used[j];
if (!success)
continue;
}
if (is_constructor)
args_flags[0] |= (uint8_t) cast_flags::construct;
rv_policy policy = (rv_policy) (f->flags & 0b111);
try {
result = nullptr;
// Found a suitable overload, let's try calling it
result = f->impl((void *) f->capture, args, args_flags,
policy, &cleanup);
if (NB_UNLIKELY(!result))
error_handler = nb_func_error_noconvert;
} catch (builtin_exception &e) {
if (!set_builtin_exception_status(e))
result = NB_NEXT_OVERLOAD;
} catch (python_error &e) {
e.restore();
} catch (...) {
nb_func_convert_cpp_exception();
}
if (result != NB_NEXT_OVERLOAD) {
if (is_constructor && result != nullptr) {
nb_inst *self_arg_nb = (nb_inst *) self_arg;
self_arg_nb->destruct = true;
self_arg_nb->state = nb_inst::state_ready;
if (NB_UNLIKELY(self_arg_nb->intrusive))
nb_type_data(Py_TYPE(self_arg))
->set_self_py(inst_ptr(self_arg_nb), self_arg);
}
goto done;
}
}
}
error_handler = nb_func_error_overload;
done:
if (NB_UNLIKELY(cleanup.used()))
cleanup.release();
if (NB_UNLIKELY(error_handler))
result = error_handler(self, args_in, nargs_in, kwargs_in);
return result;
}
/// Simplified nb_func_vectorcall variant for functions w/o keyword arguments
static PyObject *nb_func_vectorcall_simple(PyObject *self,
PyObject *const *args_in,
size_t nargsf,
PyObject *kwargs_in) noexcept {
uint8_t args_flags[NB_MAXARGS_SIMPLE];
func_data *fr = nb_func_data(self);
const size_t count = (size_t) Py_SIZE(self),
nargs_in = (size_t) NB_VECTORCALL_NARGS(nargsf);
const bool is_method = fr->flags & (uint32_t) func_flags::is_method,
is_constructor = fr->flags & (uint32_t) func_flags::is_constructor;
PyObject *result = nullptr,
*self_arg = (is_method && nargs_in > 0) ? args_in[0] : nullptr;
// Small array holding temporaries (implicit conversion/*args/**kwargs)
cleanup_list cleanup(self_arg);
// Handler routine that will be invoked in case of an error condition
PyObject *(*error_handler)(PyObject *, PyObject *const *, size_t,
PyObject *) noexcept = nullptr;
bool fail = kwargs_in != nullptr;
PyObject *none_ptr = Py_None;
for (size_t i = 0; i < nargs_in; ++i)
fail |= args_in[i] == none_ptr;
if (fail) { // keyword/None arguments unsupported in simple vectorcall
error_handler = nb_func_error_overload;
goto done;
}
for (size_t pass = (count > 1) ? 0 : 1; pass < 2; ++pass) {
for (int i = 0; i < NB_MAXARGS_SIMPLE; ++i)
args_flags[i] = (uint8_t) pass;
if (is_constructor)
args_flags[0] = (uint8_t) cast_flags::construct;
for (size_t k = 0; k < count; ++k) {
const func_data *f = fr + k;
if (nargs_in != f->nargs)
continue;
try {
result = nullptr;
// Found a suitable overload, let's try calling it
result = f->impl((void *) f->capture, (PyObject **) args_in,
args_flags, (rv_policy) (f->flags & 0b111),
&cleanup);
if (NB_UNLIKELY(!result))
error_handler = nb_func_error_noconvert;
} catch (builtin_exception &e) {
if (!set_builtin_exception_status(e))
result = NB_NEXT_OVERLOAD;
} catch (python_error &e) {
e.restore();
} catch (...) {
nb_func_convert_cpp_exception();
}
if (result != NB_NEXT_OVERLOAD) {
if (is_constructor && result != nullptr) {
nb_inst *self_arg_nb = (nb_inst *) self_arg;
self_arg_nb->destruct = true;
self_arg_nb->state = nb_inst::state_ready;
if (NB_UNLIKELY(self_arg_nb->intrusive))
nb_type_data(Py_TYPE(self_arg))
->set_self_py(inst_ptr(self_arg_nb), self_arg);
}
goto done;
}
}
}
error_handler = nb_func_error_overload;
done:
if (NB_UNLIKELY(cleanup.used()))
cleanup.release();
if (NB_UNLIKELY(error_handler))
result = error_handler(self, args_in, nargs_in, kwargs_in);
return result;
}
static PyObject *nb_bound_method_vectorcall(PyObject *self,
PyObject *const *args_in,
size_t nargsf,
PyObject *kwargs_in) noexcept {
nb_bound_method *mb = (nb_bound_method *) self;
size_t nargs = (size_t) NB_VECTORCALL_NARGS(nargsf);
const size_t buf_size = 5;
PyObject **args, *args_buf[buf_size], *temp = nullptr, *result;
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 = args_buf;
} else {
args = (PyObject **) PyMem_Malloc(size * sizeof(PyObject *));
if (!args)
return PyErr_NoMemory();
alloc = true;
}
memcpy(args + 1, args_in, sizeof(PyObject *) * (size - 1));
}
args[0] = mb->self;
result = mb->func->vectorcall((PyObject *) mb->func, args, nargs + 1, kwargs_in);
args[0] = temp;
if (NB_UNLIKELY(alloc))
PyMem_Free(args);
return result;
}
PyObject *nb_method_descr_get(PyObject *self, PyObject *inst, PyObject *) {
if (inst) {
/* Return a bound method. This should be avoidable in most cases via the
'CALL_METHOD' opcode and vector calls. Pytest rewrites the bytecode
in a way that breaks this optimization :-/ */
nb_bound_method *mb =
PyObject_GC_New(nb_bound_method, internals->nb_bound_method);
mb->func = (nb_func *) self;
mb->self = inst;
mb->vectorcall = nb_bound_method_vectorcall;
Py_INCREF(self);
Py_INCREF(inst);
return (PyObject *) mb;
} else {
Py_INCREF(self);
return self;
}
}
/// Render the function signature of a single function. Callers must hold the
/// 'internals' mutex.
static uint32_t nb_func_render_signature(const func_data *f,
bool nb_signature_mode) noexcept {
const bool is_method = f->flags & (uint32_t) func_flags::is_method,