Coverage Report

Created: 2025-10-10 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/bltinmodule.c
Line
Count
Source
1
/* Built-in functions */
2
3
#include "Python.h"
4
#include "pycore_ast.h"           // _PyAST_Validate()
5
#include "pycore_call.h"          // _PyObject_CallNoArgs()
6
#include "pycore_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.46k
{
30
4.46k
    Py_ssize_t i, j;
31
4.46k
    PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
32
4.46k
    assert(PyTuple_Check(bases));
33
34
8.91k
    for (i = 0; i < nargs; i++) {
35
4.44k
        base  = args[i];
36
4.44k
        if (PyType_Check(base)) {
37
4.44k
            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.44k
            continue;
45
4.44k
        }
46
2
        if (PyObject_GetOptionalAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
47
0
            goto error;
48
0
        }
49
2
        if (!meth) {
50
0
            if (new_bases) {
51
0
                if (PyList_Append(new_bases, base) < 0) {
52
0
                    goto error;
53
0
                }
54
0
            }
55
0
            continue;
56
0
        }
57
2
        new_base = PyObject_CallOneArg(meth, bases);
58
2
        Py_DECREF(meth);
59
2
        if (!new_base) {
60
0
            goto error;
61
0
        }
62
2
        if (!PyTuple_Check(new_base)) {
63
0
            PyErr_SetString(PyExc_TypeError,
64
0
                            "__mro_entries__ must return a tuple");
65
0
            Py_DECREF(new_base);
66
0
            goto error;
67
0
        }
68
2
        if (!new_bases) {
69
            /* If this is a first successful replacement, create new_bases list and
70
               copy previously encountered bases. */
71
2
            if (!(new_bases = PyList_New(i))) {
72
0
                Py_DECREF(new_base);
73
0
                goto error;
74
0
            }
75
2
            for (j = 0; j < i; j++) {
76
0
                base = args[j];
77
0
                PyList_SET_ITEM(new_bases, j, Py_NewRef(base));
78
0
            }
79
2
        }
80
2
        j = PyList_GET_SIZE(new_bases);
81
2
        if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
82
0
            Py_DECREF(new_base);
83
0
            goto error;
84
0
        }
85
2
        Py_DECREF(new_base);
86
2
    }
87
4.46k
    if (!new_bases) {
88
4.46k
        return bases;
89
4.46k
    }
90
2
    result = PyList_AsTuple(new_bases);
91
2
    Py_DECREF(new_bases);
92
2
    return result;
93
94
0
error:
95
0
    Py_XDECREF(new_bases);
96
0
    return NULL;
97
4.46k
}
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.46k
{
104
4.46k
    PyObject *func, *name, *winner, *prep;
105
4.46k
    PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
106
4.46k
    PyObject *mkw = NULL, *bases = NULL;
107
4.46k
    int isclass = 0;   /* initialize to prevent gcc warning */
108
109
4.46k
    if (nargs < 2) {
110
0
        PyErr_SetString(PyExc_TypeError,
111
0
                        "__build_class__: not enough arguments");
112
0
        return NULL;
113
0
    }
114
4.46k
    func = args[0];   /* Better be callable */
115
4.46k
    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.46k
    name = args[1];
121
4.46k
    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.46k
    orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
127
4.46k
    if (orig_bases == NULL)
128
0
        return NULL;
129
130
4.46k
    bases = update_bases(orig_bases, args + 2, nargs - 2);
131
4.46k
    if (bases == NULL) {
132
0
        Py_DECREF(orig_bases);
133
0
        return NULL;
134
0
    }
135
136
4.46k
    if (kwnames == NULL) {
137
4.22k
        meta = NULL;
138
4.22k
        mkw = NULL;
139
4.22k
    }
140
238
    else {
141
238
        mkw = _PyStack_AsDict(args + nargs, kwnames);
142
238
        if (mkw == NULL) {
143
0
            goto error;
144
0
        }
145
146
238
        if (PyDict_Pop(mkw, &_Py_ID(metaclass), &meta) < 0) {
147
0
            goto error;
148
0
        }
149
238
        if (meta != NULL) {
150
            /* metaclass is explicitly given, check if it's indeed a class */
151
214
            isclass = PyType_Check(meta);
152
214
        }
153
238
    }
154
4.46k
    if (meta == NULL) {
155
        /* if there are no bases, use type: */
156
4.25k
        if (PyTuple_GET_SIZE(bases) == 0) {
157
925
            meta = (PyObject *) (&PyType_Type);
158
925
        }
159
        /* else get the type of the first base */
160
3.32k
        else {
161
3.32k
            PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
162
3.32k
            meta = (PyObject *)Py_TYPE(base0);
163
3.32k
        }
164
4.25k
        Py_INCREF(meta);
165
4.25k
        isclass = 1;  /* meta is really a class */
166
4.25k
    }
167
168
4.46k
    if (isclass) {
169
        /* meta is really a class, so check for a more derived
170
           metaclass, or possible metaclass conflicts: */
171
4.46k
        winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
172
4.46k
                                                        bases);
173
4.46k
        if (winner == NULL) {
174
0
            goto error;
175
0
        }
176
4.46k
        if (winner != meta) {
177
88
            Py_SETREF(meta, Py_NewRef(winner));
178
88
        }
179
4.46k
    }
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.46k
    if (PyObject_GetOptionalAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
183
0
        ns = NULL;
184
0
    }
185
4.46k
    else if (prep == NULL) {
186
0
        ns = PyDict_New();
187
0
    }
188
4.46k
    else {
189
4.46k
        PyObject *pargs[2] = {name, bases};
190
4.46k
        ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
191
4.46k
        Py_DECREF(prep);
192
4.46k
    }
193
4.46k
    if (ns == NULL) {
194
0
        goto error;
195
0
    }
196
4.46k
    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.46k
    PyThreadState *tstate = _PyThreadState_GET();
204
4.46k
    EVAL_CALL_STAT_INC(EVAL_CALL_BUILD_CLASS);
205
4.46k
    cell = _PyEval_Vector(tstate, (PyFunctionObject *)func, ns, NULL, 0, NULL);
206
4.46k
    if (cell != NULL) {
207
4.46k
        if (bases != orig_bases) {
208
2
            if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
209
0
                goto error;
210
0
            }
211
2
        }
212
4.46k
        PyObject *margs[3] = {name, bases, ns};
213
4.46k
        cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
214
4.46k
        if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
215
341
            PyObject *cell_cls = PyCell_GetRef((PyCellObject *)cell);
216
341
            if (cell_cls != cls) {
217
0
                if (cell_cls == NULL) {
218
0
                    const char *msg =
219
0
                        "__class__ not set defining %.200R as %.200R. "
220
0
                        "Was __classcell__ propagated to type.__new__?";
221
0
                    PyErr_Format(PyExc_RuntimeError, msg, name, cls);
222
0
                } else {
223
0
                    const char *msg =
224
0
                        "__class__ set to %.200R defining %.200R as %.200R";
225
0
                    PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
226
0
                }
227
0
                Py_XDECREF(cell_cls);
228
0
                Py_SETREF(cls, NULL);
229
0
                goto error;
230
0
            }
231
341
            else {
232
341
                Py_DECREF(cell_cls);
233
341
            }
234
341
        }
235
4.46k
    }
236
4.46k
error:
237
4.46k
    Py_XDECREF(cell);
238
4.46k
    Py_XDECREF(ns);
239
4.46k
    Py_XDECREF(meta);
240
4.46k
    Py_XDECREF(mkw);
241
4.46k
    if (bases != orig_bases) {
242
2
        Py_DECREF(orig_bases);
243
2
    }
244
4.46k
    Py_DECREF(bases);
245
4.46k
    return cls;
246
4.46k
}
247
248
PyDoc_STRVAR(build_class_doc,
249
"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
250
\n\
251
Internal helper function used by the class statement.");
252
253
/*[clinic input]
254
@permit_long_docstring_body
255
__import__ as builtin___import__
256
257
    name: object
258
    globals: object(c_default="NULL") = None
259
    locals: object(c_default="NULL") = None
260
    fromlist: object(c_default="NULL") = ()
261
    level: int = 0
262
263
Import a module.
264
265
Because this function is meant for use by the Python
266
interpreter and not for general use, it is better to use
267
importlib.import_module() to programmatically import a module.
268
269
The globals argument is only used to determine the context;
270
they are not modified.  The locals argument is unused.  The fromlist
271
should be a list of names to emulate ``from name import ...``, or an
272
empty list to emulate ``import name``.
273
When importing a module from a package, note that __import__('A.B', ...)
274
returns package A when fromlist is empty, but its submodule B when
275
fromlist is not empty.  The level argument is used to determine whether to
276
perform absolute or relative imports: 0 is absolute, while a positive number
277
is the number of parent directories to search relative to the current module.
278
[clinic start generated code]*/
279
280
static PyObject *
281
builtin___import___impl(PyObject *module, PyObject *name, PyObject *globals,
282
                        PyObject *locals, PyObject *fromlist, int level)
283
/*[clinic end generated code: output=4febeda88a0cd245 input=01a3283590eae93a]*/
284
13.0k
{
285
13.0k
    return PyImport_ImportModuleLevelObject(name, globals, locals,
286
13.0k
                                            fromlist, level);
287
13.0k
}
288
289
290
/*[clinic input]
291
abs as builtin_abs
292
293
    number: object
294
    /
295
296
Return the absolute value of the argument.
297
[clinic start generated code]*/
298
299
static PyObject *
300
builtin_abs(PyObject *module, PyObject *number)
301
/*[clinic end generated code: output=861a9db97dee0595 input=a356196903543505]*/
302
0
{
303
0
    return PyNumber_Absolute(number);
304
0
}
305
306
/*[clinic input]
307
all as builtin_all
308
309
    iterable: object
310
    /
311
312
Return True if bool(x) is True for all values x in the iterable.
313
314
If the iterable is empty, return True.
315
[clinic start generated code]*/
316
317
static PyObject *
318
builtin_all(PyObject *module, PyObject *iterable)
319
/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
320
0
{
321
0
    PyObject *it, *item;
322
0
    PyObject *(*iternext)(PyObject *);
323
0
    int cmp;
324
325
0
    it = PyObject_GetIter(iterable);
326
0
    if (it == NULL)
327
0
        return NULL;
328
0
    iternext = *Py_TYPE(it)->tp_iternext;
329
330
0
    for (;;) {
331
0
        item = iternext(it);
332
0
        if (item == NULL)
333
0
            break;
334
0
        cmp = PyObject_IsTrue(item);
335
0
        Py_DECREF(item);
336
0
        if (cmp < 0) {
337
0
            Py_DECREF(it);
338
0
            return NULL;
339
0
        }
340
0
        if (cmp == 0) {
341
0
            Py_DECREF(it);
342
0
            Py_RETURN_FALSE;
343
0
        }
344
0
    }
345
0
    Py_DECREF(it);
346
0
    if (PyErr_Occurred()) {
347
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
348
0
            PyErr_Clear();
349
0
        else
350
0
            return NULL;
351
0
    }
352
0
    Py_RETURN_TRUE;
353
0
}
354
355
/*[clinic input]
356
any as builtin_any
357
358
    iterable: object
359
    /
360
361
Return True if bool(x) is True for any x in the iterable.
362
363
If the iterable is empty, return False.
364
[clinic start generated code]*/
365
366
static PyObject *
367
builtin_any(PyObject *module, PyObject *iterable)
368
/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
369
19.4k
{
370
19.4k
    PyObject *it, *item;
371
19.4k
    PyObject *(*iternext)(PyObject *);
372
19.4k
    int cmp;
373
374
19.4k
    it = PyObject_GetIter(iterable);
375
19.4k
    if (it == NULL)
376
0
        return NULL;
377
19.4k
    iternext = *Py_TYPE(it)->tp_iternext;
378
379
270k
    for (;;) {
380
270k
        item = iternext(it);
381
270k
        if (item == NULL)
382
18.2k
            break;
383
252k
        cmp = PyObject_IsTrue(item);
384
252k
        Py_DECREF(item);
385
252k
        if (cmp < 0) {
386
0
            Py_DECREF(it);
387
0
            return NULL;
388
0
        }
389
252k
        if (cmp > 0) {
390
1.28k
            Py_DECREF(it);
391
1.28k
            Py_RETURN_TRUE;
392
1.28k
        }
393
252k
    }
394
18.2k
    Py_DECREF(it);
395
18.2k
    if (PyErr_Occurred()) {
396
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
397
0
            PyErr_Clear();
398
0
        else
399
0
            return NULL;
400
0
    }
401
18.2k
    Py_RETURN_FALSE;
402
18.2k
}
403
404
/*[clinic input]
405
ascii as builtin_ascii
406
407
    obj: object
408
    /
409
410
Return an ASCII-only representation of an object.
411
412
As repr(), return a string containing a printable representation of an
413
object, but escape the non-ASCII characters in the string returned by
414
repr() using \\x, \\u or \\U escapes. This generates a string similar
415
to that returned by repr() in Python 2.
416
[clinic start generated code]*/
417
418
static PyObject *
419
builtin_ascii(PyObject *module, PyObject *obj)
420
/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
421
0
{
422
0
    return PyObject_ASCII(obj);
423
0
}
424
425
426
/*[clinic input]
427
bin as builtin_bin
428
429
    integer: object
430
    /
431
432
Return the binary representation of an integer.
433
434
   >>> bin(2796202)
435
   '0b1010101010101010101010'
436
[clinic start generated code]*/
437
438
static PyObject *
439
builtin_bin(PyObject *module, PyObject *integer)
440
/*[clinic end generated code: output=533f9388441805cc input=d16518f148341e70]*/
441
0
{
442
0
    return PyNumber_ToBase(integer, 2);
443
0
}
444
445
446
/*[clinic input]
447
callable as builtin_callable
448
449
    obj: object
450
    /
451
452
Return whether the object is callable (i.e., some kind of function).
453
454
Note that classes are callable, as are instances of classes with a
455
__call__() method.
456
[clinic start generated code]*/
457
458
static PyObject *
459
builtin_callable(PyObject *module, PyObject *obj)
460
/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
461
112
{
462
112
    return PyBool_FromLong((long)PyCallable_Check(obj));
463
112
}
464
465
static PyObject *
466
builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
467
0
{
468
0
    PyObject *hook = PySys_GetAttrString("breakpointhook");
469
0
    if (hook == NULL) {
470
0
        return NULL;
471
0
    }
472
473
0
    if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
474
0
        Py_DECREF(hook);
475
0
        return NULL;
476
0
    }
477
478
0
    PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
479
0
    Py_DECREF(hook);
480
0
    return retval;
481
0
}
482
483
PyDoc_STRVAR(breakpoint_doc,
484
"breakpoint($module, /, *args, **kws)\n\
485
--\n\
486
\n\
487
Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept\n\
488
whatever arguments are passed.\n\
489
\n\
490
By default, this drops you into the pdb debugger.");
491
492
typedef struct {
493
    PyObject_HEAD
494
    PyObject *func;
495
    PyObject *it;
496
} filterobject;
497
498
0
#define _filterobject_CAST(op)      ((filterobject *)(op))
499
500
static PyObject *
501
filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
502
0
{
503
0
    PyObject *func, *seq;
504
0
    PyObject *it;
505
0
    filterobject *lz;
506
507
0
    if ((type == &PyFilter_Type || type->tp_init == PyFilter_Type.tp_init) &&
508
0
        !_PyArg_NoKeywords("filter", kwds))
509
0
        return NULL;
510
511
0
    if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
512
0
        return NULL;
513
514
    /* Get iterator. */
515
0
    it = PyObject_GetIter(seq);
516
0
    if (it == NULL)
517
0
        return NULL;
518
519
    /* create filterobject structure */
520
0
    lz = (filterobject *)type->tp_alloc(type, 0);
521
0
    if (lz == NULL) {
522
0
        Py_DECREF(it);
523
0
        return NULL;
524
0
    }
525
526
0
    lz->func = Py_NewRef(func);
527
0
    lz->it = it;
528
529
0
    return (PyObject *)lz;
530
0
}
531
532
static PyObject *
533
filter_vectorcall(PyObject *type, PyObject * const*args,
534
                size_t nargsf, PyObject *kwnames)
535
0
{
536
0
    PyTypeObject *tp = _PyType_CAST(type);
537
0
    if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
538
0
        return NULL;
539
0
    }
540
541
0
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
542
0
    if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
543
0
        return NULL;
544
0
    }
