PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Objects/methodobject.c

https://gitlab.com/unofficial-mirrors/cpython
C | 657 lines | 526 code | 99 blank | 32 comment | 112 complexity | 3b24a230ff414b18a37276646d41b5af MD5 | raw file
  1. /* Method object implementation */
  2. #include "Python.h"
  3. #include "structmember.h"
  4. /* Free list for method objects to safe malloc/free overhead
  5. * The m_self element is used to chain the objects.
  6. */
  7. static PyCFunctionObject *free_list = NULL;
  8. static int numfree = 0;
  9. #ifndef PyCFunction_MAXFREELIST
  10. #define PyCFunction_MAXFREELIST 256
  11. #endif
  12. /* undefine macro trampoline to PyCFunction_NewEx */
  13. #undef PyCFunction_New
  14. PyAPI_FUNC(PyObject *)
  15. PyCFunction_New(PyMethodDef *ml, PyObject *self)
  16. {
  17. return PyCFunction_NewEx(ml, self, NULL);
  18. }
  19. PyObject *
  20. PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
  21. {
  22. PyCFunctionObject *op;
  23. op = free_list;
  24. if (op != NULL) {
  25. free_list = (PyCFunctionObject *)(op->m_self);
  26. (void)PyObject_INIT(op, &PyCFunction_Type);
  27. numfree--;
  28. }
  29. else {
  30. op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type);
  31. if (op == NULL)
  32. return NULL;
  33. }
  34. op->m_weakreflist = NULL;
  35. op->m_ml = ml;
  36. Py_XINCREF(self);
  37. op->m_self = self;
  38. Py_XINCREF(module);
  39. op->m_module = module;
  40. _PyObject_GC_TRACK(op);
  41. return (PyObject *)op;
  42. }
  43. PyCFunction
  44. PyCFunction_GetFunction(PyObject *op)
  45. {
  46. if (!PyCFunction_Check(op)) {
  47. PyErr_BadInternalCall();
  48. return NULL;
  49. }
  50. return PyCFunction_GET_FUNCTION(op);
  51. }
  52. PyObject *
  53. PyCFunction_GetSelf(PyObject *op)
  54. {
  55. if (!PyCFunction_Check(op)) {
  56. PyErr_BadInternalCall();
  57. return NULL;
  58. }
  59. return PyCFunction_GET_SELF(op);
  60. }
  61. int
  62. PyCFunction_GetFlags(PyObject *op)
  63. {
  64. if (!PyCFunction_Check(op)) {
  65. PyErr_BadInternalCall();
  66. return -1;
  67. }
  68. return PyCFunction_GET_FLAGS(op);
  69. }
  70. static PyObject *
  71. cfunction_call_varargs(PyObject *func, PyObject *args, PyObject *kwargs)
  72. {
  73. assert(!PyErr_Occurred());
  74. PyCFunction meth = PyCFunction_GET_FUNCTION(func);
  75. PyObject *self = PyCFunction_GET_SELF(func);
  76. PyObject *result;
  77. if (PyCFunction_GET_FLAGS(func) & METH_KEYWORDS) {
  78. if (Py_EnterRecursiveCall(" while calling a Python object")) {
  79. return NULL;
  80. }
  81. result = (*(PyCFunctionWithKeywords)meth)(self, args, kwargs);
  82. Py_LeaveRecursiveCall();
  83. }
  84. else {
  85. if (kwargs != NULL && PyDict_Size(kwargs) != 0) {
  86. PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
  87. ((PyCFunctionObject*)func)->m_ml->ml_name);
  88. return NULL;
  89. }
  90. if (Py_EnterRecursiveCall(" while calling a Python object")) {
  91. return NULL;
  92. }
  93. result = (*meth)(self, args);
  94. Py_LeaveRecursiveCall();
  95. }
  96. return _Py_CheckFunctionResult(func, result, NULL);
  97. }
  98. PyObject *
  99. PyCFunction_Call(PyObject *func, PyObject *args, PyObject *kwargs)
  100. {
  101. /* first try METH_VARARGS to pass directly args tuple unchanged.
  102. _PyMethodDef_RawFastCallDict() creates a new temporary tuple
  103. for METH_VARARGS. */
  104. if (PyCFunction_GET_FLAGS(func) & METH_VARARGS) {
  105. return cfunction_call_varargs(func, args, kwargs);
  106. }
  107. else {
  108. return _PyCFunction_FastCallDict(func,
  109. &PyTuple_GET_ITEM(args, 0),
  110. PyTuple_GET_SIZE(args),
  111. kwargs);
  112. }
  113. }
  114. PyObject *
  115. _PyMethodDef_RawFastCallDict(PyMethodDef *method, PyObject *self, PyObject **args,
  116. Py_ssize_t nargs, PyObject *kwargs)
  117. {
  118. /* _PyMethodDef_RawFastCallDict() must not be called with an exception set,
  119. because it can clear it (directly or indirectly) and so the
  120. caller loses its exception */
  121. assert(!PyErr_Occurred());
  122. assert(method != NULL);
  123. assert(nargs >= 0);
  124. assert(nargs == 0 || args != NULL);
  125. assert(kwargs == NULL || PyDict_Check(kwargs));
  126. PyCFunction meth = method->ml_meth;
  127. int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST);
  128. PyObject *result = NULL;
  129. if (Py_EnterRecursiveCall(" while calling a Python object")) {
  130. return NULL;
  131. }
  132. switch (flags)
  133. {
  134. case METH_NOARGS:
  135. if (nargs != 0) {
  136. PyErr_Format(PyExc_TypeError,
  137. "%.200s() takes no arguments (%zd given)",
  138. method->ml_name, nargs);
  139. goto exit;
  140. }
  141. if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
  142. goto no_keyword_error;
  143. }
  144. result = (*meth) (self, NULL);
  145. break;
  146. case METH_O:
  147. if (nargs != 1) {
  148. PyErr_Format(PyExc_TypeError,
  149. "%.200s() takes exactly one argument (%zd given)",
  150. method->ml_name, nargs);
  151. goto exit;
  152. }
  153. if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
  154. goto no_keyword_error;
  155. }
  156. result = (*meth) (self, args[0]);
  157. break;
  158. case METH_VARARGS:
  159. if (!(flags & METH_KEYWORDS)
  160. && kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) {
  161. goto no_keyword_error;
  162. }
  163. /* fall through next case */
  164. case METH_VARARGS | METH_KEYWORDS:
  165. {
  166. /* Slow-path: create a temporary tuple for positional arguments */
  167. PyObject *argstuple = _PyStack_AsTuple(args, nargs);
  168. if (argstuple == NULL) {
  169. goto exit;
  170. }
  171. if (flags & METH_KEYWORDS) {
  172. result = (*(PyCFunctionWithKeywords)meth) (self, argstuple, kwargs);
  173. }
  174. else {
  175. result = (*meth) (self, argstuple);
  176. }
  177. Py_DECREF(argstuple);
  178. break;
  179. }
  180. case METH_FASTCALL:
  181. {
  182. PyObject **stack;
  183. PyObject *kwnames;
  184. _PyCFunctionFast fastmeth = (_PyCFunctionFast)meth;
  185. if (_PyStack_UnpackDict(args, nargs, kwargs, &stack, &kwnames) < 0) {
  186. goto exit;
  187. }
  188. result = (*fastmeth) (self, stack, nargs, kwnames);
  189. if (stack != args) {
  190. PyMem_Free(stack);
  191. }
  192. Py_XDECREF(kwnames);
  193. break;
  194. }
  195. default:
  196. PyErr_SetString(PyExc_SystemError,
  197. "Bad call flags in _PyMethodDef_RawFastCallDict. "
  198. "METH_OLDARGS is no longer supported!");
  199. goto exit;
  200. }
  201. goto exit;
  202. no_keyword_error:
  203. PyErr_Format(PyExc_TypeError,
  204. "%.200s() takes no keyword arguments",
  205. method->ml_name, nargs);
  206. exit:
  207. Py_LeaveRecursiveCall();
  208. return result;
  209. }
  210. PyObject *
  211. _PyCFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs,
  212. PyObject *kwargs)
  213. {
  214. PyObject *result;
  215. assert(func != NULL);
  216. assert(PyCFunction_Check(func));
  217. result = _PyMethodDef_RawFastCallDict(((PyCFunctionObject*)func)->m_ml,
  218. PyCFunction_GET_SELF(func),
  219. args, nargs, kwargs);
  220. result = _Py_CheckFunctionResult(func, result, NULL);
  221. return result;
  222. }
  223. PyObject *
  224. _PyMethodDef_RawFastCallKeywords(PyMethodDef *method, PyObject *self, PyObject **args,
  225. Py_ssize_t nargs, PyObject *kwnames)
  226. {
  227. /* _PyMethodDef_RawFastCallKeywords() must not be called with an exception set,
  228. because it can clear it (directly or indirectly) and so the
  229. caller loses its exception */
  230. assert(!PyErr_Occurred());
  231. assert(method != NULL);
  232. assert(nargs >= 0);
  233. assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
  234. /* kwnames must only contains str strings, no subclass, and all keys must
  235. be unique */
  236. PyCFunction meth = method->ml_meth;
  237. int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST);
  238. Py_ssize_t nkwargs = kwnames == NULL ? 0 : PyTuple_Size(kwnames);
  239. PyObject *result = NULL;
  240. if (Py_EnterRecursiveCall(" while calling a Python object")) {
  241. return NULL;
  242. }
  243. switch (flags)
  244. {
  245. case METH_NOARGS:
  246. if (nargs != 0) {
  247. PyErr_Format(PyExc_TypeError,
  248. "%.200s() takes no arguments (%zd given)",
  249. method->ml_name, nargs);
  250. goto exit;
  251. }
  252. if (nkwargs) {
  253. goto no_keyword_error;
  254. }
  255. result = (*meth) (self, NULL);
  256. break;
  257. case METH_O:
  258. if (nargs != 1) {
  259. PyErr_Format(PyExc_TypeError,
  260. "%.200s() takes exactly one argument (%zd given)",
  261. method->ml_name, nargs);
  262. goto exit;
  263. }
  264. if (nkwargs) {
  265. goto no_keyword_error;
  266. }
  267. result = (*meth) (self, args[0]);
  268. break;
  269. case METH_FASTCALL:
  270. /* Fast-path: avoid temporary dict to pass keyword arguments */
  271. result = ((_PyCFunctionFast)meth) (self, args, nargs, kwnames);
  272. break;
  273. case METH_VARARGS:
  274. case METH_VARARGS | METH_KEYWORDS:
  275. {
  276. /* Slow-path: create a temporary tuple for positional arguments
  277. and a temporary dict for keyword arguments */
  278. PyObject *argtuple;
  279. if (!(flags & METH_KEYWORDS) && nkwargs) {
  280. goto no_keyword_error;
  281. }
  282. argtuple = _PyStack_AsTuple(args, nargs);
  283. if (argtuple == NULL) {
  284. goto exit;
  285. }
  286. if (flags & METH_KEYWORDS) {
  287. PyObject *kwdict;
  288. if (nkwargs > 0) {
  289. kwdict = _PyStack_AsDict(args + nargs, kwnames);
  290. if (kwdict == NULL) {
  291. Py_DECREF(argtuple);
  292. goto exit;
  293. }
  294. }
  295. else {
  296. kwdict = NULL;
  297. }
  298. result = (*(PyCFunctionWithKeywords)meth) (self, argtuple, kwdict);
  299. Py_XDECREF(kwdict);
  300. }
  301. else {
  302. result = (*meth) (self, argtuple);
  303. }
  304. Py_DECREF(argtuple);
  305. break;
  306. }
  307. default:
  308. PyErr_SetString(PyExc_SystemError,
  309. "Bad call flags in _PyCFunction_FastCallKeywords. "
  310. "METH_OLDARGS is no longer supported!");
  311. goto exit;
  312. }
  313. goto exit;
  314. no_keyword_error:
  315. PyErr_Format(PyExc_TypeError,
  316. "%.200s() takes no keyword arguments",
  317. method->ml_name);
  318. exit:
  319. Py_LeaveRecursiveCall();
  320. return result;
  321. }
  322. PyObject *
  323. _PyCFunction_FastCallKeywords(PyObject *func, PyObject **args,
  324. Py_ssize_t nargs, PyObject *kwnames)
  325. {
  326. PyObject *result;
  327. assert(func != NULL);
  328. assert(PyCFunction_Check(func));
  329. result = _PyMethodDef_RawFastCallKeywords(((PyCFunctionObject*)func)->m_ml,
  330. PyCFunction_GET_SELF(func),
  331. args, nargs, kwnames);
  332. result = _Py_CheckFunctionResult(func, result, NULL);
  333. return result;
  334. }
  335. /* Methods (the standard built-in methods, that is) */
  336. static void
  337. meth_dealloc(PyCFunctionObject *m)
  338. {
  339. _PyObject_GC_UNTRACK(m);
  340. if (m->m_weakreflist != NULL) {
  341. PyObject_ClearWeakRefs((PyObject*) m);
  342. }
  343. Py_XDECREF(m->m_self);
  344. Py_XDECREF(m->m_module);
  345. if (numfree < PyCFunction_MAXFREELIST) {
  346. m->m_self = (PyObject *)free_list;
  347. free_list = m;
  348. numfree++;
  349. }
  350. else {
  351. PyObject_GC_Del(m);
  352. }
  353. }
  354. static PyObject *
  355. meth_reduce(PyCFunctionObject *m)
  356. {
  357. PyObject *builtins;
  358. PyObject *getattr;
  359. _Py_IDENTIFIER(getattr);
  360. if (m->m_self == NULL || PyModule_Check(m->m_self))
  361. return PyUnicode_FromString(m->m_ml->ml_name);
  362. builtins = PyEval_GetBuiltins();
  363. getattr = _PyDict_GetItemId(builtins, &PyId_getattr);
  364. return Py_BuildValue("O(Os)", getattr, m->m_self, m->m_ml->ml_name);
  365. }
  366. static PyMethodDef meth_methods[] = {
  367. {"__reduce__", (PyCFunction)meth_reduce, METH_NOARGS, NULL},
  368. {NULL, NULL}
  369. };
  370. static PyObject *
  371. meth_get__text_signature__(PyCFunctionObject *m, void *closure)
  372. {
  373. return _PyType_GetTextSignatureFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc);
  374. }
  375. static PyObject *
  376. meth_get__doc__(PyCFunctionObject *m, void *closure)
  377. {
  378. return _PyType_GetDocFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc);
  379. }
  380. static PyObject *
  381. meth_get__name__(PyCFunctionObject *m, void *closure)
  382. {
  383. return PyUnicode_FromString(m->m_ml->ml_name);
  384. }
  385. static PyObject *
  386. meth_get__qualname__(PyCFunctionObject *m, void *closure)
  387. {
  388. /* If __self__ is a module or NULL, return m.__name__
  389. (e.g. len.__qualname__ == 'len')
  390. If __self__ is a type, return m.__self__.__qualname__ + '.' + m.__name__
  391. (e.g. dict.fromkeys.__qualname__ == 'dict.fromkeys')
  392. Otherwise return type(m.__self__).__qualname__ + '.' + m.__name__
  393. (e.g. [].append.__qualname__ == 'list.append') */
  394. PyObject *type, *type_qualname, *res;
  395. _Py_IDENTIFIER(__qualname__);
  396. if (m->m_self == NULL || PyModule_Check(m->m_self))
  397. return PyUnicode_FromString(m->m_ml->ml_name);
  398. type = PyType_Check(m->m_self) ? m->m_self : (PyObject*)Py_TYPE(m->m_self);
  399. type_qualname = _PyObject_GetAttrId(type, &PyId___qualname__);
  400. if (type_qualname == NULL)
  401. return NULL;
  402. if (!PyUnicode_Check(type_qualname)) {
  403. PyErr_SetString(PyExc_TypeError, "<method>.__class__."
  404. "__qualname__ is not a unicode object");
  405. Py_XDECREF(type_qualname);
  406. return NULL;
  407. }
  408. res = PyUnicode_FromFormat("%S.%s", type_qualname, m->m_ml->ml_name);
  409. Py_DECREF(type_qualname);
  410. return res;
  411. }
  412. static int
  413. meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg)
  414. {
  415. Py_VISIT(m->m_self);
  416. Py_VISIT(m->m_module);
  417. return 0;
  418. }
  419. static PyObject *
  420. meth_get__self__(PyCFunctionObject *m, void *closure)
  421. {
  422. PyObject *self;
  423. self = PyCFunction_GET_SELF(m);
  424. if (self == NULL)
  425. self = Py_None;
  426. Py_INCREF(self);
  427. return self;
  428. }
  429. static PyGetSetDef meth_getsets [] = {
  430. {"__doc__", (getter)meth_get__doc__, NULL, NULL},
  431. {"__name__", (getter)meth_get__name__, NULL, NULL},
  432. {"__qualname__", (getter)meth_get__qualname__, NULL, NULL},
  433. {"__self__", (getter)meth_get__self__, NULL, NULL},
  434. {"__text_signature__", (getter)meth_get__text_signature__, NULL, NULL},
  435. {0}
  436. };
  437. #define OFF(x) offsetof(PyCFunctionObject, x)
  438. static PyMemberDef meth_members[] = {
  439. {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED},
  440. {NULL}
  441. };
  442. static PyObject *
  443. meth_repr(PyCFunctionObject *m)
  444. {
  445. if (m->m_self == NULL || PyModule_Check(m->m_self))
  446. return PyUnicode_FromFormat("<built-in function %s>",
  447. m->m_ml->ml_name);
  448. return PyUnicode_FromFormat("<built-in method %s of %s object at %p>",
  449. m->m_ml->ml_name,
  450. m->m_self->ob_type->tp_name,
  451. m->m_self);
  452. }
  453. static PyObject *
  454. meth_richcompare(PyObject *self, PyObject *other, int op)
  455. {
  456. PyCFunctionObject *a, *b;
  457. PyObject *res;
  458. int eq;
  459. if ((op != Py_EQ && op != Py_NE) ||
  460. !PyCFunction_Check(self) ||
  461. !PyCFunction_Check(other))
  462. {
  463. Py_RETURN_NOTIMPLEMENTED;
  464. }
  465. a = (PyCFunctionObject *)self;
  466. b = (PyCFunctionObject *)other;
  467. eq = a->m_self == b->m_self;
  468. if (eq)
  469. eq = a->m_ml->ml_meth == b->m_ml->ml_meth;
  470. if (op == Py_EQ)
  471. res = eq ? Py_True : Py_False;
  472. else
  473. res = eq ? Py_False : Py_True;
  474. Py_INCREF(res);
  475. return res;
  476. }
  477. static Py_hash_t
  478. meth_hash(PyCFunctionObject *a)
  479. {
  480. Py_hash_t x, y;
  481. if (a->m_self == NULL)
  482. x = 0;
  483. else {
  484. x = PyObject_Hash(a->m_self);
  485. if (x == -1)
  486. return -1;
  487. }
  488. y = _Py_HashPointer((void*)(a->m_ml->ml_meth));
  489. if (y == -1)
  490. return -1;
  491. x ^= y;
  492. if (x == -1)
  493. x = -2;
  494. return x;
  495. }
  496. PyTypeObject PyCFunction_Type = {
  497. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  498. "builtin_function_or_method",
  499. sizeof(PyCFunctionObject),
  500. 0,
  501. (destructor)meth_dealloc, /* tp_dealloc */
  502. 0, /* tp_print */
  503. 0, /* tp_getattr */
  504. 0, /* tp_setattr */
  505. 0, /* tp_reserved */
  506. (reprfunc)meth_repr, /* tp_repr */
  507. 0, /* tp_as_number */
  508. 0, /* tp_as_sequence */
  509. 0, /* tp_as_mapping */
  510. (hashfunc)meth_hash, /* tp_hash */
  511. PyCFunction_Call, /* tp_call */
  512. 0, /* tp_str */
  513. PyObject_GenericGetAttr, /* tp_getattro */
  514. 0, /* tp_setattro */
  515. 0, /* tp_as_buffer */
  516. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  517. 0, /* tp_doc */
  518. (traverseproc)meth_traverse, /* tp_traverse */
  519. 0, /* tp_clear */
  520. meth_richcompare, /* tp_richcompare */
  521. offsetof(PyCFunctionObject, m_weakreflist), /* tp_weaklistoffset */
  522. 0, /* tp_iter */
  523. 0, /* tp_iternext */
  524. meth_methods, /* tp_methods */
  525. meth_members, /* tp_members */
  526. meth_getsets, /* tp_getset */
  527. 0, /* tp_base */
  528. 0, /* tp_dict */
  529. };
  530. /* Clear out the free list */
  531. int
  532. PyCFunction_ClearFreeList(void)
  533. {
  534. int freelist_size = numfree;
  535. while (free_list) {
  536. PyCFunctionObject *v = free_list;
  537. free_list = (PyCFunctionObject *)(v->m_self);
  538. PyObject_GC_Del(v);
  539. numfree--;
  540. }
  541. assert(numfree == 0);
  542. return freelist_size;
  543. }
  544. void
  545. PyCFunction_Fini(void)
  546. {
  547. (void)PyCFunction_ClearFreeList();
  548. }
  549. /* Print summary info about the state of the optimized allocator */
  550. void
  551. _PyCFunction_DebugMallocStats(FILE *out)
  552. {
  553. _PyDebugAllocatorStats(out,
  554. "free PyCFunctionObject",
  555. numfree, sizeof(PyCFunctionObject));
  556. }