blob: b9e7111299e2fe86eee8fa6c46c582faf1840ad3 [file] [log] [blame]
Guido van Rossume15dee51995-07-18 14:12:02 +00001/* Abstract Object Interface (many thanks to Jim Fulton) */
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002
Guido van Rossume15dee51995-07-18 14:12:02 +00003#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_abstract.h" // _PyIndex_Check()
5#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
Victor Stinner61b64922020-06-23 15:55:06 +02006#include "pycore_pyerrors.h" // _PyErr_Occurred()
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +00008#include <ctype.h>
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include <stddef.h> // offsetof()
Tim Peters64b5ce32001-09-10 20:52:51 +000010#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +000011
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000014/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000015
16static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000018{
Victor Stinner0d76d2b2020-02-07 01:53:23 +010019 PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000021}
22
Guido van Rossum052b7e11996-11-11 15:08:19 +000023static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000024null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000025{
Victor Stinner61b64922020-06-23 15:55:06 +020026 PyThreadState *tstate = _PyThreadState_GET();
27 if (!_PyErr_Occurred(tstate)) {
28 _PyErr_SetString(tstate, PyExc_SystemError,
29 "null argument to internal routine");
30 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000032}
33
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000034/* Operations on any object */
35
Guido van Rossume15dee51995-07-18 14:12:02 +000036PyObject *
Fred Drake79912472000-07-09 04:06:11 +000037PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000040
Victor Stinner71aea8e2016-08-19 16:59:55 +020041 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020043 }
44
Victor Stinner0d76d2b2020-02-07 01:53:23 +010045 v = (PyObject *)Py_TYPE(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 Py_INCREF(v);
47 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000048}
49
Martin v. Löwis18e16552006-02-15 17:27:45 +000050Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000051PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 if (o == NULL) {
56 null_error();
57 return -1;
58 }
Guido van Rossume15dee51995-07-18 14:12:02 +000059
Victor Stinner0d76d2b2020-02-07 01:53:23 +010060 m = Py_TYPE(o)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +030061 if (m && m->sq_length) {
62 Py_ssize_t len = m->sq_length(o);
63 assert(len >= 0 || PyErr_Occurred());
64 return len;
65 }
Guido van Rossume15dee51995-07-18 14:12:02 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000068}
69
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000070#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000071Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000072PyObject_Length(PyObject *o)
73{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000075}
76#define PyObject_Length PyObject_Size
77
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020078int
79_PyObject_HasLen(PyObject *o) {
80 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
81 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
82}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000083
Christian Heimes255f53b2007-12-08 15:33:56 +000084/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020085 or o.__length_hint__(). If those methods aren't found the defaultvalue is
86 returned. If one of the calls fails with an exception other than TypeError
87 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000088*/
89
90Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020091PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000092{
Christian Heimesb70e8a12012-10-06 17:16:39 +020093 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020094 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050095 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030096 if (_PyObject_HasLen(o)) {
97 res = PyObject_Length(o);
Serhiy Storchaka813f9432017-04-16 09:21:44 +030098 if (res < 0) {
Victor Stinner61b64922020-06-23 15:55:06 +020099 PyThreadState *tstate = _PyThreadState_GET();
100 assert(_PyErr_Occurred(tstate));
101 if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300102 return -1;
103 }
Victor Stinner61b64922020-06-23 15:55:06 +0200104 _PyErr_Clear(tstate);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200105 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300106 else {
107 return res;
108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
Christian Heimes6314d162012-10-06 17:13:29 +0200110 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200111 if (hint == NULL) {
112 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 return defaultvalue;
116 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100117 result = _PyObject_CallNoArg(hint);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200118 Py_DECREF(hint);
119 if (result == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +0200120 PyThreadState *tstate = _PyThreadState_GET();
121 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
122 _PyErr_Clear(tstate);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200123 return defaultvalue;
124 }
125 return -1;
126 }
127 else if (result == Py_NotImplemented) {
128 Py_DECREF(result);
129 return defaultvalue;
130 }
131 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200132 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200133 Py_TYPE(result)->tp_name);
134 Py_DECREF(result);
135 return -1;
136 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200137 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200138 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200139 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200140 return -1;
141 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200142 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200143 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
144 return -1;
145 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200146 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000147}
148
Guido van Rossume15dee51995-07-18 14:12:02 +0000149PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000150PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 PyMappingMethods *m;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000153 PySequenceMethods *ms;
Guido van Rossume15dee51995-07-18 14:12:02 +0000154
Victor Stinner71aea8e2016-08-19 16:59:55 +0200155 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200157 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000158
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100159 m = Py_TYPE(o)->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100160 if (m && m->mp_subscript) {
161 PyObject *item = m->mp_subscript(o, key);
162 assert((item != NULL) ^ (PyErr_Occurred() != NULL));
163 return item;
164 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000165
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100166 ms = Py_TYPE(o)->tp_as_sequence;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000167 if (ms && ms->sq_item) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200168 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 Py_ssize_t key_value;
170 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
171 if (key_value == -1 && PyErr_Occurred())
172 return NULL;
173 return PySequence_GetItem(o, key_value);
174 }
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000175 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return type_error("sequence index must "
177 "be integer, not '%.200s'", key);
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000178 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000180
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100181 if (PyType_Check(o)) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200182 PyObject *meth, *result;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100183 _Py_IDENTIFIER(__class_getitem__);
Victor Stinnera15e2602020-04-08 02:01:56 +0200184
Guido van Rossum48b069a2020-04-07 09:50:06 -0700185 // Special case type[int], but disallow other types so str[int] fails
186 if ((PyTypeObject*)o == &PyType_Type) {
187 return Py_GenericAlias(o, key);
188 }
189
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200190 if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
191 return NULL;
192 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100193 if (meth) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100194 result = PyObject_CallOneArg(meth, key);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100195 Py_DECREF(meth);
196 return result;
197 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100198 }
199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000201}
202
203int
Fred Drake79912472000-07-09 04:06:11 +0000204PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (o == NULL || key == NULL || value == NULL) {
209 null_error();
210 return -1;
211 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100212 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (m && m->mp_ass_subscript)
214 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000215
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100216 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200217 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 Py_ssize_t key_value;
219 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
220 if (key_value == -1 && PyErr_Occurred())
221 return -1;
222 return PySequence_SetItem(o, key_value, value);
223 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100224 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 type_error("sequence index must be "
226 "integer, not '%.200s'", key);
227 return -1;
228 }
229 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 type_error("'%.200s' object does not support item assignment", o);
232 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000233}
234
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000235int
Fred Drake79912472000-07-09 04:06:11 +0000236PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (o == NULL || key == NULL) {
241 null_error();
242 return -1;
243 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100244 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (m && m->mp_ass_subscript)
246 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000247
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100248 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200249 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 Py_ssize_t key_value;
251 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
252 if (key_value == -1 && PyErr_Occurred())
253 return -1;
254 return PySequence_DelItem(o, key_value);
255 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100256 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 type_error("sequence index must be "
258 "integer, not '%.200s'", key);
259 return -1;
260 }
261 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 type_error("'%.200s' object does not support item deletion", o);
264 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000265}
266
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000267int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300268PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyObject *okey;
271 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (o == NULL || key == NULL) {
274 null_error();
275 return -1;
276 }
277 okey = PyUnicode_FromString(key);
278 if (okey == NULL)
279 return -1;
280 ret = PyObject_DelItem(o, okey);
281 Py_DECREF(okey);
282 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000283}
284
Victor Stinneref5c6152020-04-08 01:13:53 +0200285
286/* Return 1 if the getbuffer function is available, otherwise return 0. */
287int
288PyObject_CheckBuffer(PyObject *obj)
289{
290 PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
291 return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
292}
293
294
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000295/* We release the buffer right after use of this function which could
Guido van Rossum98297ee2007-11-06 21:34:58 +0000296 cause issues later on. Don't use these functions in new code.
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000297 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000298int
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000299PyObject_CheckReadBuffer(PyObject *obj)
300{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100301 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 Py_buffer view;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (pb == NULL ||
305 pb->bf_getbuffer == NULL)
306 return 0;
307 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
308 PyErr_Clear();
309 return 0;
310 }
311 PyBuffer_Release(&view);
312 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000313}
314
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200315static int
316as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
321 null_error();
322 return -1;
323 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200324 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return -1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 *buffer = view.buf;
328 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200329 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000331}
332
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200333int
334PyObject_AsCharBuffer(PyObject *obj,
335 const char **buffer,
336 Py_ssize_t *buffer_len)
337{
338 return as_read_buffer(obj, (const void **)buffer, buffer_len);
339}
340
341int PyObject_AsReadBuffer(PyObject *obj,
342 const void **buffer,
343 Py_ssize_t *buffer_len)
344{
345 return as_read_buffer(obj, buffer, buffer_len);
346}
347
Guido van Rossum4c08d552000-03-10 22:55:18 +0000348int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 void **buffer,
350 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyBufferProcs *pb;
353 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
356 null_error();
357 return -1;
358 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100359 pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (pb == NULL ||
361 pb->bf_getbuffer == NULL ||
362 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
363 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400364 "expected a writable bytes-like object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 return -1;
366 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 *buffer = view.buf;
369 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200370 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000372}
373
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000374/* Buffer C-API for Python 3.0 */
375
376int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000377PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000378{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100379 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200380
381 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400383 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_TYPE(obj)->tp_name);
385 return -1;
386 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200387 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000388}
389
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000390static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100391_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t sd, dim;
394 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000395
Stefan Krah363af442015-02-01 14:53:54 +0100396 /* 1) len = product(shape) * itemsize
397 2) itemsize > 0
398 3) len = 0 <==> exists i: shape[i] = 0 */
399 if (view->len == 0) return 1;
400 if (view->strides == NULL) { /* C-contiguous by definition */
401 /* Trivially F-contiguous */
402 if (view->ndim <= 1) return 1;
403
404 /* ndim > 1 implies shape != NULL */
405 assert(view->shape != NULL);
406
407 /* Effectively 1-d */
408 sd = 0;
409 for (i=0; i<view->ndim; i++) {
410 if (view->shape[i] > 1) sd += 1;
411 }
412 return sd <= 1;
413 }
414
415 /* strides != NULL implies both of these */
416 assert(view->ndim > 0);
417 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 for (i=0; i<view->ndim; i++) {
421 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100422 if (dim > 1 && view->strides[i] != sd) {
423 return 0;
424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 sd *= dim;
426 }
427 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000428}
429
430static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100431_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_ssize_t sd, dim;
434 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000435
Stefan Krah363af442015-02-01 14:53:54 +0100436 /* 1) len = product(shape) * itemsize
437 2) itemsize > 0
438 3) len = 0 <==> exists i: shape[i] = 0 */
439 if (view->len == 0) return 1;
440 if (view->strides == NULL) return 1; /* C-contiguous by definition */
441
442 /* strides != NULL implies both of these */
443 assert(view->ndim > 0);
444 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 for (i=view->ndim-1; i>=0; i--) {
448 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100449 if (dim > 1 && view->strides[i] != sd) {
450 return 0;
451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 sd *= dim;
453 }
454 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000455}
456
457int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100458PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000459{
460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000462
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100463 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100465 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100467 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return (_IsCContiguous(view) || _IsFortranContiguous(view));
469 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000470}
471
472
Guido van Rossum98297ee2007-11-06 21:34:58 +0000473void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000474PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 char* pointer;
477 int i;
478 pointer = (char *)view->buf;
479 for (i = 0; i < view->ndim; i++) {
480 pointer += view->strides[i]*indices[i];
481 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
482 pointer = *((char**)pointer) + view->suboffsets[i];
483 }
484 }
485 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000486}
487
488
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000490_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 for (k=0; k<nd; k++) {
495 if (index[k] < shape[k]-1) {
496 index[k]++;
497 break;
498 }
499 else {
500 index[k] = 0;
501 }
502 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000503}
504
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000506_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 for (k=nd-1; k>=0; k--) {
511 if (index[k] < shape[k]-1) {
512 index[k]++;
513 break;
514 }
515 else {
516 index[k] = 0;
517 }
518 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000519}
520
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -0300521Py_ssize_t
522PyBuffer_SizeFromFormat(const char *format)
523{
524 PyObject *structmodule = NULL;
525 PyObject *calcsize = NULL;
526 PyObject *res = NULL;
527 PyObject *fmt = NULL;
528 Py_ssize_t itemsize = -1;
529
530 structmodule = PyImport_ImportModule("struct");
531 if (structmodule == NULL) {
532 return itemsize;
533 }
534
535 calcsize = PyObject_GetAttrString(structmodule, "calcsize");
536 if (calcsize == NULL) {
537 goto done;
538 }
539
540 fmt = PyUnicode_FromString(format);
541 if (fmt == NULL) {
542 goto done;
543 }
544
545 res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
546 if (res == NULL) {
547 goto done;
548 }
549
550 itemsize = PyLong_AsSsize_t(res);
551 if (itemsize < 0) {
552 goto done;
553 }
554
555done:
556 Py_DECREF(structmodule);
557 Py_XDECREF(calcsize);
558 Py_XDECREF(fmt);
559 Py_XDECREF(res);
560 return itemsize;
561}
562
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000563int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000564PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000567 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_ssize_t *indices, elements;
569 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (len > view->len) {
572 len = view->len;
573 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (PyBuffer_IsContiguous(view, fort)) {
576 /* simplest copy is all that is needed */
577 memcpy(view->buf, buf, len);
578 return 0;
579 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000582
Stefan Krah7213fcc2015-02-01 16:19:23 +0100583 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
585 if (indices == NULL) {
586 PyErr_NoMemory();
587 return -1;
588 }
589 for (k=0; k<view->ndim;k++) {
590 indices[k] = 0;
591 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000594 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 }
596 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000597 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 }
599 src = buf;
600 /* XXX : This is not going to be the fastest code in the world
601 several optimizations are possible.
602 */
603 elements = len / view->itemsize;
604 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 ptr = PyBuffer_GetPointer(view, indices);
606 memcpy(ptr, src, view->itemsize);
607 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100608 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 PyMem_Free(indices);
612 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000613}
614
Guido van Rossum98297ee2007-11-06 21:34:58 +0000615int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 Py_buffer view_dest, view_src;
618 int k;
619 Py_ssize_t *indices, elements;
620 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!PyObject_CheckBuffer(dest) ||
623 !PyObject_CheckBuffer(src)) {
624 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400625 "both destination and source must be "\
626 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return -1;
628 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
631 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
632 PyBuffer_Release(&view_dest);
633 return -1;
634 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (view_dest.len < view_src.len) {
637 PyErr_SetString(PyExc_BufferError,
638 "destination is too small to receive data from source");
639 PyBuffer_Release(&view_dest);
640 PyBuffer_Release(&view_src);
641 return -1;
642 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
645 PyBuffer_IsContiguous(&view_src, 'C')) ||
646 (PyBuffer_IsContiguous(&view_dest, 'F') &&
647 PyBuffer_IsContiguous(&view_src, 'F'))) {
648 /* simplest copy is all that is needed */
649 memcpy(view_dest.buf, view_src.buf, view_src.len);
650 PyBuffer_Release(&view_dest);
651 PyBuffer_Release(&view_src);
652 return 0;
653 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* XXX(nnorwitz): need to check for overflow! */
658 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
659 if (indices == NULL) {
660 PyErr_NoMemory();
661 PyBuffer_Release(&view_dest);
662 PyBuffer_Release(&view_src);
663 return -1;
664 }
665 for (k=0; k<view_src.ndim;k++) {
666 indices[k] = 0;
667 }
668 elements = 1;
669 for (k=0; k<view_src.ndim; k++) {
670 /* XXX(nnorwitz): can this overflow? */
671 elements *= view_src.shape[k];
672 }
673 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000674 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 dptr = PyBuffer_GetPointer(&view_dest, indices);
676 sptr = PyBuffer_GetPointer(&view_src, indices);
677 memcpy(dptr, sptr, view_src.itemsize);
678 }
679 PyMem_Free(indices);
680 PyBuffer_Release(&view_dest);
681 PyBuffer_Release(&view_src);
682 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000683}
684
685void
686PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 Py_ssize_t *strides, int itemsize,
688 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 int k;
691 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 sd = itemsize;
694 if (fort == 'F') {
695 for (k=0; k<nd; k++) {
696 strides[k] = sd;
697 sd *= shape[k];
698 }
699 }
700 else {
701 for (k=nd-1; k>=0; k--) {
702 strides[k] = sd;
703 sd *= shape[k];
704 }
705 }
706 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000707}
708
709int
Martin v. Löwis423be952008-08-13 15:53:07 +0000710PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100711 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000712{
Stefan Krah5178d912015-02-03 16:57:21 +0100713 if (view == NULL) {
714 PyErr_SetString(PyExc_BufferError,
Victor Stinner61b64922020-06-23 15:55:06 +0200715 "PyBuffer_FillInfo: view==NULL argument is obsolete");
Stefan Krah5178d912015-02-03 16:57:21 +0100716 return -1;
717 }
718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
720 (readonly == 1)) {
721 PyErr_SetString(PyExc_BufferError,
722 "Object is not writable.");
723 return -1;
724 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 view->obj = obj;
727 if (obj)
728 Py_INCREF(obj);
729 view->buf = buf;
730 view->len = len;
731 view->readonly = readonly;
732 view->itemsize = 1;
733 view->format = NULL;
734 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
735 view->format = "B";
736 view->ndim = 1;
737 view->shape = NULL;
738 if ((flags & PyBUF_ND) == PyBUF_ND)
739 view->shape = &(view->len);
740 view->strides = NULL;
741 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
742 view->strides = &(view->itemsize);
743 view->suboffsets = NULL;
744 view->internal = NULL;
745 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000746}
747
Martin v. Löwis423be952008-08-13 15:53:07 +0000748void
749PyBuffer_Release(Py_buffer *view)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200752 PyBufferProcs *pb;
753 if (obj == NULL)
754 return;
755 pb = Py_TYPE(obj)->tp_as_buffer;
756 if (pb && pb->bf_releasebuffer)
757 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200759 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000760}
761
Eric Smith8fd3eba2008-02-17 19:48:00 +0000762PyObject *
763PyObject_Format(PyObject *obj, PyObject *format_spec)
764{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000765 PyObject *meth;
766 PyObject *empty = NULL;
767 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500768 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000769
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300770 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
771 PyErr_Format(PyExc_SystemError,
772 "Format specifier must be a string, not %.200s",
773 Py_TYPE(format_spec)->tp_name);
774 return NULL;
775 }
776
777 /* Fast path for common types. */
778 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
779 if (PyUnicode_CheckExact(obj)) {
780 Py_INCREF(obj);
781 return obj;
782 }
783 if (PyLong_CheckExact(obj)) {
784 return PyObject_Str(obj);
785 }
786 }
787
Eric Smith8fd3eba2008-02-17 19:48:00 +0000788 /* If no format_spec is provided, use an empty string */
789 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100790 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000791 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000792 }
793
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300794 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500795 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000796 if (meth == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +0200797 PyThreadState *tstate = _PyThreadState_GET();
798 if (!_PyErr_Occurred(tstate)) {
799 _PyErr_Format(tstate, PyExc_TypeError,
800 "Type %.100s doesn't define __format__",
801 Py_TYPE(obj)->tp_name);
802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000804 }
805
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000806 /* And call it. */
Petr Viktorinffd97532020-02-11 17:46:57 +0100807 result = PyObject_CallOneArg(meth, format_spec);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000808 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000809
810 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800811 PyErr_Format(PyExc_TypeError,
Victor Stinner61b64922020-06-23 15:55:06 +0200812 "__format__ must return a str, not %.200s",
813 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000814 Py_DECREF(result);
815 result = NULL;
816 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000817 }
818
819done:
820 Py_XDECREF(empty);
821 return result;
822}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000823/* Operations on numbers */
824
825int
Fred Drake79912472000-07-09 04:06:11 +0000826PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000827{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100828 return o && Py_TYPE(o)->tp_as_number &&
829 (Py_TYPE(o)->tp_as_number->nb_index ||
830 Py_TYPE(o)->tp_as_number->nb_int ||
831 Py_TYPE(o)->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000832}
833
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000834/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000835
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000836#define NB_SLOT(x) offsetof(PyNumberMethods, x)
837#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000839#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000841
842/*
843 Calling scheme used for binary operations:
844
Neal Norwitz4886cc32006-08-21 17:06:07 +0000845 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000847
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100848 [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
849 Py_TYPE(v)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000850 */
851
852static PyObject *
853binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 PyObject *x;
856 binaryfunc slotv = NULL;
857 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000858
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100859 if (Py_TYPE(v)->tp_as_number != NULL)
860 slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600861 if (!Py_IS_TYPE(w, Py_TYPE(v)) &&
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100862 Py_TYPE(w)->tp_as_number != NULL) {
863 slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (slotw == slotv)
865 slotw = NULL;
866 }
867 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100868 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 x = slotw(v, w);
870 if (x != Py_NotImplemented)
871 return x;
872 Py_DECREF(x); /* can't do it */
873 slotw = NULL;
874 }
875 x = slotv(v, w);
876 if (x != Py_NotImplemented)
877 return x;
878 Py_DECREF(x); /* can't do it */
879 }
880 if (slotw) {
881 x = slotw(v, w);
882 if (x != Py_NotImplemented)
883 return x;
884 Py_DECREF(x); /* can't do it */
885 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500886 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000887}
Guido van Rossum77660912002-04-16 16:32:50 +0000888
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000889static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000890binop_type_error(PyObject *v, PyObject *w, const char *op_name)
891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 PyErr_Format(PyExc_TypeError,
893 "unsupported operand type(s) for %.100s: "
894 "'%.100s' and '%.100s'",
895 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100896 Py_TYPE(v)->tp_name,
897 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000899}
900
901static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000902binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyObject *result = binary_op1(v, w, op_slot);
905 if (result == Py_NotImplemented) {
906 Py_DECREF(result);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530907
908 if (op_slot == NB_SLOT(nb_rshift) &&
scoder4c9ea092020-05-12 16:12:41 +0200909 PyCFunction_CheckExact(v) &&
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530910 strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
911 {
912 PyErr_Format(PyExc_TypeError,
913 "unsupported operand type(s) for %.100s: "
914 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
Sanyam Khuranaa7c449b2017-08-18 17:48:14 +0530915 "file=<output_stream>)\"?",
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530916 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100917 Py_TYPE(v)->tp_name,
918 Py_TYPE(w)->tp_name);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530919 return NULL;
920 }
921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 return binop_type_error(v, w, op_name);
923 }
924 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000925}
926
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000927
928/*
929 Calling scheme used for ternary operations:
930
Neal Norwitz4886cc32006-08-21 17:06:07 +0000931 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000933 */
934
935static PyObject *
936ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 PyObject *w,
938 PyObject *z,
939 const int op_slot,
940 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyNumberMethods *mv, *mw, *mz;
943 PyObject *x = NULL;
944 ternaryfunc slotv = NULL;
945 ternaryfunc slotw = NULL;
946 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000947
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100948 mv = Py_TYPE(v)->tp_as_number;
949 mw = Py_TYPE(w)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (mv != NULL)
951 slotv = NB_TERNOP(mv, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600952 if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 slotw = NB_TERNOP(mw, op_slot);
954 if (slotw == slotv)
955 slotw = NULL;
956 }
957 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100958 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 x = slotw(v, w, z);
960 if (x != Py_NotImplemented)
961 return x;
962 Py_DECREF(x); /* can't do it */
963 slotw = NULL;
964 }
965 x = slotv(v, w, z);
966 if (x != Py_NotImplemented)
967 return x;
968 Py_DECREF(x); /* can't do it */
969 }
970 if (slotw) {
971 x = slotw(v, w, z);
972 if (x != Py_NotImplemented)
973 return x;
974 Py_DECREF(x); /* can't do it */
975 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100976 mz = Py_TYPE(z)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (mz != NULL) {
978 slotz = NB_TERNOP(mz, op_slot);
979 if (slotz == slotv || slotz == slotw)
980 slotz = NULL;
981 if (slotz) {
982 x = slotz(v, w, z);
983 if (x != Py_NotImplemented)
984 return x;
985 Py_DECREF(x); /* can't do it */
986 }
987 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (z == Py_None)
990 PyErr_Format(
991 PyExc_TypeError,
992 "unsupported operand type(s) for ** or pow(): "
993 "'%.100s' and '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100994 Py_TYPE(v)->tp_name,
995 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 else
997 PyErr_Format(
998 PyExc_TypeError,
999 "unsupported operand type(s) for pow(): "
1000 "'%.100s', '%.100s', '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001001 Py_TYPE(v)->tp_name,
1002 Py_TYPE(w)->tp_name,
1003 Py_TYPE(z)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001005}
1006
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001007#define BINARY_FUNC(func, op, op_name) \
1008 PyObject * \
1009 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001011 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001012
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001013BINARY_FUNC(PyNumber_Or, nb_or, "|")
1014BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1015BINARY_FUNC(PyNumber_And, nb_and, "&")
1016BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1017BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1018BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001019BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001020
1021PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001022PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1025 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001026 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 Py_DECREF(result);
1028 if (m && m->sq_concat) {
1029 return (*m->sq_concat)(v, w);
1030 }
1031 result = binop_type_error(v, w, "+");
1032 }
1033 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001034}
1035
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001036static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001037sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 Py_ssize_t count;
Victor Stinnera15e2602020-04-08 02:01:56 +02001040 if (_PyIndex_Check(n)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1042 if (count == -1 && PyErr_Occurred())
1043 return NULL;
1044 }
1045 else {
1046 return type_error("can't multiply sequence by "
1047 "non-int of type '%.200s'", n);
1048 }
1049 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001050}
1051
1052PyObject *
1053PyNumber_Multiply(PyObject *v, PyObject *w)
1054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1056 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001057 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1058 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 Py_DECREF(result);
1060 if (mv && mv->sq_repeat) {
1061 return sequence_repeat(mv->sq_repeat, v, w);
1062 }
1063 else if (mw && mw->sq_repeat) {
1064 return sequence_repeat(mw->sq_repeat, w, v);
1065 }
1066 result = binop_type_error(v, w, "*");
1067 }
1068 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001069}
1070
Guido van Rossume15dee51995-07-18 14:12:02 +00001071PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001072PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1073{
1074 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1075}
1076
1077PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001078PyNumber_FloorDivide(PyObject *v, PyObject *w)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001081}
1082
1083PyObject *
1084PyNumber_TrueDivide(PyObject *v, PyObject *w)
1085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001087}
1088
1089PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001090PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001093}
1094
1095PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001096PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001099}
1100
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001101/* Binary in-place operators */
1102
1103/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001104 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001105
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001106 - If the left hand object has the appropriate struct members, and
1107 they are filled, call the appropriate function and return the
1108 result. No coercion is done on the arguments; the left-hand object
1109 is the one the operation is performed on, and it's up to the
1110 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001111
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001112 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001113 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001114
1115 */
1116
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001117static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001118binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001119{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001120 PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (mv != NULL) {
1122 binaryfunc slot = NB_BINOP(mv, iop_slot);
1123 if (slot) {
1124 PyObject *x = (slot)(v, w);
1125 if (x != Py_NotImplemented) {
1126 return x;
1127 }
1128 Py_DECREF(x);
1129 }
1130 }
1131 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001132}
1133
1134static PyObject *
1135binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1139 if (result == Py_NotImplemented) {
1140 Py_DECREF(result);
1141 return binop_type_error(v, w, op_name);
1142 }
1143 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001144}
1145
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001146#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject * \
1148 func(PyObject *v, PyObject *w) { \
1149 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1150 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001151
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001152INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1153INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1154INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1155INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1156INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1157INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001158INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001159
1160PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001161PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1164 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001165}
1166
1167PyObject *
1168PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1171 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001172}
1173
1174PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001175PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1178 NB_SLOT(nb_add));
1179 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001180 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_DECREF(result);
1182 if (m != NULL) {
1183 binaryfunc f = NULL;
1184 f = m->sq_inplace_concat;
1185 if (f == NULL)
1186 f = m->sq_concat;
1187 if (f != NULL)
1188 return (*f)(v, w);
1189 }
1190 result = binop_type_error(v, w, "+=");
1191 }
1192 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001193}
1194
1195PyObject *
1196PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1199 NB_SLOT(nb_multiply));
1200 if (result == Py_NotImplemented) {
1201 ssizeargfunc f = NULL;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001202 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1203 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_DECREF(result);
1205 if (mv != NULL) {
1206 f = mv->sq_inplace_repeat;
1207 if (f == NULL)
1208 f = mv->sq_repeat;
1209 if (f != NULL)
1210 return sequence_repeat(f, v, w);
1211 }
1212 else if (mw != NULL) {
1213 /* Note that the right hand operand should not be
1214 * mutated in this case so sq_inplace_repeat is not
1215 * used. */
1216 if (mw->sq_repeat)
1217 return sequence_repeat(mw->sq_repeat, w, v);
1218 }
1219 result = binop_type_error(v, w, "*=");
1220 }
1221 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001222}
1223
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001224PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001225PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1226{
1227 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1228 NB_SLOT(nb_matrix_multiply), "@=");
1229}
1230
1231PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001232PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1235 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001236}
1237
1238PyObject *
1239PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1240{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001241 if (Py_TYPE(v)->tp_as_number &&
1242 Py_TYPE(v)->tp_as_number->nb_inplace_power != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1244 }
1245 else {
1246 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1247 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001248}
1249
1250
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001251/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001252
1253PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001254PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001257
Victor Stinner71aea8e2016-08-19 16:59:55 +02001258 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001260 }
1261
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001262 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (m && m->nb_negative)
1264 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001267}
1268
1269PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001270PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001273
Victor Stinner71aea8e2016-08-19 16:59:55 +02001274 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001276 }
1277
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001278 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (m && m->nb_positive)
1280 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001283}
1284
1285PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001286PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001289
Victor Stinner71aea8e2016-08-19 16:59:55 +02001290 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001292 }
1293
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001294 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (m && m->nb_invert)
1296 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001299}
1300
1301PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001302PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001305
Victor Stinner71aea8e2016-08-19 16:59:55 +02001306 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001308 }
1309
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001310 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (m && m->nb_absolute)
1312 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001315}
1316
Victor Stinnera15e2602020-04-08 02:01:56 +02001317
Christian Tismerea62ce72018-06-09 20:32:25 +02001318int
1319PyIndex_Check(PyObject *obj)
1320{
Victor Stinnera15e2602020-04-08 02:01:56 +02001321 return _PyIndex_Check(obj);
Christian Tismerea62ce72018-06-09 20:32:25 +02001322}
1323
Victor Stinnera15e2602020-04-08 02:01:56 +02001324
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001325/* Return a Python int from the object item.
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001326 Can return an instance of int subclass.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001327 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001328 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001329*/
1330PyObject *
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001331_PyNumber_Index(PyObject *item)
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001334 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001336 }
1337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (PyLong_Check(item)) {
1339 Py_INCREF(item);
1340 return item;
1341 }
Victor Stinnera15e2602020-04-08 02:01:56 +02001342 if (!_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyErr_Format(PyExc_TypeError,
1344 "'%.200s' object cannot be interpreted "
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001345 "as an integer", Py_TYPE(item)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001346 return NULL;
1347 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001348 result = Py_TYPE(item)->tp_as_number->nb_index(item);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001349 if (!result || PyLong_CheckExact(result))
1350 return result;
1351 if (!PyLong_Check(result)) {
1352 PyErr_Format(PyExc_TypeError,
1353 "__index__ returned non-int (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001354 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001355 Py_DECREF(result);
1356 return NULL;
1357 }
1358 /* Issue #17576: warn if 'result' not of exact type int. */
1359 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1360 "__index__ returned non-int (type %.200s). "
1361 "The ability to return an instance of a strict subclass of int "
1362 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001363 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001364 Py_DECREF(result);
1365 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 }
1367 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001368}
1369
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001370/* Return an exact Python int from the object item.
1371 Raise TypeError if the result is not an int
1372 or if the object cannot be interpreted as an index.
1373*/
1374PyObject *
1375PyNumber_Index(PyObject *item)
1376{
1377 PyObject *result = _PyNumber_Index(item);
1378 if (result != NULL && !PyLong_CheckExact(result)) {
1379 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1380 }
1381 return result;
1382}
1383
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001384/* Return an error on Overflow only if err is not NULL*/
1385
1386Py_ssize_t
1387PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_ssize_t result;
1390 PyObject *runerr;
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001391 PyObject *value = _PyNumber_Index(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (value == NULL)
1393 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 /* We're done if PyLong_AsSsize_t() returns without error. */
1396 result = PyLong_AsSsize_t(value);
Victor Stinner61b64922020-06-23 15:55:06 +02001397 if (result != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001399
Victor Stinner61b64922020-06-23 15:55:06 +02001400 PyThreadState *tstate = _PyThreadState_GET();
1401 runerr = _PyErr_Occurred(tstate);
1402 if (!runerr) {
1403 goto finish;
1404 }
1405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* Error handling code -- only manage OverflowError differently */
Victor Stinner61b64922020-06-23 15:55:06 +02001407 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 goto finish;
Victor Stinner61b64922020-06-23 15:55:06 +02001409 }
1410 _PyErr_Clear(tstate);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* If no error-handling desired then the default clipping
Victor Stinner61b64922020-06-23 15:55:06 +02001413 is sufficient. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (!err) {
1415 assert(PyLong_Check(value));
1416 /* Whether or not it is less than or equal to
1417 zero is determined by the sign of ob_size
1418 */
1419 if (_PyLong_Sign(value) < 0)
1420 result = PY_SSIZE_T_MIN;
1421 else
1422 result = PY_SSIZE_T_MAX;
1423 }
1424 else {
1425 /* Otherwise replace the error with caller's error object. */
Victor Stinner61b64922020-06-23 15:55:06 +02001426 _PyErr_Format(tstate, err,
1427 "cannot fit '%.200s' into an index-sized integer",
1428 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001430
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001431 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_DECREF(value);
1433 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001434}
1435
1436
Guido van Rossume15dee51995-07-18 14:12:02 +00001437PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001438PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001439{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001440 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001443 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001444 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001445
Victor Stinner71aea8e2016-08-19 16:59:55 +02001446 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001448 }
1449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (PyLong_CheckExact(o)) {
1451 Py_INCREF(o);
1452 return o;
1453 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001454 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001456 /* Convert using the nb_int slot, which should return something
1457 of exact type int. */
1458 result = m->nb_int(o);
1459 if (!result || PyLong_CheckExact(result))
1460 return result;
1461 if (!PyLong_Check(result)) {
1462 PyErr_Format(PyExc_TypeError,
Victor Stinner61b64922020-06-23 15:55:06 +02001463 "__int__ returned non-int (type %.200s)",
1464 result->ob_type->tp_name);
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001465 Py_DECREF(result);
1466 return NULL;
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001467 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001468 /* Issue #17576: warn if 'result' not of exact type int. */
1469 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1470 "__int__ returned non-int (type %.200s). "
1471 "The ability to return an instance of a strict subclass of int "
1472 "is deprecated, and may be removed in a future version of Python.",
1473 result->ob_type->tp_name)) {
1474 Py_DECREF(result);
1475 return NULL;
1476 }
1477 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001478 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001480 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001481 return PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001482 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001483 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001485 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001487 if (result == NULL || PyLong_CheckExact(result)) {
1488 return result;
1489 }
1490 if (PyLong_Check(result)) {
1491 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1492 return result;
1493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001495 but int() needs to return an int. */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001496 if (!PyIndex_Check(result)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001497 PyErr_Format(
1498 PyExc_TypeError,
1499 "__trunc__ returned non-Integral (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001500 Py_TYPE(result)->tp_name);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001501 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001502 return NULL;
1503 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001504 Py_SETREF(result, PyNumber_Index(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001505 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001507 if (PyErr_Occurred())
1508 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001509
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001510 if (PyUnicode_Check(o))
1511 /* The below check is done in PyLong_FromUnicode(). */
1512 return PyLong_FromUnicodeObject(o, 10);
1513
Martin Pantereeb896c2015-11-07 02:32:21 +00001514 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001516 * doesn't do. In particular int('9\x005') must raise an
1517 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001519 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1520 PyBytes_GET_SIZE(o), 10);
1521
1522 if (PyByteArray_Check(o))
1523 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1524 PyByteArray_GET_SIZE(o), 10);
1525
1526 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001527 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001528
1529 /* Copy to NUL-terminated buffer. */
1530 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1531 if (bytes == NULL) {
1532 PyBuffer_Release(&view);
1533 return NULL;
1534 }
1535 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1536 PyBytes_GET_SIZE(bytes), 10);
1537 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001538 PyBuffer_Release(&view);
1539 return result;
1540 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001541
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001542 return type_error("int() argument must be a string, a bytes-like object "
1543 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001544}
1545
1546PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001547PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001550
Victor Stinner71aea8e2016-08-19 16:59:55 +02001551 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001553 }
1554
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001555 if (PyFloat_CheckExact(o)) {
1556 Py_INCREF(o);
1557 return o;
1558 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001559 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (m && m->nb_float) { /* This should include subclasses of float */
1561 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001562 double val;
1563 if (!res || PyFloat_CheckExact(res)) {
1564 return res;
1565 }
1566 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001568 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001569 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 Py_DECREF(res);
1571 return NULL;
1572 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001573 /* Issue #26983: warn if 'res' not of exact type float. */
1574 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1575 "%.50s.__float__ returned non-float (type %.50s). "
1576 "The ability to return an instance of a strict subclass of float "
1577 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001578 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001579 Py_DECREF(res);
1580 return NULL;
1581 }
1582 val = PyFloat_AS_DOUBLE(res);
1583 Py_DECREF(res);
1584 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001586 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001587 PyObject *res = _PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001588 if (!res) {
1589 return NULL;
1590 }
1591 double val = PyLong_AsDouble(res);
1592 Py_DECREF(res);
1593 if (val == -1.0 && PyErr_Occurred()) {
1594 return NULL;
1595 }
1596 return PyFloat_FromDouble(val);
1597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001599 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 }
1601 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001602}
1603
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001604
1605PyObject *
1606PyNumber_ToBase(PyObject *n, int base)
1607{
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001608 if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1609 PyErr_SetString(PyExc_SystemError,
1610 "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1611 return NULL;
1612 }
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001613 PyObject *index = _PyNumber_Index(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (!index)
1615 return NULL;
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001616 PyObject *res = _PyLong_Format(index, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 Py_DECREF(index);
1618 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001619}
1620
1621
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001622/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001623
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001624int
Fred Drake79912472000-07-09 04:06:11 +00001625PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (PyDict_Check(s))
1628 return 0;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001629 return Py_TYPE(s)->tp_as_sequence &&
1630 Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001631}
1632
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001634PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (s == NULL) {
1639 null_error();
1640 return -1;
1641 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001642
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001643 m = Py_TYPE(s)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001644 if (m && m->sq_length) {
1645 Py_ssize_t len = m->sq_length(s);
1646 assert(len >= 0 || PyErr_Occurred());
1647 return len;
1648 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001649
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001650 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001651 type_error("%.200s is not a sequence", s);
1652 return -1;
1653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 type_error("object of type '%.200s' has no len()", s);
1655 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001656}
1657
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001658#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001659Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001660PySequence_Length(PyObject *s)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001663}
1664#define PySequence_Length PySequence_Size
1665
Guido van Rossume15dee51995-07-18 14:12:02 +00001666PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001667PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001670
Victor Stinner71aea8e2016-08-19 16:59:55 +02001671 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001673 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001674
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001675 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (m && m->sq_concat)
1677 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 /* Instances of user classes defining an __add__() method only
1680 have an nb_add slot, not an sq_concat slot. So we fall back
1681 to nb_add if both arguments appear to be sequences. */
1682 if (PySequence_Check(s) && PySequence_Check(o)) {
1683 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1684 if (result != Py_NotImplemented)
1685 return result;
1686 Py_DECREF(result);
1687 }
1688 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001689}
1690
1691PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001692PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001695
Victor Stinner71aea8e2016-08-19 16:59:55 +02001696 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001698 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001699
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001700 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (m && m->sq_repeat)
1702 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 /* Instances of user classes defining a __mul__() method only
1705 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1706 to nb_multiply if o appears to be a sequence. */
1707 if (PySequence_Check(o)) {
1708 PyObject *n, *result;
1709 n = PyLong_FromSsize_t(count);
1710 if (n == NULL)
1711 return NULL;
1712 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1713 Py_DECREF(n);
1714 if (result != Py_NotImplemented)
1715 return result;
1716 Py_DECREF(result);
1717 }
1718 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001719}
1720
1721PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001722PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001725
Victor Stinner71aea8e2016-08-19 16:59:55 +02001726 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001728 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001729
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001730 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (m && m->sq_inplace_concat)
1732 return m->sq_inplace_concat(s, o);
1733 if (m && m->sq_concat)
1734 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (PySequence_Check(s) && PySequence_Check(o)) {
1737 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1738 NB_SLOT(nb_add));
1739 if (result != Py_NotImplemented)
1740 return result;
1741 Py_DECREF(result);
1742 }
1743 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001744}
1745
1746PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001747PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001750
Victor Stinner71aea8e2016-08-19 16:59:55 +02001751 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001753 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001754
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001755 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (m && m->sq_inplace_repeat)
1757 return m->sq_inplace_repeat(o, count);
1758 if (m && m->sq_repeat)
1759 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (PySequence_Check(o)) {
1762 PyObject *n, *result;
1763 n = PyLong_FromSsize_t(count);
1764 if (n == NULL)
1765 return NULL;
1766 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1767 NB_SLOT(nb_multiply));
1768 Py_DECREF(n);
1769 if (result != Py_NotImplemented)
1770 return result;
1771 Py_DECREF(result);
1772 }
1773 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001774}
1775
1776PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001777PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001780
Victor Stinner71aea8e2016-08-19 16:59:55 +02001781 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001783 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001784
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001785 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (m && m->sq_item) {
1787 if (i < 0) {
1788 if (m->sq_length) {
1789 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001790 if (l < 0) {
1791 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 i += l;
1795 }
1796 }
1797 return m->sq_item(s, i);
1798 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001799
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001800 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001801 return type_error("%.200s is not a sequence", s);
1802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001804}
1805
1806PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001807PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001810
Victor Stinner71aea8e2016-08-19 16:59:55 +02001811 if (!s) {
1812 return null_error();
1813 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001814
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001815 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001816 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyObject *res;
1818 PyObject *slice = _PySlice_FromIndices(i1, i2);
1819 if (!slice)
1820 return NULL;
1821 res = mp->mp_subscript(s, slice);
1822 Py_DECREF(slice);
1823 return res;
1824 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001827}
1828
1829int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001830PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (s == NULL) {
1835 null_error();
1836 return -1;
1837 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001838
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001839 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (m && m->sq_ass_item) {
1841 if (i < 0) {
1842 if (m->sq_length) {
1843 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001844 if (l < 0) {
1845 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 i += l;
1849 }
1850 }
1851 return m->sq_ass_item(s, i, o);
1852 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001853
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001854 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001855 type_error("%.200s is not a sequence", s);
1856 return -1;
1857 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 type_error("'%.200s' object does not support item assignment", s);
1859 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001860}
1861
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001862int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001863PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (s == NULL) {
1868 null_error();
1869 return -1;
1870 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001871
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001872 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (m && m->sq_ass_item) {
1874 if (i < 0) {
1875 if (m->sq_length) {
1876 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001877 if (l < 0) {
1878 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 i += l;
1882 }
1883 }
1884 return m->sq_ass_item(s, i, (PyObject *)NULL);
1885 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001886
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001887 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001888 type_error("%.200s is not a sequence", s);
1889 return -1;
1890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 type_error("'%.200s' object doesn't support item deletion", s);
1892 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001893}
1894
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001895int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001896PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (s == NULL) {
1901 null_error();
1902 return -1;
1903 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001904
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001905 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001906 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 int res;
1908 PyObject *slice = _PySlice_FromIndices(i1, i2);
1909 if (!slice)
1910 return -1;
1911 res = mp->mp_ass_subscript(s, slice, o);
1912 Py_DECREF(slice);
1913 return res;
1914 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 type_error("'%.200s' object doesn't support slice assignment", s);
1917 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001918}
1919
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001920int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001921PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (s == NULL) {
1926 null_error();
1927 return -1;
1928 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001929
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001930 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001931 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 int res;
1933 PyObject *slice = _PySlice_FromIndices(i1, i2);
1934 if (!slice)
1935 return -1;
1936 res = mp->mp_ass_subscript(s, slice, NULL);
1937 Py_DECREF(slice);
1938 return res;
1939 }
1940 type_error("'%.200s' object doesn't support slice deletion", s);
1941 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001942}
1943
Guido van Rossume15dee51995-07-18 14:12:02 +00001944PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001945PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject *it; /* iter(v) */
1948 Py_ssize_t n; /* guess for result tuple size */
1949 PyObject *result = NULL;
1950 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001951
Victor Stinner71aea8e2016-08-19 16:59:55 +02001952 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001954 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* Special-case the common tuple and list cases, for efficiency. */
1957 if (PyTuple_CheckExact(v)) {
1958 /* Note that we can't know whether it's safe to return
1959 a tuple *subclass* instance as-is, hence the restriction
1960 to exact tuples here. In contrast, lists always make
1961 a copy, so there's no need for exactness below. */
1962 Py_INCREF(v);
1963 return v;
1964 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001965 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* Get iterator. */
1969 it = PyObject_GetIter(v);
1970 if (it == NULL)
1971 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001974 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (n == -1)
1976 goto Fail;
1977 result = PyTuple_New(n);
1978 if (result == NULL)
1979 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Fill the tuple. */
1982 for (j = 0; ; ++j) {
1983 PyObject *item = PyIter_Next(it);
1984 if (item == NULL) {
1985 if (PyErr_Occurred())
1986 goto Fail;
1987 break;
1988 }
1989 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001990 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* The over-allocation strategy can grow a bit faster
1992 than for lists because unlike lists the
1993 over-allocation isn't permanent -- we reclaim
1994 the excess before the end of this routine.
1995 So, grow by ten and then add 25%.
1996 */
Martin Pantere8db8612016-07-25 02:30:05 +00001997 newn += 10u;
1998 newn += newn >> 2;
1999 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 /* Check for overflow */
2001 PyErr_NoMemory();
2002 Py_DECREF(item);
2003 goto Fail;
2004 }
Martin Pantere8db8612016-07-25 02:30:05 +00002005 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (_PyTuple_Resize(&result, n) != 0) {
2007 Py_DECREF(item);
2008 goto Fail;
2009 }
2010 }
2011 PyTuple_SET_ITEM(result, j, item);
2012 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 /* Cut tuple back if guess was too large. */
2015 if (j < n &&
2016 _PyTuple_Resize(&result, j) != 0)
2017 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_DECREF(it);
2020 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002021
2022Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_XDECREF(result);
2024 Py_DECREF(it);
2025 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002026}
2027
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002028PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002029PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 PyObject *result; /* result list */
2032 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002033
Victor Stinner71aea8e2016-08-19 16:59:55 +02002034 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002036 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 result = PyList_New(0);
2039 if (result == NULL)
2040 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 rv = _PyList_Extend((PyListObject *)result, v);
2043 if (rv == NULL) {
2044 Py_DECREF(result);
2045 return NULL;
2046 }
2047 Py_DECREF(rv);
2048 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002049}
2050
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002051PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002052PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002055
Victor Stinner71aea8e2016-08-19 16:59:55 +02002056 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002058 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2061 Py_INCREF(v);
2062 return v;
2063 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 it = PyObject_GetIter(v);
2066 if (it == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +02002067 PyThreadState *tstate = _PyThreadState_GET();
2068 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2069 _PyErr_SetString(tstate, PyExc_TypeError, m);
2070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return NULL;
2072 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 v = PySequence_List(it);
2075 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002078}
2079
Tim Peters16a77ad2001-09-08 04:00:12 +00002080/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2082 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2083 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002084 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2085*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002086Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002087_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 Py_ssize_t n;
2090 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2091 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (seq == NULL || obj == NULL) {
2094 null_error();
2095 return -1;
2096 }
Tim Peters75f8e352001-05-05 11:33:43 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 it = PyObject_GetIter(seq);
2099 if (it == NULL) {
Serhiy Storchakacafe1b62020-06-22 10:43:35 +03002100 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2101 type_error("argument of type '%.200s' is not iterable", seq);
2102 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 return -1;
2104 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 n = wrapped = 0;
2107 for (;;) {
2108 int cmp;
2109 PyObject *item = PyIter_Next(it);
2110 if (item == NULL) {
2111 if (PyErr_Occurred())
2112 goto Fail;
2113 break;
2114 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002115
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002116 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 Py_DECREF(item);
2118 if (cmp < 0)
2119 goto Fail;
2120 if (cmp > 0) {
2121 switch (operation) {
2122 case PY_ITERSEARCH_COUNT:
2123 if (n == PY_SSIZE_T_MAX) {
2124 PyErr_SetString(PyExc_OverflowError,
2125 "count exceeds C integer size");
2126 goto Fail;
2127 }
2128 ++n;
2129 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 case PY_ITERSEARCH_INDEX:
2132 if (wrapped) {
2133 PyErr_SetString(PyExc_OverflowError,
2134 "index exceeds C integer size");
2135 goto Fail;
2136 }
2137 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 case PY_ITERSEARCH_CONTAINS:
2140 n = 1;
2141 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002144 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 }
2146 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (operation == PY_ITERSEARCH_INDEX) {
2149 if (n == PY_SSIZE_T_MAX)
2150 wrapped = 1;
2151 ++n;
2152 }
2153 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (operation != PY_ITERSEARCH_INDEX)
2156 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyErr_SetString(PyExc_ValueError,
2159 "sequence.index(x): x not in sequence");
2160 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002161Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 n = -1;
2163 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002164Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 Py_DECREF(it);
2166 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002167
Guido van Rossume15dee51995-07-18 14:12:02 +00002168}
2169
Tim Peters16a77ad2001-09-08 04:00:12 +00002170/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002171Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002172PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002175}
2176
Tim Peterscb8d3682001-05-05 21:05:01 +00002177/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002178 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002179 */
2180int
2181PySequence_Contains(PyObject *seq, PyObject *ob)
2182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 Py_ssize_t result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002184 PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (sqm != NULL && sqm->sq_contains != NULL)
2186 return (*sqm->sq_contains)(seq, ob);
2187 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2188 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002189}
2190
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002191/* Backwards compatibility */
2192#undef PySequence_In
2193int
Fred Drake79912472000-07-09 04:06:11 +00002194PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002197}
2198
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002199Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002200PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002203}
2204
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002205/* Operations on mappings */
2206
2207int
Fred Drake79912472000-07-09 04:06:11 +00002208PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002209{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002210 return o && Py_TYPE(o)->tp_as_mapping &&
2211 Py_TYPE(o)->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002212}
2213
Martin v. Löwis18e16552006-02-15 17:27:45 +00002214Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002215PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (o == NULL) {
2220 null_error();
2221 return -1;
2222 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002223
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002224 m = Py_TYPE(o)->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002225 if (m && m->mp_length) {
2226 Py_ssize_t len = m->mp_length(o);
2227 assert(len >= 0 || PyErr_Occurred());
2228 return len;
2229 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002230
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002231 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002232 type_error("%.200s is not a mapping", o);
2233 return -1;
2234 }
2235 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 type_error("object of type '%.200s' has no len()", o);
2237 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002238}
2239
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002240#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002241Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002242PyMapping_Length(PyObject *o)
2243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002245}
2246#define PyMapping_Length PyMapping_Size
2247
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002248PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002249PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002252
Victor Stinner71aea8e2016-08-19 16:59:55 +02002253 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002255 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 okey = PyUnicode_FromString(key);
2258 if (okey == NULL)
2259 return NULL;
2260 r = PyObject_GetItem(o, okey);
2261 Py_DECREF(okey);
2262 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002263}
2264
2265int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002266PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyObject *okey;
2269 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (key == NULL) {
2272 null_error();
2273 return -1;
2274 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 okey = PyUnicode_FromString(key);
2277 if (okey == NULL)
2278 return -1;
2279 r = PyObject_SetItem(o, okey, value);
2280 Py_DECREF(okey);
2281 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002282}
2283
2284int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002285PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 v = PyMapping_GetItemString(o, key);
2290 if (v) {
2291 Py_DECREF(v);
2292 return 1;
2293 }
2294 PyErr_Clear();
2295 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002296}
2297
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002298int
Fred Drake79912472000-07-09 04:06:11 +00002299PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 v = PyObject_GetItem(o, key);
2304 if (v) {
2305 Py_DECREF(v);
2306 return 1;
2307 }
2308 PyErr_Clear();
2309 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002310}
2311
Oren Milman0ccc0f62017-10-08 11:17:46 +03002312/* This function is quite similar to PySequence_Fast(), but specialized to be
2313 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2314 */
2315static PyObject *
2316method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2317{
2318 PyObject *it, *result, *meth_output;
2319
2320 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002321 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002322 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2323 return meth_output;
2324 }
2325 it = PyObject_GetIter(meth_output);
2326 if (it == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +02002327 PyThreadState *tstate = _PyThreadState_GET();
2328 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2329 _PyErr_Format(tstate, PyExc_TypeError,
2330 "%.200s.%U() returned a non-iterable (type %.200s)",
2331 Py_TYPE(o)->tp_name,
2332 _PyUnicode_FromId(meth_id),
2333 Py_TYPE(meth_output)->tp_name);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002334 }
2335 Py_DECREF(meth_output);
2336 return NULL;
2337 }
2338 Py_DECREF(meth_output);
2339 result = PySequence_List(it);
2340 Py_DECREF(it);
2341 return result;
2342}
2343
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002344PyObject *
2345PyMapping_Keys(PyObject *o)
2346{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002347 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002348
Oren Milman0ccc0f62017-10-08 11:17:46 +03002349 if (o == NULL) {
2350 return null_error();
2351 }
2352 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002354 }
2355 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002356}
2357
2358PyObject *
2359PyMapping_Items(PyObject *o)
2360{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002361 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002362
Oren Milman0ccc0f62017-10-08 11:17:46 +03002363 if (o == NULL) {
2364 return null_error();
2365 }
2366 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002368 }
2369 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002370}
2371
2372PyObject *
2373PyMapping_Values(PyObject *o)
2374{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002375 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002376
Oren Milman0ccc0f62017-10-08 11:17:46 +03002377 if (o == NULL) {
2378 return null_error();
2379 }
2380 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002382 }
2383 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002384}
2385
Guido van Rossum823649d2001-03-21 18:40:58 +00002386/* isinstance(), issubclass() */
2387
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002388/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002389 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002390 * 1. getattr(cls, '__bases__') could raise an AttributeError
2391 * 2. getattr(cls, '__bases__') could raise some other exception
2392 * 3. getattr(cls, '__bases__') could return a tuple
2393 * 4. getattr(cls, '__bases__') could return something other than a tuple
2394 *
2395 * Only state #3 is a non-error state and only it returns a non-NULL object
2396 * (it returns the retrieved tuple).
2397 *
2398 * Any raised AttributeErrors are masked by clearing the exception and
2399 * returning NULL. If an object other than a tuple comes out of __bases__,
2400 * then again, the return value is NULL. So yes, these two situations
2401 * produce exactly the same results: NULL is returned and no error is set.
2402 *
2403 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002405 * exception to be propagated along.
2406 *
2407 * Callers are expected to test for PyErr_Occurred() when the return value
2408 * is NULL to decide whether a valid exception should be propagated or not.
2409 * When there's no exception to propagate, it's customary for the caller to
2410 * set a TypeError.
2411 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002412static PyObject *
2413abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002414{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002415 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 Py_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002419 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 Py_END_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002421 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 Py_DECREF(bases);
2423 return NULL;
2424 }
2425 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002426}
2427
2428
2429static int
2430abstract_issubclass(PyObject *derived, PyObject *cls)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyObject *bases = NULL;
2433 Py_ssize_t i, n;
2434 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 while (1) {
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002437 if (derived == cls) {
2438 Py_XDECREF(bases); /* See below comment */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return 1;
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002440 }
2441 /* Use XSETREF to drop bases reference *after* finishing with
2442 derived; bases might be the only reference to it.
2443 XSETREF is used instead of SETREF, because bases is NULL on the
2444 first iteration of the loop.
2445 */
2446 Py_XSETREF(bases, abstract_get_bases(derived));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 if (bases == NULL) {
2448 if (PyErr_Occurred())
2449 return -1;
2450 return 0;
2451 }
2452 n = PyTuple_GET_SIZE(bases);
2453 if (n == 0) {
2454 Py_DECREF(bases);
2455 return 0;
2456 }
2457 /* Avoid recursivity in the single inheritance case */
2458 if (n == 1) {
2459 derived = PyTuple_GET_ITEM(bases, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 continue;
2461 }
2462 for (i = 0; i < n; i++) {
2463 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2464 if (r != 0)
2465 break;
2466 }
2467 Py_DECREF(bases);
2468 return r;
2469 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002470}
2471
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002472static int
2473check_class(PyObject *cls, const char *error)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 PyObject *bases = abstract_get_bases(cls);
2476 if (bases == NULL) {
2477 /* Do not mask errors. */
Victor Stinner61b64922020-06-23 15:55:06 +02002478 PyThreadState *tstate = _PyThreadState_GET();
2479 if (!_PyErr_Occurred(tstate)) {
2480 _PyErr_SetString(tstate, PyExc_TypeError, error);
2481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return 0;
2483 }
2484 Py_DECREF(bases);
2485 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002486}
2487
Brett Cannon4f653312004-03-20 22:52:14 +00002488static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002489object_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002492 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002493 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (PyType_Check(cls)) {
2496 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2497 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002498 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2499 if (icls != NULL) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002500 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002502 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002504 }
2505 else {
2506 retval = 0;
2507 }
2508 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 }
2510 }
2511 }
2512 else {
2513 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002514 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002516 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2517 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 retval = abstract_issubclass(icls, cls);
2519 Py_DECREF(icls);
2520 }
2521 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002524}
2525
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002526static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002527object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002528{
Benjamin Petersonce798522012-01-22 11:24:29 -05002529 _Py_IDENTIFIER(__instancecheck__);
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* Quick test for an exact match */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002532 if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 return 1;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002534 }
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002535
Georg Brandl72b8a802014-10-03 09:26:37 +02002536 /* We know what type's __instancecheck__ does. */
2537 if (PyType_CheckExact(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002538 return object_isinstance(inst, cls);
Georg Brandl72b8a802014-10-03 09:26:37 +02002539 }
2540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (PyTuple_Check(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002542 /* Not a general sequence -- that opens up the road to
2543 recursion and stack overflow. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002544 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002546 }
2547 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2548 int r = 0;
2549 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002551 r = object_recursive_isinstance(tstate, inst, item);
2552 if (r != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /* either found it, or got an error */
2554 break;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002557 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return r;
2559 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002560
Victor Stinner850a4bd2020-02-04 13:42:13 +01002561 PyObject *checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (checker != NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002563 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002565 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002567
Petr Viktorinffd97532020-02-11 17:46:57 +01002568 PyObject *res = PyObject_CallOneArg(checker, inst);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002569 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002571
2572 if (res == NULL) {
2573 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002575 int ok = PyObject_IsTrue(res);
2576 Py_DECREF(res);
2577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return ok;
2579 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002580 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002582 }
2583
Victor Stinner850a4bd2020-02-04 13:42:13 +01002584 /* cls has no __instancecheck__() method */
2585 return object_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002586}
2587
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002588
2589int
2590PyObject_IsInstance(PyObject *inst, PyObject *cls)
2591{
2592 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner850a4bd2020-02-04 13:42:13 +01002593 return object_recursive_isinstance(tstate, inst, cls);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002594}
2595
2596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002598recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (PyType_Check(cls) && PyType_Check(derived)) {
2601 /* Fast path (non-recursive) */
2602 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2603 }
2604 if (!check_class(derived,
2605 "issubclass() arg 1 must be a class"))
2606 return -1;
2607 if (!check_class(cls,
2608 "issubclass() arg 2 must be a class"
2609 " or tuple of classes"))
2610 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002613}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002614
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002615static int
2616object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002617{
Benjamin Petersonce798522012-01-22 11:24:29 -05002618 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002620
Georg Brandl72b8a802014-10-03 09:26:37 +02002621 /* We know what type's __subclasscheck__ does. */
2622 if (PyType_CheckExact(cls)) {
2623 /* Quick test for an exact match */
2624 if (derived == cls)
2625 return 1;
2626 return recursive_issubclass(derived, cls);
2627 }
2628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (PyTuple_Check(cls)) {
Antoine Pitrouec569b72008-08-26 22:40:48 +00002630
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002631 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002633 }
2634 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2635 int r = 0;
2636 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002638 r = object_issubclass(tstate, derived, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 if (r != 0)
2640 /* either found it, or got an error */
2641 break;
2642 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002643 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return r;
2645 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002646
Benjamin Petersonce798522012-01-22 11:24:29 -05002647 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 if (checker != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 int ok = -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002650 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 Py_DECREF(checker);
2652 return ok;
2653 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002654 PyObject *res = PyObject_CallOneArg(checker, derived);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002655 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 Py_DECREF(checker);
2657 if (res != NULL) {
2658 ok = PyObject_IsTrue(res);
2659 Py_DECREF(res);
2660 }
2661 return ok;
2662 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002663 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002665 }
2666
Georg Brandl72b8a802014-10-03 09:26:37 +02002667 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002669}
2670
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002671
2672int
2673PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2674{
2675 PyThreadState *tstate = _PyThreadState_GET();
2676 return object_issubclass(tstate, derived, cls);
2677}
2678
2679
Antoine Pitrouec569b72008-08-26 22:40:48 +00002680int
2681_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2682{
Victor Stinner850a4bd2020-02-04 13:42:13 +01002683 return object_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002684}
2685
2686int
2687_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002690}
2691
2692
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002693PyObject *
2694PyObject_GetIter(PyObject *o)
2695{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002696 PyTypeObject *t = Py_TYPE(o);
Victor Stinner14e6d092016-12-09 17:08:59 +01002697 getiterfunc f;
2698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 f = t->tp_iter;
2700 if (f == NULL) {
2701 if (PySequence_Check(o))
2702 return PySeqIter_New(o);
2703 return type_error("'%.200s' object is not iterable", o);
2704 }
2705 else {
2706 PyObject *res = (*f)(o);
2707 if (res != NULL && !PyIter_Check(res)) {
2708 PyErr_Format(PyExc_TypeError,
2709 "iter() returned non-iterator "
2710 "of type '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002711 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 Py_DECREF(res);
2713 res = NULL;
2714 }
2715 return res;
2716 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002717}
2718
Christian Tismerea62ce72018-06-09 20:32:25 +02002719#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002720
Christian Tismerea62ce72018-06-09 20:32:25 +02002721int PyIter_Check(PyObject *obj)
2722{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002723 return Py_TYPE(obj)->tp_iternext != NULL &&
2724 Py_TYPE(obj)->tp_iternext != &_PyObject_NextNotImplemented;
Christian Tismerea62ce72018-06-09 20:32:25 +02002725}
2726
Tim Petersf4848da2001-05-05 00:14:56 +00002727/* Return next item.
2728 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2729 * If the iteration terminates normally, return NULL and clear the
2730 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2731 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002733 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002734PyObject *
2735PyIter_Next(PyObject *iter)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 PyObject *result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002738 result = (*Py_TYPE(iter)->tp_iternext)(iter);
Victor Stinner61b64922020-06-23 15:55:06 +02002739 if (result == NULL) {
2740 PyThreadState *tstate = _PyThreadState_GET();
2741 if (_PyErr_Occurred(tstate)
2742 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2743 {
2744 _PyErr_Clear(tstate);
2745 }
2746 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002748}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002749
2750
2751/*
2752 * Flatten a sequence of bytes() objects into a C array of
2753 * NULL terminated string pointers with a NULL char* terminating the array.
2754 * (ie: an argv or env list)
2755 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002756 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2757 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002758 */
2759char *const *
2760_PySequence_BytesToCharpArray(PyObject* self)
2761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 char **array;
2763 Py_ssize_t i, argc;
2764 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002765 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 argc = PySequence_Size(self);
2768 if (argc == -1)
2769 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002770
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002771 assert(argc >= 0);
2772
2773 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2774 PyErr_NoMemory();
2775 return NULL;
2776 }
2777
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002778 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (array == NULL) {
2780 PyErr_NoMemory();
2781 return NULL;
2782 }
2783 for (i = 0; i < argc; ++i) {
2784 char *data;
2785 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002786 if (item == NULL) {
2787 /* NULL terminate before freeing. */
2788 array[i] = NULL;
2789 goto fail;
2790 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002791 /* check for embedded null bytes */
2792 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 /* NULL terminate before freeing. */
2794 array[i] = NULL;
2795 goto fail;
2796 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002797 size = PyBytes_GET_SIZE(item) + 1;
2798 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 if (!array[i]) {
2800 PyErr_NoMemory();
2801 goto fail;
2802 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002803 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 Py_DECREF(item);
2805 }
2806 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002809
2810fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 Py_XDECREF(item);
2812 _Py_FreeCharPArray(array);
2813 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002814}
2815
2816
2817/* Free's a NULL terminated char** array of C strings. */
2818void
2819_Py_FreeCharPArray(char *const array[])
2820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 Py_ssize_t i;
2822 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002823 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002825 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002826}