classobject.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /* Class object implementation (dead now except for methods) */
  2. #include "Python.h"
  3. #include "pycore_call.h" // _PyObject_VectorcallTstate()
  4. #include "pycore_object.h"
  5. #include "pycore_pyerrors.h"
  6. #include "pycore_pystate.h" // _PyThreadState_GET()
  7. #include "structmember.h" // PyMemberDef
  8. #include "clinic/classobject.c.h"
  9. #define TP_DESCR_GET(t) ((t)->tp_descr_get)
  10. /*[clinic input]
  11. class method "PyMethodObject *" "&PyMethod_Type"
  12. [clinic start generated code]*/
  13. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b16e47edf6107c23]*/
  14. PyObject *
  15. PyMethod_Function(PyObject *im)
  16. {
  17. if (!PyMethod_Check(im)) {
  18. PyErr_BadInternalCall();
  19. return NULL;
  20. }
  21. return ((PyMethodObject *)im)->im_func;
  22. }
  23. PyObject *
  24. PyMethod_Self(PyObject *im)
  25. {
  26. if (!PyMethod_Check(im)) {
  27. PyErr_BadInternalCall();
  28. return NULL;
  29. }
  30. return ((PyMethodObject *)im)->im_self;
  31. }
  32. static PyObject *
  33. method_vectorcall(PyObject *method, PyObject *const *args,
  34. size_t nargsf, PyObject *kwnames)
  35. {
  36. assert(Py_IS_TYPE(method, &PyMethod_Type));
  37. PyThreadState *tstate = _PyThreadState_GET();
  38. PyObject *self = PyMethod_GET_SELF(method);
  39. PyObject *func = PyMethod_GET_FUNCTION(method);
  40. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  41. assert(nargs == 0 || args[nargs-1]);
  42. PyObject *result;
  43. if (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET) {
  44. /* PY_VECTORCALL_ARGUMENTS_OFFSET is set, so we are allowed to mutate the vector */
  45. PyObject **newargs = (PyObject**)args - 1;
  46. nargs += 1;
  47. PyObject *tmp = newargs[0];
  48. newargs[0] = self;
  49. assert(newargs[nargs-1]);
  50. result = _PyObject_VectorcallTstate(tstate, func, newargs,
  51. nargs, kwnames);
  52. newargs[0] = tmp;
  53. }
  54. else {
  55. Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
  56. Py_ssize_t totalargs = nargs + nkwargs;
  57. if (totalargs == 0) {
  58. return _PyObject_VectorcallTstate(tstate, func, &self, 1, NULL);
  59. }
  60. PyObject *newargs_stack[_PY_FASTCALL_SMALL_STACK];
  61. PyObject **newargs;
  62. if (totalargs <= (Py_ssize_t)Py_ARRAY_LENGTH(newargs_stack) - 1) {
  63. newargs = newargs_stack;
  64. }
  65. else {
  66. newargs = PyMem_Malloc((totalargs+1) * sizeof(PyObject *));
  67. if (newargs == NULL) {
  68. _PyErr_NoMemory(tstate);
  69. return NULL;
  70. }
  71. }
  72. /* use borrowed references */
  73. newargs[0] = self;
  74. /* bpo-37138: since totalargs > 0, it's impossible that args is NULL.
  75. * We need this, since calling memcpy() with a NULL pointer is
  76. * undefined behaviour. */
  77. assert(args != NULL);
  78. memcpy(newargs + 1, args, totalargs * sizeof(PyObject *));
  79. result = _PyObject_VectorcallTstate(tstate, func,
  80. newargs, nargs+1, kwnames);
  81. if (newargs != newargs_stack) {
  82. PyMem_Free(newargs);
  83. }
  84. }
  85. return result;
  86. }
  87. /* Method objects are used for bound instance methods returned by
  88. instancename.methodname. ClassName.methodname returns an ordinary
  89. function.
  90. */
  91. PyObject *
  92. PyMethod_New(PyObject *func, PyObject *self)
  93. {
  94. if (self == NULL) {
  95. PyErr_BadInternalCall();
  96. return NULL;
  97. }
  98. PyMethodObject *im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
  99. if (im == NULL) {
  100. return NULL;
  101. }
  102. im->im_weakreflist = NULL;
  103. im->im_func = Py_NewRef(func);
  104. im->im_self = Py_NewRef(self);
  105. im->vectorcall = method_vectorcall;
  106. _PyObject_GC_TRACK(im);
  107. return (PyObject *)im;
  108. }
  109. /*[clinic input]
  110. method.__reduce__
  111. [clinic start generated code]*/
  112. static PyObject *
  113. method___reduce___impl(PyMethodObject *self)
  114. /*[clinic end generated code: output=6c04506d0fa6fdcb input=143a0bf5e96de6e8]*/
  115. {
  116. PyObject *funcself = PyMethod_GET_SELF(self);
  117. PyObject *func = PyMethod_GET_FUNCTION(self);
  118. PyObject *funcname = PyObject_GetAttr(func, &_Py_ID(__name__));
  119. if (funcname == NULL) {
  120. return NULL;
  121. }
  122. return Py_BuildValue(
  123. "N(ON)", _PyEval_GetBuiltin(&_Py_ID(getattr)), funcself, funcname);
  124. }
  125. static PyMethodDef method_methods[] = {
  126. METHOD___REDUCE___METHODDEF
  127. {NULL, NULL}
  128. };
  129. /* Descriptors for PyMethod attributes */
  130. /* im_func and im_self are stored in the PyMethod object */
  131. #define MO_OFF(x) offsetof(PyMethodObject, x)
  132. static PyMemberDef method_memberlist[] = {
  133. {"__func__", T_OBJECT, MO_OFF(im_func), READONLY,
  134. "the function (or other callable) implementing a method"},
  135. {"__self__", T_OBJECT, MO_OFF(im_self), READONLY,
  136. "the instance to which a method is bound"},
  137. {NULL} /* Sentinel */
  138. };
  139. /* Christian Tismer argued convincingly that method attributes should
  140. (nearly) always override function attributes.
  141. The one exception is __doc__; there's a default __doc__ which
  142. should only be used for the class, not for instances */
  143. static PyObject *
  144. method_get_doc(PyMethodObject *im, void *context)
  145. {
  146. return PyObject_GetAttr(im->im_func, &_Py_ID(__doc__));
  147. }
  148. static PyGetSetDef method_getset[] = {
  149. {"__doc__", (getter)method_get_doc, NULL, NULL},
  150. {0}
  151. };
  152. static PyObject *
  153. method_getattro(PyObject *obj, PyObject *name)
  154. {
  155. PyMethodObject *im = (PyMethodObject *)obj;
  156. PyTypeObject *tp = Py_TYPE(obj);
  157. PyObject *descr = NULL;
  158. {
  159. if (!_PyType_IsReady(tp)) {
  160. if (PyType_Ready(tp) < 0)
  161. return NULL;
  162. }
  163. descr = _PyType_Lookup(tp, name);
  164. }
  165. if (descr != NULL) {
  166. descrgetfunc f = TP_DESCR_GET(Py_TYPE(descr));
  167. if (f != NULL)
  168. return f(descr, obj, (PyObject *)Py_TYPE(obj));
  169. else {
  170. return Py_NewRef(descr);
  171. }
  172. }
  173. return PyObject_GetAttr(im->im_func, name);
  174. }
  175. /*[clinic input]
  176. @classmethod
  177. method.__new__ as method_new
  178. function: object
  179. instance: object
  180. /
  181. Create a bound instance method object.
  182. [clinic start generated code]*/
  183. static PyObject *
  184. method_new_impl(PyTypeObject *type, PyObject *function, PyObject *instance)
  185. /*[clinic end generated code: output=d33ef4ebf702e1f7 input=4e32facc3c3108ae]*/
  186. {
  187. if (!PyCallable_Check(function)) {
  188. PyErr_SetString(PyExc_TypeError,
  189. "first argument must be callable");
  190. return NULL;
  191. }
  192. if (instance == NULL || instance == Py_None) {
  193. PyErr_SetString(PyExc_TypeError,
  194. "instance must not be None");
  195. return NULL;
  196. }
  197. return PyMethod_New(function, instance);
  198. }
  199. static void
  200. method_dealloc(PyMethodObject *im)
  201. {
  202. _PyObject_GC_UNTRACK(im);
  203. if (im->im_weakreflist != NULL)
  204. PyObject_ClearWeakRefs((PyObject *)im);
  205. Py_DECREF(im->im_func);
  206. Py_XDECREF(im->im_self);
  207. PyObject_GC_Del(im);
  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. if ((op != Py_EQ && op != Py_NE) ||
  216. !PyMethod_Check(self) ||
  217. !PyMethod_Check(other))
  218. {
  219. Py_RETURN_NOTIMPLEMENTED;
  220. }
  221. a = (PyMethodObject *)self;
  222. b = (PyMethodObject *)other;
  223. eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ);
  224. if (eq == 1) {
  225. eq = (a->im_self == b->im_self);
  226. }
  227. else if (eq < 0)
  228. return NULL;
  229. if (op == Py_EQ)
  230. res = eq ? Py_True : Py_False;
  231. else
  232. res = eq ? Py_False : Py_True;
  233. return Py_NewRef(res);
  234. }
  235. static PyObject *
  236. method_repr(PyMethodObject *a)
  237. {
  238. PyObject *self = a->im_self;
  239. PyObject *func = a->im_func;
  240. PyObject *funcname, *result;
  241. const char *defname = "?";
  242. if (_PyObject_LookupAttr(func, &_Py_ID(__qualname__), &funcname) < 0 ||
  243. (funcname == NULL &&
  244. _PyObject_LookupAttr(func, &_Py_ID(__name__), &funcname) < 0))
  245. {
  246. return NULL;
  247. }
  248. if (funcname != NULL && !PyUnicode_Check(funcname)) {
  249. Py_SETREF(funcname, NULL);
  250. }
  251. /* XXX Shouldn't use repr()/%R here! */
  252. result = PyUnicode_FromFormat("<bound method %V of %R>",
  253. funcname, defname, self);
  254. Py_XDECREF(funcname);
  255. return result;
  256. }
  257. static Py_hash_t
  258. method_hash(PyMethodObject *a)
  259. {
  260. Py_hash_t x, y;
  261. x = _Py_HashPointer(a->im_self);
  262. y = PyObject_Hash(a->im_func);
  263. if (y == -1)
  264. return -1;
  265. x = x ^ y;
  266. if (x == -1)
  267. x = -2;
  268. return x;
  269. }
  270. static int
  271. method_traverse(PyMethodObject *im, visitproc visit, void *arg)
  272. {
  273. Py_VISIT(im->im_func);
  274. Py_VISIT(im->im_self);
  275. return 0;
  276. }
  277. PyTypeObject PyMethod_Type = {
  278. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  279. .tp_name = "method",
  280. .tp_basicsize = sizeof(PyMethodObject),
  281. .tp_dealloc = (destructor)method_dealloc,
  282. .tp_vectorcall_offset = offsetof(PyMethodObject, vectorcall),
  283. .tp_repr = (reprfunc)method_repr,
  284. .tp_hash = (hashfunc)method_hash,
  285. .tp_call = PyVectorcall_Call,
  286. .tp_getattro = method_getattro,
  287. .tp_setattro = PyObject_GenericSetAttr,
  288. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  289. Py_TPFLAGS_HAVE_VECTORCALL,
  290. .tp_doc = method_new__doc__,
  291. .tp_traverse = (traverseproc)method_traverse,
  292. .tp_richcompare = method_richcompare,
  293. .tp_weaklistoffset = offsetof(PyMethodObject, im_weakreflist),
  294. .tp_methods = method_methods,
  295. .tp_members = method_memberlist,
  296. .tp_getset = method_getset,
  297. .tp_new = method_new,
  298. };
  299. /* ------------------------------------------------------------------------
  300. * instance method
  301. */
  302. /*[clinic input]
  303. class instancemethod "PyInstanceMethodObject *" "&PyInstanceMethod_Type"
  304. [clinic start generated code]*/
  305. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=28c9762a9016f4d2]*/
  306. PyObject *
  307. PyInstanceMethod_New(PyObject *func) {
  308. PyInstanceMethodObject *method;
  309. method = PyObject_GC_New(PyInstanceMethodObject,
  310. &PyInstanceMethod_Type);
  311. if (method == NULL) return NULL;
  312. method->func = Py_NewRef(func);
  313. _PyObject_GC_TRACK(method);
  314. return (PyObject *)method;
  315. }
  316. PyObject *
  317. PyInstanceMethod_Function(PyObject *im)
  318. {
  319. if (!PyInstanceMethod_Check(im)) {
  320. PyErr_BadInternalCall();
  321. return NULL;
  322. }
  323. return PyInstanceMethod_GET_FUNCTION(im);
  324. }
  325. #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x)
  326. static PyMemberDef instancemethod_memberlist[] = {
  327. {"__func__", T_OBJECT, IMO_OFF(func), READONLY,
  328. "the function (or other callable) implementing a method"},
  329. {NULL} /* Sentinel */
  330. };
  331. static PyObject *
  332. instancemethod_get_doc(PyObject *self, void *context)
  333. {
  334. return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self),
  335. &_Py_ID(__doc__));
  336. }
  337. static PyGetSetDef instancemethod_getset[] = {
  338. {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
  339. {0}
  340. };
  341. static PyObject *
  342. instancemethod_getattro(PyObject *self, PyObject *name)
  343. {
  344. PyTypeObject *tp = Py_TYPE(self);
  345. PyObject *descr = NULL;
  346. if (!_PyType_IsReady(tp)) {
  347. if (PyType_Ready(tp) < 0)
  348. return NULL;
  349. }
  350. descr = _PyType_Lookup(tp, name);
  351. if (descr != NULL) {
  352. descrgetfunc f = TP_DESCR_GET(Py_TYPE(descr));
  353. if (f != NULL)
  354. return f(descr, self, (PyObject *)Py_TYPE(self));
  355. else {
  356. return Py_NewRef(descr);
  357. }
  358. }
  359. return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name);
  360. }
  361. static void
  362. instancemethod_dealloc(PyObject *self) {
  363. _PyObject_GC_UNTRACK(self);
  364. Py_DECREF(PyInstanceMethod_GET_FUNCTION(self));
  365. PyObject_GC_Del(self);
  366. }
  367. static int
  368. instancemethod_traverse(PyObject *self, visitproc visit, void *arg) {
  369. Py_VISIT(PyInstanceMethod_GET_FUNCTION(self));
  370. return 0;
  371. }
  372. static PyObject *
  373. instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw)
  374. {
  375. return PyObject_Call(PyInstanceMethod_GET_FUNCTION(self), arg, kw);
  376. }
  377. static PyObject *
  378. instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) {
  379. PyObject *func = PyInstanceMethod_GET_FUNCTION(descr);
  380. if (obj == NULL) {
  381. return Py_NewRef(func);
  382. }
  383. else
  384. return PyMethod_New(func, obj);
  385. }
  386. static PyObject *
  387. instancemethod_richcompare(PyObject *self, PyObject *other, int op)
  388. {
  389. PyInstanceMethodObject *a, *b;
  390. PyObject *res;
  391. int eq;
  392. if ((op != Py_EQ && op != Py_NE) ||
  393. !PyInstanceMethod_Check(self) ||
  394. !PyInstanceMethod_Check(other))
  395. {
  396. Py_RETURN_NOTIMPLEMENTED;
  397. }
  398. a = (PyInstanceMethodObject *)self;
  399. b = (PyInstanceMethodObject *)other;
  400. eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ);
  401. if (eq < 0)
  402. return NULL;
  403. if (op == Py_EQ)
  404. res = eq ? Py_True : Py_False;
  405. else
  406. res = eq ? Py_False : Py_True;
  407. return Py_NewRef(res);
  408. }
  409. static PyObject *
  410. instancemethod_repr(PyObject *self)
  411. {
  412. PyObject *func = PyInstanceMethod_Function(self);
  413. PyObject *funcname, *result;
  414. const char *defname = "?";
  415. if (func == NULL) {
  416. PyErr_BadInternalCall();
  417. return NULL;
  418. }
  419. if (_PyObject_LookupAttr(func, &_Py_ID(__name__), &funcname) < 0) {
  420. return NULL;
  421. }
  422. if (funcname != NULL && !PyUnicode_Check(funcname)) {
  423. Py_SETREF(funcname, NULL);
  424. }
  425. result = PyUnicode_FromFormat("<instancemethod %V at %p>",
  426. funcname, defname, self);
  427. Py_XDECREF(funcname);
  428. return result;
  429. }
  430. /*[clinic input]
  431. @classmethod
  432. instancemethod.__new__ as instancemethod_new
  433. function: object
  434. /
  435. Bind a function to a class.
  436. [clinic start generated code]*/
  437. static PyObject *
  438. instancemethod_new_impl(PyTypeObject *type, PyObject *function)
  439. /*[clinic end generated code: output=5e0397b2bdb750be input=cfc54e8b973664a8]*/
  440. {
  441. if (!PyCallable_Check(function)) {
  442. PyErr_SetString(PyExc_TypeError,
  443. "first argument must be callable");
  444. return NULL;
  445. }
  446. return PyInstanceMethod_New(function);
  447. }
  448. PyTypeObject PyInstanceMethod_Type = {
  449. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  450. .tp_name = "instancemethod",
  451. .tp_basicsize = sizeof(PyInstanceMethodObject),
  452. .tp_dealloc = instancemethod_dealloc,
  453. .tp_repr = (reprfunc)instancemethod_repr,
  454. .tp_call = instancemethod_call,
  455. .tp_getattro = instancemethod_getattro,
  456. .tp_setattro = PyObject_GenericSetAttr,
  457. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  458. .tp_doc = instancemethod_new__doc__,
  459. .tp_traverse = instancemethod_traverse,
  460. .tp_richcompare = instancemethod_richcompare,
  461. .tp_members = instancemethod_memberlist,
  462. .tp_getset = instancemethod_getset,
  463. .tp_descr_get = instancemethod_descr_get,
  464. .tp_new = instancemethod_new,
  465. };