Coverage Report

Created: 2025-12-07 07:03

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