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