Coverage Report

Created: 2025-10-12 06:48

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
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
29.6M
{
55
29.6M
    assert(Py_REFCNT(func) > 0);
56
29.6M
    PyInterpreterState *interp = _PyInterpreterState_GET();
57
29.6M
    assert(interp->_initialized);
58
29.6M
    if (interp->active_func_watchers) {
59
0
        notify_func_watchers(interp, event, func, new_value);
60
0
    }
61
29.6M
    switch (event) {
62
0
        case PyFunction_EVENT_MODIFY_CODE:
63
4
        case PyFunction_EVENT_MODIFY_DEFAULTS:
64
4
        case PyFunction_EVENT_MODIFY_KWDEFAULTS:
65
697
        case PyFunction_EVENT_MODIFY_QUALNAME:
66
697
            RARE_EVENT_INTERP_INC(interp, func_modification);
67
697
            break;
68
29.6M
        default:
69
29.6M
            break;
70
29.6M
    }
71
29.6M
}
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
1.14k
{
110
1.14k
    PyObject *module;
111
1.14k
    if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
112
0
        return NULL;
113
0
    }
114
115
1.14k
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
116
1.14k
    if (op == NULL) {
117
0
        Py_XDECREF(module);
118
0
        return NULL;
119
0
    }
120
1.14k
    _Py_INCREF_DICT(constr->fc_globals);
121
1.14k
    op->func_globals = constr->fc_globals;
122
1.14k
    _Py_INCREF_BUILTINS(constr->fc_builtins);
123
1.14k
    op->func_builtins = constr->fc_builtins;
124
1.14k
    op->func_name = Py_NewRef(constr->fc_name);
125
1.14k
    op->func_qualname = Py_NewRef(constr->fc_qualname);
126
1.14k
    _Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
127
1.14k
    op->func_code = constr->fc_code;
128
1.14k
    op->func_defaults = Py_XNewRef(constr->fc_defaults);
129
1.14k
    op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
130
1.14k
    op->func_closure = Py_XNewRef(constr->fc_closure);
131
1.14k
    op->func_doc = Py_NewRef(Py_None);
132
1.14k
    op->func_dict = NULL;
133
1.14k
    op->func_weakreflist = NULL;
134
1.14k
    op->func_module = module;
135
1.14k
    op->func_annotations = NULL;
136
1.14k
    op->func_annotate = NULL;
137
1.14k
    op->func_typeparams = NULL;
138
1.14k
    op->vectorcall = _PyFunction_Vectorcall;
139
1.14k
    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
1.14k
    _PyObject_GC_TRACK(op);
144
1.14k
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
145
1.14k
    return op;
146
1.14k
}
147
148
PyObject *
149
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
150
14.8M
{
151
14.8M
    assert(globals != NULL);
152
14.8M
    assert(PyDict_Check(globals));
153
14.8M
    _Py_INCREF_DICT(globals);
154
155
14.8M
    PyCodeObject *code_obj = (PyCodeObject *)code;
156
14.8M
    _Py_INCREF_CODE(code_obj);
157
158
14.8M
    assert(code_obj->co_name != NULL);
159
14.8M
    PyObject *name = Py_NewRef(code_obj->co_name);
160
161
14.8M
    if (!qualname) {
162
14.8M
        qualname = code_obj->co_qualname;
163
14.8M
    }
164
14.8M
    assert(qualname != NULL);
165
14.8M
    Py_INCREF(qualname);
166
167
14.8M
    PyObject *consts = code_obj->co_consts;
168
14.8M
    assert(PyTuple_Check(consts));
169
14.8M
    PyObject *doc;
170
14.8M
    if (code_obj->co_flags & CO_HAS_DOCSTRING) {
171
27.6k
        assert(PyTuple_Size(consts) >= 1);
172
27.6k
        doc = PyTuple_GetItem(consts, 0);
173
27.6k
        if (!PyUnicode_Check(doc)) {
174
0
            doc = Py_None;
175
0
        }
176
27.6k
    }
177
14.7M
    else {
178
14.7M
        doc = Py_None;
179
14.7M
    }
180
14.8M
    Py_INCREF(doc);
181
182
    // __module__: Use globals['__name__'] if it exists, or NULL.
183
14.8M
    PyObject *module;
184
14.8M
    PyObject *builtins = NULL;
185
14.8M
    if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
186
0
        goto error;
187
0
    }
188
189
14.8M
    builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
190
14.8M
    if (builtins == NULL) {
191
0
        goto error;
192
0
    }
193
194
14.8M
    PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
195
14.8M
    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.8M
    op->func_globals = globals;
202
14.8M
    op->func_builtins = builtins;
203
14.8M
    op->func_name = name;
204
14.8M
    op->func_qualname = qualname;
205
14.8M
    op->func_code = (PyObject*)code_obj;
206
14.8M
    op->func_defaults = NULL;    // No default positional arguments
207
14.8M
    op->func_kwdefaults = NULL;  // No default keyword arguments
208
14.8M
    op->func_closure = NULL;
209
14.8M
    op->func_doc = doc;
210
14.8M
    op->func_dict = NULL;
211
14.8M
    op->func_weakreflist = NULL;
212
14.8M
    op->func_module = module;
213
14.8M
    op->func_annotations = NULL;
214
14.8M
    op->func_annotate = NULL;
215
14.8M
    op->func_typeparams = NULL;
