Coverage Report

Created: 2025-11-24 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/bltinmodule.c
Line
Count
Source
1
/* Built-in functions */
2
3
#include "Python.h"
4
#include "pycore_ast.h"           // _PyAST_Validate()
5
#include "pycore_call.h"          // _PyObject_CallNoArgs()
6
#include "pycore_cell.h"          // PyCell_GetRef()
7
#include "pycore_ceval.h"         // _PyEval_Vector()
8
#include "pycore_compile.h"       // _PyAST_Compile()
9
#include "pycore_fileutils.h"     // _PyFile_Flush
10
#include "pycore_floatobject.h"   // _PyFloat_ExactDealloc()
11
#include "pycore_interp.h"        // _PyInterpreterState_GetConfig()
12
#include "pycore_long.h"          // _PyLong_CompactValue
13
#include "pycore_modsupport.h"    // _PyArg_NoKwnames()
14
#include "pycore_object.h"        // _Py_AddToAllObjects()
15
#include "pycore_pyerrors.h"      // _PyErr_NoMemory()
16
#include "pycore_pystate.h"       // _PyThreadState_GET()
17
#include "pycore_pythonrun.h"     // _Py_SourceAsString()
18
#include "pycore_tuple.h"         // _PyTuple_Recycle()
19
20
#include "clinic/bltinmodule.c.h"
21
22
#ifdef HAVE_UNISTD_H
23
#  include <unistd.h>             // isatty()
24
#endif
25
26
27
static PyObject*
28
update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
29
6.71k
{
30
6.71k
    Py_ssize_t i, j;
31
6.71k
    PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
32
6.71k
    assert(PyTuple_Check(bases));
33
34
12.8k
    for (i = 0; i < nargs; i++) {
35
6.11k
        base  = args[i];
36
6.11k
        if (PyType_Check(base)) {
37
6.09k
            if (new_bases) {
38
                /* If we already have made a replacement, then we append every normal base,
39
                   otherwise just skip it. */
40
0
                if (PyList_Append(new_bases, base) < 0) {
41
0
                    goto error;
42
0
                }
43
0
            }
44
6.09k
            continue;
45
6.09k
        }
46
22
        if (PyObject_GetOptionalAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
47
0
            goto error;
48
0
        }
49
22
        if (!meth) {
50
0
            if (new_bases) {
51
0
                if (PyList_Append(new_bases, base) < 0) {
52
0
                    goto error;
53
0
                }
54
0
            }
55
0
            continue;
56
0
        }
57
22
        new_base = PyObject_CallOneArg(meth, bases);
58
22
        Py_DECREF(meth);
59
22
        if (!new_base) {
60
0
            goto error;
61
0
        }
62
22
        if (!PyTuple_Check(new_base)) {
63
0
            PyErr_SetString(PyExc_TypeError,
64
0
                            "__mro_entries__ must return a tuple");
65
0
            Py_DECREF(new_base);
66
0
            goto error;
67
0
        }
68
22
        if (!new_bases) {
69
            /* If this is a first successful replacement, create new_bases list and
70
               copy previously encountered bases. */
71
22
            if (!(new_bases = PyList_New(i))) {
72
0
                Py_DECREF(new_base);
73
0
                goto error;
74
0
            }
75
30
            for (j = 0; j < i; j++) {
76
8
                base = args[j];
77
8
                PyList_SET_ITEM(new_bases, j, Py_NewRef(base));
78
8
            }
79
22
        }
80
22
        j = PyList_GET_SIZE(new_bases);
81
22
        if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
82
0
            Py_DECREF(new_base);
83
0
            goto error;
84
0
        }
85
22
        Py_DECREF(new_base);
86
22
    }
87
6.71k
    if (!new_bases) {
88
6.69k
        return bases;
89
6.69k
    }
90
22
    result = PyList_AsTuple(new_bases);
91
22
    Py_DECREF(new_bases);
92
22
    return result;
93
94
0
error:
95
0
    Py_XDECREF(new_bases);
96
0
    return NULL;
97
6.71k
}
98
99
/* AC: cannot convert yet, waiting for *args support */
100
static PyObject *
101
builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
102
                        PyObject *kwnames)
103
6.71k
{
104
6.71k
    PyObject *func, *name, *winner, *prep;
105
6.71k
    PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
106
6.71k
    PyObject *mkw = NULL, *bases = NULL;
107
6.71k
    int isclass = 0;   /* initialize to prevent gcc warning */
108
109
6.71k
    if (nargs < 2) {
110
0
        PyErr_SetString(PyExc_TypeError,
111
0
                        "__build_class__: not enough arguments");
112
0
        return NULL;
113
0
    }
114
6.71k
    func = args[0];   /* Better be callable */
115
6.71k
    if (!PyFunction_Check(func)) {
116
0
        PyErr_SetString(PyExc_TypeError,
117
0
                        "__build_class__: func must be a function");
118
0
        return NULL;
119
0
    }
120
6.71k
    name = args[1];
121
6.71k
    if (!PyUnicode_Check(name)) {
122
0
        PyErr_SetString(PyExc_TypeError,
123
0
                        "__build_class__: name is not a string");
124
0
        return NULL;
125
0
    }
126
6.71k
    orig_bases = PyTuple_FromArray(args + 2, nargs - 2);
127
6.71k
    if (orig_bases == NULL)
128
0
        return NULL;
129
130
6.71k
    bases = update_bases(orig_bases, args + 2, nargs - 2);
131
6.71k
    if (bases == NULL) {
132
0
        Py_DECREF(orig_bases);
133
0
        return NULL;
134
0
    }
135
136
6.71k
    if (kwnames == NULL) {
137
6.23k
        meta = NULL;
138
6.23k
        mkw = NULL;
139
6.23k
    }
140
487
    else {
141
487
        mkw = _PyStack_AsDict(args + nargs, kwnames);
142
487
        if (mkw == NULL) {
143
0
            goto error;
144
0
        }
145
146
487
        if (PyDict_Pop(mkw, &_Py_ID(metaclass), &meta) < 0) {
147
0
            goto error;
148
0
        }
149
487
        if (meta != NULL) {
150
            /* metaclass is explicitly given, check if it's indeed a class */
151
391
            isclass = PyType_Check(meta);
152
391
        }
153
487
    }
154
6.71k
    if (meta == NULL) {
155
        /* if there are no bases, use type: */
156
6.32k
        if (PyTuple_GET_SIZE(bases) == 0) {
157
1.62k
            meta = (PyObject *) (&PyType_Type);
158
1.62k
        }
159
        /* else get the type of the first base */
160
4.70k
        else {
161
4.70k
            PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
162
4.70k
            meta = (PyObject *)Py_TYPE(base0);
163
4.70k
        }
164
6.32k
        Py_INCREF(meta);
165
6.32k
        isclass = 1;  /* meta is really a class */
166
6.32k
    }
167
168
6.71k
    if (isclass) {
169
        /* meta is really a class, so check for a more derived
170
           metaclass, or possible metaclass conflicts: */
171
6.71k
        winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
172
6.71k
                                                        bases);
173
6.71k
        if (winner == NULL) {
174
0
            goto error;
175
0
        }
176
6.71k
        if (winner != meta) {
177
175
            Py_SETREF(meta, Py_NewRef(winner));
178
175
        }
179
6.71k
    }
180
    /* else: meta is not a class, so we cannot do the metaclass
181
       calculation, so we will use the explicitly given object as it is */
182
6.71k
    if (PyObject_GetOptionalAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
183
0
        ns = NULL;
184
0
    }
185
6.71k
    else if (prep == NULL) {
186
0
        ns = PyDict_New();
187
0
    }
188
6.71k
    else {
189
6.71k
        PyObject *pargs[2] = {name, bases};
190
6.71k
        ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
191
6.71k
        Py_DECREF(prep);
192
6.71k
    }
193
6.71k
    if (ns == NULL) {
194
0
        goto error;
195
0
    }
196
6.71k
    if (!PyMapping_Check(ns)) {
197
0
        PyErr_Format(PyExc_TypeError,
198
0
                     "%.200s.__prepare__() must return a mapping, not %.200s",
199
0
                     isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
200
0
                     Py_TYPE(ns)->tp_name);
201
0
        goto error;
202
0
    }
203
6.71k
    PyThreadState *tstate = _PyThreadState_GET();
204
6.71k
    EVAL_CALL_STAT_INC(EVAL_CALL_BUILD_CLASS);
205
6.71k
    cell = _PyEval_Vector(tstate, (PyFunctionObject *)func, ns, NULL, 0, NULL);
206
6.71k
    if (cell != NULL) {
207
6.71k
        if (bases != orig_bases) {
208
22
            if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
209
0
                goto error;
210
0
            }
211
22
        }
212
6.71k
        PyObject *margs[3] = {name, bases, ns};
213
6.71k
        cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
214
6.71k
        if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
215
589
            PyObject *cell_cls = PyCell_GetRef((PyCellObject *)cell);
216
589
            if (cell_cls != cls) {
217
0
                if (cell_cls == NULL) {
218
0
                    const char *msg =
219
0
                        "__class__ not set defining %.200R as %.200R. "
220
0
                        "Was __classcell__ propagated to type.__new__?";
221
0
                    PyErr_Format(PyExc_RuntimeError, msg, name, cls);
222
0
                } else {
223
0
                    const char *msg =
224
0
                        "__class__ set to %.200R defining %.200R as %.200R";
225
0
                    PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
226
0
                }
227
0
                Py_XDECREF(cell_cls);
228
0
                Py_SETREF(cls, NULL);
229
0
                goto error;
230
0
            }
231
589
            else {
232
589
                Py_DECREF(cell_cls);
233
589
            }
234
589
        }
235
6.71k
    }
236
6.71k
error:
237
6.71k
    Py_XDECREF(cell);
238
6.71k
    Py_XDECREF(ns);
239
6.71k
    Py_XDECREF(meta);
240
6.71k
    Py_XDECREF(mkw);
241
6.71k
    if (bases != orig_bases) {
242
22
        Py_DECREF(orig_bases);
243
22
    }
244
6.71k
    Py_DECREF(bases);
245
6.71k
    return cls;
246
6.71k
}
247
248
PyDoc_STRVAR(build_class_doc,
249
"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
250
\n\
251
Internal helper function used by the class statement.");
252
253
/*[clinic input]
254
@permit_long_docstring_body
255
__import__ as builtin___import__
256
257
    name: object
258
    globals: object(c_default="NULL") = None
259
    locals: object(c_default="NULL") = None
260
    fromlist: object(c_default="NULL") = ()
261
    level: int = 0
262
263
Import a module.
264
265
Because this function is meant for use by the Python
266
interpreter and not for general use, it is better to use
267
importlib.import_module() to programmatically import a module.
268
269
The globals argument is only used to determine the context;
270
they are not modified.  The locals argument is unused.  The fromlist
271
should be a list of names to emulate ``from name import ...``, or an
272
empty list to emulate ``import name``.
273
When importing a module from a package, note that __import__('A.B', ...)
274
returns package A when fromlist is empty, but its submodule B when
275
fromlist is not empty.  The level argument is used to determine whether to
276
perform absolute or relative imports: 0 is absolute, while a positive number
277
is the number of parent directories to search relative to the current module.
278
[clinic start generated code]*/
279
280
static PyObject *
281
builtin___import___impl(PyObject *module, PyObject *name, PyObject *globals,
282
                        PyObject *locals, PyObject *fromlist, int level)
283
/*[clinic end generated code: output=4febeda88a0cd245 input=01a3283590eae93a]*/
284
179k
{
285
179k
    return PyImport_ImportModuleLevelObject(name, globals, locals,
286
179k
                                            fromlist, level);
287
179k
}
288
289
290
/*[clinic input]
291
abs as builtin_abs
292
293
    number: object
294
    /
295
296
Return the absolute value of the argument.
297
[clinic start generated code]*/
298
299
static PyObject *
300
builtin_abs(PyObject *module, PyObject *number)
301
/*[clinic end generated code: output=861a9db97dee0595 input=a356196903543505]*/
302
0
{
303
0
    return PyNumber_Absolute(number);
304
0
}
305
306
/*[clinic input]
307
all as builtin_all
308
309
    iterable: object
310
    /
311
312
Return True if bool(x) is True for all values x in the iterable.
313
314
If the iterable is empty, return True.
315
[clinic start generated code]*/
316
317
static PyObject *
318
builtin_all(PyObject *module, PyObject *iterable)
319
/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
320
0
{
321
0
    PyObject *it, *item;
322
0
    PyObject *(*iternext)(PyObject *);
323
0
    int cmp;
324
325
0
    it = PyObject_GetIter(iterable);
326
0
    if (it == NULL)
327
0
        return NULL;
328
0
    iternext = *Py_TYPE(it)->tp_iternext;
329
330
0
    for (;;) {
331
0
        item = iternext(it);
332
0
        if (item == NULL)
333
0
            break;
334
0
        cmp = PyObject_IsTrue(item);
335
0
        Py_DECREF(item);
336
0
        if (cmp < 0) {
337
0
            Py_DECREF(it);
338
0
            return NULL;
339
0
        }
340
0
        if (cmp == 0) {
341
0
            Py_DECREF(it);
342
0
            Py_RETURN_FALSE;
343
0
        }
344
0
    }
345
0
    Py_DECREF(it);
346
0
    if (PyErr_Occurred()) {
347
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
348
0
            PyErr_Clear();
349
0
        else
350
0
            return NULL;
351
0
    }
352
0
    Py_RETURN_TRUE;
353
0
}
354
355
/*[clinic input]
356
any as builtin_any
357
358
    iterable: object
359
    /
360
361
Return True if bool(x) is True for any x in the iterable.
362
363
If the iterable is empty, return False.
364
[clinic start generated code]*/
365
366
static PyObject *
367
builtin_any(PyObject *module, PyObject *iterable)
368
/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
369
19.8k
{
370
19.8k
    PyObject *it, *item;
371
19.8k
    PyObject *(*iternext)(PyObject *);
372
19.8k
    int cmp;
373
374
19.8k
    it = PyObject_GetIter(iterable);
375
19.8k
    if (it == NULL)
376
0
        return NULL;
377
19.8k
    iternext = *Py_TYPE(it)->tp_iternext;
378
379
227k
    for (;;) {
380
227k
        item = iternext(it);
381
227k
        if (item == NULL)
382
17.6k
            break;
383
209k
        cmp = PyObject_IsTrue(item);
384
209k
        Py_DECREF(item);
385
209k
        if (cmp < 0) {
386
0
            Py_DECREF(it);
387
0
            return NULL;
388
0
        }
389
209k
        if (cmp > 0) {
390
2.27k
            Py_DECREF(it);
391
2.27k
            Py_RETURN_TRUE;
392
2.27k
        }
393
209k
    }
394
17.6k
    Py_DECREF(it);
395
17.6k
    if (PyErr_Occurred()) {
396
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
397
0
            PyErr_Clear();
398
0
        else
399
0
            return NULL;
400
0
    }
401
17.6k
    Py_RETURN_FALSE;
402
17.6k
}
403
404
/*[clinic input]
405
ascii as builtin_ascii
406
407
    obj: object
408
    /
409
410
Return an ASCII-only representation of an object.
411
412
As repr(), return a string containing a printable representation of an
413
object, but escape the non-ASCII characters in the string returned by
414
repr() using \\x, \\u or \\U escapes. This generates a string similar
415
to that returned by repr() in Python 2.
416
[clinic start generated code]*/
417
418
static PyObject *
419
builtin_ascii(PyObject *module, PyObject *obj)
420
/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
421
0
{
422
0
    return PyObject_ASCII(obj);
423
0
}
424
425
426
/*[clinic input]
427
bin as builtin_bin
428
429
    integer: object
430
    /
431
432
Return the binary representation of an integer.
433
434
   >>> bin(2796202)
435
   '0b1010101010101010101010'
436
[clinic start generated code]*/
437
438
static PyObject *
439
builtin_bin(PyObject *module, PyObject *integer)
440
/*[clinic end generated code: output=533f9388441805cc input=d16518f148341e70]*/
441
0
{
442
0
    return PyNumber_ToBase(integer, 2);
443
0
}
444
445
446
/*[clinic input]
447
callable as builtin_callable
448
449
    obj: object
450
    /
451
452
Return whether the object is callable (i.e., some kind of function).
453
454
Note that classes are callable, as are instances of classes with a
455
__call__() method.
456
[clinic start generated code]*/
457
458
static PyObject *
459
builtin_callable(PyObject *module, PyObject *obj)
460
/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
461
16.4k
{
462
16.4k
    return PyBool_FromLong((long)PyCallable_Check(obj));
463
16.4k
}
464
465
static PyObject *
466
builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
467
0
{
468
0
    PyObject *hook = PySys_GetAttrString("breakpointhook");
469
0
    if (hook == NULL) {
470
0
        return NULL;
471
0
    }
472
473
0
    if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
474
0
        Py_DECREF(hook);
475
0
        return NULL;
476
0
    }
477
478
0
    PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
479
0
    Py_DECREF(hook);
480
0
    return retval;
481
0
}
482
483
PyDoc_STRVAR(breakpoint_doc,
484
"breakpoint($module, /, *args, **kws)\n\
485
--\n\
486
\n\
487
Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept\n\
488
whatever arguments are passed.\n\
489
\n\
490
By default, this drops you into the pdb debugger.");
491
492
typedef struct {
493
    PyObject_HEAD
494
    PyObject *func;
495
    PyObject *it;
496
} filterobject;
497
498
0
#define _filterobject_CAST(op)      ((filterobject *)(op))
499
500
static PyObject *
501
filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
502
0
{
503
0
    PyObject *func, *seq;
504
0
    PyObject *it;
505
0
    filterobject *lz;
506
507
0
    if ((type == &PyFilter_Type || type->tp_init == PyFilter_Type.tp_init) &&
508
0
        !_PyArg_NoKeywords("filter", kwds))
509
0
        return NULL;
510
511
0
    if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
512
0
        return NULL;
513
514
    /* Get iterator. */
515
0
    it = PyObject_GetIter(seq);
516
0
    if (it == NULL)
517
0
        return NULL;
518
519
    /* create filterobject structure */
520
0
    lz = (filterobject *)type->tp_alloc(type, 0);
521
0
    if (lz == NULL) {
522
0
        Py_DECREF(it);
523
0
        return NULL;
524
0
    }
525
526
0
    lz->func = Py_NewRef(func);
527
0
    lz->it = it;
528
529
0
    return (PyObject *)lz;
530
0
}
531
532
static PyObject *
533
filter_vectorcall(PyObject *type, PyObject * const*args,
534
                size_t nargsf, PyObject *kwnames)
535
0
{
536
0
    PyTypeObject *tp = _PyType_CAST(type);
537
0
    if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
538
0
        return NULL;
539
0
    }
540
541
0
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
542
0
    if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
543
0
        return NULL;
544
0
    }
