Coverage Report

Created: 2026-05-16 06:46

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