Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_functoolsmodule.c
Line
Count
Source
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_pyatomic_ft_wrappers.h"
8
#include "pycore_pystate.h"       // _PyThreadState_GET()
9
#include "pycore_tuple.h"         // _PyTuple_ITEMS()
10
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
11
12
13
#include "clinic/_functoolsmodule.c.h"
14
/*[clinic input]
15
module _functools
16
class _functools._lru_cache_wrapper "PyObject *" "&lru_cache_type_spec"
17
[clinic start generated code]*/
18
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bece4053896b09c0]*/
19
20
/* _functools module written and maintained
21
   by Hye-Shik Chang <perky@FreeBSD.org>
22
   with adaptations by Raymond Hettinger <python@rcn.com>
23
   Copyright (c) 2004 Python Software Foundation.
24
   All rights reserved.
25
*/
26
27
typedef struct _functools_state {
28
    /* this object is used delimit args and keywords in the cache keys */
29
    PyObject *kwd_mark;
30
    PyObject *placeholder;  // strong reference (singleton)
31
    PyTypeObject *partial_type;
32
    PyTypeObject *keyobject_type;
33
    PyTypeObject *lru_list_elem_type;
34
} _functools_state;
35
36
static inline _functools_state *
37
get_functools_state(PyObject *module)
38
176k
{
39
176k
    void *state = _PyModule_GetState(module);
40
176k
    assert(state != NULL);
41
176k
    return (_functools_state *)state;
42
176k
}
43
44
/* partial object **********************************************************/
45
46
47
// The 'Placeholder' singleton indicates which formal positional
48
// parameters are to be bound first when using a 'partial' object.
49
50
typedef struct {
51
    PyObject_HEAD
52
} placeholderobject;
53
54
static inline _functools_state *
55
get_functools_state_by_type(PyTypeObject *type);
56
57
typedef struct {
58
    PyObject_HEAD
59
    PyObject *fn;
60
    PyObject *args;
61
    PyObject *kw;
62
    PyObject *dict;        /* __dict__ */
63
    PyObject *weakreflist; /* List of weak references */
64
    PyObject *placeholder; /* Placeholder for positional arguments */
65
    Py_ssize_t phcount;    /* Number of placeholders */
66
    vectorcallfunc vectorcall;
67
} partialobject;
68
69
// cast a PyObject pointer PTR to a partialobject pointer (no type checks)
70
712k
#define partialobject_CAST(op)  ((partialobject *)(op))
71
72
static void partial_setvectorcall(partialobject *pto);
73
static struct PyModuleDef _functools_module;
74
static PyObject *
75
partial_call(PyObject *pto, PyObject *args, PyObject *kwargs);
76
77
static inline _functools_state *
78
get_functools_state_by_type(PyTypeObject *type)
79
174k
{
80
174k
    PyObject *module = PyType_GetModuleByDef(type, &_functools_module);
81
174k
    if (module == NULL) {
82
0
        return NULL;
83
0
    }
84
174k
    return get_functools_state(module);
85
174k
}
86
87
// Not converted to argument clinic, because of `*args, **kwargs` arguments.
88
static PyObject *
89
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
90
173k
{
91
173k
    PyObject *func, *pto_args, *new_args, *pto_kw, *phold;
92
173k
    partialobject *pto;
93
173k
    Py_ssize_t pto_phcount = 0;
94
173k
    Py_ssize_t new_nargs = PyTuple_GET_SIZE(args) - 1;
95
96
173k
    if (new_nargs < 0) {
97
0
        PyErr_SetString(PyExc_TypeError,
98
0
                        "type 'partial' takes at least one argument");
99
0
        return NULL;
100
0
    }
101
173k
    func = PyTuple_GET_ITEM(args, 0);
102
173k
    if (!PyCallable_Check(func)) {
103
0
        PyErr_SetString(PyExc_TypeError,
104
0
                        "the first argument must be callable");
105
0
        return NULL;
106
0
    }
107
108
173k
    _functools_state *state = get_functools_state_by_type(type);
109
173k
    if (state == NULL) {
110
0
        return NULL;
111
0
    }
112
173k
    phold = state->placeholder;
113
114
    /* Placeholder restrictions */
115
173k
    if (new_nargs && PyTuple_GET_ITEM(args, new_nargs) == phold) {
116
0
        PyErr_SetString(PyExc_TypeError,
117
0
                        "trailing Placeholders are not allowed");
118
0
        return NULL;
119
0
    }
120
121
    /* keyword Placeholder prohibition */
122
173k
    if (kw != NULL) {
123
173k
        PyObject *key, *val;
124
173k
        Py_ssize_t pos = 0;
125
352k
        while (PyDict_Next(kw, &pos, &key, &val)) {
126
178k
            if (val == phold) {
127
0
                PyErr_SetString(PyExc_TypeError,
128
0
                                "Placeholder cannot be passed as a keyword argument");
129
0
                return NULL;
130
0
            }
131
178k
        }
132
173k
    }
133
134
    /* check wrapped function / object */
135
173k
    pto_args = pto_kw = NULL;
136
173k
    int res = PyObject_TypeCheck(func, state->partial_type);
137
173k
    if (res == -1) {
138
0
        return NULL;
139
0
    }
140
173k
    if (res == 1) {
141
        // We can use its underlying function directly and merge the arguments.
142
0
        partialobject *part = (partialobject *)func;
143
0
        if (part->dict == NULL) {
144
0
            pto_args = part->args;
145
0
            pto_kw = part->kw;
146
0
            func = part->fn;
147
0
            pto_phcount = part->phcount;
148
0
            assert(PyTuple_Check(pto_args));
149
0
            assert(PyDict_Check(pto_kw));
150
0
        }
151
0
    }
152
153
    /* create partialobject structure */
154
173k
    pto = (partialobject *)type->tp_alloc(type, 0);
155
173k
    if (pto == NULL)
156
0
        return NULL;
157
158
173k
    pto->fn = Py_NewRef(func);
159
173k
    pto->placeholder = phold;
160
161
173k
    new_args = PyTuple_GetSlice(args, 1, new_nargs + 1);
162
173k
    if (new_args == NULL) {
163
0
        Py_DECREF(pto);
164
0
        return NULL;
165
0
    }
166
167
    /* Count placeholders */
168
173k
    Py_ssize_t phcount = 0;
169
173k
    for (Py_ssize_t i = 0; i < new_nargs - 1; i++) {
170
0
        if (PyTuple_GET_ITEM(new_args, i) == phold) {
171
0
            phcount++;
172
0
        }
173
0
    }
174
    /* merge args with args of `func` which is `partial` */
175
173k
    if (pto_phcount > 0 && new_nargs > 0) {
176
0
        Py_ssize_t npargs = PyTuple_GET_SIZE(pto_args);
177
0
        Py_ssize_t tot_nargs = npargs;
178
0
        if (new_nargs > pto_phcount) {
179
0
            tot_nargs += new_nargs - pto_phcount;
180
0
        }
181
0
        PyObject *item;
182
0
        PyObject *tot_args = PyTuple_New(tot_nargs);
183
0
        if (tot_args == NULL) {
184
0
            Py_DECREF(new_args);
185
0
            Py_DECREF(pto);
186
0
            return NULL;
187
0
        }
188
0
        for (Py_ssize_t i = 0, j = 0; i < tot_nargs; i++) {
189
0
            if (i < npargs) {
190
0
                item = PyTuple_GET_ITEM(pto_args, i);
191
0
                if (j < new_nargs && item == phold) {
192
0
                    item = PyTuple_GET_ITEM(new_args, j);
193
0
                    j++;
194
0
                    pto_phcount--;
195
0
                }
196
0
            }
197
0
            else {
198
0
                item = PyTuple_GET_ITEM(new_args, j);
199
0
                j++;
200
0
            }
201
0
            Py_INCREF(item);
202
0
            PyTuple_SET_ITEM(tot_args, i, item);
203
0
        }
204
0
        pto->args = tot_args;
205
0
        pto->phcount = pto_phcount + phcount;
206
0
        Py_DECREF(new_args);
207
0
    }
208
173k
    else if (pto_args == NULL) {
209
173k
        pto->args = new_args;
210
173k
        pto->phcount = phcount;
211
173k
    }
212
0
    else {
213
0
        pto->args = PySequence_Concat(pto_args, new_args);
214
0
        pto->phcount = pto_phcount + phcount;
215
0
        Py_DECREF(new_args);
216
0
        if (pto->args == NULL) {
217
0
            Py_DECREF(pto);
218
0
            return NULL;
219
0
        }
220
0
        assert(PyTuple_Check(pto->args));
221
0
    }
222
223
173k
    if (pto_kw == NULL || PyDict_GET_SIZE(pto_kw) == 0) {
224
173k
        if (kw == NULL) {
225
12
            pto->kw = PyDict_New();
226
12
        }
227
173k
        else if (_PyObject_IsUniquelyReferenced(kw)) {
228
173k
            pto->kw = Py_NewRef(kw);
229
173k
        }
230
0
        else {
231
0
            pto->kw = PyDict_Copy(kw);
232
0
        }
233
173k
    }
234
0
    else {
235
0
        pto->kw = PyDict_Copy(pto_kw);
236
0
        if (kw != NULL && pto->kw != NULL) {
237
0
            if (PyDict_Merge(pto->kw, kw, 1) != 0) {
238
0
                Py_DECREF(pto);
239
0
                return NULL;
240
0
            }
241
0
        }
242
0
    }
243
173k
    if (pto->kw == NULL) {
244
0
        Py_DECREF(pto);
245
0
        return NULL;
246
0
    }
247
248
173k
    partial_setvectorcall(pto);
249
173k
    return (PyObject *)pto;
250
173k
}
251
252
static int
253
partial_clear(PyObject *self)
254
173k
{
255
173k
    partialobject *pto = partialobject_CAST(self);
256
173k
    Py_CLEAR(pto->fn);
257
173k
    Py_CLEAR(pto->args);
258
173k
    Py_CLEAR(pto->kw);
259
173k
    Py_CLEAR(pto->dict);
260
173k
    return 0;
261
173k
}
262
263
static int
264
partial_traverse(PyObject *self, visitproc visit, void *arg)
265
494k
{
266
494k
    partialobject *pto = partialobject_CAST(self);
267
494k
    Py_VISIT(Py_TYPE(pto));
268
494k
    Py_VISIT(pto->fn);
269
494k
    Py_VISIT(pto->args);
270
494k
    Py_VISIT(pto->kw);
271
494k
    Py_VISIT(pto->dict);
272
494k
    return 0;
273
494k
}
274
275
static void
276
partial_dealloc(PyObject *self)
277
173k
{
278
173k
    PyTypeObject *tp = Py_TYPE(self);
279
    /* bpo-31095: UnTrack is needed before calling any callbacks */
280
173k
    PyObject_GC_UnTrack(self);
281
173k
    FT_CLEAR_WEAKREFS(self, partialobject_CAST(self)->weakreflist);
282
173k
    (void)partial_clear(self);
283
173k
    tp->tp_free(self);
284
173k
    Py_DECREF(tp);
285
173k
}
286
287
static PyObject *
288
partial_descr_get(PyObject *self, PyObject *obj, PyObject *type)
289
0
{
290
0
    if (obj == Py_None || obj == NULL) {
291
0
        return Py_NewRef(self);
292
0
    }
293
0
    return PyMethod_New(self, obj);
294
0
}
295
296
static PyObject *
297
partial_vectorcall(PyObject *self, PyObject *const *args,
298
                   size_t nargsf, PyObject *kwnames)