545
546
0
    PyObject *it = PyObject_GetIter(args[1]);
547
0
    if (it == NULL) {
548
0
        return NULL;
549
0
    }
550
551
0
    filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
552
553
0
    if (lz == NULL) {
554
0
        Py_DECREF(it);
555
0
        return NULL;
556
0
    }
557
558
0
    lz->func = Py_NewRef(args[0]);
559
0
    lz->it = it;
560
561
0
    return (PyObject *)lz;
562
0
}
563
564
static void
565
filter_dealloc(PyObject *self)
566
0
{
567
0
    filterobject *lz = _filterobject_CAST(self);
568
0
    PyObject_GC_UnTrack(lz);
569
0
    Py_XDECREF(lz->func);
570
0
    Py_XDECREF(lz->it);
571
0
    Py_TYPE(lz)->tp_free(lz);
572
0
}
573
574
static int
575
filter_traverse(PyObject *self, visitproc visit, void *arg)
576
0
{
577
0
    filterobject *lz = _filterobject_CAST(self);
578
0
    Py_VISIT(lz->it);
579
0
    Py_VISIT(lz->func);
580
0
    return 0;
581
0
}
582
583
static PyObject *
584
filter_next(PyObject *self)
585
0
{
586
0
    filterobject *lz = _filterobject_CAST(self);
587
0
    PyObject *item;
588
0
    PyObject *it = lz->it;
589
0
    long ok;
590
0
    PyObject *(*iternext)(PyObject *);
591
0
    int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
592
593
0
    iternext = *Py_TYPE(it)->tp_iternext;
594
0
    for (;;) {
595
0
        item = iternext(it);
596
0
        if (item == NULL)
597
0
            return NULL;
598
599
0
        if (checktrue) {
600
0
            ok = PyObject_IsTrue(item);
601
0
        } else {
602
0
            PyObject *good;
603
0
            good = PyObject_CallOneArg(lz->func, item);
604
0
            if (good == NULL) {
605
0
                Py_DECREF(item);
606
0
                return NULL;
607
0
            }
608
0
            ok = PyObject_IsTrue(good);
609
0
            Py_DECREF(good);
610
0
        }
611
0
        if (ok > 0)
612
0
            return item;
613
0
        Py_DECREF(item);
614
0
        if (ok < 0)
615
0
            return NULL;
616
0
    }
617
0
}
618
619
static PyObject *
620
filter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
621
0
{
622
0
    filterobject *lz = _filterobject_CAST(self);
623
0
    return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
624
0
}
625
626
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
627
628
static PyMethodDef filter_methods[] = {
629
    {"__reduce__", filter_reduce, METH_NOARGS, reduce_doc},
630
    {NULL,           NULL}           /* sentinel */
631
};
632
633
PyDoc_STRVAR(filter_doc,
634
"filter(function, iterable, /)\n\
635
--\n\
636
\n\
637
Return an iterator yielding those items of iterable for which function(item)\n\
638
is true. If function is None, return the items that are true.");
639
640
PyTypeObject PyFilter_Type = {
641
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
642
    "filter",                           /* tp_name */
643
    sizeof(filterobject),               /* tp_basicsize */
644
    0,                                  /* tp_itemsize */
645
    /* methods */
646
    filter_dealloc,                     /* tp_dealloc */
647
    0,                                  /* tp_vectorcall_offset */
648
    0,                                  /* tp_getattr */
649
    0,                                  /* tp_setattr */
650
    0,                                  /* tp_as_async */
651
    0,                                  /* tp_repr */
652
    0,                                  /* tp_as_number */
653
    0,                                  /* tp_as_sequence */
654
    0,                                  /* tp_as_mapping */
655
    0,                                  /* tp_hash */
656
    0,                                  /* tp_call */
657
    0,                                  /* tp_str */
658
    PyObject_GenericGetAttr,            /* tp_getattro */
659
    0,                                  /* tp_setattro */
660
    0,                                  /* tp_as_buffer */
661
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
662
        Py_TPFLAGS_BASETYPE,            /* tp_flags */
663
    filter_doc,                         /* tp_doc */
664
    filter_traverse,                    /* tp_traverse */
665
    0,                                  /* tp_clear */
666
    0,                                  /* tp_richcompare */
667
    0,                                  /* tp_weaklistoffset */
668
    PyObject_SelfIter,                  /* tp_iter */
669
    filter_next,                        /* tp_iternext */
670
    filter_methods,                     /* tp_methods */
671
    0,                                  /* tp_members */
672
    0,                                  /* tp_getset */
673
    0,                                  /* tp_base */
674
    0,                                  /* tp_dict */
675
    0,                                  /* tp_descr_get */
676
    0,                                  /* tp_descr_set */
677
    0,                                  /* tp_dictoffset */
678
    0,                                  /* tp_init */
679
    PyType_GenericAlloc,                /* tp_alloc */
680
    filter_new,                         /* tp_new */
681
    PyObject_GC_Del,                    /* tp_free */
682
    .tp_vectorcall = filter_vectorcall
683
};
684
685
686
/*[clinic input]
687
format as builtin_format
688
689
    value: object
690
    format_spec: unicode(c_default="NULL") = ''
691
    /
692
693
Return type(value).__format__(value, format_spec)
694
695
Many built-in types implement format_spec according to the
696
Format Specification Mini-language. See help('FORMATTING').
697
698
If type(value) does not supply a method named __format__
699
and format_spec is empty, then str(value) is returned.
700
See also help('SPECIALMETHODS').
701
[clinic start generated code]*/
702
703
static PyObject *
704
builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
705
/*[clinic end generated code: output=2f40bdfa4954b077 input=45ef3934b86d5624]*/
706
0
{
707
0
    return PyObject_Format(value, format_spec);
708
0
}
709
710
/*[clinic input]
711
chr as builtin_chr
712
713
    i: object
714
    /
715
716
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
717
[clinic start generated code]*/
718
719
static PyObject *
720
builtin_chr(PyObject *module, PyObject *i)
721
/*[clinic end generated code: output=d34f25b8035a9b10 input=f919867f0ba2f496]*/
722
309k
{
723
309k
    int overflow;
724
309k
    long v = PyLong_AsLongAndOverflow(i, &overflow);
725
309k
    if (v == -1 && PyErr_Occurred()) {
726
0
        return NULL;
727
0
    }
728
309k
    if (overflow) {
729
0
        v = overflow < 0 ? INT_MIN : INT_MAX;
730
        /* Allow PyUnicode_FromOrdinal() to raise an exception */
731
0
    }
732
309k
#if SIZEOF_INT < SIZEOF_LONG
733
309k
    else if (v < INT_MIN) {
734
0
        v = INT_MIN;
735
0
    }
736
309k
    else if (v > INT_MAX) {
737
19
        v = INT_MAX;
738
19
    }
739
309k
#endif
740
309k
    return PyUnicode_FromOrdinal(v);
741
309k
}
742
743
744
/*[clinic input]
745
compile as builtin_compile
746
747
    source: object
748
    filename: unicode_fs_decoded
749
    mode: str
750
    flags: int = 0
751
    dont_inherit: bool = False
752
    optimize: int = -1
753
    *
754
    module as modname: object = None
755
    _feature_version as feature_version: int = -1
756
757
Compile source into a code object that can be executed by exec() or eval().
758
759
The source code may represent a Python module, statement or expression.
760
The filename will be used for run-time error messages.
761
The mode must be 'exec' to compile a module, 'single' to compile a
762
single (interactive) statement, or 'eval' to compile an expression.
763
The flags argument, if present, controls which future statements influence
764
the compilation of the code.
765
The dont_inherit argument, if true, stops the compilation inheriting
766
the effects of any future statements in effect in the code calling
767
compile; if absent or false these statements do influence the compilation,
768
in addition to any features explicitly specified.
769
[clinic start generated code]*/
770
771
static PyObject *
772
builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
773
                     const char *mode, int flags, int dont_inherit,
774
                     int optimize, PyObject *modname, int feature_version)
775
/*[clinic end generated code: output=9a0dce1945917a86 input=ddeae1e0253459dc]*/
776
20.5k
{
777
20.5k
    PyObject *source_copy;
778
20.5k
    const char *str;
779
20.5k
    int compile_mode = -1;
780
20.5k
    int is_ast;
781
20.5k
    int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
782
20.5k
    PyObject *result;
783
784
20.5k
    PyCompilerFlags cf = _PyCompilerFlags_INIT;
785
20.5k
    cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
786
20.5k
    if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
787
0
        cf.cf_feature_version = feature_version;
788
0
    }
789
790
20.5k
    if (flags &
791
20.5k
        ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
792
0
    {
793
0
        PyErr_SetString(PyExc_ValueError,
794
0
                        "compile(): unrecognised flags");
795
0
        goto error;
796
0
    }
797
    /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
798
799
20.5k
    if (optimize < -1 || optimize > 2) {
800
0
        PyErr_SetString(PyExc_ValueError,
801
0
                        "compile(): invalid optimize value");
802
0
        goto error;
803
0
    }
804
20.5k
    if (modname == Py_None) {
805
20.3k
        modname = NULL;
806
20.3k
    }
807
265
    else if (!PyUnicode_Check(modname)) {
808
0
        PyErr_Format(PyExc_TypeError,
809
0
                     "compile() argument 'module' must be str or None, not %T",
810
0
                     modname);
811
0
        goto error;
812
0
    }
813
814
20.5k
    if (!dont_inherit) {
815
20.3k
        PyEval_MergeCompilerFlags(&cf);
816
20.3k
    }
817
818
20.5k
    if (strcmp(mode, "exec") == 0)
819
20.5k
        compile_mode = 0;
820
0
    else if (strcmp(mode, "eval") == 0)
821
0
        compile_mode = 1;
822
0
    else if (strcmp(mode, "single") == 0)
823
0
        compile_mode = 2;
824
0
    else if (strcmp(mode, "func_type") == 0) {
825
0
        if (!(flags & PyCF_ONLY_AST)) {
826
0
            PyErr_SetString(PyExc_ValueError,
827
0
                            "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
828
0
            goto error;
829
0
        }
830
0
        compile_mode = 3;
831
0
    }
832
0
    else {
833
0
        const char *msg;
834
0
        if (flags & PyCF_ONLY_AST)
835
0
            msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
836
0
        else
837
0
            msg = "compile() mode must be 'exec', 'eval' or 'single'";
838
0
        PyErr_SetString(PyExc_ValueError, msg);
839
0
        goto error;
840
0
    }
841
842
20.5k
    is_ast = PyAST_Check(source);
843
20.5k
    if (is_ast == -1)
844
0
        goto error;
845
20.5k
    if (is_ast) {
846
0
        PyArena *arena = _PyArena_New();
847
0
        if (arena == NULL) {
848
0
            goto error;
849
0
        }
850
851
0
        if (flags & PyCF_ONLY_AST) {
852
0
            mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
853
0
            if (mod == NULL || !_PyAST_Validate(mod)) {
854
0
                _PyArena_Free(arena);
855
0
                goto error;
856
0
            }
857
0
            int syntax_check_only = ((flags & PyCF_OPTIMIZED_AST) == PyCF_ONLY_AST); /* unoptiomized AST */
858
0
            if (_PyCompile_AstPreprocess(mod, filename, &cf, optimize, arena,
859
0
                                         syntax_check_only, modname) < 0)
860
0
            {
861
0
                _PyArena_Free(arena);
862
0
                goto error;
863
0
            }
864
0
            result = PyAST_mod2obj(mod);
865
0
        }
866
0
        else {
867
0
            mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
868
0
            if (mod == NULL || !_PyAST_Validate(mod)) {
869
0
                _PyArena_Free(arena);
870
0
                goto error;
871
0
            }
872
0
            result = (PyObject*)_PyAST_Compile(mod, filename,
873
0
                                               &cf, optimize, arena, modname);
874
0
        }
875
0
        _PyArena_Free(arena);
876
0
        goto finally;
877
0
    }
878
879
20.5k
    str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
880
20.5k
    if (str == NULL)
881
6
        goto error;
882
883
#ifdef Py_GIL_DISABLED
884
    // Disable immortalization of code constants for explicit
885
    // compile() calls to get consistent frozen outputs between the default
886
    // and free-threaded builds.
887
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
888
    tstate->suppress_co_const_immortalization++;
889
#endif
890
891
20.5k
    result = _Py_CompileStringObjectWithModule(str, filename,
892
20.5k
                                               start[compile_mode], &cf,
893
20.5k
                                               optimize, modname);
894
895
#ifdef Py_GIL_DISABLED
896
    tstate->suppress_co_const_immortalization--;
897
#endif
898
899
20.5k
    Py_XDECREF(source_copy);
900
20.5k
    goto finally;
901
902
6
error:
903
6
    result = NULL;
904
20.5k
finally:
905
20.5k
    return result;
906
6
}
907
908
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
909
static PyObject *
910
builtin_dir(PyObject *self, PyObject *args)
911
5.11k
{
912
5.11k
    PyObject *arg = NULL;
913
914
5.11k
    if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
915
0
        return NULL;
916
5.11k
    return PyObject_Dir(arg);
917
5.11k
}
918
919
PyDoc_STRVAR(dir_doc,
920
"dir([object]) -> list of strings\n"
921
"\n"
922
"If called without an argument, return the names in the current scope.\n"
923
"Else, return an alphabetized list of names comprising (some of) the attributes\n"
924
"of the given object, and of attributes reachable from it.\n"
925
"If the object supplies a method named __dir__, it will be used; otherwise\n"
926
"the default dir() logic is used and returns:\n"
927
"  for a module object: the module's attributes.\n"
928
"  for a class object:  its attributes, and recursively the attributes\n"
929
"    of its bases.\n"
930
"  for any other object: its attributes, its class's attributes, and\n"
931
"    recursively the attributes of its class's base classes.");
932
933
/*[clinic input]
934
divmod as builtin_divmod
935
936
    x: object
937
    y: object
938
    /
939
940
Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
941
[clinic start generated code]*/
942
943
static PyObject *
944
builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
945
/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
946
119
{
947
119
    return PyNumber_Divmod(x, y);
948
119
}
949
950
951
/*[clinic input]
952
eval as builtin_eval
953
954
    source: object
955
    /
956
    globals: object = None
957
    locals: object = None
958
959
Evaluate the given source in the context of globals and locals.
960
961
The source may be a string representing a Python expression
962
or a code object as returned by compile().
963
The globals must be a dictionary and locals can be any mapping,
964
defaulting to the current globals and locals.
965
If only globals is given, locals defaults to it.
966
[clinic start generated code]*/
967
968
static PyObject *
969
builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
970
                  PyObject *locals)
