_functoolsmodule.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. #include "Python.h"
  2. #include "pycore_call.h" // _PyObject_CallNoArgs()
  3. #include "pycore_dict.h" // _PyDict_Pop_KnownHash()
  4. #include "pycore_long.h" // _PyLong_GetZero()
  5. #include "pycore_moduleobject.h" // _PyModule_GetState()
  6. #include "pycore_object.h" // _PyObject_GC_TRACK
  7. #include "pycore_pystate.h" // _PyThreadState_GET()
  8. #include "pycore_tuple.h" // _PyTuple_ITEMS()
  9. #include "structmember.h" // PyMemberDef
  10. #include "clinic/_functoolsmodule.c.h"
  11. /*[clinic input]
  12. module _functools
  13. class _functools._lru_cache_wrapper "PyObject *" "&lru_cache_type_spec"
  14. [clinic start generated code]*/
  15. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=bece4053896b09c0]*/
  16. /* _functools module written and maintained
  17. by Hye-Shik Chang <perky@FreeBSD.org>
  18. with adaptations by Raymond Hettinger <python@rcn.com>
  19. Copyright (c) 2004, 2005, 2006 Python Software Foundation.
  20. All rights reserved.
  21. */
  22. typedef struct _functools_state {
  23. /* this object is used delimit args and keywords in the cache keys */
  24. PyObject *kwd_mark;
  25. PyTypeObject *partial_type;
  26. PyTypeObject *keyobject_type;
  27. PyTypeObject *lru_list_elem_type;
  28. } _functools_state;
  29. static inline _functools_state *
  30. get_functools_state(PyObject *module)
  31. {
  32. void *state = _PyModule_GetState(module);
  33. assert(state != NULL);
  34. return (_functools_state *)state;
  35. }
  36. /* partial object **********************************************************/
  37. typedef struct {
  38. PyObject_HEAD
  39. PyObject *fn;
  40. PyObject *args;
  41. PyObject *kw;
  42. PyObject *dict; /* __dict__ */
  43. PyObject *weakreflist; /* List of weak references */
  44. vectorcallfunc vectorcall;
  45. } partialobject;
  46. static void partial_setvectorcall(partialobject *pto);
  47. static struct PyModuleDef _functools_module;
  48. static PyObject *
  49. partial_call(partialobject *pto, PyObject *args, PyObject *kwargs);
  50. static inline _functools_state *
  51. get_functools_state_by_type(PyTypeObject *type)
  52. {
  53. PyObject *module = PyType_GetModuleByDef(type, &_functools_module);
  54. if (module == NULL) {
  55. return NULL;
  56. }
  57. return get_functools_state(module);
  58. }
  59. // Not converted to argument clinic, because of `*args, **kwargs` arguments.
  60. static PyObject *
  61. partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  62. {
  63. PyObject *func, *pargs, *nargs, *pkw;
  64. partialobject *pto;
  65. if (PyTuple_GET_SIZE(args) < 1) {
  66. PyErr_SetString(PyExc_TypeError,
  67. "type 'partial' takes at least one argument");
  68. return NULL;
  69. }
  70. pargs = pkw = NULL;
  71. func = PyTuple_GET_ITEM(args, 0);
  72. if (Py_TYPE(func)->tp_call == (ternaryfunc)partial_call) {
  73. // The type of "func" might not be exactly the same type object
  74. // as "type", but if it is called using partial_call, it must have the
  75. // same memory layout (fn, args and kw members).
  76. // We can use its underlying function directly and merge the arguments.
  77. partialobject *part = (partialobject *)func;
  78. if (part->dict == NULL) {
  79. pargs = part->args;
  80. pkw = part->kw;
  81. func = part->fn;
  82. assert(PyTuple_Check(pargs));
  83. assert(PyDict_Check(pkw));
  84. }
  85. }
  86. if (!PyCallable_Check(func)) {
  87. PyErr_SetString(PyExc_TypeError,
  88. "the first argument must be callable");
  89. return NULL;
  90. }
  91. /* create partialobject structure */
  92. pto = (partialobject *)type->tp_alloc(type, 0);
  93. if (pto == NULL)
  94. return NULL;
  95. pto->fn = Py_NewRef(func);
  96. nargs = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
  97. if (nargs == NULL) {
  98. Py_DECREF(pto);
  99. return NULL;
  100. }
  101. if (pargs == NULL) {
  102. pto->args = nargs;
  103. }
  104. else {
  105. pto->args = PySequence_Concat(pargs, nargs);
  106. Py_DECREF(nargs);
  107. if (pto->args == NULL) {
  108. Py_DECREF(pto);
  109. return NULL;
  110. }
  111. assert(PyTuple_Check(pto->args));
  112. }
  113. if (pkw == NULL || PyDict_GET_SIZE(pkw) == 0) {
  114. if (kw == NULL) {
  115. pto->kw = PyDict_New();
  116. }
  117. else if (Py_REFCNT(kw) == 1) {
  118. pto->kw = Py_NewRef(kw);
  119. }
  120. else {
  121. pto->kw = PyDict_Copy(kw);
  122. }
  123. }
  124. else {
  125. pto->kw = PyDict_Copy(pkw);
  126. if (kw != NULL && pto->kw != NULL) {
  127. if (PyDict_Merge(pto->kw, kw, 1) != 0) {
  128. Py_DECREF(pto);
  129. return NULL;
  130. }
  131. }
  132. }
  133. if (pto->kw == NULL) {
  134. Py_DECREF(pto);
  135. return NULL;
  136. }
  137. partial_setvectorcall(pto);
  138. return (PyObject *)pto;
  139. }
  140. static int
  141. partial_clear(partialobject *pto)
  142. {
  143. Py_CLEAR(pto->fn);
  144. Py_CLEAR(pto->args);
  145. Py_CLEAR(pto->kw);
  146. Py_CLEAR(pto->dict);
  147. return 0;
  148. }
  149. static int
  150. partial_traverse(partialobject *pto, visitproc visit, void *arg)
  151. {
  152. Py_VISIT(Py_TYPE(pto));
  153. Py_VISIT(pto->fn);
  154. Py_VISIT(pto->args);
  155. Py_VISIT(pto->kw);
  156. Py_VISIT(pto->dict);
  157. return 0;
  158. }
  159. static void
  160. partial_dealloc(partialobject *pto)
  161. {
  162. PyTypeObject *tp = Py_TYPE(pto);
  163. /* bpo-31095: UnTrack is needed before calling any callbacks */
  164. PyObject_GC_UnTrack(pto);
  165. if (pto->weakreflist != NULL) {
  166. PyObject_ClearWeakRefs((PyObject *) pto);
  167. }
  168. (void)partial_clear(pto);
  169. tp->tp_free(pto);
  170. Py_DECREF(tp);
  171. }
  172. /* Merging keyword arguments using the vectorcall convention is messy, so
  173. * if we would need to do that, we stop using vectorcall and fall back
  174. * to using partial_call() instead. */
  175. Py_NO_INLINE static PyObject *
  176. partial_vectorcall_fallback(PyThreadState *tstate, partialobject *pto,
  177. PyObject *const *args, size_t nargsf,
  178. PyObject *kwnames)
  179. {
  180. pto->vectorcall = NULL;
  181. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  182. return _PyObject_MakeTpCall(tstate, (PyObject *)pto,
  183. args, nargs, kwnames);
  184. }
  185. static PyObject *
  186. partial_vectorcall(partialobject *pto, PyObject *const *args,
  187. size_t nargsf, PyObject *kwnames)
  188. {
  189. PyThreadState *tstate = _PyThreadState_GET();
  190. /* pto->kw is mutable, so need to check every time */
  191. if (PyDict_GET_SIZE(pto->kw)) {
  192. return partial_vectorcall_fallback(tstate, pto, args, nargsf, kwnames);
  193. }
  194. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  195. Py_ssize_t nargs_total = nargs;
  196. if (kwnames != NULL) {
  197. nargs_total += PyTuple_GET_SIZE(kwnames);
  198. }
  199. PyObject **pto_args = _PyTuple_ITEMS(pto->args);
  200. Py_ssize_t pto_nargs = PyTuple_GET_SIZE(pto->args);
  201. /* Fast path if we're called without arguments */
  202. if (nargs_total == 0) {
  203. return _PyObject_VectorcallTstate(tstate, pto->fn,
  204. pto_args, pto_nargs, NULL);
  205. }
  206. /* Fast path using PY_VECTORCALL_ARGUMENTS_OFFSET to prepend a single
  207. * positional argument */
  208. if (pto_nargs == 1 && (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET)) {
  209. PyObject **newargs = (PyObject **)args - 1;
  210. PyObject *tmp = newargs[0];
  211. newargs[0] = pto_args[0];
  212. PyObject *ret = _PyObject_VectorcallTstate(tstate, pto->fn,
  213. newargs, nargs + 1, kwnames);
  214. newargs[0] = tmp;
  215. return ret;
  216. }
  217. Py_ssize_t newnargs_total = pto_nargs + nargs_total;
  218. PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
  219. PyObject *ret;
  220. PyObject **stack;
  221. if (newnargs_total <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
  222. stack = small_stack;
  223. }
  224. else {
  225. stack = PyMem_Malloc(newnargs_total * sizeof(PyObject *));
  226. if (stack == NULL) {
  227. PyErr_NoMemory();
  228. return NULL;
  229. }
  230. }
  231. /* Copy to new stack, using borrowed references */
  232. memcpy(stack, pto_args, pto_nargs * sizeof(PyObject*));
  233. memcpy(stack + pto_nargs, args, nargs_total * sizeof(PyObject*));
  234. ret = _PyObject_VectorcallTstate(tstate, pto->fn,
  235. stack, pto_nargs + nargs, kwnames);
  236. if (stack != small_stack) {
  237. PyMem_Free(stack);
  238. }
  239. return ret;
  240. }
  241. /* Set pto->vectorcall depending on the parameters of the partial object */
  242. static void
  243. partial_setvectorcall(partialobject *pto)
  244. {
  245. if (_PyVectorcall_Function(pto->fn) == NULL) {
  246. /* Don't use vectorcall if the underlying function doesn't support it */
  247. pto->vectorcall = NULL;
  248. }
  249. /* We could have a special case if there are no arguments,
  250. * but that is unlikely (why use partial without arguments?),
  251. * so we don't optimize that */
  252. else {
  253. pto->vectorcall = (vectorcallfunc)partial_vectorcall;
  254. }
  255. }
  256. // Not converted to argument clinic, because of `*args, **kwargs` arguments.
  257. static PyObject *
  258. partial_call(partialobject *pto, PyObject *args, PyObject *kwargs)
  259. {
  260. assert(PyCallable_Check(pto->fn));
  261. assert(PyTuple_Check(pto->args));
  262. assert(PyDict_Check(pto->kw));
  263. /* Merge keywords */
  264. PyObject *kwargs2;
  265. if (PyDict_GET_SIZE(pto->kw) == 0) {
  266. /* kwargs can be NULL */
  267. kwargs2 = Py_XNewRef(kwargs);
  268. }
  269. else {
  270. /* bpo-27840, bpo-29318: dictionary of keyword parameters must be
  271. copied, because a function using "**kwargs" can modify the
  272. dictionary. */
  273. kwargs2 = PyDict_Copy(pto->kw);
  274. if (kwargs2 == NULL) {
  275. return NULL;
  276. }
  277. if (kwargs != NULL) {
  278. if (PyDict_Merge(kwargs2, kwargs, 1) != 0) {
  279. Py_DECREF(kwargs2);
  280. return NULL;
  281. }
  282. }
  283. }
  284. /* Merge positional arguments */
  285. /* Note: tupleconcat() is optimized for empty tuples */
  286. PyObject *args2 = PySequence_Concat(pto->args, args);
  287. if (args2 == NULL) {
  288. Py_XDECREF(kwargs2);
  289. return NULL;
  290. }
  291. PyObject *res = PyObject_Call(pto->fn, args2, kwargs2);
  292. Py_DECREF(args2);
  293. Py_XDECREF(kwargs2);
  294. return res;
  295. }
  296. PyDoc_STRVAR(partial_doc,
  297. "partial(func, *args, **keywords) - new function with partial application\n\
  298. of the given arguments and keywords.\n");
  299. #define OFF(x) offsetof(partialobject, x)
  300. static PyMemberDef partial_memberlist[] = {
  301. {"func", T_OBJECT, OFF(fn), READONLY,
  302. "function object to use in future partial calls"},
  303. {"args", T_OBJECT, OFF(args), READONLY,
  304. "tuple of arguments to future partial calls"},
  305. {"keywords", T_OBJECT, OFF(kw), READONLY,
  306. "dictionary of keyword arguments to future partial calls"},
  307. {"__weaklistoffset__", T_PYSSIZET,
  308. offsetof(partialobject, weakreflist), READONLY},
  309. {"__dictoffset__", T_PYSSIZET,
  310. offsetof(partialobject, dict), READONLY},
  311. {"__vectorcalloffset__", T_PYSSIZET,
  312. offsetof(partialobject, vectorcall), READONLY},
  313. {NULL} /* Sentinel */
  314. };
  315. static PyGetSetDef partial_getsetlist[] = {
  316. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  317. {NULL} /* Sentinel */
  318. };
  319. static PyObject *
  320. partial_repr(partialobject *pto)
  321. {
  322. PyObject *result = NULL;
  323. PyObject *arglist;
  324. Py_ssize_t i, n;
  325. PyObject *key, *value;
  326. int status;
  327. status = Py_ReprEnter((PyObject *)pto);
  328. if (status != 0) {
  329. if (status < 0)
  330. return NULL;
  331. return PyUnicode_FromString("...");
  332. }
  333. arglist = PyUnicode_FromString("");
  334. if (arglist == NULL)
  335. goto done;
  336. /* Pack positional arguments */
  337. assert (PyTuple_Check(pto->args));
  338. n = PyTuple_GET_SIZE(pto->args);
  339. for (i = 0; i < n; i++) {
  340. Py_SETREF(arglist, PyUnicode_FromFormat("%U, %R", arglist,
  341. PyTuple_GET_ITEM(pto->args, i)));
  342. if (arglist == NULL)
  343. goto done;
  344. }
  345. /* Pack keyword arguments */
  346. assert (PyDict_Check(pto->kw));
  347. for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
  348. /* Prevent key.__str__ from deleting the value. */
  349. Py_INCREF(value);
  350. Py_SETREF(arglist, PyUnicode_FromFormat("%U, %S=%R", arglist,
  351. key, value));
  352. Py_DECREF(value);
  353. if (arglist == NULL)
  354. goto done;
  355. }
  356. result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
  357. pto->fn, arglist);
  358. Py_DECREF(arglist);
  359. done:
  360. Py_ReprLeave((PyObject *)pto);
  361. return result;
  362. }
  363. /* Pickle strategy:
  364. __reduce__ by itself doesn't support getting kwargs in the unpickle
  365. operation so we define a __setstate__ that replaces all the information
  366. about the partial. If we only replaced part of it someone would use
  367. it as a hook to do strange things.
  368. */
  369. static PyObject *
  370. partial_reduce(partialobject *pto, PyObject *unused)
  371. {
  372. return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
  373. pto->args, pto->kw,
  374. pto->dict ? pto->dict : Py_None);
  375. }
  376. static PyObject *
  377. partial_setstate(partialobject *pto, PyObject *state)
  378. {
  379. PyObject *fn, *fnargs, *kw, *dict;
  380. if (!PyTuple_Check(state) ||
  381. !PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) ||
  382. !PyCallable_Check(fn) ||
  383. !PyTuple_Check(fnargs) ||
  384. (kw != Py_None && !PyDict_Check(kw)))
  385. {
  386. PyErr_SetString(PyExc_TypeError, "invalid partial state");
  387. return NULL;
  388. }
  389. if(!PyTuple_CheckExact(fnargs))
  390. fnargs = PySequence_Tuple(fnargs);
  391. else
  392. Py_INCREF(fnargs);
  393. if (fnargs == NULL)
  394. return NULL;
  395. if (kw == Py_None)
  396. kw = PyDict_New();
  397. else if(!PyDict_CheckExact(kw))
  398. kw = PyDict_Copy(kw);
  399. else
  400. Py_INCREF(kw);
  401. if (kw == NULL) {
  402. Py_DECREF(fnargs);
  403. return NULL;
  404. }
  405. if (dict == Py_None)
  406. dict = NULL;
  407. else
  408. Py_INCREF(dict);
  409. Py_SETREF(pto->fn, Py_NewRef(fn));
  410. Py_SETREF(pto->args, fnargs);
  411. Py_SETREF(pto->kw, kw);
  412. Py_XSETREF(pto->dict, dict);
  413. partial_setvectorcall(pto);
  414. Py_RETURN_NONE;
  415. }
  416. static PyMethodDef partial_methods[] = {
  417. {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
  418. {"__setstate__", (PyCFunction)partial_setstate, METH_O},
  419. {"__class_getitem__", Py_GenericAlias,
  420. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  421. {NULL, NULL} /* sentinel */
  422. };
  423. static PyType_Slot partial_type_slots[] = {
  424. {Py_tp_dealloc, partial_dealloc},
  425. {Py_tp_repr, partial_repr},
  426. {Py_tp_call, partial_call},
  427. {Py_tp_getattro, PyObject_GenericGetAttr},
  428. {Py_tp_setattro, PyObject_GenericSetAttr},
  429. {Py_tp_doc, (void *)partial_doc},
  430. {Py_tp_traverse, partial_traverse},
  431. {Py_tp_clear, partial_clear},
  432. {Py_tp_methods, partial_methods},
  433. {Py_tp_members, partial_memberlist},
  434. {Py_tp_getset, partial_getsetlist},
  435. {Py_tp_new, partial_new},
  436. {Py_tp_free, PyObject_GC_Del},
  437. {0, 0}
  438. };
  439. static PyType_Spec partial_type_spec = {
  440. .name = "functools.partial",
  441. .basicsize = sizeof(partialobject),
  442. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  443. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL |
  444. Py_TPFLAGS_IMMUTABLETYPE,
  445. .slots = partial_type_slots
  446. };
  447. /* cmp_to_key ***************************************************************/
  448. typedef struct {
  449. PyObject_HEAD
  450. PyObject *cmp;
  451. PyObject *object;
  452. } keyobject;
  453. static int
  454. keyobject_clear(keyobject *ko)
  455. {
  456. Py_CLEAR(ko->cmp);
  457. Py_CLEAR(ko->object);
  458. return 0;
  459. }
  460. static void
  461. keyobject_dealloc(keyobject *ko)
  462. {
  463. PyTypeObject *tp = Py_TYPE(ko);
  464. PyObject_GC_UnTrack(ko);
  465. (void)keyobject_clear(ko);
  466. tp->tp_free(ko);
  467. Py_DECREF(tp);
  468. }
  469. static int
  470. keyobject_traverse(keyobject *ko, visitproc visit, void *arg)
  471. {
  472. Py_VISIT(Py_TYPE(ko));
  473. Py_VISIT(ko->cmp);
  474. Py_VISIT(ko->object);
  475. return 0;
  476. }
  477. static PyMemberDef keyobject_members[] = {
  478. {"obj", T_OBJECT,
  479. offsetof(keyobject, object), 0,
  480. PyDoc_STR("Value wrapped by a key function.")},
  481. {NULL}
  482. };
  483. static PyObject *
  484. keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds);
  485. static PyObject *
  486. keyobject_richcompare(PyObject *ko, PyObject *other, int op);
  487. static PyType_Slot keyobject_type_slots[] = {
  488. {Py_tp_dealloc, keyobject_dealloc},
  489. {Py_tp_call, keyobject_call},
  490. {Py_tp_getattro, PyObject_GenericGetAttr},
  491. {Py_tp_traverse, keyobject_traverse},
  492. {Py_tp_clear, keyobject_clear},
  493. {Py_tp_richcompare, keyobject_richcompare},
  494. {Py_tp_members, keyobject_members},
  495. {0, 0}
  496. };
  497. static PyType_Spec keyobject_type_spec = {
  498. .name = "functools.KeyWrapper",
  499. .basicsize = sizeof(keyobject),
  500. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
  501. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  502. .slots = keyobject_type_slots
  503. };
  504. static PyObject *
  505. keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds)
  506. {
  507. PyObject *object;
  508. keyobject *result;
  509. static char *kwargs[] = {"obj", NULL};
  510. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:K", kwargs, &object))
  511. return NULL;
  512. result = PyObject_GC_New(keyobject, Py_TYPE(ko));
  513. if (result == NULL) {
  514. return NULL;
  515. }
  516. result->cmp = Py_NewRef(ko->cmp);
  517. result->object = Py_NewRef(object);
  518. PyObject_GC_Track(result);
  519. return (PyObject *)result;
  520. }
  521. static PyObject *
  522. keyobject_richcompare(PyObject *ko, PyObject *other, int op)
  523. {
  524. PyObject *res;
  525. PyObject *x;
  526. PyObject *y;
  527. PyObject *compare;
  528. PyObject *answer;
  529. PyObject* stack[2];
  530. if (!Py_IS_TYPE(other, Py_TYPE(ko))) {
  531. PyErr_Format(PyExc_TypeError, "other argument must be K instance");
  532. return NULL;
  533. }
  534. compare = ((keyobject *) ko)->cmp;
  535. assert(compare != NULL);
  536. x = ((keyobject *) ko)->object;
  537. y = ((keyobject *) other)->object;
  538. if (!x || !y){
  539. PyErr_Format(PyExc_AttributeError, "object");
  540. return NULL;
  541. }
  542. /* Call the user's comparison function and translate the 3-way
  543. * result into true or false (or error).
  544. */
  545. stack[0] = x;
  546. stack[1] = y;
  547. res = _PyObject_FastCall(compare, stack, 2);
  548. if (res == NULL) {
  549. return NULL;
  550. }
  551. answer = PyObject_RichCompare(res, _PyLong_GetZero(), op);
  552. Py_DECREF(res);
  553. return answer;
  554. }
  555. /*[clinic input]
  556. _functools.cmp_to_key
  557. mycmp: object
  558. Function that compares two objects.
  559. Convert a cmp= function into a key= function.
  560. [clinic start generated code]*/
  561. static PyObject *
  562. _functools_cmp_to_key_impl(PyObject *module, PyObject *mycmp)
  563. /*[clinic end generated code: output=71eaad0f4fc81f33 input=d1b76f231c0dfeb3]*/
  564. {
  565. keyobject *object;
  566. _functools_state *state;
  567. state = get_functools_state(module);
  568. object = PyObject_GC_New(keyobject, state->keyobject_type);
  569. if (!object)
  570. return NULL;
  571. object->cmp = Py_NewRef(mycmp);
  572. object->object = NULL;
  573. PyObject_GC_Track(object);
  574. return (PyObject *)object;
  575. }
  576. /* reduce (used to be a builtin) ********************************************/
  577. // Not converted to argument clinic, because of `args` in-place modification.
  578. // AC will affect performance.
  579. static PyObject *
  580. functools_reduce(PyObject *self, PyObject *args)
  581. {
  582. PyObject *seq, *func, *result = NULL, *it;
  583. if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
  584. return NULL;
  585. if (result != NULL)
  586. Py_INCREF(result);
  587. it = PyObject_GetIter(seq);
  588. if (it == NULL) {
  589. if (PyErr_ExceptionMatches(PyExc_TypeError))
  590. PyErr_SetString(PyExc_TypeError,
  591. "reduce() arg 2 must support iteration");
  592. Py_XDECREF(result);
  593. return NULL;
  594. }
  595. if ((args = PyTuple_New(2)) == NULL)
  596. goto Fail;
  597. for (;;) {
  598. PyObject *op2;
  599. if (Py_REFCNT(args) > 1) {
  600. Py_DECREF(args);
  601. if ((args = PyTuple_New(2)) == NULL)
  602. goto Fail;
  603. }
  604. op2 = PyIter_Next(it);
  605. if (op2 == NULL) {
  606. if (PyErr_Occurred())
  607. goto Fail;
  608. break;
  609. }
  610. if (result == NULL)
  611. result = op2;
  612. else {
  613. /* Update the args tuple in-place */
  614. assert(Py_REFCNT(args) == 1);
  615. Py_XSETREF(_PyTuple_ITEMS(args)[0], result);
  616. Py_XSETREF(_PyTuple_ITEMS(args)[1], op2);
  617. if ((result = PyObject_Call(func, args, NULL)) == NULL) {
  618. goto Fail;
  619. }
  620. // bpo-42536: The GC may have untracked this args tuple. Since we're
  621. // recycling it, make sure it's tracked again:
  622. if (!_PyObject_GC_IS_TRACKED(args)) {
  623. _PyObject_GC_TRACK(args);
  624. }
  625. }
  626. }
  627. Py_DECREF(args);
  628. if (result == NULL)
  629. PyErr_SetString(PyExc_TypeError,
  630. "reduce() of empty iterable with no initial value");
  631. Py_DECREF(it);
  632. return result;
  633. Fail:
  634. Py_XDECREF(args);
  635. Py_XDECREF(result);
  636. Py_DECREF(it);
  637. return NULL;
  638. }
  639. PyDoc_STRVAR(functools_reduce_doc,
  640. "reduce(function, iterable[, initial]) -> value\n\
  641. \n\
  642. Apply a function of two arguments cumulatively to the items of a sequence\n\
  643. or iterable, from left to right, so as to reduce the iterable to a single\n\
  644. value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
  645. ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
  646. of the iterable in the calculation, and serves as a default when the\n\
  647. iterable is empty.");
  648. /* lru_cache object **********************************************************/
  649. /* There are four principal algorithmic differences from the pure python version:
  650. 1). The C version relies on the GIL instead of having its own reentrant lock.
  651. 2). The prev/next link fields use borrowed references.
  652. 3). For a full cache, the pure python version rotates the location of the
  653. root entry so that it never has to move individual links and it can
  654. limit updates to just the key and result fields. However, in the C
  655. version, links are temporarily removed while the cache dict updates are
  656. occurring. Afterwards, they are appended or prepended back into the
  657. doubly-linked lists.
  658. 4) In the Python version, the _HashSeq class is used to prevent __hash__
  659. from being called more than once. In the C version, the "known hash"
  660. variants of dictionary calls as used to the same effect.
  661. */
  662. struct lru_list_elem;
  663. struct lru_cache_object;
  664. typedef struct lru_list_elem {
  665. PyObject_HEAD
  666. struct lru_list_elem *prev, *next; /* borrowed links */
  667. Py_hash_t hash;
  668. PyObject *key, *result;
  669. } lru_list_elem;
  670. static void
  671. lru_list_elem_dealloc(lru_list_elem *link)
  672. {
  673. PyTypeObject *tp = Py_TYPE(link);
  674. Py_XDECREF(link->key);
  675. Py_XDECREF(link->result);
  676. tp->tp_free(link);
  677. Py_DECREF(tp);
  678. }
  679. static PyType_Slot lru_list_elem_type_slots[] = {
  680. {Py_tp_dealloc, lru_list_elem_dealloc},
  681. {0, 0}
  682. };
  683. static PyType_Spec lru_list_elem_type_spec = {
  684. .name = "functools._lru_list_elem",
  685. .basicsize = sizeof(lru_list_elem),
  686. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
  687. Py_TPFLAGS_IMMUTABLETYPE,
  688. .slots = lru_list_elem_type_slots
  689. };
  690. typedef PyObject *(*lru_cache_ternaryfunc)(struct lru_cache_object *, PyObject *, PyObject *);
  691. typedef struct lru_cache_object {
  692. lru_list_elem root; /* includes PyObject_HEAD */
  693. lru_cache_ternaryfunc wrapper;
  694. int typed;
  695. PyObject *cache;
  696. Py_ssize_t hits;
  697. PyObject *func;
  698. Py_ssize_t maxsize;
  699. Py_ssize_t misses;
  700. /* the kwd_mark is used delimit args and keywords in the cache keys */
  701. PyObject *kwd_mark;
  702. PyTypeObject *lru_list_elem_type;
  703. PyObject *cache_info_type;
  704. PyObject *dict;
  705. PyObject *weakreflist;
  706. } lru_cache_object;
  707. static PyObject *
  708. lru_cache_make_key(PyObject *kwd_mark, PyObject *args,
  709. PyObject *kwds, int typed)
  710. {
  711. PyObject *key, *keyword, *value;
  712. Py_ssize_t key_size, pos, key_pos, kwds_size;
  713. kwds_size = kwds ? PyDict_GET_SIZE(kwds) : 0;
  714. /* short path, key will match args anyway, which is a tuple */
  715. if (!typed && !kwds_size) {
  716. if (PyTuple_GET_SIZE(args) == 1) {
  717. key = PyTuple_GET_ITEM(args, 0);
  718. if (PyUnicode_CheckExact(key) || PyLong_CheckExact(key)) {
  719. /* For common scalar keys, save space by
  720. dropping the enclosing args tuple */
  721. return Py_NewRef(key);
  722. }
  723. }
  724. return Py_NewRef(args);
  725. }
  726. key_size = PyTuple_GET_SIZE(args);
  727. if (kwds_size)
  728. key_size += kwds_size * 2 + 1;
  729. if (typed)
  730. key_size += PyTuple_GET_SIZE(args) + kwds_size;
  731. key = PyTuple_New(key_size);
  732. if (key == NULL)
  733. return NULL;
  734. key_pos = 0;
  735. for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
  736. PyObject *item = PyTuple_GET_ITEM(args, pos);
  737. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
  738. }
  739. if (kwds_size) {
  740. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(kwd_mark));
  741. for (pos = 0; PyDict_Next(kwds, &pos, &keyword, &value);) {
  742. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(keyword));
  743. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(value));
  744. }
  745. assert(key_pos == PyTuple_GET_SIZE(args) + kwds_size * 2 + 1);
  746. }
  747. if (typed) {
  748. for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
  749. PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(args, pos));
  750. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
  751. }
  752. if (kwds_size) {
  753. for (pos = 0; PyDict_Next(kwds, &pos, &keyword, &value);) {
  754. PyObject *item = (PyObject *)Py_TYPE(value);
  755. PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
  756. }
  757. }
  758. }
  759. assert(key_pos == key_size);
  760. return key;
  761. }
  762. static PyObject *
  763. uncached_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
  764. {
  765. PyObject *result;
  766. self->misses++;
  767. result = PyObject_Call(self->func, args, kwds);
  768. if (!result)
  769. return NULL;
  770. return result;
  771. }
  772. static PyObject *
  773. infinite_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
  774. {
  775. PyObject *result;
  776. Py_hash_t hash;
  777. PyObject *key = lru_cache_make_key(self->kwd_mark, args, kwds, self->typed);
  778. if (!key)
  779. return NULL;
  780. hash = PyObject_Hash(key);
  781. if (hash == -1) {
  782. Py_DECREF(key);
  783. return NULL;
  784. }
  785. result = _PyDict_GetItem_KnownHash(self->cache, key, hash);
  786. if (result) {
  787. Py_INCREF(result);
  788. self->hits++;
  789. Py_DECREF(key);
  790. return result;
  791. }
  792. if (PyErr_Occurred()) {
  793. Py_DECREF(key);
  794. return NULL;
  795. }
  796. self->misses++;
  797. result = PyObject_Call(self->func, args, kwds);
  798. if (!result) {
  799. Py_DECREF(key);
  800. return NULL;
  801. }
  802. if (_PyDict_SetItem_KnownHash(self->cache, key, result, hash) < 0) {
  803. Py_DECREF(result);
  804. Py_DECREF(key);
  805. return NULL;
  806. }
  807. Py_DECREF(key);
  808. return result;
  809. }
  810. static void
  811. lru_cache_extract_link(lru_list_elem *link)
  812. {
  813. lru_list_elem *link_prev = link->prev;
  814. lru_list_elem *link_next = link->next;
  815. link_prev->next = link->next;
  816. link_next->prev = link->prev;
  817. }
  818. static void
  819. lru_cache_append_link(lru_cache_object *self, lru_list_elem *link)
  820. {
  821. lru_list_elem *root = &self->root;
  822. lru_list_elem *last = root->prev;
  823. last->next = root->prev = link;
  824. link->prev = last;
  825. link->next = root;
  826. }
  827. static void
  828. lru_cache_prepend_link(lru_cache_object *self, lru_list_elem *link)
  829. {
  830. lru_list_elem *root = &self->root;
  831. lru_list_elem *first = root->next;
  832. first->prev = root->next = link;
  833. link->prev = root;
  834. link->next = first;
  835. }
  836. /* General note on reentrancy:
  837. There are four dictionary calls in the bounded_lru_cache_wrapper():
  838. 1) The initial check for a cache match. 2) The post user-function
  839. check for a cache match. 3) The deletion of the oldest entry.
  840. 4) The addition of the newest entry.
  841. In all four calls, we have a known hash which lets use avoid a call
  842. to __hash__(). That leaves only __eq__ as a possible source of a
  843. reentrant call.
  844. The __eq__ method call is always made for a cache hit (dict access #1).
  845. Accordingly, we have make sure not modify the cache state prior to
  846. this call.
  847. The __eq__ method call is never made for the deletion (dict access #3)
  848. because it is an identity match.
  849. For the other two accesses (#2 and #4), calls to __eq__ only occur
  850. when some other entry happens to have an exactly matching hash (all
  851. 64-bits). Though rare, this can happen, so we have to make sure to
  852. either call it at the top of its code path before any cache
  853. state modifications (dict access #2) or be prepared to restore
  854. invariants at the end of the code path (dict access #4).
  855. Another possible source of reentrancy is a decref which can trigger
  856. arbitrary code execution. To make the code easier to reason about,
  857. the decrefs are deferred to the end of the each possible code path
  858. so that we know the cache is a consistent state.
  859. */
  860. static PyObject *
  861. bounded_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
  862. {
  863. lru_list_elem *link;
  864. PyObject *key, *result, *testresult;
  865. Py_hash_t hash;
  866. key = lru_cache_make_key(self->kwd_mark, args, kwds, self->typed);
  867. if (!key)
  868. return NULL;
  869. hash = PyObject_Hash(key);
  870. if (hash == -1) {
  871. Py_DECREF(key);
  872. return NULL;
  873. }
  874. link = (lru_list_elem *)_PyDict_GetItem_KnownHash(self->cache, key, hash);
  875. if (link != NULL) {
  876. lru_cache_extract_link(link);
  877. lru_cache_append_link(self, link);
  878. result = link->result;
  879. self->hits++;
  880. Py_INCREF(result);
  881. Py_DECREF(key);
  882. return result;
  883. }
  884. if (PyErr_Occurred()) {
  885. Py_DECREF(key);
  886. return NULL;
  887. }
  888. self->misses++;
  889. result = PyObject_Call(self->func, args, kwds);
  890. if (!result) {
  891. Py_DECREF(key);
  892. return NULL;
  893. }
  894. testresult = _PyDict_GetItem_KnownHash(self->cache, key, hash);
  895. if (testresult != NULL) {
  896. /* Getting here means that this same key was added to the cache
  897. during the PyObject_Call(). Since the link update is already
  898. done, we need only return the computed result. */
  899. Py_DECREF(key);
  900. return result;
  901. }
  902. if (PyErr_Occurred()) {
  903. /* This is an unusual case since this same lookup
  904. did not previously trigger an error during lookup.
  905. Treat it the same as an error in user function
  906. and return with the error set. */
  907. Py_DECREF(key);
  908. Py_DECREF(result);
  909. return NULL;
  910. }
  911. /* This is the normal case. The new key wasn't found before
  912. user function call and it is still not there. So we
  913. proceed normally and update the cache with the new result. */
  914. assert(self->maxsize > 0);
  915. if (PyDict_GET_SIZE(self->cache) < self->maxsize ||
  916. self->root.next == &self->root)
  917. {
  918. /* Cache is not full, so put the result in a new link */
  919. link = (lru_list_elem *)PyObject_New(lru_list_elem,
  920. self->lru_list_elem_type);
  921. if (link == NULL) {
  922. Py_DECREF(key);
  923. Py_DECREF(result);
  924. return NULL;
  925. }
  926. link->hash = hash;
  927. link->key = key;
  928. link->result = result;
  929. /* What is really needed here is a SetItem variant with a "no clobber"
  930. option. If the __eq__ call triggers a reentrant call that adds
  931. this same key, then this setitem call will update the cache dict
  932. with this new link, leaving the old link as an orphan (i.e. not
  933. having a cache dict entry that refers to it). */
  934. if (_PyDict_SetItem_KnownHash(self->cache, key, (PyObject *)link,
  935. hash) < 0) {
  936. Py_DECREF(link);
  937. return NULL;
  938. }
  939. lru_cache_append_link(self, link);
  940. return Py_NewRef(result);
  941. }
  942. /* Since the cache is full, we need to evict an old key and add
  943. a new key. Rather than free the old link and allocate a new
  944. one, we reuse the link for the new key and result and move it
  945. to front of the cache to mark it as recently used.
  946. We try to assure all code paths (including errors) leave all
  947. of the links in place. Either the link is successfully
  948. updated and moved or it is restored to its old position.
  949. However if an unrecoverable error is found, it doesn't
  950. make sense to reinsert the link, so we leave it out
  951. and the cache will no longer register as full.
  952. */
  953. PyObject *oldkey, *oldresult, *popresult;
  954. /* Extract the oldest item. */
  955. assert(self->root.next != &self->root);
  956. link = self->root.next;
  957. lru_cache_extract_link(link);
  958. /* Remove it from the cache.
  959. The cache dict holds one reference to the link.
  960. We created one other reference when the link was created.
  961. The linked list only has borrowed references. */
  962. popresult = _PyDict_Pop_KnownHash(self->cache, link->key,
  963. link->hash, Py_None);
  964. if (popresult == Py_None) {
  965. /* Getting here means that the user function call or another
  966. thread has already removed the old key from the dictionary.
  967. This link is now an orphan. Since we don't want to leave the
  968. cache in an inconsistent state, we don't restore the link. */
  969. Py_DECREF(popresult);
  970. Py_DECREF(link);
  971. Py_DECREF(key);
  972. return result;
  973. }
  974. if (popresult == NULL) {
  975. /* An error arose while trying to remove the oldest key (the one
  976. being evicted) from the cache. We restore the link to its
  977. original position as the oldest link. Then we allow the
  978. error propagate upward; treating it the same as an error
  979. arising in the user function. */
  980. lru_cache_prepend_link(self, link);
  981. Py_DECREF(key);
  982. Py_DECREF(result);
  983. return NULL;
  984. }
  985. /* Keep a reference to the old key and old result to prevent their
  986. ref counts from going to zero during the update. That will
  987. prevent potentially arbitrary object clean-up code (i.e. __del__)
  988. from running while we're still adjusting the links. */
  989. oldkey = link->key;
  990. oldresult = link->result;
  991. link->hash = hash;
  992. link->key = key;
  993. link->result = result;
  994. /* Note: The link is being added to the cache dict without the
  995. prev and next fields set to valid values. We have to wait
  996. for successful insertion in the cache dict before adding the
  997. link to the linked list. Otherwise, the potentially reentrant
  998. __eq__ call could cause the then orphan link to be visited. */
  999. if (_PyDict_SetItem_KnownHash(self->cache, key, (PyObject *)link,
  1000. hash) < 0) {
  1001. /* Somehow the cache dict update failed. We no longer can
  1002. restore the old link. Let the error propagate upward and
  1003. leave the cache short one link. */
  1004. Py_DECREF(popresult);
  1005. Py_DECREF(link);
  1006. Py_DECREF(oldkey);
  1007. Py_DECREF(oldresult);
  1008. return NULL;
  1009. }
  1010. lru_cache_append_link(self, link);
  1011. Py_INCREF(result); /* for return */
  1012. Py_DECREF(popresult);
  1013. Py_DECREF(oldkey);
  1014. Py_DECREF(oldresult);
  1015. return result;
  1016. }
  1017. static PyObject *
  1018. lru_cache_new(PyTypeObject *type, PyObject *args, PyObject *kw)
  1019. {
  1020. PyObject *func, *maxsize_O, *cache_info_type, *cachedict;
  1021. int typed;
  1022. lru_cache_object *obj;
  1023. Py_ssize_t maxsize;
  1024. PyObject *(*wrapper)(lru_cache_object *, PyObject *, PyObject *);
  1025. _functools_state *state;
  1026. static char *keywords[] = {"user_function", "maxsize", "typed",
  1027. "cache_info_type", NULL};
  1028. if (!PyArg_ParseTupleAndKeywords(args, kw, "OOpO:lru_cache", keywords,
  1029. &func, &maxsize_O, &typed,
  1030. &cache_info_type)) {
  1031. return NULL;
  1032. }
  1033. if (!PyCallable_Check(func)) {
  1034. PyErr_SetString(PyExc_TypeError,
  1035. "the first argument must be callable");
  1036. return NULL;
  1037. }
  1038. state = get_functools_state_by_type(type);
  1039. if (state == NULL) {
  1040. return NULL;
  1041. }
  1042. /* select the caching function, and make/inc maxsize_O */
  1043. if (maxsize_O == Py_None) {
  1044. wrapper = infinite_lru_cache_wrapper;
  1045. /* use this only to initialize lru_cache_object attribute maxsize */
  1046. maxsize = -1;
  1047. } else if (PyIndex_Check(maxsize_O)) {
  1048. maxsize = PyNumber_AsSsize_t(maxsize_O, PyExc_OverflowError);
  1049. if (maxsize == -1 && PyErr_Occurred())
  1050. return NULL;
  1051. if (maxsize < 0) {
  1052. maxsize = 0;
  1053. }
  1054. if (maxsize == 0)
  1055. wrapper = uncached_lru_cache_wrapper;
  1056. else
  1057. wrapper = bounded_lru_cache_wrapper;
  1058. } else {
  1059. PyErr_SetString(PyExc_TypeError, "maxsize should be integer or None");
  1060. return NULL;
  1061. }
  1062. if (!(cachedict = PyDict_New()))
  1063. return NULL;
  1064. obj = (lru_cache_object *)type->tp_alloc(type, 0);
  1065. if (obj == NULL) {
  1066. Py_DECREF(cachedict);
  1067. return NULL;
  1068. }
  1069. obj->root.prev = &obj->root;
  1070. obj->root.next = &obj->root;
  1071. obj->wrapper = wrapper;
  1072. obj->typed = typed;
  1073. obj->cache = cachedict;
  1074. obj->func = Py_NewRef(func);
  1075. obj->misses = obj->hits = 0;
  1076. obj->maxsize = maxsize;
  1077. obj->kwd_mark = Py_NewRef(state->kwd_mark);
  1078. obj->lru_list_elem_type = (PyTypeObject*)Py_NewRef(state->lru_list_elem_type);
  1079. obj->cache_info_type = Py_NewRef(cache_info_type);
  1080. obj->dict = NULL;
  1081. obj->weakreflist = NULL;
  1082. return (PyObject *)obj;
  1083. }
  1084. static lru_list_elem *
  1085. lru_cache_unlink_list(lru_cache_object *self)
  1086. {
  1087. lru_list_elem *root = &self->root;
  1088. lru_list_elem *link = root->next;
  1089. if (link == root)
  1090. return NULL;
  1091. root->prev->next = NULL;
  1092. root->next = root->prev = root;
  1093. return link;
  1094. }
  1095. static void
  1096. lru_cache_clear_list(lru_list_elem *link)
  1097. {
  1098. while (link != NULL) {
  1099. lru_list_elem *next = link->next;
  1100. Py_SETREF(link, next);
  1101. }
  1102. }
  1103. static int
  1104. lru_cache_tp_clear(lru_cache_object *self)
  1105. {
  1106. lru_list_elem *list = lru_cache_unlink_list(self);
  1107. Py_CLEAR(self->cache);
  1108. Py_CLEAR(self->func);
  1109. Py_CLEAR(self->kwd_mark);
  1110. Py_CLEAR(self->lru_list_elem_type);
  1111. Py_CLEAR(self->cache_info_type);
  1112. Py_CLEAR(self->dict);
  1113. lru_cache_clear_list(list);
  1114. return 0;
  1115. }
  1116. static void
  1117. lru_cache_dealloc(lru_cache_object *obj)
  1118. {
  1119. PyTypeObject *tp = Py_TYPE(obj);
  1120. /* bpo-31095: UnTrack is needed before calling any callbacks */
  1121. PyObject_GC_UnTrack(obj);
  1122. if (obj->weakreflist != NULL) {
  1123. PyObject_ClearWeakRefs((PyObject*)obj);
  1124. }
  1125. (void)lru_cache_tp_clear(obj);
  1126. tp->tp_free(obj);
  1127. Py_DECREF(tp);
  1128. }
  1129. static PyObject *
  1130. lru_cache_call(lru_cache_object *self, PyObject *args, PyObject *kwds)
  1131. {
  1132. return self->wrapper(self, args, kwds);
  1133. }
  1134. static PyObject *
  1135. lru_cache_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  1136. {
  1137. if (obj == Py_None || obj == NULL) {
  1138. return Py_NewRef(self);
  1139. }
  1140. return PyMethod_New(self, obj);
  1141. }
  1142. /*[clinic input]
  1143. _functools._lru_cache_wrapper.cache_info
  1144. Report cache statistics
  1145. [clinic start generated code]*/
  1146. static PyObject *
  1147. _functools__lru_cache_wrapper_cache_info_impl(PyObject *self)
  1148. /*[clinic end generated code: output=cc796a0b06dbd717 input=f05e5b6ebfe38645]*/
  1149. {
  1150. lru_cache_object *_self = (lru_cache_object *) self;
  1151. if (_self->maxsize == -1) {
  1152. return PyObject_CallFunction(_self->cache_info_type, "nnOn",
  1153. _self->hits, _self->misses, Py_None,
  1154. PyDict_GET_SIZE(_self->cache));
  1155. }
  1156. return PyObject_CallFunction(_self->cache_info_type, "nnnn",
  1157. _self->hits, _self->misses, _self->maxsize,
  1158. PyDict_GET_SIZE(_self->cache));
  1159. }
  1160. /*[clinic input]
  1161. _functools._lru_cache_wrapper.cache_clear
  1162. Clear the cache and cache statistics
  1163. [clinic start generated code]*/
  1164. static PyObject *
  1165. _functools__lru_cache_wrapper_cache_clear_impl(PyObject *self)
  1166. /*[clinic end generated code: output=58423b35efc3e381 input=6ca59dba09b12584]*/
  1167. {
  1168. lru_cache_object *_self = (lru_cache_object *) self;
  1169. lru_list_elem *list = lru_cache_unlink_list(_self);
  1170. _self->hits = _self->misses = 0;
  1171. PyDict_Clear(_self->cache);
  1172. lru_cache_clear_list(list);
  1173. Py_RETURN_NONE;
  1174. }
  1175. static PyObject *
  1176. lru_cache_reduce(PyObject *self, PyObject *unused)
  1177. {
  1178. return PyObject_GetAttrString(self, "__qualname__");
  1179. }
  1180. static PyObject *
  1181. lru_cache_copy(PyObject *self, PyObject *unused)
  1182. {
  1183. return Py_NewRef(self);
  1184. }
  1185. static PyObject *
  1186. lru_cache_deepcopy(PyObject *self, PyObject *unused)
  1187. {
  1188. return Py_NewRef(self);
  1189. }
  1190. static int
  1191. lru_cache_tp_traverse(lru_cache_object *self, visitproc visit, void *arg)
  1192. {
  1193. Py_VISIT(Py_TYPE(self));
  1194. lru_list_elem *link = self->root.next;
  1195. while (link != &self->root) {
  1196. lru_list_elem *next = link->next;
  1197. Py_VISIT(link->key);
  1198. Py_VISIT(link->result);
  1199. Py_VISIT(Py_TYPE(link));
  1200. link = next;
  1201. }
  1202. Py_VISIT(self->cache);
  1203. Py_VISIT(self->func);
  1204. Py_VISIT(self->kwd_mark);
  1205. Py_VISIT(self->lru_list_elem_type);
  1206. Py_VISIT(self->cache_info_type);
  1207. Py_VISIT(self->dict);
  1208. return 0;
  1209. }
  1210. PyDoc_STRVAR(lru_cache_doc,
  1211. "Create a cached callable that wraps another function.\n\
  1212. \n\
  1213. user_function: the function being cached\n\
  1214. \n\
  1215. maxsize: 0 for no caching\n\
  1216. None for unlimited cache size\n\
  1217. n for a bounded cache\n\
  1218. \n\
  1219. typed: False cache f(3) and f(3.0) as identical calls\n\
  1220. True cache f(3) and f(3.0) as distinct calls\n\
  1221. \n\
  1222. cache_info_type: namedtuple class with the fields:\n\
  1223. hits misses currsize maxsize\n"
  1224. );
  1225. static PyMethodDef lru_cache_methods[] = {
  1226. _FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_INFO_METHODDEF
  1227. _FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_CLEAR_METHODDEF
  1228. {"__reduce__", (PyCFunction)lru_cache_reduce, METH_NOARGS},
  1229. {"__copy__", (PyCFunction)lru_cache_copy, METH_VARARGS},
  1230. {"__deepcopy__", (PyCFunction)lru_cache_deepcopy, METH_VARARGS},
  1231. {NULL}
  1232. };
  1233. static PyGetSetDef lru_cache_getsetlist[] = {
  1234. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  1235. {NULL}
  1236. };
  1237. static PyMemberDef lru_cache_memberlist[] = {
  1238. {"__dictoffset__", T_PYSSIZET,
  1239. offsetof(lru_cache_object, dict), READONLY},
  1240. {"__weaklistoffset__", T_PYSSIZET,
  1241. offsetof(lru_cache_object, weakreflist), READONLY},
  1242. {NULL} /* Sentinel */
  1243. };
  1244. static PyType_Slot lru_cache_type_slots[] = {
  1245. {Py_tp_dealloc, lru_cache_dealloc},
  1246. {Py_tp_call, lru_cache_call},
  1247. {Py_tp_doc, (void *)lru_cache_doc},
  1248. {Py_tp_traverse, lru_cache_tp_traverse},
  1249. {Py_tp_clear, lru_cache_tp_clear},
  1250. {Py_tp_methods, lru_cache_methods},
  1251. {Py_tp_members, lru_cache_memberlist},
  1252. {Py_tp_getset, lru_cache_getsetlist},
  1253. {Py_tp_descr_get, lru_cache_descr_get},
  1254. {Py_tp_new, lru_cache_new},
  1255. {0, 0}
  1256. };
  1257. static PyType_Spec lru_cache_type_spec = {
  1258. .name = "functools._lru_cache_wrapper",
  1259. .basicsize = sizeof(lru_cache_object),
  1260. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1261. Py_TPFLAGS_METHOD_DESCRIPTOR | Py_TPFLAGS_IMMUTABLETYPE,
  1262. .slots = lru_cache_type_slots
  1263. };
  1264. /* module level code ********************************************************/
  1265. PyDoc_STRVAR(_functools_doc,
  1266. "Tools that operate on functions.");
  1267. static PyMethodDef _functools_methods[] = {
  1268. {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
  1269. _FUNCTOOLS_CMP_TO_KEY_METHODDEF
  1270. {NULL, NULL} /* sentinel */
  1271. };
  1272. static int
  1273. _functools_exec(PyObject *module)
  1274. {
  1275. _functools_state *state = get_functools_state(module);
  1276. state->kwd_mark = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
  1277. if (state->kwd_mark == NULL) {
  1278. return -1;
  1279. }
  1280. state->partial_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
  1281. &partial_type_spec, NULL);
  1282. if (state->partial_type == NULL) {
  1283. return -1;
  1284. }
  1285. if (PyModule_AddType(module, state->partial_type) < 0) {
  1286. return -1;
  1287. }
  1288. PyObject *lru_cache_type = PyType_FromModuleAndSpec(module,
  1289. &lru_cache_type_spec, NULL);
  1290. if (lru_cache_type == NULL) {
  1291. return -1;
  1292. }
  1293. if (PyModule_AddType(module, (PyTypeObject *)lru_cache_type) < 0) {
  1294. Py_DECREF(lru_cache_type);
  1295. return -1;
  1296. }
  1297. Py_DECREF(lru_cache_type);
  1298. state->keyobject_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
  1299. &keyobject_type_spec, NULL);
  1300. if (state->keyobject_type == NULL) {
  1301. return -1;
  1302. }
  1303. // keyobject_type is used only internally.
  1304. // So we don't expose it in module namespace.
  1305. state->lru_list_elem_type = (PyTypeObject *)PyType_FromModuleAndSpec(
  1306. module, &lru_list_elem_type_spec, NULL);
  1307. if (state->lru_list_elem_type == NULL) {
  1308. return -1;
  1309. }
  1310. // lru_list_elem is used only in _lru_cache_wrapper.
  1311. // So we don't expose it in module namespace.
  1312. return 0;
  1313. }
  1314. static int
  1315. _functools_traverse(PyObject *module, visitproc visit, void *arg)
  1316. {
  1317. _functools_state *state = get_functools_state(module);
  1318. Py_VISIT(state->kwd_mark);
  1319. Py_VISIT(state->partial_type);
  1320. Py_VISIT(state->keyobject_type);
  1321. Py_VISIT(state->lru_list_elem_type);
  1322. return 0;
  1323. }
  1324. static int
  1325. _functools_clear(PyObject *module)
  1326. {
  1327. _functools_state *state = get_functools_state(module);
  1328. Py_CLEAR(state->kwd_mark);
  1329. Py_CLEAR(state->partial_type);
  1330. Py_CLEAR(state->keyobject_type);
  1331. Py_CLEAR(state->lru_list_elem_type);
  1332. return 0;
  1333. }
  1334. static void
  1335. _functools_free(void *module)
  1336. {
  1337. _functools_clear((PyObject *)module);
  1338. }
  1339. static struct PyModuleDef_Slot _functools_slots[] = {
  1340. {Py_mod_exec, _functools_exec},
  1341. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1342. {0, NULL}
  1343. };
  1344. static struct PyModuleDef _functools_module = {
  1345. PyModuleDef_HEAD_INIT,
  1346. .m_name = "_functools",
  1347. .m_doc = _functools_doc,
  1348. .m_size = sizeof(_functools_state),
  1349. .m_methods = _functools_methods,
  1350. .m_slots = _functools_slots,
  1351. .m_traverse = _functools_traverse,
  1352. .m_clear = _functools_clear,
  1353. .m_free = _functools_free,
  1354. };
  1355. PyMODINIT_FUNC
  1356. PyInit__functools(void)
  1357. {
  1358. return PyModuleDef_Init(&_functools_module);
  1359. }