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