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