Coverage Report

Created: 2026-04-12 06:54

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