-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
funcobject.c
1753 lines (1584 loc) · 54.2 KB
/
funcobject.c
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
/* Function object implementation */
#include "Python.h"
#include "pycore_dict.h" // _Py_INCREF_DICT()
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_modsupport.h" // _PyArg_NoKeywords()
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _PyErr_Occurred()
static const char *
func_event_name(PyFunction_WatchEvent event) {
switch (event) {
#define CASE(op) \
case PyFunction_EVENT_##op: \
return "PyFunction_EVENT_" #op;
PY_FOREACH_FUNC_EVENT(CASE)
#undef CASE
}
Py_UNREACHABLE();
}
static void
notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
PyFunctionObject *func, PyObject *new_value)
{
uint8_t bits = interp->active_func_watchers;
int i = 0;
while (bits) {
assert(i < FUNC_MAX_WATCHERS);
if (bits & 1) {
PyFunction_WatchCallback cb = interp->func_watchers[i];
// callback must be non-null if the watcher bit is set
assert(cb != NULL);
if (cb(event, func, new_value) < 0) {
PyErr_FormatUnraisable(
"Exception ignored in %s watcher callback for function %U at %p",
func_event_name(event), func->func_qualname, func);
}
}
i++;
bits >>= 1;
}
}
static inline void
handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
PyObject *new_value)
{
assert(Py_REFCNT(func) > 0);
PyInterpreterState *interp = _PyInterpreterState_GET();
assert(interp->_initialized);
if (interp->active_func_watchers) {
notify_func_watchers(interp, event, func, new_value);
}
switch (event) {
case PyFunction_EVENT_MODIFY_CODE:
case PyFunction_EVENT_MODIFY_DEFAULTS:
case PyFunction_EVENT_MODIFY_KWDEFAULTS:
RARE_EVENT_INTERP_INC(interp, func_modification);
break;
default:
break;
}
}
int
PyFunction_AddWatcher(PyFunction_WatchCallback callback)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
assert(interp->_initialized);
for (int i = 0; i < FUNC_MAX_WATCHERS; i++) {
if (interp->func_watchers[i] == NULL) {
interp->func_watchers[i] = callback;
interp->active_func_watchers |= (1 << i);
return i;
}
}
PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available");
return -1;
}
int
PyFunction_ClearWatcher(int watcher_id)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) {
PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d",
watcher_id);
return -1;
}
if (!interp->func_watchers[watcher_id]) {
PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d",
watcher_id);
return -1;
}
interp->func_watchers[watcher_id] = NULL;
interp->active_func_watchers &= ~(1 << watcher_id);
return 0;
}
PyFunctionObject *
_PyFunction_FromConstructor(PyFrameConstructor *constr)
{
PyObject *module;
if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
return NULL;
}
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
if (op == NULL) {
Py_XDECREF(module);
return NULL;
}
_Py_INCREF_DICT(constr->fc_globals);
op->func_globals = constr->fc_globals;
_Py_INCREF_BUILTINS(constr->fc_builtins);
op->func_builtins = constr->fc_builtins;
op->func_name = Py_NewRef(constr->fc_name);
op->func_qualname = Py_NewRef(constr->fc_qualname);
_Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
op->func_code = constr->fc_code;
op->func_defaults = Py_XNewRef(constr->fc_defaults);
op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
op->func_closure = Py_XNewRef(constr->fc_closure);
op->func_doc = Py_NewRef(Py_None);
op->func_dict = NULL;
op->func_weakreflist = NULL;
op->func_module = module;
op->func_annotations = NULL;
op->func_annotate = NULL;
op->func_typeparams = NULL;
op->vectorcall = _PyFunction_Vectorcall;
op->func_version = FUNC_VERSION_UNSET;
// NOTE: functions created via FrameConstructor do not use deferred
// reference counting because they are typically not part of cycles
// nor accessed by multiple threads.
_PyObject_GC_TRACK(op);
handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
return op;
}
PyObject *
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
{
assert(globals != NULL);
assert(PyDict_Check(globals));
_Py_INCREF_DICT(globals);
PyCodeObject *code_obj = (PyCodeObject *)code;
_Py_INCREF_CODE(code_obj);
assert(code_obj->co_name != NULL);
PyObject *name = Py_NewRef(code_obj->co_name);
if (!qualname) {
qualname = code_obj->co_qualname;
}
assert(qualname != NULL);
Py_INCREF(qualname);
PyObject *consts = code_obj->co_consts;
assert(PyTuple_Check(consts));
PyObject *doc;
if (code_obj->co_flags & CO_HAS_DOCSTRING) {
assert(PyTuple_Size(consts) >= 1);
doc = PyTuple_GetItem(consts, 0);
if (!PyUnicode_Check(doc)) {
doc = Py_None;
}
}
else {
doc = Py_None;
}
Py_INCREF(doc);
// __module__: Use globals['__name__'] if it exists, or NULL.
PyObject *module;
PyObject *builtins = NULL;
if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
goto error;
}
builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
if (builtins == NULL) {
goto error;
}
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
if (op == NULL) {
goto error;
}
/* Note: No failures from this point on, since func_dealloc() does not
expect a partially-created object. */
op->func_globals = globals;
op->func_builtins = builtins;
op->func_name = name;
op->func_qualname = qualname;
op->func_code = (PyObject*)code_obj;
op->func_defaults = NULL; // No default positional arguments
op->func_kwdefaults = NULL; // No default keyword arguments
op->func_closure = NULL;
op->func_doc = doc;
op->func_dict = NULL;
op->func_weakreflist = NULL;
op->func_module = module;
op->func_annotations = NULL;
op->func_annotate = NULL;
op->func_typeparams = NULL;
op->vectorcall = _PyFunction_Vectorcall;
op->func_version = FUNC_VERSION_UNSET;
if ((code_obj->co_flags & CO_NESTED) == 0) {
// Use deferred reference counting for top-level functions, but not
// nested functions because they are more likely to capture variables,
// which makes prompt deallocation more important.
_PyObject_SetDeferredRefcount((PyObject *)op);
}
_PyObject_GC_TRACK(op);
handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
return (PyObject *)op;
error:
Py_DECREF(globals);
Py_DECREF(code_obj);
Py_DECREF(name);
Py_DECREF(qualname);
Py_DECREF(doc);
Py_XDECREF(module);
Py_XDECREF(builtins);
return NULL;
}
/*
(This is purely internal documentation. There are no public APIs here.)
Function (and code) versions
----------------------------
The Tier 1 specializer generates CALL variants that can be invalidated
by changes to critical function attributes:
- __code__
- __defaults__
- __kwdefaults__
- __closure__
For this purpose function objects have a 32-bit func_version member
that the specializer writes to the specialized instruction's inline
cache and which is checked by a guard on the specialized instructions.
The MAKE_FUNCTION bytecode sets func_version from the code object's
co_version field. The latter is initialized from a counter in the
interpreter state (interp->func_state.next_version) and never changes.
When this counter overflows, it remains zero and the specializer loses
the ability to specialize calls to new functions.
The func_version is reset to zero when any of the critical attributes
is modified; after this point the specializer will no longer specialize
calls to this function, and the guard will always fail.
The function and code version cache
-----------------------------------
The Tier 2 optimizer now has a problem, since it needs to find the
function and code objects given only the version number from the inline
cache. Our solution is to maintain a cache mapping version numbers to
function and code objects. To limit the cache size we could hash
the version number, but for now we simply use it modulo the table size.
There are some corner cases (e.g. generator expressions) where we will
be unable to find the function object in the cache but we can still
find the code object. For this reason the cache stores both the
function object and the code object.
The cache doesn't contain strong references; cache entries are
invalidated whenever the function or code object is deallocated.
Invariants
----------
These should hold at any time except when one of the cache-mutating
functions is running.
- For any slot s at index i:
- s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i
- s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i
if s->func != NULL, then s->func->func_code == s->code
*/
#ifndef Py_GIL_DISABLED
static inline struct _func_version_cache_item *
get_cache_item(PyInterpreterState *interp, uint32_t version)
{
return interp->func_state.func_version_cache +
(version % FUNC_VERSION_CACHE_SIZE);
}
#endif
void
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
{
assert(func->func_version == FUNC_VERSION_UNSET);
assert(version >= FUNC_VERSION_FIRST_VALID);
// This should only be called from MAKE_FUNCTION. No code is specialized
// based on the version, so we do not need to stop the world to set it.
func->func_version = version;
#ifndef Py_GIL_DISABLED
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
slot->func = func;
slot->code = func->func_code;
#endif
}
static void
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
{
if (func->func_version < FUNC_VERSION_FIRST_VALID) {
// Version was never set or has already been cleared.
return;
}
#ifndef Py_GIL_DISABLED
struct _func_version_cache_item *slot =
get_cache_item(interp, func->func_version);
if (slot->func == func) {
slot->func = NULL;
// Leave slot->code alone, there may be use for it.
}
#endif
func->func_version = FUNC_VERSION_CLEARED;
}
// Called when any of the critical function attributes are changed
static void
_PyFunction_ClearVersion(PyFunctionObject *func)
{
if (func->func_version < FUNC_VERSION_FIRST_VALID) {
// Version was never set or has already been cleared.
return;
}
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, func);
_PyEval_StartTheWorld(interp);
}
void
_PyFunction_ClearCodeByVersion(uint32_t version)
{
#ifndef Py_GIL_DISABLED
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
if (slot->code) {
assert(PyCode_Check(slot->code));
PyCodeObject *code = (PyCodeObject *)slot->code;
if (code->co_version == version) {
slot->code = NULL;
slot->func = NULL;
}
}
#endif
}
PyFunctionObject *
_PyFunction_LookupByVersion(uint32_t version, PyObject **p_code)
{
#ifdef Py_GIL_DISABLED
return NULL;
#else
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
if (slot->code) {
assert(PyCode_Check(slot->code));
PyCodeObject *code = (PyCodeObject *)slot->code;
if (code->co_version == version) {
*p_code = slot->code;
}
}
else {
*p_code = NULL;
}
if (slot->func && slot->func->func_version == version) {
assert(slot->func->func_code == slot->code);
return slot->func;
}
return NULL;
#endif
}
uint32_t
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
{
return func->func_version;
}
PyObject *
PyFunction_New(PyObject *code, PyObject *globals)
{
return PyFunction_NewWithQualName(code, globals, NULL);
}
PyObject *
PyFunction_GetCode(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_code;
}
PyObject *
PyFunction_GetGlobals(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_globals;
}
PyObject *
PyFunction_GetModule(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_module;
}
PyObject *
PyFunction_GetDefaults(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_defaults;
}
int
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (defaults == Py_None)
defaults = NULL;
else if (defaults && PyTuple_Check(defaults)) {
Py_INCREF(defaults);
}
else {
PyErr_SetString(PyExc_SystemError, "non-tuple default args");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS,
(PyFunctionObject *) op, defaults);
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
return 0;
}
void
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
{
assert(func != NULL);
_PyFunction_ClearVersion(func);
func->vectorcall = vectorcall;
}
PyObject *
PyFunction_GetKwDefaults(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_kwdefaults;
}
int
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (defaults == Py_None)
defaults = NULL;
else if (defaults && PyDict_Check(defaults)) {
Py_INCREF(defaults);
}
else {
PyErr_SetString(PyExc_SystemError,
"non-dict keyword only default args");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS,
(PyFunctionObject *) op, defaults);
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
return 0;
}
PyObject *
PyFunction_GetClosure(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_closure;
}
int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (closure == Py_None)
closure = NULL;
else if (PyTuple_Check(closure)) {
Py_INCREF(closure);
}
else {
PyErr_Format(PyExc_SystemError,
"expected tuple for closure, got '%.100s'",
Py_TYPE(closure)->tp_name);
return -1;
}
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
return 0;
}
static PyObject *
func_get_annotation_dict(PyFunctionObject *op)
{
if (op->func_annotations == NULL) {
if (op->func_annotate == NULL || !PyCallable_Check(op->func_annotate)) {
Py_RETURN_NONE;
}
PyObject *one = _PyLong_GetOne();
PyObject *ann_dict = _PyObject_CallOneArg(op->func_annotate, one);
if (ann_dict == NULL) {
return NULL;
}
if (!PyDict_Check(ann_dict)) {
PyErr_Format(PyExc_TypeError, "__annotate__ returned non-dict of type '%.100s'",
Py_TYPE(ann_dict)->tp_name);
Py_DECREF(ann_dict);
return NULL;
}
Py_XSETREF(op->func_annotations, ann_dict);
return ann_dict;
}
if (PyTuple_CheckExact(op->func_annotations)) {
PyObject *ann_tuple = op->func_annotations;
PyObject *ann_dict = PyDict_New();
if (ann_dict == NULL) {
return NULL;
}
assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
int err = PyDict_SetItem(ann_dict,
PyTuple_GET_ITEM(ann_tuple, i),
PyTuple_GET_ITEM(ann_tuple, i + 1));
if (err < 0) {
Py_DECREF(ann_dict);
return NULL;
}
}
Py_SETREF(op->func_annotations, ann_dict);
}
assert(PyDict_Check(op->func_annotations));
return op->func_annotations;
}
PyObject *
PyFunction_GetAnnotations(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return func_get_annotation_dict((PyFunctionObject *)op);
}
int
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (annotations == Py_None)
annotations = NULL;
else if (annotations && PyDict_Check(annotations)) {
Py_INCREF(annotations);
}
else {
PyErr_SetString(PyExc_SystemError,
"non-dict annotations");
return -1;
}
PyFunctionObject *func = (PyFunctionObject *)op;
Py_XSETREF(func->func_annotations, annotations);
Py_CLEAR(func->func_annotate);
return 0;
}
/* Methods */
#define OFF(x) offsetof(PyFunctionObject, x)
static PyMemberDef func_memberlist[] = {
{"__closure__", _Py_T_OBJECT, OFF(func_closure), Py_READONLY},
{"__doc__", _Py_T_OBJECT, OFF(func_doc), 0},
{"__globals__", _Py_T_OBJECT, OFF(func_globals), Py_READONLY},
{"__module__", _Py_T_OBJECT, OFF(func_module), 0},
{"__builtins__", _Py_T_OBJECT, OFF(func_builtins), Py_READONLY},
{NULL} /* Sentinel */
};
static PyObject *
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
return NULL;
}
return Py_NewRef(op->func_code);
}
static int
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.func_code or to set it to anything
* other than a code object. */
if (value == NULL || !PyCode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__code__ must be set to a code object");
return -1;
}
if (PySys_Audit("object.__setattr__", "OsO",
op, "__code__", value) < 0) {
return -1;
}
int nfree = ((PyCodeObject *)value)->co_nfreevars;
Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
PyTuple_GET_SIZE(op->func_closure));
if (nclosure != nfree) {
PyErr_Format(PyExc_ValueError,
"%U() requires a code object with %zd free vars,"
" not %zd",
op->func_name,
nclosure, nfree);
return -1;
}
PyObject *func_code = PyFunction_GET_CODE(op);
int old_flags = ((PyCodeObject *)func_code)->co_flags;
int new_flags = ((PyCodeObject *)value)->co_flags;
int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
if ((old_flags & mask) != (new_flags & mask)) {
if (PyErr_Warn(PyExc_DeprecationWarning,
"Assigning a code object of non-matching type is deprecated "
"(e.g., from a generator to a plain function)") < 0)
{
return -1;
}
}
handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_code, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
return Py_NewRef(op->func_name);
}
static int
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.func_name or to set it to anything
* other than a string object. */
if (value == NULL || !PyUnicode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__name__ must be set to a string object");
return -1;
}
Py_XSETREF(op->func_name, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
return Py_NewRef(op->func_qualname);
}
static int
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.__qualname__ or to set it to anything
* other than a string object. */
if (value == NULL || !PyUnicode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__qualname__ must be set to a string object");
return -1;
}
Py_XSETREF(op->func_qualname, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
return NULL;
}
if (op->func_defaults == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(op->func_defaults);
}
static int
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
/* Legal to del f.func_defaults.
* Can only set func_defaults to NULL or a tuple. */
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == Py_None)
value = NULL;
if (value != NULL && !PyTuple_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__defaults__ must be set to a tuple object");
return -1;
}
if (value) {
if (PySys_Audit("object.__setattr__", "OsO",
op, "__defaults__", value) < 0) {
return -1;
}
} else if (PySys_Audit("object.__delattr__", "Os",
op, "__defaults__") < 0) {
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_defaults, Py_XNewRef(value));
return 0;
}
static PyObject *
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os",
op, "__kwdefaults__") < 0) {
return NULL;
}
if (op->func_kwdefaults == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(op->func_kwdefaults);
}
static int
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == Py_None)
value = NULL;
/* Legal to del f.func_kwdefaults.
* Can only set func_kwdefaults to NULL or a dict. */
if (value != NULL && !PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__kwdefaults__ must be set to a dict object");
return -1;
}
if (value) {
if (PySys_Audit("object.__setattr__", "OsO",
op, "__kwdefaults__", value) < 0) {
return -1;
}
} else if (PySys_Audit("object.__delattr__", "Os",
op, "__kwdefaults__") < 0) {
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_kwdefaults, Py_XNewRef(value));
return 0;
}
static PyObject *
func_get_annotate(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (op->func_annotate == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(op->func_annotate);
}
static int
func_set_annotate(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"__annotate__ cannot be deleted");
return -1;
}
if (Py_IsNone(value)) {
Py_XSETREF(op->func_annotate, value);
return 0;
}
else if (PyCallable_Check(value)) {
Py_XSETREF(op->func_annotate, Py_XNewRef(value));
Py_CLEAR(op->func_annotations);
return 0;
}
else {
PyErr_SetString(PyExc_TypeError,
"__annotate__ must be callable or None");
return -1;
}
}
static PyObject *
func_get_annotations(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (op->func_annotations == NULL &&
(op->func_annotate == NULL || !PyCallable_Check(op->func_annotate))) {
op->func_annotations = PyDict_New();
if (op->func_annotations == NULL)
return NULL;
}
PyObject *d = func_get_annotation_dict(op);
return Py_XNewRef(d);
}
static int
func_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == Py_None)
value = NULL;
/* Legal to del f.func_annotations.
* Can only set func_annotations to NULL (through C api)
* or a dict. */
if (value != NULL && !PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__annotations__ must be set to a dict object");
return -1;
}
Py_XSETREF(op->func_annotations, Py_XNewRef(value));
Py_CLEAR(op->func_annotate);
return 0;
}
static PyObject *
func_get_type_params(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (op->func_typeparams == NULL) {
return PyTuple_New(0);
}
assert(PyTuple_Check(op->func_typeparams));
return Py_NewRef(op->func_typeparams);
}
static int
func_set_type_params(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
/* Not legal to del f.__type_params__ or to set it to anything
* other than a tuple object. */
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == NULL || !PyTuple_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__type_params__ must be set to a tuple");
return -1;
}
Py_XSETREF(op->func_typeparams, Py_NewRef(value));
return 0;
}
PyObject *
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
PyObject *type_params)
{
assert(PyFunction_Check(func));
assert(PyTuple_Check(type_params));
PyFunctionObject *f = (PyFunctionObject *)func;
Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
return Py_NewRef(func);
}
static PyGetSetDef func_getsetlist[] = {
{"__code__", func_get_code, func_set_code},
{"__defaults__", func_get_defaults, func_set_defaults},
{"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults},
{"__annotations__", func_get_annotations, func_set_annotations},
{"__annotate__", func_get_annotate, func_set_annotate},
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
{"__name__", func_get_name, func_set_name},
{"__qualname__", func_get_qualname, func_set_qualname},
{"__type_params__", func_get_type_params, func_set_type_params},
{NULL} /* Sentinel */
};
/*[clinic input]
class function "PyFunctionObject *" "&PyFunction_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
#include "clinic/funcobject.c.h"
/* function.__new__() maintains the following invariants for closures.
The closure must correspond to the free variables of the code object.
if len(code.co_freevars) == 0:
closure = NULL
else:
len(closure) == len(code.co_freevars)
for every elt in closure, type(elt) == cell
*/
/*[clinic input]
@classmethod
function.__new__ as func_new
code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
a code object
globals: object(subclass_of="&PyDict_Type")
the globals dictionary
name: object = None
a string that overrides the name from the code object
argdefs as defaults: object = None
a tuple that specifies the default argument values
closure: object = None
a tuple that supplies the bindings for free variables
kwdefaults: object = None
a dictionary that specifies the default keyword argument values
Create a function object.
[clinic start generated code]*/
static PyObject *
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
PyObject *name, PyObject *defaults, PyObject *closure,
PyObject *kwdefaults)
/*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/
{
PyFunctionObject *newfunc;
Py_ssize_t nclosure;
if (name != Py_None && !PyUnicode_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"arg 3 (name) must be None or string");
return NULL;
}
if (defaults != Py_None && !PyTuple_Check(defaults)) {
PyErr_SetString(PyExc_TypeError,
"arg 4 (defaults) must be None or tuple");
return NULL;
}
if (!PyTuple_Check(closure)) {
if (code->co_nfreevars && closure == Py_None) {
PyErr_SetString(PyExc_TypeError,
"arg 5 (closure) must be tuple");