Coverage Report

Created: 2025-07-11 06:24

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