971
/*[clinic end generated code: output=0a0824aa70093116 input=7c7bce5299a89062]*/
972
85
{
973
85
    PyThreadState *tstate = _PyThreadState_GET();
974
85
    PyObject *result = NULL, *source_copy;
975
85
    const char *str;
976
977
85
    if (locals != Py_None && !PyMapping_Check(locals)) {
978
0
        PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
979
0
        return NULL;
980
0
    }
981
85
    if (globals != Py_None && !PyDict_Check(globals)) {
982
0
        PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
983
0
            "globals must be a real dict; try eval(expr, {}, mapping)"
984
0
            : "globals must be a dict");
985
0
        return NULL;
986
0
    }
987
988
85
    int fromframe = 0;
989
85
    if (globals != Py_None) {
990
85
        Py_INCREF(globals);
991
85
    }
992
0
    else if (_PyEval_GetFrame() != NULL) {
993
0
        fromframe = 1;
994
0
        globals = PyEval_GetGlobals();
995
0
        assert(globals != NULL);
996
0
        Py_INCREF(globals);
997
0
    }
998
0
    else {
999
0
        globals = _PyEval_GetGlobalsFromRunningMain(tstate);
1000
0
        if (globals == NULL) {
1001
0
            if (!_PyErr_Occurred(tstate)) {
1002
0
                PyErr_SetString(PyExc_TypeError,
1003
0
                    "eval must be given globals and locals "
1004
0
                    "when called without a frame");
1005
0
            }
1006
0
            return NULL;
1007
0
        }
1008
0
        Py_INCREF(globals);
1009
0
    }
1010
1011
85
    if (locals != Py_None) {
1012
0
        Py_INCREF(locals);
1013
0
    }
1014
85
    else if (fromframe) {
1015
0
        locals = _PyEval_GetFrameLocals();
1016
0
        if (locals == NULL) {
1017
0
            assert(PyErr_Occurred());
1018
0
            Py_DECREF(globals);
1019
0
            return NULL;
1020
0
        }
1021
0
    }
1022
85
    else {
1023
85
        locals = Py_NewRef(globals);
1024
85
    }
1025
1026
85
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1027
0
        goto error;
1028
0
    }
1029
1030
85
    if (PyCode_Check(source)) {
1031
0
        if (PySys_Audit("exec", "O", source) < 0) {
1032
0
            goto error;
1033
0
        }
1034
1035
0
        if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
1036
0
            PyErr_SetString(PyExc_TypeError,
1037
0
                "code object passed to eval() may not contain free variables");
1038
0
            goto error;
1039
0
        }
1040
0
        result = PyEval_EvalCode(source, globals, locals);
1041
0
    }
1042
85
    else {
1043
85
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1044
85
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1045
85
        str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
1046
85
        if (str == NULL)
1047
0
            goto error;
1048
1049
85
        while (*str == ' ' || *str == '\t')
1050
0
            str++;
1051
1052
85
        (void)PyEval_MergeCompilerFlags(&cf);
1053
#ifdef Py_GIL_DISABLED
1054
        // Don't immortalize code constants for explicit eval() calls
1055
        // to avoid memory leaks.
1056
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
1057
        tstate->suppress_co_const_immortalization++;
1058
#endif
1059
85
        result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1060
#ifdef Py_GIL_DISABLED
1061
        tstate->suppress_co_const_immortalization--;
1062
#endif
1063
85
        Py_XDECREF(source_copy);
1064
85
    }
1065
1066
85
  error:
1067
85
    Py_XDECREF(globals);
1068
85
    Py_XDECREF(locals);
1069
85
    return result;
1070
85
}
1071
1072
/*[clinic input]
1073
exec as builtin_exec
1074
1075
    source: object
1076
    /
1077
    globals: object = None
1078
    locals: object = None
1079
    *
1080
    closure: object(c_default="NULL") = None
1081
1082
Execute the given source in the context of globals and locals.
1083
1084
The source may be a string representing one or more Python statements
1085
or a code object as returned by compile().
1086
The globals must be a dictionary and locals can be any mapping,
1087
defaulting to the current globals and locals.
1088
If only globals is given, locals defaults to it.
1089
The closure must be a tuple of cellvars, and can only be used
1090
when source is a code object requiring exactly that many cellvars.
1091
[clinic start generated code]*/
1092
1093
static PyObject *
1094
builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
1095
                  PyObject *locals, PyObject *closure)
1096
/*[clinic end generated code: output=7579eb4e7646743d input=25e989b6d87a3a21]*/
1097
6.83k
{
1098
6.83k
    PyThreadState *tstate = _PyThreadState_GET();
1099
6.83k
    PyObject *v;
1100
1101
6.83k
    int fromframe = 0;
1102
6.83k
    if (globals != Py_None) {
1103
6.83k
        Py_INCREF(globals);
1104
6.83k
    }
1105
0
    else if (_PyEval_GetFrame() != NULL) {
1106
0
        fromframe = 1;
1107
0
        globals = PyEval_GetGlobals();
1108
0
        assert(globals != NULL);
1109
0
        Py_INCREF(globals);
1110
0
    }
1111
0
    else {
1112
0
        globals = _PyEval_GetGlobalsFromRunningMain(tstate);
1113
0
        if (globals == NULL) {
1114
0
            if (!_PyErr_Occurred(tstate)) {
1115
0
                PyErr_SetString(PyExc_SystemError,
1116
0
                                "globals and locals cannot be NULL");
1117
0
            }
1118
0
            goto error;
1119
0
        }
1120
0
        Py_INCREF(globals);
1121
0
    }
1122
1123
6.83k
    if (locals != Py_None) {
1124
12
        Py_INCREF(locals);
1125
12
    }
1126
6.82k
    else if (fromframe) {
1127
0
        locals = _PyEval_GetFrameLocals();
1128
0
        if (locals == NULL) {
1129
0
            assert(PyErr_Occurred());
1130
0
            Py_DECREF(globals);
1131
0
            return NULL;
1132
0
        }
1133
0
    }
1134
6.82k
    else {
1135
6.82k
        locals = Py_NewRef(globals);
1136
6.82k
    }
1137
1138
6.83k
    if (!PyDict_Check(globals)) {
1139
0
        PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
1140
0
                     Py_TYPE(globals)->tp_name);
1141
0
        goto error;
1142
0
    }
1143
6.83k
    if (!PyMapping_Check(locals)) {
1144
0
        PyErr_Format(PyExc_TypeError,
1145
0
            "locals must be a mapping or None, not %.100s",
1146
0
            Py_TYPE(locals)->tp_name);
1147
0
        goto error;
1148
0
    }
1149
1150
6.83k
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1151
0
        goto error;
1152
0
    }
1153
1154
6.83k
    if (closure == Py_None) {
1155
0
        closure = NULL;
1156
0
    }
1157
1158
6.83k
    if (PyCode_Check(source)) {
1159
6.82k
        Py_ssize_t num_free = PyCode_GetNumFree((PyCodeObject *)source);
1160
6.82k
        if (num_free == 0) {
1161
6.82k
            if (closure) {
1162
0
                PyErr_SetString(PyExc_TypeError,
1163
0
                    "cannot use a closure with this code object");
1164
0
                goto error;
1165
0
            }
1166
6.82k
        } else {
1167
0
            int closure_is_ok =
1168
0
                closure
1169
0
                && PyTuple_CheckExact(closure)
1170
0
                && (PyTuple_GET_SIZE(closure) == num_free);
1171
0
            if (closure_is_ok) {
1172
0
                for (Py_ssize_t i = 0; i < num_free; i++) {
1173
0
                    PyObject *cell = PyTuple_GET_ITEM(closure, i);
1174
0
                    if (!PyCell_Check(cell)) {
1175
0
                        closure_is_ok = 0;
1176
0
                        break;
1177
0
                    }
1178
0
                }
1179
0
            }
1180
0
            if (!closure_is_ok) {
1181
0
                PyErr_Format(PyExc_TypeError,
1182
0
                    "code object requires a closure of exactly length %zd",
1183
0
                    num_free);
1184
0
                goto error;
1185
0
            }
1186
0
        }
1187
1188
6.82k
        if (PySys_Audit("exec", "O", source) < 0) {
1189
0
            goto error;
1190
0
        }
1191
1192
6.82k
        if (!closure) {
1193
6.82k
            v = PyEval_EvalCode(source, globals, locals);
1194
6.82k
        } else {
1195
0
            v = PyEval_EvalCodeEx(source, globals, locals,
1196
0
                NULL, 0,
1197
0
                NULL, 0,
1198
0
                NULL, 0,
1199
0
                NULL,
1200
0
                closure);
1201
0
        }
1202
6.82k
    }
1203
12
    else {
1204
12
        if (closure != NULL) {
1205
0
            PyErr_SetString(PyExc_TypeError,
1206
0
                "closure can only be used when source is a code object");
1207
0
            goto error;
1208
0
        }
1209
12
        PyObject *source_copy;
1210
12
        const char *str;
1211
12
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1212
12
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1213
12
        str = _Py_SourceAsString(source, "exec",
1214
12
                                       "string, bytes or code", &cf,
1215
12
                                       &source_copy);
1216
12
        if (str == NULL)
1217
0
            goto error;
1218
12
        if (PyEval_MergeCompilerFlags(&cf))
1219
12
            v = PyRun_StringFlags(str, Py_file_input, globals,
1220
12
                                  locals, &cf);
1221
0
        else
1222
0
            v = PyRun_String(str, Py_file_input, globals, locals);
1223
12
        Py_XDECREF(source_copy);
1224
12
    }
1225
6.83k
    if (v == NULL)
1226
5.40k
        goto error;
1227
1.42k
    Py_DECREF(globals);
1228
1.42k
    Py_DECREF(locals);
1229
1.42k
    Py_DECREF(v);
1230
1.42k
    Py_RETURN_NONE;
1231
1232
5.40k
  error:
1233
5.40k
    Py_XDECREF(globals);
1234
5.40k
    Py_XDECREF(locals);
1235
5.40k
    return NULL;
1236
6.83k
}
1237
1238
1239
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1240
static PyObject *
1241
builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
1242
2.36M
{
1243
2.36M
    PyObject *v, *name, *result;
1244
1245
2.36M
    if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
1246
0
        return NULL;
1247
1248
2.36M
    v = args[0];
1249
2.36M
    name = args[1];
1250
2.36M
    if (nargs > 2) {
1251
2.22M
        if (PyObject_GetOptionalAttr(v, name, &result) == 0) {
1252
1.77M
            PyObject *dflt = args[2];
1253
1.77M
            return Py_NewRef(dflt);
1254
1.77M
        }
1255
2.22M
    }
1256
144k
    else {
1257
144k
        result = PyObject_GetAttr(v, name);
1258
144k
    }
1259
587k
    return result;
1260
2.36M
}
1261
1262
PyDoc_STRVAR(getattr_doc,
1263
"getattr(object, name[, default]) -> value\n\
1264
\n\
1265
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1266
When a default argument is given, it is returned when the attribute doesn't\n\
1267
exist; without it, an exception is raised in that case.");
1268
1269
1270
/*[clinic input]
1271
globals as builtin_globals
1272
1273
Return the dictionary containing the current scope's global variables.
1274
1275
NOTE: Updates to this dictionary *will* affect name lookups in the current
1276
global scope and vice-versa.
1277
[clinic start generated code]*/
1278
1279
static PyObject *
1280
builtin_globals_impl(PyObject *module)
1281
/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
1282
645
{
1283
645
    PyObject *globals;
1284
645
    if (_PyEval_GetFrame() != NULL) {
1285
645
        globals = PyEval_GetGlobals();
1286
645
        assert(globals != NULL);
1287
645
        return Py_NewRef(globals);
1288
645
    }
1289
0
    PyThreadState *tstate = _PyThreadState_GET();
1290
0
    globals = _PyEval_GetGlobalsFromRunningMain(tstate);
1291
0
    if (globals == NULL) {
1292
0
        if (_PyErr_Occurred(tstate)) {
1293
0
            return NULL;
1294
0
        }
1295
0
        Py_RETURN_NONE;
1296
0
    }
1297
0
    return Py_NewRef(globals);
1298
0
}
1299
1300
1301
/*[clinic input]
1302
hasattr as builtin_hasattr
1303
1304
    obj: object
1305
    name: object
1306
    /
1307
1308
Return whether the object has an attribute with the given name.
1309
1310
This is done by calling getattr(obj, name) and catching AttributeError.
1311
[clinic start generated code]*/
1312
1313
static PyObject *
1314
builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1315
/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
1316
7.93M
{
1317
7.93M
    PyObject *v;
1318
1319
7.93M
    if (PyObject_GetOptionalAttr(obj, name, &v) < 0) {
1320
0
        return NULL;
1321
0
    }
1322
7.93M
    if (v == NULL) {
1323
284k
        Py_RETURN_FALSE;
1324
284k
    }
1325
7.65M
    Py_DECREF(v);
1326
7.65M
    Py_RETURN_TRUE;
1327
7.93M
}
1328
1329
1330
/* AC: gdb's integration with CPython relies on builtin_id having
1331
 * the *exact* parameter names of "self" and "v", so we ensure we
1332
 * preserve those name rather than using the AC defaults.
1333
 */
1334
/*[clinic input]
1335
id as builtin_id
1336
1337
    self: self(type="PyModuleDef *")
1338
    obj as v: object
1339
    /
1340
1341
Return the identity of an object.
1342
1343
This is guaranteed to be unique among simultaneously existing objects.
1344
(CPython uses the object's memory address.)
1345
[clinic start generated code]*/
1346
1347
static PyObject *
1348
builtin_id_impl(PyModuleDef *self, PyObject *v)
1349
/*[clinic end generated code: output=4908a6782ed343e9 input=5a534136419631f4]*/
1350
305
{
1351
305
    PyObject *id = PyLong_FromVoidPtr(v);
1352
1353
305
    if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1354
0
        Py_DECREF(id);
1355
0
        return NULL;
1356
0
    }
1357
1358
305
    return id;
1359
305
}
1360
1361
1362
/* map object ************************************************************/
1363
1364
typedef struct {
1365
    PyObject_HEAD
1366
    PyObject *iters;
1367
    PyObject *func;
1368
    int strict;
1369
} mapobject;
1370
1371
53.5M
#define _mapobject_CAST(op)     ((mapobject *)(op))
1372
1373
static PyObject *
1374
map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1375
0
{
1376
0
    PyObject *it, *iters, *func;
1377
0
    mapobject *lz;
1378
0
    Py_ssize_t numargs, i;
1379
0
    int strict = 0;
1380
1381
0
    if (kwds) {
1382
0
        PyObject *empty = PyTuple_New(0);
1383
0
        if (empty == NULL) {
1384
0
            return NULL;
1385
0
        }
1386
0
        static char *kwlist[] = {"strict", NULL};
1387
0
        int parsed = PyArg_ParseTupleAndKeywords(
1388
0
                empty, kwds, "|$p:map", kwlist, &strict);
1389
0
        Py_DECREF(empty);
1390
0
        if (!parsed) {
1391
0
            return NULL;
1392
0
        }
1393
0
    }
1394
1395
0
    numargs = PyTuple_Size(args);
1396
0
    if (numargs < 2) {
1397
0
        PyErr_SetString(PyExc_TypeError,
1398
0
           "map() must have at least two arguments.");
1399
0
        return NULL;
1400
0
    }
1401
1402
0
    iters = PyTuple_New(numargs-1);
1403
0
    if (iters == NULL)
1404
0
        return NULL;
1405
1406
0
    for (i=1 ; i<numargs ; i++) {
1407
        /* Get iterator. */
1408
0
        it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1409
0
        if (it == NULL) {
1410
0
            Py_DECREF(iters);
1411
0
            return NULL;
1412
0
        }
1413
0
        PyTuple_SET_ITEM(iters, i-1, it);
1414
0
    }
1415
1416
    /* create mapobject structure */
1417
0
    lz = (mapobject *)type->tp_alloc(type, 0);
1418
0
    if (lz == NULL) {
1419
0
        Py_DECREF(iters);
1420
0
        return NULL;
1421
0
    }
1422
0
    lz->iters = iters;
1423
0
    func = PyTuple_GET_ITEM(args, 0);
1424
0
    lz->func = Py_NewRef(func);
1425
0
    lz->strict = strict;
1426
1427
0
    return (PyObject *)lz;
1428
0
}
1429
1430
static PyObject *
1431
map_vectorcall(PyObject *type, PyObject * const*args,
1432
                size_t nargsf, PyObject *kwnames)