299
44.0k
{
300
44.0k
    partialobject *pto = partialobject_CAST(self);;
301
44.0k
    PyThreadState *tstate = _PyThreadState_GET();
302
44.0k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
303
304
    /* Placeholder check */
305
44.0k
    Py_ssize_t pto_phcount = pto->phcount;
306
44.0k
    if (nargs < pto_phcount) {
307
0
        PyErr_Format(PyExc_TypeError,
308
0
                     "missing positional arguments in 'partial' call; "
309
0
                     "expected at least %zd, got %zd", pto_phcount, nargs);
310
0
        return NULL;
311
0
    }
312
313
44.0k
    PyObject *result = NULL;
314
44.0k
    PyObject *partial_function = Py_NewRef(pto->fn);
315
44.0k
    PyObject *partial_args = Py_NewRef(pto->args);
316
44.0k
    PyObject *partial_keywords = Py_NewRef(pto->kw);
317
318
44.0k
    PyObject **pto_args = _PyTuple_ITEMS(partial_args);
319
44.0k
    Py_ssize_t pto_nargs = PyTuple_GET_SIZE(partial_args);
320
44.0k
    Py_ssize_t pto_nkwds = PyDict_GET_SIZE(partial_keywords);
321
44.0k
    Py_ssize_t nkwds = kwnames == NULL ? 0 : PyTuple_GET_SIZE(kwnames);
322
44.0k
    Py_ssize_t nargskw = nargs + nkwds;
323
324
    /* Special cases */
325
44.0k
    if (!pto_nkwds) {
326
        /* Fast path if we're called without arguments */
327
43.5k
        if (nargskw == 0) {
328
0
            result = _PyObject_VectorcallTstate(tstate, partial_function, pto_args,
329
0
                                                pto_nargs, NULL);
330
0
            goto done;
331
0
        }
332
333
        /* Use PY_VECTORCALL_ARGUMENTS_OFFSET to prepend a single
334
         * positional argument. */
335
43.5k
        if (pto_nargs == 1 && (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET)) {
336
43.5k
            PyObject **newargs = (PyObject **)args - 1;
337
43.5k
            PyObject *tmp = newargs[0];
338
43.5k
            newargs[0] = pto_args[0];
339
43.5k
            result = _PyObject_VectorcallTstate(tstate, partial_function, newargs,
340
43.5k
                                                nargs + 1, kwnames);
341
43.5k
            newargs[0] = tmp;
342
43.5k
            goto done;
343
43.5k
        }
344
43.5k
    }
345
346
    /* Total sizes */
347
473
    Py_ssize_t tot_nargs = pto_nargs + nargs - pto_phcount;
348
473
    Py_ssize_t tot_nkwds = pto_nkwds + nkwds;
349
473
    Py_ssize_t tot_nargskw = tot_nargs + tot_nkwds;
350
351
473
    PyObject *pto_kw_merged = NULL;  // pto_kw with duplicates merged (if any)
352
473
    PyObject *tot_kwnames;
353
354
    /* Allocate Stack
355
     * Note, _PY_FASTCALL_SMALL_STACK is optimal for positional only
356
     * This case might have keyword arguments
357
     *  furthermore, it might use extra stack space for temporary key storage
358
     *  thus, double small_stack size is used, which is 10 * 8 = 80 bytes */
359
473
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK * 2];
360
473
    PyObject **tmp_stack, **stack;
361
473
    Py_ssize_t init_stack_size = tot_nargskw;
362
473
    if (pto_nkwds) {
363
        // If pto_nkwds, allocate additional space for temporary new keys
364
473
        init_stack_size += nkwds;
365
473
    }
366
473
    if (init_stack_size <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
367
473
        stack = small_stack;
368
473
    }
369
0
    else {
370
0
        stack = PyMem_Malloc(init_stack_size * sizeof(PyObject *));
371
0
        if (stack == NULL) {
372
0
            PyErr_NoMemory();
373
0
            goto done;
374
0
        }
375
0
    }
376
377
    /* Copy keywords to stack */
378
473
    if (!pto_nkwds) {
379
0
        tot_kwnames = kwnames;
380
0
        if (nkwds) {
381
            /* if !pto_nkwds & nkwds, then simply append kw */
382
0
            memcpy(stack + tot_nargs, args + nargs, nkwds * sizeof(PyObject*));
383
0
        }
384
0
    }
385
473
    else {
386
        /* stack is now         [<positionals>, <pto_kwds>, <kwds>, <kwds_keys>]
387
         * Will resize later to [<positionals>, <merged_kwds>] */
388
473
        PyObject *key, *val;
389
390
        /* Merge kw to pto_kw or add to tail (if not duplicate) */
391
473
        Py_ssize_t n_tail = 0;
392
473
        for (Py_ssize_t i = 0; i < nkwds; ++i) {
393
0
            key = PyTuple_GET_ITEM(kwnames, i);
394
0
            val = args[nargs + i];
395
0
            int contains = PyDict_Contains(partial_keywords, key);
396
0
            if (contains < 0) {
397
0
                goto clean_stack;
398
0
            }
399
0
            else if (contains == 1) {
400
0
                if (pto_kw_merged == NULL) {
401
0
                    pto_kw_merged = PyDict_Copy(partial_keywords);
402
0
                    if (pto_kw_merged == NULL) {
403
0
                        goto clean_stack;
404
0
                    }
405
0
                }
406
0
                if (PyDict_SetItem(pto_kw_merged, key, val) < 0) {
407
0
                    Py_DECREF(pto_kw_merged);
408
0
                    goto clean_stack;
409
0
                }
410
0
            }
411
0
            else {
412
                /* Copy keyword tail to stack */
413
0
                stack[tot_nargs + pto_nkwds + n_tail] = val;
414
0
                stack[tot_nargskw + n_tail] = key;
415
0
                n_tail++;
416
0
            }
417
0
        }
418
473
        Py_ssize_t n_merges = nkwds - n_tail;
419
420
        /* Create total kwnames */
421
473
        tot_kwnames = PyTuple_New(tot_nkwds - n_merges);
422
473
        if (tot_kwnames == NULL) {
423
0
            Py_XDECREF(pto_kw_merged);
424
0
            goto clean_stack;
425
0
        }
426
473
        for (Py_ssize_t i = 0; i < n_tail; ++i) {
427
0
            key = Py_NewRef(stack[tot_nargskw + i]);
428
0
            PyTuple_SET_ITEM(tot_kwnames, pto_nkwds + i, key);
429
0
        }
430
431
        /* Copy pto_keywords with overlapping call keywords merged
432
         * Note, tail is already coppied. */
433
473
        Py_ssize_t pos = 0, i = 0;
434
473
        PyObject *keyword_dict = n_merges ? pto_kw_merged : partial_keywords;
435
473
        Py_BEGIN_CRITICAL_SECTION(keyword_dict);
436
1.88k
        while (PyDict_Next(keyword_dict, &pos, &key, &val)) {
437
1.41k
            assert(i < pto_nkwds);
438
1.41k
            PyTuple_SET_ITEM(tot_kwnames, i, Py_NewRef(key));
439
1.41k
            stack[tot_nargs + i] = val;
440
1.41k
            i++;
441
1.41k
        }
442
473
        Py_END_CRITICAL_SECTION();
443
473
        assert(i == pto_nkwds);
444
473
        Py_XDECREF(pto_kw_merged);
445
446
        /* Resize Stack if the removing overallocation saves some noticable memory
447
         * NOTE: This whole block can be removed without breaking anything */
448
473
        Py_ssize_t noveralloc = n_merges + nkwds;
449
473
        if (stack != small_stack && noveralloc > 6 && noveralloc > init_stack_size / 10) {
450
0
            tmp_stack = PyMem_Realloc(stack, (tot_nargskw - n_merges) * sizeof(PyObject *));
451
0
            if (tmp_stack == NULL) {
452
0
                Py_DECREF(tot_kwnames);
453
0
                PyErr_NoMemory();
454
0
                goto clean_stack;
455
0
            }
456
0
            stack = tmp_stack;
457
0
        }
458
473
    }
459
460
    /* Copy Positionals to stack */
461
473
    if (pto_phcount) {
462
0
        Py_ssize_t j = 0;       // New args index
463
0
        for (Py_ssize_t i = 0; i < pto_nargs; i++) {
464
0
            if (pto_args[i] == pto->placeholder) {
465
0
                stack[i] = args[j];
466
0
                j += 1;
467
0
            }
468
0
            else {
469
0
                stack[i] = pto_args[i];
470
0
            }
471
0
        }
472
0
        assert(j == pto_phcount);
473
        /* Add remaining args from new_args */
474
0
        if (nargs > pto_phcount) {
475
0
            memcpy(stack + pto_nargs, args + j, (nargs - j) * sizeof(PyObject*));
476
0
        }
477
0
    }
478
473
    else {
479
473
        memcpy(stack, pto_args, pto_nargs * sizeof(PyObject*));
480
473
        memcpy(stack + pto_nargs, args, nargs * sizeof(PyObject*));
481
473
    }
482
483
473
    result = _PyObject_VectorcallTstate(tstate, partial_function, stack,
484
473
                                        tot_nargs, tot_kwnames);
485
473
    if (pto_nkwds) {
486
473
        Py_DECREF(tot_kwnames);
487
473
    }
488
489
473
 clean_stack:
