summaryrefslogtreecommitdiffstats
path: root/contrib/tools/python3/Python/bltinmodule.c
diff options
context:
space:
mode:
Diffstat (limited to 'contrib/tools/python3/Python/bltinmodule.c')
-rw-r--r--contrib/tools/python3/Python/bltinmodule.c593
1 files changed, 337 insertions, 256 deletions
diff --git a/contrib/tools/python3/Python/bltinmodule.c b/contrib/tools/python3/Python/bltinmodule.c
index 1a65ddd0154..bcf7e7355da 100644
--- a/contrib/tools/python3/Python/bltinmodule.c
+++ b/contrib/tools/python3/Python/bltinmodule.c
@@ -1,19 +1,26 @@
/* Built-in functions */
#include "Python.h"
-#include <ctype.h>
#include "pycore_ast.h" // _PyAST_Validate()
#include "pycore_call.h" // _PyObject_CallNoArgs()
+#include "pycore_ceval.h" // _PyEval_Vector()
#include "pycore_compile.h" // _PyAST_Compile()
#include "pycore_long.h" // _PyLong_CompactValue
+#include "pycore_modsupport.h" // _PyArg_NoKwnames()
#include "pycore_object.h" // _Py_AddToAllObjects()
#include "pycore_pyerrors.h" // _PyErr_NoMemory()
#include "pycore_pystate.h" // _PyThreadState_GET()
+#include "pycore_pythonrun.h" // _Py_SourceAsString()
+#include "pycore_sysmodule.h" // _PySys_GetRequiredAttr()
#include "pycore_tuple.h" // _PyTuple_FromArray()
-#include "pycore_ceval.h" // _PyEval_Vector()
#include "clinic/bltinmodule.c.h"
+#ifdef HAVE_UNISTD_H
+# include <unistd.h> // isatty()
+#endif
+
+
static PyObject*
update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
{
@@ -33,7 +40,7 @@ update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
}
continue;
}
- if (_PyObject_LookupAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
+ if (PyObject_GetOptionalAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
goto error;
}
if (!meth) {
@@ -133,18 +140,13 @@ builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
goto error;
}
- meta = _PyDict_GetItemWithError(mkw, &_Py_ID(metaclass));
+ if (PyDict_Pop(mkw, &_Py_ID(metaclass), &meta) < 0) {
+ goto error;
+ }
if (meta != NULL) {
- Py_INCREF(meta);
- if (PyDict_DelItem(mkw, &_Py_ID(metaclass)) < 0) {
- goto error;
- }
/* metaclass is explicitly given, check if it's indeed a class */
isclass = PyType_Check(meta);
}
- else if (PyErr_Occurred()) {
- goto error;
- }
}
if (meta == NULL) {
/* if there are no bases, use type: */
@@ -174,7 +176,7 @@ builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
}
/* else: meta is not a class, so we cannot do the metaclass
calculation, so we will use the explicitly given object as it is */
- if (_PyObject_LookupAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
+ if (PyObject_GetOptionalAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
ns = NULL;
}
else if (prep == NULL) {
@@ -455,25 +457,24 @@ builtin_callable(PyObject *module, PyObject *obj)
static PyObject *
builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
{
- PyObject *hook = PySys_GetObject("breakpointhook");
-
+ PyObject *hook = _PySys_GetRequiredAttrString("breakpointhook");
if (hook == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
return NULL;
}
if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
+ Py_DECREF(hook);
return NULL;
}
- Py_INCREF(hook);
PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Py_DECREF(hook);
return retval;
}
PyDoc_STRVAR(breakpoint_doc,
-"breakpoint(*args, **kws)\n\
+"breakpoint($module, /, *args, **kws)\n\
+--\n\
\n\
Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
whatever arguments are passed.\n\
@@ -618,7 +619,8 @@ static PyMethodDef filter_methods[] = {
};
PyDoc_STRVAR(filter_doc,
-"filter(function or None, iterable) --> filter object\n\
+"filter(function, iterable, /)\n\
+--\n\
\n\
Return an iterator yielding those items of iterable for which function(item)\n\
is true. If function is None, return the items that are true.");
@@ -696,17 +698,34 @@ builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
/*[clinic input]
chr as builtin_chr
- i: int
+ i: object
/
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
[clinic start generated code]*/
static PyObject *
-builtin_chr_impl(PyObject *module, int i)
-/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
+builtin_chr(PyObject *module, PyObject *i)
+/*[clinic end generated code: output=d34f25b8035a9b10 input=f919867f0ba2f496]*/
{
- return PyUnicode_FromOrdinal(i);
+ int overflow;
+ long v = PyLong_AsLongAndOverflow(i, &overflow);
+ if (v == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ if (overflow) {
+ v = overflow < 0 ? INT_MIN : INT_MAX;
+ /* Allow PyUnicode_FromOrdinal() to raise an exception */
+ }
+#if SIZEOF_INT < SIZEOF_LONG
+ else if (v < INT_MIN) {
+ v = INT_MIN;
+ }
+ else if (v > INT_MAX) {
+ v = INT_MAX;
+ }
+#endif
+ return PyUnicode_FromOrdinal(v);
}
@@ -714,7 +733,7 @@ builtin_chr_impl(PyObject *module, int i)
compile as builtin_compile
source: object
- filename: object(converter="PyUnicode_FSDecoder")
+ filename: unicode_fs_decoded
mode: str
flags: int = 0
dont_inherit: bool = False
@@ -740,7 +759,7 @@ static PyObject *
builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
const char *mode, int flags, int dont_inherit,
int optimize, int feature_version)
-/*[clinic end generated code: output=b0c09c84f116d3d7 input=cc78e20e7c7682ba]*/
+/*[clinic end generated code: output=b0c09c84f116d3d7 input=8f0069edbdac381b]*/
{
PyObject *source_copy;
const char *str;
@@ -802,23 +821,40 @@ builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
if (is_ast == -1)
goto error;
if (is_ast) {
- if (flags & PyCF_ONLY_AST) {
+ if ((flags & PyCF_OPTIMIZED_AST) == PyCF_ONLY_AST) {
+ // return an un-optimized AST
result = Py_NewRef(source);
}
else {
- PyArena *arena;
- mod_ty mod;
+ // Return an optimized AST or code object
- arena = _PyArena_New();
- if (arena == NULL)
- goto error;
- mod = PyAST_obj2mod(source, arena, compile_mode);
- if (mod == NULL || !_PyAST_Validate(mod)) {
- _PyArena_Free(arena);
+ PyArena *arena = _PyArena_New();
+ if (arena == NULL) {
goto error;
}
- result = (PyObject*)_PyAST_Compile(mod, filename,
- &cf, optimize, arena);
+
+ if (flags & PyCF_ONLY_AST) {
+ mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
+ if (mod == NULL || !_PyAST_Validate(mod)) {
+ _PyArena_Free(arena);
+ goto error;
+ }
+ if (_PyCompile_AstOptimize(mod, filename, &cf, optimize,
+ arena) < 0) {
+ _PyArena_Free(arena);
+ goto error;
+ }
+ result = PyAST_mod2obj(mod);
+ }
+ else {
+ mod_ty mod = PyAST_obj2mod(source, arena, compile_mode);
+ if (mod == NULL || !_PyAST_Validate(mod)) {
+ _PyArena_Free(arena);
+ goto error;
+ }
+ result = (PyObject*)_PyAST_Compile(mod, filename,
+ &cf, optimize, arena);
+ }
_PyArena_Free(arena);
}
goto finally;
@@ -828,45 +864,55 @@ builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
if (str == NULL)
goto error;
+#ifdef Py_GIL_DISABLED
+ // gh-118527: Disable immortalization of code constants for explicit
+ // compile() calls to get consistent frozen outputs between the default
+ // and free-threaded builds.
+ // Subtract two to suppress immortalization (so that 1 -> -1)
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ _Py_atomic_add_int(&interp->gc.immortalize, -2);
+#endif
+
result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
+#ifdef Py_GIL_DISABLED
+ _Py_atomic_add_int(&interp->gc.immortalize, 2);
+#endif
+
Py_XDECREF(source_copy);
goto finally;
error:
result = NULL;
finally:
- Py_DECREF(filename);
return result;
}
-/*[clinic input]
-dir as builtin_dir
-
- arg: object = NULL
- /
-
-Show attributes of an object.
-
-If called without an argument, return the names in the current scope.
-Else, return an alphabetized list of names comprising (some of) the attributes
-of the given object, and of attributes reachable from it.
-If the object supplies a method named __dir__, it will be used; otherwise
-the default dir() logic is used and returns:
- for a module object: the module's attributes.
- for a class object: its attributes, and recursively the attributes
- of its bases.
- for any other object: its attributes, its class's attributes, and
- recursively the attributes of its class's base classes.
-[clinic start generated code]*/
-
+/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
static PyObject *
-builtin_dir_impl(PyObject *module, PyObject *arg)
-/*[clinic end generated code: output=24f2c7a52c1e3b08 input=ed6d6ccb13d52251]*/
+builtin_dir(PyObject *self, PyObject *args)
{
+ PyObject *arg = NULL;
+
+ if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
+ return NULL;
return PyObject_Dir(arg);
}
+PyDoc_STRVAR(dir_doc,
+"dir([object]) -> list of strings\n"
+"\n"
+"If called without an argument, return the names in the current scope.\n"
+"Else, return an alphabetized list of names comprising (some of) the attributes\n"
+"of the given object, and of attributes reachable from it.\n"
+"If the object supplies a method named __dir__, it will be used; otherwise\n"
+"the default dir() logic is used and returns:\n"
+" for a module object: the module's attributes.\n"
+" for a class object: its attributes, and recursively the attributes\n"
+" of its bases.\n"
+" for any other object: its attributes, its class's attributes, and\n"
+" recursively the attributes of its class's base classes.");
+
/*[clinic input]
divmod as builtin_divmod
@@ -889,9 +935,9 @@ builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
eval as builtin_eval
source: object
+ /
globals: object = None
locals: object = None
- /
Evaluate the given source in the context of globals and locals.
@@ -905,7 +951,7 @@ If only globals is given, locals defaults to it.
static PyObject *
builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
PyObject *locals)
-/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
+/*[clinic end generated code: output=0a0824aa70093116 input=7c7bce5299a89062]*/
{
PyObject *result = NULL, *source_copy;
const char *str;
@@ -988,9 +1034,9 @@ builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
exec as builtin_exec
source: object
+ /
globals: object = None
locals: object = None
- /
*
closure: object(c_default="NULL") = None
@@ -1008,7 +1054,7 @@ when source is a code object requiring exactly that many cellvars.
static PyObject *
builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
PyObject *locals, PyObject *closure)
-/*[clinic end generated code: output=7579eb4e7646743d input=f13a7e2b503d1d9a]*/
+/*[clinic end generated code: output=7579eb4e7646743d input=25e989b6d87a3a21]*/
{
PyObject *v;
@@ -1107,6 +1153,7 @@ builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
if (closure != NULL) {
PyErr_SetString(PyExc_TypeError,
"closure can only be used when source is a code object");
+ goto error;
}
PyObject *source_copy;
const char *str;
@@ -1136,39 +1183,36 @@ builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
}
-/*[clinic input]
-getattr as builtin_getattr
-
- object: object
- name: object
- default: object = NULL
- /
-
-Get a named attribute from an object.
-
-getattr(x, 'y') is equivalent to x.y
-When a default argument is given, it is returned when the attribute doesn't
-exist; without it, an exception is raised in that case.
-[clinic start generated code]*/
-
+/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
static PyObject *
-builtin_getattr_impl(PyObject *module, PyObject *object, PyObject *name,
- PyObject *default_value)
-/*[clinic end generated code: output=74ad0e225e3f701c input=d7562cd4c3556171]*/
+builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
- PyObject *result;
+ PyObject *v, *name, *result;
- if (default_value != NULL) {
- if (_PyObject_LookupAttr(object, name, &result) == 0) {
- return Py_NewRef(default_value);
+ if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
+ return NULL;
+
+ v = args[0];
+ name = args[1];
+ if (nargs > 2) {
+ if (PyObject_GetOptionalAttr(v, name, &result) == 0) {
+ PyObject *dflt = args[2];
+ return Py_NewRef(dflt);
}
}
else {
- result = PyObject_GetAttr(object, name);
+ result = PyObject_GetAttr(v, name);
}
return result;
}
+PyDoc_STRVAR(getattr_doc,
+"getattr(object, name[, default]) -> value\n\
+\n\
+Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
+When a default argument is given, it is returned when the attribute doesn't\n\
+exist; without it, an exception is raised in that case.");
+
/*[clinic input]
globals as builtin_globals
@@ -1208,7 +1252,7 @@ builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
{
PyObject *v;
- if (_PyObject_LookupAttr(obj, name, &v) < 0) {
+ if (PyObject_GetOptionalAttr(obj, name, &v) < 0) {
return NULL;
}
if (v == NULL) {
@@ -1429,7 +1473,8 @@ static PyMethodDef map_methods[] = {
PyDoc_STRVAR(map_doc,
-"map(func, *iterables) --> map object\n\
+"map(function, iterable, /, *iterables)\n\
+--\n\
\n\
Make an iterator that computes the function using arguments from\n\
each of the iterables. Stops when the shortest iterable is exhausted.");
@@ -1480,43 +1525,34 @@ PyTypeObject PyMap_Type = {
};
-/*[clinic input]
-next as builtin_next
-
- iterator: object
- default: object = NULL
- /
-
-Return the next item from the iterator.
-
-If default is given and the iterator is exhausted,
-it is returned instead of raising StopIteration.
-[clinic start generated code]*/
-
+/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
static PyObject *
-builtin_next_impl(PyObject *module, PyObject *iterator,
- PyObject *default_value)
-/*[clinic end generated code: output=a38a94eeb447fef9 input=180f9984f182020f]*/
+builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
- PyObject *res;
+ PyObject *it, *res;
- if (!PyIter_Check(iterator)) {
+ if (!_PyArg_CheckPositional("next", nargs, 1, 2))
+ return NULL;
+
+ it = args[0];
+ if (!PyIter_Check(it)) {
PyErr_Format(PyExc_TypeError,
"'%.200s' object is not an iterator",
- Py_TYPE(iterator)->tp_name);
+ Py_TYPE(it)->tp_name);
return NULL;
}
- res = (*Py_TYPE(iterator)->tp_iternext)(iterator);
+ res = (*Py_TYPE(it)->tp_iternext)(it);
if (res != NULL) {
return res;
- } else if (default_value != NULL) {
+ } else if (nargs > 1) {
+ PyObject *def = args[1];
if (PyErr_Occurred()) {
if(!PyErr_ExceptionMatches(PyExc_StopIteration))
return NULL;
PyErr_Clear();
}
- return Py_NewRef(default_value);
+ return Py_NewRef(def);
} else if (PyErr_Occurred()) {
return NULL;
} else {
@@ -1525,6 +1561,12 @@ builtin_next_impl(PyObject *module, PyObject *iterator,
}
}
+PyDoc_STRVAR(next_doc,
+"next(iterator[, default])\n\
+\n\
+Return the next item from the iterator. If default is given and the iterator\n\
+is exhausted, it is returned instead of raising StopIteration.");
+
/*[clinic input]
setattr as builtin_setattr
@@ -1566,8 +1608,9 @@ static PyObject *
builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
/*[clinic end generated code: output=85134bc58dff79fa input=164865623abe7216]*/
{
- if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
+ if (PyObject_DelAttr(obj, name) < 0) {
return NULL;
+ }
Py_RETURN_NONE;
}
@@ -1617,33 +1660,34 @@ builtin_hex(PyObject *module, PyObject *number)
}
-/*[clinic input]
-iter as builtin_iter
-
- object: object
- sentinel: object = NULL
- /
-
-Get an iterator from an object.
-
-In the first form, the argument must supply its own iterator, or be a sequence.
-In the second form, the callable is called until it returns the sentinel.
-[clinic start generated code]*/
-
+/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
static PyObject *
-builtin_iter_impl(PyObject *module, PyObject *object, PyObject *sentinel)
-/*[clinic end generated code: output=12cf64203c195a94 input=a5d64d9d81880ba6]*/
+builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
- if (sentinel == NULL)
- return PyObject_GetIter(object);
- if (!PyCallable_Check(object)) {
+ PyObject *v;
+
+ if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
+ return NULL;
+ v = args[0];
+ if (nargs == 1)
+ return PyObject_GetIter(v);
+ if (!PyCallable_Check(v)) {
PyErr_SetString(PyExc_TypeError,
- "iter(object, sentinel): object must be callable");
+ "iter(v, w): v must be callable");
return NULL;
}
- return PyCallIter_New(object, sentinel);
+ PyObject *sentinel = args[1];
+ return PyCallIter_New(v, sentinel);
}
+PyDoc_STRVAR(iter_doc,
+"iter(iterable) -> iterator\n\
+iter(callable, sentinel) -> iterator\n\
+\n\
+Get an iterator from an object. In the first form, the argument must\n\
+supply its own iterator, or be a sequence.\n\
+In the second form, the callable is called until it returns the sentinel.");
+
/*[clinic input]
aiter as builtin_aiter
@@ -1670,16 +1714,16 @@ anext as builtin_anext
default: object = NULL
/
-async anext(aiterator[, default])
+Return the next item from the async iterator.
-Return the next item from the async iterator. If default is given and the async
-iterator is exhausted, it is returned instead of raising StopAsyncIteration.
+If default is given and the async iterator is exhausted,
+it is returned instead of raising StopAsyncIteration.
[clinic start generated code]*/
static PyObject *
builtin_anext_impl(PyObject *module, PyObject *aiterator,
PyObject *default_value)
-/*[clinic end generated code: output=f02c060c163a81fa input=8f63f4f78590bb4c]*/
+/*[clinic end generated code: output=f02c060c163a81fa input=2900e4a370d39550]*/
{
PyTypeObject *t;
PyObject *awaitable;
@@ -1693,6 +1737,9 @@ builtin_anext_impl(PyObject *module, PyObject *aiterator,
}
awaitable = (*t->tp_as_async->am_anext)(aiterator);
+ if (awaitable == NULL) {
+ return NULL;
+ }
if (default_value == NULL) {
return awaitable;
}
@@ -1747,35 +1794,27 @@ builtin_locals_impl(PyObject *module)
static PyObject *
-min_max(PyObject *args, PyObject *kwds, int op)
+min_max(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames, int op)
{
- PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
- PyObject *emptytuple, *defaultval = NULL;
- static char *kwlist[] = {"key", "default", NULL};
- const char *name = op == Py_LT ? "min" : "max";
- const int positional = PyTuple_Size(args) > 1;
- int ret;
+ PyObject *it = NULL, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
+ PyObject *defaultval = NULL;
+ static const char * const keywords[] = {"key", "default", NULL};
+ static _PyArg_Parser _parser_min = {"|$OO:min", keywords, 0};
+ static _PyArg_Parser _parser_max = {"|$OO:max", keywords, 0};
+ const char *name = (op == Py_LT) ? "min" : "max";
+ _PyArg_Parser *_parser = (op == Py_LT) ? &_parser_min : &_parser_max;
- if (positional) {
- v = args;
- }
- else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
- if (PyExceptionClass_Check(PyExc_TypeError)) {
- PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
- }
+ if (nargs == 0) {
+ PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
return NULL;
}
- emptytuple = PyTuple_New(0);
- if (emptytuple == NULL)
- return NULL;
- ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
- (op == Py_LT) ? "|$OO:min" : "|$OO:max",
- kwlist, &keyfunc, &defaultval);
- Py_DECREF(emptytuple);
- if (!ret)
+ if (kwnames != NULL && !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, _parser,
+ &keyfunc, &defaultval)) {
return NULL;
+ }
+ const int positional = nargs > 1; // False iff nargs == 1
if (positional && defaultval != NULL) {
PyErr_Format(PyExc_TypeError,
"Cannot specify a default for %s() with multiple "
@@ -1783,9 +1822,11 @@ min_max(PyObject *args, PyObject *kwds, int op)
return NULL;
}
- it = PyObject_GetIter(v);
- if (it == NULL) {
- return NULL;
+ if (!positional) {
+ it = PyObject_GetIter(args[0]);
+ if (it == NULL) {
+ return NULL;
+ }
}
if (keyfunc == Py_None) {
@@ -1794,7 +1835,24 @@ min_max(PyObject *args, PyObject *kwds, int op)
maxitem = NULL; /* the result */
maxval = NULL; /* the value associated with the result */
- while (( item = PyIter_Next(it) )) {
+ while (1) {
+ if (it == NULL) {
+ if (nargs-- <= 0) {
+ break;
+ }
+ item = *args++;
+ Py_INCREF(item);
+ }
+ else {
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ if (PyErr_Occurred()) {
+ goto Fail_it;
+ }
+ break;
+ }
+ }
+
/* get the value from the key function */
if (keyfunc != NULL) {
val = PyObject_CallOneArg(keyfunc, item);
@@ -1828,8 +1886,6 @@ min_max(PyObject *args, PyObject *kwds, int op)
}
}
}
- if (PyErr_Occurred())
- goto Fail_it;
if (maxval == NULL) {
assert(maxitem == NULL);
if (defaultval != NULL) {
@@ -1841,7 +1897,7 @@ min_max(PyObject *args, PyObject *kwds, int op)
}
else
Py_DECREF(maxval);
- Py_DECREF(it);
+ Py_XDECREF(it);
return maxitem;
Fail_it_item_and_val:
@@ -1851,15 +1907,15 @@ Fail_it_item:
Fail_it:
Py_XDECREF(maxval);
Py_XDECREF(maxitem);
- Py_DECREF(it);
+ Py_XDECREF(it);
return NULL;
}
/* AC: cannot convert yet, waiting for *args support */
static PyObject *
-builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
+builtin_min(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
- return min_max(args, kwds, Py_LT);
+ return min_max(args, nargs, kwnames, Py_LT);
}
PyDoc_STRVAR(min_doc,
@@ -1869,14 +1925,14 @@ min(arg1, arg2, *args, *[, key=func]) -> value\n\
With a single iterable argument, return its smallest item. The\n\
default keyword-only argument specifies an object to return if\n\
the provided iterable is empty.\n\
-With two or more arguments, return the smallest argument.");
+With two or more positional arguments, return the smallest argument.");
/* AC: cannot convert yet, waiting for *args support */
static PyObject *
-builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
+builtin_max(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
- return min_max(args, kwds, Py_GT);
+ return min_max(args, nargs, kwnames, Py_GT);
}
PyDoc_STRVAR(max_doc,
@@ -1886,7 +1942,7 @@ max(arg1, arg2, *args, *[, key=func]) -> value\n\
With a single iterable argument, return its biggest item. The\n\
default keyword-only argument specifies an object to return if\n\
the provided iterable is empty.\n\
-With two or more arguments, return the largest argument.");
+With two or more positional arguments, return the largest argument.");
/*[clinic input]
@@ -1912,15 +1968,21 @@ builtin_oct(PyObject *module, PyObject *number)
/*[clinic input]
ord as builtin_ord
- c: object
+ character as c: object
/
-Return the Unicode code point for a one-character string.
+Return the ordinal value of a character.
+
+If the argument is a one-character string, return the Unicode code
+point of that character.
+
+If the argument is a bytes or bytearray object of length 1, return its
+single byte value.
[clinic start generated code]*/
static PyObject *
builtin_ord(PyObject *module, PyObject *c)
-/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
+/*[clinic end generated code: output=4fa5e87a323bae71 input=98d38480432e1177]*/
{
long ord;
Py_ssize_t size;
@@ -1933,8 +1995,6 @@ builtin_ord(PyObject *module, PyObject *c)
}
}
else if (PyUnicode_Check(c)) {
- if (PyUnicode_READY(c) == -1)
- return NULL;
size = PyUnicode_GET_LENGTH(c);
if (size == 1) {
ord = (long)PyUnicode_READ_CHAR(c, 0);
@@ -2010,18 +2070,20 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
int i, err;
if (file == Py_None) {
- PyThreadState *tstate = _PyThreadState_GET();
- file = _PySys_GetAttr(tstate, &_Py_ID(stdout));
+ file = _PySys_GetRequiredAttr(&_Py_ID(stdout));
if (file == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
return NULL;
}
/* sys.stdout may be None when FILE* stdout isn't connected */
if (file == Py_None) {
+ Py_DECREF(file);
Py_RETURN_NONE;
}
}
+ else {
+ Py_INCREF(file);
+ }
if (sep == Py_None) {
sep = NULL;
@@ -2030,6 +2092,7 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
PyErr_Format(PyExc_TypeError,
"sep must be None or a string, not %.200s",
Py_TYPE(sep)->tp_name);
+ Py_DECREF(file);
return NULL;
}
if (end == Py_None) {
@@ -2039,6 +2102,7 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
PyErr_Format(PyExc_TypeError,
"end must be None or a string, not %.200s",
Py_TYPE(end)->tp_name);
+ Py_DECREF(file);
return NULL;
}
@@ -2051,11 +2115,13 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
}
if (err) {
+ Py_DECREF(file);
return NULL;
}
}
err = PyFile_WriteObject(PyTuple_GET_ITEM(args, i), file, Py_PRINT_RAW);
if (err) {
+ Py_DECREF(file);
return NULL;
}
}
@@ -2067,16 +2133,17 @@ builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
}
if (err) {
+ Py_DECREF(file);
return NULL;
}
if (flush) {
- PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush));
- if (tmp == NULL) {
+ if (_PyFile_Flush(file) < 0) {
+ Py_DECREF(file);
return NULL;
}
- Py_DECREF(tmp);
}
+ Py_DECREF(file);
Py_RETURN_NONE;
}
@@ -2101,44 +2168,47 @@ static PyObject *
builtin_input_impl(PyObject *module, PyObject *prompt)
/*[clinic end generated code: output=83db5a191e7a0d60 input=159c46d4ae40977e]*/
{
- PyThreadState *tstate = _PyThreadState_GET();
- PyObject *fin = _PySys_GetAttr(
- tstate, &_Py_ID(stdin));
- PyObject *fout = _PySys_GetAttr(
- tstate, &_Py_ID(stdout));
- PyObject *ferr = _PySys_GetAttr(
- tstate, &_Py_ID(stderr));
+ PyObject *fin = NULL;
+ PyObject *fout = NULL;
+ PyObject *ferr = NULL;
PyObject *tmp;
long fd;
int tty;
/* Check that stdin/out/err are intact */
- if (fin == NULL || fin == Py_None) {
- PyErr_SetString(PyExc_RuntimeError,
- "input(): lost sys.stdin");
- return NULL;
+ fin = _PySys_GetRequiredAttr(&_Py_ID(stdin));
+ if (fin == NULL) {
+ goto error;
}
- if (fout == NULL || fout == Py_None) {
- PyErr_SetString(PyExc_RuntimeError,
- "input(): lost sys.stdout");
- return NULL;
+ if (fin == Py_None) {
+ PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
+ goto error;
}
- if (ferr == NULL || ferr == Py_None) {
- PyErr_SetString(PyExc_RuntimeError,
- "input(): lost sys.stderr");
- return NULL;
+ fout = _PySys_GetRequiredAttr(&_Py_ID(stdout));
+ if (fout == NULL) {
+ goto error;
+ }
+ if (fout == Py_None) {
+ PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
+ goto error;
+ }
+ ferr = _PySys_GetRequiredAttr(&_Py_ID(stderr));
+ if (ferr == NULL) {
+ goto error;
+ }
+ if (ferr == Py_None) {
+ PyErr_SetString(PyExc_RuntimeError, "lost sys.stderr");
+ goto error;
}
if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
- return NULL;
+ goto error;
}
/* First of all, flush stderr */
- tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush));
- if (tmp == NULL)
+ if (_PyFile_Flush(ferr) < 0) {
PyErr_Clear();
- else
- Py_DECREF(tmp);
+ }
/* We should only use (GNU) readline if Python's sys.stdin and
sys.stdout are the same as C's stdin and stdout, because we
@@ -2151,8 +2221,9 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
else {
fd = PyLong_AsLong(tmp);
Py_DECREF(tmp);
- if (fd < 0 && PyErr_Occurred())
- return NULL;
+ if (fd < 0 && PyErr_Occurred()) {
+ goto error;
+ }
tty = fd == fileno(stdin) && isatty(fd);
}
if (tty) {
@@ -2165,7 +2236,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
fd = PyLong_AsLong(tmp);
Py_DECREF(tmp);
if (fd < 0 && PyErr_Occurred())
- return NULL;
+ goto error;
tty = fd == fileno(stdout) && isatty(fd);
}
}
@@ -2206,11 +2277,9 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
if (stdin_errors_str == NULL) {
goto _readline_errors;
}
- tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
- if (tmp == NULL)
+ if (_PyFile_Flush(fout) < 0) {
PyErr_Clear();
- else
- Py_DECREF(tmp);
+ }
if (prompt != NULL) {
/* We have a prompt, encode it as stdout would */
const char *stdout_encoding_str, *stdout_errors_str;
@@ -2251,6 +2320,11 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
goto _readline_errors;
assert(PyBytes_Check(po));
promptstr = PyBytes_AS_STRING(po);
+ if ((Py_ssize_t)strlen(promptstr) != PyBytes_GET_SIZE(po)) {
+ PyErr_SetString(PyExc_ValueError,
+ "input: prompt string cannot contain null characters");
+ goto _readline_errors;
+ }
}
else {
po = NULL;
@@ -2290,10 +2364,13 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
if (result != NULL) {
if (PySys_Audit("builtins.input/result", "O", result) < 0) {
- return NULL;
+ goto error;
}
}
+ Py_DECREF(fin);
+ Py_DECREF(fout);
+ Py_DECREF(ferr);
return result;
_readline_errors:
@@ -2303,7 +2380,7 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
Py_XDECREF(stdout_errors);
Py_XDECREF(po);
if (tty)
- return NULL;
+ goto error;
PyErr_Clear();
}
@@ -2311,14 +2388,22 @@ builtin_input_impl(PyObject *module, PyObject *prompt)
/* Fallback if we're not interactive */
if (prompt != NULL) {
if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
- return NULL;
+ goto error;
}
- tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
- if (tmp == NULL)
+ if (_PyFile_Flush(fout) < 0) {
PyErr_Clear();
- else
- Py_DECREF(tmp);
- return PyFile_GetLine(fin, -1);
+ }
+ tmp = PyFile_GetLine(fin, -1);
+ Py_DECREF(fin);
+ Py_DECREF(fout);
+ Py_DECREF(ferr);
+ return tmp;
+
+error:
+ Py_XDECREF(fin);
+ Py_XDECREF(fout);
+ Py_XDECREF(ferr);
+ return NULL;
}
@@ -2359,11 +2444,6 @@ builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
{
PyObject *round, *result;
- if (!_PyType_IsReady(Py_TYPE(number))) {
- if (PyType_Ready(Py_TYPE(number)) < 0)
- return NULL;
- }
-
round = _PyObject_LookupSpecial(number, &_Py_ID(__round__));
if (round == NULL) {
if (!PyErr_Occurred())
@@ -2443,29 +2523,20 @@ builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject
}
-/*[clinic input]
-vars as builtin_vars
-
- object: object = NULL
- /
-
-Show vars.
-
-Without arguments, equivalent to locals().
-With an argument, equivalent to object.__dict__.
-[clinic start generated code]*/
-
+/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
static PyObject *
-builtin_vars_impl(PyObject *module, PyObject *object)
-/*[clinic end generated code: output=840a7f64007a3e0a input=80cbdef9182c4ba3]*/
+builtin_vars(PyObject *self, PyObject *args)
{
+ PyObject *v = NULL;
PyObject *d;
- if (object == NULL) {
+ if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
+ return NULL;
+ if (v == NULL) {
d = _PyEval_GetFrameLocals();
}
else {
- if (_PyObject_LookupAttr(object, &_Py_ID(__dict__), &d) == 0) {
+ if (PyObject_GetOptionalAttr(v, &_Py_ID(__dict__), &d) == 0) {
PyErr_SetString(PyExc_TypeError,
"vars() argument must have __dict__ attribute");
}
@@ -2473,6 +2544,12 @@ builtin_vars_impl(PyObject *module, PyObject *object)
return d;
}
+PyDoc_STRVAR(vars_doc,
+"vars([object]) -> dictionary\n\
+\n\
+Without arguments, equivalent to locals().\n\
+With an argument, equivalent to object.__dict__.");
+
/*[clinic input]
sum as builtin_sum
@@ -2896,7 +2973,7 @@ check:
// ValueError: zip() argument 3 is shorter than arguments 1-2
const char* plural = i == 1 ? " " : "s 1-";
return PyErr_Format(PyExc_ValueError,
- "zip() argument %d is shorter than argument%s%d",
+ "zip() argument %zd is shorter than argument%s%zd",
i + 1, plural, i);
}
for (i = 1; i < tuplesize; i++) {
@@ -2906,7 +2983,7 @@ check:
Py_DECREF(item);
const char* plural = i == 1 ? " " : "s 1-";
return PyErr_Format(PyExc_ValueError,
- "zip() argument %d is longer than argument%s%d",
+ "zip() argument %zd is longer than argument%s%zd",
i + 1, plural, i);
}
if (PyErr_Occurred()) {
@@ -2952,10 +3029,8 @@ static PyMethodDef zip_methods[] = {
};
PyDoc_STRVAR(zip_doc,
-"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
-\n\
- >>> list(zip('abcdefg', range(3), range(4)))\n\
- [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
+"zip(*iterables, strict=False)\n\
+--\n\
\n\
The zip object yields n-length tuples, where n is the number of iterables\n\
passed as positional arguments to zip(). The i-th element in every tuple\n\
@@ -2963,7 +3038,10 @@ comes from the i-th iterable argument to zip(). This continues until the\n\
shortest argument is exhausted.\n\
\n\
If strict is true and one of the arguments is exhausted before the others,\n\
-raise a ValueError.");
+raise a ValueError.\n\
+\n\
+ >>> list(zip('abcdefg', range(3), range(4)))\n\
+ [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]");
PyTypeObject PyZip_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
@@ -3024,12 +3102,12 @@ static PyMethodDef builtin_methods[] = {
BUILTIN_CHR_METHODDEF
BUILTIN_COMPILE_METHODDEF
BUILTIN_DELATTR_METHODDEF
- BUILTIN_DIR_METHODDEF
+ {"dir", builtin_dir, METH_VARARGS, dir_doc},
BUILTIN_DIVMOD_METHODDEF
BUILTIN_EVAL_METHODDEF
BUILTIN_EXEC_METHODDEF
BUILTIN_FORMAT_METHODDEF
- BUILTIN_GETATTR_METHODDEF
+ {"getattr", _PyCFunction_CAST(builtin_getattr), METH_FASTCALL, getattr_doc},
BUILTIN_GLOBALS_METHODDEF
BUILTIN_HASATTR_METHODDEF
BUILTIN_HASH_METHODDEF
@@ -3038,13 +3116,13 @@ static PyMethodDef builtin_methods[] = {
BUILTIN_INPUT_METHODDEF
BUILTIN_ISINSTANCE_METHODDEF
BUILTIN_ISSUBCLASS_METHODDEF
- BUILTIN_ITER_METHODDEF
+ {"iter", _PyCFunction_CAST(builtin_iter), METH_FASTCALL, iter_doc},
BUILTIN_AITER_METHODDEF
BUILTIN_LEN_METHODDEF
BUILTIN_LOCALS_METHODDEF
- {"max", _PyCFunction_CAST(builtin_max), METH_VARARGS | METH_KEYWORDS, max_doc},
- {"min", _PyCFunction_CAST(builtin_min), METH_VARARGS | METH_KEYWORDS, min_doc},
- BUILTIN_NEXT_METHODDEF
+ {"max", _PyCFunction_CAST(builtin_max), METH_FASTCALL | METH_KEYWORDS, max_doc},
+ {"min", _PyCFunction_CAST(builtin_min), METH_FASTCALL | METH_KEYWORDS, min_doc},
+ {"next", _PyCFunction_CAST(builtin_next), METH_FASTCALL, next_doc},
BUILTIN_ANEXT_METHODDEF
BUILTIN_OCT_METHODDEF
BUILTIN_ORD_METHODDEF
@@ -3055,7 +3133,7 @@ static PyMethodDef builtin_methods[] = {
BUILTIN_SETATTR_METHODDEF
BUILTIN_SORTED_METHODDEF
BUILTIN_SUM_METHODDEF
- BUILTIN_VARS_METHODDEF
+ {"vars", builtin_vars, METH_VARARGS, vars_doc},
{NULL, NULL},
};
@@ -3094,6 +3172,9 @@ _PyBuiltin_Init(PyInterpreterState *interp)
mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
if (mod == NULL)
return NULL;
+#ifdef Py_GIL_DISABLED
+ PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
+#endif
dict = PyModule_GetDict(mod);
#ifdef Py_TRACE_REFS
@@ -3103,7 +3184,7 @@ _PyBuiltin_Init(PyInterpreterState *interp)
* result, programs leaking references to None and False (etc)
* couldn't be diagnosed by examining sys.getobjects(0).
*/
-#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
+#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT))
#else
#define ADD_TO_ALL(OBJECT) (void)0
#endif