Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/funcobject.c
Line
Count
Source
1
/* Function object implementation */
2
3
#include "Python.h"
4
#include "pycore_code.h"          // _PyCode_VerifyStateless()
5
#include "pycore_dict.h"          // _Py_INCREF_DICT()
6
#include "pycore_function.h"      // _PyFunction_Vectorcall
7
#include "pycore_long.h"          // _PyLong_GetOne()
8
#include "pycore_modsupport.h"    // _PyArg_NoKeywords()
9
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
10
#include "pycore_object_deferred.h" // _PyObject_SetDeferredRefcount()
11
#include "pycore_optimizer.h"       // _Py_Executors_InvalidateDependency()
12
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
13
#include "pycore_setobject.h"     // _PySet_NextEntry()
14
#include "pycore_stats.h"
15
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
16
17
static const char *
18
0
func_event_name(PyFunction_WatchEvent event) {
19
0
    switch (event) {
20
0
        #define CASE(op)                \
21
0
        case PyFunction_EVENT_##op:         \
22
0
            return "PyFunction_EVENT_" #op;
23
0
        PY_FOREACH_FUNC_EVENT(CASE)
24
0
        #undef CASE
25
0
    }
26
0
    Py_UNREACHABLE();
27
0
}
28
29
static void
30
notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
31
                     PyFunctionObject *func, PyObject *new_value)
32
0
{
33
0
    uint8_t bits = interp->active_func_watchers;
34
0
    int i = 0;
35
0
    while (bits) {
36
0
        assert(i < FUNC_MAX_WATCHERS);
37
0
        if (bits & 1) {
38
0
            PyFunction_WatchCallback cb = interp->func_watchers[i];
39
            // callback must be non-null if the watcher bit is set
40
0
            assert(cb != NULL);
41
0
            if (cb(event, func, new_value) < 0) {
42
0
                PyErr_FormatUnraisable(
43
0
                    "Exception ignored in %s watcher callback for function %U at %p",
44
0
                    func_event_name(event),
45
0
                    FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_qualname), func);
46
0
            }
47
0
        }
48
0
        i++;
49
0
        bits >>= 1;
50
0
    }
51
0
}
52
53
static inline void
54
handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
55
                  PyObject *new_value)
56
35.1M
{
57
35.1M
    assert(Py_REFCNT(func) > 0);
58
35.1M
    PyInterpreterState *interp = _PyInterpreterState_GET();
59
35.1M
    assert(interp->_initialized);
60
35.1M
    if (interp->active_func_watchers) {
61
0
        notify_func_watchers(interp, event, func, new_value);
62
0
    }
63
35.1M
    switch (event) {
64
254
        case PyFunction_EVENT_MODIFY_CODE:
65
544
        case PyFunction_EVENT_MODIFY_DEFAULTS:
66
696
        case PyFunction_EVENT_MODIFY_KWDEFAULTS:
67
3.29k
        case PyFunction_EVENT_MODIFY_QUALNAME:
68
#if _Py_TIER2
69
            // Note: we only invalidate JIT code if a function version changes.
70
            // Not when the function is deallocated.
71
            // Function deallocation occurs frequently (think: lambdas),
72
            // so we want to minimize dependency invalidation there.
73
            _Py_Executors_InvalidateDependency(interp, func, 1);
74
#endif
75
3.29k
            RARE_EVENT_INTERP_INC(interp, func_modification);
76
3.29k
            break;
77
35.1M
        default:
78
35.1M
            break;
79
35.1M
    }
80
35.1M
}
81
82
int
83
PyFunction_AddWatcher(PyFunction_WatchCallback callback)
84
0
{
85
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
86
0
    assert(interp->_initialized);
87
0
    for (int i = 0; i < FUNC_MAX_WATCHERS; i++) {
88
0
        if (interp->func_watchers[i] == NULL) {
89
0
            interp->func_watchers[i] = callback;
90
0
            interp->active_func_watchers |= (1 << i);
91
0
            return i;
92
0
        }
93
0
    }
94
0
    PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available");
95
0
    return -1;
96
0
}
97
98
int
99
PyFunction_ClearWatcher(int watcher_id)
100
0
{
101
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
102
0
    if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) {
103
0
        PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d",
104
0
                     watcher_id);
105
0
        return -1;
106
0
    }
107
0
    if (!interp->func_watchers[watcher_id]) {
108
0
        PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d",
109
0
                     watcher_id);
110
0
        return -1;
111
0
    }
112
0
    interp->func_watchers[watcher_id] = NULL;
113
0
    interp->active_func_watchers &= ~(1 << watcher_id);
114
0
    return 0;
115
0
}
116
PyFunctionObject *
117
_PyFunction_FromConstructor(PyFrameConstructor *constr)
118
7.52k
{
119
7.52k
    PyObject *module;
120
7.52k
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
121
0
        return NULL;
122
0
    }
123
124
7.52k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
125
7.52k
    if (op == NULL) {
126
0
        Py_XDECREF(module);
127
0
        return NULL;
128
0
    }
129
7.52k
    _Py_INCREF_DICT(constr->fc_globals);
130
7.52k
    op->func_globals = constr->fc_globals;
131
7.52k
    _Py_INCREF_BUILTINS(constr->fc_builtins);
132
7.52k
    op->func_builtins = constr->fc_builtins;
133
7.52k
    op->func_name = Py_NewRef(constr->fc_name);
134
7.52k
    op->func_qualname = Py_NewRef(constr->fc_qualname);
135
7.52k
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
136
7.52k
    op->func_code = constr->fc_code;
137
7.52k
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
138
7.52k
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
139
7.52k
    op->func_closure = Py_XNewRef(constr->fc_closure);
140
7.52k
    op->func_doc = Py_NewRef(Py_None);
141
7.52k
    op->func_dict = NULL;
142
7.52k
    op->func_weakreflist = NULL;
143
7.52k
    op->func_module = module;
144
7.52k
    op->func_annotations = NULL;
145
7.52k
    op->func_annotate = NULL;
146
7.52k
    op->func_typeparams = NULL;
147
7.52k
    op->vectorcall = _PyFunction_Vectorcall;
148
7.52k
    op->func_version = FUNC_VERSION_UNSET;
149
    // NOTE: functions created via FrameConstructor do not use deferred
150
    // reference counting because they are typically not part of cycles
151
    // nor accessed by multiple threads.
152
7.52k
    _PyObject_GC_TRACK(op);
153
7.52k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
154
7.52k
    return op;
155
7.52k
}
156
157
PyObject *
158
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
159
17.6M
{
160
17.6M
    assert(globals != NULL);
161
17.6M
    assert(PyAnyDict_Check(globals));
162
17.6M
    _Py_INCREF_DICT(globals);
163
164
17.6M
    PyCodeObject *code_obj = (PyCodeObject *)code;
165
17.6M
    _Py_INCREF_CODE(code_obj);
166
167
17.6M
    assert(code_obj->co_name != NULL);
168
17.6M
    PyObject *name = Py_NewRef(code_obj->co_name);
169
170
17.6M
    if (!qualname) {
171
17.6M
        qualname = code_obj->co_qualname;
172
17.6M
    }
173
17.6M
    assert(qualname != NULL);
174
17.6M
    Py_INCREF(qualname);
175
176
17.6M
    PyObject *consts = code_obj->co_consts;
177
17.6M
    assert(PyTuple_Check(consts));
178
17.6M
    PyObject *doc;
179
17.6M
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
180
51.5k
        assert(PyTuple_Size(consts) >= 1);
181
51.5k
        doc = PyTuple_GetItem(consts, 0);
182
51.5k
        if (!PyUnicode_Check(doc)) {
183
0
            doc = Py_None;
184
0
        }
185
51.5k
    }
186
17.5M
    else {
187
17.5M
        doc = Py_None;
188
17.5M
    }
189
17.6M
    Py_INCREF(doc);
190
191
    // __module__: Use globals['__name__'] if it exists, or NULL.
192
17.6M
    PyObject *module;
193
17.6M
    PyObject *builtins = NULL;
194
17.6M
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
195
0
        goto error;
196
0
    }
197
198
17.6M
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
199
17.6M
    if (builtins == NULL) {
200
0
        goto error;
201
0
    }
202
203
17.6M
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
204
17.6M
    if (op == NULL) {
205
0
        goto error;
206
0
    }
207
    /* Note: No failures from this point on, since func_dealloc() does not
208
       expect a partially-created object. */
209
210
17.6M
    op->func_globals = globals;
211
17.6M
    op->func_builtins = builtins;
212
17.6M
    op->func_name = name;
213
17.6M
    op->func_qualname = qualname;
214
17.6M
    op->func_code = (PyObject*)code_obj;
215
17.6M
    op->func_defaults = NULL;    // No default positional arguments
216
17.6M
    op->func_kwdefaults = NULL;  // No default keyword arguments
217
17.6M
    op->func_closure = NULL;
218
17.6M
    op->func_doc = doc;
219
17.6M
    op->func_dict = NULL;
220
17.6M
    op->func_weakreflist = NULL;
221
17.6M
    op->func_module = module;
222
17.6M
    op->func_annotations = NULL;
223
17.6M
    op->func_annotate = NULL;
224
17.6M
    op->func_typeparams = NULL;
225
17.6M
    op->vectorcall = _PyFunction_Vectorcall;
226
17.6M
    op->func_version = FUNC_VERSION_UNSET;