490
473
    if (stack != small_stack) {
491
0
        PyMem_Free(stack);
492
0
    }
493
494
44.0k
 done:
495
44.0k
    Py_DECREF(partial_function);
496
44.0k
    Py_DECREF(partial_args);
497
44.0k
    Py_DECREF(partial_keywords);
498
44.0k
    return result;
499
473
}
500
501
/* Set pto->vectorcall depending on the parameters of the partial object */
502
static void
503
partial_setvectorcall(partialobject *pto)
504
173k
{
505
173k
    if (PyVectorcall_Function(pto->fn) == NULL) {
506
        /* Don't use vectorcall if the underlying function doesn't support it */
507
8
        pto->vectorcall = NULL;
508
8
    }
509
    /* We could have a special case if there are no arguments,
510
     * but that is unlikely (why use partial without arguments?),
511
     * so we don't optimize that */
512
173k
    else {
513
173k
        pto->vectorcall = partial_vectorcall;
514
173k
    }
515
173k
}
516
517
518
// Not converted to argument clinic, because of `*args, **kwargs` arguments.
519
static PyObject *
520
partial_call(PyObject *self, PyObject *args, PyObject *kwargs)
521
44
{
522
44
    partialobject *pto = partialobject_CAST(self);
523
44
    assert(PyCallable_Check(pto->fn));
524
44
    assert(PyTuple_Check(pto->args));
525
44
    assert(PyDict_Check(pto->kw));
526
527
44
    Py_ssize_t nargs = PyTuple_GET_SIZE(args);
528
44
    Py_ssize_t pto_phcount = pto->phcount;
529
44
    if (nargs < pto_phcount) {
530
0
        PyErr_Format(PyExc_TypeError,
531
0
                     "missing positional arguments in 'partial' call; "
532
0
                     "expected at least %zd, got %zd", pto_phcount, nargs);
533
0
        return NULL;
534
0
    }
535
536
    /* Merge keywords */
537
44
    PyObject *tot_kw;
538
44
    if (PyDict_GET_SIZE(pto->kw) == 0) {
539
        /* kwargs can be NULL */
540
44
        tot_kw = Py_XNewRef(kwargs);
541
44
    }
542
0
    else {
543
        /* bpo-27840, bpo-29318: dictionary of keyword parameters must be
544
           copied, because a function using "**kwargs" can modify the
545
           dictionary. */
546
0
        tot_kw = PyDict_Copy(pto->kw);
547
0
        if (tot_kw == NULL) {
548
0
            return NULL;
549
0
        }
550
551
0
        if (kwargs != NULL) {
552
0
            if (PyDict_Merge(tot_kw, kwargs, 1) != 0) {
553
0
                Py_DECREF(tot_kw);
554
0
                return NULL;
555
0
            }
556
0
        }
557
0
    }
558
559
    /* Merge positional arguments */
560
44
    PyObject *tot_args;
561
44
    if (pto_phcount) {
562
0
        Py_ssize_t pto_nargs = PyTuple_GET_SIZE(pto->args);
563
0
        Py_ssize_t tot_nargs = pto_nargs + nargs - pto_phcount;
564
0
        assert(tot_nargs >= 0);
565
0
        tot_args = PyTuple_New(tot_nargs);
566
0
        if (tot_args == NULL) {
567
0
            Py_XDECREF(tot_kw);
568
0
            return NULL;
569
0
        }
570
0
        PyObject *pto_args = pto->args;
571
0
        PyObject *item;
572
0
        Py_ssize_t j = 0;   // New args index
573
0
        for (Py_ssize_t i = 0; i < pto_nargs; i++) {
574
0
            item = PyTuple_GET_ITEM(pto_args, i);
575
0
            if (item == pto->placeholder) {
576
0
                item = PyTuple_GET_ITEM(args, j);
577
0
                j += 1;
578
0
            }
579
0
            Py_INCREF(item);
580
0
            PyTuple_SET_ITEM(tot_args, i, item);
581
0
        }
582
0
        assert(j == pto_phcount);
583
0
        for (Py_ssize_t i = pto_nargs; i < tot_nargs; i++) {
584
0
            item = PyTuple_GET_ITEM(args, j);
585
0
            Py_INCREF(item);
586
0
            PyTuple_SET_ITEM(tot_args, i, item);
587
0
            j += 1;
588
0
        }
589
0
    }
590
44
    else {
591
        /* Note: tupleconcat() is optimized for empty tuples */
592
44
        tot_args = PySequence_Concat(pto->args, args);
593
44
        if (tot_args == NULL) {
594
0
            Py_XDECREF(tot_kw);
595
0
            return NULL;
596
0
        }
597
44
    }
598
599
44
    PyObject *res = PyObject_Call(pto->fn, tot_args, tot_kw);
600
44
    Py_DECREF(tot_args);
601
44
    Py_XDECREF(tot_kw);
602
44
    return res;
603
44
}
604
605
PyDoc_STRVAR(partial_doc,
606
"partial(func, /, *args, **keywords)\n--\n\n\
607
Create a new function with partial application of the given arguments\n\
608
and keywords.");
609
610
#define OFF(x) offsetof(partialobject, x)
611
static PyMemberDef partial_memberlist[] = {
612
    {"func",            _Py_T_OBJECT,       OFF(fn),        Py_READONLY,
613
     "function object to use in future partial calls"},
614
    {"args",            _Py_T_OBJECT,       OFF(args),      Py_READONLY,
615
     "tuple of arguments to future partial calls"},
616
    {"keywords",        _Py_T_OBJECT,       OFF(kw),        Py_READONLY,
617
     "dictionary of keyword arguments to future partial calls"},
618
    {"__weaklistoffset__", Py_T_PYSSIZET,
619
     offsetof(partialobject, weakreflist), Py_READONLY},
620
    {"__dictoffset__", Py_T_PYSSIZET,
621
     offsetof(partialobject, dict), Py_READONLY},
622
    {"__vectorcalloffset__", Py_T_PYSSIZET,
623
     offsetof(partialobject, vectorcall), Py_READONLY},
624
    {NULL}  /* Sentinel */
625
};
626
627
static PyGetSetDef partial_getsetlist[] = {
628
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
629
    {NULL} /* Sentinel */
630
};
631
632
static PyObject *
633
partial_repr(PyObject *self)
634
0
{
635
0
    partialobject *pto = partialobject_CAST(self);
636
0
    PyObject *result = NULL;
637
0
    PyObject *arglist = NULL;
638
0
    PyObject *mod = NULL;
639
0
    PyObject *name = NULL;
640
0
    Py_ssize_t i, n;
641
0
    PyObject *key, *value;
642
0
    int status;
643
644
0
    status = Py_ReprEnter(self);
645
0
    if (status != 0) {
646
0
        if (status < 0) {
647
0
            return NULL;
648
0
        }
649
0
        return PyUnicode_FromString("...");
650
0
    }
651
    /* Reference arguments in case they change */
652
0
    PyObject *fn = Py_NewRef(pto->fn);
653
0
    PyObject *args = Py_NewRef(pto->args);
654
0
    PyObject *kw = Py_NewRef(pto->kw);
655
0
    assert(PyTuple_Check(args));
656
0
    assert(PyDict_Check(kw));
657
658
0
    arglist = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
659
0
    if (arglist == NULL) {
660
0
        goto done;
661
0
    }
662
    /* Pack positional arguments */
663
0
    n = PyTuple_GET_SIZE(args);
664
0
    for (i = 0; i < n; i++) {
665
0
        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %R", arglist,
666
0
                                        PyTuple_GET_ITEM(args, i)));
667
0
        if (arglist == NULL) {
668
0
            goto done;
669
0
        }
670
0
    }
671
    /* Pack keyword arguments */
672
0
    int error = 0;
673
0
    Py_BEGIN_CRITICAL_SECTION(kw);
674
0
    for (i = 0; PyDict_Next(kw, &i, &key, &value);) {
675
        /* Prevent key.__str__ from deleting the value. */
676
0
        Py_INCREF(value);
677
0
        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %S=%R", arglist,
678
0
                                                key, value));
679
0
        Py_DECREF(value);
680
0
        if (arglist == NULL) {
681
0
            error = 1;
682
0
            break;
683
0
        }
684
0
    }
685
0
    Py_END_CRITICAL_SECTION();
686
0
    if (error) {
687
0
        goto done;
688
0
    }
689
690
0
    mod = PyType_GetModuleName(Py_TYPE(pto));
691
0
    if (mod == NULL) {
692
0
        goto done;
693
0
    }
694
695
0
    name = PyType_GetQualName(Py_TYPE(pto));
696
0
    if (name == NULL) {
697
0
        goto done;
698
0
    }
699
700
0
    result = PyUnicode_FromFormat("%S.%S(%R%U)", mod, name, fn, arglist);
701
0
done:
702
0
    Py_XDECREF(name);
703
0
    Py_XDECREF(mod);
704
0
    Py_XDECREF(arglist);
705
0
    Py_DECREF(fn);
706
0
    Py_DECREF(args);
707
0
    Py_DECREF(kw);
708
0
    Py_ReprLeave(self);
709
0
    return result;
710
0
}
711
712
/* Pickle strategy:
713
   __reduce__ by itself doesn't support getting kwargs in the unpickle
714
   operation so we define a __setstate__ that replaces all the information
715
   about the partial.  If we only replaced part of it someone would use
716
   it as a hook to do strange things.
717
 */
718
719
static PyObject *
720
partial_reduce(PyObject *self, PyObject *Py_UNUSED(args))
721
0
{
722
0
    partialobject *pto = partialobject_CAST(self);
723
0
    return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
724
0
                         pto->args, pto->kw,
725
0
                         pto->dict ? pto->dict : Py_None);
726
0
}
727
728
static PyObject *
729
partial_setstate(PyObject *self, PyObject *state)
730
0
{
731
0
    partialobject *pto = partialobject_CAST(self);
732
0
    PyObject *fn, *fnargs, *kw, *dict;
733
734
0
    if (!PyTuple_Check(state)) {
735
0
        PyErr_SetString(PyExc_TypeError, "invalid partial state");
736
0
        return NULL;
737
0
    }
738
0
    if (!PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) ||
739
0
        !PyCallable_Check(fn) ||
740
0
        !PyTuple_Check(fnargs) ||
741
0
        (kw != Py_None && !PyDict_Check(kw)) ||
742
0
        (dict != Py_None && !PyDict_Check(dict)))