545
546
0
    PyObject *it = PyObject_GetIter(args[1]);
547
0
    if (it == NULL) {
548
0
        return NULL;
549
0
    }
550
551
0
    filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
552
553
0
    if (lz == NULL) {
554
0
        Py_DECREF(it);
555
0
        return NULL;
556
0
    }
557
558
0
    lz->func = Py_NewRef(args[0]);
559
0
    lz->it = it;
560
561
0
    return (PyObject *)lz;
562
0
}
563
564
static void
565
filter_dealloc(PyObject *self)
566
0
{
567
0
    filterobject *lz = _filterobject_CAST(self);
568
0
    PyObject_GC_UnTrack(lz);
569
0
    Py_XDECREF(lz->func);
570
0
    Py_XDECREF(lz->it);
571
0
    Py_TYPE(lz)->tp_free(lz);
572
0
}
573
574
static int
575
filter_traverse(PyObject *self, visitproc visit, void *arg)
576
0
{
577
0
    filterobject *lz = _filterobject_CAST(self);
578
0
    Py_VISIT(lz->it);
579
0
    Py_VISIT(lz->func);
580
0
    return 0;
581
0
}
582
583
static PyObject *
584
filter_next(PyObject *self)
585
0
{
586
0
    filterobject *lz = _filterobject_CAST(self);
587
0
    PyObject *item;
588
0
    PyObject *it = lz->it;
589
0
    long ok;
590
0
    PyObject *(*iternext)(PyObject *);
591
0
    int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
592
593
0
    iternext = *Py_TYPE(it)->tp_iternext;
594
0
    for (;;) {
595
0
        item = iternext(it);
596
0
        if (item == NULL)
597
0
            return NULL;
598
599
0
        if (checktrue) {
600
0
            ok = PyObject_IsTrue(item);
601
0
        } else {
602
0
            PyObject *good;
603
0
            good = PyObject_CallOneArg(lz->func, item);
604
0
            if (good == NULL) {
605
0
                Py_DECREF(item);
606
0
                return NULL;
607
0
            }
608
0
            ok = PyObject_IsTrue(good);
609
0
            Py_DECREF(good);
610
0
        }
611
0
        if (ok > 0)
612
0
            return item;
613
0
        Py_DECREF(item);
614
0
        if (ok < 0)
615
0
            return NULL;
616
0
    }
617
0
}
618
619
static PyObject *
620
filter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
621
0
{
622
0
    filterobject *lz = _filterobject_CAST(self);
623
0
    return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
624
0
}
625
626
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
627
628
static PyMethodDef filter_methods[] = {
629
    {"__reduce__", filter_reduce, METH_NOARGS, reduce_doc},
630
    {NULL,           NULL}           /* sentinel */
631
};
632
633
PyDoc_STRVAR(filter_doc,
634
"filter(function, iterable, /)\n\
635
--\n\
636
\n\
637
Return an iterator yielding those items of iterable for which function(item)\n\
638
is true. If function is None, return the items that are true.");
639
640
PyTypeObject PyFilter_Type = {
641
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
642
    "filter",                           /* tp_name */
643
    sizeof(filterobject),               /* tp_basicsize */
644
    0,                                  /* tp_itemsize */
645
    /* methods */
646
    filter_dealloc,                     /* tp_dealloc */
647
    0,                                  /* tp_vectorcall_offset */
648
    0,                                  /* tp_getattr */
649
    0,                                  /* tp_setattr */
650
    0,                                  /* tp_as_async */
651
    0,                                  /* tp_repr */
652
    0,                                  /* tp_as_number */
653
    0,                                  /* tp_as_sequence */
654
    0,                                  /* tp_as_mapping */
655
    0,                                  /* tp_hash */
656
    0,                                  /* tp_call */
657
    0,                                  /* tp_str */
658
    PyObject_GenericGetAttr,            /* tp_getattro */
659
    0,                                  /* tp_setattro */
660
    0,                                  /* tp_as_buffer */
661
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
662
        Py_TPFLAGS_BASETYPE,            /* tp_flags */
663
    filter_doc,                         /* tp_doc */
664
    filter_traverse,                    /* tp_traverse */
665
    0,                                  /* tp_clear */
666
    0,                                  /* tp_richcompare */
667
    0,                                  /* tp_weaklistoffset */
668
    PyObject_SelfIter,                  /* tp_iter */
669
    filter_next,                        /* tp_iternext */
670
    filter_methods,                     /* tp_methods */
671
    0,                                  /* tp_members */
672
    0,                                  /* tp_getset */
673
    0,                                  /* tp_base */
674
    0,                                  /* tp_dict */
675
    0,                                  /* tp_descr_get */
676
    0,                                  /* tp_descr_set */
677
    0,                                  /* tp_dictoffset */
678
    0,                                  /* tp_init */
679
    PyType_GenericAlloc,                /* tp_alloc */
680
    filter_new,                         /* tp_new */
681
    PyObject_GC_Del,                    /* tp_free */
682
    .tp_vectorcall = filter_vectorcall
683
};
684
685
686
/*[clinic input]
687
format as builtin_format
688
689
    value: object
690
    format_spec: unicode(c_default="NULL") = ''
691
    /
692
693
Return type(value).__format__(value, format_spec)
694
695
Many built-in types implement format_spec according to the
696
Format Specification Mini-language. See help('FORMATTING').
697
698
If type(value) does not supply a method named __format__
699
and format_spec is empty, then str(value) is returned.
700
See also help('SPECIALMETHODS').
701
[clinic start generated code]*/
702
703
static PyObject *
704
builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
705
/*[clinic end generated code: output=2f40bdfa4954b077 input=45ef3934b86d5624]*/
706
0
{
707
0
    return PyObject_Format(value, format_spec);
708
0
}
709
710
/*[clinic input]
711
chr as builtin_chr
712
713
    i: object
714
    /
715
716
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
717
[clinic start generated code]*/
718
719
static PyObject *
720
builtin_chr(PyObject *module, PyObject *i)
721
/*[clinic end generated code: output=d34f25b8035a9b10 input=f919867f0ba2f496]*/
722
228k
{
723
228k
    int overflow;
724
228k
    long v = PyLong_AsLongAndOverflow(i, &overflow);
725
228k
    if (v == -1 && PyErr_Occurred()) {
726
0
        return NULL;
727
0
    }
728
228k
    if (overflow) {
729
0
        v = overflow < 0 ? INT_MIN : INT_MAX;
730
        /* Allow PyUnicode_FromOrdinal() to raise an exception */
731
0
    }
732
228k
#if SIZEOF_INT < SIZEOF_LONG
733
228k
    else if (v < INT_MIN) {
734
0
        v = INT_MIN;
735
0
    }
736
228k
    else if (v > INT_MAX) {
737
0
        v = INT_MAX;
738
0
    }
739
228k
#endif
740
228k
    return PyUnicode_FromOrdinal(v);
741
228k
}
742
743
744
/*[clinic input]
745
compile as builtin_compile
746
747
    source: object
748
    filename: unicode_fs_decoded
749
    mode: str
750
    flags: int = 0
751
    dont_inherit: bool = False
752
    optimize: int = -1
753
    *
754
    _feature_version as feature_version: int = -1
755
756
Compile source into a code object that can be executed by exec() or eval().
757
758
The source code may represent a Python module, statement or expression.
759
The filename will be used for run-time error messages.
760
The mode must be 'exec' to compile a module, 'single' to compile a
761
single (interactive) statement, or 'eval' to compile an expression.
762
The flags argument, if present, controls which future statements influence
763
the compilation of the code.
764
The dont_inherit argument, if true, stops the compilation inheriting
765
the effects of any future statements in effect in the code calling
766
compile; if absent or false these statements do influence the compilation,
767
in addition to any features explicitly specified.
768
[clinic start generated code]*/
769
770
static PyObject *
771
builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
772
                     const char *mode, int flags, int dont_inherit,
773
                     int optimize, int feature_version)
774
/*[clinic end generated code: output=b0c09c84f116d3d7 input=8f0069edbdac381b]*/
775
21.9k
{
776
21.9k
    PyObject *source_copy;
777
21.9k
    const char *str;
778
21.9k
    int compile_mode = -1;
779
21.9k
    int is_ast;
780
21.9k
    int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
781
21.9k
    PyObject *result;
782
783
21.9k
    PyCompilerFlags cf = _PyCompilerFlags_INIT;
784
21.9k
    cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
785
21.9k
    if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
786
0
        cf.cf_feature_version = feature_version;
787
0
    }