227
17.6M
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
228
17.5M
        (code_obj->co_flags & CO_METHOD)) {
229
        // Use deferred reference counting for top-level functions, but not
230
        // nested functions because they are more likely to capture variables,
231
        // which makes prompt deallocation more important.
232
        //
233
        // Nested methods (functions defined in class scope) are also deferred,
234
        // since they will likely be cleaned up by GC anyway.
235
87.9k
        _PyObject_SetDeferredRefcount((PyObject *)op);
236
87.9k
    }
237
17.6M
    _PyObject_GC_TRACK(op);
238
17.6M
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
239
17.6M
    return (PyObject *)op;
240
241
0
error:
242
0
    Py_DECREF(globals);
243
0
    Py_DECREF(code_obj);
244
0
    Py_DECREF(name);
245
0
    Py_DECREF(qualname);
246
0
    Py_DECREF(doc);
247
0
    Py_XDECREF(module);
248
0
    Py_XDECREF(builtins);
249
0
    return NULL;
250
17.6M
}
251
252
/*
253
(This is purely internal documentation. There are no public APIs here.)
254
255
Function (and code) versions
256
----------------------------
257
258
The Tier 1 specializer generates CALL variants that can be invalidated
259
by changes to critical function attributes:
260
261
- __code__
262
- __defaults__
263
- __kwdefaults__
264
- __closure__
265
266
For this purpose function objects have a 32-bit func_version member
267
that the specializer writes to the specialized instruction's inline
268
cache and which is checked by a guard on the specialized instructions.
269
270
The MAKE_FUNCTION bytecode sets func_version from the code object's
271
co_version field.  The latter is initialized from a counter in the
272
interpreter state (interp->func_state.next_version) and never changes.
273
When this counter overflows, it remains zero and the specializer loses
274
the ability to specialize calls to new functions.
275
276
The func_version is reset to zero when any of the critical attributes
277
is modified; after this point the specializer will no longer specialize
278
calls to this function, and the guard will always fail.
279
280
The function and code version cache
281
-----------------------------------
282
283
The Tier 2 optimizer now has a problem, since it needs to find the
284
function and code objects given only the version number from the inline
285
cache.  Our solution is to maintain a cache mapping version numbers to
286
function and code objects.  To limit the cache size we could hash
287
the version number, but for now we simply use it modulo the table size.
288
289
There are some corner cases (e.g. generator expressions) where we will
290
be unable to find the function object in the cache but we can still
291
find the code object.  For this reason the cache stores both the
292
function object and the code object.
293
294
The cache doesn't contain strong references; cache entries are
295
invalidated whenever the function or code object is deallocated.
296
297
Invariants
298
----------
299
300
These should hold at any time except when one of the cache-mutating
301
functions is running.
302
303
- For any slot s at index i:
304
    - s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i
305
    - s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i
306
    if s->func != NULL, then s->func->func_code == s->code
307
308
*/
309
310
#ifndef Py_GIL_DISABLED
311
static inline struct _func_version_cache_item *
312
get_cache_item(PyInterpreterState *interp, uint32_t version)
313
35.2M
{
314
35.2M
    return interp->func_state.func_version_cache +
315
35.2M
           (version % FUNC_VERSION_CACHE_SIZE);
316
35.2M
}
317
#endif
318
319
void
320
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
321
17.6M
{
322
17.6M
    assert(func->func_version == FUNC_VERSION_UNSET);
323
17.6M
    assert(version >= FUNC_VERSION_FIRST_VALID);
324
    // This should only be called from MAKE_FUNCTION. No code is specialized
325
    // based on the version, so we do not need to stop the world to set it.
326
17.6M
    func->func_version = version;
327
17.6M
#ifndef Py_GIL_DISABLED
328
17.6M
    PyInterpreterState *interp = _PyInterpreterState_GET();
329
17.6M
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
330
17.6M
    slot->func = func;
331
17.6M
    slot->code = func->func_code;
332
17.6M
#endif
333
17.6M
}
334
335
static void
336
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
337
17.5M
{
338
17.5M
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
339
        // Version was never set or has already been cleared.
340
39.7k
        return;
341
39.7k
    }
342
17.5M
#ifndef Py_GIL_DISABLED
343
17.5M
    struct _func_version_cache_item *slot =
344
17.5M
        get_cache_item(interp, func->func_version);
345
17.5M
    if (slot->func == func) {
346
10.2M
        slot->func = NULL;
347
        // Leave slot->code alone, there may be use for it.
348
10.2M
    }
349
17.5M
#endif
350
17.5M
    func->func_version = FUNC_VERSION_CLEARED;
351
17.5M
}
352
353
void
354
_PyFunction_ClearCodeByVersion(uint32_t version)
355
76.9k
{
356
76.9k
#ifndef Py_GIL_DISABLED
357
76.9k
    PyInterpreterState *interp = _PyInterpreterState_GET();
358
76.9k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
359
76.9k
    if (slot->code) {
360
61.2k
        assert(PyCode_Check(slot->code));
361
61.2k
        PyCodeObject *code = (PyCodeObject *)slot->code;
362
61.2k
        if (code->co_version == version) {
363
11.8k
            slot->code = NULL;
364
11.8k
            slot->func = NULL;
365
11.8k
        }
366
61.2k
    }
367
76.9k
#endif
368
76.9k
}
369
370
uint32_t
371
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
372
279k
{
373
279k
    return func->func_version;
374
279k
}
375
376
PyObject *
377
PyFunction_New(PyObject *code, PyObject *globals)
378
17.6M
{
379
17.6M
    return PyFunction_NewWithQualName(code, globals, NULL);
380
17.6M
}
381
382
PyObject *
383
PyFunction_GetCode(PyObject *op)
384
0
{
385
0
    if (!PyFunction_Check(op)) {
386
0
        PyErr_BadInternalCall();
387
0
        return NULL;
388
0
    }
389
0
    return ((PyFunctionObject *) op) -> func_code;
390
0
}
391
392
PyObject *
393
PyFunction_GetGlobals(PyObject *op)
394
0
{
395
0
    if (!PyFunction_Check(op)) {
396
0
        PyErr_BadInternalCall();
397
0
        return NULL;
398
0
    }
399
0
    return ((PyFunctionObject *) op) -> func_globals;
400
0
}
401
402
PyObject *
403
PyFunction_GetModule(PyObject *op)
404
488
{
405
488
    if (!PyFunction_Check(op)) {
406
0
        PyErr_BadInternalCall();
407
0
        return NULL;
408
0
    }
409
488
    return PyFunction_GET_MODULE(op);
410
488
}
411
412
PyObject *
413
PyFunction_GetDefaults(PyObject *op)
414
0
{
415
0
    if (!PyFunction_Check(op)) {
416
0
        PyErr_BadInternalCall();
417
0
        return NULL;
418
0
    }
419
0
    return ((PyFunctionObject *) op) -> func_defaults;
420
0
}
421
422
int
423
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
424
0
{
425
0
    if (!PyFunction_Check(op)) {
426
0
        PyErr_BadInternalCall();
427
0
        return -1;
428
0
    }
429
0
    if (defaults == Py_None)
430
0
        defaults = NULL;
431
0
    else if (defaults && PyTuple_Check(defaults)) {
432
0
        Py_INCREF(defaults);
433
0
    }
434
0
    else {
435
0
        PyErr_SetString(PyExc_SystemError, "non-tuple default args");
436
0
        return -1;
437
0
    }
438
0
    PyFunctionObject *func = (PyFunctionObject *)op;
439
0
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, func, defaults);
440
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
441
0
    _PyEval_StopTheWorld(interp);
442
0
    func_clear_version(interp, func);
443
0
    PyObject *old_defaults = func->func_defaults;
444
0
    func->func_defaults = defaults;
445
0
    _PyEval_StartTheWorld(interp);
446
0
    Py_XDECREF(old_defaults);
447
0
    return 0;
448
0
}
449
450
void
451
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
452
0
{
453
0
    assert(func != NULL);
454
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
455
0
    _PyEval_StopTheWorld(interp);
456
0
    func_clear_version(interp, func);
457
0
    func->vectorcall = vectorcall;
458
0
    _PyEval_StartTheWorld(interp);
459
0
}
460
461
PyObject *
462
PyFunction_GetKwDefaults(PyObject *op)
463
0
{
464
0
    if (!PyFunction_Check(op)) {
465
0
        PyErr_BadInternalCall();
466
0
        return NULL;
467
0
    }
468
0
    return ((PyFunctionObject *) op) -> func_kwdefaults;
469
0
}
470
471
int
472
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
473
0
{
474
0
    if (!PyFunction_Check(op)) {
475
0
        PyErr_BadInternalCall();
476
0
        return -1;
477
0
    }
478
0
    if (defaults == Py_None)
479
0
        defaults = NULL;
480
0
    else if (defaults && PyDict_Check(defaults)) {
481
0
        Py_INCREF(defaults);
482
0
    }
483
0
    else {
484
0
        PyErr_SetString(PyExc_SystemError,
485
0
                        "non-dict keyword only default args");
486
0
        return -1;
487
0
    }
488
0
    PyFunctionObject *func = (PyFunctionObject *)op;
489
0
    handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, func, defaults);
490
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
491
0
    _PyEval_StopTheWorld(interp);
492
0
    func_clear_version(interp, func);
493
0
    PyObject *old_kwdefaults = func->func_kwdefaults;
494
0
    func->func_kwdefaults = defaults;
495
0
    _PyEval_StartTheWorld(interp);
496
0
    Py_XDECREF(old_kwdefaults);
497
0
    return 0;