743
0
    {
744
0
        PyErr_SetString(PyExc_TypeError, "invalid partial state");
745
0
        return NULL;
746
0
    }
747
748
0
    Py_ssize_t nargs = PyTuple_GET_SIZE(fnargs);
749
0
    if (nargs && PyTuple_GET_ITEM(fnargs, nargs - 1) == pto->placeholder) {
750
0
        PyErr_SetString(PyExc_TypeError,
751
0
                        "trailing Placeholders are not allowed");
752
0
        return NULL;
753
0
    }
754
    /* Count placeholders */
755
0
    Py_ssize_t phcount = 0;
756
0
    for (Py_ssize_t i = 0; i < nargs - 1; i++) {
757
0
        if (PyTuple_GET_ITEM(fnargs, i) == pto->placeholder) {
758
0
            phcount++;
759
0
        }
760
0
    }
761
762
0
    if(!PyTuple_CheckExact(fnargs))
763
0
        fnargs = PySequence_Tuple(fnargs);
764
0
    else
765
0
        Py_INCREF(fnargs);
766
0
    if (fnargs == NULL)
767
0
        return NULL;
768
769
0
    if (kw == Py_None)
770
0
        kw = PyDict_New();
771
0
    else if(!PyDict_CheckExact(kw))
772
0
        kw = PyDict_Copy(kw);
773
0
    else
774
0
        Py_INCREF(kw);
775
0
    if (kw == NULL) {
776
0
        Py_DECREF(fnargs);
777
0
        return NULL;
778
0
    }
779
780
0
    if (dict == Py_None)
781
0
        dict = NULL;
782
0
    else
783
0
        Py_INCREF(dict);
784
0
    Py_SETREF(pto->fn, Py_NewRef(fn));
785
0
    Py_SETREF(pto->args, fnargs);
786
0
    Py_SETREF(pto->kw, kw);
787
0
    pto->phcount = phcount;
788
0
    Py_XSETREF(pto->dict, dict);
789
0
    partial_setvectorcall(pto);
790
0
    Py_RETURN_NONE;
791
0
}
792
793
static PyMethodDef partial_methods[] = {
794
    {"__reduce__", partial_reduce, METH_NOARGS},
795
    {"__setstate__", partial_setstate, METH_O},
796
    {"__class_getitem__",    Py_GenericAlias,
797
    METH_O|METH_CLASS,
798
    PyDoc_STR("partial is generic over the wrapped function's return type")},
799
    {NULL,              NULL}           /* sentinel */
800
};
801
802
static PyType_Slot partial_type_slots[] = {
803
    {Py_tp_dealloc, partial_dealloc},
804
    {Py_tp_repr, partial_repr},
805
    {Py_tp_call, partial_call},
806
    {Py_tp_getattro, PyObject_GenericGetAttr},
807
    {Py_tp_setattro, PyObject_GenericSetAttr},
808
    {Py_tp_doc, (void *)partial_doc},
809
    {Py_tp_traverse, partial_traverse},
810
    {Py_tp_clear, partial_clear},
811
    {Py_tp_methods, partial_methods},
812
    {Py_tp_members, partial_memberlist},
813
    {Py_tp_getset, partial_getsetlist},
814
    {Py_tp_descr_get, partial_descr_get},
815
    {Py_tp_new, partial_new},
816
    {Py_tp_free, PyObject_GC_Del},
817
    {0, 0}
818
};
819
820
static PyType_Spec partial_type_spec = {
821
    .name = "functools.partial",
822
    .basicsize = sizeof(partialobject),
823
    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
824
             Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL |
825
             Py_TPFLAGS_IMMUTABLETYPE,
826
    .slots = partial_type_slots
827
};
828
829
830
/* cmp_to_key ***************************************************************/
831
832
typedef struct {
833
    PyObject_HEAD
834
    PyObject *cmp;
835
    PyObject *object;
836
} keyobject;
837
838
0
#define keyobject_CAST(op)  ((keyobject *)(op))
839
840
static int
841
keyobject_clear(PyObject *op)
842
0
{
843
0
    keyobject *ko = keyobject_CAST(op);
844
0
    Py_CLEAR(ko->cmp);
845
0
    Py_CLEAR(ko->object);
846
0
    return 0;
847
0
}
848
849
static void
850
keyobject_dealloc(PyObject *ko)
851
0
{
852
0
    PyTypeObject *tp = Py_TYPE(ko);
853
0
    PyObject_GC_UnTrack(ko);
854
0
    (void)keyobject_clear(ko);
855
0
    tp->tp_free(ko);
856
0
    Py_DECREF(tp);
857
0
}
858
859
static int
860
keyobject_traverse(PyObject *op, visitproc visit, void *arg)
861
0
{
862
0
    keyobject *ko = keyobject_CAST(op);
863
0
    Py_VISIT(Py_TYPE(ko));
864
0
    Py_VISIT(ko->cmp);
865
0
    Py_VISIT(ko->object);
866
0
    return 0;
867
0
}
868
869
static PyMemberDef keyobject_members[] = {
870
    {"obj", _Py_T_OBJECT,
871
     offsetof(keyobject, object), 0,
872
     PyDoc_STR("Value wrapped by a key function.")},
873
    {NULL}
874
};
875
876
static PyObject *
877
keyobject_text_signature(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
878
0
{
879
0
    return PyUnicode_FromString("(obj)");
880
0
}
881
882
static PyGetSetDef keyobject_getset[] = {
883
    {"__text_signature__", keyobject_text_signature, NULL},
884
    {NULL}
885
};
886
887
static PyObject *
888
keyobject_call(PyObject *ko, PyObject *args, PyObject *kwds);
889
890
static PyObject *
891
keyobject_richcompare(PyObject *ko, PyObject *other, int op);
892
893
static PyType_Slot keyobject_type_slots[] = {
894
    {Py_tp_dealloc, keyobject_dealloc},
895
    {Py_tp_call, keyobject_call},
896
    {Py_tp_getattro, PyObject_GenericGetAttr},
897
    {Py_tp_traverse, keyobject_traverse},
898
    {Py_tp_clear, keyobject_clear},
899
    {Py_tp_richcompare, keyobject_richcompare},
900
    {Py_tp_members, keyobject_members},
901
    {Py_tp_getset, keyobject_getset},
902
    {0, 0}
903
};
904
905
static PyType_Spec keyobject_type_spec = {
906
    .name = "functools.KeyWrapper",
907
    .basicsize = sizeof(keyobject),
908
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
909
              Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
910
    .slots = keyobject_type_slots
911
};
912
913
static PyObject *
914
keyobject_call(PyObject *self, PyObject *args, PyObject *kwds)
915
0
{
916
0
    PyObject *object;
917
0
    keyobject *result;
918
0
    static char *kwargs[] = {"obj", NULL};
919
0
    keyobject *ko = keyobject_CAST(self);
920
921
0
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:K", kwargs, &object))
922
0
        return NULL;
923
924
0
    result = PyObject_GC_New(keyobject, Py_TYPE(ko));
925
0
    if (result == NULL) {
926
0
        return NULL;
927
0
    }
928
0
    result->cmp = Py_NewRef(ko->cmp);
929
0
    result->object = Py_NewRef(object);
930
0
    PyObject_GC_Track(result);
931
0
    return (PyObject *)result;
932
0
}
933
934
static PyObject *
935
keyobject_richcompare(PyObject *self, PyObject *other, int op)
936
0
{
937
0
    if (!Py_IS_TYPE(other, Py_TYPE(self))) {
938
0
        PyErr_Format(PyExc_TypeError, "other argument must be K instance");
939
0
        return NULL;
940
0
    }
941
942
0
    keyobject *lhs = keyobject_CAST(self);
943
0
    keyobject *rhs = keyobject_CAST(other);
944
945
0
    PyObject *compare = lhs->cmp;
946
0
    assert(compare != NULL);
947
0
    PyObject *x = lhs->object;
948
0
    PyObject *y = rhs->object;
949
0
    if (!x || !y){
950
0
        PyErr_Format(PyExc_AttributeError, "object");
951
0
        return NULL;
952
0
    }
953
954
    /* Call the user's comparison function and translate the 3-way
955
     * result into true or false (or error).
956
     */
957
0
    PyObject* args[2] = {x, y};
958
0
    PyObject *res = PyObject_Vectorcall(compare, args, 2, NULL);
959
0
    if (res == NULL) {
960
0
        return NULL;
961
0
    }
962
963
0
    PyObject *answer = PyObject_RichCompare(res, _PyLong_GetZero(), op);
964
0
    Py_DECREF(res);
965
0
    return answer;
966
0
}
967
968
/*[clinic input]
969
_functools.cmp_to_key
970
971
    mycmp: object
972
        Function that compares two objects.
973
974
Convert a cmp= function into a key= function.
975
[clinic start generated code]*/
976
977
static PyObject *
978
_functools_cmp_to_key_impl(PyObject *module, PyObject *mycmp)
979
/*[clinic end generated code: output=71eaad0f4fc81f33 input=d1b76f231c0dfeb3]*/
980
0
{
981
0
    keyobject *object;
982
0
    _functools_state *state;
983
984
0
    state = get_functools_state(module);
985
0
    object = PyObject_GC_New(keyobject, state->keyobject_type);
986
0
    if (!object)
987
0
        return NULL;
988
0
    object->cmp = Py_NewRef(mycmp);
989
0
    object->object = NULL;
990
0
    PyObject_GC_Track(object);
991
0
    return (PyObject *)object;
992
0
}
993
994
/* reduce (used to be a builtin) ********************************************/
995
996
/*[clinic input]
997
@permit_long_summary
998
_functools.reduce
999
1000
    function as func: object
1001
    iterable as seq: object
1002
    /
1003
    initial as result: object(c_default="NULL") = functools._initial_missing
1004
1005
Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
1006
1007
This effectively reduces the iterable to a single value.  If initial is
1008
present, it is placed before the items of the iterable in the
1009
calculation, and serves as a default when the iterable is empty.
1010
1011
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
1012
calculates ((((1 + 2) + 3) + 4) + 5).
1013
[clinic start generated code]*/
1014
1015
static PyObject *
1016
_functools_reduce_impl(PyObject *module, PyObject *func, PyObject *seq,
1017
                       PyObject *result)
1018
/*[clinic end generated code: output=30d898fe1267c79d input=ff4d5c73100e72e8]*/
1019
0
{
1020
0
    PyObject *args, *it;
1021
1022
0
    if (result != NULL)
1023
0
        Py_INCREF(result);
1024
1025
0
    it = PyObject_GetIter(seq);
1026
0
    if (it == NULL) {
1027
0
        if (PyErr_ExceptionMatches(PyExc_TypeError))
1028
0
            PyErr_SetString(PyExc_TypeError,
1029
0
                            "reduce() arg 2 must support iteration");
1030
0
        Py_XDECREF(result);
1031
0
        return NULL;
1032
0
    }
1033
1034
0
    if ((args = PyTuple_New(2)) == NULL)
1035
0
        goto Fail;
1036
1037
0
    for (;;) {
1038
0
        PyObject *op2;
1039
1040
0
        if (!_PyObject_IsUniquelyReferenced(args)) {
1041
0
            Py_DECREF(args);
1042
0
            if ((args = PyTuple_New(2)) == NULL)
1043
0
                goto Fail;
1044
0
        }
1045
1046
0
        op2 = PyIter_Next(it);
1047
0
        if (op2 == NULL) {
1048
0
            if (PyErr_Occurred())
1049
0
                goto Fail;
1050
0
            break;
1051
0
        }
1052
1053
0
        if (result == NULL)
1054
0
            result = op2;
1055
0
        else {
1056
            /* Update the args tuple in-place */
1057
0
            assert(Py_REFCNT(args) == 1);
1058
0
            Py_XSETREF(_PyTuple_ITEMS(args)[0], result);
1059
0
            Py_XSETREF(_PyTuple_ITEMS(args)[1], op2);
1060
0
            if ((result = PyObject_Call(func, args, NULL)) == NULL) {
1061
0
                goto Fail;
1062
0
            }
1063
            // bpo-42536: The GC may have untracked this args tuple. Since we're
1064
            // recycling it, make sure it's tracked again:
1065
0
            _PyTuple_Recycle(args);
1066
0
        }
1067
0
    }
1068
1069
0
    Py_DECREF(args);
1070
1071
0
    if (result == NULL)
1072
0
        PyErr_SetString(PyExc_TypeError,
1073
0
                        "reduce() of empty iterable with no initial value");
1074
1075
0
    Py_DECREF(it);
1076
0
    return result;
1077
1078
0
Fail:
1079
0
    Py_XDECREF(args);
1080
0
    Py_XDECREF(result);
1081
0
    Py_DECREF(it);
1082
0
    return NULL;
1083
0
}
1084
1085
/* lru_cache object **********************************************************/
1086
1087
/* There are four principal algorithmic differences from the pure python version:
1088
1089
   1). The C version relies on the GIL instead of having its own reentrant lock.
1090
1091
   2). The prev/next link fields use borrowed references.
1092
1093
   3). For a full cache, the pure python version rotates the location of the
1094
       root entry so that it never has to move individual links and it can
1095
       limit updates to just the key and result fields.  However, in the C
1096
       version, links are temporarily removed while the cache dict updates are
1097
       occurring. Afterwards, they are appended or prepended back into the
1098
       doubly-linked lists.
1099
1100
   4)  In the Python version, the _HashSeq class is used to prevent __hash__
1101
       from being called more than once.  In the C version, the "known hash"
1102
       variants of dictionary calls as used to the same effect.
1103
1104
*/
1105
1106
struct lru_list_elem;
1107
struct lru_cache_object;
1108
1109
typedef struct lru_list_elem {
1110
    PyObject_HEAD
1111
    struct lru_list_elem *prev, *next;  /* borrowed links */
1112
    Py_hash_t hash;
1113
    PyObject *key, *result;
1114
} lru_list_elem;
1115
1116
0
#define lru_list_elem_CAST(op)  ((lru_list_elem *)(op))
1117
1118
static void
1119
lru_list_elem_dealloc(PyObject *op)
1120
0
{
1121
0
    lru_list_elem *link = lru_list_elem_CAST(op);
1122
0
    PyTypeObject *tp = Py_TYPE(link);
1123
0
    Py_XDECREF(link->key);
1124
0
    Py_XDECREF(link->result);
1125
0
    tp->tp_free(link);
1126
0
    Py_DECREF(tp);
1127
0
}
1128
1129
static PyType_Slot lru_list_elem_type_slots[] = {
1130
    {Py_tp_dealloc, lru_list_elem_dealloc},
1131
    {0, 0}
1132
};
1133
1134
static PyType_Spec lru_list_elem_type_spec = {
1135
    .name = "functools._lru_list_elem",
1136
    .basicsize = sizeof(lru_list_elem),
1137
    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
1138
             Py_TPFLAGS_IMMUTABLETYPE,
1139
    .slots = lru_list_elem_type_slots
1140
};
1141
1142
1143
typedef PyObject *(*lru_cache_ternaryfunc)(struct lru_cache_object *, PyObject *, PyObject *);
1144
1145
typedef struct lru_cache_object {
1146
    lru_list_elem root;  /* includes PyObject_HEAD */
1147
    lru_cache_ternaryfunc wrapper;
1148
    int typed;
1149
    PyObject *cache;
1150
    Py_ssize_t hits;
1151
    PyObject *func;
1152
    Py_ssize_t maxsize;
1153
    Py_ssize_t misses;
1154
    /* the kwd_mark is used delimit args and keywords in the cache keys */
1155
    PyObject *kwd_mark;
1156
    PyTypeObject *lru_list_elem_type;
1157
    PyObject *cache_info_type;
1158
    PyObject *dict;
1159
    PyObject *weakreflist;
1160
} lru_cache_object;
1161
1162
49.1k
#define lru_cache_object_CAST(op)   ((lru_cache_object *)(op))
1163
1164
static PyObject *
1165
lru_cache_make_key(PyObject *kwd_mark, PyObject *args,
1166
                   PyObject *kwds, int typed)
1167
42.1k
{
1168
42.1k
    PyObject *key, *keyword, *value;
1169
42.1k
    Py_ssize_t key_size, pos, key_pos, kwds_size;
1170
1171
42.1k
    kwds_size = kwds ? PyDict_GET_SIZE(kwds) : 0;
1172
1173
    /* short path, key will match args anyway, which is a tuple */
1174
42.1k
    if (!typed && !kwds_size) {
1175
42.0k
        if (PyTuple_GET_SIZE(args) == 1) {
1176
3.80k
            key = PyTuple_GET_ITEM(args, 0);
1177
3.80k
            if (PyUnicode_CheckExact(key) || PyLong_CheckExact(key)) {
1178
                /* For common scalar keys, save space by
1179
                   dropping the enclosing args tuple  */
1180
3.78k
                return Py_NewRef(key);
1181
3.78k
            }
1182
3.80k
        }
1183
38.2k
        return Py_NewRef(args);
1184
42.0k
    }
1185
1186
80
    key_size = PyTuple_GET_SIZE(args);
1187
80
    if (kwds_size)
1188
0
        key_size += kwds_size * 2 + 1;
1189
80
    if (typed)
1190
80
        key_size += PyTuple_GET_SIZE(args) + kwds_size;
1191
1192
80
    key = PyTuple_New(key_size);
1193
80
    if (key == NULL)
1194
0
        return NULL;
1195
1196
80
    key_pos = 0;
1197
512
    for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
1198
432
        PyObject *item = PyTuple_GET_ITEM(args, pos);
1199
432
        PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
1200
432
    }
1201
80
    if (kwds_size) {
1202
0
        PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(kwd_mark));
1203
0
        for (pos = 0; PyDict_Next(kwds, &pos, &keyword, &value);) {
1204
0
            PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(keyword));
1205
0
            PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(value));
