Coverage Report

Created: 2026-02-26 06:53

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