Coverage Report

Created: 2026-06-09 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
2.20k
{
31
2.20k
    Py_ssize_t i, j;
32
2.20k
    PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
33
2.20k
    assert(PyTuple_Check(bases));
34
35
4.01k
    for (i = 0; i < nargs; i++) {
36
1.80k
        base  = args[i];
37
1.80k
        if (PyType_Check(base)) {
38
1.80k
            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
1.80k
            continue;
46
1.80k
        }
47
0
        if (PyObject_GetOptionalAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
48
0
            goto error;
49
0
        }
50
0
        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
0
        new_base = PyObject_CallOneArg(meth, bases);
59
0
        Py_DECREF(meth);
60
0
        if (!new_base) {
61
0
            goto error;
62
0
        }
63
0
        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
0
        if (!new_bases) {
70
            /* If this is a first successful replacement, create new_bases list and
71
               copy previously encountered bases. */
72
0
            if (!(new_bases = PyList_New(i))) {
73
0
                Py_DECREF(new_base);
74
0
                goto error;
75
0
            }
76
0
            for (j = 0; j < i; j++) {
77
0
                base = args[j];
78
0
                PyList_SET_ITEM(new_bases, j, Py_NewRef(base));
79
0
            }
80
0
        }
81
0
        j = PyList_GET_SIZE(new_bases);
82
0
        if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
83
0
            Py_DECREF(new_base);
84
0
            goto error;
85
0
        }
86
0
        Py_DECREF(new_base);
87
0
    }
88
2.20k
    if (!new_bases) {
89
2.20k
        return bases;
90
2.20k
    }
91
0
    result = PyList_AsTuple(new_bases);
92
0
    Py_DECREF(new_bases);
93
0
    return result;
94
95
0
error:
96
0
    Py_XDECREF(new_bases);
97
0
    return NULL;
98
2.20k
}
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
2.20k
{
105
2.20k
    PyObject *func, *name, *winner, *prep;
106
2.20k
    PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
107
2.20k
    PyObject *mkw = NULL, *bases = NULL;
108
2.20k
    int isclass = 0;   /* initialize to prevent gcc warning */
109
110
2.20k
    if (nargs < 2) {
111
0
        PyErr_SetString(PyExc_TypeError,
112
0
                        "__build_class__: not enough arguments");
113
0
        return NULL;
114
0
    }
115
2.20k
    func = args[0];   /* Better be callable */
116
2.20k
    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
2.20k
    name = args[1];
122
2.20k
    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
2.20k
    orig_bases = PyTuple_FromArray(args + 2, nargs - 2);
128
2.20k
    if (orig_bases == NULL)
129
0
        return NULL;
130
131
2.20k
    bases = update_bases(orig_bases, args + 2, nargs - 2);
132
2.20k
    if (bases == NULL) {
133
0
        Py_DECREF(orig_bases);
134
0
        return NULL;
135
0
    }
136
137
2.20k
    if (kwnames == NULL) {
138
1.99k
        meta = NULL;
139
1.99k
        mkw = NULL;
140
1.99k
    }
141
217
    else {
142
217
        mkw = _PyStack_AsDict(args + nargs, kwnames);
143
217
        if (mkw == NULL) {
144
0
            goto error;
145
0
        }
146
147
217
        if (PyDict_Pop(mkw, &_Py_ID(metaclass), &meta) < 0) {
148
0
            goto error;
149
0
        }
150
217
        if (meta != NULL) {
151
            /* metaclass is explicitly given, check if it's indeed a class */
152
207
            isclass = PyType_Check(meta);
153
207
        }
154
217
    }
155
2.20k
    if (meta == NULL) {
156
        /* if there are no bases, use type: */
157
2.00k
        if (PyTuple_GET_SIZE(bases) == 0) {
158
585
            meta = (PyObject *) (&PyType_Type);
159
585
        }
160
        /* else get the type of the first base */
161
1.41k
        else {
162
1.41k
            PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
163
1.41k
            meta = (PyObject *)Py_TYPE(base0);
164
1.41k
        }
165
2.00k
        Py_INCREF(meta);
166
2.00k
        isclass = 1;  /* meta is really a class */
167
2.00k
    }
168
169
2.20k
    if (isclass) {
170
        /* meta is really a class, so check for a more derived
171
           metaclass, or possible metaclass conflicts: */
172
2.20k
        winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
173
2.20k
                                                        bases);
174
2.20k
        if (winner == NULL) {
175
0
            goto error;
176
0
        }
177
2.20k
        if (winner != meta) {
178
24
            Py_SETREF(meta, Py_NewRef(winner));
179
24
        }
180
2.20k
    }
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
2.20k
    if (PyObject_GetOptionalAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
184
0
        ns = NULL;
185
0
    }
186
2.20k
    else if (prep == NULL) {
187
0
        ns = PyDict_New();
188
0
    }
189
2.20k
    else {
190
2.20k
        PyObject *pargs[2] = {name, bases};
191
2.20k
        ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
192
2.20k
        Py_DECREF(prep);
193
2.20k
    }
194
2.20k
    if (ns == NULL) {
195
0
        goto error;
196
0
    }
197
2.20k
    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
2.20k
    PyThreadState *tstate = _PyThreadState_GET();
205
2.20k
    EVAL_CALL_STAT_INC(EVAL_CALL_BUILD_CLASS);
206
2.20k
    cell = _PyEval_Vector(tstate, (PyFunctionObject *)func, ns, NULL, 0, NULL);
207
2.20k
    if (cell != NULL) {
208
2.20k
        if (bases != orig_bases) {
209
0
            if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
210
0
                goto error;
211
0
            }
212
0
        }
213
2.20k
        PyObject *margs[3] = {name, bases, ns};
214
2.20k
        cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
215
2.20k
        if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
216
160
            PyObject *cell_cls = PyCell_GetRef((PyCellObject *)cell);
217
160
            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
160
            else {
233
160
                Py_DECREF(cell_cls);
234
160
            }
