Coverage Report

Created: 2026-02-26 06:53

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