1206
0
        }
1207
0
        assert(key_pos == PyTuple_GET_SIZE(args) + kwds_size * 2 + 1);
1208
0
    }
1209
80
    if (typed) {
1210
512
        for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
1211
432
            PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(args, pos));
1212
432
            PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
1213
432
        }
1214
80
        if (kwds_size) {
1215
0
            for (pos = 0; PyDict_Next(kwds, &pos, &keyword, &value);) {
1216
0
                PyObject *item = (PyObject *)Py_TYPE(value);
1217
0
                PyTuple_SET_ITEM(key, key_pos++, Py_NewRef(item));
1218
0
            }
1219
0
        }
1220
80
    }
1221
80
    assert(key_pos == key_size);
1222
80
    return key;
1223
80
}
1224
1225
static PyObject *
1226
uncached_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
1227
0
{
1228
0
    PyObject *result;
1229
1230
0
    FT_ATOMIC_ADD_SSIZE_RELAXED(self->misses, 1);
1231
0
    result = PyObject_Call(self->func, args, kwds);
1232
0
    if (!result)
1233
0
        return NULL;
1234
0
    return result;
1235
0
}
1236
1237
static PyObject *
1238
infinite_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
1239
2.92k
{
1240
2.92k
    PyObject *result;
1241
2.92k
    Py_hash_t hash;
1242
2.92k
    PyObject *key = lru_cache_make_key(self->kwd_mark, args, kwds, self->typed);
1243
2.92k
    if (!key)
1244
0
        return NULL;
1245
2.92k
    hash = PyObject_Hash(key);
1246
2.92k
    if (hash == -1) {
1247
0
        Py_DECREF(key);
1248
0
        return NULL;
1249
0
    }
1250
2.92k
    int res = _PyDict_GetItemRef_KnownHash((PyDictObject *)self->cache, key, hash, &result);
1251
2.92k
    if (res > 0) {
1252
2.79k
        FT_ATOMIC_ADD_SSIZE_RELAXED(self->hits, 1);
1253
2.79k
        Py_DECREF(key);
1254
2.79k
        return result;
1255
2.79k
    }
1256
129
    if (res < 0) {
1257
0
        Py_DECREF(key);
1258
0
        return NULL;
1259
0
    }
1260
129
    FT_ATOMIC_ADD_SSIZE_RELAXED(self->misses, 1);
1261
129
    result = PyObject_Call(self->func, args, kwds);
1262
129
    if (!result) {
1263
0
        Py_DECREF(key);
1264
0
        return NULL;
1265
0
    }
1266
129
    if (_PyDict_SetItem_KnownHash(self->cache, key, result, hash) < 0) {
1267
0
        Py_DECREF(result);
1268
0
        Py_DECREF(key);
1269
0
        return NULL;
1270
0
    }
1271
129
    Py_DECREF(key);
1272
129
    return result;
1273
129
}
1274
1275
static void
1276
lru_cache_extract_link(lru_list_elem *link)
1277
38.0k
{
1278
38.0k
    lru_list_elem *link_prev = link->prev;
1279
38.0k
    lru_list_elem *link_next = link->next;
1280
38.0k
    link_prev->next = link->next;
1281
38.0k
    link_next->prev = link->prev;
1282
38.0k
}
1283
1284
static void
1285
lru_cache_append_link(lru_cache_object *self, lru_list_elem *link)
1286
39.2k
{
1287
39.2k
    lru_list_elem *root = &self->root;
1288
39.2k
    lru_list_elem *last = root->prev;
1289
39.2k
    last->next = root->prev = link;
1290
39.2k
    link->prev = last;
1291
39.2k
    link->next = root;
1292
39.2k
}
1293
1294
static void
1295
lru_cache_prepend_link(lru_cache_object *self, lru_list_elem *link)
1296
0
{
1297
0
    lru_list_elem *root = &self->root;
1298
0
    lru_list_elem *first = root->next;
1299
0
    first->prev = root->next = link;
1300
0
    link->prev = root;
1301
0
    link->next = first;
1302
0
}
1303
1304
/* General note on reentrancy:
1305
1306
   There are four dictionary calls in the bounded_lru_cache_wrapper():
1307
   1) The initial check for a cache match.  2) The post user-function
1308
   check for a cache match.  3) The deletion of the oldest entry.
1309
   4) The addition of the newest entry.
1310
1311
   In all four calls, we have a known hash which lets use avoid a call
1312
   to __hash__().  That leaves only __eq__ as a possible source of a
1313
   reentrant call.
1314
1315
   The __eq__ method call is always made for a cache hit (dict access #1).
1316
   Accordingly, we have make sure not modify the cache state prior to
1317
   this call.
1318
1319
   The __eq__ method call is never made for the deletion (dict access #3)
1320
   because it is an identity match.
1321
1322
   For the other two accesses (#2 and #4), calls to __eq__ only occur
1323
   when some other entry happens to have an exactly matching hash (all
1324
   64-bits).  Though rare, this can happen, so we have to make sure to
1325
   either call it at the top of its code path before any cache
1326
   state modifications (dict access #2) or be prepared to restore
1327
   invariants at the end of the code path (dict access #4).
1328
1329
   Another possible source of reentrancy is a decref which can trigger
1330
   arbitrary code execution.  To make the code easier to reason about,
1331
   the decrefs are deferred to the end of the each possible code path
1332
   so that we know the cache is a consistent state.
1333
 */