216
14.8M
    op->vectorcall = _PyFunction_Vectorcall;
217
14.8M
    op->func_version = FUNC_VERSION_UNSET;
218
14.8M
    if (((code_obj->co_flags & CO_NESTED) == 0) ||
219
14.7M
        (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
29.2k
        _PyObject_SetDeferredRefcount((PyObject *)op);
227
29.2k
    }
228
14.8M
    _PyObject_GC_TRACK(op);
229
14.8M
    handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
230
14.8M
    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.8M
}
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
29.6M
{
305
29.6M
    return interp->func_state.func_version_cache +
306
29.6M
           (version % FUNC_VERSION_CACHE_SIZE);
307
29.6M
}
308
#endif
309
310
void
311
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
312
14.8M
{
313
14.8M
    assert(func->func_version == FUNC_VERSION_UNSET);
314
14.8M
    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.8M
    func->func_version = version;
318
14.8M
#ifndef Py_GIL_DISABLED
319
14.8M
    PyInterpreterState *interp = _PyInterpreterState_GET();
320
14.8M
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
321
14.8M
    slot->func = func;
322
14.8M
    slot->code = func->func_code;
323
14.8M
#endif
324
14.8M
}
325
326
static void
327
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
328
14.8M
{
329
14.8M
    if (func->func_version < FUNC_VERSION_FIRST_VALID) {
330
        // Version was never set or has already been cleared.
331
1.66k
        return;
332
1.66k
    }
333
14.8M
#ifndef Py_GIL_DISABLED
334
14.8M
    struct _func_version_cache_item *slot =
335
14.8M
        get_cache_item(interp, func->func_version);
336
14.8M
    if (slot->func == func) {
337
9.04M
        slot->func = NULL;
338
        // Leave slot->code alone, there may be use for it.
339
9.04M
    }
340
14.8M
#endif
341
14.8M
    func->func_version = FUNC_VERSION_CLEARED;
342
14.8M
}
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
8.33k
{
361
8.33k
#ifndef Py_GIL_DISABLED
362
8.33k
    PyInterpreterState *interp = _PyInterpreterState_GET();
363
8.33k
    struct _func_version_cache_item *slot = get_cache_item(interp, version);
364
8.33k
    if (slot->code) {
365
6.11k
        assert(PyCode_Check(slot->code));
366
6.11k
        PyCodeObject *code = (PyCodeObject *)slot->code;
367
6.11k
        if (code->co_version == version) {
368
6.11k
            slot->code = NULL;
369
6.11k
            slot->func = NULL;
370
6.11k
        }
371
6.11k
    }
372
8.33k
#endif
373
8.33k
}
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
17.6k
{
404
17.6k
    return func->func_version;
405
17.6k
}
406
407
PyObject *
408
PyFunction_New(PyObject *code, PyObject *globals)
409
14.8M
{
410
14.8M
    return PyFunction_NewWithQualName(code, globals, NULL);
411
14.8M
}
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
66
{
436
66
    if (!PyFunction_Check(op)) {
437
0
        PyErr_BadInternalCall();
438
0
        return NULL;
439
0
    }
440
66
    return ((PyFunctionObject *) op) -> func_module;
441
66
}
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
0
            return NULL;
562
0
        }
563
8
        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
8
        Py_XSETREF(op->func_annotations, ann_dict);
571
8
        return ann_dict;
572
8
    }
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
40
{
654
40
    PyFunctionObject *op = _PyFunction_CAST(self);
655
40
    if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
656
0
        return NULL;
657
0
    }
658
659
40
    return Py_NewRef(op->func_code);
660
40
}
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
2.28k
{
714
2.28k
    PyFunctionObject *op = _PyFunction_CAST(self);
715
2.28k
    return Py_NewRef(op->func_name);
716
2.28k
}
717
718
static int
719
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
720
327
{
721
327
    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
327
    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
327
    Py_XSETREF(op->func_name, Py_NewRef(value));
730
327
    return 0;
731
327
}
732
733
static PyObject *
734
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
735
1.73k
{
736
1.73k
    PyFunctionObject *op = _PyFunction_CAST(self);
737
1.73k
    return Py_NewRef(op->func_qualname);
738
1.73k
}
739
740
static int
741
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
742
693
{
743
693
    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
693
    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
693
    handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
752
693
    Py_XSETREF(op->func_qualname, Py_NewRef(value));
753
693
    return 0;
754
693
}
755
756
static PyObject *
757
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
758
8
{
759
8
    PyFunctionObject *op = _PyFunction_CAST(self);
760
8
    if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
761
0
        return NULL;
762
0
    }
763
8
    if (op->func_defaults == NULL) {
764
6
        Py_RETURN_NONE;
765
6
    }
766
2
    return Py_NewRef(op->func_defaults);
