Coverage Report

Created: 2026-03-08 06:40

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