1433
208k
{
1434
208k
    PyTypeObject *tp = _PyType_CAST(type);
1435
1436
208k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1437
208k
    if (kwnames != NULL && PyTuple_GET_SIZE(kwnames) != 0) {
1438
        // Fallback to map_new()
1439
0
        PyThreadState *tstate = _PyThreadState_GET();
1440
0
        return _PyObject_MakeTpCall(tstate, type, args, nargs, kwnames);
1441
0
    }
1442
1443
208k
    if (nargs < 2) {
1444
0
        PyErr_SetString(PyExc_TypeError,
1445
0
           "map() must have at least two arguments.");
1446
0
        return NULL;
1447
0
    }
1448
1449
208k
    PyObject *iters = PyTuple_New(nargs-1);
1450
208k
    if (iters == NULL) {
1451
0
        return NULL;
1452
0
    }
1453
1454
417k
    for (int i=1; i<nargs; i++) {
1455
208k
        PyObject *it = PyObject_GetIter(args[i]);
1456
208k
        if (it == NULL) {
1457
0
            Py_DECREF(iters);
1458
0
            return NULL;
1459
0
        }
1460
208k
        PyTuple_SET_ITEM(iters, i-1, it);
1461
208k
    }
1462
1463
208k
    mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1464
208k
    if (lz == NULL) {
1465
0
        Py_DECREF(iters);
1466
0
        return NULL;
1467
0
    }
1468
208k
    lz->iters = iters;
1469
208k
    lz->func = Py_NewRef(args[0]);
1470
208k
    lz->strict = 0;
1471
1472
208k
    return (PyObject *)lz;
1473
208k
}
1474
1475
static void
1476
map_dealloc(PyObject *self)
1477
208k
{
1478
208k
    mapobject *lz = _mapobject_CAST(self);
1479
208k
    PyObject_GC_UnTrack(lz);
1480
208k
    Py_XDECREF(lz->iters);
1481
208k
    Py_XDECREF(lz->func);
1482
208k
    Py_TYPE(lz)->tp_free(lz);
1483
208k
}
1484
1485
static int
1486
map_traverse(PyObject *self, visitproc visit, void *arg)
1487
469
{
1488
469
    mapobject *lz = _mapobject_CAST(self);
1489
469
    Py_VISIT(lz->iters);
1490
469
    Py_VISIT(lz->func);
1491
469
    return 0;
1492
469
}
1493
1494
static PyObject *
1495
map_next(PyObject *self)
1496
53.3M
{
1497
53.3M
    mapobject *lz = _mapobject_CAST(self);
1498
53.3M
    Py_ssize_t i;
1499
53.3M
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1500
53.3M
    PyObject **stack;
1501
53.3M
    PyObject *result = NULL;
1502
53.3M
    PyThreadState *tstate = _PyThreadState_GET();
1503
1504
53.3M
    const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
1505
53.3M
    if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1506
53.3M
        stack = small_stack;
1507
53.3M
    }
1508
0
    else {
1509
0
        stack = PyMem_Malloc(niters * sizeof(stack[0]));
1510
0
        if (stack == NULL) {
1511
0
            _PyErr_NoMemory(tstate);
1512
0
            return NULL;
1513
0
        }
1514
0
    }
1515
1516
53.3M
    Py_ssize_t nargs = 0;
1517
106M
    for (i = 0; i < niters; i++) {
1518
53.3M
        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1519
53.3M
        PyObject *val = Py_TYPE(it)->tp_iternext(it);
1520
53.3M
        if (val == NULL) {
1521
205k
            if (lz->strict) {
1522
0
                goto check;
1523
0
            }
1524
205k
            goto exit_no_result;
1525
205k
        }
1526
53.1M
        stack[i] = val;
1527
53.1M
        nargs++;
1528
53.1M
    }
1529
1530
53.1M
    result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
1531
53.1M
    goto exit;
1532
1533
0
check:
1534
0
    if (PyErr_Occurred()) {
1535
0
        if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
1536
            // next() on argument i raised an exception (not StopIteration)
1537
0
            goto exit_no_result;
1538
0
        }
1539
0
        PyErr_Clear();
1540
0
    }
1541
0
    if (i) {
1542
        // ValueError: map() argument 2 is shorter than argument 1
1543
        // ValueError: map() argument 3 is shorter than arguments 1-2
1544
0
        const char* plural = i == 1 ? " " : "s 1-";
1545
0
        PyErr_Format(PyExc_ValueError,
1546
0
                     "map() argument %d is shorter than argument%s%d",
1547
0
                     i + 1, plural, i);
1548
0
        goto exit_no_result;
1549
0
    }
1550
0
    for (i = 1; i < niters; i++) {
1551
0
        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1552
0
        PyObject *val = (*Py_TYPE(it)->tp_iternext)(it);
1553
0
        if (val) {
1554
0
            Py_DECREF(val);
1555
0
            const char* plural = i == 1 ? " " : "s 1-";
1556
0
            PyErr_Format(PyExc_ValueError,
1557
0
                         "map() argument %d is longer than argument%s%d",
1558
0
                         i + 1, plural, i);
1559
0
            goto exit_no_result;
1560
0
        }
1561
0
        if (PyErr_Occurred()) {
1562
0
            if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
1563
                // next() on argument i raised an exception (not StopIteration)
1564
0
                goto exit_no_result;
1565
0
            }
1566
0
            PyErr_Clear();
1567
0
        }
1568
        // Argument i is exhausted. So far so good...
1569
0
    }
1570
    // All arguments are exhausted. Success!
1571
1572
205k
exit_no_result:
1573
205k
    assert(result == NULL);
1574
1575
53.3M
exit:
1576
106M
    for (i = 0; i < nargs; i++) {
1577
53.1M
        Py_DECREF(stack[i]);
1578
53.1M
    }
1579
53.3M
    if (stack != small_stack) {
1580
0
        PyMem_Free(stack);
1581
0
    }
1582
53.3M
    return result;
