Coverage Report

Created: 2026-05-30 06:18

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