498
0
}
499
500
PyObject *
501
PyFunction_GetClosure(PyObject *op)
502
0
{
503
0
    if (!PyFunction_Check(op)) {
504
0
        PyErr_BadInternalCall();
505
0
        return NULL;
506
0
    }
507
0
    return ((PyFunctionObject *) op) -> func_closure;
508
0
}
509
510
int
511
PyFunction_SetClosure(PyObject *op, PyObject *closure)
512
0
{
513
0
    if (!PyFunction_Check(op)) {
514
0
        PyErr_BadInternalCall();
515
0
        return -1;
516
0
    }
517
0
    if (closure == Py_None)
518
0
        closure = NULL;
519
0
    else if (PyTuple_Check(closure)) {
520
0
        Py_INCREF(closure);
521
0
    }
522
0
    else {
523
0
        PyErr_Format(PyExc_SystemError,
524
0
                     "expected tuple for closure, got '%.100s'",
525
0
                     Py_TYPE(closure)->tp_name);
526
0
        return -1;
527
0
    }
528
0
    PyFunctionObject *func = (PyFunctionObject *)op;
529
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
530
0
    _PyEval_StopTheWorld(interp);
531
0
    func_clear_version(interp, func);
532
0
    PyObject *old_closure = func->func_closure;
533
0
    func->func_closure = closure;
534
0
    _PyEval_StartTheWorld(interp);
535
0
    Py_XDECREF(old_closure);
536
0
    return 0;
537
0
}
538
539
static void
540
func_set_annotations_and_annotate(PyFunctionObject *op, PyObject *annotations,
541
                                  PyObject *annotate)
542
663
{
543
663
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
544
    // Care is needed, finalizers can run when references are dropped.  Store
545
    // both new values before dropping references to the old.
546
663
    PyObject *old_annotations = op->func_annotations;
547
663
    PyObject *old_annotate = op->func_annotate;
548
663
    FT_ATOMIC_STORE_PTR_RELEASE(op->func_annotations, annotations);
549
663
    FT_ATOMIC_STORE_PTR_RELEASE(op->func_annotate, annotate);
550
663
    if (old_annotations != NULL && !_Py_IsImmortal(old_annotations)) {
551
230
        _PyObject_XDecRefDelayed(old_annotations);
552
230
    }
553
663
    if (old_annotate != NULL && !_Py_IsImmortal(old_annotate)) {
554
0
        _PyObject_XDecRefDelayed(old_annotate);
555
0
    }
556
663
}
557
558
static PyObject *
559
func_get_annotation_dict(PyFunctionObject *op)
560
574
{
561
574
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
562
574
    if (op->func_annotations == NULL) {
563
248
        if (op->func_annotate == NULL || !PyCallable_Check(op->func_annotate)) {
564
0
            Py_RETURN_NONE;
565
0
        }
566
248
        PyObject *one = _PyLong_GetOne();
567
248
        PyObject *ann_dict = _PyObject_CallOneArg(op->func_annotate, one);
568
248
        if (ann_dict == NULL) {
569
0
            return NULL;
570
0
        }
571
248
        if (!PyDict_Check(ann_dict)) {
572
0
            PyErr_Format(PyExc_TypeError,
573
0
                         "__annotate__() must return a dict, not %T",
574
0
                         ann_dict);
575
0
            Py_DECREF(ann_dict);
576
0
            return NULL;
577
0
        }
578
248
        _PyObject_XSetRefDelayed(&op->func_annotations, ann_dict);
579
248
        return ann_dict;
580
248
    }
581
326
    if (PyTuple_CheckExact(op->func_annotations)) {
582
0
        PyObject *ann_tuple = op->func_annotations;
583
0
        PyObject *ann_dict = PyDict_New();
584
0
        if (ann_dict == NULL) {
585
0
            return NULL;
586
0
        }
587
588
0
        assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
589
590
0
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
591
0
            int err = PyDict_SetItem(ann_dict,
592
0
                                     PyTuple_GET_ITEM(ann_tuple, i),
593
0
                                     PyTuple_GET_ITEM(ann_tuple, i + 1));
594
595
0
            if (err < 0) {
596
0
                Py_DECREF(ann_dict);
597
0
                return NULL;
598
0
            }
599
0
        }
600
0
        _PyObject_XSetRefDelayed(&op->func_annotations, ann_dict);
601
0
    }
602
326
    assert(PyDict_Check(op->func_annotations));
603
326
    return op->func_annotations;
604
326
}
605
606
PyObject *
607
PyFunction_GetAnnotations(PyObject *op)
608
0
{
609
0
    if (!PyFunction_Check(op)) {
610
0
        PyErr_BadInternalCall();
611
0
        return NULL;
612
0
    }
613
0
    PyObject *d;
614
0
    Py_BEGIN_CRITICAL_SECTION(op);
615
0
    d = func_get_annotation_dict((PyFunctionObject *)op);
616
0
    Py_END_CRITICAL_SECTION();
617
0
    return d;
618
0
}
619
620
int
621
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
622
0
{
623
0
    if (!PyFunction_Check(op)) {
624
0
        PyErr_BadInternalCall();
625
0
        return -1;
626
0
    }
627
0
    if (annotations == Py_None)
628
0
        annotations = NULL;
629
0
    else if (annotations && PyDict_Check(annotations)) {
630
0
        Py_INCREF(annotations);
631
0
    }
632
0
    else {
633
0
        PyErr_SetString(PyExc_SystemError,
634
0
                        "non-dict annotations");
635
0
        return -1;
636
0
    }
637
0
    PyFunctionObject *func = (PyFunctionObject *)op;
638
0
    Py_BEGIN_CRITICAL_SECTION(func);
639
0
    func_set_annotations_and_annotate(func, annotations, NULL);
640
0
    Py_END_CRITICAL_SECTION();
641
0
    return 0;
642
0
}
643
644
/* Methods */
645
646
#define OFF(x) offsetof(PyFunctionObject, x)
647
648
static PyMemberDef func_memberlist[] = {
649
    {"__closure__",   _Py_T_OBJECT,     OFF(func_closure), Py_READONLY},
650
    {"__globals__",   _Py_T_OBJECT,     OFF(func_globals), Py_READONLY},
651
    {"__builtins__",  _Py_T_OBJECT,     OFF(func_builtins), Py_READONLY},
652
    {NULL}  /* Sentinel */
653
};
654
655
/*[clinic input]
656
class function "PyFunctionObject *" "&PyFunction_Type"
657
[clinic start generated code]*/
658
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
659
660
#include "clinic/funcobject.c.h"
661
662
static PyObject *
663
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
664
205k
{
665
205k
    PyFunctionObject *op = _PyFunction_CAST(self);
666
205k
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
667
0
        return NULL;
668
0
    }
669
670
205k
    return Py_NewRef(op->func_code);
671
205k
}
672
673
static int
674
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
675
254
{
676
254
    PyFunctionObject *op = _PyFunction_CAST(self);
677
678
    /* Not legal to del f.func_code or to set it to anything
679
     * other than a code object. */
680
254
    if (value == NULL || !PyCode_Check(value)) {
681
0
        PyErr_SetString(PyExc_TypeError,
682
0
                        "__code__ must be set to a code object");
683
0
        return -1;
684
0
    }
685
686
254
    if (PySys_Audit("object.__setattr__", "OsO",
687
254
                    op, "__code__", value) < 0) {
688
0
        return -1;
689
0
    }
690
691
254
    int nfree = ((PyCodeObject *)value)->co_nfreevars;
692
254
    Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
693
254
                                        PyTuple_GET_SIZE(op->func_closure));
694
254
    if (nclosure != nfree) {
695
0
        PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_name);
696
0
        PyErr_Format(PyExc_ValueError,
697
0
                     "%U() requires a code object with %zd free vars,"
698
0
                     " not %d",
699
0
                     name, nclosure, nfree);
700
0
        return -1;
701
0
    }
702
703
254
    PyObject *func_code = PyFunction_GET_CODE(op);
704
254
    int old_flags = ((PyCodeObject *)func_code)->co_flags;
705
254
    int new_flags = ((PyCodeObject *)value)->co_flags;
706
254
    int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
707
254
    if ((old_flags & mask) != (new_flags & mask)) {
708
0
        if (PyErr_Warn(PyExc_DeprecationWarning,
709
0
            "Assigning a code object of non-matching type is deprecated "
710
0
            "(e.g., from a generator to a plain function)") < 0)
711
0
        {
712
0
            return -1;
713
0
        }
714
0
    }
715
716
254
    handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
717
254
    PyInterpreterState *interp = _PyInterpreterState_GET();
718
254
    _PyEval_StopTheWorld(interp);
719
254
    func_clear_version(interp, op);
720
254
    PyObject *old_code = op->func_code;
721
254
    op->func_code = Py_NewRef(value);
722
254
    _PyEval_StartTheWorld(interp);
723
254
    Py_XDECREF(old_code);
724
254
    return 0;
725
254
}
726
727
static PyObject *
728
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
729
61.5k
{
730
61.5k
    PyFunctionObject *op = _PyFunction_CAST(self);
731
61.5k
    PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_name);
732
61.5k
    return Py_NewRef(name);
733
61.5k
}
734
735
static int
736
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
737
1.61k
{
738
1.61k
    PyFunctionObject *op = _PyFunction_CAST(self);
739
    /* Not legal to del f.func_name or to set it to anything
740
     * other than a string object. */
741
1.61k
    if (value == NULL || !PyUnicode_Check(value)) {
742
0
        PyErr_SetString(PyExc_TypeError,
743
0
                        "__name__ must be set to a string object");
744
0
        return -1;
745
0
    }
746
1.61k
    Py_BEGIN_CRITICAL_SECTION(op);
747
1.61k
    _PyObject_XSetRefDelayed(&op->func_name, Py_NewRef(value));
748
1.61k
    Py_END_CRITICAL_SECTION();
749
1.61k
    return 0;
750
1.61k
}
751
752
static PyObject *
753
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
754
5.97k
{
755
5.97k
    PyFunctionObject *op = _PyFunction_CAST(self);
756
5.97k
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_qualname);
757
5.97k
    return Py_NewRef(qualname);
