Coverage Report

Created: 2025-11-02 06:30

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