ยปCore Development>Code coverage>Python/bltinmodule.c

Python code coverage for Python/bltinmodule.c

#countcontent
1n/a/* Built-in functions */
2n/a
3n/a#include "Python.h"
4n/a#include "Python-ast.h"
5n/a
6n/a#include "node.h"
7n/a#include "code.h"
8n/a
9n/a#include "asdl.h"
10n/a#include "ast.h"
11n/a
12n/a#include <ctype.h>
13n/a
14n/a#ifdef HAVE_LANGINFO_H
15n/a#include <langinfo.h> /* CODESET */
16n/a#endif
17n/a
18n/a/* The default encoding used by the platform file system APIs
19n/a Can remain NULL for all platforms that don't have such a concept
20n/a
21n/a Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22n/a values for Py_FileSystemDefaultEncoding!
23n/a*/
24n/a#if defined(__APPLE__)
25n/aconst char *Py_FileSystemDefaultEncoding = "utf-8";
26n/aint Py_HasFileSystemDefaultEncoding = 1;
27n/a#elif defined(MS_WINDOWS)
28n/a/* may be changed by initfsencoding(), but should never be free()d */
29n/aconst char *Py_FileSystemDefaultEncoding = "utf-8";
30n/aint Py_HasFileSystemDefaultEncoding = 1;
31n/a#else
32n/aconst char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
33n/aint Py_HasFileSystemDefaultEncoding = 0;
34n/a#endif
35n/aconst char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
36n/a
37n/a_Py_IDENTIFIER(__builtins__);
38n/a_Py_IDENTIFIER(__dict__);
39n/a_Py_IDENTIFIER(__prepare__);
40n/a_Py_IDENTIFIER(__round__);
41n/a_Py_IDENTIFIER(encoding);
42n/a_Py_IDENTIFIER(errors);
43n/a_Py_IDENTIFIER(fileno);
44n/a_Py_IDENTIFIER(flush);
45n/a_Py_IDENTIFIER(metaclass);
46n/a_Py_IDENTIFIER(sort);
47n/a_Py_IDENTIFIER(stdin);
48n/a_Py_IDENTIFIER(stdout);
49n/a_Py_IDENTIFIER(stderr);
50n/a
51n/a#include "clinic/bltinmodule.c.h"
52n/a
53n/a/* AC: cannot convert yet, waiting for *args support */
54n/astatic PyObject *
55n/abuiltin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs,
56n/a PyObject *kwnames)
57n/a{
58n/a PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
59n/a PyObject *cls = NULL, *cell = NULL;
60n/a int isclass = 0; /* initialize to prevent gcc warning */
61n/a
62n/a if (nargs < 2) {
63n/a PyErr_SetString(PyExc_TypeError,
64n/a "__build_class__: not enough arguments");
65n/a return NULL;
66n/a }
67n/a func = args[0]; /* Better be callable */
68n/a if (!PyFunction_Check(func)) {
69n/a PyErr_SetString(PyExc_TypeError,
70n/a "__build_class__: func must be a function");
71n/a return NULL;
72n/a }
73n/a name = args[1];
74n/a if (!PyUnicode_Check(name)) {
75n/a PyErr_SetString(PyExc_TypeError,
76n/a "__build_class__: name is not a string");
77n/a return NULL;
78n/a }
79n/a bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
80n/a if (bases == NULL)
81n/a return NULL;
82n/a
83n/a if (kwnames == NULL) {
84n/a meta = NULL;
85n/a mkw = NULL;
86n/a }
87n/a else {
88n/a mkw = _PyStack_AsDict(args + nargs, kwnames);
89n/a if (mkw == NULL) {
90n/a Py_DECREF(bases);
91n/a return NULL;
92n/a }
93n/a
94n/a meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
95n/a if (meta != NULL) {
96n/a Py_INCREF(meta);
97n/a if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
98n/a Py_DECREF(meta);
99n/a Py_DECREF(mkw);
100n/a Py_DECREF(bases);
101n/a return NULL;
102n/a }
103n/a /* metaclass is explicitly given, check if it's indeed a class */
104n/a isclass = PyType_Check(meta);
105n/a }
106n/a }
107n/a if (meta == NULL) {
108n/a /* if there are no bases, use type: */
109n/a if (PyTuple_GET_SIZE(bases) == 0) {
110n/a meta = (PyObject *) (&PyType_Type);
111n/a }
112n/a /* else get the type of the first base */
113n/a else {
114n/a PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
115n/a meta = (PyObject *) (base0->ob_type);
116n/a }
117n/a Py_INCREF(meta);
118n/a isclass = 1; /* meta is really a class */
119n/a }
120n/a
121n/a if (isclass) {
122n/a /* meta is really a class, so check for a more derived
123n/a metaclass, or possible metaclass conflicts: */
124n/a winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
125n/a bases);
126n/a if (winner == NULL) {
127n/a Py_DECREF(meta);
128n/a Py_XDECREF(mkw);
129n/a Py_DECREF(bases);
130n/a return NULL;
131n/a }
132n/a if (winner != meta) {
133n/a Py_DECREF(meta);
134n/a meta = winner;
135n/a Py_INCREF(meta);
136n/a }
137n/a }
138n/a /* else: meta is not a class, so we cannot do the metaclass
139n/a calculation, so we will use the explicitly given object as it is */
140n/a prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
141n/a if (prep == NULL) {
142n/a if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
143n/a PyErr_Clear();
144n/a ns = PyDict_New();
145n/a }
146n/a else {
147n/a Py_DECREF(meta);
148n/a Py_XDECREF(mkw);
149n/a Py_DECREF(bases);
150n/a return NULL;
151n/a }
152n/a }
153n/a else {
154n/a PyObject *pargs[2] = {name, bases};
155n/a ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
156n/a Py_DECREF(prep);
157n/a }
158n/a if (ns == NULL) {
159n/a Py_DECREF(meta);
160n/a Py_XDECREF(mkw);
161n/a Py_DECREF(bases);
162n/a return NULL;
163n/a }
164n/a cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
165n/a NULL, 0, NULL, 0, NULL, 0, NULL,
166n/a PyFunction_GET_CLOSURE(func));
167n/a if (cell != NULL) {
168n/a PyObject *margs[3] = {name, bases, ns};
169n/a cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
170n/a if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
171n/a PyObject *cell_cls = PyCell_GET(cell);
172n/a if (cell_cls != cls) {
173n/a /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
174n/a * At that point, cell_error won't be needed.
175n/a */
176n/a int cell_error;
177n/a if (cell_cls == NULL) {
178n/a const char *msg =
179n/a "__class__ not set defining %.200R as %.200R. "
180n/a "Was __classcell__ propagated to type.__new__?";
181n/a cell_error = PyErr_WarnFormat(
182n/a PyExc_DeprecationWarning, 1, msg, name, cls);
183n/a } else {
184n/a const char *msg =
185n/a "__class__ set to %.200R defining %.200R as %.200R";
186n/a PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
187n/a cell_error = 1;
188n/a }
189n/a if (cell_error) {
190n/a Py_DECREF(cls);
191n/a cls = NULL;
192n/a goto error;
193n/a } else {
194n/a /* Fill in the cell, since type.__new__ didn't do it */
195n/a PyCell_Set(cell, cls);
196n/a }
197n/a }
198n/a }
199n/a }
200n/aerror:
201n/a Py_XDECREF(cell);
202n/a Py_DECREF(ns);
203n/a Py_DECREF(meta);
204n/a Py_XDECREF(mkw);
205n/a Py_DECREF(bases);
206n/a return cls;
207n/a}
208n/a
209n/aPyDoc_STRVAR(build_class_doc,
210n/a"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
211n/a\n\
212n/aInternal helper function used by the class statement.");
213n/a
214n/astatic PyObject *
215n/abuiltin___import__(PyObject *self, PyObject *args, PyObject *kwds)
216n/a{
217n/a static char *kwlist[] = {"name", "globals", "locals", "fromlist",
218n/a "level", 0};
219n/a PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
220n/a int level = 0;
221n/a
222n/a if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
223n/a kwlist, &name, &globals, &locals, &fromlist, &level))
224n/a return NULL;
225n/a return PyImport_ImportModuleLevelObject(name, globals, locals,
226n/a fromlist, level);
227n/a}
228n/a
229n/aPyDoc_STRVAR(import_doc,
230n/a"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
231n/a\n\
232n/aImport a module. Because this function is meant for use by the Python\n\
233n/ainterpreter and not for general use it is better to use\n\
234n/aimportlib.import_module() to programmatically import a module.\n\
235n/a\n\
236n/aThe globals argument is only used to determine the context;\n\
237n/athey are not modified. The locals argument is unused. The fromlist\n\
238n/ashould be a list of names to emulate ``from name import ...'', or an\n\
239n/aempty list to emulate ``import name''.\n\
240n/aWhen importing a module from a package, note that __import__('A.B', ...)\n\
241n/areturns package A when fromlist is empty, but its submodule B when\n\
242n/afromlist is not empty. Level is used to determine whether to perform \n\
243n/aabsolute or relative imports. 0 is absolute while a positive number\n\
244n/ais the number of parent directories to search relative to the current module.");
245n/a
246n/a
247n/a/*[clinic input]
248n/aabs as builtin_abs
249n/a
250n/a x: object
251n/a /
252n/a
253n/aReturn the absolute value of the argument.
254n/a[clinic start generated code]*/
255n/a
256n/astatic PyObject *
257n/abuiltin_abs(PyObject *module, PyObject *x)
258n/a/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
259n/a{
260n/a return PyNumber_Absolute(x);
261n/a}
262n/a
263n/a/*[clinic input]
264n/aall as builtin_all
265n/a
266n/a iterable: object
267n/a /
268n/a
269n/aReturn True if bool(x) is True for all values x in the iterable.
270n/a
271n/aIf the iterable is empty, return True.
272n/a[clinic start generated code]*/
273n/a
274n/astatic PyObject *
275n/abuiltin_all(PyObject *module, PyObject *iterable)
276n/a/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
277n/a{
278n/a PyObject *it, *item;
279n/a PyObject *(*iternext)(PyObject *);
280n/a int cmp;
281n/a
282n/a it = PyObject_GetIter(iterable);
283n/a if (it == NULL)
284n/a return NULL;
285n/a iternext = *Py_TYPE(it)->tp_iternext;
286n/a
287n/a for (;;) {
288n/a item = iternext(it);
289n/a if (item == NULL)
290n/a break;
291n/a cmp = PyObject_IsTrue(item);
292n/a Py_DECREF(item);
293n/a if (cmp < 0) {
294n/a Py_DECREF(it);
295n/a return NULL;
296n/a }
297n/a if (cmp == 0) {
298n/a Py_DECREF(it);
299n/a Py_RETURN_FALSE;
300n/a }
301n/a }
302n/a Py_DECREF(it);
303n/a if (PyErr_Occurred()) {
304n/a if (PyErr_ExceptionMatches(PyExc_StopIteration))
305n/a PyErr_Clear();
306n/a else
307n/a return NULL;
308n/a }
309n/a Py_RETURN_TRUE;
310n/a}
311n/a
312n/a/*[clinic input]
313n/aany as builtin_any
314n/a
315n/a iterable: object
316n/a /
317n/a
318n/aReturn True if bool(x) is True for any x in the iterable.
319n/a
320n/aIf the iterable is empty, return False.
321n/a[clinic start generated code]*/
322n/a
323n/astatic PyObject *
324n/abuiltin_any(PyObject *module, PyObject *iterable)
325n/a/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
326n/a{
327n/a PyObject *it, *item;
328n/a PyObject *(*iternext)(PyObject *);
329n/a int cmp;
330n/a
331n/a it = PyObject_GetIter(iterable);
332n/a if (it == NULL)
333n/a return NULL;
334n/a iternext = *Py_TYPE(it)->tp_iternext;
335n/a
336n/a for (;;) {
337n/a item = iternext(it);
338n/a if (item == NULL)
339n/a break;
340n/a cmp = PyObject_IsTrue(item);
341n/a Py_DECREF(item);
342n/a if (cmp < 0) {
343n/a Py_DECREF(it);
344n/a return NULL;
345n/a }
346n/a if (cmp > 0) {
347n/a Py_DECREF(it);
348n/a Py_RETURN_TRUE;
349n/a }
350n/a }
351n/a Py_DECREF(it);
352n/a if (PyErr_Occurred()) {
353n/a if (PyErr_ExceptionMatches(PyExc_StopIteration))
354n/a PyErr_Clear();
355n/a else
356n/a return NULL;
357n/a }
358n/a Py_RETURN_FALSE;
359n/a}
360n/a
361n/a/*[clinic input]
362n/aascii as builtin_ascii
363n/a
364n/a obj: object
365n/a /
366n/a
367n/aReturn an ASCII-only representation of an object.
368n/a
369n/aAs repr(), return a string containing a printable representation of an
370n/aobject, but escape the non-ASCII characters in the string returned by
371n/arepr() using \\x, \\u or \\U escapes. This generates a string similar
372n/ato that returned by repr() in Python 2.
373n/a[clinic start generated code]*/
374n/a
375n/astatic PyObject *
376n/abuiltin_ascii(PyObject *module, PyObject *obj)
377n/a/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
378n/a{
379n/a return PyObject_ASCII(obj);
380n/a}
381n/a
382n/a
383n/a/*[clinic input]
384n/abin as builtin_bin
385n/a
386n/a number: object
387n/a /
388n/a
389n/aReturn the binary representation of an integer.
390n/a
391n/a >>> bin(2796202)
392n/a '0b1010101010101010101010'
393n/a[clinic start generated code]*/
394n/a
395n/astatic PyObject *
396n/abuiltin_bin(PyObject *module, PyObject *number)
397n/a/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
398n/a{
399n/a return PyNumber_ToBase(number, 2);
400n/a}
401n/a
402n/a
403n/a/*[clinic input]
404n/acallable as builtin_callable
405n/a
406n/a obj: object
407n/a /
408n/a
409n/aReturn whether the object is callable (i.e., some kind of function).
410n/a
411n/aNote that classes are callable, as are instances of classes with a
412n/a__call__() method.
413n/a[clinic start generated code]*/
414n/a
415n/astatic PyObject *
416n/abuiltin_callable(PyObject *module, PyObject *obj)
417n/a/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
418n/a{
419n/a return PyBool_FromLong((long)PyCallable_Check(obj));
420n/a}
421n/a
422n/a
423n/atypedef struct {
424n/a PyObject_HEAD
425n/a PyObject *func;
426n/a PyObject *it;
427n/a} filterobject;
428n/a
429n/astatic PyObject *
430n/afilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
431n/a{
432n/a PyObject *func, *seq;
433n/a PyObject *it;
434n/a filterobject *lz;
435n/a
436n/a if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
437n/a return NULL;
438n/a
439n/a if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
440n/a return NULL;
441n/a
442n/a /* Get iterator. */
443n/a it = PyObject_GetIter(seq);
444n/a if (it == NULL)
445n/a return NULL;
446n/a
447n/a /* create filterobject structure */
448n/a lz = (filterobject *)type->tp_alloc(type, 0);
449n/a if (lz == NULL) {
450n/a Py_DECREF(it);
451n/a return NULL;
452n/a }
453n/a Py_INCREF(func);
454n/a lz->func = func;
455n/a lz->it = it;
456n/a
457n/a return (PyObject *)lz;
458n/a}
459n/a
460n/astatic void
461n/afilter_dealloc(filterobject *lz)
462n/a{
463n/a PyObject_GC_UnTrack(lz);
464n/a Py_XDECREF(lz->func);
465n/a Py_XDECREF(lz->it);
466n/a Py_TYPE(lz)->tp_free(lz);
467n/a}
468n/a
469n/astatic int
470n/afilter_traverse(filterobject *lz, visitproc visit, void *arg)
471n/a{
472n/a Py_VISIT(lz->it);
473n/a Py_VISIT(lz->func);
474n/a return 0;
475n/a}
476n/a
477n/astatic PyObject *
478n/afilter_next(filterobject *lz)
479n/a{
480n/a PyObject *item;
481n/a PyObject *it = lz->it;
482n/a long ok;
483n/a PyObject *(*iternext)(PyObject *);
484n/a int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
485n/a
486n/a iternext = *Py_TYPE(it)->tp_iternext;
487n/a for (;;) {
488n/a item = iternext(it);
489n/a if (item == NULL)
490n/a return NULL;
491n/a
492n/a if (checktrue) {
493n/a ok = PyObject_IsTrue(item);
494n/a } else {
495n/a PyObject *good;
496n/a good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
497n/a if (good == NULL) {
498n/a Py_DECREF(item);
499n/a return NULL;
500n/a }
501n/a ok = PyObject_IsTrue(good);
502n/a Py_DECREF(good);
503n/a }
504n/a if (ok > 0)
505n/a return item;
506n/a Py_DECREF(item);
507n/a if (ok < 0)
508n/a return NULL;
509n/a }
510n/a}
511n/a
512n/astatic PyObject *
513n/afilter_reduce(filterobject *lz)
514n/a{
515n/a return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
516n/a}
517n/a
518n/aPyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
519n/a
520n/astatic PyMethodDef filter_methods[] = {
521n/a {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
522n/a {NULL, NULL} /* sentinel */
523n/a};
524n/a
525n/aPyDoc_STRVAR(filter_doc,
526n/a"filter(function or None, iterable) --> filter object\n\
527n/a\n\
528n/aReturn an iterator yielding those items of iterable for which function(item)\n\
529n/ais true. If function is None, return the items that are true.");
530n/a
531n/aPyTypeObject PyFilter_Type = {
532n/a PyVarObject_HEAD_INIT(&PyType_Type, 0)
533n/a "filter", /* tp_name */
534n/a sizeof(filterobject), /* tp_basicsize */
535n/a 0, /* tp_itemsize */
536n/a /* methods */
537n/a (destructor)filter_dealloc, /* tp_dealloc */
538n/a 0, /* tp_print */
539n/a 0, /* tp_getattr */
540n/a 0, /* tp_setattr */
541n/a 0, /* tp_reserved */
542n/a 0, /* tp_repr */
543n/a 0, /* tp_as_number */
544n/a 0, /* tp_as_sequence */
545n/a 0, /* tp_as_mapping */
546n/a 0, /* tp_hash */
547n/a 0, /* tp_call */
548n/a 0, /* tp_str */
549n/a PyObject_GenericGetAttr, /* tp_getattro */
550n/a 0, /* tp_setattro */
551n/a 0, /* tp_as_buffer */
552n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
553n/a Py_TPFLAGS_BASETYPE, /* tp_flags */
554n/a filter_doc, /* tp_doc */
555n/a (traverseproc)filter_traverse, /* tp_traverse */
556n/a 0, /* tp_clear */
557n/a 0, /* tp_richcompare */
558n/a 0, /* tp_weaklistoffset */
559n/a PyObject_SelfIter, /* tp_iter */
560n/a (iternextfunc)filter_next, /* tp_iternext */
561n/a filter_methods, /* tp_methods */
562n/a 0, /* tp_members */
563n/a 0, /* tp_getset */
564n/a 0, /* tp_base */
565n/a 0, /* tp_dict */
566n/a 0, /* tp_descr_get */
567n/a 0, /* tp_descr_set */
568n/a 0, /* tp_dictoffset */
569n/a 0, /* tp_init */
570n/a PyType_GenericAlloc, /* tp_alloc */
571n/a filter_new, /* tp_new */
572n/a PyObject_GC_Del, /* tp_free */
573n/a};
574n/a
575n/a
576n/a/*[clinic input]
577n/aformat as builtin_format
578n/a
579n/a value: object
580n/a format_spec: unicode(c_default="NULL") = ''
581n/a /
582n/a
583n/aReturn value.__format__(format_spec)
584n/a
585n/aformat_spec defaults to the empty string
586n/a[clinic start generated code]*/
587n/a
588n/astatic PyObject *
589n/abuiltin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
590n/a/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
591n/a{
592n/a return PyObject_Format(value, format_spec);
593n/a}
594n/a
595n/a/*[clinic input]
596n/achr as builtin_chr
597n/a
598n/a i: int
599n/a /
600n/a
601n/aReturn a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
602n/a[clinic start generated code]*/
603n/a
604n/astatic PyObject *
605n/abuiltin_chr_impl(PyObject *module, int i)
606n/a/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
607n/a{
608n/a return PyUnicode_FromOrdinal(i);
609n/a}
610n/a
611n/a
612n/astatic const char *
613n/asource_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
614n/a{
615n/a const char *str;
616n/a Py_ssize_t size;
617n/a Py_buffer view;
618n/a
619n/a *cmd_copy = NULL;
620n/a if (PyUnicode_Check(cmd)) {
621n/a cf->cf_flags |= PyCF_IGNORE_COOKIE;
622n/a str = PyUnicode_AsUTF8AndSize(cmd, &size);
623n/a if (str == NULL)
624n/a return NULL;
625n/a }
626n/a else if (PyBytes_Check(cmd)) {
627n/a str = PyBytes_AS_STRING(cmd);
628n/a size = PyBytes_GET_SIZE(cmd);
629n/a }
630n/a else if (PyByteArray_Check(cmd)) {
631n/a str = PyByteArray_AS_STRING(cmd);
632n/a size = PyByteArray_GET_SIZE(cmd);
633n/a }
634n/a else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
635n/a /* Copy to NUL-terminated buffer. */
636n/a *cmd_copy = PyBytes_FromStringAndSize(
637n/a (const char *)view.buf, view.len);
638n/a PyBuffer_Release(&view);
639n/a if (*cmd_copy == NULL) {
640n/a return NULL;
641n/a }
642n/a str = PyBytes_AS_STRING(*cmd_copy);
643n/a size = PyBytes_GET_SIZE(*cmd_copy);
644n/a }
645n/a else {
646n/a PyErr_Format(PyExc_TypeError,
647n/a "%s() arg 1 must be a %s object",
648n/a funcname, what);
649n/a return NULL;
650n/a }
651n/a
652n/a if (strlen(str) != (size_t)size) {
653n/a PyErr_SetString(PyExc_ValueError,
654n/a "source code string cannot contain null bytes");
655n/a Py_CLEAR(*cmd_copy);
656n/a return NULL;
657n/a }
658n/a return str;
659n/a}
660n/a
661n/a/*[clinic input]
662n/acompile as builtin_compile
663n/a
664n/a source: object
665n/a filename: object(converter="PyUnicode_FSDecoder")
666n/a mode: str
667n/a flags: int = 0
668n/a dont_inherit: int(c_default="0") = False
669n/a optimize: int = -1
670n/a
671n/aCompile source into a code object that can be executed by exec() or eval().
672n/a
673n/aThe source code may represent a Python module, statement or expression.
674n/aThe filename will be used for run-time error messages.
675n/aThe mode must be 'exec' to compile a module, 'single' to compile a
676n/asingle (interactive) statement, or 'eval' to compile an expression.
677n/aThe flags argument, if present, controls which future statements influence
678n/athe compilation of the code.
679n/aThe dont_inherit argument, if true, stops the compilation inheriting
680n/athe effects of any future statements in effect in the code calling
681n/acompile; if absent or false these statements do influence the compilation,
682n/ain addition to any features explicitly specified.
683n/a[clinic start generated code]*/
684n/a
685n/astatic PyObject *
686n/abuiltin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
687n/a const char *mode, int flags, int dont_inherit,
688n/a int optimize)
689n/a/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
690n/a{
691n/a PyObject *source_copy;
692n/a const char *str;
693n/a int compile_mode = -1;
694n/a int is_ast;
695n/a PyCompilerFlags cf;
696n/a int start[] = {Py_file_input, Py_eval_input, Py_single_input};
697n/a PyObject *result;
698n/a
699n/a cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
700n/a
701n/a if (flags &
702n/a ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
703n/a {
704n/a PyErr_SetString(PyExc_ValueError,
705n/a "compile(): unrecognised flags");
706n/a goto error;
707n/a }
708n/a /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
709n/a
710n/a if (optimize < -1 || optimize > 2) {
711n/a PyErr_SetString(PyExc_ValueError,
712n/a "compile(): invalid optimize value");
713n/a goto error;
714n/a }
715n/a
716n/a if (!dont_inherit) {
717n/a PyEval_MergeCompilerFlags(&cf);
718n/a }
719n/a
720n/a if (strcmp(mode, "exec") == 0)
721n/a compile_mode = 0;
722n/a else if (strcmp(mode, "eval") == 0)
723n/a compile_mode = 1;
724n/a else if (strcmp(mode, "single") == 0)
725n/a compile_mode = 2;
726n/a else {
727n/a PyErr_SetString(PyExc_ValueError,
728n/a "compile() mode must be 'exec', 'eval' or 'single'");
729n/a goto error;
730n/a }
731n/a
732n/a is_ast = PyAST_Check(source);
733n/a if (is_ast == -1)
734n/a goto error;
735n/a if (is_ast) {
736n/a if (flags & PyCF_ONLY_AST) {
737n/a Py_INCREF(source);
738n/a result = source;
739n/a }
740n/a else {
741n/a PyArena *arena;
742n/a mod_ty mod;
743n/a
744n/a arena = PyArena_New();
745n/a if (arena == NULL)
746n/a goto error;
747n/a mod = PyAST_obj2mod(source, arena, compile_mode);
748n/a if (mod == NULL) {
749n/a PyArena_Free(arena);
750n/a goto error;
751n/a }
752n/a if (!PyAST_Validate(mod)) {
753n/a PyArena_Free(arena);
754n/a goto error;
755n/a }
756n/a result = (PyObject*)PyAST_CompileObject(mod, filename,
757n/a &cf, optimize, arena);
758n/a PyArena_Free(arena);
759n/a }
760n/a goto finally;
761n/a }
762n/a
763n/a str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
764n/a if (str == NULL)
765n/a goto error;
766n/a
767n/a result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
768n/a Py_XDECREF(source_copy);
769n/a goto finally;
770n/a
771n/aerror:
772n/a result = NULL;
773n/afinally:
774n/a Py_DECREF(filename);
775n/a return result;
776n/a}
777n/a
778n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
779n/astatic PyObject *
780n/abuiltin_dir(PyObject *self, PyObject *args)
781n/a{
782n/a PyObject *arg = NULL;
783n/a
784n/a if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
785n/a return NULL;
786n/a return PyObject_Dir(arg);
787n/a}
788n/a
789n/aPyDoc_STRVAR(dir_doc,
790n/a"dir([object]) -> list of strings\n"
791n/a"\n"
792n/a"If called without an argument, return the names in the current scope.\n"
793n/a"Else, return an alphabetized list of names comprising (some of) the attributes\n"
794n/a"of the given object, and of attributes reachable from it.\n"
795n/a"If the object supplies a method named __dir__, it will be used; otherwise\n"
796n/a"the default dir() logic is used and returns:\n"
797n/a" for a module object: the module's attributes.\n"
798n/a" for a class object: its attributes, and recursively the attributes\n"
799n/a" of its bases.\n"
800n/a" for any other object: its attributes, its class's attributes, and\n"
801n/a" recursively the attributes of its class's base classes.");
802n/a
803n/a/*[clinic input]
804n/adivmod as builtin_divmod
805n/a
806n/a x: object
807n/a y: object
808n/a /
809n/a
810n/aReturn the tuple (x//y, x%y). Invariant: div*y + mod == x.
811n/a[clinic start generated code]*/
812n/a
813n/astatic PyObject *
814n/abuiltin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
815n/a/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
816n/a{
817n/a return PyNumber_Divmod(x, y);
818n/a}
819n/a
820n/a
821n/a/*[clinic input]
822n/aeval as builtin_eval
823n/a
824n/a source: object
825n/a globals: object = None
826n/a locals: object = None
827n/a /
828n/a
829n/aEvaluate the given source in the context of globals and locals.
830n/a
831n/aThe source may be a string representing a Python expression
832n/aor a code object as returned by compile().
833n/aThe globals must be a dictionary and locals can be any mapping,
834n/adefaulting to the current globals and locals.
835n/aIf only globals is given, locals defaults to it.
836n/a[clinic start generated code]*/
837n/a
838n/astatic PyObject *
839n/abuiltin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
840n/a PyObject *locals)
841n/a/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
842n/a{
843n/a PyObject *result, *source_copy;
844n/a const char *str;
845n/a PyCompilerFlags cf;
846n/a
847n/a if (locals != Py_None && !PyMapping_Check(locals)) {
848n/a PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
849n/a return NULL;
850n/a }
851n/a if (globals != Py_None && !PyDict_Check(globals)) {
852n/a PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
853n/a "globals must be a real dict; try eval(expr, {}, mapping)"
854n/a : "globals must be a dict");
855n/a return NULL;
856n/a }
857n/a if (globals == Py_None) {
858n/a globals = PyEval_GetGlobals();
859n/a if (locals == Py_None) {
860n/a locals = PyEval_GetLocals();
861n/a if (locals == NULL)
862n/a return NULL;
863n/a }
864n/a }
865n/a else if (locals == Py_None)
866n/a locals = globals;
867n/a
868n/a if (globals == NULL || locals == NULL) {
869n/a PyErr_SetString(PyExc_TypeError,
870n/a "eval must be given globals and locals "
871n/a "when called without a frame");
872n/a return NULL;
873n/a }
874n/a
875n/a if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
876n/a if (_PyDict_SetItemId(globals, &PyId___builtins__,
877n/a PyEval_GetBuiltins()) != 0)
878n/a return NULL;
879n/a }
880n/a
881n/a if (PyCode_Check(source)) {
882n/a if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
883n/a PyErr_SetString(PyExc_TypeError,
884n/a "code object passed to eval() may not contain free variables");
885n/a return NULL;
886n/a }
887n/a return PyEval_EvalCode(source, globals, locals);
888n/a }
889n/a
890n/a cf.cf_flags = PyCF_SOURCE_IS_UTF8;
891n/a str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
892n/a if (str == NULL)
893n/a return NULL;
894n/a
895n/a while (*str == ' ' || *str == '\t')
896n/a str++;
897n/a
898n/a (void)PyEval_MergeCompilerFlags(&cf);
899n/a result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
900n/a Py_XDECREF(source_copy);
901n/a return result;
902n/a}
903n/a
904n/a/*[clinic input]
905n/aexec as builtin_exec
906n/a
907n/a source: object
908n/a globals: object = None
909n/a locals: object = None
910n/a /
911n/a
912n/aExecute the given source in the context of globals and locals.
913n/a
914n/aThe source may be a string representing one or more Python statements
915n/aor a code object as returned by compile().
916n/aThe globals must be a dictionary and locals can be any mapping,
917n/adefaulting to the current globals and locals.
918n/aIf only globals is given, locals defaults to it.
919n/a[clinic start generated code]*/
920n/a
921n/astatic PyObject *
922n/abuiltin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
923n/a PyObject *locals)
924n/a/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
925n/a{
926n/a PyObject *v;
927n/a
928n/a if (globals == Py_None) {
929n/a globals = PyEval_GetGlobals();
930n/a if (locals == Py_None) {
931n/a locals = PyEval_GetLocals();
932n/a if (locals == NULL)
933n/a return NULL;
934n/a }
935n/a if (!globals || !locals) {
936n/a PyErr_SetString(PyExc_SystemError,
937n/a "globals and locals cannot be NULL");
938n/a return NULL;
939n/a }
940n/a }
941n/a else if (locals == Py_None)
942n/a locals = globals;
943n/a
944n/a if (!PyDict_Check(globals)) {
945n/a PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
946n/a globals->ob_type->tp_name);
947n/a return NULL;
948n/a }
949n/a if (!PyMapping_Check(locals)) {
950n/a PyErr_Format(PyExc_TypeError,
951n/a "locals must be a mapping or None, not %.100s",
952n/a locals->ob_type->tp_name);
953n/a return NULL;
954n/a }
955n/a if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
956n/a if (_PyDict_SetItemId(globals, &PyId___builtins__,
957n/a PyEval_GetBuiltins()) != 0)
958n/a return NULL;
959n/a }
960n/a
961n/a if (PyCode_Check(source)) {
962n/a if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
963n/a PyErr_SetString(PyExc_TypeError,
964n/a "code object passed to exec() may not "
965n/a "contain free variables");
966n/a return NULL;
967n/a }
968n/a v = PyEval_EvalCode(source, globals, locals);
969n/a }
970n/a else {
971n/a PyObject *source_copy;
972n/a const char *str;
973n/a PyCompilerFlags cf;
974n/a cf.cf_flags = PyCF_SOURCE_IS_UTF8;
975n/a str = source_as_string(source, "exec",
976n/a "string, bytes or code", &cf,
977n/a &source_copy);
978n/a if (str == NULL)
979n/a return NULL;
980n/a if (PyEval_MergeCompilerFlags(&cf))
981n/a v = PyRun_StringFlags(str, Py_file_input, globals,
982n/a locals, &cf);
983n/a else
984n/a v = PyRun_String(str, Py_file_input, globals, locals);
985n/a Py_XDECREF(source_copy);
986n/a }
987n/a if (v == NULL)
988n/a return NULL;
989n/a Py_DECREF(v);
990n/a Py_RETURN_NONE;
991n/a}
992n/a
993n/a
994n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
995n/astatic PyObject *
996n/abuiltin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs,
997n/a PyObject *kwnames)
998n/a{
999n/a PyObject *v, *result, *dflt = NULL;
1000n/a PyObject *name;
1001n/a
1002n/a if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1003n/a return NULL;
1004n/a
1005n/a if (!_PyArg_NoStackKeywords("getattr", kwnames)) {
1006n/a return NULL;
1007n/a }
1008n/a
1009n/a if (!PyUnicode_Check(name)) {
1010n/a PyErr_SetString(PyExc_TypeError,
1011n/a "getattr(): attribute name must be string");
1012n/a return NULL;
1013n/a }
1014n/a result = PyObject_GetAttr(v, name);
1015n/a if (result == NULL && dflt != NULL &&
1016n/a PyErr_ExceptionMatches(PyExc_AttributeError))
1017n/a {
1018n/a PyErr_Clear();
1019n/a Py_INCREF(dflt);
1020n/a result = dflt;
1021n/a }
1022n/a return result;
1023n/a}
1024n/a
1025n/aPyDoc_STRVAR(getattr_doc,
1026n/a"getattr(object, name[, default]) -> value\n\
1027n/a\n\
1028n/aGet a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1029n/aWhen a default argument is given, it is returned when the attribute doesn't\n\
1030n/aexist; without it, an exception is raised in that case.");
1031n/a
1032n/a
1033n/a/*[clinic input]
1034n/aglobals as builtin_globals
1035n/a
1036n/aReturn the dictionary containing the current scope's global variables.
1037n/a
1038n/aNOTE: Updates to this dictionary *will* affect name lookups in the current
1039n/aglobal scope and vice-versa.
1040n/a[clinic start generated code]*/
1041n/a
1042n/astatic PyObject *
1043n/abuiltin_globals_impl(PyObject *module)
1044n/a/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
1045n/a{
1046n/a PyObject *d;
1047n/a
1048n/a d = PyEval_GetGlobals();
1049n/a Py_XINCREF(d);
1050n/a return d;
1051n/a}
1052n/a
1053n/a
1054n/a/*[clinic input]
1055n/ahasattr as builtin_hasattr
1056n/a
1057n/a obj: object
1058n/a name: object
1059n/a /
1060n/a
1061n/aReturn whether the object has an attribute with the given name.
1062n/a
1063n/aThis is done by calling getattr(obj, name) and catching AttributeError.
1064n/a[clinic start generated code]*/
1065n/a
1066n/astatic PyObject *
1067n/abuiltin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1068n/a/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
1069n/a{
1070n/a PyObject *v;
1071n/a
1072n/a if (!PyUnicode_Check(name)) {
1073n/a PyErr_SetString(PyExc_TypeError,
1074n/a "hasattr(): attribute name must be string");
1075n/a return NULL;
1076n/a }
1077n/a v = PyObject_GetAttr(obj, name);
1078n/a if (v == NULL) {
1079n/a if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1080n/a PyErr_Clear();
1081n/a Py_RETURN_FALSE;
1082n/a }
1083n/a return NULL;
1084n/a }
1085n/a Py_DECREF(v);
1086n/a Py_RETURN_TRUE;
1087n/a}
1088n/a
1089n/a
1090n/a/* AC: gdb's integration with CPython relies on builtin_id having
1091n/a * the *exact* parameter names of "self" and "v", so we ensure we
1092n/a * preserve those name rather than using the AC defaults.
1093n/a */
1094n/a/*[clinic input]
1095n/aid as builtin_id
1096n/a
1097n/a self: self(type="PyModuleDef *")
1098n/a obj as v: object
1099n/a /
1100n/a
1101n/aReturn the identity of an object.
1102n/a
1103n/aThis is guaranteed to be unique among simultaneously existing objects.
1104n/a(CPython uses the object's memory address.)
1105n/a[clinic start generated code]*/
1106n/a
1107n/astatic PyObject *
1108n/abuiltin_id(PyModuleDef *self, PyObject *v)
1109n/a/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
1110n/a{
1111n/a return PyLong_FromVoidPtr(v);
1112n/a}
1113n/a
1114n/a
1115n/a/* map object ************************************************************/
1116n/a
1117n/atypedef struct {
1118n/a PyObject_HEAD
1119n/a PyObject *iters;
1120n/a PyObject *func;
1121n/a} mapobject;
1122n/a
1123n/astatic PyObject *
1124n/amap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1125n/a{
1126n/a PyObject *it, *iters, *func;
1127n/a mapobject *lz;
1128n/a Py_ssize_t numargs, i;
1129n/a
1130n/a if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1131n/a return NULL;
1132n/a
1133n/a numargs = PyTuple_Size(args);
1134n/a if (numargs < 2) {
1135n/a PyErr_SetString(PyExc_TypeError,
1136n/a "map() must have at least two arguments.");
1137n/a return NULL;
1138n/a }
1139n/a
1140n/a iters = PyTuple_New(numargs-1);
1141n/a if (iters == NULL)
1142n/a return NULL;
1143n/a
1144n/a for (i=1 ; i<numargs ; i++) {
1145n/a /* Get iterator. */
1146n/a it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1147n/a if (it == NULL) {
1148n/a Py_DECREF(iters);
1149n/a return NULL;
1150n/a }
1151n/a PyTuple_SET_ITEM(iters, i-1, it);
1152n/a }
1153n/a
1154n/a /* create mapobject structure */
1155n/a lz = (mapobject *)type->tp_alloc(type, 0);
1156n/a if (lz == NULL) {
1157n/a Py_DECREF(iters);
1158n/a return NULL;
1159n/a }
1160n/a lz->iters = iters;
1161n/a func = PyTuple_GET_ITEM(args, 0);
1162n/a Py_INCREF(func);
1163n/a lz->func = func;
1164n/a
1165n/a return (PyObject *)lz;
1166n/a}
1167n/a
1168n/astatic void
1169n/amap_dealloc(mapobject *lz)
1170n/a{
1171n/a PyObject_GC_UnTrack(lz);
1172n/a Py_XDECREF(lz->iters);
1173n/a Py_XDECREF(lz->func);
1174n/a Py_TYPE(lz)->tp_free(lz);
1175n/a}
1176n/a
1177n/astatic int
1178n/amap_traverse(mapobject *lz, visitproc visit, void *arg)
1179n/a{
1180n/a Py_VISIT(lz->iters);
1181n/a Py_VISIT(lz->func);
1182n/a return 0;
1183n/a}
1184n/a
1185n/astatic PyObject *
1186n/amap_next(mapobject *lz)
1187n/a{
1188n/a PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1189n/a PyObject **stack;
1190n/a Py_ssize_t niters, nargs, i;
1191n/a PyObject *result = NULL;
1192n/a
1193n/a niters = PyTuple_GET_SIZE(lz->iters);
1194n/a if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1195n/a stack = small_stack;
1196n/a }
1197n/a else {
1198n/a stack = PyMem_Malloc(niters * sizeof(stack[0]));
1199n/a if (stack == NULL) {
1200n/a PyErr_NoMemory();
1201n/a return NULL;
1202n/a }
1203n/a }
1204n/a
1205n/a nargs = 0;
1206n/a for (i=0; i < niters; i++) {
1207n/a PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1208n/a PyObject *val = Py_TYPE(it)->tp_iternext(it);
1209n/a if (val == NULL) {
1210n/a goto exit;
1211n/a }
1212n/a stack[i] = val;
1213n/a nargs++;
1214n/a }
1215n/a
1216n/a result = _PyObject_FastCall(lz->func, stack, nargs);
1217n/a
1218n/aexit:
1219n/a for (i=0; i < nargs; i++) {
1220n/a Py_DECREF(stack[i]);
1221n/a }
1222n/a if (stack != small_stack) {
1223n/a PyMem_Free(stack);
1224n/a }
1225n/a return result;
1226n/a}
1227n/a
1228n/astatic PyObject *
1229n/amap_reduce(mapobject *lz)
1230n/a{
1231n/a Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1232n/a PyObject *args = PyTuple_New(numargs+1);
1233n/a Py_ssize_t i;
1234n/a if (args == NULL)
1235n/a return NULL;
1236n/a Py_INCREF(lz->func);
1237n/a PyTuple_SET_ITEM(args, 0, lz->func);
1238n/a for (i = 0; i<numargs; i++){
1239n/a PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1240n/a Py_INCREF(it);
1241n/a PyTuple_SET_ITEM(args, i+1, it);
1242n/a }
1243n/a
1244n/a return Py_BuildValue("ON", Py_TYPE(lz), args);
1245n/a}
1246n/a
1247n/astatic PyMethodDef map_methods[] = {
1248n/a {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1249n/a {NULL, NULL} /* sentinel */
1250n/a};
1251n/a
1252n/a
1253n/aPyDoc_STRVAR(map_doc,
1254n/a"map(func, *iterables) --> map object\n\
1255n/a\n\
1256n/aMake an iterator that computes the function using arguments from\n\
1257n/aeach of the iterables. Stops when the shortest iterable is exhausted.");
1258n/a
1259n/aPyTypeObject PyMap_Type = {
1260n/a PyVarObject_HEAD_INIT(&PyType_Type, 0)
1261n/a "map", /* tp_name */
1262n/a sizeof(mapobject), /* tp_basicsize */
1263n/a 0, /* tp_itemsize */
1264n/a /* methods */
1265n/a (destructor)map_dealloc, /* tp_dealloc */
1266n/a 0, /* tp_print */
1267n/a 0, /* tp_getattr */
1268n/a 0, /* tp_setattr */
1269n/a 0, /* tp_reserved */
1270n/a 0, /* tp_repr */
1271n/a 0, /* tp_as_number */
1272n/a 0, /* tp_as_sequence */
1273n/a 0, /* tp_as_mapping */
1274n/a 0, /* tp_hash */
1275n/a 0, /* tp_call */
1276n/a 0, /* tp_str */
1277n/a PyObject_GenericGetAttr, /* tp_getattro */
1278n/a 0, /* tp_setattro */
1279n/a 0, /* tp_as_buffer */
1280n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1281n/a Py_TPFLAGS_BASETYPE, /* tp_flags */
1282n/a map_doc, /* tp_doc */
1283n/a (traverseproc)map_traverse, /* tp_traverse */
1284n/a 0, /* tp_clear */
1285n/a 0, /* tp_richcompare */
1286n/a 0, /* tp_weaklistoffset */
1287n/a PyObject_SelfIter, /* tp_iter */
1288n/a (iternextfunc)map_next, /* tp_iternext */
1289n/a map_methods, /* tp_methods */
1290n/a 0, /* tp_members */
1291n/a 0, /* tp_getset */
1292n/a 0, /* tp_base */
1293n/a 0, /* tp_dict */
1294n/a 0, /* tp_descr_get */
1295n/a 0, /* tp_descr_set */
1296n/a 0, /* tp_dictoffset */
1297n/a 0, /* tp_init */
1298n/a PyType_GenericAlloc, /* tp_alloc */
1299n/a map_new, /* tp_new */
1300n/a PyObject_GC_Del, /* tp_free */
1301n/a};
1302n/a
1303n/a
1304n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1305n/astatic PyObject *
1306n/abuiltin_next(PyObject *self, PyObject **args, Py_ssize_t nargs,
1307n/a PyObject *kwnames)
1308n/a{
1309n/a PyObject *it, *res;
1310n/a PyObject *def = NULL;
1311n/a
1312n/a if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1313n/a return NULL;
1314n/a
1315n/a if (!_PyArg_NoStackKeywords("next", kwnames)) {
1316n/a return NULL;
1317n/a }
1318n/a
1319n/a if (!PyIter_Check(it)) {
1320n/a PyErr_Format(PyExc_TypeError,
1321n/a "'%.200s' object is not an iterator",
1322n/a it->ob_type->tp_name);
1323n/a return NULL;
1324n/a }
1325n/a
1326n/a res = (*it->ob_type->tp_iternext)(it);
1327n/a if (res != NULL) {
1328n/a return res;
1329n/a } else if (def != NULL) {
1330n/a if (PyErr_Occurred()) {
1331n/a if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1332n/a return NULL;
1333n/a PyErr_Clear();
1334n/a }
1335n/a Py_INCREF(def);
1336n/a return def;
1337n/a } else if (PyErr_Occurred()) {
1338n/a return NULL;
1339n/a } else {
1340n/a PyErr_SetNone(PyExc_StopIteration);
1341n/a return NULL;
1342n/a }
1343n/a}
1344n/a
1345n/aPyDoc_STRVAR(next_doc,
1346n/a"next(iterator[, default])\n\
1347n/a\n\
1348n/aReturn the next item from the iterator. If default is given and the iterator\n\
1349n/ais exhausted, it is returned instead of raising StopIteration.");
1350n/a
1351n/a
1352n/a/*[clinic input]
1353n/asetattr as builtin_setattr
1354n/a
1355n/a obj: object
1356n/a name: object
1357n/a value: object
1358n/a /
1359n/a
1360n/aSets the named attribute on the given object to the specified value.
1361n/a
1362n/asetattr(x, 'y', v) is equivalent to ``x.y = v''
1363n/a[clinic start generated code]*/
1364n/a
1365n/astatic PyObject *
1366n/abuiltin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
1367n/a PyObject *value)
1368n/a/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
1369n/a{
1370n/a if (PyObject_SetAttr(obj, name, value) != 0)
1371n/a return NULL;
1372n/a Py_RETURN_NONE;
1373n/a}
1374n/a
1375n/a
1376n/a/*[clinic input]
1377n/adelattr as builtin_delattr
1378n/a
1379n/a obj: object
1380n/a name: object
1381n/a /
1382n/a
1383n/aDeletes the named attribute from the given object.
1384n/a
1385n/adelattr(x, 'y') is equivalent to ``del x.y''
1386n/a[clinic start generated code]*/
1387n/a
1388n/astatic PyObject *
1389n/abuiltin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1390n/a/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
1391n/a{
1392n/a if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
1393n/a return NULL;
1394n/a Py_RETURN_NONE;
1395n/a}
1396n/a
1397n/a
1398n/a/*[clinic input]
1399n/ahash as builtin_hash
1400n/a
1401n/a obj: object
1402n/a /
1403n/a
1404n/aReturn the hash value for the given object.
1405n/a
1406n/aTwo objects that compare equal must also have the same hash value, but the
1407n/areverse is not necessarily true.
1408n/a[clinic start generated code]*/
1409n/a
1410n/astatic PyObject *
1411n/abuiltin_hash(PyObject *module, PyObject *obj)
1412n/a/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
1413n/a{
1414n/a Py_hash_t x;
1415n/a
1416n/a x = PyObject_Hash(obj);
1417n/a if (x == -1)
1418n/a return NULL;
1419n/a return PyLong_FromSsize_t(x);
1420n/a}
1421n/a
1422n/a
1423n/a/*[clinic input]
1424n/ahex as builtin_hex
1425n/a
1426n/a number: object
1427n/a /
1428n/a
1429n/aReturn the hexadecimal representation of an integer.
1430n/a
1431n/a >>> hex(12648430)
1432n/a '0xc0ffee'
1433n/a[clinic start generated code]*/
1434n/a
1435n/astatic PyObject *
1436n/abuiltin_hex(PyObject *module, PyObject *number)
1437n/a/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
1438n/a{
1439n/a return PyNumber_ToBase(number, 16);
1440n/a}
1441n/a
1442n/a
1443n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1444n/astatic PyObject *
1445n/abuiltin_iter(PyObject *self, PyObject *args)
1446n/a{
1447n/a PyObject *v, *w = NULL;
1448n/a
1449n/a if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1450n/a return NULL;
1451n/a if (w == NULL)
1452n/a return PyObject_GetIter(v);
1453n/a if (!PyCallable_Check(v)) {
1454n/a PyErr_SetString(PyExc_TypeError,
1455n/a "iter(v, w): v must be callable");
1456n/a return NULL;
1457n/a }
1458n/a return PyCallIter_New(v, w);
1459n/a}
1460n/a
1461n/aPyDoc_STRVAR(iter_doc,
1462n/a"iter(iterable) -> iterator\n\
1463n/aiter(callable, sentinel) -> iterator\n\
1464n/a\n\
1465n/aGet an iterator from an object. In the first form, the argument must\n\
1466n/asupply its own iterator, or be a sequence.\n\
1467n/aIn the second form, the callable is called until it returns the sentinel.");
1468n/a
1469n/a
1470n/a/*[clinic input]
1471n/alen as builtin_len
1472n/a
1473n/a obj: object
1474n/a /
1475n/a
1476n/aReturn the number of items in a container.
1477n/a[clinic start generated code]*/
1478n/a
1479n/astatic PyObject *
1480n/abuiltin_len(PyObject *module, PyObject *obj)
1481n/a/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
1482n/a{
1483n/a Py_ssize_t res;
1484n/a
1485n/a res = PyObject_Size(obj);
1486n/a if (res < 0 && PyErr_Occurred())
1487n/a return NULL;
1488n/a return PyLong_FromSsize_t(res);
1489n/a}
1490n/a
1491n/a
1492n/a/*[clinic input]
1493n/alocals as builtin_locals
1494n/a
1495n/aReturn a dictionary containing the current scope's local variables.
1496n/a
1497n/aNOTE: Whether or not updates to this dictionary will affect name lookups in
1498n/athe local scope and vice-versa is *implementation dependent* and not
1499n/acovered by any backwards compatibility guarantees.
1500n/a[clinic start generated code]*/
1501n/a
1502n/astatic PyObject *
1503n/abuiltin_locals_impl(PyObject *module)
1504n/a/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
1505n/a{
1506n/a PyObject *d;
1507n/a
1508n/a d = PyEval_GetLocals();
1509n/a Py_XINCREF(d);
1510n/a return d;
1511n/a}
1512n/a
1513n/a
1514n/astatic PyObject *
1515n/amin_max(PyObject *args, PyObject *kwds, int op)
1516n/a{
1517n/a PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1518n/a PyObject *emptytuple, *defaultval = NULL;
1519n/a static char *kwlist[] = {"key", "default", NULL};
1520n/a const char *name = op == Py_LT ? "min" : "max";
1521n/a const int positional = PyTuple_Size(args) > 1;
1522n/a int ret;
1523n/a
1524n/a if (positional)
1525n/a v = args;
1526n/a else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
1527n/a return NULL;
1528n/a
1529n/a emptytuple = PyTuple_New(0);
1530n/a if (emptytuple == NULL)
1531n/a return NULL;
1532n/a ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1533n/a &keyfunc, &defaultval);
1534n/a Py_DECREF(emptytuple);
1535n/a if (!ret)
1536n/a return NULL;
1537n/a
1538n/a if (positional && defaultval != NULL) {
1539n/a PyErr_Format(PyExc_TypeError,
1540n/a "Cannot specify a default for %s() with multiple "
1541n/a "positional arguments", name);
1542n/a return NULL;
1543n/a }
1544n/a
1545n/a it = PyObject_GetIter(v);
1546n/a if (it == NULL) {
1547n/a return NULL;
1548n/a }
1549n/a
1550n/a maxitem = NULL; /* the result */
1551n/a maxval = NULL; /* the value associated with the result */
1552n/a while (( item = PyIter_Next(it) )) {
1553n/a /* get the value from the key function */
1554n/a if (keyfunc != NULL) {
1555n/a val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1556n/a if (val == NULL)
1557n/a goto Fail_it_item;
1558n/a }
1559n/a /* no key function; the value is the item */
1560n/a else {
1561n/a val = item;
1562n/a Py_INCREF(val);
1563n/a }
1564n/a
1565n/a /* maximum value and item are unset; set them */
1566n/a if (maxval == NULL) {
1567n/a maxitem = item;
1568n/a maxval = val;
1569n/a }
1570n/a /* maximum value and item are set; update them as necessary */
1571n/a else {
1572n/a int cmp = PyObject_RichCompareBool(val, maxval, op);
1573n/a if (cmp < 0)
1574n/a goto Fail_it_item_and_val;
1575n/a else if (cmp > 0) {
1576n/a Py_DECREF(maxval);
1577n/a Py_DECREF(maxitem);
1578n/a maxval = val;
1579n/a maxitem = item;
1580n/a }
1581n/a else {
1582n/a Py_DECREF(item);
1583n/a Py_DECREF(val);
1584n/a }
1585n/a }
1586n/a }
1587n/a if (PyErr_Occurred())
1588n/a goto Fail_it;
1589n/a if (maxval == NULL) {
1590n/a assert(maxitem == NULL);
1591n/a if (defaultval != NULL) {
1592n/a Py_INCREF(defaultval);
1593n/a maxitem = defaultval;
1594n/a } else {
1595n/a PyErr_Format(PyExc_ValueError,
1596n/a "%s() arg is an empty sequence", name);
1597n/a }
1598n/a }
1599n/a else
1600n/a Py_DECREF(maxval);
1601n/a Py_DECREF(it);
1602n/a return maxitem;
1603n/a
1604n/aFail_it_item_and_val:
1605n/a Py_DECREF(val);
1606n/aFail_it_item:
1607n/a Py_DECREF(item);
1608n/aFail_it:
1609n/a Py_XDECREF(maxval);
1610n/a Py_XDECREF(maxitem);
1611n/a Py_DECREF(it);
1612n/a return NULL;
1613n/a}
1614n/a
1615n/a/* AC: cannot convert yet, waiting for *args support */
1616n/astatic PyObject *
1617n/abuiltin_min(PyObject *self, PyObject *args, PyObject *kwds)
1618n/a{
1619n/a return min_max(args, kwds, Py_LT);
1620n/a}
1621n/a
1622n/aPyDoc_STRVAR(min_doc,
1623n/a"min(iterable, *[, default=obj, key=func]) -> value\n\
1624n/amin(arg1, arg2, *args, *[, key=func]) -> value\n\
1625n/a\n\
1626n/aWith a single iterable argument, return its smallest item. The\n\
1627n/adefault keyword-only argument specifies an object to return if\n\
1628n/athe provided iterable is empty.\n\
1629n/aWith two or more arguments, return the smallest argument.");
1630n/a
1631n/a
1632n/a/* AC: cannot convert yet, waiting for *args support */
1633n/astatic PyObject *
1634n/abuiltin_max(PyObject *self, PyObject *args, PyObject *kwds)
1635n/a{
1636n/a return min_max(args, kwds, Py_GT);
1637n/a}
1638n/a
1639n/aPyDoc_STRVAR(max_doc,
1640n/a"max(iterable, *[, default=obj, key=func]) -> value\n\
1641n/amax(arg1, arg2, *args, *[, key=func]) -> value\n\
1642n/a\n\
1643n/aWith a single iterable argument, return its biggest item. The\n\
1644n/adefault keyword-only argument specifies an object to return if\n\
1645n/athe provided iterable is empty.\n\
1646n/aWith two or more arguments, return the largest argument.");
1647n/a
1648n/a
1649n/a/*[clinic input]
1650n/aoct as builtin_oct
1651n/a
1652n/a number: object
1653n/a /
1654n/a
1655n/aReturn the octal representation of an integer.
1656n/a
1657n/a >>> oct(342391)
1658n/a '0o1234567'
1659n/a[clinic start generated code]*/
1660n/a
1661n/astatic PyObject *
1662n/abuiltin_oct(PyObject *module, PyObject *number)
1663n/a/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
1664n/a{
1665n/a return PyNumber_ToBase(number, 8);
1666n/a}
1667n/a
1668n/a
1669n/a/*[clinic input]
1670n/aord as builtin_ord
1671n/a
1672n/a c: object
1673n/a /
1674n/a
1675n/aReturn the Unicode code point for a one-character string.
1676n/a[clinic start generated code]*/
1677n/a
1678n/astatic PyObject *
1679n/abuiltin_ord(PyObject *module, PyObject *c)
1680n/a/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
1681n/a{
1682n/a long ord;
1683n/a Py_ssize_t size;
1684n/a
1685n/a if (PyBytes_Check(c)) {
1686n/a size = PyBytes_GET_SIZE(c);
1687n/a if (size == 1) {
1688n/a ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
1689n/a return PyLong_FromLong(ord);
1690n/a }
1691n/a }
1692n/a else if (PyUnicode_Check(c)) {
1693n/a if (PyUnicode_READY(c) == -1)
1694n/a return NULL;
1695n/a size = PyUnicode_GET_LENGTH(c);
1696n/a if (size == 1) {
1697n/a ord = (long)PyUnicode_READ_CHAR(c, 0);
1698n/a return PyLong_FromLong(ord);
1699n/a }
1700n/a }
1701n/a else if (PyByteArray_Check(c)) {
1702n/a /* XXX Hopefully this is temporary */
1703n/a size = PyByteArray_GET_SIZE(c);
1704n/a if (size == 1) {
1705n/a ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
1706n/a return PyLong_FromLong(ord);
1707n/a }
1708n/a }
1709n/a else {
1710n/a PyErr_Format(PyExc_TypeError,
1711n/a "ord() expected string of length 1, but " \
1712n/a "%.200s found", c->ob_type->tp_name);
1713n/a return NULL;
1714n/a }
1715n/a
1716n/a PyErr_Format(PyExc_TypeError,
1717n/a "ord() expected a character, "
1718n/a "but string of length %zd found",
1719n/a size);
1720n/a return NULL;
1721n/a}
1722n/a
1723n/a
1724n/a/*[clinic input]
1725n/apow as builtin_pow
1726n/a
1727n/a x: object
1728n/a y: object
1729n/a z: object = None
1730n/a /
1731n/a
1732n/aEquivalent to x**y (with two arguments) or x**y % z (with three arguments)
1733n/a
1734n/aSome types, such as ints, are able to use a more efficient algorithm when
1735n/ainvoked using the three argument form.
1736n/a[clinic start generated code]*/
1737n/a
1738n/astatic PyObject *
1739n/abuiltin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1740n/a/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
1741n/a{
1742n/a return PyNumber_Power(x, y, z);
1743n/a}
1744n/a
1745n/a
1746n/a/* AC: cannot convert yet, waiting for *args support */
1747n/astatic PyObject *
1748n/abuiltin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
1749n/a{
1750n/a static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1751n/a static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
1752n/a PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
1753n/a int i, err;
1754n/a
1755n/a if (kwnames != NULL &&
1756n/a !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1757n/a &sep, &end, &file, &flush)) {
1758n/a return NULL;
1759n/a }
1760n/a
1761n/a if (file == NULL || file == Py_None) {
1762n/a file = _PySys_GetObjectId(&PyId_stdout);
1763n/a if (file == NULL) {
1764n/a PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1765n/a return NULL;
1766n/a }
1767n/a
1768n/a /* sys.stdout may be None when FILE* stdout isn't connected */
1769n/a if (file == Py_None)
1770n/a Py_RETURN_NONE;
1771n/a }
1772n/a
1773n/a if (sep == Py_None) {
1774n/a sep = NULL;
1775n/a }
1776n/a else if (sep && !PyUnicode_Check(sep)) {
1777n/a PyErr_Format(PyExc_TypeError,
1778n/a "sep must be None or a string, not %.200s",
1779n/a sep->ob_type->tp_name);
1780n/a return NULL;
1781n/a }
1782n/a if (end == Py_None) {
1783n/a end = NULL;
1784n/a }
1785n/a else if (end && !PyUnicode_Check(end)) {
1786n/a PyErr_Format(PyExc_TypeError,
1787n/a "end must be None or a string, not %.200s",
1788n/a end->ob_type->tp_name);
1789n/a return NULL;
1790n/a }
1791n/a
1792n/a for (i = 0; i < nargs; i++) {
1793n/a if (i > 0) {
1794n/a if (sep == NULL)
1795n/a err = PyFile_WriteString(" ", file);
1796n/a else
1797n/a err = PyFile_WriteObject(sep, file,
1798n/a Py_PRINT_RAW);
1799n/a if (err)
1800n/a return NULL;
1801n/a }
1802n/a err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
1803n/a if (err)
1804n/a return NULL;
1805n/a }
1806n/a
1807n/a if (end == NULL)
1808n/a err = PyFile_WriteString("\n", file);
1809n/a else
1810n/a err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1811n/a if (err)
1812n/a return NULL;
1813n/a
1814n/a if (flush != NULL) {
1815n/a PyObject *tmp;
1816n/a int do_flush = PyObject_IsTrue(flush);
1817n/a if (do_flush == -1)
1818n/a return NULL;
1819n/a else if (do_flush) {
1820n/a tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
1821n/a if (tmp == NULL)
1822n/a return NULL;
1823n/a else
1824n/a Py_DECREF(tmp);
1825n/a }
1826n/a }
1827n/a
1828n/a Py_RETURN_NONE;
1829n/a}
1830n/a
1831n/aPyDoc_STRVAR(print_doc,
1832n/a"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
1833n/a\n\
1834n/aPrints the values to a stream, or to sys.stdout by default.\n\
1835n/aOptional keyword arguments:\n\
1836n/afile: a file-like object (stream); defaults to the current sys.stdout.\n\
1837n/asep: string inserted between values, default a space.\n\
1838n/aend: string appended after the last value, default a newline.\n\
1839n/aflush: whether to forcibly flush the stream.");
1840n/a
1841n/a
1842n/a/*[clinic input]
1843n/ainput as builtin_input
1844n/a
1845n/a prompt: object(c_default="NULL") = None
1846n/a /
1847n/a
1848n/aRead a string from standard input. The trailing newline is stripped.
1849n/a
1850n/aThe prompt string, if given, is printed to standard output without a
1851n/atrailing newline before reading input.
1852n/a
1853n/aIf the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1854n/aOn *nix systems, readline is used if available.
1855n/a[clinic start generated code]*/
1856n/a
1857n/astatic PyObject *
1858n/abuiltin_input_impl(PyObject *module, PyObject *prompt)
1859n/a/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
1860n/a{
1861n/a PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1862n/a PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1863n/a PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1864n/a PyObject *tmp;
1865n/a long fd;
1866n/a int tty;
1867n/a
1868n/a /* Check that stdin/out/err are intact */
1869n/a if (fin == NULL || fin == Py_None) {
1870n/a PyErr_SetString(PyExc_RuntimeError,
1871n/a "input(): lost sys.stdin");
1872n/a return NULL;
1873n/a }
1874n/a if (fout == NULL || fout == Py_None) {
1875n/a PyErr_SetString(PyExc_RuntimeError,
1876n/a "input(): lost sys.stdout");
1877n/a return NULL;
1878n/a }
1879n/a if (ferr == NULL || ferr == Py_None) {
1880n/a PyErr_SetString(PyExc_RuntimeError,
1881n/a "input(): lost sys.stderr");
1882n/a return NULL;
1883n/a }
1884n/a
1885n/a /* First of all, flush stderr */
1886n/a tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
1887n/a if (tmp == NULL)
1888n/a PyErr_Clear();
1889n/a else
1890n/a Py_DECREF(tmp);
1891n/a
1892n/a /* We should only use (GNU) readline if Python's sys.stdin and
1893n/a sys.stdout are the same as C's stdin and stdout, because we
1894n/a need to pass it those. */
1895n/a tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
1896n/a if (tmp == NULL) {
1897n/a PyErr_Clear();
1898n/a tty = 0;
1899n/a }
1900n/a else {
1901n/a fd = PyLong_AsLong(tmp);
1902n/a Py_DECREF(tmp);
1903n/a if (fd < 0 && PyErr_Occurred())
1904n/a return NULL;
1905n/a tty = fd == fileno(stdin) && isatty(fd);
1906n/a }
1907n/a if (tty) {
1908n/a tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
1909n/a if (tmp == NULL) {
1910n/a PyErr_Clear();
1911n/a tty = 0;
1912n/a }
1913n/a else {
1914n/a fd = PyLong_AsLong(tmp);
1915n/a Py_DECREF(tmp);
1916n/a if (fd < 0 && PyErr_Occurred())
1917n/a return NULL;
1918n/a tty = fd == fileno(stdout) && isatty(fd);
1919n/a }
1920n/a }
1921n/a
1922n/a /* If we're interactive, use (GNU) readline */
1923n/a if (tty) {
1924n/a PyObject *po = NULL;
1925n/a char *promptstr;
1926n/a char *s = NULL;
1927n/a PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1928n/a PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1929n/a const char *stdin_encoding_str, *stdin_errors_str;
1930n/a PyObject *result;
1931n/a size_t len;
1932n/a
1933n/a stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
1934n/a stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
1935n/a if (!stdin_encoding || !stdin_errors)
1936n/a /* stdin is a text stream, so it must have an
1937n/a encoding. */
1938n/a goto _readline_errors;
1939n/a stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1940n/a stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
1941n/a if (!stdin_encoding_str || !stdin_errors_str)
1942n/a goto _readline_errors;
1943n/a tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
1944n/a if (tmp == NULL)
1945n/a PyErr_Clear();
1946n/a else
1947n/a Py_DECREF(tmp);
1948n/a if (prompt != NULL) {
1949n/a /* We have a prompt, encode it as stdout would */
1950n/a const char *stdout_encoding_str, *stdout_errors_str;
1951n/a PyObject *stringpo;
1952n/a stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
1953n/a stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
1954n/a if (!stdout_encoding || !stdout_errors)
1955n/a goto _readline_errors;
1956n/a stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1957n/a stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
1958n/a if (!stdout_encoding_str || !stdout_errors_str)
1959n/a goto _readline_errors;
1960n/a stringpo = PyObject_Str(prompt);
1961n/a if (stringpo == NULL)
1962n/a goto _readline_errors;
1963n/a po = PyUnicode_AsEncodedString(stringpo,
1964n/a stdout_encoding_str, stdout_errors_str);
1965n/a Py_CLEAR(stdout_encoding);
1966n/a Py_CLEAR(stdout_errors);
1967n/a Py_CLEAR(stringpo);
1968n/a if (po == NULL)
1969n/a goto _readline_errors;
1970n/a assert(PyBytes_Check(po));
1971n/a promptstr = PyBytes_AS_STRING(po);
1972n/a }
1973n/a else {
1974n/a po = NULL;
1975n/a promptstr = "";
1976n/a }
1977n/a s = PyOS_Readline(stdin, stdout, promptstr);
1978n/a if (s == NULL) {
1979n/a PyErr_CheckSignals();
1980n/a if (!PyErr_Occurred())
1981n/a PyErr_SetNone(PyExc_KeyboardInterrupt);
1982n/a goto _readline_errors;
1983n/a }
1984n/a
1985n/a len = strlen(s);
1986n/a if (len == 0) {
1987n/a PyErr_SetNone(PyExc_EOFError);
1988n/a result = NULL;
1989n/a }
1990n/a else {
1991n/a if (len > PY_SSIZE_T_MAX) {
1992n/a PyErr_SetString(PyExc_OverflowError,
1993n/a "input: input too long");
1994n/a result = NULL;
1995n/a }
1996n/a else {
1997n/a len--; /* strip trailing '\n' */
1998n/a if (len != 0 && s[len-1] == '\r')
1999n/a len--; /* strip trailing '\r' */
2000n/a result = PyUnicode_Decode(s, len, stdin_encoding_str,
2001n/a stdin_errors_str);
2002n/a }
2003n/a }
2004n/a Py_DECREF(stdin_encoding);
2005n/a Py_DECREF(stdin_errors);
2006n/a Py_XDECREF(po);
2007n/a PyMem_FREE(s);
2008n/a return result;
2009n/a _readline_errors:
2010n/a Py_XDECREF(stdin_encoding);
2011n/a Py_XDECREF(stdout_encoding);
2012n/a Py_XDECREF(stdin_errors);
2013n/a Py_XDECREF(stdout_errors);
2014n/a Py_XDECREF(po);
2015n/a return NULL;
2016n/a }
2017n/a
2018n/a /* Fallback if we're not interactive */
2019n/a if (prompt != NULL) {
2020n/a if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
2021n/a return NULL;
2022n/a }
2023n/a tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
2024n/a if (tmp == NULL)
2025n/a PyErr_Clear();
2026n/a else
2027n/a Py_DECREF(tmp);
2028n/a return PyFile_GetLine(fin, -1);
2029n/a}
2030n/a
2031n/a
2032n/a/*[clinic input]
2033n/arepr as builtin_repr
2034n/a
2035n/a obj: object
2036n/a /
2037n/a
2038n/aReturn the canonical string representation of the object.
2039n/a
2040n/aFor many object types, including most builtins, eval(repr(obj)) == obj.
2041n/a[clinic start generated code]*/
2042n/a
2043n/astatic PyObject *
2044n/abuiltin_repr(PyObject *module, PyObject *obj)
2045n/a/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
2046n/a{
2047n/a return PyObject_Repr(obj);
2048n/a}
2049n/a
2050n/a
2051n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2052n/a * or a semantic change to accept None for "ndigits"
2053n/a */
2054n/astatic PyObject *
2055n/abuiltin_round(PyObject *self, PyObject *args, PyObject *kwds)
2056n/a{
2057n/a PyObject *ndigits = NULL;
2058n/a static char *kwlist[] = {"number", "ndigits", 0};
2059n/a PyObject *number, *round, *result;
2060n/a
2061n/a if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2062n/a kwlist, &number, &ndigits))
2063n/a return NULL;
2064n/a
2065n/a if (Py_TYPE(number)->tp_dict == NULL) {
2066n/a if (PyType_Ready(Py_TYPE(number)) < 0)
2067n/a return NULL;
2068n/a }
2069n/a
2070n/a round = _PyObject_LookupSpecial(number, &PyId___round__);
2071n/a if (round == NULL) {
2072n/a if (!PyErr_Occurred())
2073n/a PyErr_Format(PyExc_TypeError,
2074n/a "type %.100s doesn't define __round__ method",
2075n/a Py_TYPE(number)->tp_name);
2076n/a return NULL;
2077n/a }
2078n/a
2079n/a if (ndigits == NULL || ndigits == Py_None)
2080n/a result = _PyObject_CallNoArg(round);
2081n/a else
2082n/a result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2083n/a Py_DECREF(round);
2084n/a return result;
2085n/a}
2086n/a
2087n/aPyDoc_STRVAR(round_doc,
2088n/a"round(number[, ndigits]) -> number\n\
2089n/a\n\
2090n/aRound a number to a given precision in decimal digits (default 0 digits).\n\
2091n/aThis returns an int when called with one argument, otherwise the\n\
2092n/asame type as the number. ndigits may be negative.");
2093n/a
2094n/a
2095n/a/*AC: we need to keep the kwds dict intact to easily call into the
2096n/a * list.sort method, which isn't currently supported in AC. So we just use
2097n/a * the initially generated signature with a custom implementation.
2098n/a */
2099n/a/* [disabled clinic input]
2100n/asorted as builtin_sorted
2101n/a
2102n/a iterable as seq: object
2103n/a key as keyfunc: object = None
2104n/a reverse: object = False
2105n/a
2106n/aReturn a new list containing all items from the iterable in ascending order.
2107n/a
2108n/aA custom key function can be supplied to customize the sort order, and the
2109n/areverse flag can be set to request the result in descending order.
2110n/a[end disabled clinic input]*/
2111n/a
2112n/aPyDoc_STRVAR(builtin_sorted__doc__,
2113n/a"sorted($module, iterable, /, *, key=None, reverse=False)\n"
2114n/a"--\n"
2115n/a"\n"
2116n/a"Return a new list containing all items from the iterable in ascending order.\n"
2117n/a"\n"
2118n/a"A custom key function can be supplied to customize the sort order, and the\n"
2119n/a"reverse flag can be set to request the result in descending order.");
2120n/a
2121n/a#define BUILTIN_SORTED_METHODDEF \
2122n/a {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL, builtin_sorted__doc__},
2123n/a
2124n/astatic PyObject *
2125n/abuiltin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
2126n/a{
2127n/a PyObject *newlist, *v, *seq, *callable;
2128n/a
2129n/a /* Keyword arguments are passed through list.sort() which will check
2130n/a them. */
2131n/a if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
2132n/a return NULL;
2133n/a
2134n/a newlist = PySequence_List(seq);
2135n/a if (newlist == NULL)
2136n/a return NULL;
2137n/a
2138n/a callable = _PyObject_GetAttrId(newlist, &PyId_sort);
2139n/a if (callable == NULL) {
2140n/a Py_DECREF(newlist);
2141n/a return NULL;
2142n/a }
2143n/a
2144n/a assert(nargs >= 1);
2145n/a v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
2146n/a Py_DECREF(callable);
2147n/a if (v == NULL) {
2148n/a Py_DECREF(newlist);
2149n/a return NULL;
2150n/a }
2151n/a Py_DECREF(v);
2152n/a return newlist;
2153n/a}
2154n/a
2155n/a
2156n/a/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
2157n/astatic PyObject *
2158n/abuiltin_vars(PyObject *self, PyObject *args)
2159n/a{
2160n/a PyObject *v = NULL;
2161n/a PyObject *d;
2162n/a
2163n/a if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2164n/a return NULL;
2165n/a if (v == NULL) {
2166n/a d = PyEval_GetLocals();
2167n/a if (d == NULL)
2168n/a return NULL;
2169n/a Py_INCREF(d);
2170n/a }
2171n/a else {
2172n/a d = _PyObject_GetAttrId(v, &PyId___dict__);
2173n/a if (d == NULL) {
2174n/a PyErr_SetString(PyExc_TypeError,
2175n/a "vars() argument must have __dict__ attribute");
2176n/a return NULL;
2177n/a }
2178n/a }
2179n/a return d;
2180n/a}
2181n/a
2182n/aPyDoc_STRVAR(vars_doc,
2183n/a"vars([object]) -> dictionary\n\
2184n/a\n\
2185n/aWithout arguments, equivalent to locals().\n\
2186n/aWith an argument, equivalent to object.__dict__.");
2187n/a
2188n/a
2189n/a/*[clinic input]
2190n/asum as builtin_sum
2191n/a
2192n/a iterable: object
2193n/a start: object(c_default="NULL") = 0
2194n/a /
2195n/a
2196n/aReturn the sum of a 'start' value (default: 0) plus an iterable of numbers
2197n/a
2198n/aWhen the iterable is empty, return the start value.
2199n/aThis function is intended specifically for use with numeric values and may
2200n/areject non-numeric types.
2201n/a[clinic start generated code]*/
2202n/a
2203n/astatic PyObject *
2204n/abuiltin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2205n/a/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
2206n/a{
2207n/a PyObject *result = start;
2208n/a PyObject *temp, *item, *iter;
2209n/a
2210n/a iter = PyObject_GetIter(iterable);
2211n/a if (iter == NULL)
2212n/a return NULL;
2213n/a
2214n/a if (result == NULL) {
2215n/a result = PyLong_FromLong(0);
2216n/a if (result == NULL) {
2217n/a Py_DECREF(iter);
2218n/a return NULL;
2219n/a }
2220n/a } else {
2221n/a /* reject string values for 'start' parameter */
2222n/a if (PyUnicode_Check(result)) {
2223n/a PyErr_SetString(PyExc_TypeError,
2224n/a "sum() can't sum strings [use ''.join(seq) instead]");
2225n/a Py_DECREF(iter);
2226n/a return NULL;
2227n/a }
2228n/a if (PyBytes_Check(result)) {
2229n/a PyErr_SetString(PyExc_TypeError,
2230n/a "sum() can't sum bytes [use b''.join(seq) instead]");
2231n/a Py_DECREF(iter);
2232n/a return NULL;
2233n/a }
2234n/a if (PyByteArray_Check(result)) {
2235n/a PyErr_SetString(PyExc_TypeError,
2236n/a "sum() can't sum bytearray [use b''.join(seq) instead]");
2237n/a Py_DECREF(iter);
2238n/a return NULL;
2239n/a }
2240n/a Py_INCREF(result);
2241n/a }
2242n/a
2243n/a#ifndef SLOW_SUM
2244n/a /* Fast addition by keeping temporary sums in C instead of new Python objects.
2245n/a Assumes all inputs are the same type. If the assumption fails, default
2246n/a to the more general routine.
2247n/a */
2248n/a if (PyLong_CheckExact(result)) {
2249n/a int overflow;
2250n/a long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2251n/a /* If this already overflowed, don't even enter the loop. */
2252n/a if (overflow == 0) {
2253n/a Py_DECREF(result);
2254n/a result = NULL;
2255n/a }
2256n/a while(result == NULL) {
2257n/a item = PyIter_Next(iter);
2258n/a if (item == NULL) {
2259n/a Py_DECREF(iter);
2260n/a if (PyErr_Occurred())
2261n/a return NULL;
2262n/a return PyLong_FromLong(i_result);
2263n/a }
2264n/a if (PyLong_CheckExact(item)) {
2265n/a long b = PyLong_AsLongAndOverflow(item, &overflow);
2266n/a long x = i_result + b;
2267n/a if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2268n/a i_result = x;
2269n/a Py_DECREF(item);
2270n/a continue;
2271n/a }
2272n/a }
2273n/a /* Either overflowed or is not an int. Restore real objects and process normally */
2274n/a result = PyLong_FromLong(i_result);
2275n/a if (result == NULL) {
2276n/a Py_DECREF(item);
2277n/a Py_DECREF(iter);
2278n/a return NULL;
2279n/a }
2280n/a temp = PyNumber_Add(result, item);
2281n/a Py_DECREF(result);
2282n/a Py_DECREF(item);
2283n/a result = temp;
2284n/a if (result == NULL) {
2285n/a Py_DECREF(iter);
2286n/a return NULL;
2287n/a }
2288n/a }
2289n/a }
2290n/a
2291n/a if (PyFloat_CheckExact(result)) {
2292n/a double f_result = PyFloat_AS_DOUBLE(result);
2293n/a Py_DECREF(result);
2294n/a result = NULL;
2295n/a while(result == NULL) {
2296n/a item = PyIter_Next(iter);
2297n/a if (item == NULL) {
2298n/a Py_DECREF(iter);
2299n/a if (PyErr_Occurred())
2300n/a return NULL;
2301n/a return PyFloat_FromDouble(f_result);
2302n/a }
2303n/a if (PyFloat_CheckExact(item)) {
2304n/a PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2305n/a f_result += PyFloat_AS_DOUBLE(item);
2306n/a PyFPE_END_PROTECT(f_result)
2307n/a Py_DECREF(item);
2308n/a continue;
2309n/a }
2310n/a if (PyLong_CheckExact(item)) {
2311n/a long value;
2312n/a int overflow;
2313n/a value = PyLong_AsLongAndOverflow(item, &overflow);
2314n/a if (!overflow) {
2315n/a PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2316n/a f_result += (double)value;
2317n/a PyFPE_END_PROTECT(f_result)
2318n/a Py_DECREF(item);
2319n/a continue;
2320n/a }
2321n/a }
2322n/a result = PyFloat_FromDouble(f_result);
2323n/a temp = PyNumber_Add(result, item);
2324n/a Py_DECREF(result);
2325n/a Py_DECREF(item);
2326n/a result = temp;
2327n/a if (result == NULL) {
2328n/a Py_DECREF(iter);
2329n/a return NULL;
2330n/a }
2331n/a }
2332n/a }
2333n/a#endif
2334n/a
2335n/a for(;;) {
2336n/a item = PyIter_Next(iter);
2337n/a if (item == NULL) {
2338n/a /* error, or end-of-sequence */
2339n/a if (PyErr_Occurred()) {
2340n/a Py_DECREF(result);
2341n/a result = NULL;
2342n/a }
2343n/a break;
2344n/a }
2345n/a /* It's tempting to use PyNumber_InPlaceAdd instead of
2346n/a PyNumber_Add here, to avoid quadratic running time
2347n/a when doing 'sum(list_of_lists, [])'. However, this
2348n/a would produce a change in behaviour: a snippet like
2349n/a
2350n/a empty = []
2351n/a sum([[x] for x in range(10)], empty)
2352n/a
2353n/a would change the value of empty. */
2354n/a temp = PyNumber_Add(result, item);
2355n/a Py_DECREF(result);
2356n/a Py_DECREF(item);
2357n/a result = temp;
2358n/a if (result == NULL)
2359n/a break;
2360n/a }
2361n/a Py_DECREF(iter);
2362n/a return result;
2363n/a}
2364n/a
2365n/a
2366n/a/*[clinic input]
2367n/aisinstance as builtin_isinstance
2368n/a
2369n/a obj: object
2370n/a class_or_tuple: object
2371n/a /
2372n/a
2373n/aReturn whether an object is an instance of a class or of a subclass thereof.
2374n/a
2375n/aA tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2376n/acheck against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2377n/aor ...`` etc.
2378n/a[clinic start generated code]*/
2379n/a
2380n/astatic PyObject *
2381n/abuiltin_isinstance_impl(PyObject *module, PyObject *obj,
2382n/a PyObject *class_or_tuple)
2383n/a/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
2384n/a{
2385n/a int retval;
2386n/a
2387n/a retval = PyObject_IsInstance(obj, class_or_tuple);
2388n/a if (retval < 0)
2389n/a return NULL;
2390n/a return PyBool_FromLong(retval);
2391n/a}
2392n/a
2393n/a
2394n/a/*[clinic input]
2395n/aissubclass as builtin_issubclass
2396n/a
2397n/a cls: object
2398n/a class_or_tuple: object
2399n/a /
2400n/a
2401n/aReturn whether 'cls' is a derived from another class or is the same class.
2402n/a
2403n/aA tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2404n/acheck against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2405n/aor ...`` etc.
2406n/a[clinic start generated code]*/
2407n/a
2408n/astatic PyObject *
2409n/abuiltin_issubclass_impl(PyObject *module, PyObject *cls,
2410n/a PyObject *class_or_tuple)
2411n/a/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
2412n/a{
2413n/a int retval;
2414n/a
2415n/a retval = PyObject_IsSubclass(cls, class_or_tuple);
2416n/a if (retval < 0)
2417n/a return NULL;
2418n/a return PyBool_FromLong(retval);
2419n/a}
2420n/a
2421n/a
2422n/atypedef struct {
2423n/a PyObject_HEAD
2424n/a Py_ssize_t tuplesize;
2425n/a PyObject *ittuple; /* tuple of iterators */
2426n/a PyObject *result;
2427n/a} zipobject;
2428n/a
2429n/astatic PyObject *
2430n/azip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2431n/a{
2432n/a zipobject *lz;
2433n/a Py_ssize_t i;
2434n/a PyObject *ittuple; /* tuple of iterators */
2435n/a PyObject *result;
2436n/a Py_ssize_t tuplesize = PySequence_Length(args);
2437n/a
2438n/a if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2439n/a return NULL;
2440n/a
2441n/a /* args must be a tuple */
2442n/a assert(PyTuple_Check(args));
2443n/a
2444n/a /* obtain iterators */
2445n/a ittuple = PyTuple_New(tuplesize);
2446n/a if (ittuple == NULL)
2447n/a return NULL;
2448n/a for (i=0; i < tuplesize; ++i) {
2449n/a PyObject *item = PyTuple_GET_ITEM(args, i);
2450n/a PyObject *it = PyObject_GetIter(item);
2451n/a if (it == NULL) {
2452n/a if (PyErr_ExceptionMatches(PyExc_TypeError))
2453n/a PyErr_Format(PyExc_TypeError,
2454n/a "zip argument #%zd must support iteration",
2455n/a i+1);
2456n/a Py_DECREF(ittuple);
2457n/a return NULL;
2458n/a }
2459n/a PyTuple_SET_ITEM(ittuple, i, it);
2460n/a }
2461n/a
2462n/a /* create a result holder */
2463n/a result = PyTuple_New(tuplesize);
2464n/a if (result == NULL) {
2465n/a Py_DECREF(ittuple);
2466n/a return NULL;
2467n/a }
2468n/a for (i=0 ; i < tuplesize ; i++) {
2469n/a Py_INCREF(Py_None);
2470n/a PyTuple_SET_ITEM(result, i, Py_None);
2471n/a }
2472n/a
2473n/a /* create zipobject structure */
2474n/a lz = (zipobject *)type->tp_alloc(type, 0);
2475n/a if (lz == NULL) {
2476n/a Py_DECREF(ittuple);
2477n/a Py_DECREF(result);
2478n/a return NULL;
2479n/a }
2480n/a lz->ittuple = ittuple;
2481n/a lz->tuplesize = tuplesize;
2482n/a lz->result = result;
2483n/a
2484n/a return (PyObject *)lz;
2485n/a}
2486n/a
2487n/astatic void
2488n/azip_dealloc(zipobject *lz)
2489n/a{
2490n/a PyObject_GC_UnTrack(lz);
2491n/a Py_XDECREF(lz->ittuple);
2492n/a Py_XDECREF(lz->result);
2493n/a Py_TYPE(lz)->tp_free(lz);
2494n/a}
2495n/a
2496n/astatic int
2497n/azip_traverse(zipobject *lz, visitproc visit, void *arg)
2498n/a{
2499n/a Py_VISIT(lz->ittuple);
2500n/a Py_VISIT(lz->result);
2501n/a return 0;
2502n/a}
2503n/a
2504n/astatic PyObject *
2505n/azip_next(zipobject *lz)
2506n/a{
2507n/a Py_ssize_t i;
2508n/a Py_ssize_t tuplesize = lz->tuplesize;
2509n/a PyObject *result = lz->result;
2510n/a PyObject *it;
2511n/a PyObject *item;
2512n/a PyObject *olditem;
2513n/a
2514n/a if (tuplesize == 0)
2515n/a return NULL;
2516n/a if (Py_REFCNT(result) == 1) {
2517n/a Py_INCREF(result);
2518n/a for (i=0 ; i < tuplesize ; i++) {
2519n/a it = PyTuple_GET_ITEM(lz->ittuple, i);
2520n/a item = (*Py_TYPE(it)->tp_iternext)(it);
2521n/a if (item == NULL) {
2522n/a Py_DECREF(result);
2523n/a return NULL;
2524n/a }
2525n/a olditem = PyTuple_GET_ITEM(result, i);
2526n/a PyTuple_SET_ITEM(result, i, item);
2527n/a Py_DECREF(olditem);
2528n/a }
2529n/a } else {
2530n/a result = PyTuple_New(tuplesize);
2531n/a if (result == NULL)
2532n/a return NULL;
2533n/a for (i=0 ; i < tuplesize ; i++) {
2534n/a it = PyTuple_GET_ITEM(lz->ittuple, i);
2535n/a item = (*Py_TYPE(it)->tp_iternext)(it);
2536n/a if (item == NULL) {
2537n/a Py_DECREF(result);
2538n/a return NULL;
2539n/a }
2540n/a PyTuple_SET_ITEM(result, i, item);
2541n/a }
2542n/a }
2543n/a return result;
2544n/a}
2545n/a
2546n/astatic PyObject *
2547n/azip_reduce(zipobject *lz)
2548n/a{
2549n/a /* Just recreate the zip with the internal iterator tuple */
2550n/a return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2551n/a}
2552n/a
2553n/astatic PyMethodDef zip_methods[] = {
2554n/a {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2555n/a {NULL, NULL} /* sentinel */
2556n/a};
2557n/a
2558n/aPyDoc_STRVAR(zip_doc,
2559n/a"zip(iter1 [,iter2 [...]]) --> zip object\n\
2560n/a\n\
2561n/aReturn a zip object whose .__next__() method returns a tuple where\n\
2562n/athe i-th element comes from the i-th iterable argument. The .__next__()\n\
2563n/amethod continues until the shortest iterable in the argument sequence\n\
2564n/ais exhausted and then it raises StopIteration.");
2565n/a
2566n/aPyTypeObject PyZip_Type = {
2567n/a PyVarObject_HEAD_INIT(&PyType_Type, 0)
2568n/a "zip", /* tp_name */
2569n/a sizeof(zipobject), /* tp_basicsize */
2570n/a 0, /* tp_itemsize */
2571n/a /* methods */
2572n/a (destructor)zip_dealloc, /* tp_dealloc */
2573n/a 0, /* tp_print */
2574n/a 0, /* tp_getattr */
2575n/a 0, /* tp_setattr */
2576n/a 0, /* tp_reserved */
2577n/a 0, /* tp_repr */
2578n/a 0, /* tp_as_number */
2579n/a 0, /* tp_as_sequence */
2580n/a 0, /* tp_as_mapping */
2581n/a 0, /* tp_hash */
2582n/a 0, /* tp_call */
2583n/a 0, /* tp_str */
2584n/a PyObject_GenericGetAttr, /* tp_getattro */
2585n/a 0, /* tp_setattro */
2586n/a 0, /* tp_as_buffer */
2587n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2588n/a Py_TPFLAGS_BASETYPE, /* tp_flags */
2589n/a zip_doc, /* tp_doc */
2590n/a (traverseproc)zip_traverse, /* tp_traverse */
2591n/a 0, /* tp_clear */
2592n/a 0, /* tp_richcompare */
2593n/a 0, /* tp_weaklistoffset */
2594n/a PyObject_SelfIter, /* tp_iter */
2595n/a (iternextfunc)zip_next, /* tp_iternext */
2596n/a zip_methods, /* tp_methods */
2597n/a 0, /* tp_members */
2598n/a 0, /* tp_getset */
2599n/a 0, /* tp_base */
2600n/a 0, /* tp_dict */
2601n/a 0, /* tp_descr_get */
2602n/a 0, /* tp_descr_set */
2603n/a 0, /* tp_dictoffset */
2604n/a 0, /* tp_init */
2605n/a PyType_GenericAlloc, /* tp_alloc */
2606n/a zip_new, /* tp_new */
2607n/a PyObject_GC_Del, /* tp_free */
2608n/a};
2609n/a
2610n/a
2611n/astatic PyMethodDef builtin_methods[] = {
2612n/a {"__build_class__", (PyCFunction)builtin___build_class__,
2613n/a METH_FASTCALL, build_class_doc},
2614n/a {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2615n/a BUILTIN_ABS_METHODDEF
2616n/a BUILTIN_ALL_METHODDEF
2617n/a BUILTIN_ANY_METHODDEF
2618n/a BUILTIN_ASCII_METHODDEF
2619n/a BUILTIN_BIN_METHODDEF
2620n/a BUILTIN_CALLABLE_METHODDEF
2621n/a BUILTIN_CHR_METHODDEF
2622n/a BUILTIN_COMPILE_METHODDEF
2623n/a BUILTIN_DELATTR_METHODDEF
2624n/a {"dir", builtin_dir, METH_VARARGS, dir_doc},
2625n/a BUILTIN_DIVMOD_METHODDEF
2626n/a BUILTIN_EVAL_METHODDEF
2627n/a BUILTIN_EXEC_METHODDEF
2628n/a BUILTIN_FORMAT_METHODDEF
2629n/a {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
2630n/a BUILTIN_GLOBALS_METHODDEF
2631n/a BUILTIN_HASATTR_METHODDEF
2632n/a BUILTIN_HASH_METHODDEF
2633n/a BUILTIN_HEX_METHODDEF
2634n/a BUILTIN_ID_METHODDEF
2635n/a BUILTIN_INPUT_METHODDEF
2636n/a BUILTIN_ISINSTANCE_METHODDEF
2637n/a BUILTIN_ISSUBCLASS_METHODDEF
2638n/a {"iter", builtin_iter, METH_VARARGS, iter_doc},
2639n/a BUILTIN_LEN_METHODDEF
2640n/a BUILTIN_LOCALS_METHODDEF
2641n/a {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2642n/a {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2643n/a {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
2644n/a BUILTIN_OCT_METHODDEF
2645n/a BUILTIN_ORD_METHODDEF
2646n/a BUILTIN_POW_METHODDEF
2647n/a {"print", (PyCFunction)builtin_print, METH_FASTCALL, print_doc},
2648n/a BUILTIN_REPR_METHODDEF
2649n/a {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2650n/a BUILTIN_SETATTR_METHODDEF
2651n/a BUILTIN_SORTED_METHODDEF
2652n/a BUILTIN_SUM_METHODDEF
2653n/a {"vars", builtin_vars, METH_VARARGS, vars_doc},
2654n/a {NULL, NULL},
2655n/a};
2656n/a
2657n/aPyDoc_STRVAR(builtin_doc,
2658n/a"Built-in functions, exceptions, and other objects.\n\
2659n/a\n\
2660n/aNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2661n/a
2662n/astatic struct PyModuleDef builtinsmodule = {
2663n/a PyModuleDef_HEAD_INIT,
2664n/a "builtins",
2665n/a builtin_doc,
2666n/a -1, /* multiple "initialization" just copies the module dict. */
2667n/a builtin_methods,
2668n/a NULL,
2669n/a NULL,
2670n/a NULL,
2671n/a NULL
2672n/a};
2673n/a
2674n/a
2675n/aPyObject *
2676n/a_PyBuiltin_Init(void)
2677n/a{
2678n/a PyObject *mod, *dict, *debug;
2679n/a
2680n/a if (PyType_Ready(&PyFilter_Type) < 0 ||
2681n/a PyType_Ready(&PyMap_Type) < 0 ||
2682n/a PyType_Ready(&PyZip_Type) < 0)
2683n/a return NULL;
2684n/a
2685n/a mod = PyModule_Create(&builtinsmodule);
2686n/a if (mod == NULL)
2687n/a return NULL;
2688n/a dict = PyModule_GetDict(mod);
2689n/a
2690n/a#ifdef Py_TRACE_REFS
2691n/a /* "builtins" exposes a number of statically allocated objects
2692n/a * that, before this code was added in 2.3, never showed up in
2693n/a * the list of "all objects" maintained by Py_TRACE_REFS. As a
2694n/a * result, programs leaking references to None and False (etc)
2695n/a * couldn't be diagnosed by examining sys.getobjects(0).
2696n/a */
2697n/a#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2698n/a#else
2699n/a#define ADD_TO_ALL(OBJECT) (void)0
2700n/a#endif
2701n/a
2702n/a#define SETBUILTIN(NAME, OBJECT) \
2703n/a if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2704n/a return NULL; \
2705n/a ADD_TO_ALL(OBJECT)
2706n/a
2707n/a SETBUILTIN("None", Py_None);
2708n/a SETBUILTIN("Ellipsis", Py_Ellipsis);
2709n/a SETBUILTIN("NotImplemented", Py_NotImplemented);
2710n/a SETBUILTIN("False", Py_False);
2711n/a SETBUILTIN("True", Py_True);
2712n/a SETBUILTIN("bool", &PyBool_Type);
2713n/a SETBUILTIN("memoryview", &PyMemoryView_Type);
2714n/a SETBUILTIN("bytearray", &PyByteArray_Type);
2715n/a SETBUILTIN("bytes", &PyBytes_Type);
2716n/a SETBUILTIN("classmethod", &PyClassMethod_Type);
2717n/a SETBUILTIN("complex", &PyComplex_Type);
2718n/a SETBUILTIN("dict", &PyDict_Type);
2719n/a SETBUILTIN("enumerate", &PyEnum_Type);
2720n/a SETBUILTIN("filter", &PyFilter_Type);
2721n/a SETBUILTIN("float", &PyFloat_Type);
2722n/a SETBUILTIN("frozenset", &PyFrozenSet_Type);
2723n/a SETBUILTIN("property", &PyProperty_Type);
2724n/a SETBUILTIN("int", &PyLong_Type);
2725n/a SETBUILTIN("list", &PyList_Type);
2726n/a SETBUILTIN("map", &PyMap_Type);
2727n/a SETBUILTIN("object", &PyBaseObject_Type);
2728n/a SETBUILTIN("range", &PyRange_Type);
2729n/a SETBUILTIN("reversed", &PyReversed_Type);
2730n/a SETBUILTIN("set", &PySet_Type);
2731n/a SETBUILTIN("slice", &PySlice_Type);
2732n/a SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2733n/a SETBUILTIN("str", &PyUnicode_Type);
2734n/a SETBUILTIN("super", &PySuper_Type);
2735n/a SETBUILTIN("tuple", &PyTuple_Type);
2736n/a SETBUILTIN("type", &PyType_Type);
2737n/a SETBUILTIN("zip", &PyZip_Type);
2738n/a debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2739n/a if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2740n/a Py_DECREF(debug);
2741n/a return NULL;
2742n/a }
2743n/a Py_DECREF(debug);
2744n/a
2745n/a return mod;
2746n/a#undef ADD_TO_ALL
2747n/a#undef SETBUILTIN
2748n/a}