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