758
5.97k
}
759
760
static int
761
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
762
2.59k
{
763
2.59k
    PyFunctionObject *op = _PyFunction_CAST(self);
764
    /* Not legal to del f.__qualname__ or to set it to anything
765
     * other than a string object. */
766
2.59k
    if (value == NULL || !PyUnicode_Check(value)) {
767
0
        PyErr_SetString(PyExc_TypeError,
768
0
                        "__qualname__ must be set to a string object");
769
0
        return -1;
770
0
    }
771
2.59k
    handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
772
2.59k
    Py_BEGIN_CRITICAL_SECTION(op);
773
2.59k
    _PyObject_XSetRefDelayed(&op->func_qualname, Py_NewRef(value));
774
2.59k
    Py_END_CRITICAL_SECTION();
775
2.59k
    return 0;
776
2.59k
}
777
778
static PyObject *
779
func_get_doc(PyObject *self, void *Py_UNUSED(ignored))
780
188k
{
781
188k
    PyFunctionObject *op = _PyFunction_CAST(self);
782
188k
    PyObject *doc = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_doc);
783
188k
    if (doc == NULL) {
784
0
        doc = Py_None;
785
0
    }
786
188k
    return Py_NewRef(doc);
787
188k
}
788
789
static int
790
func_set_doc(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
791
2.32k
{
792
    /* Legal to del f.__doc__ or to set it to any object. */
793
2.32k
    PyFunctionObject *op = _PyFunction_CAST(self);
794
2.32k
    Py_BEGIN_CRITICAL_SECTION(op);
795
2.32k
    _PyObject_XSetRefDelayed(&op->func_doc, Py_XNewRef(value));
796
2.32k
    Py_END_CRITICAL_SECTION();
797
2.32k
    return 0;
798
2.32k
}
799
800
static PyObject *
801
func_get_module(PyObject *self, void *Py_UNUSED(ignored))
802
6.38k
{
803
6.38k
    PyFunctionObject *op = _PyFunction_CAST(self);
804
6.38k
    PyObject *module = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_module);
805
6.38k
    if (module == NULL) {
806
0
        module = Py_None;
807
0
    }
808
6.38k
    return Py_NewRef(module);
809
6.38k
}
810
811
static int
812
func_set_module(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
813
1.33k
{
814
    /* Legal to del f.__module__ or to set it to any object. */
815
1.33k
    PyFunctionObject *op = _PyFunction_CAST(self);
816
1.33k
    Py_BEGIN_CRITICAL_SECTION(op);
817
1.33k
    _PyObject_XSetRefDelayed(&op->func_module, Py_XNewRef(value));
818
1.33k
    Py_END_CRITICAL_SECTION();
819
1.33k
    return 0;
820
1.33k
}
821
822
static PyObject *
823
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
824
26.9k
{
825
26.9k
    PyFunctionObject *op = _PyFunction_CAST(self);
826
26.9k
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
827
0
        return NULL;
828
0
    }
829
26.9k
    if (op->func_defaults == NULL) {
830
26.7k
        Py_RETURN_NONE;
831
26.7k
    }
832
136
    return Py_NewRef(op->func_defaults);
833
26.9k
}
834
835
static int
836
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
837
290
{
838
    /* Legal to del f.func_defaults.
839
     * Can only set func_defaults to NULL or a tuple. */
840
290
    PyFunctionObject *op = _PyFunction_CAST(self);
841
290
    if (value == Py_None)
842
0
        value = NULL;
843
290
    if (value != NULL && !PyTuple_Check(value)) {
844
0
        PyErr_SetString(PyExc_TypeError,
845
0
                        "__defaults__ must be set to a tuple object");
846
0
        return -1;
847
0
    }
848
290
    if (value) {
849
290
        if (PySys_Audit("object.__setattr__", "OsO",
850
290
                        op, "__defaults__", value) < 0) {
851
0
            return -1;
852
0
        }
853
290
    } else if (PySys_Audit("object.__delattr__", "Os",
854
0
                           op, "__defaults__") < 0) {
855
0
        return -1;
856
0
    }
857
858
290
    handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
859
290
    PyInterpreterState *interp = _PyInterpreterState_GET();
860
290
    _PyEval_StopTheWorld(interp);
861
290
    func_clear_version(interp, op);
862
290
    PyObject *old_defaults = op->func_defaults;
863
290
    op->func_defaults = Py_XNewRef(value);
864
290
    _PyEval_StartTheWorld(interp);
865
290
    Py_XDECREF(old_defaults);
866
290
    return 0;
867
290
}
868
869
static PyObject *
870
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
871
26.9k
{
872
26.9k
    PyFunctionObject *op = _PyFunction_CAST(self);
873
26.9k
    if (PySys_Audit("object.__getattr__", "Os",
874
26.9k
                    op, "__kwdefaults__") < 0) {
875
0
        return NULL;
876
0
    }
877
26.9k
    if (op->func_kwdefaults == NULL) {
878
26.7k
        Py_RETURN_NONE;
879
26.7k
    }
880
160
    return Py_NewRef(op->func_kwdefaults);
881
26.9k
}
882
883
static int
884
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
885
152
{
886
152
    PyFunctionObject *op = _PyFunction_CAST(self);
887
152
    if (value == Py_None)
888
0
        value = NULL;
889
    /* Legal to del f.func_kwdefaults.
890
     * Can only set func_kwdefaults to NULL or a dict. */
891
152
    if (value != NULL && !PyDict_Check(value)) {
892
0
        PyErr_SetString(PyExc_TypeError,
893
0
            "__kwdefaults__ must be set to a dict object");
894
0
        return -1;
895
0
    }
896
152
    if (value) {
897
152
        if (PySys_Audit("object.__setattr__", "OsO",
898
152
                        op, "__kwdefaults__", value) < 0) {
899
0
            return -1;
900
0
        }
901
152
    } else if (PySys_Audit("object.__delattr__", "Os",
902
0
                           op, "__kwdefaults__") < 0) {
903
0
        return -1;
904
0
    }
905
906
152
    handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
907
152
    PyInterpreterState *interp = _PyInterpreterState_GET();
908
152
    _PyEval_StopTheWorld(interp);
909
152
    func_clear_version(interp, op);
910
152
    PyObject *old_kwdefaults = op->func_kwdefaults;
911
152
    op->func_kwdefaults = Py_XNewRef(value);
912
152
    _PyEval_StartTheWorld(interp);
913
152
    Py_XDECREF(old_kwdefaults);
914
152
    return 0;
915
152
}
916
917
/*[clinic input]
918
@critical_section
919
@getter
920
function.__annotate__
921
922
Get the code object for a function.
923
[clinic start generated code]*/
924
925
static PyObject *
926
function___annotate___get_impl(PyFunctionObject *self)
927
/*[clinic end generated code: output=5ec7219ff2bda9e6 input=7f3db11e3c3329f3]*/
928
1.02k
{
929
1.02k
    if (self->func_annotate == NULL) {
930
582
        Py_RETURN_NONE;
931
582
    }
932
443
    return Py_NewRef(self->func_annotate);
933
1.02k
}
934
935
/*[clinic input]
936
@critical_section
937
@setter
938
function.__annotate__
939
[clinic start generated code]*/
940
941
static int
942
function___annotate___set_impl(PyFunctionObject *self, PyObject *value)
943
/*[clinic end generated code: output=05b7dfc07ada66cd input=eb6225e358d97448]*/
944
772
{
945
772
    if (Py_IsNone(value)) {
946
371
        _PyObject_XSetRefDelayed(&self->func_annotate, Py_NewRef(value));
947
371
        return 0;
948
371
    }
949
401
    else if (PyCallable_Check(value)) {
950
401
        func_set_annotations_and_annotate(self, NULL, Py_NewRef(value));
951
401
        return 0;
952
401
    }
953
0
    else {
954
0
        PyErr_SetString(PyExc_TypeError,
955
0
            "__annotate__ must be callable or None");
956
0
        return -1;
957
0
    }
958
772
}
959
960
/*[clinic input]
961
@critical_section
962
@getter
963
function.__annotations__
964
965
Dict of annotations in a function object.
966
[clinic start generated code]*/
967
968
static PyObject *
969
function___annotations___get_impl(PyFunctionObject *self)
970
/*[clinic end generated code: output=a4cf4c884c934cbb input=92643d7186c1ad0c]*/
971
574
{
972
574
    PyObject *d = NULL;
973
574
    if (self->func_annotations == NULL &&
974
528
        (self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) {
975
280
        PyObject *ann_dict = PyDict_New();
976
280
        if (ann_dict == NULL)
977
0
            return NULL;
978
280
        FT_ATOMIC_STORE_PTR_RELEASE(self->func_annotations, ann_dict);
979
280
    }
980
574
    d = func_get_annotation_dict(self);
981
574
    return Py_XNewRef(d);
982
574
}
983
984
/*[clinic input]
985
@critical_section
986
@setter
987
@deleter
988
function.__annotations__
989
[clinic start generated code]*/
990
991
static int
992
function___annotations___set_impl(PyFunctionObject *self, PyObject *value)
993
/*[clinic end generated code: output=a61795d4a95eede4 input=71f6a58c00ac6745]*/
994
262
{
995
262
    if (value == Py_None)
996
0
        value = NULL;
997
    /* Legal to del f.func_annotations.
998
     * Can only set func_annotations to NULL (through C api)
999
     * or a dict. */
1000
262
    if (value != NULL && !PyDict_Check(value)) {
1001
0
        PyErr_SetString(PyExc_TypeError,
1002
0
            "__annotations__ must be set to a dict object");
1003
0
        return -1;
1004
0
    }
1005
262
    func_set_annotations_and_annotate(self, Py_XNewRef(value), NULL);
1006
262
    return 0;
1007
262
}
1008
1009
/*[clinic input]
1010
@critical_section
1011
@getter
1012
function.__type_params__
1013
1014
Get the declared type parameters for a function.
1015
[clinic start generated code]*/
1016
1017
static PyObject *
1018
function___type_params___get_impl(PyFunctionObject *self)
1019
/*[clinic end generated code: output=eb844d7ffca517a8 input=0864721484293724]*/
1020
941
{
1021
941
    if (self->func_typeparams == NULL) {
1022
865
        return PyTuple_New(0);
1023
865
    }
1024
1025
941
    assert(PyTuple_Check(self->func_typeparams));
1026
76
    return Py_NewRef(self->func_typeparams);
1027
941
}
1028
1029
/*[clinic input]
1030
@critical_section
1031
@setter
1032
function.__type_params__
1033
    value: object(subclass_of='&PyTuple_Type')
1034
[clinic start generated code]*/
1035
1036
static int
1037
function___type_params___set_impl(PyFunctionObject *self, PyObject *value)
1038
/*[clinic end generated code: output=038b4cda220e56fb input=e848b79ec6fec497]*/
1039
661
{
1040
661
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
1041
661
    return 0;
1042
661
}
1043
1044
PyObject *
1045
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
1046
                             PyObject *type_params)