788
789
21.9k
    if (flags &
790
21.9k
        ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
791
0
    {
792
0
        PyErr_SetString(PyExc_ValueError,
793
0
                        "compile(): unrecognised flags");
794
0
        goto error;
795
0
    }
796
    /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
797
798
21.9k
    if (optimize < -1 || optimize > 2) {
799
0
        PyErr_SetString(PyExc_ValueError,
800
0
                        "compile(): invalid optimize value");
801
0
        goto error;
802
0
    }
803
804
21.9k
    if (!dont_inherit) {
805
21.7k
        PyEval_MergeCompilerFlags(&cf);
806
21.7k
    }
807
808
21.9k
    if (strcmp(mode, "exec") == 0)
809
21.9k
        compile_mode = 0;
810
0
    else if (strcmp(mode, "eval") == 0)
811
0
        compile_mode = 1;
812
0
    else if (strcmp(mode, "single") == 0)
813
0
        compile_mode = 2;
814
0
    else if (strcmp(mode, "func_type") == 0) {
815
0
        if (!(flags & PyCF_ONLY_AST)) {
816
0
            PyErr_SetString(PyExc_ValueError,
817
0
                            "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
818
0
            goto error;
819
0
        }
820
0
        compile_mode = 3;
821
0
    }
822
0
    else {
823
0
        const char *msg;
824
0
        if (flags & PyCF_ONLY_AST)
825
0
            msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
826
0
        else
827
0
            msg = "compile() mode must be 'exec', 'eval' or 'single'";
828
0
        PyErr_SetString(PyExc_ValueError, msg);
829
0
        goto error;
830
0
    }
831
832
21.9k
    is_ast = PyAST_Check(source);
833
21.9k
    if (is_ast == -1)
834
0
        goto error;
835
21.9k
    if (is_ast) {
836
0
        PyArena *arena = _PyArena_New();
837
0
        if (arena == NULL) {
838
0
            goto error;
839
0
        }
840
841
0
        if (flags & PyCF_ONLY_AST) {
842
0
            mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
843
0
            if (mod == NULL || !_PyAST_Validate(mod)) {
844
0
                _PyArena_Free(arena);
845
0
                goto error;
846
0
            }
847
0
            int syntax_check_only = ((flags & PyCF_OPTIMIZED_AST) == PyCF_ONLY_AST); /* unoptiomized AST */
848
0
            if (_PyCompile_AstPreprocess(mod, filename, &cf, optimize,
849
0
                                           arena, syntax_check_only) < 0) {
850
0
                _PyArena_Free(arena);
851
0
                goto error;
852
0
            }
853
0
            result = PyAST_mod2obj(mod);
854
0
        }
855
0
        else {
856
0
            mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
857
0
            if (mod == NULL || !_PyAST_Validate(mod)) {
858
0
                _PyArena_Free(arena);
859
0
                goto error;
860
0
            }
861
0
            result = (PyObject*)_PyAST_Compile(mod, filename,
862
0
                                               &cf, optimize, arena);
863
0
        }
864
0
        _PyArena_Free(arena);
865
0
        goto finally;
866
0
    }
867
868
21.9k
    str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
869
21.9k
    if (str == NULL)
870
4
        goto error;
871
872
#ifdef Py_GIL_DISABLED
873
    // Disable immortalization of code constants for explicit
874
    // compile() calls to get consistent frozen outputs between the default
875
    // and free-threaded builds.
876
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
877
    tstate->suppress_co_const_immortalization++;
878
#endif
879
880
21.9k
    result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
881
882
#ifdef Py_GIL_DISABLED
883
    tstate->suppress_co_const_immortalization--;
884
#endif
885
886
21.9k
    Py_XDECREF(source_copy);
887
21.9k
    goto finally;
888
889
4
error:
890
4
    result = NULL;
891
21.9k
finally:
892
21.9k
    return result;
893
4
}
894
895
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
896
static PyObject *
897
builtin_dir(PyObject *self, PyObject *args)
898
20
{
899
20
    PyObject *arg = NULL;
900
901
20
    if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
902
0
        return NULL;
903
20
    return PyObject_Dir(arg);
904
20
}
905
906
PyDoc_STRVAR(dir_doc,
907
"dir([object]) -> list of strings\n"
908
"\n"
909
"If called without an argument, return the names in the current scope.\n"
910
"Else, return an alphabetized list of names comprising (some of) the attributes\n"
911
"of the given object, and of attributes reachable from it.\n"
912
"If the object supplies a method named __dir__, it will be used; otherwise\n"
913
"the default dir() logic is used and returns:\n"
914
"  for a module object: the module's attributes.\n"
915
"  for a class object:  its attributes, and recursively the attributes\n"
916
"    of its bases.\n"
917
"  for any other object: its attributes, its class's attributes, and\n"
918
"    recursively the attributes of its class's base classes.");
919
920
/*[clinic input]
921
divmod as builtin_divmod
922
923
    x: object
924
    y: object
925
    /
926
927
Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
928
[clinic start generated code]*/
929
930
static PyObject *
931
builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
932
/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
933
0
{
934
0
    return PyNumber_Divmod(x, y);
935
0
}
936
937
938
/*[clinic input]
939
eval as builtin_eval
940
941
    source: object
942
    /
943
    globals: object = None
944
    locals: object = None
945
946
Evaluate the given source in the context of globals and locals.
947
948
The source may be a string representing a Python expression
949
or a code object as returned by compile().
950
The globals must be a dictionary and locals can be any mapping,
951
defaulting to the current globals and locals.
952
If only globals is given, locals defaults to it.
953
[clinic start generated code]*/
954
955
static PyObject *
956
builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
957
                  PyObject *locals)
958
/*[clinic end generated code: output=0a0824aa70093116 input=7c7bce5299a89062]*/
959
66
{
960
66
    PyThreadState *tstate = _PyThreadState_GET();
961
66
    PyObject *result = NULL, *source_copy;
962
66
    const char *str;
963
964
66
    if (locals != Py_None && !PyMapping_Check(locals)) {
965
0
        PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
966
0
        return NULL;
967
0
    }
968
66
    if (globals != Py_None && !PyDict_Check(globals)) {
969
0
        PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
970
0
            "globals must be a real dict; try eval(expr, {}, mapping)"
971
0
            : "globals must be a dict");
972
0
        return NULL;
973
0
    }
974
975
66
    int fromframe = 0;
976
66
    if (globals != Py_None) {
977
66
        Py_INCREF(globals);
978
66
    }
979
0
    else if (_PyEval_GetFrame() != NULL) {
980
0
        fromframe = 1;
981
0
        globals = PyEval_GetGlobals();
982
0
        assert(globals != NULL);
983
0
        Py_INCREF(globals);
984
0
    }
985
0
    else {
986
0
        globals = _PyEval_GetGlobalsFromRunningMain(tstate);
987
0
        if (globals == NULL) {
988
0
            if (!_PyErr_Occurred(tstate)) {
989
0
                PyErr_SetString(PyExc_TypeError,
990
0
                    "eval must be given globals and locals "
991
0
                    "when called without a frame");
992
0
            }
993
0
            return NULL;
994
0
        }
995
0
        Py_INCREF(globals);
996
0
    }
997
998
66
    if (locals != Py_None) {
999
0
        Py_INCREF(locals);
1000
0
    }
1001
66
    else if (fromframe) {
1002
0
        locals = _PyEval_GetFrameLocals();
1003
0
        if (locals == NULL) {
1004
0
            assert(PyErr_Occurred());
1005
0
            Py_DECREF(globals);
1006
0
            return NULL;
1007
0
        }
1008
0
    }
1009
66
    else {
1010
66
        locals = Py_NewRef(globals);
1011
66
    }
1012
1013
66
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1014
0
        goto error;
1015
0
    }
1016
1017
66
    if (PyCode_Check(source)) {
1018
0
        if (PySys_Audit("exec", "O", source) < 0) {
1019
0
            goto error;
1020
0
        }
1021
1022
0
        if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
1023
0
            PyErr_SetString(PyExc_TypeError,
1024
0
                "code object passed to eval() may not contain free variables");
1025
0
            goto error;
1026
0
        }
1027
0
        result = PyEval_EvalCode(source, globals, locals);
1028
0
    }
1029
66
    else {
1030
66
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1031
66
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1032
66
        str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
1033
66
        if (str == NULL)
1034
0
            goto error;
1035
1036
66
        while (*str == ' ' || *str == '\t')
1037
0
            str++;
1038
1039
66
        (void)PyEval_MergeCompilerFlags(&cf);
1040
#ifdef Py_GIL_DISABLED
1041
        // Don't immortalize code constants for explicit eval() calls
1042
        // to avoid memory leaks.
1043
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
1044
        tstate->suppress_co_const_immortalization++;
1045
#endif
1046
66
        result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1047
#ifdef Py_GIL_DISABLED
1048
        tstate->suppress_co_const_immortalization--;
1049
#endif
1050
66
        Py_XDECREF(source_copy);
1051
66
    }
1052
1053
66
  error:
1054
66
    Py_XDECREF(globals);
1055
66
    Py_XDECREF(locals);
1056
66
    return result;
1057
66
}
1058
1059
/*[clinic input]
1060
exec as builtin_exec
1061
1062
    source: object
1063
    /
1064
    globals: object = None
1065
    locals: object = None
1066
    *
1067
    closure: object(c_default="NULL") = None
1068
1069
Execute the given source in the context of globals and locals.
1070
1071
The source may be a string representing one or more Python statements
1072
or a code object as returned by compile().
1073
The globals must be a dictionary and locals can be any mapping,
1074
defaulting to the current globals and locals.
1075
If only globals is given, locals defaults to it.
1076
The closure must be a tuple of cellvars, and can only be used
1077
when source is a code object requiring exactly that many cellvars.
1078
[clinic start generated code]*/
1079
1080
static PyObject *
1081
builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
1082
                  PyObject *locals, PyObject *closure)
1083
/*[clinic end generated code: output=7579eb4e7646743d input=25e989b6d87a3a21]*/
1084
1.00k
{
1085
1.00k
    PyThreadState *tstate = _PyThreadState_GET();
1086
1.00k
    PyObject *v;
1087
1088
1.00k
    int fromframe = 0;
1089
1.00k
    if (globals != Py_None) {
1090
1.00k
        Py_INCREF(globals);
1091
1.00k
    }
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
1.00k
    if (locals != Py_None) {
1111
12
        Py_INCREF(locals);
1112
12
    }
1113
994
    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
994
    else {
1122
994
        locals = Py_NewRef(globals);
1123
994
    }
1124
1125
1.00k
    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
1.00k
    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
1.00k
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1138
0
        goto error;
1139
0
    }
1140
1141
1.00k
    if (closure == Py_None) {
1142
0
        closure = NULL;
1143
0
    }
1144
1145
1.00k
    if (PyCode_Check(source)) {
1146
994
        Py_ssize_t num_free = PyCode_GetNumFree((PyCodeObject *)source);
1147
994
        if (num_free == 0) {
1148
994
            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
994
        } 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
994
        if (PySys_Audit("exec", "O", source) < 0) {
1176
0
            goto error;
1177
0
        }
1178
1179
994
        if (!closure) {
1180
994
            v = PyEval_EvalCode(source, globals, locals);
1181
994
        } 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
994
    }
1190
12
    else {
1191
12
        if (closure != NULL) {
1192
0
            PyErr_SetString(PyExc_TypeError,
1193
0
                "closure can only be used when source is a code object");
1194
0
            goto error;
1195
0
        }
1196
12
        PyObject *source_copy;
1197
12
        const char *str;
1198
12
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1199
12
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1200
12
        str = _Py_SourceAsString(source, "exec",
1201
12
                                       "string, bytes or code", &cf,
1202
12
                                       &source_copy);
1203
12
        if (str == NULL)
1204
0
            goto error;
1205
12
        if (PyEval_MergeCompilerFlags(&cf))
1206
12
            v = PyRun_StringFlags(str, Py_file_input, globals,
1207
12
                                  locals, &cf);
1208
0
        else
1209
0
            v = PyRun_String(str, Py_file_input, globals, locals);
1210
12
        Py_XDECREF(source_copy);
1211
12
    }
1212
1.00k
    if (v == NULL)
1213
44
        goto error;
1214
962
    Py_DECREF(globals);
1215
962
    Py_DECREF(locals);
1216
962
    Py_DECREF(v);
1217
962
    Py_RETURN_NONE;
1218
1219
44
  error:
1220
44
    Py_XDECREF(globals);
1221
44
    Py_XDECREF(locals);
1222
44
    return NULL;
1223
1.00k
}
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
503k
{
1230
503k
    PyObject *v, *name, *result;
1231
1232
503k
    if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
1233
0
        return NULL;
1234
1235
503k
    v = args[0];
1236
503k
    name = args[1];
1237
503k
    if (nargs > 2) {
1238
499k
        if (PyObject_GetOptionalAttr(v, name, &result) == 0) {
1239
3.80k
            PyObject *dflt = args[2];
1240
3.80k
            return Py_NewRef(dflt);
1241
3.80k
        }
1242
499k
    }
1243
4.08k
    else {
1244
4.08k
        result = PyObject_GetAttr(v, name);
1245
4.08k
    }
1246
499k
    return result;
1247
503k
}
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
310
{
1270
310
    PyObject *globals;
1271
310
    if (_PyEval_GetFrame() != NULL) {
1272
310
        globals = PyEval_GetGlobals();
1273
310
        assert(globals != NULL);
1274
310
        return Py_NewRef(globals);
1275
310
    }
1276
0
    PyThreadState *tstate = _PyThreadState_GET();
1277
0
    globals = _PyEval_GetGlobalsFromRunningMain(tstate);
1278
0
    if (globals == NULL) {
1279
0
        if (_PyErr_Occurred(tstate)) {
1280
0
            return NULL;
1281
0
        }
1282
0
        Py_RETURN_NONE;
1283
0
    }
1284
0
    return Py_NewRef(globals);
1285
0
}
1286
1287
1288
/*[clinic input]
1289
hasattr as builtin_hasattr
1290
1291
    obj: object
1292
    name: object
1293
    /
1294
1295
Return whether the object has an attribute with the given name.
1296
1297
This is done by calling getattr(obj, name) and catching AttributeError.
1298
[clinic start generated code]*/
1299
1300
static PyObject *
1301
builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1302
/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
1303
6.10M
{
1304
6.10M
    PyObject *v;
1305
1306
6.10M
    if (PyObject_GetOptionalAttr(obj, name, &v) < 0) {
1307
0
        return NULL;
1308
0
    }
1309
6.10M
    if (v == NULL) {
1310
280k
        Py_RETURN_FALSE;
1311
280k
    }
1312
5.82M
    Py_DECREF(v);
1313
5.82M
    Py_RETURN_TRUE;
1314
6.10M
}
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
284
{
1338
284
    PyObject *id = PyLong_FromVoidPtr(v);
1339
1340
284
    if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1341
0
        Py_DECREF(id);
1342
0
        return NULL;
1343
0
    }
