Coverage Report

Created: 2026-11-30 07:19

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