1047
24
{
1048
24
    assert(PyFunction_Check(func));
1049
24
    assert(PyTuple_Check(type_params));
1050
24
    PyFunctionObject *f = (PyFunctionObject *)func;
1051
24
    Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
1052
24
    return Py_NewRef(func);
1053
24
}
1054
1055
static PyGetSetDef func_getsetlist[] = {
1056
    {"__code__", func_get_code, func_set_code},
1057
    {"__defaults__", func_get_defaults, func_set_defaults},
1058
    {"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults},
1059
    FUNCTION___ANNOTATIONS___GETSETDEF
1060
    FUNCTION___ANNOTATE___GETSETDEF
1061
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
1062
    {"__doc__", func_get_doc, func_set_doc},
1063
    {"__module__", func_get_module, func_set_module},
1064
    {"__name__", func_get_name, func_set_name},
1065
    {"__qualname__", func_get_qualname, func_set_qualname},
1066
    FUNCTION___TYPE_PARAMS___GETSETDEF
1067
    {NULL} /* Sentinel */
1068
};
1069
1070
/* function.__new__() maintains the following invariants for closures.
1071
   The closure must correspond to the free variables of the code object.
1072
1073
   if len(code.co_freevars) == 0:
1074
       closure = NULL
1075
   else:
1076
       len(closure) == len(code.co_freevars)
1077
   for every elt in closure, type(elt) == cell
1078
*/
1079
1080
/*[clinic input]
1081
@classmethod
1082
function.__new__ as func_new
1083
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1084
        a code object
1085
    globals: object(subclass_of="&PyDict_Type")
1086
        the globals dictionary
1087
    name: object = None
1088
        a string that overrides the name from the code object
1089
    argdefs as defaults: object = None
1090
        a tuple that specifies the default argument values
1091
    closure: object = None
1092
        a tuple that supplies the bindings for free variables
1093
    kwdefaults: object = None
1094
        a dictionary that specifies the default keyword argument values
1095
1096
Create a function object.
1097
[clinic start generated code]*/
1098
1099
static PyObject *
1100
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
1101
              PyObject *name, PyObject *defaults, PyObject *closure,
1102
              PyObject *kwdefaults)
1103
/*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/
1104
36
{
1105
36
    PyFunctionObject *newfunc;
1106
36
    Py_ssize_t nclosure;
1107
1108
36
    if (name != Py_None && !PyUnicode_Check(name)) {
1109
0
        PyErr_SetString(PyExc_TypeError,
1110
0
                        "arg 3 (name) must be None or string");
1111
0
        return NULL;
1112
0
    }
1113
36
    if (defaults != Py_None && !PyTuple_Check(defaults)) {
1114
0
        PyErr_SetString(PyExc_TypeError,
1115
0
                        "arg 4 (defaults) must be None or tuple");
1116
0
        return NULL;
1117
0
    }
1118
36
    if (!PyTuple_Check(closure)) {
1119
0
        if (code->co_nfreevars && closure == Py_None) {
1120
0
            PyErr_SetString(PyExc_TypeError,
1121
0
                            "arg 5 (closure) must be tuple");
1122
0
            return NULL;
1123
0
        }
1124
0
        else if (closure != Py_None) {
1125
0
            PyErr_SetString(PyExc_TypeError,
1126
0
                "arg 5 (closure) must be None or tuple");
1127
0
            return NULL;
1128
0
        }
1129
0
    }
1130
36
    if (kwdefaults != Py_None && !PyDict_Check(kwdefaults)) {
1131
0
        PyErr_SetString(PyExc_TypeError,
1132
0
                        "arg 6 (kwdefaults) must be None or dict");
1133
0
        return NULL;
1134
0
    }
1135
1136
    /* check that the closure is well-formed */
1137
36
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
1138
36
    if (code->co_nfreevars != nclosure)
1139
0
        return PyErr_Format(PyExc_ValueError,
1140
0
                            "%U requires closure of length %d, not %zd",
1141
0
                            code->co_name, code->co_nfreevars, nclosure);
1142
36
    if (nclosure) {
1143
36
        Py_ssize_t i;
1144
72
        for (i = 0; i < nclosure; i++) {
1145
36
            PyObject *o = PyTuple_GET_ITEM(closure, i);
1146
36
            if (!PyCell_Check(o)) {
1147
0
                return PyErr_Format(PyExc_TypeError,
1148
0
                    "arg 5 (closure) expected cell, found %s",
1149
0
                                    Py_TYPE(o)->tp_name);
1150
0
            }
1151
36
        }
1152
36
    }
1153
36
    if (PySys_Audit("function.__new__", "O", code) < 0) {
1154
0
        return NULL;
1155
0
    }
1156
1157
36
    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
1158
36
                                                 globals);
1159
36
    if (newfunc == NULL) {
1160
0
        return NULL;
1161
0
    }
1162
36
    if (name != Py_None) {
1163
0
        Py_SETREF(newfunc->func_name, Py_NewRef(name));
1164
0
    }
1165
36
    if (defaults != Py_None) {
1166
0
        newfunc->func_defaults = Py_NewRef(defaults);
1167
0
    }
1168
36
    if (closure != Py_None) {
1169
36
        newfunc->func_closure = Py_NewRef(closure);
1170
36
    }
1171
36
    if (kwdefaults != Py_None) {
1172
0
        newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
1173
0
    }
1174
1175
36
    return (PyObject *)newfunc;
1176
36
}
1177
1178
static int
1179
func_clear(PyObject *self)
1180
17.5M
{
1181
17.5M
    PyFunctionObject *op = _PyFunction_CAST(self);
1182
17.5M
    func_clear_version(_PyInterpreterState_GET(), op);
1183
17.5M
    PyObject *globals = op->func_globals;
1184
17.5M
    op->func_globals = NULL;
1185
17.5M
    if (globals != NULL) {
1186
17.5M
        _Py_DECREF_DICT(globals);
1187
17.5M
    }
1188
17.5M
    PyObject *builtins = op->func_builtins;
1189
17.5M
    op->func_builtins = NULL;
1190
17.5M
    if (builtins != NULL) {
1191
17.5M
        _Py_DECREF_BUILTINS(builtins);
1192
17.5M
    }
1193
17.5M
    Py_CLEAR(op->func_module);
1194
17.5M
    Py_CLEAR(op->func_defaults);
1195
17.5M
    Py_CLEAR(op->func_kwdefaults);
1196
17.5M
    Py_CLEAR(op->func_doc);
1197
17.5M
    Py_CLEAR(op->func_dict);
1198
17.5M
    Py_CLEAR(op->func_closure);
1199
17.5M
    Py_CLEAR(op->func_annotations);
1200
17.5M
    Py_CLEAR(op->func_annotate);
1201
17.5M
    Py_CLEAR(op->func_typeparams);
1202
    // Don't Py_CLEAR(op->func_code), since code is always required
1203
    // to be non-NULL. Similarly, name and qualname shouldn't be NULL.
1204
    // However, name and qualname could be str subclasses, so they
1205
    // could have reference cycles. The solution is to replace them
1206
    // with a genuinely immutable string.
1207
17.5M
    Py_SETREF(op->func_name, &_Py_STR(empty));
1208
17.5M
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1209
17.5M
    return 0;
1210
17.5M
}
1211
1212
static void
1213
func_dealloc(PyObject *self)
1214
17.5M
{
1215
17.5M
    PyFunctionObject *op = _PyFunction_CAST(self);
1216
17.5M
    _PyObject_ResurrectStart(self);
1217
17.5M
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1218
17.5M
    if (_PyObject_ResurrectEnd(self)) {
1219
0
        return;
1220
0
    }
1221
17.5M
    _PyObject_GC_UNTRACK(op);
1222
17.5M
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1223
17.5M
    (void)func_clear((PyObject*)op);
1224
    // These aren't cleared by func_clear().
1225
17.5M
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1226
17.5M
    Py_DECREF(op->func_name);
1227
17.5M
    Py_DECREF(op->func_qualname);
1228
17.5M
    PyObject_GC_Del(op);
1229
17.5M
}
1230
1231
static PyObject*
1232
func_repr(PyObject *self)
1233
0
{
1234
0
    PyFunctionObject *op = _PyFunction_CAST(self);
1235
0
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->func_qualname);
1236
0
    return PyUnicode_FromFormat("<function %U at %p>", qualname, op);
