Coverage Report

Created: 2025-08-26 06:26

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