Coverage Report

Created: 2026-06-09 06:53

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