767
8
}
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
8
{
801
8
    PyFunctionObject *op = _PyFunction_CAST(self);
802
8
    if (PySys_Audit("object.__getattr__", "Os",
803
8
                    op, "__kwdefaults__") < 0) {
804
0
        return NULL;
805
0
    }
806
8
    if (op->func_kwdefaults == NULL) {
807
2
        Py_RETURN_NONE;
808
2
    }
809
6
    return Py_NewRef(op->func_kwdefaults);
810
8
}
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
121
{
853
121
    if (self->func_annotate == NULL) {
854
121
        Py_RETURN_NONE;
855
121
    }
856
0
    return Py_NewRef(self->func_annotate);
857
121
}
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
65
{
869
65
    if (value == NULL) {
870
0
        PyErr_SetString(PyExc_TypeError,
871
0
            "__annotate__ cannot be deleted");
872
0
        return -1;
873
0
    }
874
65
    if (Py_IsNone(value)) {
875
65
        Py_XSETREF(self->func_annotate, value);
876
65
        return 0;
877
65
    }
878
0
    else if (PyCallable_Check(value)) {
879
0
        Py_XSETREF(self->func_annotate, Py_XNewRef(value));
880
0
        Py_CLEAR(self->func_annotations);
881
0
        return 0;
882
0
    }
883
0
    else {
884
0
        PyErr_SetString(PyExc_TypeError,
885
0
            "__annotate__ must be callable or None");
886
0
        return -1;
887
0
    }
888
65
}
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
121
{
950
121
    if (self->func_typeparams == NULL) {
951
121
        return PyTuple_New(0);
952
121
    }
953
954
121
    assert(PyTuple_Check(self->func_typeparams));
955
0
    return Py_NewRef(self->func_typeparams);
956
121
}
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
65
{
968
    /* Not legal to del f.__type_params__ or to set it to anything
969
     * other than a tuple object. */
970
65
    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
65
    Py_XSETREF(self->func_typeparams, Py_NewRef(value));
976
65
    return 0;
977
65
}
978
979
PyObject *
980
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
981
                             PyObject *type_params)
982
0
{
983
0
    assert(PyFunction_Check(func));
984
0
    assert(PyTuple_Check(type_params));
985
0
    PyFunctionObject *f = (PyFunctionObject *)func;
986
0
    Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
987
0
    return Py_NewRef(func);
988
0
}
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
0
{
1038
0
    PyFunctionObject *newfunc;
1039
0
    Py_ssize_t nclosure;
1040
1041
0
    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
0
    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
0
    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
0
    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
0
    nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
1071
0
    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
0
    if (nclosure) {
1076
0
        Py_ssize_t i;
1077
0
        for (i = 0; i < nclosure; i++) {
1078
0
            PyObject *o = PyTuple_GET_ITEM(closure, i);
1079
0
            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
0
        }
1085
0
    }
1086
0
    if (PySys_Audit("function.__new__", "O", code) < 0) {
1087
0
        return NULL;
1088
0
    }
1089
1090
0
    newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
1091
0
                                                 globals);
1092
0
    if (newfunc == NULL) {
1093
0
        return NULL;
1094
0
    }
1095
0
    if (name != Py_None) {
1096
0
        Py_SETREF(newfunc->func_name, Py_NewRef(name));
1097
0
    }
1098
0
    if (defaults != Py_None) {
1099
0
        newfunc->func_defaults = Py_NewRef(defaults);
1100
0
    }
1101
0
    if (closure != Py_None) {
1102
0
        newfunc->func_closure = Py_NewRef(closure);
1103
0
    }
1104
0
    if (kwdefaults != Py_None) {
1105
0
        newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
1106
0
    }
1107
1108
0
    return (PyObject *)newfunc;