1344
1345
284
    return id;
1346
284
}
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.83M
#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
209k
{
1421
209k
    PyTypeObject *tp = _PyType_CAST(type);
1422
1423
209k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1424
209k
    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
209k
    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
209k
    PyObject *iters = PyTuple_New(nargs-1);
1437
209k
    if (iters == NULL) {
1438
0
        return NULL;
1439
0
    }
1440
1441
418k
    for (int i=1; i<nargs; i++) {
1442
209k
        PyObject *it = PyObject_GetIter(args[i]);
1443
209k
        if (it == NULL) {
1444
0
            Py_DECREF(iters);
1445
0
            return NULL;
1446
0
        }
1447
209k
        PyTuple_SET_ITEM(iters, i-1, it);
1448
209k
    }
1449
1450
209k
    mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1451
209k
    if (lz == NULL) {
1452
0
        Py_DECREF(iters);
1453
0
        return NULL;
1454
0
    }
1455
209k
    lz->iters = iters;
1456
209k
    lz->func = Py_NewRef(args[0]);
1457
209k
    lz->strict = 0;
1458
1459
209k
    return (PyObject *)lz;
1460
209k
}
1461
1462
static void
1463
map_dealloc(PyObject *self)
1464
209k
{
1465
209k
    mapobject *lz = _mapobject_CAST(self);
1466
209k
    PyObject_GC_UnTrack(lz);
1467
209k
    Py_XDECREF(lz->iters);
1468
209k
    Py_XDECREF(lz->func);
1469
209k
    Py_TYPE(lz)->tp_free(lz);
1470
209k
}
1471
1472
static int
1473
map_traverse(PyObject *self, visitproc visit, void *arg)
1474
23
{
1475
23
    mapobject *lz = _mapobject_CAST(self);
1476
23
    Py_VISIT(lz->iters);
1477
23
    Py_VISIT(lz->func);
1478
23
    return 0;
1479
23
}
1480
1481
static PyObject *
1482
map_next(PyObject *self)
1483
2.63M
{
1484
2.63M
    mapobject *lz = _mapobject_CAST(self);
1485
2.63M
    Py_ssize_t i;
1486
2.63M
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1487
2.63M
    PyObject **stack;
1488
2.63M
    PyObject *result = NULL;
1489
2.63M
    PyThreadState *tstate = _PyThreadState_GET();
1490
1491
2.63M
    const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
1492
2.63M
    if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1493
2.63M
        stack = small_stack;
1494
2.63M
    }
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.63M
    Py_ssize_t nargs = 0;
1504
5.05M
    for (i=0; i < niters; i++) {
1505
2.63M
        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1506
2.63M
        PyObject *val = Py_TYPE(it)->tp_iternext(it);
1507
2.63M
        if (val == NULL) {
1508
209k
            if (lz->strict) {
1509
0
                goto check;
1510
0
            }
1511
209k
            goto exit;
1512
209k
        }
1513
2.42M
        stack[i] = val;
1514
2.42M
        nargs++;
1515
2.42M
    }
1516
1517
2.42M
    result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
1518
1519
2.63M
exit:
1520
5.05M
    for (i=0; i < nargs; i++) {
1521
2.42M
        Py_DECREF(stack[i]);
1522
2.42M
    }
1523
2.63M
    if (stack != small_stack) {
1524
0
        PyMem_Free(stack);
1525
0
    }
1526
2.63M
    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
15.5M
{
1668
15.5M
    PyObject *it, *res;
1669
1670
15.5M
    if (!_PyArg_CheckPositional("next", nargs, 1, 2))
1671
0
        return NULL;
1672
1673
15.5M
    it = args[0];
1674
15.5M
    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
15.5M
    res = (*Py_TYPE(it)->tp_iternext)(it);
1682
15.5M
    if (res != NULL) {
1683
15.4M
        return res;
1684
15.4M
    } else if (nargs > 1) {
1685
22.0k
        PyObject *def = args[1];
1686
22.0k
        if (PyErr_Occurred()) {
1687
0
            if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1688
0
                return NULL;
1689
0
            PyErr_Clear();
1690
0
        }
1691
22.0k
        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
15.5M
}
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.67k
{
1725
3.67k
    if (PyObject_SetAttr(obj, name, value) != 0)
1726
0
        return NULL;
1727
3.67k
    Py_RETURN_NONE;
1728
3.67k
}
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
556
{
1747
556
    if (PyObject_DelAttr(obj, name) < 0) {
1748
0
        return NULL;
1749
0
    }
1750
556
    Py_RETURN_NONE;
1751
556
}
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
    integer: 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 *integer)
1793
/*[clinic end generated code: output=e5de857ba61aae08 input=3bef4746efc62fac]*/
1794
0
{
1795
0
    return PyNumber_ToBase(integer, 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
19.0k
{
1803
19.0k
    PyObject *v;
1804
1805
19.0k
    if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
1806
0
        return NULL;
1807
19.0k
    v = args[0];
1808
19.0k
    if (nargs == 1)
1809
19.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
    async_iterator as 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=f3dc5a93f073e5ac]*/
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
880
{
1903
880
    Py_ssize_t res;
1904
1905
880
    res = PyObject_Size(obj);
1906
880
    if (res < 0) {
1907
0
        assert(PyErr_Occurred());
1908
0
        return NULL;
1909
0
    }
1910
880
    return PyLong_FromSsize_t(res);
1911
880
}
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
7.14M
{
1949
7.14M
    PyObject *it = NULL, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1950
7.14M
    PyObject *defaultval = NULL;
1951
7.14M
    static const char * const keywords[] = {"key", "default", NULL};
1952
7.14M
    static _PyArg_Parser _parser_min = {"|$OO:min", keywords, 0};
1953
7.14M
    static _PyArg_Parser _parser_max = {"|$OO:max", keywords, 0};
1954
7.14M
    const char *name = (op == Py_LT) ? "min" : "max";
1955
7.14M
    _PyArg_Parser *_parser = (op == Py_LT) ? &_parser_min : &_parser_max;
1956
1957
7.14M
    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
7.14M
    if (kwnames != NULL && !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, _parser,
1963
0
                                                         &keyfunc, &defaultval)) {
1964
0
        return NULL;
1965
0
    }
1966
1967
7.14M
    const int positional = nargs > 1; // False iff nargs == 1
1968
7.14M
    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
7.14M
    if (!positional) {
1976
52.3k
        it = PyObject_GetIter(args[0]);
1977
52.3k
        if (it == NULL) {
1978
0
            return NULL;
1979
0
        }
1980
52.3k
    }
1981
1982
7.14M
    if (keyfunc == Py_None) {
1983
0
        keyfunc = NULL;
1984
0
    }
1985
1986
7.14M
    maxitem = NULL; /* the result */
1987
7.14M
    maxval = NULL;  /* the value associated with the result */
1988
21.4M
    while (1) {
1989
21.4M
        if (it == NULL) {
1990
21.2M
            if (nargs-- <= 0) {
1991
7.09M
                break;
1992
7.09M
            }
1993
14.1M
            item = *args++;
1994
14.1M
            Py_INCREF(item);
1995
14.1M
        }
1996
155k
        else {
1997
155k
            item = PyIter_Next(it);
1998
155k
            if (item == NULL) {
1999
52.3k
                if (PyErr_Occurred()) {
2000
0
                    goto Fail_it;
2001
0
                }
2002
52.3k
                break;
2003
52.3k
            }
2004
155k
        }
2005
2006
        /* get the value from the key function */
2007
14.2M
        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
14.2M
        else {
2014
14.2M
            val = Py_NewRef(item);
2015
14.2M
        }
2016
2017
        /* maximum value and item are unset; set them */
2018
14.2M
        if (maxval == NULL) {
2019
7.14M
            maxitem = item;
2020
7.14M
            maxval = val;
2021
7.14M
        }
2022
        /* maximum value and item are set; update them as necessary */
2023
7.14M
        else {
2024
7.14M
            int cmp = PyObject_RichCompareBool(val, maxval, op);
2025
7.14M
            if (cmp < 0)
2026
0
                goto Fail_it_item_and_val;
2027
7.14M
            else if (cmp > 0) {
2028
1.29M
                Py_DECREF(maxval);
2029
1.29M
                Py_DECREF(maxitem);
2030
1.29M
                maxval = val;
2031
1.29M
                maxitem = item;
2032
1.29M
            }
2033
5.84M
            else {
2034
5.84M
                Py_DECREF(item);
2035
5.84M
                Py_DECREF(val);
2036
5.84M
            }
2037
7.14M
        }
2038
14.2M
    }
2039
7.14M
    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
7.14M
    else
2049
7.14M
        Py_DECREF(maxval);
2050
7.14M
    Py_XDECREF(it);
2051
7.14M
    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
6.40M
{
2068
6.40M
    return min_max(args, nargs, kwnames, Py_LT);
2069
6.40M
}
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
744k
{
2085
744k
    return min_max(args, nargs, kwnames, Py_GT);
2086
744k
}
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
    integer: 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 *integer)
2112
/*[clinic end generated code: output=8c15f2145a74c390 input=b97c377b15fedf8d]*/
2113
0
{
2114
0
    return PyNumber_ToBase(integer, 8);
2115
0
}
2116
2117
2118
/*[clinic input]
2119
ord as builtin_ord
2120
2121
    character as c: object
2122
    /
2123
2124
Return the ordinal value of a character.
2125
2126
If the argument is a one-character string, return the Unicode code
2127
point of that character.
2128
2129
If the argument is a bytes or bytearray object of length 1, return its
2130
single byte value.
2131
[clinic start generated code]*/
2132
2133
static PyObject *
2134
builtin_ord(PyObject *module, PyObject *c)
2135
/*[clinic end generated code: output=4fa5e87a323bae71 input=98d38480432e1177]*/
2136
26.4M
{
2137
26.4M
    long ord;
2138
26.4M
    Py_ssize_t size;
2139
2140
26.4M
    if (PyBytes_Check(c)) {
2141
0
        size = PyBytes_GET_SIZE(c);
2142
0
        if (size == 1) {
2143
0
            ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
2144
0
            return PyLong_FromLong(ord);
2145
0
        }
2146
0
    }
2147
26.4M
    else if (PyUnicode_Check(c)) {
2148
26.4M
        size = PyUnicode_GET_LENGTH(c);
2149
26.4M
        if (size == 1) {
2150
26.4M
            ord = (long)PyUnicode_READ_CHAR(c, 0);
2151
26.4M
            return PyLong_FromLong(ord);
2152
26.4M
        }
2153
26.4M
    }
2154
0
    else if (PyByteArray_Check(c)) {
2155
        /* XXX Hopefully this is temporary */
2156
0
        size = PyByteArray_GET_SIZE(c);
2157
0
        if (size == 1) {
2158
0
            ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
2159
0
            return PyLong_FromLong(ord);
2160
0
        }
2161
0
    }
2162
0
    else {
2163
0
        PyErr_Format(PyExc_TypeError,
2164
0
                     "ord() expected string of length 1, but " \
2165
0
                     "%.200s found", Py_TYPE(c)->tp_name);
2166
0
        return NULL;
2167
0
    }
2168
2169
0
    PyErr_Format(PyExc_TypeError,
2170
0
                 "ord() expected a character, "
2171
0
                 "but string of length %zd found",
2172
0
                 size);
2173
0
    return NULL;
2174
26.4M
}
2175
2176
2177
/*[clinic input]
2178
pow as builtin_pow
2179
2180
    base: object
2181
    exp: object
2182
    mod: object = None
2183
2184
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
2185
2186
Some types, such as ints, are able to use a more efficient algorithm when
2187
invoked using the three argument form.
2188
[clinic start generated code]*/
2189
2190
static PyObject *
2191
builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
2192
                 PyObject *mod)
2193
/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
2194
0
{
2195
0
    return PyNumber_Power(base, exp, mod);
2196
0
}
2197
2198
/*[clinic input]
2199
print as builtin_print
2200
2201
    *objects: array
2202
    sep: object(c_default="Py_None") = ' '
2203
        string inserted between values, default a space.
2204
    end: object(c_default="Py_None") = '\n'
2205
        string appended after the last value, default a newline.
2206
    file: object = None
2207
        a file-like object (stream); defaults to the current sys.stdout.
2208
    flush: bool = False
2209
        whether to forcibly flush the stream.
2210
2211
Prints the values to a stream, or to sys.stdout by default.
2212
2213
[clinic start generated code]*/
2214
2215
static PyObject *
2216
builtin_print_impl(PyObject *module, PyObject * const *objects,
2217
                   Py_ssize_t objects_length, PyObject *sep, PyObject *end,
2218
                   PyObject *file, int flush)