1334
1335
static int
1336
bounded_lru_cache_get_lock_held(lru_cache_object *self, PyObject *args, PyObject *kwds,
1337
                                PyObject **result, PyObject **key, Py_hash_t *hash)
1338
39.2k
{
1339
39.2k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
1340
39.2k
    lru_list_elem *link;
1341
1342
39.2k
    PyObject *key_ = *key = lru_cache_make_key(self->kwd_mark, args, kwds, self->typed);
1343
39.2k
    if (!key_)
1344
0
        return -1;
1345
39.2k
    Py_hash_t hash_ = *hash = PyObject_Hash(key_);
1346
39.2k
    if (hash_ == -1) {
1347
0
        Py_DECREF(key_);  /* dead reference left in *key, is not used */
1348
0
        return -1;
1349
0
    }
1350
39.2k
    int res = _PyDict_GetItemRef_KnownHash_LockHeld((PyDictObject *)self->cache, key_, hash_,
1351
39.2k
                                                    (PyObject **)&link);
1352
39.2k
    if (res > 0) {
1353
38.0k
        lru_cache_extract_link(link);
1354
38.0k
        lru_cache_append_link(self, link);
1355
38.0k
        *result = link->result;
1356
38.0k
        FT_ATOMIC_ADD_SSIZE_RELAXED(self->hits, 1);
1357
38.0k
        Py_INCREF(link->result);
1358
38.0k
        Py_DECREF(link);
1359
38.0k
        Py_DECREF(key_);
1360
38.0k
        return 1;
1361
38.0k
    }
1362
1.14k
    if (res < 0) {
1363
0
        Py_DECREF(key_);
1364
0
        return -1;
1365
0
    }
1366
1.14k
    FT_ATOMIC_ADD_SSIZE_RELAXED(self->misses, 1);
1367
1.14k
    return 0;
1368
1.14k
}
1369
1370
static PyObject *
1371
bounded_lru_cache_update_lock_held(lru_cache_object *self,
1372
                                   PyObject *result, PyObject *key, Py_hash_t hash)
