1 
2 /* Function object implementation */
3 
4 #include "Python.h"
5 #include "pycore_object.h"
6 #include "pycore_pymem.h"
7 #include "pycore_pystate.h"
8 #include "pycore_tupleobject.h"
9 #include "code.h"
10 #include "structmember.h"
11 
12 PyObject *
PyFunction_NewWithQualName(PyObject * code,PyObject * globals,PyObject * qualname)13 PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
14 {
15     PyFunctionObject *op;
16     PyObject *doc, *consts, *module;
17     static PyObject *__name__ = NULL;
18 
19     if (__name__ == NULL) {
20         __name__ = PyUnicode_InternFromString("__name__");
21         if (__name__ == NULL)
22             return NULL;
23     }
24 
25     /* __module__: If module name is in globals, use it.
26        Otherwise, use None. */
27     module = PyDict_GetItemWithError(globals, __name__);
28     if (module) {
29         Py_INCREF(module);
30     }
31     else if (PyErr_Occurred()) {
32         return NULL;
33     }
34 
35     op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
36     if (op == NULL) {
37         Py_XDECREF(module);
38         return NULL;
39     }
40     /* Note: No failures from this point on, since func_dealloc() does not
41        expect a partially-created object. */
42 
43     op->func_weakreflist = NULL;
44     Py_INCREF(code);
45     op->func_code = code;
46     Py_INCREF(globals);
47     op->func_globals = globals;
48     op->func_name = ((PyCodeObject *)code)->co_name;
49     Py_INCREF(op->func_name);
50     op->func_defaults = NULL; /* No default arguments */
51     op->func_kwdefaults = NULL; /* No keyword only defaults */
52     op->func_closure = NULL;
53     op->vectorcall = _PyFunction_Vectorcall;
54     op->func_module = module;
55 
56     consts = ((PyCodeObject *)code)->co_consts;
57     if (PyTuple_Size(consts) >= 1) {
58         doc = PyTuple_GetItem(consts, 0);
59         if (!PyUnicode_Check(doc))
60             doc = Py_None;
61     }
62     else
63         doc = Py_None;
64     Py_INCREF(doc);
65     op->func_doc = doc;
66 
67     op->func_dict = NULL;
68     op->func_annotations = NULL;
69 
70     if (qualname)
71         op->func_qualname = qualname;
72     else
73         op->func_qualname = op->func_name;
74     Py_INCREF(op->func_qualname);
75 
76     _PyObject_GC_TRACK(op);
77     return (PyObject *)op;
78 }
79 
80 PyObject *
PyFunction_New(PyObject * code,PyObject * globals)81 PyFunction_New(PyObject *code, PyObject *globals)
82 {
83     return PyFunction_NewWithQualName(code, globals, NULL);
84 }
85 
86 PyObject *
PyFunction_GetCode(PyObject * op)87 PyFunction_GetCode(PyObject *op)
88 {
89     if (!PyFunction_Check(op)) {
90         PyErr_BadInternalCall();
91         return NULL;
92     }
93     return ((PyFunctionObject *) op) -> func_code;
94 }
95 
96 PyObject *
PyFunction_GetGlobals(PyObject * op)97 PyFunction_GetGlobals(PyObject *op)
98 {
99     if (!PyFunction_Check(op)) {
100         PyErr_BadInternalCall();
101         return NULL;
102     }
103     return ((PyFunctionObject *) op) -> func_globals;
104 }
105 
106 PyObject *
PyFunction_GetModule(PyObject * op)107 PyFunction_GetModule(PyObject *op)
108 {
109     if (!PyFunction_Check(op)) {
110         PyErr_BadInternalCall();
111         return NULL;
112     }
113     return ((PyFunctionObject *) op) -> func_module;
114 }
115 
116 PyObject *
PyFunction_GetDefaults(PyObject * op)117 PyFunction_GetDefaults(PyObject *op)
118 {
119     if (!PyFunction_Check(op)) {
120         PyErr_BadInternalCall();
121         return NULL;
122     }
123     return ((PyFunctionObject *) op) -> func_defaults;
124 }
125 
126 int
PyFunction_SetDefaults(PyObject * op,PyObject * defaults)127 PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
128 {
129     if (!PyFunction_Check(op)) {
130         PyErr_BadInternalCall();
131         return -1;
132     }
133     if (defaults == Py_None)
134         defaults = NULL;
135     else if (defaults && PyTuple_Check(defaults)) {
136         Py_INCREF(defaults);
137     }
138     else {
139         PyErr_SetString(PyExc_SystemError, "non-tuple default args");
140         return -1;
141     }
142     Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
143     return 0;
144 }
145 
146 PyObject *
PyFunction_GetKwDefaults(PyObject * op)147 PyFunction_GetKwDefaults(PyObject *op)
148 {
149     if (!PyFunction_Check(op)) {
150         PyErr_BadInternalCall();
151         return NULL;
152     }
153     return ((PyFunctionObject *) op) -> func_kwdefaults;
154 }
155 
156 int
PyFunction_SetKwDefaults(PyObject * op,PyObject * defaults)157 PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
158 {
159     if (!PyFunction_Check(op)) {
160         PyErr_BadInternalCall();
161         return -1;
162     }
163     if (defaults == Py_None)
164         defaults = NULL;
165     else if (defaults && PyDict_Check(defaults)) {
166         Py_INCREF(defaults);
167     }
168     else {
169         PyErr_SetString(PyExc_SystemError,
170                         "non-dict keyword only default args");
171         return -1;
172     }
173     Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
174     return 0;
175 }
176 
177 PyObject *
PyFunction_GetClosure(PyObject * op)178 PyFunction_GetClosure(PyObject *op)
179 {
180     if (!PyFunction_Check(op)) {
181         PyErr_BadInternalCall();
182         return NULL;
183     }
184     return ((PyFunctionObject *) op) -> func_closure;
185 }
186 
187 int
PyFunction_SetClosure(PyObject * op,PyObject * closure)188 PyFunction_SetClosure(PyObject *op, PyObject *closure)
189 {
190     if (!PyFunction_Check(op)) {
191         PyErr_BadInternalCall();
192         return -1;
193     }
194     if (closure == Py_None)
195         closure = NULL;
196     else if (PyTuple_Check(closure)) {
197         Py_INCREF(closure);
198     }
199     else {
200         PyErr_Format(PyExc_SystemError,
201                      "expected tuple for closure, got '%.100s'",
202                      closure->ob_type->tp_name);
203         return -1;
204     }
205     Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
206     return 0;
207 }
208 
209 PyObject *
PyFunction_GetAnnotations(PyObject * op)210 PyFunction_GetAnnotations(PyObject *op)
211 {
212     if (!PyFunction_Check(op)) {
213         PyErr_BadInternalCall();
214         return NULL;
215     }
216     return ((PyFunctionObject *) op) -> func_annotations;
217 }
218 
219 int
PyFunction_SetAnnotations(PyObject * op,PyObject * annotations)220 PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
221 {
222     if (!PyFunction_Check(op)) {
223         PyErr_BadInternalCall();
224         return -1;
225     }
226     if (annotations == Py_None)
227         annotations = NULL;
228     else if (annotations && PyDict_Check(annotations)) {
229         Py_INCREF(annotations);
230     }
231     else {
232         PyErr_SetString(PyExc_SystemError,
233                         "non-dict annotations");
234         return -1;
235     }
236     Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
237     return 0;
238 }
239 
240 /* Methods */
241 
242 #define OFF(x) offsetof(PyFunctionObject, x)
243 
244 static PyMemberDef func_memberlist[] = {
245     {"__closure__",   T_OBJECT,     OFF(func_closure),
246      RESTRICTED|READONLY},
247     {"__doc__",       T_OBJECT,     OFF(func_doc), PY_WRITE_RESTRICTED},
248     {"__globals__",   T_OBJECT,     OFF(func_globals),
249      RESTRICTED|READONLY},
250     {"__module__",    T_OBJECT,     OFF(func_module), PY_WRITE_RESTRICTED},
251     {NULL}  /* Sentinel */
252 };
253 
254 static PyObject *
func_get_code(PyFunctionObject * op,void * Py_UNUSED (ignored))255 func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored))
256 {
257     if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
258         return NULL;
259     }
260 
261     Py_INCREF(op->func_code);
262     return op->func_code;
263 }
264 
265 static int
func_set_code(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))266 func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
267 {
268     Py_ssize_t nfree, nclosure;
269 
270     /* Not legal to del f.func_code or to set it to anything
271      * other than a code object. */
272     if (value == NULL || !PyCode_Check(value)) {
273         PyErr_SetString(PyExc_TypeError,
274                         "__code__ must be set to a code object");
275         return -1;
276     }
277 
278     if (PySys_Audit("object.__setattr__", "OsO",
279                     op, "__code__", value) < 0) {
280         return -1;
281     }
282 
283     nfree = PyCode_GetNumFree((PyCodeObject *)value);
284     nclosure = (op->func_closure == NULL ? 0 :
285             PyTuple_GET_SIZE(op->func_closure));
286     if (nclosure != nfree) {
287         PyErr_Format(PyExc_ValueError,
288                      "%U() requires a code object with %zd free vars,"
289                      " not %zd",
290                      op->func_name,
291                      nclosure, nfree);
292         return -1;
293     }
294     Py_INCREF(value);
295     Py_XSETREF(op->func_code, value);
296     return 0;
297 }
298 
299 static PyObject *
func_get_name(PyFunctionObject * op,void * Py_UNUSED (ignored))300 func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored))
301 {
302     Py_INCREF(op->func_name);
303     return op->func_name;
304 }
305 
306 static int
func_set_name(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))307 func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
308 {
309     /* Not legal to del f.func_name or to set it to anything
310      * other than a string object. */
311     if (value == NULL || !PyUnicode_Check(value)) {
312         PyErr_SetString(PyExc_TypeError,
313                         "__name__ must be set to a string object");
314         return -1;
315     }
316     Py_INCREF(value);
317     Py_XSETREF(op->func_name, value);
318     return 0;
319 }
320 
321 static PyObject *
func_get_qualname(PyFunctionObject * op,void * Py_UNUSED (ignored))322 func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored))
323 {
324     Py_INCREF(op->func_qualname);
325     return op->func_qualname;
326 }
327 
328 static int
func_set_qualname(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))329 func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
330 {
331     /* Not legal to del f.__qualname__ or to set it to anything
332      * other than a string object. */
333     if (value == NULL || !PyUnicode_Check(value)) {
334         PyErr_SetString(PyExc_TypeError,
335                         "__qualname__ must be set to a string object");
336         return -1;
337     }
338     Py_INCREF(value);
339     Py_XSETREF(op->func_qualname, value);
340     return 0;
341 }
342 
343 static PyObject *
func_get_defaults(PyFunctionObject * op,void * Py_UNUSED (ignored))344 func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
345 {
346     if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
347         return NULL;
348     }
349     if (op->func_defaults == NULL) {
350         Py_RETURN_NONE;
351     }
352     Py_INCREF(op->func_defaults);
353     return op->func_defaults;
354 }
355 
356 static int
func_set_defaults(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))357 func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
358 {
359     /* Legal to del f.func_defaults.
360      * Can only set func_defaults to NULL or a tuple. */
361     if (value == Py_None)
362         value = NULL;
363     if (value != NULL && !PyTuple_Check(value)) {
364         PyErr_SetString(PyExc_TypeError,
365                         "__defaults__ must be set to a tuple object");
366         return -1;
367     }
368     if (value) {
369         if (PySys_Audit("object.__setattr__", "OsO",
370                         op, "__defaults__", value) < 0) {
371             return -1;
372         }
373     } else if (PySys_Audit("object.__delattr__", "Os",
374                            op, "__defaults__") < 0) {
375         return -1;
376     }
377 
378     Py_XINCREF(value);
379     Py_XSETREF(op->func_defaults, value);
380     return 0;
381 }
382 
383 static PyObject *
func_get_kwdefaults(PyFunctionObject * op,void * Py_UNUSED (ignored))384 func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored))
385 {
386     if (PySys_Audit("object.__getattr__", "Os",
387                     op, "__kwdefaults__") < 0) {
388         return NULL;
389     }
390     if (op->func_kwdefaults == NULL) {
391         Py_RETURN_NONE;
392     }
393     Py_INCREF(op->func_kwdefaults);
394     return op->func_kwdefaults;
395 }
396 
397 static int
func_set_kwdefaults(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))398 func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
399 {
400     if (value == Py_None)
401         value = NULL;
402     /* Legal to del f.func_kwdefaults.
403      * Can only set func_kwdefaults to NULL or a dict. */
404     if (value != NULL && !PyDict_Check(value)) {
405         PyErr_SetString(PyExc_TypeError,
406             "__kwdefaults__ must be set to a dict object");
407         return -1;
408     }
409     if (value) {
410         if (PySys_Audit("object.__setattr__", "OsO",
411                         op, "__kwdefaults__", value) < 0) {
412             return -1;
413         }
414     } else if (PySys_Audit("object.__delattr__", "Os",
415                            op, "__kwdefaults__") < 0) {
416         return -1;
417     }
418 
419     Py_XINCREF(value);
420     Py_XSETREF(op->func_kwdefaults, value);
421     return 0;
422 }
423 
424 static PyObject *
func_get_annotations(PyFunctionObject * op,void * Py_UNUSED (ignored))425 func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored))
426 {
427     if (op->func_annotations == NULL) {
428         op->func_annotations = PyDict_New();
429         if (op->func_annotations == NULL)
430             return NULL;
431     }
432     Py_INCREF(op->func_annotations);
433     return op->func_annotations;
434 }
435 
436 static int
func_set_annotations(PyFunctionObject * op,PyObject * value,void * Py_UNUSED (ignored))437 func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored))
438 {
439     if (value == Py_None)
440         value = NULL;
441     /* Legal to del f.func_annotations.
442      * Can only set func_annotations to NULL (through C api)
443      * or a dict. */
444     if (value != NULL && !PyDict_Check(value)) {
445         PyErr_SetString(PyExc_TypeError,
446             "__annotations__ must be set to a dict object");
447         return -1;
448     }
449     Py_XINCREF(value);
450     Py_XSETREF(op->func_annotations, value);
451     return 0;
452 }
453 
454 static PyGetSetDef func_getsetlist[] = {
455     {"__code__", (getter)func_get_code, (setter)func_set_code},
456     {"__defaults__", (getter)func_get_defaults,
457      (setter)func_set_defaults},
458     {"__kwdefaults__", (getter)func_get_kwdefaults,
459      (setter)func_set_kwdefaults},
460     {"__annotations__", (getter)func_get_annotations,
461      (setter)func_set_annotations},
462     {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
463     {"__name__", (getter)func_get_name, (setter)func_set_name},
464     {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname},
465     {NULL} /* Sentinel */
466 };
467 
468 /*[clinic input]
469 class function "PyFunctionObject *" "&PyFunction_Type"
470 [clinic start generated code]*/
471 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
472 
473 #include "clinic/funcobject.c.h"
474 
475 /* function.__new__() maintains the following invariants for closures.
476    The closure must correspond to the free variables of the code object.
477 
478    if len(code.co_freevars) == 0:
479        closure = NULL
480    else:
481        len(closure) == len(code.co_freevars)
482    for every elt in closure, type(elt) == cell
483 */
484 
485 /*[clinic input]
486 @classmethod
487 function.__new__ as func_new
488     code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
489         a code object
490     globals: object(subclass_of="&PyDict_Type")
491         the globals dictionary
492     name: object = None
493         a string that overrides the name from the code object
494     argdefs as defaults: object = None
495         a tuple that specifies the default argument values
496     closure: object = None
497         a tuple that supplies the bindings for free variables
498 
499 Create a function object.
500 [clinic start generated code]*/
501 
502 static PyObject *
func_new_impl(PyTypeObject * type,PyCodeObject * code,PyObject * globals,PyObject * name,PyObject * defaults,PyObject * closure)503 func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
504               PyObject *name, PyObject *defaults, PyObject *closure)
505 /*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/
506 {
507     PyFunctionObject *newfunc;
508     Py_ssize_t nfree, nclosure;
509 
510     if (name != Py_None && !PyUnicode_Check(name)) {
511         PyErr_SetString(PyExc_TypeError,
512                         "arg 3 (name) must be None or string");
513         return NULL;
514     }
515     if (defaults != Py_None && !PyTuple_Check(defaults)) {
516         PyErr_SetString(PyExc_TypeError,
517                         "arg 4 (defaults) must be None or tuple");
518         return NULL;
519     }
520     nfree = PyTuple_GET_SIZE(code->co_freevars);
521     if (!PyTuple_Check(closure)) {
522         if (nfree && closure == Py_None) {
523             PyErr_SetString(PyExc_TypeError,
524                             "arg 5 (closure) must be tuple");
525             return NULL;
526         }
527         else if (closure != Py_None) {
528             PyErr_SetString(PyExc_TypeError,
529                 "arg 5 (closure) must be None or tuple");
530             return NULL;
531         }
532     }
533 
534     /* check that the closure is well-formed */
535     nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
536     if (nfree != nclosure)
537         return PyErr_Format(PyExc_ValueError,
538                             "%U requires closure of length %zd, not %zd",
539                             code->co_name, nfree, nclosure);
540     if (nclosure) {
541         Py_ssize_t i;
542         for (i = 0; i < nclosure; i++) {
543             PyObject *o = PyTuple_GET_ITEM(closure, i);
544             if (!PyCell_Check(o)) {
545                 return PyErr_Format(PyExc_TypeError,
546                     "arg 5 (closure) expected cell, found %s",
547                                     o->ob_type->tp_name);
548             }
549         }
550     }
551     if (PySys_Audit("function.__new__", "O", code) < 0) {
552         return NULL;
553     }
554 
555     newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
556                                                  globals);
557     if (newfunc == NULL)
558         return NULL;
559 
560     if (name != Py_None) {
561         Py_INCREF(name);
562         Py_SETREF(newfunc->func_name, name);
563     }
564     if (defaults != Py_None) {
565         Py_INCREF(defaults);
566         newfunc->func_defaults  = defaults;
567     }
568     if (closure != Py_None) {
569         Py_INCREF(closure);
570         newfunc->func_closure = closure;
571     }
572 
573     return (PyObject *)newfunc;
574 }
575 
576 static int
func_clear(PyFunctionObject * op)577 func_clear(PyFunctionObject *op)
578 {
579     Py_CLEAR(op->func_code);
580     Py_CLEAR(op->func_globals);
581     Py_CLEAR(op->func_module);
582     Py_CLEAR(op->func_name);
583     Py_CLEAR(op->func_defaults);
584     Py_CLEAR(op->func_kwdefaults);
585     Py_CLEAR(op->func_doc);
586     Py_CLEAR(op->func_dict);
587     Py_CLEAR(op->func_closure);
588     Py_CLEAR(op->func_annotations);
589     Py_CLEAR(op->func_qualname);
590     return 0;
591 }
592 
593 static void
func_dealloc(PyFunctionObject * op)594 func_dealloc(PyFunctionObject *op)
595 {
596     _PyObject_GC_UNTRACK(op);
597     if (op->func_weakreflist != NULL) {
598         PyObject_ClearWeakRefs((PyObject *) op);
599     }
600     (void)func_clear(op);
601     PyObject_GC_Del(op);
602 }
603 
604 static PyObject*
func_repr(PyFunctionObject * op)605 func_repr(PyFunctionObject *op)
606 {
607     return PyUnicode_FromFormat("<function %U at %p>",
608                                op->func_qualname, op);
609 }
610 
611 static int
func_traverse(PyFunctionObject * f,visitproc visit,void * arg)612 func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
613 {
614     Py_VISIT(f->func_code);
615     Py_VISIT(f->func_globals);
616     Py_VISIT(f->func_module);
617     Py_VISIT(f->func_defaults);
618     Py_VISIT(f->func_kwdefaults);
619     Py_VISIT(f->func_doc);
620     Py_VISIT(f->func_name);
621     Py_VISIT(f->func_dict);
622     Py_VISIT(f->func_closure);
623     Py_VISIT(f->func_annotations);
624     Py_VISIT(f->func_qualname);
625     return 0;
626 }
627 
628 static PyObject *
function_call(PyObject * func,PyObject * args,PyObject * kwargs)629 function_call(PyObject *func, PyObject *args, PyObject *kwargs)
630 {
631     PyObject **stack;
632     Py_ssize_t nargs;
633 
634     stack = _PyTuple_ITEMS(args);
635     nargs = PyTuple_GET_SIZE(args);
636     return _PyFunction_FastCallDict(func, stack, nargs, kwargs);
637 }
638 
639 /* Bind a function to an object */
640 static PyObject *
func_descr_get(PyObject * func,PyObject * obj,PyObject * type)641 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
642 {
643     if (obj == Py_None || obj == NULL) {
644         Py_INCREF(func);
645         return func;
646     }
647     return PyMethod_New(func, obj);
648 }
649 
650 PyTypeObject PyFunction_Type = {
651     PyVarObject_HEAD_INIT(&PyType_Type, 0)
652     "function",
653     sizeof(PyFunctionObject),
654     0,
655     (destructor)func_dealloc,                   /* tp_dealloc */
656     offsetof(PyFunctionObject, vectorcall),     /* tp_vectorcall_offset */
657     0,                                          /* tp_getattr */
658     0,                                          /* tp_setattr */
659     0,                                          /* tp_as_async */
660     (reprfunc)func_repr,                        /* tp_repr */
661     0,                                          /* tp_as_number */
662     0,                                          /* tp_as_sequence */
663     0,                                          /* tp_as_mapping */
664     0,                                          /* tp_hash */
665     function_call,                              /* tp_call */
666     0,                                          /* tp_str */
667     0,                                          /* tp_getattro */
668     0,                                          /* tp_setattro */
669     0,                                          /* tp_as_buffer */
670     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
671     _Py_TPFLAGS_HAVE_VECTORCALL |
672     Py_TPFLAGS_METHOD_DESCRIPTOR,               /* tp_flags */
673     func_new__doc__,                            /* tp_doc */
674     (traverseproc)func_traverse,                /* tp_traverse */
675     (inquiry)func_clear,                        /* tp_clear */
676     0,                                          /* tp_richcompare */
677     offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
678     0,                                          /* tp_iter */
679     0,                                          /* tp_iternext */
680     0,                                          /* tp_methods */
681     func_memberlist,                            /* tp_members */
682     func_getsetlist,                            /* tp_getset */
683     0,                                          /* tp_base */
684     0,                                          /* tp_dict */
685     func_descr_get,                             /* tp_descr_get */
686     0,                                          /* tp_descr_set */
687     offsetof(PyFunctionObject, func_dict),      /* tp_dictoffset */
688     0,                                          /* tp_init */
689     0,                                          /* tp_alloc */
690     func_new,                                   /* tp_new */
691 };
692 
693 
694 /* Class method object */
695 
696 /* A class method receives the class as implicit first argument,
697    just like an instance method receives the instance.
698    To declare a class method, use this idiom:
699 
700      class C:
701          @classmethod
702          def f(cls, arg1, arg2, ...):
703              ...
704 
705    It can be called either on the class (e.g. C.f()) or on an instance
706    (e.g. C().f()); the instance is ignored except for its class.
707    If a class method is called for a derived class, the derived class
708    object is passed as the implied first argument.
709 
710    Class methods are different than C++ or Java static methods.
711    If you want those, see static methods below.
712 */
713 
714 typedef struct {
715     PyObject_HEAD
716     PyObject *cm_callable;
717     PyObject *cm_dict;
718 } classmethod;
719 
720 static void
cm_dealloc(classmethod * cm)721 cm_dealloc(classmethod *cm)
722 {
723     _PyObject_GC_UNTRACK((PyObject *)cm);
724     Py_XDECREF(cm->cm_callable);
725     Py_XDECREF(cm->cm_dict);
726     Py_TYPE(cm)->tp_free((PyObject *)cm);
727 }
728 
729 static int
cm_traverse(classmethod * cm,visitproc visit,void * arg)730 cm_traverse(classmethod *cm, visitproc visit, void *arg)
731 {
732     Py_VISIT(cm->cm_callable);
733     Py_VISIT(cm->cm_dict);
734     return 0;
735 }
736 
737 static int
cm_clear(classmethod * cm)738 cm_clear(classmethod *cm)
739 {
740     Py_CLEAR(cm->cm_callable);
741     Py_CLEAR(cm->cm_dict);
742     return 0;
743 }
744 
745 
746 static PyObject *
cm_descr_get(PyObject * self,PyObject * obj,PyObject * type)747 cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
748 {
749     classmethod *cm = (classmethod *)self;
750 
751     if (cm->cm_callable == NULL) {
752         PyErr_SetString(PyExc_RuntimeError,
753                         "uninitialized classmethod object");
754         return NULL;
755     }
756     if (type == NULL)
757         type = (PyObject *)(Py_TYPE(obj));
758     return PyMethod_New(cm->cm_callable, type);
759 }
760 
761 static int
cm_init(PyObject * self,PyObject * args,PyObject * kwds)762 cm_init(PyObject *self, PyObject *args, PyObject *kwds)
763 {
764     classmethod *cm = (classmethod *)self;
765     PyObject *callable;
766 
767     if (!_PyArg_NoKeywords("classmethod", kwds))
768         return -1;
769     if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
770         return -1;
771     Py_INCREF(callable);
772     Py_XSETREF(cm->cm_callable, callable);
773     return 0;
774 }
775 
776 static PyMemberDef cm_memberlist[] = {
777     {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
778     {NULL}  /* Sentinel */
779 };
780 
781 static PyObject *
cm_get___isabstractmethod__(classmethod * cm,void * closure)782 cm_get___isabstractmethod__(classmethod *cm, void *closure)
783 {
784     int res = _PyObject_IsAbstract(cm->cm_callable);
785     if (res == -1) {
786         return NULL;
787     }
788     else if (res) {
789         Py_RETURN_TRUE;
790     }
791     Py_RETURN_FALSE;
792 }
793 
794 static PyGetSetDef cm_getsetlist[] = {
795     {"__isabstractmethod__",
796      (getter)cm_get___isabstractmethod__, NULL,
797      NULL,
798      NULL},
799     {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
800     {NULL} /* Sentinel */
801 };
802 
803 PyDoc_STRVAR(classmethod_doc,
804 "classmethod(function) -> method\n\
805 \n\
806 Convert a function to be a class method.\n\
807 \n\
808 A class method receives the class as implicit first argument,\n\
809 just like an instance method receives the instance.\n\
810 To declare a class method, use this idiom:\n\
811 \n\
812   class C:\n\
813       @classmethod\n\
814       def f(cls, arg1, arg2, ...):\n\
815           ...\n\
816 \n\
817 It can be called either on the class (e.g. C.f()) or on an instance\n\
818 (e.g. C().f()).  The instance is ignored except for its class.\n\
819 If a class method is called for a derived class, the derived class\n\
820 object is passed as the implied first argument.\n\
821 \n\
822 Class methods are different than C++ or Java static methods.\n\
823 If you want those, see the staticmethod builtin.");
824 
825 PyTypeObject PyClassMethod_Type = {
826     PyVarObject_HEAD_INIT(&PyType_Type, 0)
827     "classmethod",
828     sizeof(classmethod),
829     0,
830     (destructor)cm_dealloc,                     /* tp_dealloc */
831     0,                                          /* tp_vectorcall_offset */
832     0,                                          /* tp_getattr */
833     0,                                          /* tp_setattr */
834     0,                                          /* tp_as_async */
835     0,                                          /* tp_repr */
836     0,                                          /* tp_as_number */
837     0,                                          /* tp_as_sequence */
838     0,                                          /* tp_as_mapping */
839     0,                                          /* tp_hash */
840     0,                                          /* tp_call */
841     0,                                          /* tp_str */
842     0,                                          /* tp_getattro */
843     0,                                          /* tp_setattro */
844     0,                                          /* tp_as_buffer */
845     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
846     classmethod_doc,                            /* tp_doc */
847     (traverseproc)cm_traverse,                  /* tp_traverse */
848     (inquiry)cm_clear,                          /* tp_clear */
849     0,                                          /* tp_richcompare */
850     0,                                          /* tp_weaklistoffset */
851     0,                                          /* tp_iter */
852     0,                                          /* tp_iternext */
853     0,                                          /* tp_methods */
854     cm_memberlist,              /* tp_members */
855     cm_getsetlist,                              /* tp_getset */
856     0,                                          /* tp_base */
857     0,                                          /* tp_dict */
858     cm_descr_get,                               /* tp_descr_get */
859     0,                                          /* tp_descr_set */
860     offsetof(classmethod, cm_dict),             /* tp_dictoffset */
861     cm_init,                                    /* tp_init */
862     PyType_GenericAlloc,                        /* tp_alloc */
863     PyType_GenericNew,                          /* tp_new */
864     PyObject_GC_Del,                            /* tp_free */
865 };
866 
867 PyObject *
PyClassMethod_New(PyObject * callable)868 PyClassMethod_New(PyObject *callable)
869 {
870     classmethod *cm = (classmethod *)
871         PyType_GenericAlloc(&PyClassMethod_Type, 0);
872     if (cm != NULL) {
873         Py_INCREF(callable);
874         cm->cm_callable = callable;
875     }
876     return (PyObject *)cm;
877 }
878 
879 
880 /* Static method object */
881 
882 /* A static method does not receive an implicit first argument.
883    To declare a static method, use this idiom:
884 
885      class C:
886          @staticmethod
887          def f(arg1, arg2, ...):
888              ...
889 
890    It can be called either on the class (e.g. C.f()) or on an instance
891    (e.g. C().f()). Both the class and the instance are ignored, and
892    neither is passed implicitly as the first argument to the method.
893 
894    Static methods in Python are similar to those found in Java or C++.
895    For a more advanced concept, see class methods above.
896 */
897 
898 typedef struct {
899     PyObject_HEAD
900     PyObject *sm_callable;
901     PyObject *sm_dict;
902 } staticmethod;
903 
904 static void
sm_dealloc(staticmethod * sm)905 sm_dealloc(staticmethod *sm)
906 {
907     _PyObject_GC_UNTRACK((PyObject *)sm);
908     Py_XDECREF(sm->sm_callable);
909     Py_XDECREF(sm->sm_dict);
910     Py_TYPE(sm)->tp_free((PyObject *)sm);
911 }
912 
913 static int
sm_traverse(staticmethod * sm,visitproc visit,void * arg)914 sm_traverse(staticmethod *sm, visitproc visit, void *arg)
915 {
916     Py_VISIT(sm->sm_callable);
917     Py_VISIT(sm->sm_dict);
918     return 0;
919 }
920 
921 static int
sm_clear(staticmethod * sm)922 sm_clear(staticmethod *sm)
923 {
924     Py_CLEAR(sm->sm_callable);
925     Py_CLEAR(sm->sm_dict);
926     return 0;
927 }
928 
929 static PyObject *
sm_descr_get(PyObject * self,PyObject * obj,PyObject * type)930 sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
931 {
932     staticmethod *sm = (staticmethod *)self;
933 
934     if (sm->sm_callable == NULL) {
935         PyErr_SetString(PyExc_RuntimeError,
936                         "uninitialized staticmethod object");
937         return NULL;
938     }
939     Py_INCREF(sm->sm_callable);
940     return sm->sm_callable;
941 }
942 
943 static int
sm_init(PyObject * self,PyObject * args,PyObject * kwds)944 sm_init(PyObject *self, PyObject *args, PyObject *kwds)
945 {
946     staticmethod *sm = (staticmethod *)self;
947     PyObject *callable;
948 
949     if (!_PyArg_NoKeywords("staticmethod", kwds))
950         return -1;
951     if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
952         return -1;
953     Py_INCREF(callable);
954     Py_XSETREF(sm->sm_callable, callable);
955     return 0;
956 }
957 
958 static PyMemberDef sm_memberlist[] = {
959     {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
960     {NULL}  /* Sentinel */
961 };
962 
963 static PyObject *
sm_get___isabstractmethod__(staticmethod * sm,void * closure)964 sm_get___isabstractmethod__(staticmethod *sm, void *closure)
965 {
966     int res = _PyObject_IsAbstract(sm->sm_callable);
967     if (res == -1) {
968         return NULL;
969     }
970     else if (res) {
971         Py_RETURN_TRUE;
972     }
973     Py_RETURN_FALSE;
974 }
975 
976 static PyGetSetDef sm_getsetlist[] = {
977     {"__isabstractmethod__",
978      (getter)sm_get___isabstractmethod__, NULL,
979      NULL,
980      NULL},
981     {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
982     {NULL} /* Sentinel */
983 };
984 
985 PyDoc_STRVAR(staticmethod_doc,
986 "staticmethod(function) -> method\n\
987 \n\
988 Convert a function to be a static method.\n\
989 \n\
990 A static method does not receive an implicit first argument.\n\
991 To declare a static method, use this idiom:\n\
992 \n\
993      class C:\n\
994          @staticmethod\n\
995          def f(arg1, arg2, ...):\n\
996              ...\n\
997 \n\
998 It can be called either on the class (e.g. C.f()) or on an instance\n\
999 (e.g. C().f()). Both the class and the instance are ignored, and\n\
1000 neither is passed implicitly as the first argument to the method.\n\
1001 \n\
1002 Static methods in Python are similar to those found in Java or C++.\n\
1003 For a more advanced concept, see the classmethod builtin.");
1004 
1005 PyTypeObject PyStaticMethod_Type = {
1006     PyVarObject_HEAD_INIT(&PyType_Type, 0)
1007     "staticmethod",
1008     sizeof(staticmethod),
1009     0,
1010     (destructor)sm_dealloc,                     /* tp_dealloc */
1011     0,                                          /* tp_vectorcall_offset */
1012     0,                                          /* tp_getattr */
1013     0,                                          /* tp_setattr */
1014     0,                                          /* tp_as_async */
1015     0,                                          /* tp_repr */
1016     0,                                          /* tp_as_number */
1017     0,                                          /* tp_as_sequence */
1018     0,                                          /* tp_as_mapping */
1019     0,                                          /* tp_hash */
1020     0,                                          /* tp_call */
1021     0,                                          /* tp_str */
1022     0,                                          /* tp_getattro */
1023     0,                                          /* tp_setattro */
1024     0,                                          /* tp_as_buffer */
1025     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1026     staticmethod_doc,                           /* tp_doc */
1027     (traverseproc)sm_traverse,                  /* tp_traverse */
1028     (inquiry)sm_clear,                          /* tp_clear */
1029     0,                                          /* tp_richcompare */
1030     0,                                          /* tp_weaklistoffset */
1031     0,                                          /* tp_iter */
1032     0,                                          /* tp_iternext */
1033     0,                                          /* tp_methods */
1034     sm_memberlist,              /* tp_members */
1035     sm_getsetlist,                              /* tp_getset */
1036     0,                                          /* tp_base */
1037     0,                                          /* tp_dict */
1038     sm_descr_get,                               /* tp_descr_get */
1039     0,                                          /* tp_descr_set */
1040     offsetof(staticmethod, sm_dict),            /* tp_dictoffset */
1041     sm_init,                                    /* tp_init */
1042     PyType_GenericAlloc,                        /* tp_alloc */
1043     PyType_GenericNew,                          /* tp_new */
1044     PyObject_GC_Del,                            /* tp_free */
1045 };
1046 
1047 PyObject *
PyStaticMethod_New(PyObject * callable)1048 PyStaticMethod_New(PyObject *callable)
1049 {
1050     staticmethod *sm = (staticmethod *)
1051         PyType_GenericAlloc(&PyStaticMethod_Type, 0);
1052     if (sm != NULL) {
1053         Py_INCREF(callable);
1054         sm->sm_callable = callable;
1055     }
1056     return (PyObject *)sm;
1057 }
1058