1583
205k
}
1584
1585
static PyObject *
1586
map_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
1587
0
{
1588
0
    mapobject *lz = _mapobject_CAST(self);
1589
0
    Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1590
0
    PyObject *args = PyTuple_New(numargs+1);
1591
0
    Py_ssize_t i;
1592
0
    if (args == NULL)
1593
0
        return NULL;
1594
0
    PyTuple_SET_ITEM(args, 0, Py_NewRef(lz->func));
1595
0
    for (i = 0; i<numargs; i++){
1596
0
        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1597
0
        PyTuple_SET_ITEM(args, i+1, Py_NewRef(it));
1598
0
    }
1599
1600
0
    if (lz->strict) {
1601
0
        return Py_BuildValue("ONO", Py_TYPE(lz), args, Py_True);
1602
0
    }
1603
0
    return Py_BuildValue("ON", Py_TYPE(lz), args);
1604
0
}
1605
1606
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
1607
1608
static PyObject *
1609
map_setstate(PyObject *self, PyObject *state)
1610
0
{
1611
0
    int strict = PyObject_IsTrue(state);
1612
0
    if (strict < 0) {
1613
0
        return NULL;
1614
0
    }
1615
0
    mapobject *lz = _mapobject_CAST(self);
1616
0
    lz->strict = strict;
1617
0
    Py_RETURN_NONE;
1618
0
}
1619
1620
static PyMethodDef map_methods[] = {
1621
    {"__reduce__", map_reduce, METH_NOARGS, reduce_doc},
1622
    {"__setstate__", map_setstate, METH_O, setstate_doc},
1623
    {NULL,           NULL}           /* sentinel */
1624
};
1625
1626
1627
PyDoc_STRVAR(map_doc,
1628
"map(function, iterable, /, *iterables, strict=False)\n\
1629
--\n\
1630
\n\
1631
Make an iterator that computes the function using arguments from\n\
1632
each of the iterables.  Stops when the shortest iterable is exhausted.\n\
1633
\n\
1634
If strict is true and one of the arguments is exhausted before the others,\n\
1635
raise a ValueError.");
1636
1637
PyTypeObject PyMap_Type = {
1638
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1639
    "map",                              /* tp_name */
1640
    sizeof(mapobject),                  /* tp_basicsize */
1641
    0,                                  /* tp_itemsize */
1642
    /* methods */
1643
    map_dealloc,                        /* tp_dealloc */
1644
    0,                                  /* tp_vectorcall_offset */
1645
    0,                                  /* tp_getattr */
1646
    0,                                  /* tp_setattr */
1647
    0,                                  /* tp_as_async */
1648
    0,                                  /* tp_repr */
1649
    0,                                  /* tp_as_number */
1650
    0,                                  /* tp_as_sequence */
1651
    0,                                  /* tp_as_mapping */
1652
    0,                                  /* tp_hash */
1653
    0,                                  /* tp_call */
1654
    0,                                  /* tp_str */
1655
    PyObject_GenericGetAttr,            /* tp_getattro */
1656
    0,                                  /* tp_setattro */
1657
    0,                                  /* tp_as_buffer */
1658
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1659
        Py_TPFLAGS_BASETYPE,            /* tp_flags */
1660
    map_doc,                            /* tp_doc */
1661
    map_traverse,                       /* tp_traverse */
1662
    0,                                  /* tp_clear */
1663
    0,                                  /* tp_richcompare */
1664
    0,                                  /* tp_weaklistoffset */
1665
    PyObject_SelfIter,                  /* tp_iter */
1666
    map_next,                           /* tp_iternext */
1667
    map_methods,                        /* tp_methods */
1668
    0,                                  /* tp_members */
1669
    0,                                  /* tp_getset */
1670
    0,                                  /* tp_base */
1671
    0,                                  /* tp_dict */
1672
    0,                                  /* tp_descr_get */
1673
    0,                                  /* tp_descr_set */
1674
    0,                                  /* tp_dictoffset */
1675
    0,                                  /* tp_init */
1676
    PyType_GenericAlloc,                /* tp_alloc */
1677
    map_new,                            /* tp_new */
1678
    PyObject_GC_Del,                    /* tp_free */
1679
    .tp_vectorcall = map_vectorcall
1680
};
1681
1682
1683
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1684
static PyObject *
1685
builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
1686
16.3M
{
1687
16.3M
    PyObject *it, *res;
1688
1689
16.3M
    if (!_PyArg_CheckPositional("next", nargs, 1, 2))
1690
0
        return NULL;
1691
1692
16.3M
    it = args[0];
1693
16.3M
    if (!PyIter_Check(it)) {
1694
0
        PyErr_Format(PyExc_TypeError,
1695
0
            "'%.200s' object is not an iterator",
1696
0
            Py_TYPE(it)->tp_name);
1697
0
        return NULL;
1698
0
    }
1699
1700
16.3M
    res = (*Py_TYPE(it)->tp_iternext)(it);
1701
16.3M
    if (res != NULL) {
1702
16.2M
        return res;
1703
16.2M
    } else if (nargs > 1) {
1704
21.4k
        PyObject *def = args[1];
1705
21.4k
        if (PyErr_Occurred()) {
1706
0
            if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1707
0
                return NULL;
1708
0
            PyErr_Clear();
1709
0
        }
1710
21.4k
        return Py_NewRef(def);
1711
79.5k
    } else if (PyErr_Occurred()) {
1712
0
        return NULL;
1713
79.5k
    } else {
1714
79.5k
        PyErr_SetNone(PyExc_StopIteration);
1715
79.5k
        return NULL;
1716
79.5k
    }
1717
16.3M
}
1718
1719
PyDoc_STRVAR(next_doc,
1720
"next(iterator[, default])\n\
1721
\n\
1722
Return the next item from the iterator. If default is given and the iterator\n\
1723
is exhausted, it is returned instead of raising StopIteration.");
1724
1725
1726
/*[clinic input]
1727
setattr as builtin_setattr
1728
1729
    obj: object
1730
    name: object
1731
    value: object
1732
    /
1733
1734
Sets the named attribute on the given object to the specified value.
1735
1736
setattr(x, 'y', v) is equivalent to ``x.y = v``
1737
[clinic start generated code]*/
1738
1739
static PyObject *
1740
builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
1741
                     PyObject *value)
1742
/*[clinic end generated code: output=dc2ce1d1add9acb4 input=5e26417f2e8598d4]*/
1743
113k
{
1744
113k
    if (PyObject_SetAttr(obj, name, value) != 0)
1745
0
        return NULL;
1746
113k
    Py_RETURN_NONE;
1747
113k
}
1748
1749
1750
/*[clinic input]
1751
delattr as builtin_delattr
1752
1753
    obj: object
1754
    name: object
1755
    /
1756
1757
Deletes the named attribute from the given object.
1758
1759
delattr(x, 'y') is equivalent to ``del x.y``
1760
[clinic start generated code]*/
1761
1762
static PyObject *
1763
builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1764
/*[clinic end generated code: output=85134bc58dff79fa input=164865623abe7216]*/
1765
1.00k
{
1766
1.00k
    if (PyObject_DelAttr(obj, name) < 0) {
1767
0
        return NULL;
1768
0
    }
1769
1.00k
    Py_RETURN_NONE;
1770
1.00k
}
1771
1772
1773
/*[clinic input]
1774
hash as builtin_hash
1775
1776
    obj: object
1777
    /
1778
1779
Return the hash value for the given object.
1780
1781
Two objects that compare equal must also have the same hash value, but the
1782
reverse is not necessarily true.
1783
[clinic start generated code]*/
1784
1785
static PyObject *
1786
builtin_hash(PyObject *module, PyObject *obj)
1787
/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
1788
141k
{
1789
141k
    Py_hash_t x;
1790
1791
141k
    x = PyObject_Hash(obj);
1792
141k
    if (x == -1)
1793
0
        return NULL;
1794
141k
    return PyLong_FromSsize_t(x);
1795
141k
}
1796
1797
1798
/*[clinic input]
1799
hex as builtin_hex
1800
1801
    integer: object
1802
    /
1803
1804
Return the hexadecimal representation of an integer.
1805
1806
   >>> hex(12648430)
1807
   '0xc0ffee'
1808
[clinic start generated code]*/
1809
1810
static PyObject *
1811
builtin_hex(PyObject *module, PyObject *integer)
1812
/*[clinic end generated code: output=e5de857ba61aae08 input=3bef4746efc62fac]*/
1813
2.97k
{
1814
2.97k
    return PyNumber_ToBase(integer, 16);
1815
2.97k
}
1816
1817
1818
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1819
static PyObject *
1820
builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
1821
55.8k
{
1822
55.8k
    PyObject *v;
1823
1824
55.8k
    if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
1825
0
        return NULL;
1826
55.8k
    v = args[0];
1827
55.8k
    if (nargs == 1)
1828
55.8k
        return PyObject_GetIter(v);
1829
0
    if (!PyCallable_Check(v)) {
1830
0
        PyErr_SetString(PyExc_TypeError,
1831
0
                        "iter(v, w): v must be callable");
1832
0
        return NULL;
1833
0
    }
1834
0
    PyObject *sentinel = args[1];
1835
0
    return PyCallIter_New(v, sentinel);
1836
0
}
1837
1838
PyDoc_STRVAR(iter_doc,
1839
"iter(iterable) -> iterator\n\
1840
iter(callable, sentinel) -> iterator\n\
1841
\n\
1842
Get an iterator from an object.  In the first form, the argument must\n\
1843
supply its own iterator, or be a sequence.\n\
1844
In the second form, the callable is called until it returns the sentinel.");
1845
1846
1847
/*[clinic input]
1848
aiter as builtin_aiter
1849
1850
    async_iterable: object
1851
    /
1852
1853
Return an AsyncIterator for an AsyncIterable object.
1854
[clinic start generated code]*/
1855
1856
static PyObject *
1857
builtin_aiter(PyObject *module, PyObject *async_iterable)
1858
/*[clinic end generated code: output=1bae108d86f7960e input=473993d0cacc7d23]*/
1859
0
{
1860
0
    return PyObject_GetAIter(async_iterable);
1861
0
}
1862
1863
PyObject *PyAnextAwaitable_New(PyObject *, PyObject *);
1864
1865
/*[clinic input]
1866
anext as builtin_anext
1867
1868
    async_iterator as aiterator: object
1869
    default: object = NULL
1870
    /
1871
1872
Return the next item from the async iterator.
1873
1874
If default is given and the async iterator is exhausted,
1875
it is returned instead of raising StopAsyncIteration.
1876
[clinic start generated code]*/
1877
1878
static PyObject *
1879
builtin_anext_impl(PyObject *module, PyObject *aiterator,
1880
                   PyObject *default_value)
1881
/*[clinic end generated code: output=f02c060c163a81fa input=f3dc5a93f073e5ac]*/
1882
0
{
1883
0
    PyTypeObject *t;
1884
0
    PyObject *awaitable;
1885
1886
0
    t = Py_TYPE(aiterator);
1887
0
    if (t->tp_as_async == NULL || t->tp_as_async->am_anext == NULL) {
1888
0
        PyErr_Format(PyExc_TypeError,
1889
0
            "'%.200s' object is not an async iterator",
1890
0
            t->tp_name);
1891
0
        return NULL;
1892
0
    }
1893
1894
0
    awaitable = (*t->tp_as_async->am_anext)(aiterator);
1895
0
    if (awaitable == NULL) {
1896
0
        return NULL;
1897
0
    }
1898
0
    if (default_value == NULL) {
1899
0
        return awaitable;
1900
0
    }
1901
1902
0
    PyObject* new_awaitable = PyAnextAwaitable_New(
1903
0
            awaitable, default_value);
1904
0
    Py_DECREF(awaitable);
1905
0
    return new_awaitable;
1906
0
}
1907
1908
1909
/*[clinic input]
1910
len as builtin_len
1911
1912
    obj: object
1913
    /
1914
1915
Return the number of items in a container.
1916
[clinic start generated code]*/
1917
1918
static PyObject *
1919
builtin_len(PyObject *module, PyObject *obj)
1920
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
1921
1.53k
{
1922
1.53k
    Py_ssize_t res;
1923
1924
1.53k
    res = PyObject_Size(obj);
1925
1.53k
    if (res < 0) {
1926
0
        assert(PyErr_Occurred());
1927
0
        return NULL;
1928
0
    }
1929
1.53k
    return PyLong_FromSsize_t(res);
1930
1.53k
}
1931
1932
1933
/*[clinic input]
1934
locals as builtin_locals
1935
1936
Return a dictionary containing the current scope's local variables.
1937
1938
NOTE: Whether or not updates to this dictionary will affect name lookups in
1939
the local scope and vice-versa is *implementation dependent* and not
1940
covered by any backwards compatibility guarantees.
1941
[clinic start generated code]*/
1942
1943
static PyObject *
1944
builtin_locals_impl(PyObject *module)
1945
/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
1946
0
{
1947
0
    PyObject *locals;
1948
0
    if (_PyEval_GetFrame() != NULL) {
1949
0
        locals = _PyEval_GetFrameLocals();
1950
0
        assert(locals != NULL || PyErr_Occurred());
1951
0
        return locals;
1952
0
    }
1953
0
    PyThreadState *tstate = _PyThreadState_GET();
1954
0
    locals = _PyEval_GetGlobalsFromRunningMain(tstate);
1955
0
    if (locals == NULL) {
1956
0
        if (_PyErr_Occurred(tstate)) {
1957
0
            return NULL;
1958
0
        }
1959
0
        Py_RETURN_NONE;
1960
0
    }
1961
0
    return Py_NewRef(locals);
1962
0
}
1963
1964
1965
static PyObject *
1966
min_max(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames, int op)
1967
10.4M
{
1968
10.4M
    PyObject *it = NULL, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1969
10.4M
    PyObject *defaultval = NULL;
1970
10.4M
    static const char * const keywords[] = {"key", "default", NULL};
1971
10.4M
    static _PyArg_Parser _parser_min = {"|$OO:min", keywords, 0};
1972
10.4M
    static _PyArg_Parser _parser_max = {"|$OO:max", keywords, 0};
1973
10.4M
    const char *name = (op == Py_LT) ? "min" : "max";
1974
10.4M
    _PyArg_Parser *_parser = (op == Py_LT) ? &_parser_min : &_parser_max;
1975
1976
10.4M
    if (nargs == 0) {
1977
0
        PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1978
0
        return NULL;
1979
0
    }
1980
1981
10.4M
    if (kwnames != NULL && !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, _parser,
1982
0
                                                         &keyfunc, &defaultval)) {
1983
0
        return NULL;
1984
0
    }
1985
1986
10.4M
    const int positional = nargs > 1; // False iff nargs == 1
1987
10.4M
    if (positional && defaultval != NULL) {
1988
0
        PyErr_Format(PyExc_TypeError,
1989
0
                        "Cannot specify a default for %s() with multiple "
1990
0
                        "positional arguments", name);
1991
0
        return NULL;
1992
0
    }
1993
1994
10.4M
    if (!positional) {
1995
67.0k
        it = PyObject_GetIter(args[0]);
1996
67.0k
        if (it == NULL) {
1997
0
            return NULL;
1998
0
        }
1999
67.0k
    }
2000
2001
10.4M
    if (keyfunc == Py_None) {
2002
0
        keyfunc = NULL;
2003
0
    }
2004
2005
10.4M
    maxitem = NULL; /* the result */
2006
10.4M
    maxval = NULL;  /* the value associated with the result */
2007
31.3M
    while (1) {
2008
31.3M
        if (it == NULL) {
2009
31.1M
            if (nargs-- <= 0) {
2010
10.3M
                break;
2011
10.3M
            }
2012
20.7M
            item = *args++;
2013
20.7M
            Py_INCREF(item);
2014
20.7M
        }
2015
188k
        else {
2016
188k
            item = PyIter_Next(it);
2017
188k
            if (item == NULL) {
2018
67.0k
                if (PyErr_Occurred()) {
2019
0
                    goto Fail_it;
2020
0
                }
2021
67.0k
                break;
2022
67.0k
            }
2023
188k
        }
2024
2025
        /* get the value from the key function */
2026
20.8M
        if (keyfunc != NULL) {
2027
0
            val = PyObject_CallOneArg(keyfunc, item);
2028
0
            if (val == NULL)
2029
0
                goto Fail_it_item;
2030
0
        }
2031
        /* no key function; the value is the item */
2032
20.8M
        else {
2033
20.8M
            val = Py_NewRef(item);
2034
20.8M
        }
2035
2036
        /* maximum value and item are unset; set them */
2037
20.8M
        if (maxval == NULL) {
2038
10.4M
            maxitem = item;
2039
10.4M
            maxval = val;
2040
10.4M
        }
2041
        /* maximum value and item are set; update them as necessary */
2042
10.4M
        else {
2043
10.4M
            int cmp = PyObject_RichCompareBool(val, maxval, op);
2044
10.4M
            if (cmp < 0)
2045
0
                goto Fail_it_item_and_val;
2046
10.4M
            else if (cmp > 0) {
2047
1.42M
                Py_DECREF(maxval);
2048
1.42M
                Py_DECREF(maxitem);
2049
1.42M
                maxval = val;
2050
1.42M
                maxitem = item;
2051
1.42M
            }
2052
9.00M
            else {
2053
9.00M
                Py_DECREF(item);
2054
9.00M
                Py_DECREF(val);
2055
9.00M
            }
2056
10.4M
        }
2057
20.8M
    }
2058
10.4M
    if (maxval == NULL) {
2059
0
        assert(maxitem == NULL);
2060
0
        if (defaultval != NULL) {
2061
0
            maxitem = Py_NewRef(defaultval);
2062
0
        } else {
2063
0
            PyErr_Format(PyExc_ValueError,
2064
0
                         "%s() iterable argument is empty", name);
2065
0
        }
2066
0
    }
2067
10.4M
    else
2068
10.4M
        Py_DECREF(maxval);
2069
10.4M
    Py_XDECREF(it);
2070
10.4M
    return maxitem;
2071
2072
0
Fail_it_item_and_val:
2073
0
    Py_DECREF(val);
2074
0
Fail_it_item:
2075
0
    Py_DECREF(item);
2076
0
Fail_it:
2077
0
    Py_XDECREF(maxval);
2078
0
    Py_XDECREF(maxitem);
2079
0
    Py_XDECREF(it);
2080
0
    return NULL;
2081
0
}
2082
2083
/* AC: cannot convert yet, waiting for *args support */
2084
static PyObject *
2085
builtin_min(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2086
8.90M
{
2087
8.90M
    return min_max(args, nargs, kwnames, Py_LT);
2088
8.90M
}
2089
2090
PyDoc_STRVAR(min_doc,
2091
"min(iterable, *[, default=obj, key=func]) -> value\n\
2092
min(arg1, arg2, *args, *[, key=func]) -> value\n\
2093
\n\
2094
With a single iterable argument, return its smallest item. The\n\
2095
default keyword-only argument specifies an object to return if\n\
2096
the provided iterable is empty.\n\
2097
With two or more positional arguments, return the smallest argument.");
2098
2099
2100
/* AC: cannot convert yet, waiting for *args support */
2101
static PyObject *
2102
builtin_max(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2103
1.53M
{
2104
1.53M
    return min_max(args, nargs, kwnames, Py_GT);
2105
1.53M
}
2106
2107
PyDoc_STRVAR(max_doc,
2108
"max(iterable, *[, default=obj, key=func]) -> value\n\
2109
max(arg1, arg2, *args, *[, key=func]) -> value\n\
2110
\n\
2111
With a single iterable argument, return its biggest item. The\n\
2112
default keyword-only argument specifies an object to return if\n\
2113
the provided iterable is empty.\n\
2114
With two or more positional arguments, return the largest argument.");
2115
2116
2117
/*[clinic input]
2118
oct as builtin_oct
2119
2120
    integer: object
2121
    /
2122
2123
Return the octal representation of an integer.
2124
2125
   >>> oct(342391)
2126
   '0o1234567'
2127
[clinic start generated code]*/
2128
2129
static PyObject *
2130
builtin_oct(PyObject *module, PyObject *integer)
2131
/*[clinic end generated code: output=8c15f2145a74c390 input=b97c377b15fedf8d]*/
2132
0
{
2133
0
    return PyNumber_ToBase(integer, 8);
2134
0
}
2135
2136
2137
/*[clinic input]
2138
ord as builtin_ord
2139
2140
    character as c: object
2141
    /
2142
2143
Return the ordinal value of a character.
2144
2145
If the argument is a one-character string, return the Unicode code
2146
point of that character.
2147
2148
If the argument is a bytes or bytearray object of length 1, return its
2149
single byte value.
2150
[clinic start generated code]*/
2151
2152
static PyObject *
2153
builtin_ord(PyObject *module, PyObject *c)
2154
/*[clinic end generated code: output=4fa5e87a323bae71 input=98d38480432e1177]*/
2155
96.1M
{
2156
96.1M
    long ord;
2157
96.1M
    Py_ssize_t size;
2158
2159
96.1M
    if (PyBytes_Check(c)) {
2160
0
        size = PyBytes_GET_SIZE(c);
2161
0
        if (size == 1) {
2162
0
            ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
2163
0
            return PyLong_FromLong(ord);
2164
0
        }
2165
0
    }
2166
96.1M
    else if (PyUnicode_Check(c)) {
2167
96.1M
        size = PyUnicode_GET_LENGTH(c);
2168
96.1M
        if (size == 1) {
2169
96.1M
            ord = (long)PyUnicode_READ_CHAR(c, 0);
2170
96.1M
            return PyLong_FromLong(ord);
2171
96.1M
        }
2172
96.1M
    }
2173
0
    else if (PyByteArray_Check(c)) {
2174
        /* XXX Hopefully this is temporary */
2175
0
        size = PyByteArray_GET_SIZE(c);
2176
0
        if (size == 1) {
2177
0
            ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
2178
0
            return PyLong_FromLong(ord);
2179
0
        }
2180
0
    }
2181
0
    else {
2182
0
        PyErr_Format(PyExc_TypeError,
2183
0
                     "ord() expected string of length 1, but " \
2184
0
                     "%.200s found", Py_TYPE(c)->tp_name);
2185
0
        return NULL;
2186
0
    }
2187
2188
0
    PyErr_Format(PyExc_TypeError,
2189
0
                 "ord() expected a character, "
2190
0
                 "but string of length %zd found",
2191
0
                 size);
2192
0
    return NULL;
2193
96.1M
}
2194
2195
2196
/*[clinic input]
2197
pow as builtin_pow
2198
2199
    base: object
2200
    exp: object
2201
    mod: object = None
2202
2203
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
2204
2205
Some types, such as ints, are able to use a more efficient algorithm when
2206
invoked using the three argument form.
2207
[clinic start generated code]*/
2208
2209
static PyObject *
2210
builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
2211
                 PyObject *mod)
2212
/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
2213
0
{
2214
0
    return PyNumber_Power(base, exp, mod);
2215
0
}
2216
2217
/*[clinic input]
2218
print as builtin_print
2219
2220
    *objects: array
2221
    sep: object(c_default="Py_None") = ' '
2222
        string inserted between values, default a space.
2223
    end: object(c_default="Py_None") = '\n'
2224
        string appended after the last value, default a newline.
2225
    file: object = None
2226
        a file-like object (stream); defaults to the current sys.stdout.
2227
    flush: bool = False
2228
        whether to forcibly flush the stream.
2229
2230
Prints the values to a stream, or to sys.stdout by default.
2231
2232
[clinic start generated code]*/
2233
2234
static PyObject *
2235
builtin_print_impl(PyObject *module, PyObject * const *objects,
2236
                   Py_ssize_t objects_length, PyObject *sep, PyObject *end,
2237
                   PyObject *file, int flush)
2238
/*[clinic end generated code: output=38d8def56c837bcc input=ff35cb3d59ee8115]*/
2239
0
{
2240
0
    int i, err;
2241
2242
0
    if (file == Py_None) {
2243
0
        file = PySys_GetAttr(&_Py_ID(stdout));
2244
0
        if (file == NULL) {
2245
0
            return NULL;
2246
0
        }
2247
2248
        /* sys.stdout may be None when FILE* stdout isn't connected */
2249
0
        if (file == Py_None) {
2250
0
            Py_DECREF(file);
2251
0
            Py_RETURN_NONE;
2252
0
        }
2253
0
    }
2254
0
    else {
2255
0
        Py_INCREF(file);
2256
0
    }
2257
2258
0
    if (sep == Py_None) {
2259
0
        sep = NULL;
2260
0
    }
2261
0
    else if (sep && !PyUnicode_Check(sep)) {
2262
0
        PyErr_Format(PyExc_TypeError,
2263
0
                     "sep must be None or a string, not %.200s",
2264
0
                     Py_TYPE(sep)->tp_name);
2265
0
        Py_DECREF(file);
2266
0
        return NULL;
2267
0
    }
2268
0
    if (end == Py_None) {
2269
0
        end = NULL;
2270
0
    }
2271
0
    else if (end && !PyUnicode_Check(end)) {
2272
0
        PyErr_Format(PyExc_TypeError,
2273
0
                     "end must be None or a string, not %.200s",
2274
0
                     Py_TYPE(end)->tp_name);
2275
0
        Py_DECREF(file);
2276
0
        return NULL;
2277
0
    }
2278
2279
0
    for (i = 0; i < objects_length; i++) {
2280
0
        if (i > 0) {
2281
0
            if (sep == NULL) {
2282
0
                err = PyFile_WriteString(" ", file);
2283
0
            }
2284
0
            else {
2285
0
                err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
2286
0
            }
2287
0
            if (err) {
2288
0
                Py_DECREF(file);
2289
0
                return NULL;
2290
0
            }
2291
0
        }
2292
0
        err = PyFile_WriteObject(objects[i], file, Py_PRINT_RAW);
2293
0
        if (err) {
2294
0
            Py_DECREF(file);
2295
0
            return NULL;
2296
0
        }
2297
0
    }
2298
2299
0
    if (end == NULL) {
2300
0
        err = PyFile_WriteString("\n", file);
2301
0
    }
2302
0
    else {
2303
0
        err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2304
0
    }
2305
0
    if (err) {
2306
0
        Py_DECREF(file);
2307
0
        return NULL;
2308
0
    }
2309
2310
0
    if (flush) {
2311
0
        if (_PyFile_Flush(file) < 0) {
2312
0
            Py_DECREF(file);
2313
0
            return NULL;
2314
0
        }
2315
0
    }
2316
0
    Py_DECREF(file);
2317
2318
0
    Py_RETURN_NONE;
2319
0
}
2320
2321
2322
/*[clinic input]
2323
input as builtin_input
2324
2325
    prompt: object(c_default="NULL") = ""
2326
    /
2327
2328
Read a string from standard input.  The trailing newline is stripped.
2329
2330
The prompt string, if given, is printed to standard output without a
2331
trailing newline before reading input.
2332
2333
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2334
On *nix systems, readline is used if available.
2335
[clinic start generated code]*/
2336
2337
static PyObject *
2338
builtin_input_impl(PyObject *module, PyObject *prompt)
2339
/*[clinic end generated code: output=83db5a191e7a0d60 input=159c46d4ae40977e]*/
2340
0
{
2341
0
    PyObject *fin = NULL;
2342
0
    PyObject *fout = NULL;
2343
0
    PyObject *ferr = NULL;
2344
0
    PyObject *tmp;
2345
0
    long fd;
2346
0
    int tty;
2347
2348
    /* Check that stdin/out/err are intact */
2349
0
    fin = PySys_GetAttr(&_Py_ID(stdin));
2350
0
    if (fin == NULL) {
2351
0
        goto error;
2352
0
    }
2353
0
    if (fin == Py_None) {
2354
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
2355
0
        goto error;
2356
0
    }
2357
0
    fout = PySys_GetAttr(&_Py_ID(stdout));
2358
0
    if (fout == NULL) {
2359
0
        goto error;
2360
0
    }
2361
0
    if (fout == Py_None) {
2362
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
2363
0
        goto error;
2364
0
    }
2365
0
    ferr = PySys_GetAttr(&_Py_ID(stderr));
2366
0
    if (ferr == NULL) {
2367
0
        goto error;
2368
0
    }
2369
0
    if (ferr == Py_None) {
2370
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stderr");
2371
0
        goto error;
2372
0
    }
2373
2374
0
    if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2375
0
        goto error;
2376
0
    }
2377
2378
    /* First of all, flush stderr */
2379
0
    if (_PyFile_Flush(ferr) < 0) {
2380
0
        PyErr_Clear();
2381
0
    }
2382
2383
    /* We should only use (GNU) readline if Python's sys.stdin and
2384
       sys.stdout are the same as C's stdin and stdout, because we
2385
       need to pass it those. */
2386
0
    tmp = PyObject_CallMethodNoArgs(fin, &_Py_ID(fileno));
2387
0
    if (tmp == NULL) {
2388
0
        PyErr_Clear();
2389
0
        tty = 0;
2390
0
    }
2391
0
    else {
2392
0
        fd = PyLong_AsLong(tmp);
2393
0
        Py_DECREF(tmp);
2394
0
        if (fd < 0 && PyErr_Occurred()) {
2395
0
            goto error;
2396
0
        }
2397
0
        tty = fd == fileno(stdin) && isatty(fd);
2398
0
    }
2399
0
    if (tty) {
2400
0
        tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(fileno));
2401
0
        if (tmp == NULL) {
2402
0
            PyErr_Clear();
2403
0
            tty = 0;
2404
0
        }
2405
0
        else {
2406
0
            fd = PyLong_AsLong(tmp);
2407
0
            Py_DECREF(tmp);
2408
0
            if (fd < 0 && PyErr_Occurred())
2409
0
                goto error;
2410
0
            tty = fd == fileno(stdout) && isatty(fd);
2411
0
        }
2412
0
    }
2413
2414
    /* If we're interactive, use (GNU) readline */
2415
0
    if (tty) {
2416
0
        PyObject *po = NULL;
2417
0
        const char *promptstr;
2418
0
        char *s = NULL;
2419
0
        PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2420
0
        PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
2421
0
        const char *stdin_encoding_str, *stdin_errors_str;
2422
0
        PyObject *result;
2423
0
        size_t len;
2424
2425
        /* stdin is a text stream, so it must have an encoding. */
2426
0
        stdin_encoding = PyObject_GetAttr(fin, &_Py_ID(encoding));
2427
0
        if (stdin_encoding == NULL) {
2428
0
            tty = 0;
2429
0
            goto _readline_errors;
2430
0
        }
2431
0
        stdin_errors = PyObject_GetAttr(fin, &_Py_ID(errors));
2432
0
        if (stdin_errors == NULL) {
2433
0
            tty = 0;
2434
0
            goto _readline_errors;
2435
0
        }
2436
0
        if (!PyUnicode_Check(stdin_encoding) ||
2437
0
            !PyUnicode_Check(stdin_errors))
2438
0
        {
2439
0
            tty = 0;
2440
0
            goto _readline_errors;
2441
0
        }
2442
0
        stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2443
0
        if (stdin_encoding_str == NULL) {
2444
0
            goto _readline_errors;
2445
0
        }
2446
0
        stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
2447
0
        if (stdin_errors_str == NULL) {
2448
0
            goto _readline_errors;
2449
0
        }
2450
0
        if (_PyFile_Flush(fout) < 0) {
2451
0
            PyErr_Clear();
2452
0
        }
2453
0
        if (prompt != NULL) {
2454
            /* We have a prompt, encode it as stdout would */
2455
0
            const char *stdout_encoding_str, *stdout_errors_str;
2456
0
            PyObject *stringpo;
2457
0
            stdout_encoding = PyObject_GetAttr(fout, &_Py_ID(encoding));
2458
0
            if (stdout_encoding == NULL) {
2459
0
                tty = 0;
2460
0
                goto _readline_errors;
2461
0
            }
2462
0
            stdout_errors = PyObject_GetAttr(fout, &_Py_ID(errors));
2463
0
            if (stdout_errors == NULL) {
2464
0
                tty = 0;
2465
0
                goto _readline_errors;
2466
0
            }
2467
0
            if (!PyUnicode_Check(stdout_encoding) ||
2468
0
                !PyUnicode_Check(stdout_errors))
2469
0
            {
2470
0
                tty = 0;
2471
0
                goto _readline_errors;
2472
0
            }
2473
0
            stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2474
0
            if (stdout_encoding_str == NULL) {
2475
0
                goto _readline_errors;
2476
0
            }
2477
0
            stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
2478
0
            if (stdout_errors_str == NULL) {
2479
0
                goto _readline_errors;
2480
0
            }
2481
0
            stringpo = PyObject_Str(prompt);
2482
0
            if (stringpo == NULL)
2483
0
                goto _readline_errors;
2484
0
            po = PyUnicode_AsEncodedString(stringpo,
2485
0
                stdout_encoding_str, stdout_errors_str);
2486
0
            Py_CLEAR(stdout_encoding);
2487
0
            Py_CLEAR(stdout_errors);
2488
0
            Py_CLEAR(stringpo);
2489
0
            if (po == NULL)
2490
0
                goto _readline_errors;
2491
0
            assert(PyBytes_Check(po));
2492
0
            promptstr = PyBytes_AS_STRING(po);
2493
0
            if ((Py_ssize_t)strlen(promptstr) != PyBytes_GET_SIZE(po)) {
2494
0
                PyErr_SetString(PyExc_ValueError,
2495
0
                        "input: prompt string cannot contain null characters");
2496
0
                goto _readline_errors;
2497
0
            }
2498
0
        }
2499
0
        else {
2500
0
            po = NULL;
2501
0
            promptstr = "";
2502
0
        }
2503
0
        s = PyOS_Readline(stdin, stdout, promptstr);
2504
0
        if (s == NULL) {
2505
0
            PyErr_CheckSignals();
2506
0
            if (!PyErr_Occurred())
2507
0
                PyErr_SetNone(PyExc_KeyboardInterrupt);
2508
0
            goto _readline_errors;
2509
0
        }
2510
2511
0
        len = strlen(s);
2512
0
        if (len == 0) {
2513
0
            PyErr_SetNone(PyExc_EOFError);
2514
0
            result = NULL;
2515
0
        }
2516
0
        else {
2517
0
            if (len > PY_SSIZE_T_MAX) {
2518
0
                PyErr_SetString(PyExc_OverflowError,
2519
0
                                "input: input too long");
2520
0
                result = NULL;
2521
0
            }
2522
0
            else {
2523
0
                len--;   /* strip trailing '\n' */
2524
0
                if (len != 0 && s[len-1] == '\r')
2525
0
                    len--;   /* strip trailing '\r' */
2526
0
                result = PyUnicode_Decode(s, len, stdin_encoding_str,
2527
0
                                                  stdin_errors_str);
2528
0
            }
2529
0
        }
2530
0
        Py_DECREF(stdin_encoding);
2531
0
        Py_DECREF(stdin_errors);
2532
0
        Py_XDECREF(po);
2533
0
        PyMem_Free(s);
2534
2535
0
        if (result != NULL) {
2536
0
            if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2537
0
                goto error;
2538
0
            }
2539
0
        }
2540
2541
0
        Py_DECREF(fin);
2542
0
        Py_DECREF(fout);
2543
0
        Py_DECREF(ferr);
2544
0
        return result;
2545
2546
0
    _readline_errors:
2547
0
        Py_XDECREF(stdin_encoding);
2548
0
        Py_XDECREF(stdout_encoding);
2549
0
        Py_XDECREF(stdin_errors);
2550
0
        Py_XDECREF(stdout_errors);
2551
0
        Py_XDECREF(po);
2552
0
        if (tty)
2553
0
            goto error;
2554
2555
0
        PyErr_Clear();
2556
0
    }
2557
2558
    /* Fallback if we're not interactive */
2559
0
    if (prompt != NULL) {
2560
0
        if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
2561
0
            goto error;
2562
0
    }
2563
0
    if (_PyFile_Flush(fout) < 0) {
2564
0
        PyErr_Clear();
2565
0
    }
2566
0
    tmp = PyFile_GetLine(fin, -1);
2567
0
    Py_DECREF(fin);
2568
0
    Py_DECREF(fout);
2569
0
    Py_DECREF(ferr);
2570
0
    return tmp;
2571
2572
0
error:
2573
0
    Py_XDECREF(fin);
2574
0
    Py_XDECREF(fout);
2575
0
    Py_XDECREF(ferr);
2576
0
    return NULL;
2577
0
}
2578
2579
2580
/*[clinic input]
2581
repr as builtin_repr
2582
2583
    obj: object
2584
    /
2585
2586
Return the canonical string representation of the object.
2587
2588
For many object types, including most builtins, eval(repr(obj)) == obj.
2589
[clinic start generated code]*/
2590
2591
static PyObject *
2592
builtin_repr(PyObject *module, PyObject *obj)
2593
/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
2594
3.96M
{
2595
3.96M
    return PyObject_Repr(obj);
2596
3.96M
}
2597
2598
2599
/*[clinic input]
2600
round as builtin_round
2601
2602
    number: object
2603
    ndigits: object = None
2604
2605
Round a number to a given precision in decimal digits.
2606
2607
The return value is an integer if ndigits is omitted or None.  Otherwise
2608
the return value has the same type as the number.  ndigits may be negative.
2609
[clinic start generated code]*/
2610
2611
static PyObject *
2612
builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2613
/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
2614
0
{
2615
0
    PyObject *result;
2616
0
    if (ndigits == Py_None) {
2617
0
        result = _PyObject_MaybeCallSpecialNoArgs(number, &_Py_ID(__round__));
2618
0
    }
2619
0
    else {
2620
0
        result = _PyObject_MaybeCallSpecialOneArg(number, &_Py_ID(__round__),
2621
0
                                                  ndigits);
2622
0
    }
2623
0
    if (result == NULL && !PyErr_Occurred()) {
2624
0
        PyErr_Format(PyExc_TypeError,
2625
0
                     "type %.100s doesn't define __round__ method",
2626
0
                     Py_TYPE(number)->tp_name);
2627
0
    }
2628
0
    return result;
2629
0
}
2630
2631
2632
/*AC: we need to keep the kwds dict intact to easily call into the
2633
 * list.sort method, which isn't currently supported in AC. So we just use
2634
 * the initially generated signature with a custom implementation.
2635
 */
2636
/* [disabled clinic input]
2637
sorted as builtin_sorted
2638
2639
    iterable as seq: object
2640
    key as keyfunc: object = None
2641
    reverse: object = False
2642
2643
Return a new list containing all items from the iterable in ascending order.
2644
2645
A custom key function can be supplied to customize the sort order, and the
2646
reverse flag can be set to request the result in descending order.
2647
[end disabled clinic input]*/
2648
2649
PyDoc_STRVAR(builtin_sorted__doc__,
2650
"sorted($module, iterable, /, *, key=None, reverse=False)\n"
2651
"--\n"
2652
"\n"
2653
"Return a new list containing all items from the iterable in ascending order.\n"
2654
"\n"
2655
"A custom key function can be supplied to customize the sort order, and the\n"
2656
"reverse flag can be set to request the result in descending order.");
2657
2658
#define BUILTIN_SORTED_METHODDEF    \
2659
    {"sorted", _PyCFunction_CAST(builtin_sorted), METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
2660
2661
static PyObject *
2662
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2663
337k
{
2664
337k
    PyObject *newlist, *v, *seq, *callable;
2665
2666
    /* Keyword arguments are passed through list.sort() which will check
2667
       them. */
2668
337k
    if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
2669
0
        return NULL;
2670
2671
337k
    newlist = PySequence_List(seq);
2672
337k
    if (newlist == NULL)
2673
0
        return NULL;
2674
2675
337k
    callable = PyObject_GetAttr(newlist, &_Py_ID(sort));
2676
337k
    if (callable == NULL) {
2677
0
        Py_DECREF(newlist);
2678
0
        return NULL;
2679
0
    }
2680
2681
337k
    assert(nargs >= 1);
2682
337k
    v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
2683
337k
    Py_DECREF(callable);
2684
337k
    if (v == NULL) {
2685
0
        Py_DECREF(newlist);
2686
0
        return NULL;
2687
0
    }
2688
337k
    Py_DECREF(v);
2689
337k
    return newlist;
2690
337k
}
2691
2692
2693
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
2694
static PyObject *
2695
builtin_vars(PyObject *self, PyObject *args)
2696
28
{
2697
28
    PyObject *v = NULL;
2698
28
    PyObject *d;
2699
2700
28
    if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2701
0
        return NULL;
2702
28
    if (v == NULL) {
2703
0
        if (_PyEval_GetFrame() != NULL) {
2704
0
            d = _PyEval_GetFrameLocals();
2705
0
        }
2706
0
        else {
2707
0
            PyThreadState *tstate = _PyThreadState_GET();
2708
0
            d = _PyEval_GetGlobalsFromRunningMain(tstate);
2709
0
            if (d == NULL) {
2710
0
                if (!_PyErr_Occurred(tstate)) {
2711
0
                    d = _PyEval_GetFrameLocals();
2712
0
                    assert(_PyErr_Occurred(tstate));
2713
0
                }
2714
0
            }
2715
0
            else {
2716
0
                Py_INCREF(d);
2717
0
            }
2718
0
        }
2719
0
    }
2720
28
    else {
2721
28
        if (PyObject_GetOptionalAttr(v, &_Py_ID(__dict__), &d) == 0) {
2722
0
            PyErr_SetString(PyExc_TypeError,
2723
0
                "vars() argument must have __dict__ attribute");
2724
0
        }
2725
28
    }
2726
28
    return d;
2727
28
}
2728
2729
PyDoc_STRVAR(vars_doc,
2730
"vars([object]) -> dictionary\n\
2731
\n\
2732
Without arguments, equivalent to locals().\n\
2733
With an argument, equivalent to object.__dict__.");
2734
2735
2736
/* Improved Kahan–Babuška algorithm by Arnold Neumaier
2737
   Neumaier, A. (1974), Rundungsfehleranalyse einiger Verfahren
2738
   zur Summation endlicher Summen.  Z. angew. Math. Mech.,
2739
   54: 39-51. https://doi.org/10.1002/zamm.19740540106
2740
   https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
2741
 */
2742
2743
typedef struct {
2744
    double hi;     /* high-order bits for a running sum */
2745
    double lo;     /* a running compensation for lost low-order bits */
2746
} CompensatedSum;
2747
2748
static inline CompensatedSum
2749
cs_from_double(double x)
2750
0
{
2751
0
    return (CompensatedSum) {x};
2752
0
}
2753
2754
static inline CompensatedSum
2755
cs_add(CompensatedSum total, double x)
2756
0
{
2757
0
    double t = total.hi + x;
2758
0
    if (fabs(total.hi) >= fabs(x)) {
2759
0
        total.lo += (total.hi - t) + x;
2760
0
    }
2761
0
    else {
2762
0
        total.lo += (x - t) + total.hi;
2763
0
    }
2764
0
    return (CompensatedSum) {t, total.lo};
2765
0
}
2766
2767
static inline double
2768
cs_to_double(CompensatedSum total)
2769
0
{
2770
    /* Avoid losing the sign on a negative result,
2771
       and don't let adding the compensation convert
2772
       an infinite or overflowed sum to a NaN. */
2773
0
    if (total.lo && isfinite(total.lo)) {
2774
0
        return total.hi + total.lo;
2775
0
    }
2776
0
    return total.hi;
2777
0
}
2778
2779
/*[clinic input]
2780
sum as builtin_sum
2781
2782
    iterable: object
2783
    /
2784
    start: object(c_default="NULL") = 0
2785
2786
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2787
2788
When the iterable is empty, return the start value.
2789
This function is intended specifically for use with numeric values and may
2790
reject non-numeric types.
2791
[clinic start generated code]*/
2792
2793
static PyObject *
2794
builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2795
/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
2796
13.0M
{
2797
13.0M
    PyObject *result = start;
2798
13.0M
    PyObject *temp, *item, *iter;
2799
2800
13.0M
    iter = PyObject_GetIter(iterable);
2801
13.0M
    if (iter == NULL)
2802
0
        return NULL;
2803
2804
13.0M
    if (result == NULL) {
2805
3.40M
        result = PyLong_FromLong(0);
2806
3.40M
        if (result == NULL) {
2807
0
            Py_DECREF(iter);
2808
0
            return NULL;
2809
0
        }
2810
9.68M
    } else {
2811
        /* reject string values for 'start' parameter */
2812
9.68M
        if (PyUnicode_Check(result)) {
2813
0
            PyErr_SetString(PyExc_TypeError,
2814
0
                "sum() can't sum strings [use ''.join(seq) instead]");
2815
0
            Py_DECREF(iter);
2816
0
            return NULL;
2817
0
        }
2818
9.68M
        if (PyBytes_Check(result)) {
2819
0
            PyErr_SetString(PyExc_TypeError,
2820
0
                "sum() can't sum bytes [use b''.join(seq) instead]");
2821
0
            Py_DECREF(iter);
2822
0
            return NULL;
2823
0
        }
2824
9.68M
        if (PyByteArray_Check(result)) {
2825
0
            PyErr_SetString(PyExc_TypeError,
2826
0
                "sum() can't sum bytearray [use b''.join(seq) instead]");
2827
0
            Py_DECREF(iter);
2828
0
            return NULL;
2829
0
        }
2830
9.68M
        Py_INCREF(result);
2831
9.68M
    }
2832
2833
13.0M
#ifndef SLOW_SUM
2834
    /* Fast addition by keeping temporary sums in C instead of new Python objects.
2835
       Assumes all inputs are the same type.  If the assumption fails, default
2836
       to the more general routine.
2837
    */
2838
13.0M
    if (PyLong_CheckExact(result)) {
2839
3.40M
        int overflow;
2840
3.40M
        Py_ssize_t i_result = PyLong_AsLongAndOverflow(result, &overflow);
2841
        /* If this already overflowed, don't even enter the loop. */
2842
3.40M
        if (overflow == 0) {
2843
3.40M
            Py_SETREF(result, NULL);
2844
3.40M
        }
2845
1.24G
        while(result == NULL) {
2846
1.24G
            item = PyIter_Next(iter);
2847
1.24G
            if (item == NULL) {
2848
3.40M
                Py_DECREF(iter);
2849
3.40M
                if (PyErr_Occurred())
2850
0
                    return NULL;
2851
3.40M
                return PyLong_FromSsize_t(i_result);
2852
3.40M
            }
2853
1.23G
            if (PyLong_CheckExact(item) || PyBool_Check(item)) {
2854
1.23G
                Py_ssize_t b;
2855
1.23G
                overflow = 0;
2856
                /* Single digits are common, fast, and cannot overflow on unpacking. */
2857
1.23G
                if (_PyLong_IsCompact((PyLongObject *)item)) {
2858
1.23G
                    b = _PyLong_CompactValue((PyLongObject *)item);
2859
1.23G
                }
2860
0
                else {
2861
0
                    b = PyLong_AsLongAndOverflow(item, &overflow);
2862
0
                }
2863
1.23G
                if (overflow == 0 &&
2864
1.23G
                    (i_result >= 0 ? (b <= PY_SSIZE_T_MAX - i_result)
2865
1.23G
                                   : (b >= PY_SSIZE_T_MIN - i_result)))
2866
1.23G
                {
2867
1.23G
                    i_result += b;
2868
1.23G
                    Py_DECREF(item);
2869
1.23G
                    continue;
2870
1.23G
                }
2871
1.23G
            }
2872
            /* Either overflowed or is not an int. Restore real objects and process normally */
2873
0
            result = PyLong_FromSsize_t(i_result);
2874
0
            if (result == NULL) {
2875
0
                Py_DECREF(item);
2876
0
                Py_DECREF(iter);
2877
0
                return NULL;
2878
0
            }
2879
0
            temp = PyNumber_Add(result, item);
2880
0
            Py_DECREF(result);
2881
0
            Py_DECREF(item);
2882
0
            result = temp;
2883
0
            if (result == NULL) {
2884
0
                Py_DECREF(iter);
2885
0
                return NULL;
2886
0
            }
2887
0
        }
2888
3.40M
    }
2889
2890
9.68M
    if (PyFloat_CheckExact(result)) {
2891
0
        CompensatedSum re_sum = cs_from_double(PyFloat_AS_DOUBLE(result));
2892
0
        Py_SETREF(result, NULL);
2893
0
        while(result == NULL) {
2894
0
            item = PyIter_Next(iter);
2895
0
            if (item == NULL) {
2896
0
                Py_DECREF(iter);
2897
0
                if (PyErr_Occurred())
2898
0
                    return NULL;
2899
0
                return PyFloat_FromDouble(cs_to_double(re_sum));
2900
0
            }
2901
0
            if (PyFloat_CheckExact(item)) {
2902
0
                re_sum = cs_add(re_sum, PyFloat_AS_DOUBLE(item));
2903
0
                _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2904
0
                continue;
2905
0
            }
2906
0
            if (PyLong_Check(item)) {
2907
0
                double value = PyLong_AsDouble(item);
2908
0
                if (value != -1.0 || !PyErr_Occurred()) {
2909
0
                    re_sum = cs_add(re_sum, value);
2910
0
                    Py_DECREF(item);
2911
0
                    continue;
2912
0
                }
2913
0
                else {
2914
0
                    Py_DECREF(item);
2915
0
                    Py_DECREF(iter);
2916
0
                    return NULL;
2917
0
                }
2918
0
            }
2919
0
            result = PyFloat_FromDouble(cs_to_double(re_sum));
2920
0
            if (result == NULL) {
2921
0
                Py_DECREF(item);
2922
0
                Py_DECREF(iter);
2923
0
                return NULL;
2924
0
            }
2925
0
            temp = PyNumber_Add(result, item);
2926
0
            Py_DECREF(result);
2927
0
            Py_DECREF(item);
2928
0
            result = temp;
2929
0
            if (result == NULL) {
2930
0
                Py_DECREF(iter);
2931
0
                return NULL;
2932
0
            }
2933
0
        }
2934
0
    }
2935
2936
9.68M
    if (PyComplex_CheckExact(result)) {
2937
0
        Py_complex z = PyComplex_AsCComplex(result);
2938
0
        CompensatedSum re_sum = cs_from_double(z.real);
2939
0
        CompensatedSum im_sum = cs_from_double(z.imag);
2940
0
        Py_SETREF(result, NULL);
2941
0
        while (result == NULL) {
2942
0
            item = PyIter_Next(iter);
2943
0
            if (item == NULL) {
2944
0
                Py_DECREF(iter);
2945
0
                if (PyErr_Occurred()) {
2946
0
                    return NULL;
2947
0
                }
2948
0
                return PyComplex_FromDoubles(cs_to_double(re_sum),
2949
0
                                             cs_to_double(im_sum));
2950
0
            }
2951
0
            if (PyComplex_CheckExact(item)) {
2952
0
                z = PyComplex_AsCComplex(item);
2953
0
                re_sum = cs_add(re_sum, z.real);
2954
0
                im_sum = cs_add(im_sum, z.imag);
2955
0
                Py_DECREF(item);
2956
0
                continue;
2957
0
            }
2958
0
            if (PyLong_Check(item)) {
2959
0
                double value = PyLong_AsDouble(item);
2960
0
                if (value != -1.0 || !PyErr_Occurred()) {
2961
0
                    re_sum = cs_add(re_sum, value);
2962
0
                    Py_DECREF(item);
2963
0
                    continue;
2964
0
                }
2965
0
                else {
2966
0
                    Py_DECREF(item);
2967
0
                    Py_DECREF(iter);
2968
0
                    return NULL;
2969
0
                }
2970
0
            }
2971
0
            if (PyFloat_Check(item)) {
2972
0
                double value = PyFloat_AS_DOUBLE(item);
2973
0
                re_sum = cs_add(re_sum, value);
2974
0
                _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2975
0
                continue;
2976
0
            }
2977
0
            result = PyComplex_FromDoubles(cs_to_double(re_sum),
2978
0
                                           cs_to_double(im_sum));
2979
0
            if (result == NULL) {
2980
0
                Py_DECREF(item);
2981
0
                Py_DECREF(iter);
2982
0
                return NULL;
2983
0
            }
2984
0
            temp = PyNumber_Add(result, item);
2985
0
            Py_DECREF(result);
2986
0
            Py_DECREF(item);
2987
0
            result = temp;
2988
0
            if (result == NULL) {
2989
0
                Py_DECREF(iter);
2990
0
                return NULL;
2991
0
            }
2992
0
        }
2993
0
    }
2994
9.68M
#endif
2995
2996
30.3M
    for(;;) {
2997
30.3M
        item = PyIter_Next(iter);
2998
30.3M
        if (item == NULL) {
2999
            /* error, or end-of-sequence */
3000
9.68M
            if (PyErr_Occurred()) {
3001
20.2k
                Py_SETREF(result, NULL);
3002
20.2k
            }
3003
9.68M
            break;
3004
9.68M
        }
3005
        /* It's tempting to use PyNumber_InPlaceAdd instead of
3006
           PyNumber_Add here, to avoid quadratic running time
3007
           when doing 'sum(list_of_lists, [])'.  However, this
3008
           would produce a change in behaviour: a snippet like
3009
3010
             empty = []
3011
             sum([[x] for x in range(10)], empty)
3012
3013
           would change the value of empty. In fact, using
3014
           in-place addition rather that binary addition for
3015
           any of the steps introduces subtle behavior changes:
3016
3017
           https://bugs.python.org/issue18305 */
3018
20.6M
        temp = PyNumber_Add(result, item);
3019
20.6M
        Py_DECREF(result);
3020
20.6M
        Py_DECREF(item);
3021
20.6M
        result = temp;
3022
20.6M
        if (result == NULL)
3023
0
            break;
3024
20.6M
    }
3025
9.68M
    Py_DECREF(iter);
3026
9.68M
    return result;
3027
9.68M
}
3028
3029
3030
/*[clinic input]
3031
isinstance as builtin_isinstance
3032
3033
    obj: object
3034
    class_or_tuple: object
3035
    /
3036
3037
Return whether an object is an instance of a class or of a subclass thereof.
3038
3039
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
3040
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
3041
or ...`` etc.
3042
[clinic start generated code]*/
3043
3044
static PyObject *
3045
builtin_isinstance_impl(PyObject *module, PyObject *obj,
3046
                        PyObject *class_or_tuple)
3047
/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
3048
1.40k
{
3049
1.40k
    int retval;
3050
3051
1.40k
    retval = PyObject_IsInstance(obj, class_or_tuple);
3052
1.40k
    if (retval < 0)
3053
0
        return NULL;
3054
1.40k
    return PyBool_FromLong(retval);
3055
1.40k
}
3056
3057
3058
/*[clinic input]
3059
issubclass as builtin_issubclass
3060
3061
    cls: object
3062
    class_or_tuple: object
3063
    /
3064
3065
Return whether 'cls' is derived from another class or is the same class.
3066
3067
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
3068
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
3069
or ...``.
3070
[clinic start generated code]*/
3071
3072
static PyObject *
3073
builtin_issubclass_impl(PyObject *module, PyObject *cls,
3074
                        PyObject *class_or_tuple)
3075
/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
3076
6.66k
{
3077
6.66k
    int retval;
3078
3079
6.66k
    retval = PyObject_IsSubclass(cls, class_or_tuple);
3080
6.66k
    if (retval < 0)
3081
0
        return NULL;
3082
6.66k
    return PyBool_FromLong(retval);
3083
6.66k
}
3084
3085
typedef struct {
3086
    PyObject_HEAD
3087
    Py_ssize_t tuplesize;
3088
    PyObject *ittuple;     /* tuple of iterators */
3089
    PyObject *result;
3090
    int strict;
3091
} zipobject;
3092
3093
25.6M
#define _zipobject_CAST(op)     ((zipobject *)(op))
3094
3095
static PyObject *
3096
zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3097
106k
{
3098
106k
    zipobject *lz;
3099
106k
    Py_ssize_t i;
3100
106k
    PyObject *ittuple;  /* tuple of iterators */
3101
106k
    PyObject *result;
3102
106k
    Py_ssize_t tuplesize;
3103
106k
    int strict = 0;
3104
3105
106k
    if (kwds) {
3106
805
        PyObject *empty = PyTuple_New(0);
3107
805
        if (empty == NULL) {
3108
0
            return NULL;
3109
0
        }
3110
805
        static char *kwlist[] = {"strict", NULL};
3111
805
        int parsed = PyArg_ParseTupleAndKeywords(
3112
805
                empty, kwds, "|$p:zip", kwlist, &strict);
3113
805
        Py_DECREF(empty);
3114
805
        if (!parsed) {
3115
0
            return NULL;
3116
0
        }
3117
805
    }
3118
3119
    /* args must be a tuple */
3120
106k
    assert(PyTuple_Check(args));
3121
106k
    tuplesize = PyTuple_GET_SIZE(args);
3122
3123
    /* obtain iterators */
3124
106k
    ittuple = PyTuple_New(tuplesize);
3125
106k
    if (ittuple == NULL)
3126
0
        return NULL;
3127
318k
    for (i=0; i < tuplesize; ++i) {
3128
212k
        PyObject *item = PyTuple_GET_ITEM(args, i);
3129
212k
        PyObject *it = PyObject_GetIter(item);
3130
212k
        if (it == NULL) {
3131
0
            Py_DECREF(ittuple);
3132
0
            return NULL;
3133
0
        }
3134
212k
        PyTuple_SET_ITEM(ittuple, i, it);
3135
212k
    }
3136
3137
    /* create a result holder */
3138
106k
    result = PyTuple_New(tuplesize);
3139
106k
    if (result == NULL) {
3140
0
        Py_DECREF(ittuple);
3141
0
        return NULL;
3142
0
    }
3143
318k
    for (i=0 ; i < tuplesize ; i++) {
3144
212k
        PyTuple_SET_ITEM(result, i, Py_NewRef(Py_None));
3145
212k
    }
3146
3147
    /* create zipobject structure */
3148
106k
    lz = (zipobject *)type->tp_alloc(type, 0);
3149
106k
    if (lz == NULL) {
3150
0
        Py_DECREF(ittuple);
3151
0
        Py_DECREF(result);
3152
0
        return NULL;
3153
0
    }
3154
106k
    lz->ittuple = ittuple;
3155
106k
    lz->tuplesize = tuplesize;
3156
106k
    lz->result = result;
3157
106k
    lz->strict = strict;
3158
3159
106k
    return (PyObject *)lz;
3160
106k
}
3161
3162
static void
3163
zip_dealloc(PyObject *self)
3164
106k
{
3165
106k
    zipobject *lz = _zipobject_CAST(self);
3166
106k
    PyObject_GC_UnTrack(lz);
3167
106k
    Py_XDECREF(lz->ittuple);
3168
106k
    Py_XDECREF(lz->result);
3169
106k
    Py_TYPE(lz)->tp_free(lz);
3170
106k
}
3171
3172
static int
3173
zip_traverse(PyObject *self, visitproc visit, void *arg)
3174
233
{
3175
233
    zipobject *lz = _zipobject_CAST(self);
3176
233
    Py_VISIT(lz->ittuple);
3177
233
    Py_VISIT(lz->result);
3178
233
    return 0;
3179
233
}
3180
3181
static PyObject *
3182
zip_next(PyObject *self)
3183
25.5M
{
3184
25.5M
    zipobject *lz = _zipobject_CAST(self);
3185
3186
25.5M
    Py_ssize_t i;
3187
25.5M
    Py_ssize_t tuplesize = lz->tuplesize;
3188
25.5M
    PyObject *result = lz->result;
3189
25.5M
    PyObject *it;
3190
25.5M
    PyObject *item;
3191
25.5M
    PyObject *olditem;
3192
3193
25.5M
    if (tuplesize == 0)
3194
0
        return NULL;
3195
3196
25.5M
    if (_PyObject_IsUniquelyReferenced(result)) {
3197
25.5M
        Py_INCREF(result);
3198
76.5M
        for (i=0 ; i < tuplesize ; i++) {
3199
51.0M
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3200
51.0M
            item = (*Py_TYPE(it)->tp_iternext)(it);
3201
51.0M
            if (item == NULL) {
3202
104k
                Py_DECREF(result);
3203
104k
                if (lz->strict) {
3204
783
                    goto check;
3205
783
                }
3206
103k
                return NULL;
3207
104k
            }
3208
50.9M
            olditem = PyTuple_GET_ITEM(result, i);
3209
50.9M
            PyTuple_SET_ITEM(result, i, item);
3210
50.9M
            Py_DECREF(olditem);
3211
50.9M
        }
3212
        // bpo-42536: The GC may have untracked this result tuple. Since we're
3213
        // recycling it, make sure it's tracked again:
3214
25.4M
        _PyTuple_Recycle(result);
3215
25.4M
    } else {
3216
3.91k
        result = PyTuple_New(tuplesize);
3217
3.91k
        if (result == NULL)
3218
0
            return NULL;
3219
9.28k
        for (i=0 ; i < tuplesize ; i++) {
3220
6.59k
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3221
6.59k
            item = (*Py_TYPE(it)->tp_iternext)(it);
3222
6.59k
            if (item == NULL) {
3223
1.22k
                Py_DECREF(result);
3224
1.22k
                if (lz->strict) {
3225
22
                    goto check;
3226
22
                }
3227
1.20k
                return NULL;
3228
1.22k
            }
3229
5.36k
            PyTuple_SET_ITEM(result, i, item);
3230
5.36k
        }
3231
3.91k
    }
3232
25.4M
    return result;
3233
805
check:
3234
805
    if (PyErr_Occurred()) {
3235
0
        if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
3236
            // next() on argument i raised an exception (not StopIteration)
3237
0
            return NULL;
3238
0
        }
3239
0
        PyErr_Clear();
3240
0
    }
3241
805
    if (i) {
3242
        // ValueError: zip() argument 2 is shorter than argument 1
3243
        // ValueError: zip() argument 3 is shorter than arguments 1-2
3244
0
        const char* plural = i == 1 ? " " : "s 1-";
3245
0
        return PyErr_Format(PyExc_ValueError,
3246
0
                            "zip() argument %d is shorter than argument%s%d",
3247
0
                            i + 1, plural, i);
3248
0
    }
3249
1.61k
    for (i = 1; i < tuplesize; i++) {
3250
805
        it = PyTuple_GET_ITEM(lz->ittuple, i);
3251
805
        item = (*Py_TYPE(it)->tp_iternext)(it);
3252
805
        if (item) {
3253
0
            Py_DECREF(item);
3254
0
            const char* plural = i == 1 ? " " : "s 1-";
3255
0
            return PyErr_Format(PyExc_ValueError,
3256
0
                                "zip() argument %d is longer than argument%s%d",
3257
0
                                i + 1, plural, i);
3258
0
        }
3259
805
        if (PyErr_Occurred()) {
3260
0
            if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
3261
                // next() on argument i raised an exception (not StopIteration)
3262
0
                return NULL;
3263
0
            }
3264
0
            PyErr_Clear();
3265
0
        }
3266
        // Argument i is exhausted. So far so good...
3267
805
    }
3268
    // All arguments are exhausted. Success!
3269
805
    return NULL;
3270
805
}
3271
3272
static PyObject *
3273
zip_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
3274
0
{
3275
0
    zipobject *lz = _zipobject_CAST(self);
3276
    /* Just recreate the zip with the internal iterator tuple */
3277
0
    if (lz->strict) {
3278
0
        return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
3279
0
    }
3280
0
    return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
3281
0
}
3282
3283
static PyObject *
3284
zip_setstate(PyObject *self, PyObject *state)
3285
0
{
3286
0
    int strict = PyObject_IsTrue(state);
3287
0
    if (strict < 0) {
3288
0
        return NULL;
3289
0
    }
3290
0
    zipobject *lz = _zipobject_CAST(self);
3291
0
    lz->strict = strict;
3292
0
    Py_RETURN_NONE;
3293
0
}
3294
3295
static PyMethodDef zip_methods[] = {
3296
    {"__reduce__", zip_reduce, METH_NOARGS, reduce_doc},
3297
    {"__setstate__", zip_setstate, METH_O, setstate_doc},
3298
    {NULL}  /* sentinel */
3299
};
3300
3301
PyDoc_STRVAR(zip_doc,
3302
"zip(*iterables, strict=False)\n\
3303
--\n\
3304
\n\
3305
The zip object yields n-length tuples, where n is the number of iterables\n\
3306
passed as positional arguments to zip().  The i-th element in every tuple\n\
3307
comes from the i-th iterable argument to zip().  This continues until the\n\
3308
shortest argument is exhausted.\n\
3309
\n\
3310
If strict is true and one of the arguments is exhausted before the others,\n\
3311
raise a ValueError.\n\
3312
\n\
3313
   >>> list(zip('abcdefg', range(3), range(4)))\n\
3314
   [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]");
3315
3316
PyTypeObject PyZip_Type = {
3317
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3318
    "zip",                              /* tp_name */
3319
    sizeof(zipobject),                  /* tp_basicsize */
3320
    0,                                  /* tp_itemsize */
3321
    /* methods */
3322
    zip_dealloc,                        /* tp_dealloc */
3323
    0,                                  /* tp_vectorcall_offset */
3324
    0,                                  /* tp_getattr */
3325
    0,                                  /* tp_setattr */
3326
    0,                                  /* tp_as_async */
3327
    0,                                  /* tp_repr */
3328
    0,                                  /* tp_as_number */
3329
    0,                                  /* tp_as_sequence */
3330
    0,                                  /* tp_as_mapping */
3331
    0,                                  /* tp_hash */
3332
    0,                                  /* tp_call */
3333
    0,                                  /* tp_str */
3334
    PyObject_GenericGetAttr,            /* tp_getattro */
3335
    0,                                  /* tp_setattro */
3336
    0,                                  /* tp_as_buffer */
3337
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3338
        Py_TPFLAGS_BASETYPE,            /* tp_flags */
3339
    zip_doc,                            /* tp_doc */
3340
    zip_traverse,                       /* tp_traverse */
3341
    0,                                  /* tp_clear */
3342
    0,                                  /* tp_richcompare */
3343
    0,                                  /* tp_weaklistoffset */
3344
    PyObject_SelfIter,                  /* tp_iter */
3345
    zip_next,                           /* tp_iternext */
3346
    zip_methods,                        /* tp_methods */
3347
    0,                                  /* tp_members */
3348
    0,                                  /* tp_getset */
3349
    0,                                  /* tp_base */
3350
    0,                                  /* tp_dict */
3351
    0,                                  /* tp_descr_get */
3352
    0,                                  /* tp_descr_set */
3353
    0,                                  /* tp_dictoffset */
3354
    0,                                  /* tp_init */
3355
    PyType_GenericAlloc,                /* tp_alloc */
3356
    zip_new,                            /* tp_new */
3357
    PyObject_GC_Del,                    /* tp_free */
3358
};
3359
3360
3361
static PyMethodDef builtin_methods[] = {
3362
    {"__build_class__", _PyCFunction_CAST(builtin___build_class__),
3363
     METH_FASTCALL | METH_KEYWORDS, build_class_doc},
3364
    BUILTIN___IMPORT___METHODDEF
3365
    BUILTIN_ABS_METHODDEF
3366
    BUILTIN_ALL_METHODDEF
3367
    BUILTIN_ANY_METHODDEF
3368
    BUILTIN_ASCII_METHODDEF
3369
    BUILTIN_BIN_METHODDEF
3370
    {"breakpoint", _PyCFunction_CAST(builtin_breakpoint), METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
3371
    BUILTIN_CALLABLE_METHODDEF
3372
    BUILTIN_CHR_METHODDEF
3373
    BUILTIN_COMPILE_METHODDEF
3374
    BUILTIN_DELATTR_METHODDEF
3375
    {"dir", builtin_dir, METH_VARARGS, dir_doc},
3376
    BUILTIN_DIVMOD_METHODDEF
3377
    BUILTIN_EVAL_METHODDEF
3378
    BUILTIN_EXEC_METHODDEF
3379
    BUILTIN_FORMAT_METHODDEF
3380
    {"getattr", _PyCFunction_CAST(builtin_getattr), METH_FASTCALL, getattr_doc},
3381
    BUILTIN_GLOBALS_METHODDEF
3382
    BUILTIN_HASATTR_METHODDEF
3383
    BUILTIN_HASH_METHODDEF
3384
    BUILTIN_HEX_METHODDEF
3385
    BUILTIN_ID_METHODDEF
3386
    BUILTIN_INPUT_METHODDEF
3387
    BUILTIN_ISINSTANCE_METHODDEF
3388
    BUILTIN_ISSUBCLASS_METHODDEF
3389
    {"iter", _PyCFunction_CAST(builtin_iter), METH_FASTCALL, iter_doc},
3390
    BUILTIN_AITER_METHODDEF
3391
    BUILTIN_LEN_METHODDEF
3392
    BUILTIN_LOCALS_METHODDEF
3393
    {"max", _PyCFunction_CAST(builtin_max), METH_FASTCALL | METH_KEYWORDS, max_doc},
3394
    {"min", _PyCFunction_CAST(builtin_min), METH_FASTCALL | METH_KEYWORDS, min_doc},
3395
    {"next", _PyCFunction_CAST(builtin_next), METH_FASTCALL, next_doc},
3396
    BUILTIN_ANEXT_METHODDEF
3397
    BUILTIN_OCT_METHODDEF
3398
    BUILTIN_ORD_METHODDEF
3399
    BUILTIN_POW_METHODDEF
3400
    BUILTIN_PRINT_METHODDEF
3401
    BUILTIN_REPR_METHODDEF
3402
    BUILTIN_ROUND_METHODDEF
3403
    BUILTIN_SETATTR_METHODDEF
3404
    BUILTIN_SORTED_METHODDEF
3405
    BUILTIN_SUM_METHODDEF
3406
    {"vars",            builtin_vars,       METH_VARARGS, vars_doc},
3407
    {NULL,              NULL},
3408
};
3409
3410
PyDoc_STRVAR(builtin_doc,
3411
"Built-in functions, types, exceptions, and other objects.\n\
3412
\n\
3413
This module provides direct access to all 'built-in'\n\
3414
identifiers of Python; for example, builtins.len is\n\
3415
the full name for the built-in function len().\n\
3416
\n\
3417
This module is not normally accessed explicitly by most\n\
3418
applications, but can be useful in modules that provide\n\
3419
objects with the same name as a built-in value, but in\n\
3420
which the built-in of that name is also needed.");
3421
3422
static struct PyModuleDef builtinsmodule = {
3423
    PyModuleDef_HEAD_INIT,
3424
    "builtins",
3425
    builtin_doc,
3426
    -1, /* multiple "initialization" just copies the module dict. */
3427
    builtin_methods,
3428
    NULL,
3429
    NULL,
3430
    NULL,
3431
    NULL
3432
};
3433
3434
3435
PyObject *
3436
_PyBuiltin_Init(PyInterpreterState *interp)
3437
28
{
3438
28
    PyObject *mod, *dict, *debug;
3439
3440
28
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3441
3442
28
    mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
3443
28
    if (mod == NULL)
3444
0
        return NULL;
3445
#ifdef Py_GIL_DISABLED
3446
    PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
3447
#endif
3448
28
    dict = PyModule_GetDict(mod);
3449
3450
#ifdef Py_TRACE_REFS
3451
    /* "builtins" exposes a number of statically allocated objects
3452
     * that, before this code was added in 2.3, never showed up in
3453
     * the list of "all objects" maintained by Py_TRACE_REFS.  As a
3454
     * result, programs leaking references to None and False (etc)
3455
     * couldn't be diagnosed by examining sys.getobjects(0).
3456
     */
3457
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT))
3458
#else
3459
868
#define ADD_TO_ALL(OBJECT) (void)0
3460
28
#endif
3461
3462
28
#define SETBUILTIN(NAME, OBJECT) \
3463
868
    if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0)       \
3464
868
        return NULL;                                                    \
3465
868
    ADD_TO_ALL(OBJECT)
3466
3467
28
    SETBUILTIN("None",                  Py_None);
3468
28
    SETBUILTIN("Ellipsis",              Py_Ellipsis);
3469
28
    SETBUILTIN("NotImplemented",        Py_NotImplemented);
3470
28
    SETBUILTIN("False",                 Py_False);
3471
28
    SETBUILTIN("True",                  Py_True);
3472
28
    SETBUILTIN("bool",                  &PyBool_Type);
3473
28
    SETBUILTIN("memoryview",            &PyMemoryView_Type);
3474
28
    SETBUILTIN("bytearray",             &PyByteArray_Type);
3475
28
    SETBUILTIN("bytes",                 &PyBytes_Type);
3476
28
    SETBUILTIN("classmethod",           &PyClassMethod_Type);
3477
28
    SETBUILTIN("complex",               &PyComplex_Type);
3478
28
    SETBUILTIN("dict",                  &PyDict_Type);
3479
28
    SETBUILTIN("enumerate",             &PyEnum_Type);
3480
28
    SETBUILTIN("filter",                &PyFilter_Type);
3481
28
    SETBUILTIN("float",                 &PyFloat_Type);
3482
28
    SETBUILTIN("frozenset",             &PyFrozenSet_Type);
3483
28
    SETBUILTIN("property",              &PyProperty_Type);
3484
28
    SETBUILTIN("int",                   &PyLong_Type);
3485
28
    SETBUILTIN("list",                  &PyList_Type);
3486
28
    SETBUILTIN("map",                   &PyMap_Type);
3487
28
    SETBUILTIN("object",                &PyBaseObject_Type);
3488
28
    SETBUILTIN("range",                 &PyRange_Type);
3489
28
    SETBUILTIN("reversed",              &PyReversed_Type);
3490
28
    SETBUILTIN("set",                   &PySet_Type);
3491
28
    SETBUILTIN("slice",                 &PySlice_Type);
3492
28
    SETBUILTIN("staticmethod",          &PyStaticMethod_Type);
3493
28
    SETBUILTIN("str",                   &PyUnicode_Type);
3494
28
    SETBUILTIN("super",                 &PySuper_Type);
3495
28
    SETBUILTIN("tuple",                 &PyTuple_Type);
3496
28
    SETBUILTIN("type",                  &PyType_Type);
3497
28
    SETBUILTIN("zip",                   &PyZip_Type);
3498
28
    debug = PyBool_FromLong(config->optimization_level == 0);
3499
28
    if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3500
0
        Py_DECREF(debug);
3501
0
        return NULL;
3502
0
    }
3503
28
    Py_DECREF(debug);
3504
3505
28
    return mod;
3506
28
#undef ADD_TO_ALL
3507
28
#undef SETBUILTIN
3508
28
}