Coverage Report

Created: 2026-12-01 06:09

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