2219
/*[clinic end generated code: output=38d8def56c837bcc input=ff35cb3d59ee8115]*/
2220
0
{
2221
0
    int i, err;
2222
2223
0
    if (file == Py_None) {
2224
0
        file = PySys_GetAttr(&_Py_ID(stdout));
2225
0
        if (file == NULL) {
2226
0
            return NULL;
2227
0
        }
2228
2229
        /* sys.stdout may be None when FILE* stdout isn't connected */
2230
0
        if (file == Py_None) {
2231
0
            Py_DECREF(file);
2232
0
            Py_RETURN_NONE;
2233
0
        }
2234
0
    }
2235
0
    else {
2236
0
        Py_INCREF(file);
2237
0
    }
2238
2239
0
    if (sep == Py_None) {
2240
0
        sep = NULL;
2241
0
    }
2242
0
    else if (sep && !PyUnicode_Check(sep)) {
2243
0
        PyErr_Format(PyExc_TypeError,
2244
0
                     "sep must be None or a string, not %.200s",
2245
0
                     Py_TYPE(sep)->tp_name);
2246
0
        Py_DECREF(file);
2247
0
        return NULL;
2248
0
    }
2249
0
    if (end == Py_None) {
2250
0
        end = NULL;
2251
0
    }
2252
0
    else if (end && !PyUnicode_Check(end)) {
2253
0
        PyErr_Format(PyExc_TypeError,
2254
0
                     "end must be None or a string, not %.200s",
2255
0
                     Py_TYPE(end)->tp_name);
2256
0
        Py_DECREF(file);
2257
0
        return NULL;
2258
0
    }
2259
2260
0
    for (i = 0; i < objects_length; i++) {
2261
0
        if (i > 0) {
2262
0
            if (sep == NULL) {
2263
0
                err = PyFile_WriteString(" ", file);
2264
0
            }
2265
0
            else {
2266
0
                err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
2267
0
            }
2268
0
            if (err) {
2269
0
                Py_DECREF(file);
2270
0
                return NULL;
2271
0
            }
2272
0
        }
2273
0
        err = PyFile_WriteObject(objects[i], file, Py_PRINT_RAW);
2274
0
        if (err) {
2275
0
            Py_DECREF(file);
2276
0
            return NULL;
2277
0
        }
2278
0
    }
2279
2280
0
    if (end == NULL) {
2281
0
        err = PyFile_WriteString("\n", file);
2282
0
    }
2283
0
    else {
2284
0
        err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2285
0
    }
2286
0
    if (err) {
2287
0
        Py_DECREF(file);
2288
0
        return NULL;
2289
0
    }
2290
2291
0
    if (flush) {
2292
0
        if (_PyFile_Flush(file) < 0) {
2293
0
            Py_DECREF(file);
2294
0
            return NULL;
2295
0
        }
2296
0
    }
2297
0
    Py_DECREF(file);
2298
2299
0
    Py_RETURN_NONE;
2300
0
}
2301
2302
2303
/*[clinic input]
2304
input as builtin_input
2305
2306
    prompt: object(c_default="NULL") = ""
2307
    /
2308
2309
Read a string from standard input.  The trailing newline is stripped.
2310
2311
The prompt string, if given, is printed to standard output without a
2312
trailing newline before reading input.
2313
2314
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2315
On *nix systems, readline is used if available.
2316
[clinic start generated code]*/
2317
2318
static PyObject *
2319
builtin_input_impl(PyObject *module, PyObject *prompt)
2320
/*[clinic end generated code: output=83db5a191e7a0d60 input=159c46d4ae40977e]*/
2321
0
{
2322
0
    PyObject *fin = NULL;
2323
0
    PyObject *fout = NULL;
2324
0
    PyObject *ferr = NULL;
2325
0
    PyObject *tmp;
2326
0
    long fd;
2327
0
    int tty;
2328
2329
    /* Check that stdin/out/err are intact */
2330
0
    fin = PySys_GetAttr(&_Py_ID(stdin));
2331
0
    if (fin == NULL) {
2332
0
        goto error;
2333
0
    }
2334
0
    if (fin == Py_None) {
2335
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
2336
0
        goto error;
2337
0
    }
2338
0
    fout = PySys_GetAttr(&_Py_ID(stdout));
2339
0
    if (fout == NULL) {
2340
0
        goto error;
2341
0
    }
2342
0
    if (fout == Py_None) {
2343
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
2344
0
        goto error;
2345
0
    }
2346
0
    ferr = PySys_GetAttr(&_Py_ID(stderr));
2347
0
    if (ferr == NULL) {
2348
0
        goto error;
2349
0
    }
2350
0
    if (ferr == Py_None) {
2351
0
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stderr");
2352
0
        goto error;
2353
0
    }
2354
2355
0
    if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2356
0
        goto error;
2357
0
    }
2358
2359
    /* First of all, flush stderr */
2360
0
    if (_PyFile_Flush(ferr) < 0) {
2361
0
        PyErr_Clear();
2362
0
    }
2363
2364
    /* We should only use (GNU) readline if Python's sys.stdin and
2365
       sys.stdout are the same as C's stdin and stdout, because we
2366
       need to pass it those. */
2367
0
    tmp = PyObject_CallMethodNoArgs(fin, &_Py_ID(fileno));
2368
0
    if (tmp == NULL) {
2369
0
        PyErr_Clear();
2370
0
        tty = 0;
2371
0
    }
2372
0
    else {
2373
0
        fd = PyLong_AsLong(tmp);
2374
0
        Py_DECREF(tmp);
2375
0
        if (fd < 0 && PyErr_Occurred()) {
2376
0
            goto error;
2377
0
        }
2378
0
        tty = fd == fileno(stdin) && isatty(fd);
2379
0
    }
2380
0
    if (tty) {
2381
0
        tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(fileno));
2382
0
        if (tmp == NULL) {
2383
0
            PyErr_Clear();
2384
0
            tty = 0;
2385
0
        }
2386
0
        else {
2387
0
            fd = PyLong_AsLong(tmp);
2388
0
            Py_DECREF(tmp);
2389
0
            if (fd < 0 && PyErr_Occurred())
2390
0
                goto error;
2391
0
            tty = fd == fileno(stdout) && isatty(fd);
2392
0
        }
2393
0
    }
2394
2395
    /* If we're interactive, use (GNU) readline */
2396
0
    if (tty) {
2397
0
        PyObject *po = NULL;
2398
0
        const char *promptstr;
2399
0
        char *s = NULL;
2400
0
        PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2401
0
        PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
2402
0
        const char *stdin_encoding_str, *stdin_errors_str;
2403
0
        PyObject *result;
2404
0
        size_t len;
2405
2406
        /* stdin is a text stream, so it must have an encoding. */
2407
0
        stdin_encoding = PyObject_GetAttr(fin, &_Py_ID(encoding));
2408
0
        if (stdin_encoding == NULL) {
2409
0
            tty = 0;
2410
0
            goto _readline_errors;
2411
0
        }
2412
0
        stdin_errors = PyObject_GetAttr(fin, &_Py_ID(errors));
2413
0
        if (stdin_errors == NULL) {
2414
0
            tty = 0;
2415
0
            goto _readline_errors;
2416
0
        }
2417
0
        if (!PyUnicode_Check(stdin_encoding) ||
2418
0
            !PyUnicode_Check(stdin_errors))
2419
0
        {
2420
0
            tty = 0;
2421
0
            goto _readline_errors;
2422
0
        }
2423
0
        stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2424
0
        if (stdin_encoding_str == NULL) {
2425
0
            goto _readline_errors;
2426
0
        }
2427
0
        stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
2428
0
        if (stdin_errors_str == NULL) {
2429
0
            goto _readline_errors;
2430
0
        }
2431
0
        if (_PyFile_Flush(fout) < 0) {
2432
0
            PyErr_Clear();
2433
0
        }
2434
0
        if (prompt != NULL) {
2435
            /* We have a prompt, encode it as stdout would */
2436
0
            const char *stdout_encoding_str, *stdout_errors_str;
2437
0
            PyObject *stringpo;
2438
0
            stdout_encoding = PyObject_GetAttr(fout, &_Py_ID(encoding));
2439
0
            if (stdout_encoding == NULL) {
2440
0
                tty = 0;
2441
0
                goto _readline_errors;
2442
0
            }
2443
0
            stdout_errors = PyObject_GetAttr(fout, &_Py_ID(errors));
2444
0
            if (stdout_errors == NULL) {
2445
0
                tty = 0;
2446
0
                goto _readline_errors;
2447
0
            }
2448
0
            if (!PyUnicode_Check(stdout_encoding) ||
2449
0
                !PyUnicode_Check(stdout_errors))
2450
0
            {
2451
0
                tty = 0;
2452
0
                goto _readline_errors;
2453
0
            }
2454
0
            stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2455
0
            if (stdout_encoding_str == NULL) {
2456
0
                goto _readline_errors;
2457
0
            }
2458
0
            stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
2459
0
            if (stdout_errors_str == NULL) {
2460
0
                goto _readline_errors;
2461
0
            }
2462
0
            stringpo = PyObject_Str(prompt);
2463
0
            if (stringpo == NULL)
2464
0
                goto _readline_errors;
2465
0
            po = PyUnicode_AsEncodedString(stringpo,
2466
0
                stdout_encoding_str, stdout_errors_str);
2467
0
            Py_CLEAR(stdout_encoding);
2468
0
            Py_CLEAR(stdout_errors);
2469
0
            Py_CLEAR(stringpo);
2470
0
            if (po == NULL)
2471
0
                goto _readline_errors;
2472
0
            assert(PyBytes_Check(po));
2473
0
            promptstr = PyBytes_AS_STRING(po);
2474
0
            if ((Py_ssize_t)strlen(promptstr) != PyBytes_GET_SIZE(po)) {
2475
0
                PyErr_SetString(PyExc_ValueError,
2476
0
                        "input: prompt string cannot contain null characters");
2477
0
                goto _readline_errors;
2478
0
            }
2479
0
        }
2480
0
        else {
2481
0
            po = NULL;
2482
0
            promptstr = "";
2483
0
        }
2484
0
        s = PyOS_Readline(stdin, stdout, promptstr);
2485
0
        if (s == NULL) {
2486
0
            PyErr_CheckSignals();
2487
0
            if (!PyErr_Occurred())
2488
0
                PyErr_SetNone(PyExc_KeyboardInterrupt);
2489
0
            goto _readline_errors;
2490
0
        }
2491
2492
0
        len = strlen(s);
2493
0
        if (len == 0) {
2494
0
            PyErr_SetNone(PyExc_EOFError);
2495
0
            result = NULL;
2496
0
        }
2497
0
        else {
2498
0
            if (len > PY_SSIZE_T_MAX) {
2499
0
                PyErr_SetString(PyExc_OverflowError,
2500
0
                                "input: input too long");
2501
0
                result = NULL;
2502
0
            }
2503
0
            else {
2504
0
                len--;   /* strip trailing '\n' */
2505
0
                if (len != 0 && s[len-1] == '\r')
2506
0
                    len--;   /* strip trailing '\r' */
2507
0
                result = PyUnicode_Decode(s, len, stdin_encoding_str,
2508
0
                                                  stdin_errors_str);
2509
0
            }
2510
0
        }
2511
0
        Py_DECREF(stdin_encoding);
2512
0
        Py_DECREF(stdin_errors);
2513
0
        Py_XDECREF(po);
2514
0
        PyMem_Free(s);
2515
2516
0
        if (result != NULL) {
2517
0
            if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2518
0
                goto error;
2519
0
            }
2520
0
        }
2521
2522
0
        Py_DECREF(fin);
2523
0
        Py_DECREF(fout);
2524
0
        Py_DECREF(ferr);
2525
0
        return result;
2526
2527
0
    _readline_errors:
2528
0
        Py_XDECREF(stdin_encoding);
2529
0
        Py_XDECREF(stdout_encoding);
2530
0
        Py_XDECREF(stdin_errors);
2531
0
        Py_XDECREF(stdout_errors);
2532
0
        Py_XDECREF(po);
2533
0
        if (tty)
2534
0
            goto error;
2535
2536
0
        PyErr_Clear();
2537
0
    }
2538
2539
    /* Fallback if we're not interactive */
2540
0
    if (prompt != NULL) {
2541
0
        if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
2542
0
            goto error;
2543
0
    }
2544
0
    if (_PyFile_Flush(fout) < 0) {
2545
0
        PyErr_Clear();
2546
0
    }
2547
0
    tmp = PyFile_GetLine(fin, -1);
2548
0
    Py_DECREF(fin);
2549
0
    Py_DECREF(fout);