1237
0
}
1238
1239
static int
1240
func_traverse(PyObject *self, visitproc visit, void *arg)
1241
5.53M
{
1242
5.53M
    PyFunctionObject *f = _PyFunction_CAST(self);
1243
5.53M
    Py_VISIT(f->func_code);
1244
5.53M
    Py_VISIT(f->func_globals);
1245
5.53M
    Py_VISIT(f->func_builtins);
1246
5.53M
    Py_VISIT(f->func_module);
1247
5.53M
    Py_VISIT(f->func_defaults);
1248
5.53M
    Py_VISIT(f->func_kwdefaults);
1249
5.53M
    Py_VISIT(f->func_doc);
1250
5.53M
    Py_VISIT(f->func_name);
1251
5.53M
    Py_VISIT(f->func_dict);
1252
5.53M
    Py_VISIT(f->func_closure);
1253
5.53M
    Py_VISIT(f->func_annotations);
1254
5.53M
    Py_VISIT(f->func_annotate);
1255
5.53M
    Py_VISIT(f->func_typeparams);
1256
5.53M
    Py_VISIT(f->func_qualname);
1257
5.53M
    return 0;
1258
5.53M
}
1259
1260
/* Bind a function to an object */
1261
static PyObject *
1262
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1263
26.9M
{
1264
26.9M
    if (obj == Py_None || obj == NULL) {
1265
5.96k
        return Py_NewRef(func);
1266
5.96k
    }
1267
26.9M
    return PyMethod_New(func, obj);
1268
26.9M
}
1269
1270
PyTypeObject PyFunction_Type = {
1271
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1272
    "function",
1273
    sizeof(PyFunctionObject),
1274
    0,
1275
    func_dealloc,                               /* tp_dealloc */
1276
    offsetof(PyFunctionObject, vectorcall),     /* tp_vectorcall_offset */
1277
    0,                                          /* tp_getattr */
1278
    0,                                          /* tp_setattr */
1279
    0,                                          /* tp_as_async */
1280
    func_repr,                                  /* tp_repr */
1281
    0,                                          /* tp_as_number */
1282
    0,                                          /* tp_as_sequence */
1283
    0,                                          /* tp_as_mapping */
1284
    0,                                          /* tp_hash */
1285
    PyVectorcall_Call,                          /* tp_call */
1286
    0,                                          /* tp_str */
1287
    0,                                          /* tp_getattro */
1288
    0,                                          /* tp_setattro */
1289
    0,                                          /* tp_as_buffer */
1290
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1291
    Py_TPFLAGS_HAVE_VECTORCALL |
1292
    Py_TPFLAGS_METHOD_DESCRIPTOR,               /* tp_flags */
1293
    func_new__doc__,                            /* tp_doc */
1294
    func_traverse,                              /* tp_traverse */
1295
    func_clear,                                 /* tp_clear */
1296
    0,                                          /* tp_richcompare */
1297
    offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
1298
    0,                                          /* tp_iter */
1299
    0,                                          /* tp_iternext */
1300
    0,                                          /* tp_methods */
1301
    func_memberlist,                            /* tp_members */
1302
    func_getsetlist,                            /* tp_getset */
1303
    0,                                          /* tp_base */
1304
    0,                                          /* tp_dict */
1305
    func_descr_get,                             /* tp_descr_get */
1306
    0,                                          /* tp_descr_set */
1307
    offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
1308
    0,                                          /* tp_init */
1309
    0,                                          /* tp_alloc */
1310
    func_new,                                   /* tp_new */
1311
};
1312
1313
1314
int
1315
_PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func)
1316
0
{
1317
0
    assert(!PyErr_Occurred());
1318
0
    assert(PyFunction_Check(func));
1319
1320
    // Check the globals.
1321
0
    PyObject *globalsns = PyFunction_GET_GLOBALS(func);
1322
0
    if (globalsns != NULL && !PyDict_Check(globalsns)) {
1323
0
        _PyErr_Format(tstate, PyExc_TypeError,
1324
0
                      "unsupported globals %R", globalsns);
1325
0
        return -1;
1326
0
    }
1327
    // Check the builtins.
1328
0
    PyObject *builtinsns = _PyFunction_GET_BUILTINS(func);
1329
0
    if (builtinsns != NULL && !PyDict_Check(builtinsns)) {
1330
0
        _PyErr_Format(tstate, PyExc_TypeError,
1331
0
                      "unsupported builtins %R", builtinsns);
1332
0
        return -1;
1333
0
    }
1334
    // Disallow __defaults__.
1335
0
    PyObject *defaults = PyFunction_GET_DEFAULTS(func);
1336
0
    if (defaults != NULL) {
1337
0
        assert(PyTuple_Check(defaults));  // per PyFunction_New()
1338
0
        if (PyTuple_GET_SIZE(defaults) > 0) {
1339
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1340
0
                             "defaults not supported");
1341
0
            return -1;
1342
0
        }
1343
0
    }
1344
    // Disallow __kwdefaults__.
1345
0
    PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func);
1346
0
    if (kwdefaults != NULL) {
1347
0
        assert(PyDict_Check(kwdefaults));  // per PyFunction_New()
1348
0
        if (PyDict_Size(kwdefaults) > 0) {
1349
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1350
0
                             "keyword defaults not supported");
1351
0
            return -1;
1352
0
        }
1353
0
    }
1354
    // Disallow __closure__.
1355
0
    PyObject *closure = PyFunction_GET_CLOSURE(func);
1356
0
    if (closure != NULL) {
1357
0
        assert(PyTuple_Check(closure));  // per PyFunction_New()
1358
0
        if (PyTuple_GET_SIZE(closure) > 0) {
1359
0
            _PyErr_SetString(tstate, PyExc_ValueError, "closures not supported");
1360
0
            return -1;
1361
0
        }
1362
0
    }
1363
    // Check the code.
1364
0
    PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
1365
0
    if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) {
1366
0
        return -1;
1367
0
    }
1368
0
    return 0;
1369
0
}
1370
1371
1372
static int
1373
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
1374
18.8k
{
1375
18.8k
    PyObject *value;
1376
18.8k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1377
18.8k
    if (value != NULL) {
1378
18.8k
        res = PyObject_SetAttr(wrapper, name, value);
1379
18.8k
        Py_DECREF(value);
1380
18.8k
    }
1381
18.8k
    return res;
1382
18.8k
}
1383
1384
// Similar to functools.wraps(wrapper, wrapped)
1385
static int
1386
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1387
4.71k
{
1388
4.71k
#define COPY_ATTR(ATTR) \
1389
18.8k
    do { \
1390
18.8k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1391
0
            return -1; \
1392
0
        } \
1393
18.8k
    } while (0) \
1394
4.71k
1395
4.71k
    COPY_ATTR(__module__);
1396
4.71k
    COPY_ATTR(__name__);
1397
4.71k
    COPY_ATTR(__qualname__);
1398
4.71k
    COPY_ATTR(__doc__);
1399
4.71k
    return 0;
1400
1401
4.71k
#undef COPY_ATTR
1402
4.71k
}
1403
1404
// Used for wrapping __annotations__ and __annotate__ on classmethod
1405
// and staticmethod objects.
1406
static PyObject *
1407
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name)
1408
0
{
1409
0
    PyObject *dict = PyObject_GenericGetDict(obj, NULL);
1410
0
    if (dict == NULL) {
1411
0
        return NULL;
1412
0
    }
1413
0
    PyObject *res;
1414
0
    if (PyDict_GetItemRef(dict, name, &res) < 0) {
1415
0
        Py_DECREF(dict);
1416
0
        return NULL;
1417
0
    }
1418
0
    if (res != NULL) {
1419
0
        Py_DECREF(dict);
1420
0
        return res;
1421
0
    }
1422
0
    res = PyObject_GetAttr(wrapped, name);
1423
0
    if (res == NULL) {
1424
0
        Py_DECREF(dict);
1425
0
        return NULL;
1426
0
    }
1427
0
    if (PyDict_SetItem(dict, name, res) < 0) {
1428
0
        Py_DECREF(dict);
1429
0
        Py_DECREF(res);
1430
0
        return NULL;
1431
0
    }
1432
0
    Py_DECREF(dict);
1433
0
    return res;
1434
0
}
1435
1436
static int
1437
descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value,
1438
                                 char *type_name)
1439
0
{
1440
0
    PyObject *dict = PyObject_GenericGetDict(oobj, NULL);
1441
0
    if (dict == NULL) {
1442
0
        return -1;
1443
0
    }
1444
0
    if (value == NULL) {
1445
0
        if (PyDict_DelItem(dict, name) < 0) {
1446
0
            if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1447
0
                PyErr_Clear();
1448
0
                PyErr_Format(PyExc_AttributeError,
1449
0
                             "'%.200s' object has no attribute '%U'",
1450
0
                             type_name, name);
1451
0
                Py_DECREF(dict);
1452
0
                return -1;
1453
0
            }
1454
0
            else {
1455
0
                Py_DECREF(dict);
1456
0
                return -1;
1457
0
            }
1458
0
        }
1459
0
        Py_DECREF(dict);
1460
0
        return 0;
1461
0
    }