1109
0
}
1110
1111
static int
1112
func_clear(PyObject *self)
1113
14.8M
{
1114
14.8M
    PyFunctionObject *op = _PyFunction_CAST(self);
1115
14.8M
    func_clear_version(_PyInterpreterState_GET(), op);
1116
14.8M
    PyObject *globals = op->func_globals;
1117
14.8M
    op->func_globals = NULL;
1118
14.8M
    if (globals != NULL) {
1119
14.8M
        _Py_DECREF_DICT(globals);
1120
14.8M
    }
1121
14.8M
    PyObject *builtins = op->func_builtins;
1122
14.8M
    op->func_builtins = NULL;
1123
14.8M
    if (builtins != NULL) {
1124
14.8M
        _Py_DECREF_BUILTINS(builtins);
1125
14.8M
    }
1126
14.8M
    Py_CLEAR(op->func_module);
1127
14.8M
    Py_CLEAR(op->func_defaults);
1128
14.8M
    Py_CLEAR(op->func_kwdefaults);
1129
14.8M
    Py_CLEAR(op->func_doc);
1130
14.8M
    Py_CLEAR(op->func_dict);
1131
14.8M
    Py_CLEAR(op->func_closure);
1132
14.8M
    Py_CLEAR(op->func_annotations);
1133
14.8M
    Py_CLEAR(op->func_annotate);
1134
14.8M
    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.8M
    Py_SETREF(op->func_name, &_Py_STR(empty));
1141
14.8M
    Py_SETREF(op->func_qualname, &_Py_STR(empty));
1142
14.8M
    return 0;
1143
14.8M
}
1144
1145
static void
1146
func_dealloc(PyObject *self)
1147
14.8M
{
1148
14.8M
    PyFunctionObject *op = _PyFunction_CAST(self);
1149
14.8M
    _PyObject_ResurrectStart(self);
1150
14.8M
    handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
1151
14.8M
    if (_PyObject_ResurrectEnd(self)) {
1152
0
        return;
1153
0
    }
1154
14.8M
    _PyObject_GC_UNTRACK(op);
1155
14.8M
    FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
1156
14.8M
    (void)func_clear((PyObject*)op);
1157
    // These aren't cleared by func_clear().
1158
14.8M
    _Py_DECREF_CODE((PyCodeObject *)op->func_code);
1159
14.8M
    Py_DECREF(op->func_name);
1160
14.8M
    Py_DECREF(op->func_qualname);
1161
14.8M
    PyObject_GC_Del(op);
1162
14.8M
}
1163
1164
static PyObject*
1165
func_repr(PyObject *self)
1166
0
{
1167
0
    PyFunctionObject *op = _PyFunction_CAST(self);
1168
0
    return PyUnicode_FromFormat("<function %U at %p>",
1169
0
                                op->func_qualname, op);
1170
0
}
1171
1172
static int
1173
func_traverse(PyObject *self, visitproc visit, void *arg)
1174
11.9M
{
1175
11.9M
    PyFunctionObject *f = _PyFunction_CAST(self);
1176
11.9M
    Py_VISIT(f->func_code);
1177
11.9M
    Py_VISIT(f->func_globals);
1178
11.9M
    Py_VISIT(f->func_builtins);
1179
11.9M
    Py_VISIT(f->func_module);
1180
11.9M
    Py_VISIT(f->func_defaults);
1181
11.9M
    Py_VISIT(f->func_kwdefaults);
1182
11.9M
    Py_VISIT(f->func_doc);
1183
11.9M
    Py_VISIT(f->func_name);
1184
11.9M
    Py_VISIT(f->func_dict);
1185
11.9M
    Py_VISIT(f->func_closure);
1186
11.9M
    Py_VISIT(f->func_annotations);
1187
11.9M
    Py_VISIT(f->func_annotate);
1188
11.9M
    Py_VISIT(f->func_typeparams);
1189
11.9M
    Py_VISIT(f->func_qualname);
1190
11.9M
    return 0;
1191
11.9M
}
1192
1193
/* Bind a function to an object */
1194
static PyObject *
1195
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
1196
19.6M
{
1197
19.6M
    if (obj == Py_None || obj == NULL) {
1198
2.28k
        return Py_NewRef(func);
1199
2.28k
    }
1200
19.6M
    return PyMethod_New(func, obj);
1201
19.6M
}
1202
1203
PyTypeObject PyFunction_Type = {
1204
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1205
    "function",
1206
    sizeof(PyFunctionObject),
1207
    0,
1208
    func_dealloc,                               /* tp_dealloc */
1209
    offsetof(PyFunctionObject, vectorcall),     /* tp_vectorcall_offset */
1210
    0,                                          /* tp_getattr */
1211
    0,                                          /* tp_setattr */
1212
    0,                                          /* tp_as_async */
1213
    func_repr,                                  /* tp_repr */
1214
    0,                                          /* tp_as_number */
1215
    0,                                          /* tp_as_sequence */
1216
    0,                                          /* tp_as_mapping */
1217
    0,                                          /* tp_hash */
1218
    PyVectorcall_Call,                          /* tp_call */
1219
    0,                                          /* tp_str */
1220
    0,                                          /* tp_getattro */
1221
    0,                                          /* tp_setattro */
1222
    0,                                          /* tp_as_buffer */
1223
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1224
    Py_TPFLAGS_HAVE_VECTORCALL |
1225
    Py_TPFLAGS_METHOD_DESCRIPTOR,               /* tp_flags */
1226
    func_new__doc__,                            /* tp_doc */
1227
    func_traverse,                              /* tp_traverse */
1228
    func_clear,                                 /* tp_clear */
1229
    0,                                          /* tp_richcompare */
1230
    offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
1231
    0,                                          /* tp_iter */
1232
    0,                                          /* tp_iternext */
1233
    0,                                          /* tp_methods */
1234
    func_memberlist,                            /* tp_members */
1235
    func_getsetlist,                            /* tp_getset */
1236
    0,                                          /* tp_base */
1237
    0,                                          /* tp_dict */
1238
    func_descr_get,                             /* tp_descr_get */
1239
    0,                                          /* tp_descr_set */
1240
    offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
1241
    0,                                          /* tp_init */
1242
    0,                                          /* tp_alloc */
1243
    func_new,                                   /* tp_new */
1244
};
1245
1246
1247
int
1248
_PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func)
1249
0
{
1250
0
    assert(!PyErr_Occurred());
1251
0
    assert(PyFunction_Check(func));
1252
1253
    // Check the globals.
1254
0
    PyObject *globalsns = PyFunction_GET_GLOBALS(func);
1255
0
    if (globalsns != NULL && !PyDict_Check(globalsns)) {
1256
0
        _PyErr_Format(tstate, PyExc_TypeError,
1257
0
                      "unsupported globals %R", globalsns);
1258
0
        return -1;
1259
0
    }
1260
    // Check the builtins.
1261
0
    PyObject *builtinsns = _PyFunction_GET_BUILTINS(func);
1262
0
    if (builtinsns != NULL && !PyDict_Check(builtinsns)) {
1263
0
        _PyErr_Format(tstate, PyExc_TypeError,
1264
0
                      "unsupported builtins %R", builtinsns);
1265
0
        return -1;
1266
0
    }
1267
    // Disallow __defaults__.
1268
0
    PyObject *defaults = PyFunction_GET_DEFAULTS(func);
1269
0
    if (defaults != NULL) {
1270
0
        assert(PyTuple_Check(defaults));  // per PyFunction_New()
1271
0
        if (PyTuple_GET_SIZE(defaults) > 0) {
1272
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1273
0
                             "defaults not supported");
1274
0
            return -1;
1275
0
        }
1276
0
    }