2550
0
    Py_DECREF(ferr);
2551
0
    return tmp;
2552
2553
0
error:
2554
0
    Py_XDECREF(fin);
2555
0
    Py_XDECREF(fout);
2556
0
    Py_XDECREF(ferr);
2557
0
    return NULL;
2558
0
}
2559
2560
2561
/*[clinic input]
2562
repr as builtin_repr
2563
2564
    obj: object
2565
    /
2566
2567
Return the canonical string representation of the object.
2568
2569
For many object types, including most builtins, eval(repr(obj)) == obj.
2570
[clinic start generated code]*/
2571
2572
static PyObject *
2573
builtin_repr(PyObject *module, PyObject *obj)
2574
/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
2575
51.5k
{
2576
51.5k
    return PyObject_Repr(obj);
2577
51.5k
}
2578
2579
2580
/*[clinic input]
2581
round as builtin_round
2582
2583
    number: object
2584
    ndigits: object = None
2585
2586
Round a number to a given precision in decimal digits.
2587
2588
The return value is an integer if ndigits is omitted or None.  Otherwise
2589
the return value has the same type as the number.  ndigits may be negative.
2590
[clinic start generated code]*/
2591
2592
static PyObject *
2593
builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2594
/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
2595
0
{
2596
0
    PyObject *result;
2597
0
    if (ndigits == Py_None) {
2598
0
        result = _PyObject_MaybeCallSpecialNoArgs(number, &_Py_ID(__round__));
2599
0
    }
2600
0
    else {
2601
0
        result = _PyObject_MaybeCallSpecialOneArg(number, &_Py_ID(__round__),
2602
0
                                                  ndigits);
2603
0
    }
2604
0
    if (result == NULL && !PyErr_Occurred()) {
2605
0
        PyErr_Format(PyExc_TypeError,
2606
0
                     "type %.100s doesn't define __round__ method",
2607
0
                     Py_TYPE(number)->tp_name);
2608
0
    }
2609
0
    return result;
2610
0
}
2611
2612
2613
/*AC: we need to keep the kwds dict intact to easily call into the
2614
 * list.sort method, which isn't currently supported in AC. So we just use
2615
 * the initially generated signature with a custom implementation.
2616
 */