1462
0
    else {
1463
0
        int result = PyDict_SetItem(dict, name, value);
1464
0
        Py_DECREF(dict);
1465
0
        return result;
1466
0
    }
1467
0
}
1468
1469
1470
/* Class method object */
1471
1472
/* A class method receives the class as implicit first argument,
1473
   just like an instance method receives the instance.
1474
   To declare a class method, use this idiom:
1475
1476
     class C:
1477
         @classmethod
1478
         def f(cls, arg1, arg2, argN):
1479
             ...
1480
1481
   It can be called either on the class (e.g. C.f()) or on an instance
1482
   (e.g. C().f()); the instance is ignored except for its class.
1483
   If a class method is called for a derived class, the derived class
1484
   object is passed as the implied first argument.
1485
1486
   Class methods are different than C++ or Java static methods.
1487
   If you want those, see static methods below.
1488
*/
1489
1490
typedef struct {
1491
    PyObject_HEAD
1492
    PyObject *cm_callable;
1493
    PyObject *cm_dict;
1494
} classmethod;
1495
1496
#define _PyClassMethod_CAST(cm) \
1497
456k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1498
456k
     _Py_CAST(classmethod*, cm))
1499
1500
static void
1501
cm_dealloc(PyObject *self)
1502
79
{
1503
79
    classmethod *cm = _PyClassMethod_CAST(self);
1504
79
    _PyObject_GC_UNTRACK((PyObject *)cm);
1505
79
    Py_XDECREF(cm->cm_callable);
1506
79
    Py_XDECREF(cm->cm_dict);
1507
79
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1508
79
}
1509
1510
static int
1511
cm_traverse(PyObject *self, visitproc visit, void *arg)
1512
124k
{
1513
124k
    classmethod *cm = _PyClassMethod_CAST(self);
1514
124k
    Py_VISIT(cm->cm_callable);
1515
124k
    Py_VISIT(cm->cm_dict);
1516
124k
    return 0;
1517
124k
}
1518
1519
static int
1520
cm_clear(PyObject *self)
1521
53
{
1522
53
    classmethod *cm = _PyClassMethod_CAST(self);
1523
53
    Py_CLEAR(cm->cm_callable);
1524
53
    Py_CLEAR(cm->cm_dict);
1525
53
    return 0;
1526
53
}
1527
1528
1529
static PyObject *
1530
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1531
15.9M
{
1532
15.9M
    classmethod *cm = (classmethod *)self;
1533
15.9M
    if (type == NULL)
1534
0
        type = (PyObject *)(Py_TYPE(obj));
1535
15.9M
    return PyMethod_New(cm->cm_callable, type);
1536
15.9M
}
1537
1538
static int
1539
cm_set_callable(classmethod *cm, PyObject *callable)
1540
6.10k
{
1541
6.10k
    assert(callable != NULL);
1542
6.10k
    if (cm->cm_callable == callable) {
1543
        // cm_init() sets the same callable than cm_new()
1544
3.01k
        return 0;
1545
3.01k
    }
1546
1547
3.08k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1548
3.08k
    return functools_wraps((PyObject *)cm, cm->cm_callable);
1549
6.10k
}
1550
1551
static PyObject *
1552
cm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1553
3.01k
{
1554
3.01k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1555
0
        return NULL;
1556
0
    }
1557
3.01k
    PyObject *callable;  // borrowed ref
1558
3.01k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1559
0
        return NULL;
1560
0
    }
1561
1562
3.01k
    classmethod *cm = (classmethod *)PyType_GenericAlloc(type, 0);
1563
3.01k
    if (cm == NULL) {
1564
0
        return NULL;
1565
0
    }
1566
3.01k
    _PyObject_SetDeferredRefcount((PyObject *)cm);
1567
3.01k
    if (cm_set_callable(cm, callable) < 0) {
1568
0
        Py_DECREF(cm);
1569
0
        return NULL;
1570
0
    }
1571
3.01k
    return (PyObject *)cm;
1572
3.01k
}
1573
1574
static int
1575
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1576
3.01k
{
1577
3.01k
    if (!_PyArg_NoKeywords("classmethod", kwds)) {
1578
0
        return -1;
1579
0
    }
1580
3.01k
    PyObject *callable;  // borrowed ref
1581
3.01k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) {
1582
0
        return -1;
1583
0
    }
1584
1585
3.01k
    classmethod *cm = (classmethod *)self;
1586
3.01k
    return cm_set_callable(cm, callable);