235
160
        }
236
2.20k
    }
237
2.20k
error:
238
2.20k
    Py_XDECREF(cell);
239
2.20k
    Py_XDECREF(ns);
240
2.20k
    Py_XDECREF(meta);
241
2.20k
    Py_XDECREF(mkw);
242
2.20k
    if (bases != orig_bases) {
243
0
        Py_DECREF(orig_bases);
244
0
    }
245
2.20k
    Py_DECREF(bases);
246
2.20k
    return cls;
247
2.20k
}
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
50.3k
{
286
50.3k
    return PyImport_ImportModuleLevelObject(name, globals, locals,
287
50.3k
                                            fromlist, level);
288
50.3k
}
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
9
{
365
9
    return PyNumber_Absolute(number);
366
9
}
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
0
{
383
0
    PyObject *it, *item;
384
0
    PyObject *(*iternext)(PyObject *);
385
0
    int cmp;
386
387
0
    it = PyObject_GetIter(iterable);
388
0
    if (it == NULL)
389
0
        return NULL;
390
0
    iternext = *Py_TYPE(it)->tp_iternext;
391
392
0
    for (;;) {
393
0
        item = iternext(it);
394
0
        if (item == NULL)
395
0
            break;
396
0
        cmp = PyObject_IsTrue(item);
397
0
        Py_DECREF(item);
398
0
        if (cmp < 0) {
399
0
            Py_DECREF(it);
400
0
            return NULL;
401
0
        }
402
0
        if (cmp == 0) {
403
0
            Py_DECREF(it);
404
0
            Py_RETURN_FALSE;
405
0
        }
406
0
    }
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
1.15k
{
432
1.15k
    PyObject *it, *item;
433
1.15k
    PyObject *(*iternext)(PyObject *);
434
1.15k
    int cmp;
435
436
1.15k
    it = PyObject_GetIter(iterable);
437
1.15k
    if (it == NULL)
438
0
        return NULL;
439
1.15k
    iternext = *Py_TYPE(it)->tp_iternext;
440
441
88.8k
    for (;;) {
442
88.8k
        item = iternext(it);
443
88.8k
        if (item == NULL)
444
1.12k
            break;
445
87.7k
        cmp = PyObject_IsTrue(item);
446
87.7k
        Py_DECREF(item);
447
87.7k
        if (cmp < 0) {
448
0
            Py_DECREF(it);
449
0
            return NULL;
450
0
        }
451
87.7k
        if (cmp > 0) {
452
32
            Py_DECREF(it);
453
32
            Py_RETURN_TRUE;
454
32
        }
455
87.7k
    }
456
1.12k
    Py_DECREF(it);
457
1.12k
    if (PyErr_Occurred()) {
458
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
459
0
            PyErr_Clear();
460
0
        else
461
0
            return NULL;
462
0
    }
463
1.12k
    Py_RETURN_FALSE;
464
1.12k
}
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
32
{
524
32
    return PyBool_FromLong((long)PyCallable_Check(obj));
525
32
}
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
0
#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
0
{
598
0
    PyTypeObject *tp = _PyType_CAST(type);
599
0
    if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
600
0
        return NULL;
601
0
    }
602
603
0
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
604
0
    if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
605
0
        return NULL;
606
0
    }
607
608
0
    PyObject *it = PyObject_GetIter(args[1]);
609
0
    if (it == NULL) {
610
0
        return NULL;
611
0
    }
612
613
0
    filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
614
615
0
    if (lz == NULL) {
616
0
        Py_DECREF(it);
617
0
        return NULL;
618
0
    }
619
620
0
    lz->func = Py_NewRef(args[0]);
621
0
    lz->it = it;
622
623
0
    return (PyObject *)lz;
624
0
}
625
626
static void
627
filter_dealloc(PyObject *self)
628
0
{
629
0
    filterobject *lz = _filterobject_CAST(self);
630
0
    PyObject_GC_UnTrack(lz);
631
0
    Py_XDECREF(lz->func);
632
0
    Py_XDECREF(lz->it);
633
0
    Py_TYPE(lz)->tp_free(lz);
634
0
}
635
636
static int
637
filter_traverse(PyObject *self, visitproc visit, void *arg)
638
0
{
639
0
    filterobject *lz = _filterobject_CAST(self);
640
0
    Py_VISIT(lz->it);
641
0
    Py_VISIT(lz->func);
642
0
    return 0;
643
0
}
644
645
static PyObject *
646
filter_next(PyObject *self)
647
0
{
648
0
    filterobject *lz = _filterobject_CAST(self);
649
0
    PyObject *item;
650
0
    PyObject *it = lz->it;
651
0
    long ok;
652
0
    PyObject *(*iternext)(PyObject *);
653
0
    int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
654
655
0
    iternext = *Py_TYPE(it)->tp_iternext;
656
0
    for (;;) {
657
0
        item = iternext(it);
658
0
        if (item == NULL)
659
0
            return NULL;
660
661
0
        if (checktrue) {
662
0
            ok = PyObject_IsTrue(item);
663
0
        } else {
664
0
            PyObject *good;
665
0
            good = PyObject_CallOneArg(lz->func, item);
666
0
            if (good == NULL) {
667
0
                Py_DECREF(item);
668
0
                return NULL;
669
0
            }
670
0
            ok = PyObject_IsTrue(good);
671
0
            Py_DECREF(good);
672
0
        }
673
0
        if (ok > 0)
674
0
            return item;
675
0
        Py_DECREF(item);
676
0
        if (ok < 0)
677
0
            return NULL;
678
0
    }
679
0
}
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
51.5k
{
787
51.5k
    int overflow;
788
51.5k
    long v = PyLong_AsLongAndOverflow(i, &overflow);
789
51.5k
    if (v == -1 && PyErr_Occurred()) {
790
0
        return NULL;
791
0
    }
792
51.5k
    if (overflow) {
793
0
        v = overflow < 0 ? INT_MIN : INT_MAX;
794
        /* Allow PyUnicode_FromOrdinal() to raise an exception */
795
0
    }
796
51.5k
#if SIZEOF_INT < SIZEOF_LONG
797
51.5k
    else if (v < INT_MIN) {
798
0
        v = INT_MIN;
799
0
    }
800
51.5k
    else if (v > INT_MAX) {
801
0
        v = INT_MAX;
802
0
    }
803
51.5k
#endif
804
51.5k
    return PyUnicode_FromOrdinal(v);
805
51.5k
}
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
20
{
843
20
    PyObject *source_copy;
844
20
    const char *str;
845
20
    int compile_mode = -1;
846
20
    int is_ast;
847
20
    int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
848
20
    PyObject *result;
849
850
20
    PyCompilerFlags cf = _PyCompilerFlags_INIT;
851
20
    cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
852
20
    if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
853
0
        cf.cf_feature_version = feature_version;
854
0
    }