1277
    // Disallow __kwdefaults__.
1278
0
    PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func);
1279
0
    if (kwdefaults != NULL) {
1280
0
        assert(PyDict_Check(kwdefaults));  // per PyFunction_New()
1281
0
        if (PyDict_Size(kwdefaults) > 0) {
1282
0
            _PyErr_SetString(tstate, PyExc_ValueError,
1283
0
                             "keyword defaults not supported");
1284
0
            return -1;
1285
0
        }
1286
0
    }
1287
    // Disallow __closure__.
1288
0
    PyObject *closure = PyFunction_GET_CLOSURE(func);
1289
0
    if (closure != NULL) {
1290
0
        assert(PyTuple_Check(closure));  // per PyFunction_New()
1291
0
        if (PyTuple_GET_SIZE(closure) > 0) {
1292
0
            _PyErr_SetString(tstate, PyExc_ValueError, "closures not supported");
1293
0
            return -1;
1294
0
        }
1295
0
    }
1296
    // Check the code.
1297
0
    PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
1298
0
    if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) {
1299
0
        return -1;
1300
0
    }
1301
0
    return 0;
1302
0
}
1303
1304
1305
static int
1306
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
1307
5.96k
{
1308
5.96k
    PyObject *value;
1309
5.96k
    int res = PyObject_GetOptionalAttr(wrapped, name, &value);
1310
5.96k
    if (value != NULL) {
1311
5.96k
        res = PyObject_SetAttr(wrapper, name, value);
1312
5.96k
        Py_DECREF(value);
1313
5.96k
    }
1314
5.96k
    return res;
1315
5.96k
}
1316
1317
// Similar to functools.wraps(wrapper, wrapped)
1318
static int
1319
functools_wraps(PyObject *wrapper, PyObject *wrapped)
1320
1.49k
{
1321
1.49k
#define COPY_ATTR(ATTR) \
1322
5.96k
    do { \
1323
5.96k
        if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
1324
0
            return -1; \
1325
0
        } \
1326
5.96k
    } while (0) \
1327
1.49k
1328
1.49k
    COPY_ATTR(__module__);
1329
1.49k
    COPY_ATTR(__name__);
1330
1.49k
    COPY_ATTR(__qualname__);
1331
1.49k
    COPY_ATTR(__doc__);
1332
1.49k
    return 0;
1333
1334
1.49k
#undef COPY_ATTR
1335
1.49k
}
1336
1337
// Used for wrapping __annotations__ and __annotate__ on classmethod
1338
// and staticmethod objects.
1339
static PyObject *
1340
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name)
1341
0
{
1342
0
    PyObject *dict = PyObject_GenericGetDict(obj, NULL);
1343
0
    if (dict == NULL) {
1344
0
        return NULL;
1345
0
    }
1346
0
    PyObject *res;
1347
0
    if (PyDict_GetItemRef(dict, name, &res) < 0) {
1348
0
        Py_DECREF(dict);
1349
0
        return NULL;
1350
0
    }
1351
0
    if (res != NULL) {
1352
0
        Py_DECREF(dict);
1353
0
        return res;
1354
0
    }
1355
0
    res = PyObject_GetAttr(wrapped, name);
1356
0
    if (res == NULL) {
1357
0
        Py_DECREF(dict);
1358
0
        return NULL;
1359
0
    }
1360
0
    if (PyDict_SetItem(dict, name, res) < 0) {
1361
0
        Py_DECREF(dict);
1362
0
        Py_DECREF(res);
1363
0
        return NULL;
1364
0
    }
1365
0
    Py_DECREF(dict);
1366
0
    return res;
1367
0
}
1368
1369
static int
1370
descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value,
1371
                                 char *type_name)
1372
0
{
1373
0
    PyObject *dict = PyObject_GenericGetDict(oobj, NULL);
1374
0
    if (dict == NULL) {
1375
0
        return -1;
1376
0
    }
1377
0
    if (value == NULL) {
1378
0
        if (PyDict_DelItem(dict, name) < 0) {
1379
0
            if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1380
0
                PyErr_Clear();
1381
0
                PyErr_Format(PyExc_AttributeError,
1382
0
                             "'%.200s' object has no attribute '%U'",
1383
0
                             type_name, name);
1384
0
                Py_DECREF(dict);
1385
0
                return -1;
1386
0
            }
1387
0
            else {
1388
0
                Py_DECREF(dict);
1389
0
                return -1;
1390
0
            }
1391
0
        }
1392
0
        Py_DECREF(dict);
1393
0
        return 0;
1394
0
    }
1395
0
    else {
1396
0
        Py_DECREF(dict);
1397
0
        return PyDict_SetItem(dict, name, value);
1398
0
    }
1399
0
}
1400
1401
1402
/* Class method object */
1403
1404
/* A class method receives the class as implicit first argument,
1405
   just like an instance method receives the instance.
1406
   To declare a class method, use this idiom:
1407
1408
     class C:
1409
         @classmethod
1410
         def f(cls, arg1, arg2, argN):
1411
             ...
1412
1413
   It can be called either on the class (e.g. C.f()) or on an instance
1414
   (e.g. C().f()); the instance is ignored except for its class.
1415
   If a class method is called for a derived class, the derived class
1416
   object is passed as the implied first argument.
1417
1418
   Class methods are different than C++ or Java static methods.
1419
   If you want those, see static methods below.
1420
*/
1421
1422
typedef struct {
1423
    PyObject_HEAD
1424
    PyObject *cm_callable;
1425
    PyObject *cm_dict;
1426
} classmethod;
1427
1428
#define _PyClassMethod_CAST(cm) \
1429
494k
    (assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
1430
494k
     _Py_CAST(classmethod*, cm))
