Coverage Report

Created: 2026-07-14 06:16

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