1373
1.14k
{
1374
1.14k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
1375
1.14k
    lru_list_elem *link;
1376
1.14k
    PyObject *testresult;
1377
1.14k
    int res;
1378
1379
1.14k
    if (!result) {
1380
0
        Py_DECREF(key);
1381
0
        return NULL;
1382
0
    }
1383
1.14k
    res = _PyDict_GetItemRef_KnownHash_LockHeld((PyDictObject *)self->cache, key, hash,
1384
1.14k
                                                &testresult);
1385
1.14k
    if (res > 0) {
1386
        /* Getting here means that this same key was added to the cache
1387
           during the PyObject_Call().  Since the link update is already
1388
           done, we need only return the computed result. */
1389
0
        Py_DECREF(testresult);
1390
0
        Py_DECREF(key);
1391
0
        return result;
1392
0
    }
1393
1.14k
    if (res < 0) {
1394
        /* This is an unusual case since this same lookup
1395
           did not previously trigger an error during lookup.
1396
           Treat it the same as an error in user function
1397
           and return with the error set. */
1398
0
        Py_DECREF(key);
1399
0
        Py_DECREF(result);
1400
0
        return NULL;
1401
0
    }
1402
    /* This is the normal case.  The new key wasn't found before
1403
       user function call and it is still not there.  So we
1404
       proceed normally and update the cache with the new result. */
1405
1406
1.14k
    assert(self->maxsize > 0);
1407
1.14k
    if (PyDict_GET_SIZE(self->cache) < self->maxsize ||
1408
0
        self->root.next == &self->root)
1409
1.14k
    {
1410
        /* Cache is not full, so put the result in a new link */
1411
1.14k
        link = (lru_list_elem *)PyObject_New(lru_list_elem,
1412
1.14k
                                             self->lru_list_elem_type);
1413
1.14k
        if (link == NULL) {
1414
0
            Py_DECREF(key);
1415
0
            Py_DECREF(result);
1416
0
            return NULL;
1417
0
        }
1418
1419
1.14k
        link->hash = hash;
1420
1.14k
        link->key = key;
1421
1.14k
        link->result = result;
1422
        /* What is really needed here is a SetItem variant with a "no clobber"
1423
           option.  If the __eq__ call triggers a reentrant call that adds
1424
           this same key, then this setitem call will update the cache dict
1425
           with this new link, leaving the old link as an orphan (i.e. not
1426
           having a cache dict entry that refers to it). */
1427
1.14k
        if (_PyDict_SetItem_KnownHash_LockHeld((PyDictObject *)self->cache, key,
1428
1.14k
                                               (PyObject *)link, hash) < 0) {
1429
0
            Py_DECREF(link);
1430
0
            return NULL;
1431
0
        }
1432
1.14k
        lru_cache_append_link(self, link);
1433
1.14k
        return Py_NewRef(result);
1434
1.14k
    }
1435
    /* Since the cache is full, we need to evict an old key and add
1436
       a new key.  Rather than free the old link and allocate a new
1437
       one, we reuse the link for the new key and result and move it
1438
       to front of the cache to mark it as recently used.
1439
1440
       We try to assure all code paths (including errors) leave all
1441
       of the links in place.  Either the link is successfully
1442
       updated and moved or it is restored to its old position.
1443
       However if an unrecoverable error is found, it doesn't
1444
       make sense to reinsert the link, so we leave it out
1445
       and the cache will no longer register as full.
1446
    */
1447
0
    PyObject *oldkey, *oldresult, *popresult;
1448
1449
    /* Extract the oldest item. */
1450
0
    assert(self->root.next != &self->root);
1451
0
    link = self->root.next;
1452
0
    lru_cache_extract_link(link);
1453
    /* Remove it from the cache.
1454
       The cache dict holds one reference to the link.
1455
       We created one other reference when the link was created.
1456
       The linked list only has borrowed references. */
1457
0
    res = _PyDict_Pop_KnownHash((PyDictObject*)self->cache, link->key,
1458
0
                                link->hash, &popresult);
1459
0
    if (res < 0) {
1460
        /* An error arose while trying to remove the oldest key (the one
1461
           being evicted) from the cache.  We restore the link to its
1462
           original position as the oldest link.  Then we allow the
1463
           error propagate upward; treating it the same as an error
1464
           arising in the user function. */
1465
0
        lru_cache_prepend_link(self, link);
1466
0
        Py_DECREF(key);
1467
0
        Py_DECREF(result);
1468
0
        return NULL;
1469
0
    }
1470
0
    if (res == 0) {
1471
        /* Getting here means that the user function call or another
1472
           thread has already removed the old key from the dictionary.
1473
           This link is now an orphan.  Since we don't want to leave the
1474
           cache in an inconsistent state, we don't restore the link. */
1475
0
        assert(popresult == NULL);
1476
0
        Py_DECREF(link);
1477
0
        Py_DECREF(key);
1478
0
        return result;
1479
0
    }
1480
1481
    /* Keep a reference to the old key and old result to prevent their
1482
       ref counts from going to zero during the update. That will
1483
       prevent potentially arbitrary object clean-up code (i.e. __del__)
1484
       from running while we're still adjusting the links. */
1485
0
    assert(popresult != NULL);
1486
0
    oldkey = link->key;
1487
0
    oldresult = link->result;
1488
1489
0
    link->hash = hash;
1490
0
    link->key = key;
1491
0
    link->result = result;
1492
    /* Note:  The link is being added to the cache dict without the
1493
       prev and next fields set to valid values.   We have to wait
1494
       for successful insertion in the cache dict before adding the
1495
       link to the linked list.  Otherwise, the potentially reentrant
1496
       __eq__ call could cause the then orphan link to be visited. */
1497
0
    if (_PyDict_SetItem_KnownHash_LockHeld((PyDictObject *)self->cache, key,
1498
0
                                           (PyObject *)link, hash) < 0) {
1499
        /* Somehow the cache dict update failed.  We no longer can
1500
           restore the old link.  Let the error propagate upward and
1501
           leave the cache short one link. */
1502
0
        Py_DECREF(popresult);
1503
0
        Py_DECREF(link);
1504
0
        Py_DECREF(oldkey);
1505
0
        Py_DECREF(oldresult);
1506
0
        return NULL;
1507
0
    }
1508
0
    lru_cache_append_link(self, link);
1509
0
    Py_INCREF(result); /* for return */
1510
0
    Py_DECREF(popresult);
1511
0
    Py_DECREF(oldkey);
1512
0
    Py_DECREF(oldresult);
1513
0
    return result;
1514
0
}
1515
1516
static PyObject *
1517
bounded_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
1518
39.2k
{
1519
39.2k
    PyObject *key, *result;
1520
39.2k
    Py_hash_t hash;
1521
39.2k
    int res;
1522
1523
39.2k
    Py_BEGIN_CRITICAL_SECTION(self);
1524
39.2k
    res = bounded_lru_cache_get_lock_held(self, args, kwds, &result, &key, &hash);
1525
39.2k
    Py_END_CRITICAL_SECTION();
1526
1527
39.2k
    if (res < 0) {
1528
0
        return NULL;
1529
0
    }
1530
39.2k
    if (res > 0) {
1531
38.0k
        return result;
1532
38.0k
    }
1533
1534
1.14k
    result = PyObject_Call(self->func, args, kwds);
1535
1536
1.14k
    Py_BEGIN_CRITICAL_SECTION(self);
1537
    /* Note:  key will be stolen in the below function, and
1538
       result may be stolen or sometimes re-returned as a passthrough.
1539
       Treat both as being stolen.
1540
     */
1541
1.14k
    result = bounded_lru_cache_update_lock_held(self, result, key, hash);
1542
1.14k
    Py_END_CRITICAL_SECTION();
1543
1544
1.14k
    return result;
1545
39.2k
}
1546
1547
static PyObject *
1548
lru_cache_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1549
272
{
1550
272
    PyObject *func, *maxsize_O, *cache_info_type, *cachedict;
1551
272
    int typed;
1552
272
    lru_cache_object *obj;
1553
272
    Py_ssize_t maxsize;
1554
272
    PyObject *(*wrapper)(lru_cache_object *, PyObject *, PyObject *);
1555
272
    _functools_state *state;
1556
272
    static char *keywords[] = {"user_function", "maxsize", "typed",
1557
272
                               "cache_info_type", NULL};
1558
1559
272
    if (!PyArg_ParseTupleAndKeywords(args, kw, "OOpO:lru_cache", keywords,
1560
272
                                     &func, &maxsize_O, &typed,
1561
272
                                     &cache_info_type)) {
1562
0
        return NULL;
1563
0
    }
1564
1565
272
    if (!PyCallable_Check(func)) {
1566
0
        PyErr_SetString(PyExc_TypeError,
1567
0
                        "the first argument must be callable");
1568
0
        return NULL;
1569
0
    }
1570
1571
272
    state = get_functools_state_by_type(type);
1572
272
    if (state == NULL) {
1573
0
        return NULL;
1574
0
    }
1575
1576
    /* select the caching function, and make/inc maxsize_O */
1577
272
    if (maxsize_O == Py_None) {
1578
29
        wrapper = infinite_lru_cache_wrapper;
1579
        /* use this only to initialize lru_cache_object attribute maxsize */
1580
29
        maxsize = -1;
1581
243
    } else if (PyIndex_Check(maxsize_O)) {
1582
243
        maxsize = PyNumber_AsSsize_t(maxsize_O, PyExc_OverflowError);
1583
243
        if (maxsize == -1 && PyErr_Occurred())
1584
0
            return NULL;
1585
243
        if (maxsize < 0) {
1586
0
            maxsize = 0;
1587
0
        }
1588
243
        if (maxsize == 0)
1589
0
            wrapper = uncached_lru_cache_wrapper;
1590
243
        else
1591
243
            wrapper = bounded_lru_cache_wrapper;
1592
243
    } else {
1593
0
        PyErr_SetString(PyExc_TypeError, "maxsize should be integer or None");
1594
0
        return NULL;
1595
0
    }
1596
1597
272
    if (!(cachedict = PyDict_New()))
1598
0
        return NULL;
1599
1600
272
    obj = (lru_cache_object *)type->tp_alloc(type, 0);
1601
272
    if (obj == NULL) {
1602
0
        Py_DECREF(cachedict);
1603
0
        return NULL;
1604
0
    }
1605
1606
272
    obj->root.prev = &obj->root;
1607
272
    obj->root.next = &obj->root;
1608
272
    obj->wrapper = wrapper;
1609
272
    obj->typed = typed;
1610
272
    obj->cache = cachedict;
1611
272
    obj->func = Py_NewRef(func);
1612
272
    obj->misses = obj->hits = 0;
1613
272
    obj->maxsize = maxsize;
1614
272
    obj->kwd_mark = Py_NewRef(state->kwd_mark);
1615
272
    obj->lru_list_elem_type = (PyTypeObject*)Py_NewRef(state->lru_list_elem_type);
1616
272
    obj->cache_info_type = Py_NewRef(cache_info_type);
1617
272
    obj->dict = NULL;
1618
272
    obj->weakreflist = NULL;
1619
272
    return (PyObject *)obj;
1620
272
}
1621
1622
static lru_list_elem *
1623
lru_cache_unlink_list(lru_cache_object *self)
1624
6.09k
{
1625
6.09k
    lru_list_elem *root = &self->root;
1626
6.09k
    lru_list_elem *link = root->next;
1627
6.09k
    if (link == root)
1628
6.09k
        return NULL;
1629
0
    root->prev->next = NULL;
1630
0
    root->next = root->prev = root;
1631
0
    return link;
1632
6.09k
}
1633
1634
static void
1635
lru_cache_clear_list(lru_list_elem *link)
1636
6.09k
{
1637
6.09k
    while (link != NULL) {
1638
0
        lru_list_elem *next = link->next;
1639
0
        Py_SETREF(link, next);
1640
0
    }
1641
6.09k
}
1642
1643
static int
1644
lru_cache_tp_clear(PyObject *op)
1645
0
{
1646
0
    lru_cache_object *self = lru_cache_object_CAST(op);
1647
0
    lru_list_elem *list = lru_cache_unlink_list(self);
1648
0
    Py_CLEAR(self->cache);
1649
0
    Py_CLEAR(self->func);
1650
0
    Py_CLEAR(self->kwd_mark);
1651
0
    Py_CLEAR(self->lru_list_elem_type);
1652
0
    Py_CLEAR(self->cache_info_type);
1653
0
    Py_CLEAR(self->dict);
1654
0
    lru_cache_clear_list(list);
1655
0
    return 0;
1656
0
}
1657
1658
static void
1659
lru_cache_dealloc(PyObject *op)
1660
0
{
1661
0
    lru_cache_object *obj = lru_cache_object_CAST(op);
1662
0
    PyTypeObject *tp = Py_TYPE(obj);
1663
    /* bpo-31095: UnTrack is needed before calling any callbacks */
1664
0
    PyObject_GC_UnTrack(obj);
1665
0
    FT_CLEAR_WEAKREFS(op, obj->weakreflist);
1666
1667
0
    (void)lru_cache_tp_clear(op);
1668
0
    tp->tp_free(obj);
1669
0
    Py_DECREF(tp);
1670
0
}
1671
1672
static PyObject *
1673
lru_cache_call(PyObject *op, PyObject *args, PyObject *kwds)
1674
42.1k
{
1675
42.1k
    lru_cache_object *self = lru_cache_object_CAST(op);
1676
42.1k
    PyObject *result;
1677
42.1k
    result = self->wrapper(self, args, kwds);
1678
42.1k
    return result;
1679
42.1k
}
1680
1681
static PyObject *
1682
lru_cache_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1683
20
{
1684
20
    if (obj == Py_None || obj == NULL) {
1685
20
        return Py_NewRef(self);
1686
20
    }
1687
0
    return PyMethod_New(self, obj);
1688
20
}
1689
1690
/*[clinic input]
1691
@critical_section
1692
_functools._lru_cache_wrapper.cache_info
1693
1694
Report cache statistics
1695
[clinic start generated code]*/
1696
1697
static PyObject *
1698
_functools__lru_cache_wrapper_cache_info_impl(PyObject *self)
1699
/*[clinic end generated code: output=cc796a0b06dbd717 input=00e1acb31aa21ecc]*/
1700
0
{
1701
0
    lru_cache_object *_self = (lru_cache_object *) self;
1702
0
    if (_self->maxsize == -1) {
1703
0
        return PyObject_CallFunction(_self->cache_info_type, "nnOn",
1704
0
                                     FT_ATOMIC_LOAD_SSIZE_RELAXED(_self->hits),
1705
0
                                     FT_ATOMIC_LOAD_SSIZE_RELAXED(_self->misses),
1706
0
                                     Py_None,
1707
0
                                     PyDict_GET_SIZE(_self->cache));
1708
0
    }
1709
0
    return PyObject_CallFunction(_self->cache_info_type, "nnnn",
1710
0
                                 FT_ATOMIC_LOAD_SSIZE_RELAXED(_self->hits),
1711
0
                                 FT_ATOMIC_LOAD_SSIZE_RELAXED(_self->misses),
1712
0
                                 _self->maxsize,
1713
0
                                 PyDict_GET_SIZE(_self->cache));
1714
0
}
1715
1716
/*[clinic input]
1717
@critical_section
1718
_functools._lru_cache_wrapper.cache_clear
1719
1720
Clear the cache and cache statistics
1721
[clinic start generated code]*/
1722
1723
static PyObject *
1724
_functools__lru_cache_wrapper_cache_clear_impl(PyObject *self)
1725
/*[clinic end generated code: output=58423b35efc3e381 input=dfa33acbecf8b4b2]*/
1726
6.09k
{
1727
6.09k
    lru_cache_object *_self = (lru_cache_object *) self;
1728
6.09k
    lru_list_elem *list = lru_cache_unlink_list(_self);
1729
6.09k
    FT_ATOMIC_STORE_SSIZE_RELAXED(_self->hits, 0);
1730
6.09k
    FT_ATOMIC_STORE_SSIZE_RELAXED(_self->misses, 0);
1731
6.09k
    if (_self->wrapper == bounded_lru_cache_wrapper) {
1732
        /* The critical section on the lru cache itself protects the dictionary
1733
           for bounded_lru_cache instances. */
1734
6.09k
        _PyDict_Clear_LockHeld(_self->cache);
1735
6.09k
    } else {
1736
0
        PyDict_Clear(_self->cache);
1737
0
    }
1738
6.09k
    lru_cache_clear_list(list);
1739
6.09k
    Py_RETURN_NONE;
1740
6.09k
}
1741
1742
static PyObject *
1743
lru_cache_reduce(PyObject *self, PyObject *Py_UNUSED(dummy))
1744
0
{
1745
0
    return PyObject_GetAttrString(self, "__qualname__");
1746
0
}
1747
1748
/*[clinic input]
1749
_functools._lru_cache_wrapper.__copy__
1750
1751
Return a copy of the wrapper, which is the wrapper itself.
1752
[clinic start generated code]*/
1753
1754
static PyObject *
1755
_functools__lru_cache_wrapper___copy___impl(PyObject *self)
1756
/*[clinic end generated code: output=d681851615d57391 input=41d000bde05efb2b]*/
1757
0
{
1758
0
    return Py_NewRef(self);
1759
0
}
1760
1761
/*[clinic input]
1762
_functools._lru_cache_wrapper.__deepcopy__
1763
1764
    memo: object
1765
    /
1766
1767
Return a deep copy of the wrapper, which is the wrapper itself.
1768
[clinic start generated code]*/
1769
1770
static PyObject *
1771
_functools__lru_cache_wrapper___deepcopy__(PyObject *self, PyObject *memo)
1772
/*[clinic end generated code: output=3445cd9d96273c9e input=84f706565f55ce46]*/
1773
0
{
1774
0
    return Py_NewRef(self);
1775
0
}
1776
1777
static int
1778
lru_cache_tp_traverse(PyObject *op, visitproc visit, void *arg)
1779
6.99k
{
1780
6.99k
    lru_cache_object *self = lru_cache_object_CAST(op);
1781
6.99k
    Py_VISIT(Py_TYPE(self));
1782
6.99k
    lru_list_elem *link = self->root.next;
1783
8.13k
    while (link != &self->root) {
1784
1.14k
        lru_list_elem *next = link->next;
1785
1.14k
        Py_VISIT(link->key);
1786
1.14k
        Py_VISIT(link->result);
1787
1.14k
        Py_VISIT(Py_TYPE(link));
1788
1.14k
        link = next;
1789
1.14k
    }
1790
6.99k
    Py_VISIT(self->cache);
1791
6.99k
    Py_VISIT(self->func);
1792
6.99k
    Py_VISIT(self->kwd_mark);
1793
6.99k
    Py_VISIT(self->lru_list_elem_type);
1794
6.99k
    Py_VISIT(self->cache_info_type);
1795
6.99k
    Py_VISIT(self->dict);
1796
6.99k
    return 0;
1797
6.99k
}
1798
1799
1800
PyDoc_STRVAR(lru_cache_doc,
1801
"Create a cached callable that wraps another function.\n\
1802
\n\
1803
user_function:      the function being cached\n\
1804
\n\
1805
maxsize:  0         for no caching\n\
1806
          None      for unlimited cache size\n\
1807
          n         for a bounded cache\n\
1808
\n\
1809
typed:    False     cache f(3) and f(3.0) as identical calls\n\
1810
          True      cache f(3) and f(3.0) as distinct calls\n\
1811
\n\
1812
cache_info_type:    namedtuple class with the fields:\n\
1813
                        hits misses currsize maxsize\n"
1814
);
1815
1816
static PyMethodDef lru_cache_methods[] = {
1817
    _FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_INFO_METHODDEF
1818
    _FUNCTOOLS__LRU_CACHE_WRAPPER_CACHE_CLEAR_METHODDEF
1819
    {"__reduce__", lru_cache_reduce, METH_NOARGS},
1820
    _FUNCTOOLS__LRU_CACHE_WRAPPER___COPY___METHODDEF
1821
    _FUNCTOOLS__LRU_CACHE_WRAPPER___DEEPCOPY___METHODDEF
1822
    {NULL}
1823
};
1824
1825
static PyGetSetDef lru_cache_getsetlist[] = {
1826
    {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
1827
    {NULL}
1828
};
1829
1830
static PyMemberDef lru_cache_memberlist[] = {
1831
    {"__dictoffset__", Py_T_PYSSIZET,
1832
     offsetof(lru_cache_object, dict), Py_READONLY},
1833
    {"__weaklistoffset__", Py_T_PYSSIZET,
1834
     offsetof(lru_cache_object, weakreflist), Py_READONLY},
1835
    {NULL}  /* Sentinel */
1836
};
1837
1838
static PyType_Slot lru_cache_type_slots[] = {
1839
    {Py_tp_dealloc, lru_cache_dealloc},
1840
    {Py_tp_call, lru_cache_call},
1841
    {Py_tp_doc, (void *)lru_cache_doc},
1842
    {Py_tp_traverse, lru_cache_tp_traverse},
1843
    {Py_tp_clear, lru_cache_tp_clear},
1844
    {Py_tp_methods, lru_cache_methods},
1845
    {Py_tp_members, lru_cache_memberlist},
1846
    {Py_tp_getset, lru_cache_getsetlist},
1847
    {Py_tp_descr_get, lru_cache_descr_get},
1848
    {Py_tp_new, lru_cache_new},
1849
    {0, 0}
1850
};
1851
1852
static PyType_Spec lru_cache_type_spec = {
1853
    .name = "functools._lru_cache_wrapper",
1854
    .basicsize = sizeof(lru_cache_object),
1855
    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1856
             Py_TPFLAGS_METHOD_DESCRIPTOR | Py_TPFLAGS_IMMUTABLETYPE,
1857
    .slots = lru_cache_type_slots
1858
};
1859
1860
1861
/* module level code ********************************************************/
1862
1863
PyDoc_STRVAR(_functools_doc,
1864
"Tools that operate on functions.");
1865
1866
static PyMethodDef _functools_methods[] = {
1867
    _FUNCTOOLS_REDUCE_METHODDEF
1868
    _FUNCTOOLS_CMP_TO_KEY_METHODDEF
1869
    {NULL,              NULL}           /* sentinel */
1870
};
1871
1872
static int
1873
_functools_exec(PyObject *module)
1874
28
{
1875
28
    _functools_state *state = get_functools_state(module);
1876
28
    state->kwd_mark = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
1877
28
    if (state->kwd_mark == NULL) {
1878
0
        return -1;
1879
0
    }
1880
1881
28
    PyObject *placeholder = PySentinel_New("Placeholder", "functools", NULL);
1882
28
    if (placeholder == NULL) {
1883
0
        return -1;
1884
0
    }
1885
28
    if (PyModule_AddObjectRef(module, "Placeholder", placeholder) < 0) {
1886
0
        Py_DECREF(placeholder);
1887
0
        return -1;
1888
0
    }
1889
28
    state->placeholder = placeholder;
1890
1891
28
    state->partial_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
1892
28
        &partial_type_spec, NULL);
1893
28
    if (state->partial_type == NULL) {
1894
0
        return -1;
1895
0
    }
1896
28
    if (PyModule_AddType(module, state->partial_type) < 0) {
1897
0
        return -1;
1898
0
    }
1899
1900
28
    PyObject *lru_cache_type = PyType_FromModuleAndSpec(module,
1901
28
        &lru_cache_type_spec, NULL);
1902
28
    if (lru_cache_type == NULL) {
1903
0
        return -1;
1904
0
    }
1905
28
    if (PyModule_AddType(module, (PyTypeObject *)lru_cache_type) < 0) {
1906
0
        Py_DECREF(lru_cache_type);
1907
0
        return -1;
1908
0
    }
1909
28
    Py_DECREF(lru_cache_type);
1910
1911
28
    state->keyobject_type = (PyTypeObject *)PyType_FromModuleAndSpec(module,
1912
28
        &keyobject_type_spec, NULL);
1913
28
    if (state->keyobject_type == NULL) {
1914
0
        return -1;
1915
0
    }
1916
    // keyobject_type is used only internally.
1917
    // So we don't expose it in module namespace.
1918
1919
28
    state->lru_list_elem_type = (PyTypeObject *)PyType_FromModuleAndSpec(
1920
28
        module, &lru_list_elem_type_spec, NULL);
1921
28
    if (state->lru_list_elem_type == NULL) {
1922
0
        return -1;
1923
0
    }
1924
    // lru_list_elem is used only in _lru_cache_wrapper.
1925
    // So we don't expose it in module namespace.
1926
1927
28
    return 0;
1928
28
}
1929
1930
static int
1931
_functools_traverse(PyObject *module, visitproc visit, void *arg)
1932
1.99k
{
1933
1.99k
    _functools_state *state = get_functools_state(module);
1934
1.99k
    Py_VISIT(state->kwd_mark);
1935
1.99k
    Py_VISIT(state->placeholder);
1936
1.99k
    Py_VISIT(state->partial_type);
1937
1.99k
    Py_VISIT(state->keyobject_type);
1938
1.99k
    Py_VISIT(state->lru_list_elem_type);
1939
1.99k
    return 0;
1940
1.99k
}
1941
1942
static int
1943
_functools_clear(PyObject *module)
1944
0
{
1945
0
    _functools_state *state = get_functools_state(module);
1946
0
    Py_CLEAR(state->kwd_mark);
1947
0
    Py_CLEAR(state->placeholder);
1948
0
    Py_CLEAR(state->partial_type);
1949
0
    Py_CLEAR(state->keyobject_type);
1950
0
    Py_CLEAR(state->lru_list_elem_type);
1951
0
    return 0;
1952
0
}
1953
1954
static void
1955
_functools_free(void *module)
1956
0
{
1957
0
    (void)_functools_clear((PyObject *)module);
1958
0
}
1959
1960
static struct PyModuleDef_Slot _functools_slots[] = {
1961
    _Py_ABI_SLOT,
1962
    {Py_mod_exec, _functools_exec},
1963
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
1964
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
1965
    {0, NULL}
1966
};
1967
1968
static struct PyModuleDef _functools_module = {
1969
    PyModuleDef_HEAD_INIT,
1970
    .m_name = "_functools",
1971
    .m_doc = _functools_doc,
1972
    .m_size = sizeof(_functools_state),
1973
    .m_methods = _functools_methods,
1974
    .m_slots = _functools_slots,
1975
    .m_traverse = _functools_traverse,
1976
    .m_clear = _functools_clear,
1977
    .m_free = _functools_free,
1978
};
1979
1980
PyMODINIT_FUNC
1981
PyInit__functools(void)
1982
28
{
1983
28
    return PyModuleDef_Init(&_functools_module);
1984
28
}