1431
1432
static void
1433
cm_dealloc(PyObject *self)
1434
32
{
1435
32
    classmethod *cm = _PyClassMethod_CAST(self);
1436
32
    _PyObject_GC_UNTRACK((PyObject *)cm);
1437
32
    Py_XDECREF(cm->cm_callable);
1438
32
    Py_XDECREF(cm->cm_dict);
1439
32
    Py_TYPE(cm)->tp_free((PyObject *)cm);
1440
32
}
1441
1442
static int
1443
cm_traverse(PyObject *self, visitproc visit, void *arg)
1444
494k
{
1445
494k
    classmethod *cm = _PyClassMethod_CAST(self);
1446
494k
    Py_VISIT(cm->cm_callable);
1447
494k
    Py_VISIT(cm->cm_dict);
1448
494k
    return 0;
1449
494k
}
1450
1451
static int
1452
cm_clear(PyObject *self)
1453
22
{
1454
22
    classmethod *cm = _PyClassMethod_CAST(self);
1455
22
    Py_CLEAR(cm->cm_callable);
1456
22
    Py_CLEAR(cm->cm_dict);
1457
22
    return 0;
1458
22
}
1459
1460
1461
static PyObject *
1462
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1463
485k
{
1464
485k
    classmethod *cm = (classmethod *)self;
1465
1466
485k
    if (cm->cm_callable == NULL) {
1467
0
        PyErr_SetString(PyExc_RuntimeError,
1468
0
                        "uninitialized classmethod object");
1469
0
        return NULL;
1470
0
    }
1471
485k
    if (type == NULL)
1472
0
        type = (PyObject *)(Py_TYPE(obj));
1473
485k
    return PyMethod_New(cm->cm_callable, type);
1474
485k
}
1475
1476
static int
1477
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
1478
1.20k
{
1479
1.20k
    classmethod *cm = (classmethod *)self;
1480
1.20k
    PyObject *callable;
1481
1482
1.20k
    if (!_PyArg_NoKeywords("classmethod", kwds))
1483
0
        return -1;
1484
1.20k
    if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
1485
0
        return -1;
1486
1.20k
    Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
1487
1488
1.20k
    if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
1489
0
        return -1;
1490
0
    }
1491
1.20k
    return 0;
1492
1.20k
}
1493
1494
static PyMemberDef cm_memberlist[] = {
1495
    {"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1496
    {"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
1497
    {NULL}  /* Sentinel */
1498
};
1499
1500
static PyObject *
1501
cm_get___isabstractmethod__(PyObject *self, void *closure)
1502
504
{
1503
504
    classmethod *cm = _PyClassMethod_CAST(self);
1504
504
    int res = _PyObject_IsAbstract(cm->cm_callable);
1505
504
    if (res == -1) {
1506
0
        return NULL;
1507
0
    }
1508
504
    else if (res) {
1509
0
        Py_RETURN_TRUE;
1510
0
    }
1511
504
    Py_RETURN_FALSE;
1512
504
}
1513
1514
static PyObject *
1515
cm_get___annotations__(PyObject *self, void *closure)
1516
0
{
1517
0
    classmethod *cm = _PyClassMethod_CAST(self);
1518
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__));
1519
0
}
1520
1521
static int
1522
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1523
0
{
1524
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod");
1525
0
}
1526
1527
static PyObject *
1528
cm_get___annotate__(PyObject *self, void *closure)
1529
0
{
1530
0
    classmethod *cm = _PyClassMethod_CAST(self);
1531
0
    return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__));