2617
/* [disabled clinic input]
2618
sorted as builtin_sorted
2619
2620
    iterable as seq: object
2621
    key as keyfunc: object = None
2622
    reverse: object = False
2623
2624
Return a new list containing all items from the iterable in ascending order.
2625
2626
A custom key function can be supplied to customize the sort order, and the
2627
reverse flag can be set to request the result in descending order.
2628
[end disabled clinic input]*/
2629
2630
PyDoc_STRVAR(builtin_sorted__doc__,
2631
"sorted($module, iterable, /, *, key=None, reverse=False)\n"
2632
"--\n"
2633
"\n"
2634
"Return a new list containing all items from the iterable in ascending order.\n"
2635
"\n"
2636
"A custom key function can be supplied to customize the sort order, and the\n"
2637
"reverse flag can be set to request the result in descending order.");
2638
2639
#define BUILTIN_SORTED_METHODDEF    \
2640
    {"sorted", _PyCFunction_CAST(builtin_sorted), METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
2641
2642
static PyObject *
2643
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2644
316k
{
2645
316k
    PyObject *newlist, *v, *seq, *callable;
2646
2647
    /* Keyword arguments are passed through list.sort() which will check
2648
       them. */
2649
316k
    if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
2650
0
        return NULL;
2651
2652
316k
    newlist = PySequence_List(seq);
2653
316k
    if (newlist == NULL)
2654
0
        return NULL;
2655
2656
316k
    callable = PyObject_GetAttr(newlist, &_Py_ID(sort));
2657
316k
    if (callable == NULL) {
2658
0
        Py_DECREF(newlist);
2659
0
        return NULL;
2660
0
    }
2661
2662
316k
    assert(nargs >= 1);
2663
316k
    v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
2664
316k
    Py_DECREF(callable);
2665
316k
    if (v == NULL) {
2666
0
        Py_DECREF(newlist);
2667
0
        return NULL;
2668
0
    }
2669
316k
    Py_DECREF(v);
2670
316k
    return newlist;
2671
316k
}
2672
2673
2674
/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
2675
static PyObject *
2676
builtin_vars(PyObject *self, PyObject *args)
2677
16
{
2678
16
    PyObject *v = NULL;
2679
16
    PyObject *d;
2680
2681
16
    if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2682
0
        return NULL;
2683
16
    if (v == NULL) {
2684
0
        if (_PyEval_GetFrame() != NULL) {
2685
0
            d = _PyEval_GetFrameLocals();
2686
0
        }
2687
0
        else {
2688
0
            PyThreadState *tstate = _PyThreadState_GET();
2689
0
            d = _PyEval_GetGlobalsFromRunningMain(tstate);
2690
0
            if (d == NULL) {
2691
0
                if (!_PyErr_Occurred(tstate)) {
2692
0
                    d = _PyEval_GetFrameLocals();
2693
0
                    assert(_PyErr_Occurred(tstate));
2694
0
                }
2695
0
            }
2696
0
            else {
2697
0
                Py_INCREF(d);
2698
0
            }
2699
0
        }
2700
0
    }
2701
16
    else {
2702
16
        if (PyObject_GetOptionalAttr(v, &_Py_ID(__dict__), &d) == 0) {
2703
0
            PyErr_SetString(PyExc_TypeError,
2704
0
                "vars() argument must have __dict__ attribute");
2705
0
        }
2706
16
    }
2707
16
    return d;
2708
16
}
2709
2710
PyDoc_STRVAR(vars_doc,
2711
"vars([object]) -> dictionary\n\
2712
\n\
2713
Without arguments, equivalent to locals().\n\
2714
With an argument, equivalent to object.__dict__.");
2715
2716
2717
/* Improved Kahan–Babuška algorithm by Arnold Neumaier
2718
   Neumaier, A. (1974), Rundungsfehleranalyse einiger Verfahren
2719
   zur Summation endlicher Summen.  Z. angew. Math. Mech.,
2720
   54: 39-51. https://doi.org/10.1002/zamm.19740540106
2721
   https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
2722
 */
2723
2724
typedef struct {
2725
    double hi;     /* high-order bits for a running sum */
2726
    double lo;     /* a running compensation for lost low-order bits */
2727
} CompensatedSum;
2728
2729
static inline CompensatedSum
2730
cs_from_double(double x)
2731
0
{
2732
0
    return (CompensatedSum) {x};
2733
0
}
2734
2735
static inline CompensatedSum
2736
cs_add(CompensatedSum total, double x)
2737
0
{
2738
0
    double t = total.hi + x;
2739
0
    if (fabs(total.hi) >= fabs(x)) {
2740
0
        total.lo += (total.hi - t) + x;
2741
0
    }
2742
0
    else {
2743
0
        total.lo += (x - t) + total.hi;
2744
0
    }
2745
0
    return (CompensatedSum) {t, total.lo};
2746
0
}
2747
2748
static inline double
2749
cs_to_double(CompensatedSum total)
2750
0
{
2751
    /* Avoid losing the sign on a negative result,
2752
       and don't let adding the compensation convert
2753
       an infinite or overflowed sum to a NaN. */
2754
0
    if (total.lo && isfinite(total.lo)) {
2755
0
        return total.hi + total.lo;
2756
0
    }
2757
0
    return total.hi;
2758
0
}
2759
2760
/*[clinic input]
2761
sum as builtin_sum
2762
2763
    iterable: object
2764
    /
2765
    start: object(c_default="NULL") = 0
2766
2767
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2768
2769
When the iterable is empty, return the start value.
2770
This function is intended specifically for use with numeric values and may
2771
reject non-numeric types.
2772
[clinic start generated code]*/
2773
2774
static PyObject *
2775
builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2776
/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
2777
10.6M
{
2778
10.6M
    PyObject *result = start;
2779
10.6M
    PyObject *temp, *item, *iter;
2780
2781
10.6M
    iter = PyObject_GetIter(iterable);
2782
10.6M
    if (iter == NULL)
2783
0
        return NULL;
2784
2785
10.6M
    if (result == NULL) {
2786
1.11M
        result = PyLong_FromLong(0);
2787
1.11M
        if (result == NULL) {
2788
0
            Py_DECREF(iter);
2789
0
            return NULL;
2790
0
        }
2791
9.53M
    } else {
2792
        /* reject string values for 'start' parameter */
2793
9.53M
        if (PyUnicode_Check(result)) {
2794
0
            PyErr_SetString(PyExc_TypeError,
2795
0
                "sum() can't sum strings [use ''.join(seq) instead]");
2796
0
            Py_DECREF(iter);
2797
0
            return NULL;
2798
0
        }
2799
9.53M
        if (PyBytes_Check(result)) {
2800
0
            PyErr_SetString(PyExc_TypeError,
2801
0
                "sum() can't sum bytes [use b''.join(seq) instead]");
2802
0
            Py_DECREF(iter);
2803
0
            return NULL;
2804
0
        }
2805
9.53M
        if (PyByteArray_Check(result)) {
2806
0
            PyErr_SetString(PyExc_TypeError,
2807
0
                "sum() can't sum bytearray [use b''.join(seq) instead]");
2808
0
            Py_DECREF(iter);
2809
0
            return NULL;
2810
0
        }
2811
9.53M
        Py_INCREF(result);
2812
9.53M
    }
2813
2814
10.6M
#ifndef SLOW_SUM
2815
    /* Fast addition by keeping temporary sums in C instead of new Python objects.
2816
       Assumes all inputs are the same type.  If the assumption fails, default
2817
       to the more general routine.
2818
    */
2819
10.6M
    if (PyLong_CheckExact(result)) {
2820
1.11M
        int overflow;
2821
1.11M
        Py_ssize_t i_result = PyLong_AsLongAndOverflow(result, &overflow);
2822
        /* If this already overflowed, don't even enter the loop. */
2823
1.11M
        if (overflow == 0) {
2824
1.11M
            Py_SETREF(result, NULL);
2825
1.11M
        }
2826
3.27M
        while(result == NULL) {
2827
3.27M
            item = PyIter_Next(iter);
2828
3.27M
            if (item == NULL) {
2829
1.11M
                Py_DECREF(iter);
2830
1.11M
                if (PyErr_Occurred())
2831
0
                    return NULL;
2832
1.11M
                return PyLong_FromSsize_t(i_result);
2833
1.11M
            }
2834
2.16M
            if (PyLong_CheckExact(item) || PyBool_Check(item)) {
2835
2.16M
                Py_ssize_t b;
2836
2.16M
                overflow = 0;
2837
                /* Single digits are common, fast, and cannot overflow on unpacking. */
2838
2.16M
                if (_PyLong_IsCompact((PyLongObject *)item)) {
2839
2.16M
                    b = _PyLong_CompactValue((PyLongObject *)item);
2840
2.16M
                }
2841
0
                else {
2842
0
                    b = PyLong_AsLongAndOverflow(item, &overflow);
2843
0
                }
2844
2.16M
                if (overflow == 0 &&
2845
2.16M
                    (i_result >= 0 ? (b <= PY_SSIZE_T_MAX - i_result)
2846
2.16M
                                   : (b >= PY_SSIZE_T_MIN - i_result)))
2847
2.16M
                {
2848
2.16M
                    i_result += b;
2849
2.16M
                    Py_DECREF(item);
2850
2.16M
                    continue;
2851
2.16M
                }
2852
2.16M
            }
2853
            /* Either overflowed or is not an int. Restore real objects and process normally */
2854
0
            result = PyLong_FromSsize_t(i_result);
2855
0
            if (result == NULL) {
2856
0
                Py_DECREF(item);
2857
0
                Py_DECREF(iter);
2858
0
                return NULL;
2859
0
            }
2860
0
            temp = PyNumber_Add(result, item);
2861
0
            Py_DECREF(result);
2862
0
            Py_DECREF(item);
2863
0
            result = temp;
2864
0
            if (result == NULL) {
2865
0
                Py_DECREF(iter);
2866
0
                return NULL;
2867
0
            }
2868
0
        }
2869
1.11M
    }
2870
2871
9.53M
    if (PyFloat_CheckExact(result)) {
2872
0
        CompensatedSum re_sum = cs_from_double(PyFloat_AS_DOUBLE(result));
2873
0
        Py_SETREF(result, NULL);
2874
0
        while(result == NULL) {
2875
0
            item = PyIter_Next(iter);
2876
0
            if (item == NULL) {
2877
0
                Py_DECREF(iter);
2878
0
                if (PyErr_Occurred())
2879
0
                    return NULL;
2880
0
                return PyFloat_FromDouble(cs_to_double(re_sum));
2881
0
            }
2882
0
            if (PyFloat_CheckExact(item)) {
2883
0
                re_sum = cs_add(re_sum, PyFloat_AS_DOUBLE(item));
2884
0
                _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2885
0
                continue;
2886
0
            }
2887
0
            if (PyLong_Check(item)) {
2888
0
                double value = PyLong_AsDouble(item);
2889
0
                if (value != -1.0 || !PyErr_Occurred()) {
2890
0
                    re_sum = cs_add(re_sum, value);
2891
0
                    Py_DECREF(item);
2892
0
                    continue;
2893
0
                }
2894
0
                else {
2895
0
                    Py_DECREF(item);
2896
0
                    Py_DECREF(iter);
2897
0
                    return NULL;
2898
0
                }
2899
0
            }
2900
0
            result = PyFloat_FromDouble(cs_to_double(re_sum));
2901
0
            if (result == NULL) {
2902
0
                Py_DECREF(item);
2903
0
                Py_DECREF(iter);
2904
0
                return NULL;
2905
0
            }
2906
0
            temp = PyNumber_Add(result, item);
2907
0
            Py_DECREF(result);
2908
0
            Py_DECREF(item);
2909
0
            result = temp;
2910
0
            if (result == NULL) {
2911
0
                Py_DECREF(iter);
2912
0
                return NULL;
2913
0
            }
2914
0
        }
2915
0
    }
2916
2917
9.53M
    if (PyComplex_CheckExact(result)) {
2918
0
        Py_complex z = PyComplex_AsCComplex(result);
2919
0
        CompensatedSum re_sum = cs_from_double(z.real);
2920
0
        CompensatedSum im_sum = cs_from_double(z.imag);
2921
0
        Py_SETREF(result, NULL);
2922
0
        while (result == NULL) {
2923
0
            item = PyIter_Next(iter);
2924
0
            if (item == NULL) {
2925
0
                Py_DECREF(iter);
2926
0
                if (PyErr_Occurred()) {
2927
0
                    return NULL;
2928
0
                }
2929
0
                return PyComplex_FromDoubles(cs_to_double(re_sum),
2930
0
                                             cs_to_double(im_sum));
2931
0
            }
2932
0
            if (PyComplex_CheckExact(item)) {
2933
0
                z = PyComplex_AsCComplex(item);
2934
0
                re_sum = cs_add(re_sum, z.real);
2935
0
                im_sum = cs_add(im_sum, z.imag);
2936
0
                Py_DECREF(item);
2937
0
                continue;
2938
0
            }
2939
0
            if (PyLong_Check(item)) {
2940
0
                double value = PyLong_AsDouble(item);
2941
0
                if (value != -1.0 || !PyErr_Occurred()) {
2942
0
                    re_sum = cs_add(re_sum, value);
2943
0
                    Py_DECREF(item);
2944
0
                    continue;
2945
0
                }
2946
0
                else {
2947
0
                    Py_DECREF(item);
2948
0
                    Py_DECREF(iter);
2949
0
                    return NULL;
2950
0
                }
2951
0
            }
2952
0
            if (PyFloat_Check(item)) {
2953
0
                double value = PyFloat_AS_DOUBLE(item);
2954
0
                re_sum = cs_add(re_sum, value);
2955
0
                _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2956
0
                continue;
2957
0
            }
2958
0
            result = PyComplex_FromDoubles(cs_to_double(re_sum),
2959
0
                                           cs_to_double(im_sum));
2960
0
            if (result == NULL) {
2961
0
                Py_DECREF(item);
2962
0
                Py_DECREF(iter);
2963
0
                return NULL;
2964
0
            }
2965
0
            temp = PyNumber_Add(result, item);
2966
0
            Py_DECREF(result);
2967
0
            Py_DECREF(item);
2968
0
            result = temp;
2969
0
            if (result == NULL) {
2970
0
                Py_DECREF(iter);
2971
0
                return NULL;
2972
0
            }
2973
0
        }
2974
0
    }
2975
9.53M
#endif
2976
2977
29.8M
    for(;;) {
2978
29.8M
        item = PyIter_Next(iter);
2979
29.8M
        if (item == NULL) {
2980
            /* error, or end-of-sequence */
2981
9.53M
            if (PyErr_Occurred()) {
2982
20.2k
                Py_SETREF(result, NULL);
2983
20.2k
            }
2984
9.53M
            break;
2985
9.53M
        }
2986
        /* It's tempting to use PyNumber_InPlaceAdd instead of
2987
           PyNumber_Add here, to avoid quadratic running time
2988
           when doing 'sum(list_of_lists, [])'.  However, this
2989
           would produce a change in behaviour: a snippet like
2990
2991
             empty = []
2992
             sum([[x] for x in range(10)], empty)
2993
2994
           would change the value of empty. In fact, using
2995
           in-place addition rather that binary addition for
2996
           any of the steps introduces subtle behavior changes:
2997
2998
           https://bugs.python.org/issue18305 */
2999
20.2M
        temp = PyNumber_Add(result, item);
3000
20.2M
        Py_DECREF(result);
3001
20.2M
        Py_DECREF(item);
3002
20.2M
        result = temp;
3003
20.2M
        if (result == NULL)
3004
0
            break;
3005
20.2M
    }
3006
9.53M
    Py_DECREF(iter);
3007
9.53M
    return result;
3008
9.53M
}
3009
3010
3011
/*[clinic input]
3012
isinstance as builtin_isinstance
3013
3014
    obj: object
3015
    class_or_tuple: object
3016
    /
3017
3018
Return whether an object is an instance of a class or of a subclass thereof.
3019
3020
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
3021
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
3022
or ...`` etc.
3023
[clinic start generated code]*/
3024
3025
static PyObject *
3026
builtin_isinstance_impl(PyObject *module, PyObject *obj,
3027
                        PyObject *class_or_tuple)
3028
/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
3029
760
{
3030
760
    int retval;
3031
3032
760
    retval = PyObject_IsInstance(obj, class_or_tuple);
3033
760
    if (retval < 0)
3034
0
        return NULL;
3035
760
    return PyBool_FromLong(retval);
3036
760
}
3037
3038
3039
/*[clinic input]
3040
issubclass as builtin_issubclass
3041
3042
    cls: object
3043
    class_or_tuple: object
3044
    /
3045
3046
Return whether 'cls' is derived from another class or is the same class.
3047
3048
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
3049
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
3050
or ...``.
3051
[clinic start generated code]*/
3052
3053
static PyObject *
3054
builtin_issubclass_impl(PyObject *module, PyObject *cls,
3055
                        PyObject *class_or_tuple)
3056
/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
3057
1.70k
{
3058
1.70k
    int retval;
3059
3060
1.70k
    retval = PyObject_IsSubclass(cls, class_or_tuple);
3061
1.70k
    if (retval < 0)
3062
0
        return NULL;
3063
1.70k
    return PyBool_FromLong(retval);
3064
1.70k
}
3065
3066
typedef struct {
3067
    PyObject_HEAD
3068
    Py_ssize_t tuplesize;
3069
    PyObject *ittuple;     /* tuple of iterators */
3070
    PyObject *result;
3071
    int strict;
3072
} zipobject;
3073
3074
21.6M
#define _zipobject_CAST(op)     ((zipobject *)(op))
3075
3076
static PyObject *
3077
zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3078
100k
{
3079
100k
    zipobject *lz;
3080
100k
    Py_ssize_t i;
3081
100k
    PyObject *ittuple;  /* tuple of iterators */
3082
100k
    PyObject *result;
3083
100k
    Py_ssize_t tuplesize;
3084
100k
    int strict = 0;
3085
3086
100k
    if (kwds) {
3087
1.74k
        PyObject *empty = PyTuple_New(0);
3088
1.74k
        if (empty == NULL) {
3089
0
            return NULL;
3090
0
        }
3091
1.74k
        static char *kwlist[] = {"strict", NULL};
3092
1.74k
        int parsed = PyArg_ParseTupleAndKeywords(
3093
1.74k
                empty, kwds, "|$p:zip", kwlist, &strict);
3094
1.74k
        Py_DECREF(empty);
3095
1.74k
        if (!parsed) {
3096
0
            return NULL;
3097
0
        }
3098
1.74k
    }
3099
3100
    /* args must be a tuple */
3101
100k
    assert(PyTuple_Check(args));
3102
100k
    tuplesize = PyTuple_GET_SIZE(args);
3103
3104
    /* obtain iterators */
3105
100k
    ittuple = PyTuple_New(tuplesize);
3106
100k
    if (ittuple == NULL)
3107
0
        return NULL;
3108
300k
    for (i=0; i < tuplesize; ++i) {
3109
200k
        PyObject *item = PyTuple_GET_ITEM(args, i);
3110
200k
        PyObject *it = PyObject_GetIter(item);
3111
200k
        if (it == NULL) {
3112
0
            Py_DECREF(ittuple);
3113
0
            return NULL;
3114
0
        }
3115
200k
        PyTuple_SET_ITEM(ittuple, i, it);
3116
200k
    }
3117
3118
    /* create a result holder */
3119
100k
    result = PyTuple_New(tuplesize);
3120
100k
    if (result == NULL) {
3121
0
        Py_DECREF(ittuple);
3122
0
        return NULL;
3123
0
    }
3124
300k
    for (i=0 ; i < tuplesize ; i++) {
3125
200k
        PyTuple_SET_ITEM(result, i, Py_NewRef(Py_None));
3126
200k
    }
3127
3128
    /* create zipobject structure */
3129
100k
    lz = (zipobject *)type->tp_alloc(type, 0);
3130
100k
    if (lz == NULL) {
3131
0
        Py_DECREF(ittuple);
3132
0
        Py_DECREF(result);
3133
0
        return NULL;
3134
0
    }
3135
100k
    lz->ittuple = ittuple;
3136
100k
    lz->tuplesize = tuplesize;
3137
100k
    lz->result = result;
3138
100k
    lz->strict = strict;
3139
3140
100k
    return (PyObject *)lz;
3141
100k
}
3142
3143
static void
3144
zip_dealloc(PyObject *self)
3145
100k
{
3146
100k
    zipobject *lz = _zipobject_CAST(self);
3147
100k
    PyObject_GC_UnTrack(lz);
3148
100k
    Py_XDECREF(lz->ittuple);
3149
100k
    Py_XDECREF(lz->result);
3150
100k
    Py_TYPE(lz)->tp_free(lz);
3151
100k
}
3152
3153
static int
3154
zip_traverse(PyObject *self, visitproc visit, void *arg)
3155
793
{
3156
793
    zipobject *lz = _zipobject_CAST(self);
3157
793
    Py_VISIT(lz->ittuple);
3158
793
    Py_VISIT(lz->result);
3159
793
    return 0;
3160
793
}
3161
3162
static PyObject *
3163
zip_next(PyObject *self)
3164
21.5M
{
3165
21.5M
    zipobject *lz = _zipobject_CAST(self);
3166
3167
21.5M
    Py_ssize_t i;
3168
21.5M
    Py_ssize_t tuplesize = lz->tuplesize;
3169
21.5M
    PyObject *result = lz->result;
3170
21.5M
    PyObject *it;
3171
21.5M
    PyObject *item;
3172
21.5M
    PyObject *olditem;
3173
3174
21.5M
    if (tuplesize == 0)
3175
0
        return NULL;
3176
3177
21.5M
    if (_PyObject_IsUniquelyReferenced(result)) {
3178
21.5M
        Py_INCREF(result);
3179
64.3M
        for (i=0 ; i < tuplesize ; i++) {
3180
42.9M
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3181
42.9M
            item = (*Py_TYPE(it)->tp_iternext)(it);
3182
42.9M
            if (item == NULL) {
3183
98.1k
                Py_DECREF(result);
3184
98.1k
                if (lz->strict) {
3185
1.60k
                    goto check;
3186
1.60k
                }
3187
96.5k
                return NULL;
3188
98.1k
            }
3189
42.8M
            olditem = PyTuple_GET_ITEM(result, i);
3190
42.8M
            PyTuple_SET_ITEM(result, i, item);
3191
42.8M
            Py_DECREF(olditem);
3192
42.8M
        }
3193
        // bpo-42536: The GC may have untracked this result tuple. Since we're
3194
        // recycling it, make sure it's tracked again:
3195
21.4M
        _PyTuple_Recycle(result);
3196
21.4M
    } else {
3197
5.67k
        result = PyTuple_New(tuplesize);
3198
5.67k
        if (result == NULL)
3199
0
            return NULL;
3200
13.6k
        for (i=0 ; i < tuplesize ; i++) {
3201
9.64k
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3202
9.64k
            item = (*Py_TYPE(it)->tp_iternext)(it);
3203
9.64k
            if (item == NULL) {
3204
1.70k
                Py_DECREF(result);
3205
1.70k
                if (lz->strict) {
3206
139
                    goto check;
3207
139
                }
3208
1.56k
                return NULL;
3209
1.70k
            }
3210
7.93k
            PyTuple_SET_ITEM(result, i, item);
3211
7.93k
        }
3212
5.67k
    }
3213
21.4M
    return result;
3214
1.74k
check:
3215
1.74k
    if (PyErr_Occurred()) {
3216
0
        if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
3217
            // next() on argument i raised an exception (not StopIteration)
3218
0
            return NULL;
3219
0
        }
3220
0
        PyErr_Clear();
3221
0
    }
3222
1.74k
    if (i) {
3223
        // ValueError: zip() argument 2 is shorter than argument 1
3224
        // ValueError: zip() argument 3 is shorter than arguments 1-2
3225
0
        const char* plural = i == 1 ? " " : "s 1-";
3226
0
        return PyErr_Format(PyExc_ValueError,
3227
0
                            "zip() argument %d is shorter than argument%s%d",
3228
0
                            i + 1, plural, i);
3229
0
    }
3230
3.49k
    for (i = 1; i < tuplesize; i++) {
3231
1.74k
        it = PyTuple_GET_ITEM(lz->ittuple, i);
3232
1.74k
        item = (*Py_TYPE(it)->tp_iternext)(it);
3233
1.74k
        if (item) {
3234
0
            Py_DECREF(item);
3235
0
            const char* plural = i == 1 ? " " : "s 1-";
3236
0
            return PyErr_Format(PyExc_ValueError,
3237
0
                                "zip() argument %d is longer than argument%s%d",
3238
0
                                i + 1, plural, i);
3239
0
        }
3240
1.74k
        if (PyErr_Occurred()) {
3241
0
            if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
3242
                // next() on argument i raised an exception (not StopIteration)
3243
0
                return NULL;
3244
0
            }
3245
0
            PyErr_Clear();
3246
0
        }
3247
        // Argument i is exhausted. So far so good...
3248
1.74k
    }
3249
    // All arguments are exhausted. Success!
3250
1.74k
    return NULL;
3251
1.74k
}
3252
3253
static PyObject *
3254
zip_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
3255
0
{
3256
0
    zipobject *lz = _zipobject_CAST(self);
3257
    /* Just recreate the zip with the internal iterator tuple */
3258
0
    if (lz->strict) {
3259
0
        return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
3260
0
    }
3261
0
    return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
3262
0
}
3263
3264
static PyObject *
3265
zip_setstate(PyObject *self, PyObject *state)
3266
0
{
3267
0
    int strict = PyObject_IsTrue(state);
3268
0
    if (strict < 0) {
3269
0
        return NULL;
3270
0
    }
3271
0
    zipobject *lz = _zipobject_CAST(self);
3272
0
    lz->strict = strict;
3273
0
    Py_RETURN_NONE;
3274
0
}
3275
3276
static PyMethodDef zip_methods[] = {
3277
    {"__reduce__", zip_reduce, METH_NOARGS, reduce_doc},
3278
    {"__setstate__", zip_setstate, METH_O, setstate_doc},
3279
    {NULL}  /* sentinel */
3280
};
3281
3282
PyDoc_STRVAR(zip_doc,
3283
"zip(*iterables, strict=False)\n\
3284
--\n\
3285
\n\
3286
The zip object yields n-length tuples, where n is the number of iterables\n\
3287
passed as positional arguments to zip().  The i-th element in every tuple\n\
3288
comes from the i-th iterable argument to zip().  This continues until the\n\
3289
shortest argument is exhausted.\n\
3290
\n\
3291
If strict is true and one of the arguments is exhausted before the others,\n\
3292
raise a ValueError.\n\
3293
\n\
3294
   >>> list(zip('abcdefg', range(3), range(4)))\n\
3295
   [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]");
3296
3297
PyTypeObject PyZip_Type = {
3298
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3299
    "zip",                              /* tp_name */
3300
    sizeof(zipobject),                  /* tp_basicsize */
3301
    0,                                  /* tp_itemsize */
3302
    /* methods */
3303
    zip_dealloc,                        /* tp_dealloc */
3304
    0,                                  /* tp_vectorcall_offset */
3305
    0,                                  /* tp_getattr */
3306
    0,                                  /* tp_setattr */
3307
    0,                                  /* tp_as_async */
3308
    0,                                  /* tp_repr */
3309
    0,                                  /* tp_as_number */
3310
    0,                                  /* tp_as_sequence */
3311
    0,                                  /* tp_as_mapping */
3312
    0,                                  /* tp_hash */
3313
    0,                                  /* tp_call */
3314
    0,                                  /* tp_str */
3315
    PyObject_GenericGetAttr,            /* tp_getattro */
3316
    0,                                  /* tp_setattro */
3317
    0,                                  /* tp_as_buffer */
3318
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3319
        Py_TPFLAGS_BASETYPE,            /* tp_flags */
3320
    zip_doc,                            /* tp_doc */
3321
    zip_traverse,                       /* tp_traverse */
3322
    0,                                  /* tp_clear */
3323
    0,                                  /* tp_richcompare */
3324
    0,                                  /* tp_weaklistoffset */
3325
    PyObject_SelfIter,                  /* tp_iter */
3326
    zip_next,                           /* tp_iternext */
3327
    zip_methods,                        /* tp_methods */
3328
    0,                                  /* tp_members */
3329
    0,                                  /* tp_getset */
3330
    0,                                  /* tp_base */
3331
    0,                                  /* tp_dict */
3332
    0,                                  /* tp_descr_get */
3333
    0,                                  /* tp_descr_set */
3334
    0,                                  /* tp_dictoffset */
3335
    0,                                  /* tp_init */
3336
    PyType_GenericAlloc,                /* tp_alloc */
3337
    zip_new,                            /* tp_new */
3338
    PyObject_GC_Del,                    /* tp_free */
3339
};
3340
3341
3342
static PyMethodDef builtin_methods[] = {
3343
    {"__build_class__", _PyCFunction_CAST(builtin___build_class__),
3344
     METH_FASTCALL | METH_KEYWORDS, build_class_doc},
3345
    BUILTIN___IMPORT___METHODDEF
3346
    BUILTIN_ABS_METHODDEF
3347
    BUILTIN_ALL_METHODDEF
3348
    BUILTIN_ANY_METHODDEF
3349
    BUILTIN_ASCII_METHODDEF
3350
    BUILTIN_BIN_METHODDEF
3351
    {"breakpoint", _PyCFunction_CAST(builtin_breakpoint), METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
3352
    BUILTIN_CALLABLE_METHODDEF
3353
    BUILTIN_CHR_METHODDEF
3354
    BUILTIN_COMPILE_METHODDEF
3355
    BUILTIN_DELATTR_METHODDEF
3356
    {"dir", builtin_dir, METH_VARARGS, dir_doc},
3357
    BUILTIN_DIVMOD_METHODDEF
3358
    BUILTIN_EVAL_METHODDEF
3359
    BUILTIN_EXEC_METHODDEF
3360
    BUILTIN_FORMAT_METHODDEF
3361
    {"getattr", _PyCFunction_CAST(builtin_getattr), METH_FASTCALL, getattr_doc},
3362
    BUILTIN_GLOBALS_METHODDEF
3363
    BUILTIN_HASATTR_METHODDEF
3364
    BUILTIN_HASH_METHODDEF
3365
    BUILTIN_HEX_METHODDEF
3366
    BUILTIN_ID_METHODDEF
3367
    BUILTIN_INPUT_METHODDEF
3368
    BUILTIN_ISINSTANCE_METHODDEF
3369
    BUILTIN_ISSUBCLASS_METHODDEF
3370
    {"iter", _PyCFunction_CAST(builtin_iter), METH_FASTCALL, iter_doc},
3371
    BUILTIN_AITER_METHODDEF
3372
    BUILTIN_LEN_METHODDEF
3373
    BUILTIN_LOCALS_METHODDEF
3374
    {"max", _PyCFunction_CAST(builtin_max), METH_FASTCALL | METH_KEYWORDS, max_doc},
3375
    {"min", _PyCFunction_CAST(builtin_min), METH_FASTCALL | METH_KEYWORDS, min_doc},
3376
    {"next", _PyCFunction_CAST(builtin_next), METH_FASTCALL, next_doc},
3377
    BUILTIN_ANEXT_METHODDEF
3378
    BUILTIN_OCT_METHODDEF
3379
    BUILTIN_ORD_METHODDEF
3380
    BUILTIN_POW_METHODDEF
3381
    BUILTIN_PRINT_METHODDEF
3382
    BUILTIN_REPR_METHODDEF
3383
    BUILTIN_ROUND_METHODDEF
3384
    BUILTIN_SETATTR_METHODDEF
3385
    BUILTIN_SORTED_METHODDEF
3386
    BUILTIN_SUM_METHODDEF
3387
    {"vars",            builtin_vars,       METH_VARARGS, vars_doc},
3388
    {NULL,              NULL},
3389
};
3390
3391
PyDoc_STRVAR(builtin_doc,
3392
"Built-in functions, types, exceptions, and other objects.\n\
3393
\n\
3394
This module provides direct access to all 'built-in'\n\
3395
identifiers of Python; for example, builtins.len is\n\
3396
the full name for the built-in function len().\n\
3397
\n\
3398
This module is not normally accessed explicitly by most\n\
3399
applications, but can be useful in modules that provide\n\
3400
objects with the same name as a built-in value, but in\n\
3401
which the built-in of that name is also needed.");
3402
3403
static struct PyModuleDef builtinsmodule = {
3404
    PyModuleDef_HEAD_INIT,
3405
    "builtins",
3406
    builtin_doc,
3407
    -1, /* multiple "initialization" just copies the module dict. */
3408
    builtin_methods,
3409
    NULL,
3410
    NULL,
3411
    NULL,
3412
    NULL
3413
};
3414
3415
3416
PyObject *
3417
_PyBuiltin_Init(PyInterpreterState *interp)
3418
16
{
3419
16
    PyObject *mod, *dict, *debug;
3420
3421
16
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3422
3423
16
    mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
3424
16
    if (mod == NULL)
3425
0
        return NULL;
3426
#ifdef Py_GIL_DISABLED
3427
    PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
3428
#endif
3429
16
    dict = PyModule_GetDict(mod);
3430
3431
#ifdef Py_TRACE_REFS
3432
    /* "builtins" exposes a number of statically allocated objects
3433
     * that, before this code was added in 2.3, never showed up in
3434
     * the list of "all objects" maintained by Py_TRACE_REFS.  As a
3435
     * result, programs leaking references to None and False (etc)
3436
     * couldn't be diagnosed by examining sys.getobjects(0).
3437
     */
3438
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT))
3439
#else
3440
496
#define ADD_TO_ALL(OBJECT) (void)0
3441
16
#endif
3442
3443
16
#define SETBUILTIN(NAME, OBJECT) \
3444
496
    if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0)       \
3445
496
        return NULL;                                                    \
3446
496
    ADD_TO_ALL(OBJECT)
3447
3448
16
    SETBUILTIN("None",                  Py_None);
3449
16
    SETBUILTIN("Ellipsis",              Py_Ellipsis);
3450
16
    SETBUILTIN("NotImplemented",        Py_NotImplemented);
3451
16
    SETBUILTIN("False",                 Py_False);
3452
16
    SETBUILTIN("True",                  Py_True);
3453
16
    SETBUILTIN("bool",                  &PyBool_Type);
3454
16
    SETBUILTIN("memoryview",            &PyMemoryView_Type);
3455
16
    SETBUILTIN("bytearray",             &PyByteArray_Type);
3456
16
    SETBUILTIN("bytes",                 &PyBytes_Type);
3457
16
    SETBUILTIN("classmethod",           &PyClassMethod_Type);
3458
16
    SETBUILTIN("complex",               &PyComplex_Type);
3459
16
    SETBUILTIN("dict",                  &PyDict_Type);
3460
16
    SETBUILTIN("enumerate",             &PyEnum_Type);
3461
16
    SETBUILTIN("filter",                &PyFilter_Type);
3462
16
    SETBUILTIN("float",                 &PyFloat_Type);
3463
16
    SETBUILTIN("frozenset",             &PyFrozenSet_Type);
3464
16
    SETBUILTIN("property",              &PyProperty_Type);
3465
16
    SETBUILTIN("int",                   &PyLong_Type);
3466
16
    SETBUILTIN("list",                  &PyList_Type);
3467
16
    SETBUILTIN("map",                   &PyMap_Type);
3468
16
    SETBUILTIN("object",                &PyBaseObject_Type);
3469
16
    SETBUILTIN("range",                 &PyRange_Type);
3470
16
    SETBUILTIN("reversed",              &PyReversed_Type);
3471
16
    SETBUILTIN("set",                   &PySet_Type);
3472
16
    SETBUILTIN("slice",                 &PySlice_Type);
3473
16
    SETBUILTIN("staticmethod",          &PyStaticMethod_Type);
3474
16
    SETBUILTIN("str",                   &PyUnicode_Type);
3475
16
    SETBUILTIN("super",                 &PySuper_Type);
3476
16
    SETBUILTIN("tuple",                 &PyTuple_Type);
3477
16
    SETBUILTIN("type",                  &PyType_Type);
3478
16
    SETBUILTIN("zip",                   &PyZip_Type);
3479
16
    debug = PyBool_FromLong(config->optimization_level == 0);
3480
16
    if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3481
0
        Py_DECREF(debug);
3482
0
        return NULL;
3483
0
    }
3484
16
    Py_DECREF(debug);
3485
3486
16
    return mod;
3487
16
#undef ADD_TO_ALL
3488
16
#undef SETBUILTIN
3489
16
}