1587
3.01k
}
1588
1589
static PyMemberDef cm_memberlist[] = {
1590
    {"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1591
    {"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1592
    {NULL}  /* Sentinel */
1593
};
1594
1595
static PyObject *
1596
cm_get___isabstractmethod__(PyObject *self, void *closure)
1597
1.31k
{
1598
1.31k
    classmethod *cm = _PyClassMethod_CAST(self);
1599
1.31k
    int res = _PyObject_IsAbstract(cm->cm_callable);
1600
1.31k
    if (res == -1) {
1601
0
        return NULL;
1602
0
    }
1603
1.31k
    else if (res) {
1604
0
        Py_RETURN_TRUE;
1605
0
    }
1606
1.31k
    Py_RETURN_FALSE;
1607
1.31k
}
1608
1609
static PyObject *
1610
cm_get___annotations__(PyObject *self, void *closure)
1611
0
{
1612
0
    classmethod *cm = _PyClassMethod_CAST(self);
1613
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__));
1614
0
}
1615
1616
static int
1617
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1618
0
{
1619
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod");
1620
0
}
1621
1622
static PyObject *
1623
cm_get___annotate__(PyObject *self, void *closure)
1624
0
{
1625
0
    classmethod *cm = _PyClassMethod_CAST(self);
1626
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__));
1627
0
}
1628
1629
static int
1630
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1631
0
{
1632
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod");
1633
0
}
1634
1635
1636
static PyGetSetDef cm_getsetlist[] = {
1637
    {"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL},
1638
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1639
    {"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL},
1640
    {"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL},
1641
    {NULL} /* Sentinel */
1642
};
1643
1644
static PyMethodDef cm_methodlist[] = {
1645
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1646
    {NULL} /* Sentinel */
1647
};
1648
1649
static PyObject*
1650
cm_repr(PyObject *self)
1651
0
{
1652
0
    classmethod *cm = _PyClassMethod_CAST(self);
1653
0
    return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
1654
0
}
1655
1656
PyDoc_STRVAR(classmethod_doc,
1657
"classmethod(function, /)\n\
1658
--\n\
1659
\n\
1660
Convert a function to be a class method.\n\
1661
\n\
1662
A class method receives the class as implicit first argument,\n\
1663
just like an instance method receives the instance.\n\
1664
To declare a class method, use this idiom:\n\
1665
\n\
1666
  class C:\n\
1667
      @classmethod\n\
1668
      def f(cls, arg1, arg2, argN):\n\
1669
          ...\n\
1670
\n\
1671
It can be called either on the class (e.g. C.f()) or on an instance\n\
1672
(e.g. C().f()).  The instance is ignored except for its class.\n\
1673
If a class method is called for a derived class, the derived class\n\
1674
object is passed as the implied first argument.\n\
1675
\n\
1676
Class methods are different than C++ or Java static methods.\n\
1677
If you want those, see the staticmethod builtin.");
1678
1679
PyTypeObject PyClassMethod_Type = {
1680
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1681
    "classmethod",
1682
    sizeof(classmethod),
1683
    0,
1684
    cm_dealloc,                                 /* tp_dealloc */
1685
    0,                                          /* tp_vectorcall_offset */
1686
    0,                                          /* tp_getattr */
1687
    0,                                          /* tp_setattr */
1688
    0,                                          /* tp_as_async */
1689
    cm_repr,                                    /* tp_repr */
1690
    0,                                          /* tp_as_number */
1691
    0,                                          /* tp_as_sequence */
1692
    0,                                          /* tp_as_mapping */
1693
    0,                                          /* tp_hash */
1694
    0,                                          /* tp_call */
1695
    0,                                          /* tp_str */
1696
    0,                                          /* tp_getattro */
1697
    0,                                          /* tp_setattro */
1698
    0,                                          /* tp_as_buffer */
1699
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1700
    classmethod_doc,                            /* tp_doc */
1701
    cm_traverse,                                /* tp_traverse */
1702
    cm_clear,                                   /* tp_clear */
1703
    0,                                          /* tp_richcompare */
1704
    0,                                          /* tp_weaklistoffset */
1705
    0,                                          /* tp_iter */
1706
    0,                                          /* tp_iternext */
1707
    cm_methodlist,                              /* tp_methods */
1708
    cm_memberlist,                              /* tp_members */
1709
    cm_getsetlist,                              /* tp_getset */
1710
    0,                                          /* tp_base */
1711
    0,                                          /* tp_dict */
1712
    cm_descr_get,                               /* tp_descr_get */
1713
    0,                                          /* tp_descr_set */
1714
    offsetof(classmethod, cm_dict),             /* tp_dictoffset */
1715
    cm_init,                                    /* tp_init */
1716
    PyType_GenericAlloc,                        /* tp_alloc */
1717
    cm_new,                                     /* tp_new */
1718
    PyObject_GC_Del,                            /* tp_free */
1719
};
1720
1721
PyObject *
1722
PyClassMethod_New(PyObject *callable)
1723
76
{
1724
76
    classmethod *cm = (classmethod *)
1725
76
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1726
76
    if (cm == NULL) {
1727
0
        return NULL;
1728
0
    }
1729
76
    if (cm_set_callable(cm, callable) < 0) {
1730
0
        Py_DECREF(cm);
1731
0
        return NULL;
1732
0
    }
1733
76
    return (PyObject *)cm;
1734
76
}
1735
1736
1737
/* Static method object */
1738
1739
/* A static method does not receive an implicit first argument.
1740
   To declare a static method, use this idiom:
1741
1742
     class C:
1743
         @staticmethod
1744
         def f(arg1, arg2, argN):
1745
             ...
1746
1747
   It can be called either on the class (e.g. C.f()) or on an instance
1748
   (e.g. C().f()). Both the class and the instance are ignored, and
1749
   neither is passed implicitly as the first argument to the method.
1750
1751
   Static methods in Python are similar to those found in Java or C++.
1752
   For a more advanced concept, see class methods above.
1753
*/
1754
1755
typedef struct {
1756
    PyObject_HEAD
1757
    PyObject *sm_callable;
1758
    PyObject *sm_dict;
1759
} staticmethod;
1760
1761
#define _PyStaticMethod_CAST(cm) \
1762
19.6M
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1763
19.6M
     _Py_CAST(staticmethod*, cm))
1764
1765
static void
1766
sm_dealloc(PyObject *self)
1767
117
{
1768
117
    staticmethod *sm = _PyStaticMethod_CAST(self);
1769
117
    _PyObject_GC_UNTRACK((PyObject *)sm);
1770
117
    Py_XDECREF(sm->sm_callable);
1771
117
    Py_XDECREF(sm->sm_dict);
1772
117
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1773
117
}
1774
1775
static int
1776
sm_traverse(PyObject *self, visitproc visit, void *arg)
1777
59.4k
{
1778
59.4k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1779
59.4k
    Py_VISIT(sm->sm_callable);
1780
59.4k
    Py_VISIT(sm->sm_dict);
1781
59.4k
    return 0;
1782
59.4k
}
1783
1784
static int
1785
sm_clear(PyObject *self)
1786
0
{
1787
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1788
0
    Py_CLEAR(sm->sm_callable);
1789
0
    Py_CLEAR(sm->sm_dict);
1790
0
    return 0;
1791
0
}
1792
1793
static PyObject *
1794
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1795
13.9k
{
1796
13.9k
    staticmethod *sm = (staticmethod *)self;
1797
13.9k
    return Py_NewRef(sm->sm_callable);
1798
13.9k
}
1799
1800
static int
1801
sm_set_callable(staticmethod *sm, PyObject *callable)
1802
2.40k
{
1803
2.40k
    assert(callable != NULL);
1804
2.40k
    if (sm->sm_callable == callable) {
1805
        // sm_init() sets the same callable than sm_new()
1806
772
        return 0;
1807
772
    }
1808
1809
1.62k
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1810
1.62k
    return functools_wraps((PyObject *)sm, sm->sm_callable);
1811
2.40k
}
1812
1813
static PyObject *
1814
sm_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1815
772
{
1816
772
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1817
0
        return NULL;
1818
0
    }
1819
772
    PyObject *callable;  // borrowed ref
1820
772
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1821
0
        return NULL;
1822
0
    }
1823
1824
772
    staticmethod *sm = (staticmethod *)PyType_GenericAlloc(type, 0);
1825
772
    if (sm == NULL) {
1826
0
        return NULL;
1827
0
    }
1828
772
    _PyObject_SetDeferredRefcount((PyObject *)sm);
1829
772
    if (sm_set_callable(sm, callable) < 0) {
1830
0
        Py_DECREF(sm);
1831
0
        return NULL;
1832
0
    }
1833
772
    return (PyObject *)sm;
1834
772
}
1835
1836
static int
1837
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1838
772
{
1839
772
    if (!_PyArg_NoKeywords("staticmethod", kwds)) {
1840
0
        return -1;
1841
0
    }
1842
772
    PyObject *callable;  // borrowed ref
1843
772
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) {
1844
0
        return -1;
1845
0
    }
1846
1847
772
    staticmethod *sm = (staticmethod *)self;
1848
772
    return sm_set_callable(sm, callable);
1849
772
}
1850
1851
static PyObject*
1852
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
1853
0
{
1854
0
    staticmethod *sm = (staticmethod *)callable;
1855
0
    return PyObject_Call(sm->sm_callable, args, kwargs);
1856
0
}
1857
1858
static PyMemberDef sm_memberlist[] = {
1859
    {"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1860
    {"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1861
    {NULL}  /* Sentinel */
1862
};
1863
1864
static PyObject *
1865
sm_get___isabstractmethod__(PyObject *self, void *closure)
1866
71
{
1867
71
    staticmethod *sm = _PyStaticMethod_CAST(self);
1868
71
    int res = _PyObject_IsAbstract(sm->sm_callable);
1869
71
    if (res == -1) {
1870
0
        return NULL;
1871
0
    }
1872
71
    else if (res) {
1873
0
        Py_RETURN_TRUE;
1874
0
    }
1875
71
    Py_RETURN_FALSE;
1876
71
}
1877
1878
static PyObject *
1879
sm_get___annotations__(PyObject *self, void *closure)
1880
0
{
1881
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1882
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__));
1883
0
}
1884
1885
static int
1886
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1887
0
{
1888
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod");
1889
0
}
1890
1891
static PyObject *
1892
sm_get___annotate__(PyObject *self, void *closure)
1893
0
{
1894
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1895
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__));
1896
0
}
1897
1898
static int
1899
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1900
0
{
1901
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod");
1902
0
}
1903
1904
static PyGetSetDef sm_getsetlist[] = {
1905
    {"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL},
1906
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1907
    {"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL},
1908
    {"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL},
1909
    {NULL} /* Sentinel */
1910
};
1911
1912
static PyMethodDef sm_methodlist[] = {
1913
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1914
    {NULL} /* Sentinel */
1915
};
1916
1917
static PyObject*
1918
sm_repr(PyObject *self)
1919
0
{
1920
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1921
0
    return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1922
0
}
1923
1924
PyDoc_STRVAR(staticmethod_doc,
1925
"staticmethod(function, /)\n\
1926
--\n\
1927
\n\
1928
Convert a function to be a static method.\n\
1929
\n\
1930
A static method does not receive an implicit first argument.\n\
1931
To declare a static method, use this idiom:\n\
1932
\n\
1933
     class C:\n\
1934
         @staticmethod\n\
1935
         def f(arg1, arg2, argN):\n\
1936
             ...\n\
1937
\n\
1938
It can be called either on the class (e.g. C.f()) or on an instance\n\
1939
(e.g. C().f()). Both the class and the instance are ignored, and\n\
1940
neither is passed implicitly as the first argument to the method.\n\
1941
\n\
1942
Static methods in Python are similar to those found in Java or C++.\n\
1943
For a more advanced concept, see the classmethod builtin.");
1944
1945
PyTypeObject PyStaticMethod_Type = {
1946
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1947
    "staticmethod",
1948
    sizeof(staticmethod),
1949
    0,
1950
    sm_dealloc,                                 /* tp_dealloc */
1951
    0,                                          /* tp_vectorcall_offset */
1952
    0,                                          /* tp_getattr */
1953
    0,                                          /* tp_setattr */
1954
    0,                                          /* tp_as_async */
1955
    sm_repr,                                    /* tp_repr */
1956
    0,                                          /* tp_as_number */
1957
    0,                                          /* tp_as_sequence */
1958
    0,                                          /* tp_as_mapping */
1959
    0,                                          /* tp_hash */
1960
    sm_call,                                    /* tp_call */
1961
    0,                                          /* tp_str */
1962
    0,                                          /* tp_getattro */
1963
    0,                                          /* tp_setattro */
1964
    0,                                          /* tp_as_buffer */
1965
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1966
    staticmethod_doc,                           /* tp_doc */
1967
    sm_traverse,                                /* tp_traverse */
1968
    sm_clear,                                   /* tp_clear */
1969
    0,                                          /* tp_richcompare */
1970
    0,                                          /* tp_weaklistoffset */
1971
    0,                                          /* tp_iter */
1972
    0,                                          /* tp_iternext */
1973
    sm_methodlist,                              /* tp_methods */
1974
    sm_memberlist,                              /* tp_members */
1975
    sm_getsetlist,                              /* tp_getset */
1976
    0,                                          /* tp_base */
1977
    0,                                          /* tp_dict */
1978
    sm_descr_get,                               /* tp_descr_get */
1979
    0,                                          /* tp_descr_set */
1980
    offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
1981
    sm_init,                                    /* tp_init */
1982
    PyType_GenericAlloc,                        /* tp_alloc */
1983
    sm_new,                                     /* tp_new */
1984
    PyObject_GC_Del,                            /* tp_free */
1985
};
1986
1987
PyObject *
1988
PyStaticMethod_New(PyObject *callable)
1989
856
{
1990
856
    staticmethod *sm = (staticmethod *)
1991
856
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1992
856
    if (sm == NULL) {
1993
0
        return NULL;
1994
0
    }
1995
856
    _PyObject_SetDeferredRefcount((PyObject *)sm);
1996
856
    if (sm_set_callable(sm, callable) < 0) {
1997
0
        Py_DECREF(sm);
1998
0
        return NULL;
1999
0
    }
2000
856
    return (PyObject *)sm;
2001
856
}
2002
2003
PyObject *
2004
_PyClassMethod_GetFunc(PyObject *self)
2005
330k
{
2006
330k
    classmethod *cm = _PyClassMethod_CAST(self);
2007
330k
    return cm->cm_callable;
2008
330k
}
2009
2010
PyObject *
2011
_PyStaticMethod_GetFunc(PyObject *self)
2012
19.6M
{
2013
    staticmethod *sm = _PyStaticMethod_CAST(self);
2014
19.6M
    return sm->sm_callable;
2015
19.6M
}