1532
0
}
1533
1534
static int
1535
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1536
0
{
1537
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod");
1538
0
}
1539
1540
1541
static PyGetSetDef cm_getsetlist[] = {
1542
    {"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL},
1543
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1544
    {"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL},
1545
    {"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL},
1546
    {NULL} /* Sentinel */
1547
};
1548
1549
static PyMethodDef cm_methodlist[] = {
1550
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1551
    {NULL} /* Sentinel */
1552
};
1553
1554
static PyObject*
1555
cm_repr(PyObject *self)
1556
0
{
1557
0
    classmethod *cm = _PyClassMethod_CAST(self);
1558
0
    return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
1559
0
}
1560
1561
PyDoc_STRVAR(classmethod_doc,
1562
"classmethod(function, /)\n\
1563
--\n\
1564
\n\
1565
Convert a function to be a class method.\n\
1566
\n\
1567
A class method receives the class as implicit first argument,\n\
1568
just like an instance method receives the instance.\n\
1569
To declare a class method, use this idiom:\n\
1570
\n\
1571
  class C:\n\
1572
      @classmethod\n\
1573
      def f(cls, arg1, arg2, argN):\n\
1574
          ...\n\
1575
\n\
1576
It can be called either on the class (e.g. C.f()) or on an instance\n\
1577
(e.g. C().f()).  The instance is ignored except for its class.\n\
1578
If a class method is called for a derived class, the derived class\n\
1579
object is passed as the implied first argument.\n\
1580
\n\
1581
Class methods are different than C++ or Java static methods.\n\
1582
If you want those, see the staticmethod builtin.");
1583
1584
PyTypeObject PyClassMethod_Type = {
1585
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1586
    "classmethod",
1587
    sizeof(classmethod),
1588
    0,
1589
    cm_dealloc,                                 /* tp_dealloc */
1590
    0,                                          /* tp_vectorcall_offset */
1591
    0,                                          /* tp_getattr */
1592
    0,                                          /* tp_setattr */
1593
    0,                                          /* tp_as_async */
1594
    cm_repr,                                    /* tp_repr */
1595
    0,                                          /* tp_as_number */
1596
    0,                                          /* tp_as_sequence */
1597
    0,                                          /* tp_as_mapping */
1598
    0,                                          /* tp_hash */
1599
    0,                                          /* tp_call */
1600
    0,                                          /* tp_str */
1601
    0,                                          /* tp_getattro */
1602
    0,                                          /* tp_setattro */
1603
    0,                                          /* tp_as_buffer */
1604
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1605
    classmethod_doc,                            /* tp_doc */
1606
    cm_traverse,                                /* tp_traverse */
1607
    cm_clear,                                   /* tp_clear */
1608
    0,                                          /* tp_richcompare */
1609
    0,                                          /* tp_weaklistoffset */
1610
    0,                                          /* tp_iter */
1611
    0,                                          /* tp_iternext */
1612
    cm_methodlist,                              /* tp_methods */
1613
    cm_memberlist,                              /* tp_members */
1614
    cm_getsetlist,                              /* tp_getset */
1615
    0,                                          /* tp_base */
1616
    0,                                          /* tp_dict */
1617
    cm_descr_get,                               /* tp_descr_get */
1618
    0,                                          /* tp_descr_set */
1619
    offsetof(classmethod, cm_dict),             /* tp_dictoffset */
1620
    cm_init,                                    /* tp_init */
1621
    PyType_GenericAlloc,                        /* tp_alloc */
1622
    PyType_GenericNew,                          /* tp_new */
1623
    PyObject_GC_Del,                            /* tp_free */
1624
};
1625
1626
PyObject *
1627
PyClassMethod_New(PyObject *callable)
1628
24
{
1629
24
    classmethod *cm = (classmethod *)
1630
24
        PyType_GenericAlloc(&PyClassMethod_Type, 0);
1631
24
    if (cm != NULL) {
1632
24
        cm->cm_callable = Py_NewRef(callable);
1633
24
    }
1634
24
    return (PyObject *)cm;
1635
24
}
1636
1637
1638
/* Static method object */
1639
1640
/* A static method does not receive an implicit first argument.
1641
   To declare a static method, use this idiom:
1642
1643
     class C:
1644
         @staticmethod
1645
         def f(arg1, arg2, argN):
1646
             ...
1647
1648
   It can be called either on the class (e.g. C.f()) or on an instance
1649
   (e.g. C().f()). Both the class and the instance are ignored, and
1650
   neither is passed implicitly as the first argument to the method.
1651
1652
   Static methods in Python are similar to those found in Java or C++.
1653
   For a more advanced concept, see class methods above.
1654
*/
1655
1656
typedef struct {
1657
    PyObject_HEAD
1658
    PyObject *sm_callable;
1659
    PyObject *sm_dict;
1660
} staticmethod;
1661
1662
#define _PyStaticMethod_CAST(cm) \
1663
233k
    (assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
1664
233k
     _Py_CAST(staticmethod*, cm))
1665
1666
static void
1667
sm_dealloc(PyObject *self)
1668
54
{
1669
54
    staticmethod *sm = _PyStaticMethod_CAST(self);
1670
54
    _PyObject_GC_UNTRACK((PyObject *)sm);
1671
54
    Py_XDECREF(sm->sm_callable);
1672
54
    Py_XDECREF(sm->sm_dict);
1673
54
    Py_TYPE(sm)->tp_free((PyObject *)sm);
1674
54
}
1675
1676
static int
1677
sm_traverse(PyObject *self, visitproc visit, void *arg)
1678
233k
{
1679
233k
    staticmethod *sm = _PyStaticMethod_CAST(self);
1680
233k
    Py_VISIT(sm->sm_callable);
1681
233k
    Py_VISIT(sm->sm_dict);
1682
233k
    return 0;
1683
233k
}
1684
1685
static int
1686
sm_clear(PyObject *self)
1687
0
{
1688
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1689
0
    Py_CLEAR(sm->sm_callable);
1690
0
    Py_CLEAR(sm->sm_dict);
1691
0
    return 0;
1692
0
}
1693
1694
static PyObject *
1695
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1696
12.8M
{
1697
12.8M
    staticmethod *sm = (staticmethod *)self;
1698
1699
12.8M
    if (sm->sm_callable == NULL) {
1700
0
        PyErr_SetString(PyExc_RuntimeError,
1701
0
                        "uninitialized staticmethod object");
1702
0
        return NULL;
1703
0
    }
1704
12.8M
    return Py_NewRef(sm->sm_callable);
1705
12.8M
}
1706
1707
static int
1708
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
1709
288
{
1710
288
    staticmethod *sm = (staticmethod *)self;
1711
288
    PyObject *callable;
1712
1713
288
    if (!_PyArg_NoKeywords("staticmethod", kwds))
1714
0
        return -1;
1715
288
    if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
1716
0
        return -1;
1717
288
    Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
1718
1719
288
    if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
1720
0
        return -1;
1721
0
    }
1722
288
    return 0;
1723
288
}
1724
1725
static PyObject*
1726
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
1727
0
{
1728
0
    staticmethod *sm = (staticmethod *)callable;
1729
0
    return PyObject_Call(sm->sm_callable, args, kwargs);
1730
0
}
1731
1732
static PyMemberDef sm_memberlist[] = {
1733
    {"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1734
    {"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
1735
    {NULL}  /* Sentinel */
1736
};
1737
1738
static PyObject *
1739
sm_get___isabstractmethod__(PyObject *self, void *closure)
1740
6
{
1741
6
    staticmethod *sm = _PyStaticMethod_CAST(self);
1742
6
    int res = _PyObject_IsAbstract(sm->sm_callable);
1743
6
    if (res == -1) {
1744
0
        return NULL;
1745
0
    }
1746
6
    else if (res) {
1747
0
        Py_RETURN_TRUE;
1748
0
    }
1749
6
    Py_RETURN_FALSE;
1750
6
}
1751
1752
static PyObject *
1753
sm_get___annotations__(PyObject *self, void *closure)
1754
0
{
1755
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1756
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__));
1757
0
}
1758
1759
static int
1760
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
1761
0
{
1762
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod");
1763
0
}
1764
1765
static PyObject *
1766
sm_get___annotate__(PyObject *self, void *closure)
1767
0
{
1768
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1769
0
    return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__));
1770
0
}
1771
1772
static int
1773
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
1774
0
{
1775
0
    return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod");
1776
0
}
1777
1778
static PyGetSetDef sm_getsetlist[] = {
1779
    {"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL},
1780
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
1781
    {"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL},
1782
    {"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL},
1783
    {NULL} /* Sentinel */
1784
};
1785
1786
static PyMethodDef sm_methodlist[] = {
1787
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
1788
    {NULL} /* Sentinel */
1789
};
1790
1791
static PyObject*
1792
sm_repr(PyObject *self)
1793
0
{
1794
0
    staticmethod *sm = _PyStaticMethod_CAST(self);
1795
0
    return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
1796
0
}
1797
1798
PyDoc_STRVAR(staticmethod_doc,
1799
"staticmethod(function, /)\n\
1800
--\n\
1801
\n\
1802
Convert a function to be a static method.\n\
1803
\n\
1804
A static method does not receive an implicit first argument.\n\
1805
To declare a static method, use this idiom:\n\
1806
\n\
1807
     class C:\n\
1808
         @staticmethod\n\
1809
         def f(arg1, arg2, argN):\n\
1810
             ...\n\
1811
\n\
1812
It can be called either on the class (e.g. C.f()) or on an instance\n\
1813
(e.g. C().f()). Both the class and the instance are ignored, and\n\
1814
neither is passed implicitly as the first argument to the method.\n\
1815
\n\
1816
Static methods in Python are similar to those found in Java or C++.\n\
1817
For a more advanced concept, see the classmethod builtin.");
1818
1819
PyTypeObject PyStaticMethod_Type = {
1820
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1821
    "staticmethod",
1822
    sizeof(staticmethod),
1823
    0,
1824
    sm_dealloc,                                 /* tp_dealloc */
1825
    0,                                          /* tp_vectorcall_offset */
1826
    0,                                          /* tp_getattr */
1827
    0,                                          /* tp_setattr */
1828
    0,                                          /* tp_as_async */
1829
    sm_repr,                                    /* tp_repr */
1830
    0,                                          /* tp_as_number */
1831
    0,                                          /* tp_as_sequence */
1832
    0,                                          /* tp_as_mapping */
1833
    0,                                          /* tp_hash */
1834
    sm_call,                                    /* tp_call */
1835
    0,                                          /* tp_str */
1836
    0,                                          /* tp_getattro */
1837
    0,                                          /* tp_setattro */
1838
    0,                                          /* tp_as_buffer */
1839
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1840
    staticmethod_doc,                           /* tp_doc */
1841
    sm_traverse,                                /* tp_traverse */
1842
    sm_clear,                                   /* tp_clear */
1843
    0,                                          /* tp_richcompare */
1844
    0,                                          /* tp_weaklistoffset */
1845
    0,                                          /* tp_iter */
1846
    0,                                          /* tp_iternext */
1847
    sm_methodlist,                              /* tp_methods */
1848
    sm_memberlist,                              /* tp_members */
1849
    sm_getsetlist,                              /* tp_getset */
1850
    0,                                          /* tp_base */
1851
    0,                                          /* tp_dict */
1852
    sm_descr_get,                               /* tp_descr_get */
1853
    0,                                          /* tp_descr_set */
1854
    offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
1855
    sm_init,                                    /* tp_init */
1856
    PyType_GenericAlloc,                        /* tp_alloc */
1857
    PyType_GenericNew,                          /* tp_new */
1858
    PyObject_GC_Del,                            /* tp_free */
1859
};
1860
1861
PyObject *
1862
PyStaticMethod_New(PyObject *callable)
1863
332
{
1864
332
    staticmethod *sm = (staticmethod *)
1865
332
        PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1866
332
    if (sm != NULL) {
1867
332
        sm->sm_callable = Py_NewRef(callable);
1868
332
    }
1869
332
    return (PyObject *)sm;
1870
332
}