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