855
856
20
    if (flags &
857
20
        ~(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
20
    if (optimize < -1 || optimize > 2) {
866
0
        PyErr_SetString(PyExc_ValueError,
867
0
                        "compile(): invalid optimize value");
868
0
        goto error;
869
0
    }
870
20
    if (modname == Py_None) {
871
20
        modname = NULL;
872
20
    }
873
0
    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
20
    if (!dont_inherit) {
881
20
        PyEval_MergeCompilerFlags(&cf);
882
20
    }
883
884
20
    if (strcmp(mode, "exec") == 0)
885
0
        compile_mode = 0;
886
20
    else if (strcmp(mode, "eval") == 0)
887
20
        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
20
    is_ast = PyAST_Check(source);
909
20
    if (is_ast == -1)
910
0
        goto error;
911
20
    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
20
    str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
946
20
    if (str == NULL)
947
0
        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
20
    result = _Py_CompileStringObjectWithModule(str, filename,
958
20
                                               start[compile_mode], &cf,
959
20
                                               optimize, modname);
960
961
#ifdef Py_GIL_DISABLED
962
    tstate->suppress_co_const_immortalization--;
963
#endif
964
965
20
    Py_XDECREF(source_copy);
966
20
    goto finally;
967
968
0
error:
969
0
    result = NULL;
970
20
finally:
971
20
    return result;
972
0
}
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
19
{
978
19
    PyObject *arg = NULL;
979
980
19
    if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
981
0
        return NULL;
982
19
    return PyObject_Dir(arg);
983
19
}
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
0
{
1013
0
    return PyNumber_Divmod(x, y);
1014
0
}
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
10
{
1039
10
    PyThreadState *tstate = _PyThreadState_GET();
1040
10
    PyObject *result = NULL, *source_copy;
1041
10
    const char *str;
1042
1043
10
    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
10
    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
10
    int fromframe = 0;
1056
10
    if (globals != Py_None) {
1057
10
        Py_INCREF(globals);
1058
10
    }
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
10
    if (locals != Py_None) {
1079
0
        Py_INCREF(locals);
1080
0
    }
1081
10
    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
10
    else {
1090
10
        locals = Py_NewRef(globals);
1091
10
    }
1092
1093
10
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1094
0
        goto error;
1095
0
    }
1096
1097
10
    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
10
    else {
1110
10
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1111
10
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1112
10
        str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
1113
10
        if (str == NULL)
1114
0
            goto error;
1115
1116
10
        while (*str == ' ' || *str == '\t')
1117
0
            str++;
1118
1119
10
        (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
10
        result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1127
#ifdef Py_GIL_DISABLED
1128
        tstate->suppress_co_const_immortalization--;
1129
#endif
1130
10
        Py_XDECREF(source_copy);
1131
10
    }
1132
1133
10
  error:
1134
10
    Py_XDECREF(globals);
1135
10
    Py_XDECREF(locals);
1136
10
    return result;
1137
10
}
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
421
{
1165
421
    PyThreadState *tstate = _PyThreadState_GET();
1166
421
    PyObject *v;
1167
1168
421
    int fromframe = 0;
1169
421
    if (globals != Py_None) {
1170
421
        Py_INCREF(globals);
1171
421
    }
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
421
    if (locals != Py_None) {
1191
0
        Py_INCREF(locals);
1192
0
    }
1193
421
    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
421
    else {
1202
421
        locals = Py_NewRef(globals);
1203
421
    }
1204
1205
421
    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
421
    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
421
    if (_PyEval_EnsureBuiltins(tstate, globals, NULL) < 0) {
1219
0
        goto error;
1220
0
    }
1221
1222
421
    if (closure == Py_None) {
1223
0
        closure = NULL;
1224
0
    }
1225
1226
421
    if (PyCode_Check(source)) {
1227
421
        Py_ssize_t num_free = PyCode_GetNumFree((PyCodeObject *)source);
1228
421
        if (num_free == 0) {
1229
421
            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
421
        } 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
421
        if (PySys_Audit("exec", "O", source) < 0) {
1257
0
            goto error;
1258
0
        }
1259
1260
421
        if (!closure) {
1261
421
            v = PyEval_EvalCode(source, globals, locals);
1262
421
        } 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
421
    }
1271
0
    else {
1272
0
        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
0
        PyObject *source_copy;
1278
0
        const char *str;
1279
0
        PyCompilerFlags cf = _PyCompilerFlags_INIT;
1280
0
        cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1281
0
        str = _Py_SourceAsString(source, "exec",
1282
0
                                       "string, bytes or code", &cf,
1283
0
                                       &source_copy);
1284
0
        if (str == NULL)
1285
0
            goto error;
1286
0
        if (PyEval_MergeCompilerFlags(&cf))
1287
0
            v = PyRun_StringFlags(str, Py_file_input, globals,
1288
0
                                  locals, &cf);
1289
0
        else
1290
0
            v = PyRun_String(str, Py_file_input, globals, locals);
1291
0
        Py_XDECREF(source_copy);
1292
0
    }
1293
421
    if (v == NULL)
1294
0
        goto error;
1295
421
    Py_DECREF(globals);
1296
421
    Py_DECREF(locals);
1297
421
    Py_DECREF(v);
1298
421
    Py_RETURN_NONE;
1299
1300
0
  error:
1301
0
    Py_XDECREF(globals);
1302
0
    Py_XDECREF(locals);
1303
0
    return NULL;
1304
421
}
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
7.95k
{
1311
7.95k
    PyObject *v, *name, *result;
1312
1313
7.95k
    if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
1314
0
        return NULL;
1315
1316
7.95k
    v = args[0];
1317
7.95k
    name = args[1];
1318
7.95k
    if (nargs > 2) {
1319
6.64k
        if (PyObject_GetOptionalAttr(v, name, &result) == 0) {
1320
1.04k
            PyObject *dflt = args[2];
1321
1.04k
            return Py_NewRef(dflt);
1322
1.04k
        }
1323
6.64k
    }
1324
1.30k
    else {
1325
1.30k
        result = PyObject_GetAttr(v, name);
1326
1.30k
    }
1327
6.91k
    return result;
1328
7.95k
}
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
378
{
1353
378
    PyObject *globals;
1354
378
    if (_PyEval_GetFrame() != NULL) {
1355
378
        globals = PyEval_GetGlobals();
1356
378
        assert(globals != NULL);
1357
378
        return Py_NewRef(globals);
1358
378
    }
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
2.22k
{
1387
2.22k
    PyObject *v;
1388
1389
2.22k
    if (PyObject_GetOptionalAttr(obj, name, &v) < 0) {
1390
0
        return NULL;
1391
0
    }
1392
2.22k
    if (v == NULL) {
1393
422
        Py_RETURN_FALSE;
1394
422
    }
1395
1.80k
    Py_DECREF(v);
1396
1.80k
    Py_RETURN_TRUE;
1397
2.22k
}
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
0
{
1421
0
    PyObject *id = PyLong_FromVoidPtr(v);
1422
1423
0
    if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1424
0
        Py_DECREF(id);
1425
0
        return NULL;
1426
0
    }
1427
1428
0
    return id;
1429
0
}
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
220
#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
23
{
1504
23
    PyTypeObject *tp = _PyType_CAST(type);
1505
1506
23
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1507
23
    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
23
    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
23
    PyObject *iters = PyTuple_New(nargs-1);
1520
23
    if (iters == NULL) {
1521
0
        return NULL;
1522
0
    }
1523
1524
46
    for (int i=1; i<nargs; i++) {
1525
23
        PyObject *it = PyObject_GetIter(args[i]);
1526
23
        if (it == NULL) {
1527
0
            Py_DECREF(iters);
1528
0
            return NULL;
1529
0
        }
1530
23
        PyTuple_SET_ITEM(iters, i-1, it);
1531
23
    }
1532
1533
23
    mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1534
23
    if (lz == NULL) {
1535
0
        Py_DECREF(iters);
1536
0
        return NULL;
1537
0
    }
1538
23
    lz->iters = iters;
1539
23
    lz->func = Py_NewRef(args[0]);
1540
23
    lz->strict = 0;
1541
1542
23
    return (PyObject *)lz;
1543
23
}
1544
1545
static void
1546
map_dealloc(PyObject *self)
1547
23
{
1548
23
    mapobject *lz = _mapobject_CAST(self);
1549
23
    PyObject_GC_UnTrack(lz);
1550
23
    Py_XDECREF(lz->iters);
1551
23
    Py_XDECREF(lz->func);
1552
23
    Py_TYPE(lz)->tp_free(lz);
1553
23
}
1554
1555
static int
1556
map_traverse(PyObject *self, visitproc visit, void *arg)
1557
0
{
1558
0
    mapobject *lz = _mapobject_CAST(self);
1559
0
    Py_VISIT(lz->iters);
1560
0
    Py_VISIT(lz->func);
1561
0
    return 0;
1562
0
}
1563
1564
static PyObject *
1565
map_next(PyObject *self)
1566
197
{
1567
197
    mapobject *lz = _mapobject_CAST(self);
1568
197
    Py_ssize_t i;
1569
197
    PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1570
197
    PyObject **stack;
1571
197
    PyObject *result = NULL;
1572
197
    PyThreadState *tstate = _PyThreadState_GET();
1573
1574
197
    const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
1575
197
    if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1576
197
        stack = small_stack;
1577
197
    }
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
197
    Py_ssize_t nargs = 0;
1587
372
    for (i = 0; i < niters; i++) {
1588
197
        PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1589
197
        PyObject *val = Py_TYPE(it)->tp_iternext(it);
1590
197
        if (val == NULL) {
1591
22
            if (lz->strict) {
1592
0
                goto check;
1593
0
            }
1594
22
            goto exit_no_result;
1595
22
        }
1596
175
        stack[i] = val;
1597
175
        nargs++;
1598
175
    }
1599
1600
175
    result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
1601
175
    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
22
exit_no_result:
1643
22
    assert(result == NULL);
1644
1645
197
exit:
1646
372
    for (i = 0; i < nargs; i++) {
1647
175
        Py_DECREF(stack[i]);
1648
175
    }
1649
197
    if (stack != small_stack) {
1650
0
        PyMem_Free(stack);
1651
0
    }
1652
197
    return result;
1653
22
}
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
19
{
1757
19
    PyObject *it, *res;
1758
1759
19
    if (!_PyArg_CheckPositional("next", nargs, 1, 2))
1760
0
        return NULL;
1761
1762
19
    it = args[0];
1763
19
    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
19
    res = (*Py_TYPE(it)->tp_iternext)(it);
1771
19
    if (res != NULL) {
1772
0
        return res;
1773
19
    } else if (nargs > 1) {
1774
19
        PyObject *def = args[1];
1775
19
        if (PyErr_Occurred()) {
1776
0
            if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1777
0
                return NULL;
1778
0
            PyErr_Clear();
1779
0
        }
1780
19
        return Py_NewRef(def);
1781
19
    } else if (PyErr_Occurred()) {
1782
0
        return NULL;
1783
0
    } else {
1784
0
        PyErr_SetNone(PyExc_StopIteration);
1785
0
        return NULL;
1786
0
    }
1787
19
}
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.14k
{
1814
1.14k
    if (PyObject_SetAttr(obj, name, value) != 0)
1815
0
        return NULL;
1816
1.14k
    Py_RETURN_NONE;
1817
1.14k
}
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
180
{
1836
180
    if (PyObject_DelAttr(obj, name) < 0) {
1837
0
        return NULL;
1838
0
    }
1839
180
    Py_RETURN_NONE;
1840
180
}
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
0
{
1861
0
    Py_hash_t x;
1862
1863
0
    x = PyObject_Hash(obj);
1864
0
    if (x == -1)
1865
0
        return NULL;
1866
0
    return PyLong_FromSsize_t(x);
1867
0
}
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
0
{
1886
0
    return PyNumber_ToBase(integer, 16);
1887
0
}
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
247
{
1894
247
    PyObject *v;
1895
1896
247
    if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
1897
0
        return NULL;
1898
247
    v = args[0];
1899
247
    if (nargs == 1)
1900
247
        return PyObject_GetIter(v);
1901
0
    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
0
    PyObject *sentinel = args[1];
1907
0
    return PyCallIter_New(v, sentinel);
1908
0
}
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
435
{
1995
435
    Py_ssize_t res;
1996
1997
435
    res = PyObject_Size(obj);
1998
435
    if (res < 0) {
1999
0
        assert(PyErr_Occurred());
2000
0
        return NULL;
2001
0
    }
2002
435
    return PyLong_FromSsize_t(res);
2003
435
}
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
0
{
2021
0
    PyObject *locals;
2022
0
    if (_PyEval_GetFrame() != NULL) {
2023
0
        locals = _PyEval_GetFrameLocals();
2024
0
        assert(locals != NULL || PyErr_Occurred());
2025
0
        return locals;
2026
0
    }
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
44.0k
{
2042
44.0k
    PyObject *it = NULL, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
2043
44.0k
    PyObject *defaultval = NULL;
2044
44.0k
    static const char * const keywords[] = {"key", "default", NULL};
2045
44.0k
    static _PyArg_Parser _parser_min = {"|$OO:min", keywords, 0};
2046
44.0k
    static _PyArg_Parser _parser_max = {"|$OO:max", keywords, 0};
2047
44.0k
    const char *name = (op == Py_LT) ? "min" : "max";
2048
44.0k
    _PyArg_Parser *_parser = (op == Py_LT) ? &_parser_min : &_parser_max;
2049
2050
44.0k
    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
44.0k
    if (kwnames != NULL && !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, _parser,
2056
0
                                                         &keyfunc, &defaultval)) {
2057
0
        return NULL;
2058
0
    }
2059
2060
44.0k
    const int positional = nargs > 1; // False iff nargs == 1
2061
44.0k
    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
44.0k
    if (!positional) {
2069
43.5k
        it = PyObject_GetIter(args[0]);
2070
43.5k
        if (it == NULL) {
2071
0
            return NULL;
2072
0
        }
2073
43.5k
    }
2074
2075
44.0k
    if (keyfunc == Py_None) {
2076
0
        keyfunc = NULL;
2077
0
    }
2078
2079
44.0k
    maxitem = NULL; /* the result */
2080
44.0k
    maxval = NULL;  /* the value associated with the result */
2081
122k
    while (1) {
2082
122k
        if (it == NULL) {
2083
1.70k
            if (nargs-- <= 0) {
2084
568
                break;
2085
568
            }
2086
1.13k
            item = *args++;
2087
1.13k
            Py_INCREF(item);
2088
1.13k
        }
2089
121k
        else {
2090
121k
            item = PyIter_Next(it);
2091
121k
            if (item == NULL) {
2092
43.5k
                if (PyErr_Occurred()) {
2093
0
                    goto Fail_it;
2094
0
                }
2095
43.5k
                break;
2096
43.5k
            }
2097
121k
        }
2098
2099
        /* get the value from the key function */
2100
78.7k
        if (keyfunc != NULL) {
2101
0
            val = PyObject_CallOneArg(keyfunc, item);
2102
0
            if (val == NULL)
2103
0
                goto Fail_it_item;
2104
0
        }
2105
        /* no key function; the value is the item */
2106
78.7k
        else {
2107
78.7k
            val = Py_NewRef(item);
2108
78.7k
        }
2109
2110
        /* maximum value and item are unset; set them */
2111
78.7k
        if (maxval == NULL) {
2112
44.0k
            maxitem = item;
2113
44.0k
            maxval = val;
2114
44.0k
        }
2115
        /* maximum value and item are set; update them as necessary */
2116
34.6k
        else {
2117
34.6k
            int cmp = PyObject_RichCompareBool(val, maxval, op);
2118
34.6k
            if (cmp < 0)
2119
0
                goto Fail_it_item_and_val;
2120
34.6k
            else if (cmp > 0) {
2121
16.3k
                Py_DECREF(maxval);
2122
16.3k
                Py_DECREF(maxitem);
2123
16.3k
                maxval = val;
2124
16.3k
                maxitem = item;
2125
16.3k
            }
2126
18.2k
            else {
2127
18.2k
                Py_DECREF(item);
2128
18.2k
                Py_DECREF(val);
2129
18.2k
            }
2130
34.6k
        }
2131
78.7k
    }
2132
44.0k
    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
44.0k
    else
2142
44.0k
        Py_DECREF(maxval);
2143
44.0k
    Py_XDECREF(it);
2144
44.0k
    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
549
{
2161
549
    return min_max(args, nargs, kwnames, Py_LT);
2162
549
}
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
43.5k
{
2178
43.5k
    return min_max(args, nargs, kwnames, Py_GT);
2179
43.5k
}
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
7.35M
{
2230
7.35M
    long ord;
2231
7.35M
    Py_ssize_t size;
2232
2233
7.35M
    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
7.35M
    else if (PyUnicode_Check(c)) {
2241
7.35M
        size = PyUnicode_GET_LENGTH(c);
2242
7.35M
        if (size == 1) {
2243
7.35M
            ord = (long)PyUnicode_READ_CHAR(c, 0);
2244
7.35M
            return PyLong_FromLong(ord);
2245
7.35M
        }
2246
7.35M
    }
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
7.35M
}
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
3
{
2289
3
    return PyNumber_Power(base, exp, mod);
2290
3
}
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
0
{
2671
0
    return PyObject_Repr(obj);
2672
0
}
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
18.7k
{
2741
18.7k
    PyObject *newlist, *v, *seq, *callable;
2742
2743
    /* Keyword arguments are passed through list.sort() which will check
2744
       them. */
2745
18.7k
    if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
2746
0
        return NULL;
2747
2748
18.7k
    newlist = PySequence_List(seq);
2749
18.7k
    if (newlist == NULL)
2750
0
        return NULL;
2751
2752
18.7k
    callable = PyObject_GetAttr(newlist, &_Py_ID(sort));
2753
18.7k
    if (callable == NULL) {
2754
0
        Py_DECREF(newlist);
2755
0
        return NULL;
2756
0
    }
2757
2758
18.7k
    assert(nargs >= 1);
2759
18.7k
    v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
2760
18.7k
    Py_DECREF(callable);
2761
18.7k
    if (v == NULL) {
2762
0
        Py_DECREF(newlist);
2763
0
        return NULL;
2764
0
    }
2765
18.7k
    Py_DECREF(v);
2766
18.7k
    return newlist;
2767
18.7k
}
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
22
{
2774
22
    PyObject *v = NULL;
2775
22
    PyObject *d;
2776
2777
22
    if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2778
0
        return NULL;
2779
22
    if (v == NULL) {
2780
3
        if (_PyEval_GetFrame() != NULL) {
2781
3
            d = _PyEval_GetFrameLocals();
2782
3
        }
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
3
    }
2797
19
    else {
2798
19
        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
19
    }
2803
22
    return d;
2804
22
}
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
0
{
2828
0
    return (CompensatedSum) {x};
2829
0
}
2830
2831
static inline CompensatedSum
2832
cs_add(CompensatedSum total, double x)
2833
0
{
2834
0
    double t = total.hi + x;
2835
0
    if (fabs(total.hi) >= fabs(x)) {
2836
0
        total.lo += (total.hi - t) + x;
2837
0
    }
2838
0
    else {
2839
0
        total.lo += (x - t) + total.hi;
2840
0
    }
2841
0
    return (CompensatedSum) {t, total.lo};
2842
0
}
2843
2844
static inline double
2845
cs_to_double(CompensatedSum total)
2846
0
{
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
0
    if (total.lo && isfinite(total.lo)) {
2851
0
        return total.hi + total.lo;
2852
0
    }
2853
0
    return total.hi;
2854
0
}
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
507
{
2875
507
    PyObject *result = start;
2876
507
    PyObject *temp, *item, *iter;
2877
2878
507
    iter = PyObject_GetIter(iterable);
2879
507
    if (iter == NULL)
2880
0
        return NULL;
2881
2882
507
    if (result == NULL) {
2883
507
        result = PyLong_FromLong(0);
2884
507
        if (result == NULL) {
2885
0
            Py_DECREF(iter);
2886
0
            return NULL;
2887
0
        }
2888
507
    } else {
2889
        /* reject string values for 'start' parameter */
2890
0
        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
0
        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
0
        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
0
        Py_INCREF(result);
2909
0
    }
2910
2911
507
#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
507
    if (PyLong_CheckExact(result)) {
2917
507
        int overflow;
2918
507
        Py_ssize_t i_result = PyLong_AsLongAndOverflow(result, &overflow);
2919
        /* If this already overflowed, don't even enter the loop. */
2920
507
        if (overflow == 0) {
2921
507
            Py_SETREF(result, NULL);
2922
507
        }
2923
4.93k
        while(result == NULL) {
2924
4.93k
            item = PyIter_Next(iter);
2925
4.93k
            if (item == NULL) {
2926
507
                Py_DECREF(iter);
2927
507
                if (PyErr_Occurred())
2928
0
                    return NULL;
2929
507
                return PyLong_FromSsize_t(i_result);
2930
507
            }
2931
4.42k
            if (PyLong_CheckExact(item) || PyBool_Check(item)) {
2932
4.42k
                Py_ssize_t b;
2933
4.42k
                overflow = 0;
2934
                /* Single digits are common, fast, and cannot overflow on unpacking. */
2935
4.42k
                if (_PyLong_IsCompact((PyLongObject *)item)) {
2936
4.42k
                    b = _PyLong_CompactValue((PyLongObject *)item);
2937
4.42k
                }
2938
0
                else {
2939
0
                    b = PyLong_AsLongAndOverflow(item, &overflow);
2940
0
                }
2941
4.42k
                if (overflow == 0 &&
2942
4.42k
                    (i_result >= 0 ? (b <= PY_SSIZE_T_MAX - i_result)
2943
4.42k
                                   : (b >= PY_SSIZE_T_MIN - i_result)))
2944
4.42k
                {
2945
4.42k
                    i_result += b;
2946
4.42k
                    Py_DECREF(item);
2947
4.42k
                    continue;
2948
4.42k
                }
2949
4.42k
            }
2950
            /* Either overflowed or is not an int. Restore real objects and process normally */
2951
0
            result = PyLong_FromSsize_t(i_result);
2952
0
            if (result == NULL) {
2953
0
                Py_DECREF(item);
2954
0
                Py_DECREF(iter);
2955
0
                return NULL;
2956
0
            }
2957
0
            temp = PyNumber_Add(result, item);
2958
0
            Py_DECREF(result);
2959
0
            Py_DECREF(item);
2960
0
            result = temp;
2961
0
            if (result == NULL) {
2962
0
                Py_DECREF(iter);
2963
0
                return NULL;
2964
0
            }
2965
0
        }
2966
507
    }
2967
2968
0
    if (PyFloat_CheckExact(result)) {
2969
0
        CompensatedSum re_sum = cs_from_double(PyFloat_AS_DOUBLE(result));
2970
0
        Py_SETREF(result, NULL);
2971
0
        while(result == NULL) {
2972
0
            item = PyIter_Next(iter);
2973
0
            if (item == NULL) {
2974
0
                Py_DECREF(iter);
2975
0
                if (PyErr_Occurred())
2976
0
                    return NULL;
2977
0
                return PyFloat_FromDouble(cs_to_double(re_sum));
2978
0
            }
2979
0
            if (PyFloat_CheckExact(item)) {
2980
0
                re_sum = cs_add(re_sum, PyFloat_AS_DOUBLE(item));
2981
0
                _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2982
0
                continue;
2983
0
            }
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
0
    }
3013
3014
0
    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
0
#endif
3073
3074
0
    for(;;) {
3075
0
        item = PyIter_Next(iter);
3076
0
        if (item == NULL) {
3077
            /* error, or end-of-sequence */
3078
0
            if (PyErr_Occurred()) {
3079
0
                Py_SETREF(result, NULL);
3080
0
            }
3081
0
            break;
3082
0
        }
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
0
        temp = PyNumber_Add(result, item);
3097
0
        Py_DECREF(result);
3098
0
        Py_DECREF(item);
3099
0
        result = temp;
3100
0
        if (result == NULL)
3101
0
            break;
3102
0
    }
3103
0
    Py_DECREF(iter);
3104
0
    return result;
3105
0
}
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
414
{
3128
414
    int retval;
3129
3130
414
    retval = PyObject_IsInstance(obj, class_or_tuple);
3131
414
    if (retval < 0)
3132
0
        return NULL;
3133
414
    return PyBool_FromLong(retval);
3134
414
}
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
50
{
3156
50
    int retval;
3157
3158
50
    retval = PyObject_IsSubclass(cls, class_or_tuple);
3159
50
    if (retval < 0)
3160
0
        return NULL;
3161
50
    return PyBool_FromLong(retval);
3162
50
}
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
119
#define _zipobject_CAST(op)     ((zipobject *)(op))
3173
3174
static PyObject *
3175
zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3176
24
{
3177
24
    zipobject *lz;
3178
24
    Py_ssize_t i;
3179
24
    PyObject *ittuple;  /* tuple of iterators */
3180
24
    PyObject *result;
3181
24
    Py_ssize_t tuplesize;
3182
24
    int strict = 0;
3183
3184
24
    if (kwds) {
3185
0
        PyObject *empty = PyTuple_New(0);
3186
0
        if (empty == NULL) {
3187
0
            return NULL;
3188
0
        }
3189
0
        static char *kwlist[] = {"strict", NULL};
3190
0
        int parsed = PyArg_ParseTupleAndKeywords(
3191
0
                empty, kwds, "|$p:zip", kwlist, &strict);
3192
0
        Py_DECREF(empty);
3193
0
        if (!parsed) {
3194
0
            return NULL;
3195
0
        }
3196
0
    }
3197
3198
    /* args must be a tuple */
3199
24
    assert(PyTuple_Check(args));
3200
24
    tuplesize = PyTuple_GET_SIZE(args);
3201
3202
    /* obtain iterators */
3203
24
    ittuple = PyTuple_New(tuplesize);
3204
24
    if (ittuple == NULL)
3205
0
        return NULL;
3206
34
    for (i=0; i < tuplesize; ++i) {
3207
10
        PyObject *item = PyTuple_GET_ITEM(args, i);
3208
0
        PyObject *it = PyObject_GetIter(item);
3209
10
        if (it == NULL) {
3210
0
            Py_DECREF(ittuple);
3211
0
            return NULL;
3212
0
        }
3213
10
        PyTuple_SET_ITEM(ittuple, i, it);
3214
10
    }
3215
3216
    /* create a result holder */
3217
24
    result = PyTuple_New(tuplesize);
3218
24
    if (result == NULL) {
3219
0
        Py_DECREF(ittuple);
3220
0
        return NULL;
3221
0
    }
3222
34
    for (i=0 ; i < tuplesize ; i++) {
3223
10
        PyTuple_SET_ITEM(result, i, Py_NewRef(Py_None));
3224
10
    }
3225
3226
    /* create zipobject structure */
3227
24
    lz = (zipobject *)type->tp_alloc(type, 0);
3228
24
    if (lz == NULL) {
3229
0
        Py_DECREF(ittuple);
3230
0
        Py_DECREF(result);
3231
0
        return NULL;
3232
0
    }
3233
24
    lz->ittuple = ittuple;
3234
24
    lz->tuplesize = tuplesize;
3235
24
    lz->result = result;
3236
24
    lz->strict = strict;
3237
3238
24
    return (PyObject *)lz;
3239
24
}
3240
3241
static void
3242
zip_dealloc(PyObject *self)
3243
24
{
3244
24
    zipobject *lz = _zipobject_CAST(self);
3245
24
    PyObject_GC_UnTrack(lz);
3246
24
    Py_XDECREF(lz->ittuple);
3247
24
    Py_XDECREF(lz->result);
3248
24
    Py_TYPE(lz)->tp_free(lz);
3249
24
}
3250
3251
static int
3252
zip_traverse(PyObject *self, visitproc visit, void *arg)
3253
0
{
3254
0
    zipobject *lz = _zipobject_CAST(self);
3255
0
    Py_VISIT(lz->ittuple);
3256
0
    Py_VISIT(lz->result);
3257
0
    return 0;
3258
0
}
3259
3260
static PyObject *
3261
zip_next(PyObject *self)
3262
95
{
3263
95
    zipobject *lz = _zipobject_CAST(self);
3264
3265
95
    Py_ssize_t i;
3266
95
    Py_ssize_t tuplesize = lz->tuplesize;
3267
95
    PyObject *result = lz->result;
3268
95
    PyObject *it;
3269
95
    PyObject *item;
3270
95
    PyObject *olditem;
3271
3272
95
    if (tuplesize == 0)
3273
0
        return NULL;
3274
3275
95
    if (_PyObject_IsUniquelyReferenced(result)) {
3276
95
        Py_INCREF(result);
3277
275
        for (i=0 ; i < tuplesize ; i++) {
3278
185
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3279
185
            item = (*Py_TYPE(it)->tp_iternext)(it);
3280
185
            if (item == NULL) {
3281
5
                Py_DECREF(result);
3282
5
                if (lz->strict) {
3283
0
                    goto check;
3284
0
                }
3285
5
                return NULL;
3286
5
            }
3287
180
            olditem = PyTuple_GET_ITEM(result, i);
3288
180
            PyTuple_SET_ITEM(result, i, item);
3289
180
            Py_DECREF(olditem);
3290
180
        }
3291
        // bpo-42536: The GC may have untracked this result tuple. Since we're
3292
        // recycling it, make sure it's tracked again:
3293
90
        _PyTuple_Recycle(result);
3294
90
    } else {
3295
0
        result = PyTuple_New(tuplesize);
3296
0
        if (result == NULL)
3297
0
            return NULL;
3298
0
        for (i=0 ; i < tuplesize ; i++) {
3299
0
            it = PyTuple_GET_ITEM(lz->ittuple, i);
3300
0
            item = (*Py_TYPE(it)->tp_iternext)(it);
3301
0
            if (item == NULL) {
3302
0
                Py_DECREF(result);
3303
0
                if (lz->strict) {
3304
0
                    goto check;
3305
0
                }
3306
0
                return NULL;
3307
0
            }
3308
0
            PyTuple_SET_ITEM(result, i, item);
3309
0
        }
3310
0
    }
3311
90
    return result;
3312
0
check:
3313
0
    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
0
    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
0
    for (i = 1; i < tuplesize; i++) {
3329
0
        it = PyTuple_GET_ITEM(lz->ittuple, i);
3330
0
        item = (*Py_TYPE(it)->tp_iternext)(it);
3331
0
        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
0
        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
0
    }
3347
    // All arguments are exhausted. Success!
3348
0
    return NULL;
3349
0
}
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
19
{
3518
19
    PyObject *mod, *dict, *debug;
3519
3520
19
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3521
3522
19
    mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
3523
19
    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
19
    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
627
#define ADD_TO_ALL(OBJECT) (void)0
3540
19
#endif
3541
3542
19
#define SETBUILTIN(NAME, OBJECT) \
3543
627
    if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0)       \
3544
627
        return NULL;                                                    \
3545
627
    ADD_TO_ALL(OBJECT)
3546
3547
19
    SETBUILTIN("None",                  Py_None);
3548
19
    SETBUILTIN("Ellipsis",              Py_Ellipsis);
3549
19
    SETBUILTIN("NotImplemented",        Py_NotImplemented);
3550
19
    SETBUILTIN("False",                 Py_False);
3551
19
    SETBUILTIN("True",                  Py_True);
3552
19
    SETBUILTIN("bool",                  &PyBool_Type);
3553
19
    SETBUILTIN("memoryview",            &PyMemoryView_Type);
3554
19
    SETBUILTIN("bytearray",             &PyByteArray_Type);
3555
19
    SETBUILTIN("bytes",                 &PyBytes_Type);
3556
19
    SETBUILTIN("classmethod",           &PyClassMethod_Type);
3557
19
    SETBUILTIN("complex",               &PyComplex_Type);
3558
19
    SETBUILTIN("dict",                  &PyDict_Type);
3559
19
    SETBUILTIN("enumerate",             &PyEnum_Type);
3560
19
    SETBUILTIN("filter",                &PyFilter_Type);
3561
19
    SETBUILTIN("float",                 &PyFloat_Type);
3562
19
    SETBUILTIN("frozendict",            &PyFrozenDict_Type);
3563
19
    SETBUILTIN("frozenset",             &PyFrozenSet_Type);
3564
19
    SETBUILTIN("property",              &PyProperty_Type);
3565
19
    SETBUILTIN("int",                   &PyLong_Type);
3566
19
    SETBUILTIN("list",                  &PyList_Type);
3567
19
    SETBUILTIN("map",                   &PyMap_Type);
3568
19
    SETBUILTIN("object",                &PyBaseObject_Type);
3569
19
    SETBUILTIN("range",                 &PyRange_Type);
3570
19
    SETBUILTIN("reversed",              &PyReversed_Type);
3571
19
    SETBUILTIN("sentinel",              &PySentinel_Type);
3572
19
    SETBUILTIN("set",                   &PySet_Type);
3573
19
    SETBUILTIN("slice",                 &PySlice_Type);
3574
19
    SETBUILTIN("staticmethod",          &PyStaticMethod_Type);
3575
19
    SETBUILTIN("str",                   &PyUnicode_Type);
3576
19
    SETBUILTIN("super",                 &PySuper_Type);
3577
19
    SETBUILTIN("tuple",                 &PyTuple_Type);
3578
19
    SETBUILTIN("type",                  &PyType_Type);
3579
19
    SETBUILTIN("zip",                   &PyZip_Type);
3580
19
    debug = PyBool_FromLong(config->optimization_level == 0);
3581
19
    if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3582
0
        Py_DECREF(debug);
3583
0
        return NULL;
3584
0
    }
3585
19
    Py_DECREF(debug);
3586
3587
19
    return mod;
3588
19
#undef ADD_TO_ALL
3589
19
#undef SETBUILTIN
3590
19
}