Coverage Report

Created: 2025-10-12 06:40

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