1 /* Class object implementation (dead now except for methods) */
2
3 #include "Python.h"
4 #include "pycore_object.h"
5 #include "pycore_pymem.h"
6 #include "pycore_pystate.h"
7 #include "structmember.h"
8
9 #define TP_DESCR_GET(t) ((t)->tp_descr_get)
10
11 /* Free list for method objects to safe malloc/free overhead
12 * The im_self element is used to chain the elements.
13 */
14 static PyMethodObject *free_list;
15 static int numfree = 0;
16 #ifndef PyMethod_MAXFREELIST
17 #define PyMethod_MAXFREELIST 256
18 #endif
19
20 _Py_IDENTIFIER(__name__);
21 _Py_IDENTIFIER(__qualname__);
22
23 PyObject *
PyMethod_Function(PyObject * im)24 PyMethod_Function(PyObject *im)
25 {
26 if (!PyMethod_Check(im)) {
27 PyErr_BadInternalCall();
28 return NULL;
29 }
30 return ((PyMethodObject *)im)->im_func;
31 }
32
33 PyObject *
PyMethod_Self(PyObject * im)34 PyMethod_Self(PyObject *im)
35 {
36 if (!PyMethod_Check(im)) {
37 PyErr_BadInternalCall();
38 return NULL;
39 }
40 return ((PyMethodObject *)im)->im_self;
41 }
42
43
44 static PyObject *
method_vectorcall(PyObject * method,PyObject * const * args,size_t nargsf,PyObject * kwnames)45 method_vectorcall(PyObject *method, PyObject *const *args,
46 size_t nargsf, PyObject *kwnames)
47 {
48 assert(Py_TYPE(method) == &PyMethod_Type);
49 PyObject *self, *func, *result;
50 self = PyMethod_GET_SELF(method);
51 func = PyMethod_GET_FUNCTION(method);
52 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
53
54 if (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET) {
55 /* PY_VECTORCALL_ARGUMENTS_OFFSET is set, so we are allowed to mutate the vector */
56 PyObject **newargs = (PyObject**)args - 1;
57 nargs += 1;
58 PyObject *tmp = newargs[0];
59 newargs[0] = self;
60 result = _PyObject_Vectorcall(func, newargs, nargs, kwnames);
61 newargs[0] = tmp;
62 }
63 else {
64 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
65 Py_ssize_t totalargs = nargs + nkwargs;
66 if (totalargs == 0) {
67 return _PyObject_Vectorcall(func, &self, 1, NULL);
68 }
69
70 PyObject *newargs_stack[_PY_FASTCALL_SMALL_STACK];
71 PyObject **newargs;
72 if (totalargs <= (Py_ssize_t)Py_ARRAY_LENGTH(newargs_stack) - 1) {
73 newargs = newargs_stack;
74 }
75 else {
76 newargs = PyMem_Malloc((totalargs+1) * sizeof(PyObject *));
77 if (newargs == NULL) {
78 PyErr_NoMemory();
79 return NULL;
80 }
81 }
82 /* use borrowed references */
83 newargs[0] = self;
84 /* bpo-37138: since totalargs > 0, it's impossible that args is NULL.
85 * We need this, since calling memcpy() with a NULL pointer is
86 * undefined behaviour. */
87 assert(args != NULL);
88 memcpy(newargs + 1, args, totalargs * sizeof(PyObject *));
89 result = _PyObject_Vectorcall(func, newargs, nargs+1, kwnames);
90 if (newargs != newargs_stack) {
91 PyMem_Free(newargs);
92 }
93 }
94 return result;
95 }
96
97
98 /* Method objects are used for bound instance methods returned by
99 instancename.methodname. ClassName.methodname returns an ordinary
100 function.
101 */
102
103 PyObject *
PyMethod_New(PyObject * func,PyObject * self)104 PyMethod_New(PyObject *func, PyObject *self)
105 {
106 PyMethodObject *im;
107 if (self == NULL) {
108 PyErr_BadInternalCall();
109 return NULL;
110 }
111 im = free_list;
112 if (im != NULL) {
113 free_list = (PyMethodObject *)(im->im_self);
114 (void)PyObject_INIT(im, &PyMethod_Type);
115 numfree--;
116 }
117 else {
118 im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
119 if (im == NULL)
120 return NULL;
121 }
122 im->im_weakreflist = NULL;
123 Py_INCREF(func);
124 im->im_func = func;
125 Py_XINCREF(self);
126 im->im_self = self;
127 im->vectorcall = method_vectorcall;
128 _PyObject_GC_TRACK(im);
129 return (PyObject *)im;
130 }
131
132 static PyObject *
method_reduce(PyMethodObject * im,PyObject * Py_UNUSED (ignored))133 method_reduce(PyMethodObject *im, PyObject *Py_UNUSED(ignored))
134 {
135 PyObject *self = PyMethod_GET_SELF(im);
136 PyObject *func = PyMethod_GET_FUNCTION(im);
137 PyObject *funcname;
138 _Py_IDENTIFIER(getattr);
139
140 funcname = _PyObject_GetAttrId(func, &PyId___name__);
141 if (funcname == NULL) {
142 return NULL;
143 }
144 return Py_BuildValue("N(ON)", _PyEval_GetBuiltinId(&PyId_getattr),
145 self, funcname);
146 }
147
148 static PyMethodDef method_methods[] = {
149 {"__reduce__", (PyCFunction)method_reduce, METH_NOARGS, NULL},
150 {NULL, NULL}
151 };
152
153 /* Descriptors for PyMethod attributes */
154
155 /* im_func and im_self are stored in the PyMethod object */
156
157 #define MO_OFF(x) offsetof(PyMethodObject, x)
158
159 static PyMemberDef method_memberlist[] = {
160 {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED,
161 "the function (or other callable) implementing a method"},
162 {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED,
163 "the instance to which a method is bound"},
164 {NULL} /* Sentinel */
165 };
166
167 /* Christian Tismer argued convincingly that method attributes should
168 (nearly) always override function attributes.
169 The one exception is __doc__; there's a default __doc__ which
170 should only be used for the class, not for instances */
171
172 static PyObject *
method_get_doc(PyMethodObject * im,void * context)173 method_get_doc(PyMethodObject *im, void *context)
174 {
175 static PyObject *docstr;
176 if (docstr == NULL) {
177 docstr= PyUnicode_InternFromString("__doc__");
178 if (docstr == NULL)
179 return NULL;
180 }
181 return PyObject_GetAttr(im->im_func, docstr);
182 }
183
184 static PyGetSetDef method_getset[] = {
185 {"__doc__", (getter)method_get_doc, NULL, NULL},
186 {0}
187 };
188
189 static PyObject *
method_getattro(PyObject * obj,PyObject * name)190 method_getattro(PyObject *obj, PyObject *name)
191 {
192 PyMethodObject *im = (PyMethodObject *)obj;
193 PyTypeObject *tp = obj->ob_type;
194 PyObject *descr = NULL;
195
196 {
197 if (tp->tp_dict == NULL) {
198 if (PyType_Ready(tp) < 0)
199 return NULL;
200 }
201 descr = _PyType_Lookup(tp, name);
202 }
203
204 if (descr != NULL) {
205 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
206 if (f != NULL)
207 return f(descr, obj, (PyObject *)obj->ob_type);
208 else {
209 Py_INCREF(descr);
210 return descr;
211 }
212 }
213
214 return PyObject_GetAttr(im->im_func, name);
215 }
216
217 PyDoc_STRVAR(method_doc,
218 "method(function, instance)\n\
219 \n\
220 Create a bound instance method object.");
221
222 static PyObject *
method_new(PyTypeObject * type,PyObject * args,PyObject * kw)223 method_new(PyTypeObject* type, PyObject* args, PyObject *kw)
224 {
225 PyObject *func;
226 PyObject *self;
227
228 if (!_PyArg_NoKeywords("method", kw))
229 return NULL;
230 if (!PyArg_UnpackTuple(args, "method", 2, 2,
231 &func, &self))
232 return NULL;
233 if (!PyCallable_Check(func)) {
234 PyErr_SetString(PyExc_TypeError,
235 "first argument must be callable");
236 return NULL;
237 }
238 if (self == NULL || self == Py_None) {
239 PyErr_SetString(PyExc_TypeError,
240 "self must not be None");
241 return NULL;
242 }
243
244 return PyMethod_New(func, self);
245 }
246
247 static void
method_dealloc(PyMethodObject * im)248 method_dealloc(PyMethodObject *im)
249 {
250 _PyObject_GC_UNTRACK(im);
251 if (im->im_weakreflist != NULL)
252 PyObject_ClearWeakRefs((PyObject *)im);
253 Py_DECREF(im->im_func);
254 Py_XDECREF(im->im_self);
255 if (numfree < PyMethod_MAXFREELIST) {
256 im->im_self = (PyObject *)free_list;
257 free_list = im;
258 numfree++;
259 }
260 else {
261 PyObject_GC_Del(im);
262 }
263 }
264
265 static PyObject *
method_richcompare(PyObject * self,PyObject * other,int op)266 method_richcompare(PyObject *self, PyObject *other, int op)
267 {
268 PyMethodObject *a, *b;
269 PyObject *res;
270 int eq;
271
272 if ((op != Py_EQ && op != Py_NE) ||
273 !PyMethod_Check(self) ||
274 !PyMethod_Check(other))
275 {
276 Py_RETURN_NOTIMPLEMENTED;
277 }
278 a = (PyMethodObject *)self;
279 b = (PyMethodObject *)other;
280 eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ);
281 if (eq == 1) {
282 eq = (a->im_self == b->im_self);
283 }
284 else if (eq < 0)
285 return NULL;
286 if (op == Py_EQ)
287 res = eq ? Py_True : Py_False;
288 else
289 res = eq ? Py_False : Py_True;
290 Py_INCREF(res);
291 return res;
292 }
293
294 static PyObject *
method_repr(PyMethodObject * a)295 method_repr(PyMethodObject *a)
296 {
297 PyObject *self = a->im_self;
298 PyObject *func = a->im_func;
299 PyObject *funcname, *result;
300 const char *defname = "?";
301
302 if (_PyObject_LookupAttrId(func, &PyId___qualname__, &funcname) < 0 ||
303 (funcname == NULL &&
304 _PyObject_LookupAttrId(func, &PyId___name__, &funcname) < 0))
305 {
306 return NULL;
307 }
308
309 if (funcname != NULL && !PyUnicode_Check(funcname)) {
310 Py_DECREF(funcname);
311 funcname = NULL;
312 }
313
314 /* XXX Shouldn't use repr()/%R here! */
315 result = PyUnicode_FromFormat("<bound method %V of %R>",
316 funcname, defname, self);
317
318 Py_XDECREF(funcname);
319 return result;
320 }
321
322 static Py_hash_t
method_hash(PyMethodObject * a)323 method_hash(PyMethodObject *a)
324 {
325 Py_hash_t x, y;
326 x = _Py_HashPointer(a->im_self);
327 y = PyObject_Hash(a->im_func);
328 if (y == -1)
329 return -1;
330 x = x ^ y;
331 if (x == -1)
332 x = -2;
333 return x;
334 }
335
336 static int
method_traverse(PyMethodObject * im,visitproc visit,void * arg)337 method_traverse(PyMethodObject *im, visitproc visit, void *arg)
338 {
339 Py_VISIT(im->im_func);
340 Py_VISIT(im->im_self);
341 return 0;
342 }
343
344 static PyObject *
method_call(PyObject * method,PyObject * args,PyObject * kwargs)345 method_call(PyObject *method, PyObject *args, PyObject *kwargs)
346 {
347 PyObject *self, *func;
348
349 self = PyMethod_GET_SELF(method);
350 func = PyMethod_GET_FUNCTION(method);
351
352 return _PyObject_Call_Prepend(func, self, args, kwargs);
353 }
354
355 static PyObject *
method_descr_get(PyObject * meth,PyObject * obj,PyObject * cls)356 method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
357 {
358 Py_INCREF(meth);
359 return meth;
360 }
361
362 PyTypeObject PyMethod_Type = {
363 PyVarObject_HEAD_INIT(&PyType_Type, 0)
364 "method",
365 sizeof(PyMethodObject),
366 0,
367 (destructor)method_dealloc, /* tp_dealloc */
368 offsetof(PyMethodObject, vectorcall), /* tp_vectorcall_offset */
369 0, /* tp_getattr */
370 0, /* tp_setattr */
371 0, /* tp_as_async */
372 (reprfunc)method_repr, /* tp_repr */
373 0, /* tp_as_number */
374 0, /* tp_as_sequence */
375 0, /* tp_as_mapping */
376 (hashfunc)method_hash, /* tp_hash */
377 method_call, /* tp_call */
378 0, /* tp_str */
379 method_getattro, /* tp_getattro */
380 PyObject_GenericSetAttr, /* tp_setattro */
381 0, /* tp_as_buffer */
382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
383 _Py_TPFLAGS_HAVE_VECTORCALL, /* tp_flags */
384 method_doc, /* tp_doc */
385 (traverseproc)method_traverse, /* tp_traverse */
386 0, /* tp_clear */
387 method_richcompare, /* tp_richcompare */
388 offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
389 0, /* tp_iter */
390 0, /* tp_iternext */
391 method_methods, /* tp_methods */
392 method_memberlist, /* tp_members */
393 method_getset, /* tp_getset */
394 0, /* tp_base */
395 0, /* tp_dict */
396 method_descr_get, /* tp_descr_get */
397 0, /* tp_descr_set */
398 0, /* tp_dictoffset */
399 0, /* tp_init */
400 0, /* tp_alloc */
401 method_new, /* tp_new */
402 };
403
404 /* Clear out the free list */
405
406 int
PyMethod_ClearFreeList(void)407 PyMethod_ClearFreeList(void)
408 {
409 int freelist_size = numfree;
410
411 while (free_list) {
412 PyMethodObject *im = free_list;
413 free_list = (PyMethodObject *)(im->im_self);
414 PyObject_GC_Del(im);
415 numfree--;
416 }
417 assert(numfree == 0);
418 return freelist_size;
419 }
420
421 void
PyMethod_Fini(void)422 PyMethod_Fini(void)
423 {
424 (void)PyMethod_ClearFreeList();
425 }
426
427 /* Print summary info about the state of the optimized allocator */
428 void
_PyMethod_DebugMallocStats(FILE * out)429 _PyMethod_DebugMallocStats(FILE *out)
430 {
431 _PyDebugAllocatorStats(out,
432 "free PyMethodObject",
433 numfree, sizeof(PyMethodObject));
434 }
435
436 /* ------------------------------------------------------------------------
437 * instance method
438 */
439
440 PyObject *
PyInstanceMethod_New(PyObject * func)441 PyInstanceMethod_New(PyObject *func) {
442 PyInstanceMethodObject *method;
443 method = PyObject_GC_New(PyInstanceMethodObject,
444 &PyInstanceMethod_Type);
445 if (method == NULL) return NULL;
446 Py_INCREF(func);
447 method->func = func;
448 _PyObject_GC_TRACK(method);
449 return (PyObject *)method;
450 }
451
452 PyObject *
PyInstanceMethod_Function(PyObject * im)453 PyInstanceMethod_Function(PyObject *im)
454 {
455 if (!PyInstanceMethod_Check(im)) {
456 PyErr_BadInternalCall();
457 return NULL;
458 }
459 return PyInstanceMethod_GET_FUNCTION(im);
460 }
461
462 #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x)
463
464 static PyMemberDef instancemethod_memberlist[] = {
465 {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED,
466 "the function (or other callable) implementing a method"},
467 {NULL} /* Sentinel */
468 };
469
470 static PyObject *
instancemethod_get_doc(PyObject * self,void * context)471 instancemethod_get_doc(PyObject *self, void *context)
472 {
473 static PyObject *docstr;
474 if (docstr == NULL) {
475 docstr = PyUnicode_InternFromString("__doc__");
476 if (docstr == NULL)
477 return NULL;
478 }
479 return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr);
480 }
481
482 static PyGetSetDef instancemethod_getset[] = {
483 {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
484 {0}
485 };
486
487 static PyObject *
instancemethod_getattro(PyObject * self,PyObject * name)488 instancemethod_getattro(PyObject *self, PyObject *name)
489 {
490 PyTypeObject *tp = self->ob_type;
491 PyObject *descr = NULL;
492
493 if (tp->tp_dict == NULL) {
494 if (PyType_Ready(tp) < 0)
495 return NULL;
496 }
497 descr = _PyType_Lookup(tp, name);
498
499 if (descr != NULL) {
500 descrgetfunc f = TP_DESCR_GET(descr->ob_type);
501 if (f != NULL)
502 return f(descr, self, (PyObject *)self->ob_type);
503 else {
504 Py_INCREF(descr);
505 return descr;
506 }
507 }
508
509 return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name);
510 }
511
512 static void
instancemethod_dealloc(PyObject * self)513 instancemethod_dealloc(PyObject *self) {
514 _PyObject_GC_UNTRACK(self);
515 Py_DECREF(PyInstanceMethod_GET_FUNCTION(self));
516 PyObject_GC_Del(self);
517 }
518
519 static int
instancemethod_traverse(PyObject * self,visitproc visit,void * arg)520 instancemethod_traverse(PyObject *self, visitproc visit, void *arg) {
521 Py_VISIT(PyInstanceMethod_GET_FUNCTION(self));
522 return 0;
523 }
524
525 static PyObject *
instancemethod_call(PyObject * self,PyObject * arg,PyObject * kw)526 instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw)
527 {
528 return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw);
529 }
530
531 static PyObject *
instancemethod_descr_get(PyObject * descr,PyObject * obj,PyObject * type)532 instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) {
533 PyObject *func = PyInstanceMethod_GET_FUNCTION(descr);
534 if (obj == NULL) {
535 Py_INCREF(func);
536 return func;
537 }
538 else
539 return PyMethod_New(func, obj);
540 }
541
542 static PyObject *
instancemethod_richcompare(PyObject * self,PyObject * other,int op)543 instancemethod_richcompare(PyObject *self, PyObject *other, int op)
544 {
545 PyInstanceMethodObject *a, *b;
546 PyObject *res;
547 int eq;
548
549 if ((op != Py_EQ && op != Py_NE) ||
550 !PyInstanceMethod_Check(self) ||
551 !PyInstanceMethod_Check(other))
552 {
553 Py_RETURN_NOTIMPLEMENTED;
554 }
555 a = (PyInstanceMethodObject *)self;
556 b = (PyInstanceMethodObject *)other;
557 eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ);
558 if (eq < 0)
559 return NULL;
560 if (op == Py_EQ)
561 res = eq ? Py_True : Py_False;
562 else
563 res = eq ? Py_False : Py_True;
564 Py_INCREF(res);
565 return res;
566 }
567
568 static PyObject *
instancemethod_repr(PyObject * self)569 instancemethod_repr(PyObject *self)
570 {
571 PyObject *func = PyInstanceMethod_Function(self);
572 PyObject *funcname, *result;
573 const char *defname = "?";
574
575 if (func == NULL) {
576 PyErr_BadInternalCall();
577 return NULL;
578 }
579
580 if (_PyObject_LookupAttrId(func, &PyId___name__, &funcname) < 0) {
581 return NULL;
582 }
583 if (funcname != NULL && !PyUnicode_Check(funcname)) {
584 Py_DECREF(funcname);
585 funcname = NULL;
586 }
587
588 result = PyUnicode_FromFormat("<instancemethod %V at %p>",
589 funcname, defname, self);
590
591 Py_XDECREF(funcname);
592 return result;
593 }
594
595 /*
596 static long
597 instancemethod_hash(PyObject *self)
598 {
599 long x, y;
600 x = (long)self;
601 y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self));
602 if (y == -1)
603 return -1;
604 x = x ^ y;
605 if (x == -1)
606 x = -2;
607 return x;
608 }
609 */
610
611 PyDoc_STRVAR(instancemethod_doc,
612 "instancemethod(function)\n\
613 \n\
614 Bind a function to a class.");
615
616 static PyObject *
instancemethod_new(PyTypeObject * type,PyObject * args,PyObject * kw)617 instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
618 {
619 PyObject *func;
620
621 if (!_PyArg_NoKeywords("instancemethod", kw))
622 return NULL;
623 if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func))
624 return NULL;
625 if (!PyCallable_Check(func)) {
626 PyErr_SetString(PyExc_TypeError,
627 "first argument must be callable");
628 return NULL;
629 }
630
631 return PyInstanceMethod_New(func);
632 }
633
634 PyTypeObject PyInstanceMethod_Type = {
635 PyVarObject_HEAD_INIT(&PyType_Type, 0)
636 "instancemethod", /* tp_name */
637 sizeof(PyInstanceMethodObject), /* tp_basicsize */
638 0, /* tp_itemsize */
639 instancemethod_dealloc, /* tp_dealloc */
640 0, /* tp_vectorcall_offset */
641 0, /* tp_getattr */
642 0, /* tp_setattr */
643 0, /* tp_as_async */
644 (reprfunc)instancemethod_repr, /* tp_repr */
645 0, /* tp_as_number */
646 0, /* tp_as_sequence */
647 0, /* tp_as_mapping */
648 0, /*(hashfunc)instancemethod_hash, tp_hash */
649 instancemethod_call, /* tp_call */
650 0, /* tp_str */
651 instancemethod_getattro, /* tp_getattro */
652 PyObject_GenericSetAttr, /* tp_setattro */
653 0, /* tp_as_buffer */
654 Py_TPFLAGS_DEFAULT
655 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
656 instancemethod_doc, /* tp_doc */
657 instancemethod_traverse, /* tp_traverse */
658 0, /* tp_clear */
659 instancemethod_richcompare, /* tp_richcompare */
660 0, /* tp_weaklistoffset */
661 0, /* tp_iter */
662 0, /* tp_iternext */
663 0, /* tp_methods */
664 instancemethod_memberlist, /* tp_members */
665 instancemethod_getset, /* tp_getset */
666 0, /* tp_base */
667 0, /* tp_dict */
668 instancemethod_descr_get, /* tp_descr_get */
669 0, /* tp_descr_set */
670 0, /* tp_dictoffset */
671 0, /* tp_init */
672 0, /* tp_alloc */
673 instancemethod_new, /* tp_new */
674 };
675