blob: 7ab58a8bd52c39ed9c9bc53682e363aadc2ae09e [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 Stinnerbe434dc2019-11-05 00:51:22 +01004#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +00006#include <ctype.h>
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00007#include "structmember.h" /* we need the offsetof() macro from there */
Tim Peters64b5ce32001-09-10 20:52:51 +00008#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00009
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000012/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000013
14static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000016{
Victor Stinner0d76d2b2020-02-07 01:53:23 +010017 PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000019}
20
Guido van Rossum052b7e11996-11-11 15:08:19 +000021static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000022null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000024 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError,
26 "null argument to internal routine");
27 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000028}
29
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000030/* Operations on any object */
31
Guido van Rossume15dee51995-07-18 14:12:02 +000032PyObject *
Fred Drake79912472000-07-09 04:06:11 +000033PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000036
Victor Stinner71aea8e2016-08-19 16:59:55 +020037 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020039 }
40
Victor Stinner0d76d2b2020-02-07 01:53:23 +010041 v = (PyObject *)Py_TYPE(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 Py_INCREF(v);
43 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000044}
45
Martin v. Löwis18e16552006-02-15 17:27:45 +000046Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000047PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 if (o == NULL) {
52 null_error();
53 return -1;
54 }
Guido van Rossume15dee51995-07-18 14:12:02 +000055
Victor Stinner0d76d2b2020-02-07 01:53:23 +010056 m = Py_TYPE(o)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +030057 if (m && m->sq_length) {
58 Py_ssize_t len = m->sq_length(o);
59 assert(len >= 0 || PyErr_Occurred());
60 return len;
61 }
Guido van Rossume15dee51995-07-18 14:12:02 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000064}
65
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000066#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000067Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000068PyObject_Length(PyObject *o)
69{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000071}
72#define PyObject_Length PyObject_Size
73
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020074int
75_PyObject_HasLen(PyObject *o) {
76 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
77 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
78}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000079
Christian Heimes255f53b2007-12-08 15:33:56 +000080/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020081 or o.__length_hint__(). If those methods aren't found the defaultvalue is
82 returned. If one of the calls fails with an exception other than TypeError
83 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000084*/
85
86Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020087PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000088{
Christian Heimesb70e8a12012-10-06 17:16:39 +020089 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020090 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050091 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030092 if (_PyObject_HasLen(o)) {
93 res = PyObject_Length(o);
Serhiy Storchaka813f9432017-04-16 09:21:44 +030094 if (res < 0) {
95 assert(PyErr_Occurred());
Serhiy Storchakaf740d462013-10-24 23:19:51 +030096 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
97 return -1;
98 }
99 PyErr_Clear();
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200100 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300101 else {
102 return res;
103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 }
Christian Heimes6314d162012-10-06 17:13:29 +0200105 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200106 if (hint == NULL) {
107 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 return defaultvalue;
111 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100112 result = _PyObject_CallNoArg(hint);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200113 Py_DECREF(hint);
114 if (result == NULL) {
115 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
116 PyErr_Clear();
117 return defaultvalue;
118 }
119 return -1;
120 }
121 else if (result == Py_NotImplemented) {
122 Py_DECREF(result);
123 return defaultvalue;
124 }
125 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200126 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200127 Py_TYPE(result)->tp_name);
128 Py_DECREF(result);
129 return -1;
130 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200131 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200132 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200133 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200134 return -1;
135 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200136 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200137 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
138 return -1;
139 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200140 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000141}
142
Guido van Rossume15dee51995-07-18 14:12:02 +0000143PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000144PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 PyMappingMethods *m;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000147 PySequenceMethods *ms;
Guido van Rossume15dee51995-07-18 14:12:02 +0000148
Victor Stinner71aea8e2016-08-19 16:59:55 +0200149 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200151 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000152
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100153 m = Py_TYPE(o)->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100154 if (m && m->mp_subscript) {
155 PyObject *item = m->mp_subscript(o, key);
156 assert((item != NULL) ^ (PyErr_Occurred() != NULL));
157 return item;
158 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000159
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100160 ms = Py_TYPE(o)->tp_as_sequence;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000161 if (ms && ms->sq_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 if (PyIndex_Check(key)) {
163 Py_ssize_t key_value;
164 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
165 if (key_value == -1 && PyErr_Occurred())
166 return NULL;
167 return PySequence_GetItem(o, key_value);
168 }
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000169 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return type_error("sequence index must "
171 "be integer, not '%.200s'", key);
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000174
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100175 if (PyType_Check(o)) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200176 PyObject *meth, *result;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100177 _Py_IDENTIFIER(__class_getitem__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200178 if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
179 return NULL;
180 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100181 if (meth) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200182 result = _PyObject_CallOneArg(meth, key);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100183 Py_DECREF(meth);
184 return result;
185 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100186 }
187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000189}
190
191int
Fred Drake79912472000-07-09 04:06:11 +0000192PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (o == NULL || key == NULL || value == NULL) {
197 null_error();
198 return -1;
199 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100200 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (m && m->mp_ass_subscript)
202 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000203
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100204 if (Py_TYPE(o)->tp_as_sequence) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 if (PyIndex_Check(key)) {
206 Py_ssize_t key_value;
207 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
208 if (key_value == -1 && PyErr_Occurred())
209 return -1;
210 return PySequence_SetItem(o, key_value, value);
211 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100212 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 type_error("sequence index must be "
214 "integer, not '%.200s'", key);
215 return -1;
216 }
217 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 type_error("'%.200s' object does not support item assignment", o);
220 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000221}
222
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000223int
Fred Drake79912472000-07-09 04:06:11 +0000224PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (o == NULL || key == NULL) {
229 null_error();
230 return -1;
231 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100232 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (m && m->mp_ass_subscript)
234 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000235
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100236 if (Py_TYPE(o)->tp_as_sequence) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (PyIndex_Check(key)) {
238 Py_ssize_t key_value;
239 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
240 if (key_value == -1 && PyErr_Occurred())
241 return -1;
242 return PySequence_DelItem(o, key_value);
243 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100244 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 type_error("sequence index must be "
246 "integer, not '%.200s'", key);
247 return -1;
248 }
249 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 type_error("'%.200s' object does not support item deletion", o);
252 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000253}
254
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000255int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300256PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 PyObject *okey;
259 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 if (o == NULL || key == NULL) {
262 null_error();
263 return -1;
264 }
265 okey = PyUnicode_FromString(key);
266 if (okey == NULL)
267 return -1;
268 ret = PyObject_DelItem(o, okey);
269 Py_DECREF(okey);
270 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000271}
272
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000273/* We release the buffer right after use of this function which could
Guido van Rossum98297ee2007-11-06 21:34:58 +0000274 cause issues later on. Don't use these functions in new code.
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000275 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000276int
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000277PyObject_CheckReadBuffer(PyObject *obj)
278{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100279 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 Py_buffer view;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if (pb == NULL ||
283 pb->bf_getbuffer == NULL)
284 return 0;
285 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
286 PyErr_Clear();
287 return 0;
288 }
289 PyBuffer_Release(&view);
290 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000291}
292
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200293static int
294as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
299 null_error();
300 return -1;
301 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200302 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return -1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 *buffer = view.buf;
306 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200307 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000309}
310
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200311int
312PyObject_AsCharBuffer(PyObject *obj,
313 const char **buffer,
314 Py_ssize_t *buffer_len)
315{
316 return as_read_buffer(obj, (const void **)buffer, buffer_len);
317}
318
319int PyObject_AsReadBuffer(PyObject *obj,
320 const void **buffer,
321 Py_ssize_t *buffer_len)
322{
323 return as_read_buffer(obj, buffer, buffer_len);
324}
325
Guido van Rossum4c08d552000-03-10 22:55:18 +0000326int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 void **buffer,
328 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyBufferProcs *pb;
331 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
334 null_error();
335 return -1;
336 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100337 pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (pb == NULL ||
339 pb->bf_getbuffer == NULL ||
340 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
341 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400342 "expected a writable bytes-like object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return -1;
344 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 *buffer = view.buf;
347 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200348 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000350}
351
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000352/* Buffer C-API for Python 3.0 */
353
354int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000355PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000356{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100357 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200358
359 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400361 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 Py_TYPE(obj)->tp_name);
363 return -1;
364 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200365 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000366}
367
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000368static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100369_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 Py_ssize_t sd, dim;
372 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000373
Stefan Krah363af442015-02-01 14:53:54 +0100374 /* 1) len = product(shape) * itemsize
375 2) itemsize > 0
376 3) len = 0 <==> exists i: shape[i] = 0 */
377 if (view->len == 0) return 1;
378 if (view->strides == NULL) { /* C-contiguous by definition */
379 /* Trivially F-contiguous */
380 if (view->ndim <= 1) return 1;
381
382 /* ndim > 1 implies shape != NULL */
383 assert(view->shape != NULL);
384
385 /* Effectively 1-d */
386 sd = 0;
387 for (i=0; i<view->ndim; i++) {
388 if (view->shape[i] > 1) sd += 1;
389 }
390 return sd <= 1;
391 }
392
393 /* strides != NULL implies both of these */
394 assert(view->ndim > 0);
395 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 for (i=0; i<view->ndim; i++) {
399 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100400 if (dim > 1 && view->strides[i] != sd) {
401 return 0;
402 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 sd *= dim;
404 }
405 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000406}
407
408static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100409_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_ssize_t sd, dim;
412 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000413
Stefan Krah363af442015-02-01 14:53:54 +0100414 /* 1) len = product(shape) * itemsize
415 2) itemsize > 0
416 3) len = 0 <==> exists i: shape[i] = 0 */
417 if (view->len == 0) return 1;
418 if (view->strides == NULL) return 1; /* C-contiguous by definition */
419
420 /* strides != NULL implies both of these */
421 assert(view->ndim > 0);
422 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 for (i=view->ndim-1; i>=0; i--) {
426 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100427 if (dim > 1 && view->strides[i] != sd) {
428 return 0;
429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 sd *= dim;
431 }
432 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000433}
434
435int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100436PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000437{
438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000440
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100441 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100443 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100445 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 return (_IsCContiguous(view) || _IsFortranContiguous(view));
447 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000448}
449
450
Guido van Rossum98297ee2007-11-06 21:34:58 +0000451void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000452PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 char* pointer;
455 int i;
456 pointer = (char *)view->buf;
457 for (i = 0; i < view->ndim; i++) {
458 pointer += view->strides[i]*indices[i];
459 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
460 pointer = *((char**)pointer) + view->suboffsets[i];
461 }
462 }
463 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000464}
465
466
Guido van Rossum98297ee2007-11-06 21:34:58 +0000467void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000468_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 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 for (k=0; k<nd; k++) {
473 if (index[k] < shape[k]-1) {
474 index[k]++;
475 break;
476 }
477 else {
478 index[k] = 0;
479 }
480 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000481}
482
Guido van Rossum98297ee2007-11-06 21:34:58 +0000483void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000484_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 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 for (k=nd-1; k>=0; k--) {
489 if (index[k] < shape[k]-1) {
490 index[k]++;
491 break;
492 }
493 else {
494 index[k] = 0;
495 }
496 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000497}
498
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -0300499Py_ssize_t
500PyBuffer_SizeFromFormat(const char *format)
501{
502 PyObject *structmodule = NULL;
503 PyObject *calcsize = NULL;
504 PyObject *res = NULL;
505 PyObject *fmt = NULL;
506 Py_ssize_t itemsize = -1;
507
508 structmodule = PyImport_ImportModule("struct");
509 if (structmodule == NULL) {
510 return itemsize;
511 }
512
513 calcsize = PyObject_GetAttrString(structmodule, "calcsize");
514 if (calcsize == NULL) {
515 goto done;
516 }
517
518 fmt = PyUnicode_FromString(format);
519 if (fmt == NULL) {
520 goto done;
521 }
522
523 res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
524 if (res == NULL) {
525 goto done;
526 }
527
528 itemsize = PyLong_AsSsize_t(res);
529 if (itemsize < 0) {
530 goto done;
531 }
532
533done:
534 Py_DECREF(structmodule);
535 Py_XDECREF(calcsize);
536 Py_XDECREF(fmt);
537 Py_XDECREF(res);
538 return itemsize;
539}
540
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000541int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000542PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000545 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_ssize_t *indices, elements;
547 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (len > view->len) {
550 len = view->len;
551 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (PyBuffer_IsContiguous(view, fort)) {
554 /* simplest copy is all that is needed */
555 memcpy(view->buf, buf, len);
556 return 0;
557 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560
Stefan Krah7213fcc2015-02-01 16:19:23 +0100561 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
563 if (indices == NULL) {
564 PyErr_NoMemory();
565 return -1;
566 }
567 for (k=0; k<view->ndim;k++) {
568 indices[k] = 0;
569 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000572 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 }
574 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000575 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 }
577 src = buf;
578 /* XXX : This is not going to be the fastest code in the world
579 several optimizations are possible.
580 */
581 elements = len / view->itemsize;
582 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 ptr = PyBuffer_GetPointer(view, indices);
584 memcpy(ptr, src, view->itemsize);
585 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100586 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyMem_Free(indices);
590 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000591}
592
Guido van Rossum98297ee2007-11-06 21:34:58 +0000593int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 Py_buffer view_dest, view_src;
596 int k;
597 Py_ssize_t *indices, elements;
598 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!PyObject_CheckBuffer(dest) ||
601 !PyObject_CheckBuffer(src)) {
602 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400603 "both destination and source must be "\
604 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return -1;
606 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
609 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
610 PyBuffer_Release(&view_dest);
611 return -1;
612 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (view_dest.len < view_src.len) {
615 PyErr_SetString(PyExc_BufferError,
616 "destination is too small to receive data from source");
617 PyBuffer_Release(&view_dest);
618 PyBuffer_Release(&view_src);
619 return -1;
620 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
623 PyBuffer_IsContiguous(&view_src, 'C')) ||
624 (PyBuffer_IsContiguous(&view_dest, 'F') &&
625 PyBuffer_IsContiguous(&view_src, 'F'))) {
626 /* simplest copy is all that is needed */
627 memcpy(view_dest.buf, view_src.buf, view_src.len);
628 PyBuffer_Release(&view_dest);
629 PyBuffer_Release(&view_src);
630 return 0;
631 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* XXX(nnorwitz): need to check for overflow! */
636 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
637 if (indices == NULL) {
638 PyErr_NoMemory();
639 PyBuffer_Release(&view_dest);
640 PyBuffer_Release(&view_src);
641 return -1;
642 }
643 for (k=0; k<view_src.ndim;k++) {
644 indices[k] = 0;
645 }
646 elements = 1;
647 for (k=0; k<view_src.ndim; k++) {
648 /* XXX(nnorwitz): can this overflow? */
649 elements *= view_src.shape[k];
650 }
651 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000652 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 dptr = PyBuffer_GetPointer(&view_dest, indices);
654 sptr = PyBuffer_GetPointer(&view_src, indices);
655 memcpy(dptr, sptr, view_src.itemsize);
656 }
657 PyMem_Free(indices);
658 PyBuffer_Release(&view_dest);
659 PyBuffer_Release(&view_src);
660 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000661}
662
663void
664PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 Py_ssize_t *strides, int itemsize,
666 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 int k;
669 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 sd = itemsize;
672 if (fort == 'F') {
673 for (k=0; k<nd; k++) {
674 strides[k] = sd;
675 sd *= shape[k];
676 }
677 }
678 else {
679 for (k=nd-1; k>=0; k--) {
680 strides[k] = sd;
681 sd *= shape[k];
682 }
683 }
684 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000685}
686
687int
Martin v. Löwis423be952008-08-13 15:53:07 +0000688PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100689 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000690{
Stefan Krah5178d912015-02-03 16:57:21 +0100691 if (view == NULL) {
692 PyErr_SetString(PyExc_BufferError,
693 "PyBuffer_FillInfo: view==NULL argument is obsolete");
694 return -1;
695 }
696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
698 (readonly == 1)) {
699 PyErr_SetString(PyExc_BufferError,
700 "Object is not writable.");
701 return -1;
702 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 view->obj = obj;
705 if (obj)
706 Py_INCREF(obj);
707 view->buf = buf;
708 view->len = len;
709 view->readonly = readonly;
710 view->itemsize = 1;
711 view->format = NULL;
712 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
713 view->format = "B";
714 view->ndim = 1;
715 view->shape = NULL;
716 if ((flags & PyBUF_ND) == PyBUF_ND)
717 view->shape = &(view->len);
718 view->strides = NULL;
719 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
720 view->strides = &(view->itemsize);
721 view->suboffsets = NULL;
722 view->internal = NULL;
723 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000724}
725
Martin v. Löwis423be952008-08-13 15:53:07 +0000726void
727PyBuffer_Release(Py_buffer *view)
728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200730 PyBufferProcs *pb;
731 if (obj == NULL)
732 return;
733 pb = Py_TYPE(obj)->tp_as_buffer;
734 if (pb && pb->bf_releasebuffer)
735 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200737 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000738}
739
Eric Smith8fd3eba2008-02-17 19:48:00 +0000740PyObject *
741PyObject_Format(PyObject *obj, PyObject *format_spec)
742{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000743 PyObject *meth;
744 PyObject *empty = NULL;
745 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500746 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000747
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300748 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
749 PyErr_Format(PyExc_SystemError,
750 "Format specifier must be a string, not %.200s",
751 Py_TYPE(format_spec)->tp_name);
752 return NULL;
753 }
754
755 /* Fast path for common types. */
756 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
757 if (PyUnicode_CheckExact(obj)) {
758 Py_INCREF(obj);
759 return obj;
760 }
761 if (PyLong_CheckExact(obj)) {
762 return PyObject_Str(obj);
763 }
764 }
765
Eric Smith8fd3eba2008-02-17 19:48:00 +0000766 /* If no format_spec is provided, use an empty string */
767 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100768 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000769 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000770 }
771
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300772 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500773 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000774 if (meth == NULL) {
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000775 if (!PyErr_Occurred())
776 PyErr_Format(PyExc_TypeError,
777 "Type %.100s doesn't define __format__",
778 Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000780 }
781
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000782 /* And call it. */
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200783 result = _PyObject_CallOneArg(meth, format_spec);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000784 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000785
786 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800787 PyErr_Format(PyExc_TypeError,
788 "__format__ must return a str, not %.200s",
789 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000790 Py_DECREF(result);
791 result = NULL;
792 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000793 }
794
795done:
796 Py_XDECREF(empty);
797 return result;
798}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000799/* Operations on numbers */
800
801int
Fred Drake79912472000-07-09 04:06:11 +0000802PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000803{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100804 return o && Py_TYPE(o)->tp_as_number &&
805 (Py_TYPE(o)->tp_as_number->nb_index ||
806 Py_TYPE(o)->tp_as_number->nb_int ||
807 Py_TYPE(o)->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000808}
809
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000810/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000811
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000812#define NB_SLOT(x) offsetof(PyNumberMethods, x)
813#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000815#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000817
818/*
819 Calling scheme used for binary operations:
820
Neal Norwitz4886cc32006-08-21 17:06:07 +0000821 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000823
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100824 [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
825 Py_TYPE(v)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000826 */
827
828static PyObject *
829binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *x;
832 binaryfunc slotv = NULL;
833 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000834
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100835 if (Py_TYPE(v)->tp_as_number != NULL)
836 slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
837 if (Py_TYPE(w) != Py_TYPE(v) &&
838 Py_TYPE(w)->tp_as_number != NULL) {
839 slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (slotw == slotv)
841 slotw = NULL;
842 }
843 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100844 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 x = slotw(v, w);
846 if (x != Py_NotImplemented)
847 return x;
848 Py_DECREF(x); /* can't do it */
849 slotw = NULL;
850 }
851 x = slotv(v, w);
852 if (x != Py_NotImplemented)
853 return x;
854 Py_DECREF(x); /* can't do it */
855 }
856 if (slotw) {
857 x = slotw(v, w);
858 if (x != Py_NotImplemented)
859 return x;
860 Py_DECREF(x); /* can't do it */
861 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500862 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000863}
Guido van Rossum77660912002-04-16 16:32:50 +0000864
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000865static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000866binop_type_error(PyObject *v, PyObject *w, const char *op_name)
867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyErr_Format(PyExc_TypeError,
869 "unsupported operand type(s) for %.100s: "
870 "'%.100s' and '%.100s'",
871 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100872 Py_TYPE(v)->tp_name,
873 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000875}
876
877static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000878binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *result = binary_op1(v, w, op_slot);
881 if (result == Py_NotImplemented) {
882 Py_DECREF(result);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530883
884 if (op_slot == NB_SLOT(nb_rshift) &&
885 PyCFunction_Check(v) &&
886 strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
887 {
888 PyErr_Format(PyExc_TypeError,
889 "unsupported operand type(s) for %.100s: "
890 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
Sanyam Khuranaa7c449b2017-08-18 17:48:14 +0530891 "file=<output_stream>)\"?",
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530892 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100893 Py_TYPE(v)->tp_name,
894 Py_TYPE(w)->tp_name);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530895 return NULL;
896 }
897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 return binop_type_error(v, w, op_name);
899 }
900 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000901}
902
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000903
904/*
905 Calling scheme used for ternary operations:
906
Neal Norwitz4886cc32006-08-21 17:06:07 +0000907 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000909 */
910
911static PyObject *
912ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyObject *w,
914 PyObject *z,
915 const int op_slot,
916 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyNumberMethods *mv, *mw, *mz;
919 PyObject *x = NULL;
920 ternaryfunc slotv = NULL;
921 ternaryfunc slotw = NULL;
922 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000923
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100924 mv = Py_TYPE(v)->tp_as_number;
925 mw = Py_TYPE(w)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (mv != NULL)
927 slotv = NB_TERNOP(mv, op_slot);
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100928 if (Py_TYPE(w) != Py_TYPE(v) &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 mw != NULL) {
930 slotw = NB_TERNOP(mw, op_slot);
931 if (slotw == slotv)
932 slotw = NULL;
933 }
934 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100935 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 x = slotw(v, w, z);
937 if (x != Py_NotImplemented)
938 return x;
939 Py_DECREF(x); /* can't do it */
940 slotw = NULL;
941 }
942 x = slotv(v, w, z);
943 if (x != Py_NotImplemented)
944 return x;
945 Py_DECREF(x); /* can't do it */
946 }
947 if (slotw) {
948 x = slotw(v, w, z);
949 if (x != Py_NotImplemented)
950 return x;
951 Py_DECREF(x); /* can't do it */
952 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100953 mz = Py_TYPE(z)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (mz != NULL) {
955 slotz = NB_TERNOP(mz, op_slot);
956 if (slotz == slotv || slotz == slotw)
957 slotz = NULL;
958 if (slotz) {
959 x = slotz(v, w, z);
960 if (x != Py_NotImplemented)
961 return x;
962 Py_DECREF(x); /* can't do it */
963 }
964 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (z == Py_None)
967 PyErr_Format(
968 PyExc_TypeError,
969 "unsupported operand type(s) for ** or pow(): "
970 "'%.100s' and '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100971 Py_TYPE(v)->tp_name,
972 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 else
974 PyErr_Format(
975 PyExc_TypeError,
976 "unsupported operand type(s) for pow(): "
977 "'%.100s', '%.100s', '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100978 Py_TYPE(v)->tp_name,
979 Py_TYPE(w)->tp_name,
980 Py_TYPE(z)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +0000982}
983
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000984#define BINARY_FUNC(func, op, op_name) \
985 PyObject * \
986 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000988 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000989
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000990BINARY_FUNC(PyNumber_Or, nb_or, "|")
991BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
992BINARY_FUNC(PyNumber_And, nb_and, "&")
993BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
994BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
995BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000996BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +0000997
998PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000999PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1002 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001003 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Py_DECREF(result);
1005 if (m && m->sq_concat) {
1006 return (*m->sq_concat)(v, w);
1007 }
1008 result = binop_type_error(v, w, "+");
1009 }
1010 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001011}
1012
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001013static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001014sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 Py_ssize_t count;
1017 if (PyIndex_Check(n)) {
1018 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1019 if (count == -1 && PyErr_Occurred())
1020 return NULL;
1021 }
1022 else {
1023 return type_error("can't multiply sequence by "
1024 "non-int of type '%.200s'", n);
1025 }
1026 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001027}
1028
1029PyObject *
1030PyNumber_Multiply(PyObject *v, PyObject *w)
1031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1033 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001034 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1035 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 Py_DECREF(result);
1037 if (mv && mv->sq_repeat) {
1038 return sequence_repeat(mv->sq_repeat, v, w);
1039 }
1040 else if (mw && mw->sq_repeat) {
1041 return sequence_repeat(mw->sq_repeat, w, v);
1042 }
1043 result = binop_type_error(v, w, "*");
1044 }
1045 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001046}
1047
Guido van Rossume15dee51995-07-18 14:12:02 +00001048PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001049PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1050{
1051 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1052}
1053
1054PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001055PyNumber_FloorDivide(PyObject *v, PyObject *w)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001058}
1059
1060PyObject *
1061PyNumber_TrueDivide(PyObject *v, PyObject *w)
1062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001064}
1065
1066PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001067PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001070}
1071
1072PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001073PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001076}
1077
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001078/* Binary in-place operators */
1079
1080/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001081 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001082
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001083 - If the left hand object has the appropriate struct members, and
1084 they are filled, call the appropriate function and return the
1085 result. No coercion is done on the arguments; the left-hand object
1086 is the one the operation is performed on, and it's up to the
1087 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001088
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001089 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001090 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001091
1092 */
1093
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001094static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001095binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001096{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001097 PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (mv != NULL) {
1099 binaryfunc slot = NB_BINOP(mv, iop_slot);
1100 if (slot) {
1101 PyObject *x = (slot)(v, w);
1102 if (x != Py_NotImplemented) {
1103 return x;
1104 }
1105 Py_DECREF(x);
1106 }
1107 }
1108 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001109}
1110
1111static PyObject *
1112binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1116 if (result == Py_NotImplemented) {
1117 Py_DECREF(result);
1118 return binop_type_error(v, w, op_name);
1119 }
1120 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001121}
1122
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001123#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyObject * \
1125 func(PyObject *v, PyObject *w) { \
1126 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1127 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001128
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001129INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1130INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1131INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1132INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1133INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1134INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001135INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001136
1137PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001138PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1141 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001142}
1143
1144PyObject *
1145PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1148 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001149}
1150
1151PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001152PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1155 NB_SLOT(nb_add));
1156 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001157 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 Py_DECREF(result);
1159 if (m != NULL) {
1160 binaryfunc f = NULL;
1161 f = m->sq_inplace_concat;
1162 if (f == NULL)
1163 f = m->sq_concat;
1164 if (f != NULL)
1165 return (*f)(v, w);
1166 }
1167 result = binop_type_error(v, w, "+=");
1168 }
1169 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001170}
1171
1172PyObject *
1173PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1176 NB_SLOT(nb_multiply));
1177 if (result == Py_NotImplemented) {
1178 ssizeargfunc f = NULL;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001179 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1180 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_DECREF(result);
1182 if (mv != NULL) {
1183 f = mv->sq_inplace_repeat;
1184 if (f == NULL)
1185 f = mv->sq_repeat;
1186 if (f != NULL)
1187 return sequence_repeat(f, v, w);
1188 }
1189 else if (mw != NULL) {
1190 /* Note that the right hand operand should not be
1191 * mutated in this case so sq_inplace_repeat is not
1192 * used. */
1193 if (mw->sq_repeat)
1194 return sequence_repeat(mw->sq_repeat, w, v);
1195 }
1196 result = binop_type_error(v, w, "*=");
1197 }
1198 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001199}
1200
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001201PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001202PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1203{
1204 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1205 NB_SLOT(nb_matrix_multiply), "@=");
1206}
1207
1208PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001209PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1212 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001213}
1214
1215PyObject *
1216PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1217{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001218 if (Py_TYPE(v)->tp_as_number &&
1219 Py_TYPE(v)->tp_as_number->nb_inplace_power != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1221 }
1222 else {
1223 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1224 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001225}
1226
1227
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001228/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001229
1230PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001231PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001234
Victor Stinner71aea8e2016-08-19 16:59:55 +02001235 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001237 }
1238
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001239 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (m && m->nb_negative)
1241 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001244}
1245
1246PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001247PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001250
Victor Stinner71aea8e2016-08-19 16:59:55 +02001251 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001253 }
1254
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001255 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (m && m->nb_positive)
1257 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001260}
1261
1262PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001263PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001266
Victor Stinner71aea8e2016-08-19 16:59:55 +02001267 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001269 }
1270
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001271 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (m && m->nb_invert)
1273 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001276}
1277
1278PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001279PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001282
Victor Stinner71aea8e2016-08-19 16:59:55 +02001283 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001285 }
1286
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001287 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (m && m->nb_absolute)
1289 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001292}
1293
Christian Tismerea62ce72018-06-09 20:32:25 +02001294#undef PyIndex_Check
Christian Tismer83987132018-06-11 00:48:28 +02001295
Christian Tismerea62ce72018-06-09 20:32:25 +02001296int
1297PyIndex_Check(PyObject *obj)
1298{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001299 return Py_TYPE(obj)->tp_as_number != NULL &&
1300 Py_TYPE(obj)->tp_as_number->nb_index != NULL;
Christian Tismerea62ce72018-06-09 20:32:25 +02001301}
1302
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001303/* Return a Python int from the object item.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001304 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001305 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001306*/
1307PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001308PyNumber_Index(PyObject *item)
1309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001311 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001313 }
1314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (PyLong_Check(item)) {
1316 Py_INCREF(item);
1317 return item;
1318 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001319 if (!PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyErr_Format(PyExc_TypeError,
1321 "'%.200s' object cannot be interpreted "
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001322 "as an integer", Py_TYPE(item)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001323 return NULL;
1324 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001325 result = Py_TYPE(item)->tp_as_number->nb_index(item);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001326 if (!result || PyLong_CheckExact(result))
1327 return result;
1328 if (!PyLong_Check(result)) {
1329 PyErr_Format(PyExc_TypeError,
1330 "__index__ returned non-int (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001331 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001332 Py_DECREF(result);
1333 return NULL;
1334 }
1335 /* Issue #17576: warn if 'result' not of exact type int. */
1336 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1337 "__index__ returned non-int (type %.200s). "
1338 "The ability to return an instance of a strict subclass of int "
1339 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001340 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001341 Py_DECREF(result);
1342 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 }
1344 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001345}
1346
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001347/* Return an error on Overflow only if err is not NULL*/
1348
1349Py_ssize_t
1350PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 Py_ssize_t result;
1353 PyObject *runerr;
1354 PyObject *value = PyNumber_Index(item);
1355 if (value == NULL)
1356 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* We're done if PyLong_AsSsize_t() returns without error. */
1359 result = PyLong_AsSsize_t(value);
1360 if (result != -1 || !(runerr = PyErr_Occurred()))
1361 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* Error handling code -- only manage OverflowError differently */
1364 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1365 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyErr_Clear();
1368 /* If no error-handling desired then the default clipping
1369 is sufficient.
1370 */
1371 if (!err) {
1372 assert(PyLong_Check(value));
1373 /* Whether or not it is less than or equal to
1374 zero is determined by the sign of ob_size
1375 */
1376 if (_PyLong_Sign(value) < 0)
1377 result = PY_SSIZE_T_MIN;
1378 else
1379 result = PY_SSIZE_T_MAX;
1380 }
1381 else {
1382 /* Otherwise replace the error with caller's error object. */
1383 PyErr_Format(err,
1384 "cannot fit '%.200s' into an index-sized integer",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001385 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001387
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001388 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_DECREF(value);
1390 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001391}
1392
1393
Guido van Rossume15dee51995-07-18 14:12:02 +00001394PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001395PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001396{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001397 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001400 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001401 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001402
Victor Stinner71aea8e2016-08-19 16:59:55 +02001403 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001405 }
1406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (PyLong_CheckExact(o)) {
1408 Py_INCREF(o);
1409 return o;
1410 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001411 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001413 result = _PyLong_FromNbInt(o);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001414 if (result != NULL && !PyLong_CheckExact(result)) {
1415 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1416 }
1417 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001419 if (m && m->nb_index) {
1420 result = _PyLong_FromNbIndexOrNbInt(o);
1421 if (result != NULL && !PyLong_CheckExact(result)) {
1422 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1423 }
1424 return result;
1425 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001426 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001428 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001430 if (result == NULL || PyLong_CheckExact(result)) {
1431 return result;
1432 }
1433 if (PyLong_Check(result)) {
1434 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1435 return result;
1436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001438 but int() needs to return an int. */
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001439 m = Py_TYPE(result)->tp_as_number;
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001440 if (m == NULL || (m->nb_index == NULL && m->nb_int == NULL)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001441 PyErr_Format(
1442 PyExc_TypeError,
1443 "__trunc__ returned non-Integral (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001444 Py_TYPE(result)->tp_name);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001445 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001446 return NULL;
1447 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001448 Py_SETREF(result, _PyLong_FromNbIndexOrNbInt(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001449 if (result != NULL && !PyLong_CheckExact(result)) {
1450 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1451 }
1452 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001454 if (PyErr_Occurred())
1455 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001456
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001457 if (PyUnicode_Check(o))
1458 /* The below check is done in PyLong_FromUnicode(). */
1459 return PyLong_FromUnicodeObject(o, 10);
1460
Martin Pantereeb896c2015-11-07 02:32:21 +00001461 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001463 * doesn't do. In particular int('9\x005') must raise an
1464 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001466 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1467 PyBytes_GET_SIZE(o), 10);
1468
1469 if (PyByteArray_Check(o))
1470 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1471 PyByteArray_GET_SIZE(o), 10);
1472
1473 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001474 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001475
1476 /* Copy to NUL-terminated buffer. */
1477 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1478 if (bytes == NULL) {
1479 PyBuffer_Release(&view);
1480 return NULL;
1481 }
1482 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1483 PyBytes_GET_SIZE(bytes), 10);
1484 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001485 PyBuffer_Release(&view);
1486 return result;
1487 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001488
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001489 return type_error("int() argument must be a string, a bytes-like object "
1490 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001491}
1492
1493PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001494PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001497
Victor Stinner71aea8e2016-08-19 16:59:55 +02001498 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001500 }
1501
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001502 if (PyFloat_CheckExact(o)) {
1503 Py_INCREF(o);
1504 return o;
1505 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001506 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (m && m->nb_float) { /* This should include subclasses of float */
1508 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001509 double val;
1510 if (!res || PyFloat_CheckExact(res)) {
1511 return res;
1512 }
1513 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001515 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001516 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 Py_DECREF(res);
1518 return NULL;
1519 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001520 /* Issue #26983: warn if 'res' not of exact type float. */
1521 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1522 "%.50s.__float__ returned non-float (type %.50s). "
1523 "The ability to return an instance of a strict subclass of float "
1524 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001525 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001526 Py_DECREF(res);
1527 return NULL;
1528 }
1529 val = PyFloat_AS_DOUBLE(res);
1530 Py_DECREF(res);
1531 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001533 if (m && m->nb_index) {
1534 PyObject *res = PyNumber_Index(o);
1535 if (!res) {
1536 return NULL;
1537 }
1538 double val = PyLong_AsDouble(res);
1539 Py_DECREF(res);
1540 if (val == -1.0 && PyErr_Occurred()) {
1541 return NULL;
1542 }
1543 return PyFloat_FromDouble(val);
1544 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001546 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 }
1548 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001549}
1550
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001551
1552PyObject *
1553PyNumber_ToBase(PyObject *n, int base)
1554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyObject *res = NULL;
1556 PyObject *index = PyNumber_Index(n);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (!index)
1559 return NULL;
1560 if (PyLong_Check(index))
1561 res = _PyLong_Format(index, base);
1562 else
1563 /* It should not be possible to get here, as
1564 PyNumber_Index already has a check for the same
1565 condition */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001566 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 Py_DECREF(index);
1568 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001569}
1570
1571
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001572/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001573
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001574int
Fred Drake79912472000-07-09 04:06:11 +00001575PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (PyDict_Check(s))
1578 return 0;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001579 return Py_TYPE(s)->tp_as_sequence &&
1580 Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001581}
1582
Martin v. Löwis18e16552006-02-15 17:27:45 +00001583Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001584PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (s == NULL) {
1589 null_error();
1590 return -1;
1591 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001592
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001593 m = Py_TYPE(s)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001594 if (m && m->sq_length) {
1595 Py_ssize_t len = m->sq_length(s);
1596 assert(len >= 0 || PyErr_Occurred());
1597 return len;
1598 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001599
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001600 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001601 type_error("%.200s is not a sequence", s);
1602 return -1;
1603 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 type_error("object of type '%.200s' has no len()", s);
1605 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001606}
1607
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001608#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001609Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001610PySequence_Length(PyObject *s)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001613}
1614#define PySequence_Length PySequence_Size
1615
Guido van Rossume15dee51995-07-18 14:12:02 +00001616PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001617PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001620
Victor Stinner71aea8e2016-08-19 16:59:55 +02001621 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001623 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001624
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001625 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 if (m && m->sq_concat)
1627 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 /* Instances of user classes defining an __add__() method only
1630 have an nb_add slot, not an sq_concat slot. So we fall back
1631 to nb_add if both arguments appear to be sequences. */
1632 if (PySequence_Check(s) && PySequence_Check(o)) {
1633 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1634 if (result != Py_NotImplemented)
1635 return result;
1636 Py_DECREF(result);
1637 }
1638 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001639}
1640
1641PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001642PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001645
Victor Stinner71aea8e2016-08-19 16:59:55 +02001646 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001648 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001649
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001650 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if (m && m->sq_repeat)
1652 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Instances of user classes defining a __mul__() method only
1655 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1656 to nb_multiply if o appears to be a sequence. */
1657 if (PySequence_Check(o)) {
1658 PyObject *n, *result;
1659 n = PyLong_FromSsize_t(count);
1660 if (n == NULL)
1661 return NULL;
1662 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1663 Py_DECREF(n);
1664 if (result != Py_NotImplemented)
1665 return result;
1666 Py_DECREF(result);
1667 }
1668 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001669}
1670
1671PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001672PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001675
Victor Stinner71aea8e2016-08-19 16:59:55 +02001676 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001678 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001679
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001680 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (m && m->sq_inplace_concat)
1682 return m->sq_inplace_concat(s, o);
1683 if (m && m->sq_concat)
1684 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (PySequence_Check(s) && PySequence_Check(o)) {
1687 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1688 NB_SLOT(nb_add));
1689 if (result != Py_NotImplemented)
1690 return result;
1691 Py_DECREF(result);
1692 }
1693 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001694}
1695
1696PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001697PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001700
Victor Stinner71aea8e2016-08-19 16:59:55 +02001701 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001703 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001704
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001705 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (m && m->sq_inplace_repeat)
1707 return m->sq_inplace_repeat(o, count);
1708 if (m && m->sq_repeat)
1709 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (PySequence_Check(o)) {
1712 PyObject *n, *result;
1713 n = PyLong_FromSsize_t(count);
1714 if (n == NULL)
1715 return NULL;
1716 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1717 NB_SLOT(nb_multiply));
1718 Py_DECREF(n);
1719 if (result != Py_NotImplemented)
1720 return result;
1721 Py_DECREF(result);
1722 }
1723 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001724}
1725
1726PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001727PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001730
Victor Stinner71aea8e2016-08-19 16:59:55 +02001731 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001733 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001734
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001735 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (m && m->sq_item) {
1737 if (i < 0) {
1738 if (m->sq_length) {
1739 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001740 if (l < 0) {
1741 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 i += l;
1745 }
1746 }
1747 return m->sq_item(s, i);
1748 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001749
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001750 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001751 return type_error("%.200s is not a sequence", s);
1752 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001754}
1755
1756PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001757PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001760
Victor Stinner71aea8e2016-08-19 16:59:55 +02001761 if (!s) {
1762 return null_error();
1763 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001764
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001765 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001766 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyObject *res;
1768 PyObject *slice = _PySlice_FromIndices(i1, i2);
1769 if (!slice)
1770 return NULL;
1771 res = mp->mp_subscript(s, slice);
1772 Py_DECREF(slice);
1773 return res;
1774 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001777}
1778
1779int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001780PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (s == NULL) {
1785 null_error();
1786 return -1;
1787 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001788
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001789 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (m && m->sq_ass_item) {
1791 if (i < 0) {
1792 if (m->sq_length) {
1793 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001794 if (l < 0) {
1795 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 i += l;
1799 }
1800 }
1801 return m->sq_ass_item(s, i, o);
1802 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001803
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001804 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001805 type_error("%.200s is not a sequence", s);
1806 return -1;
1807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 type_error("'%.200s' object does not support item assignment", s);
1809 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001810}
1811
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001812int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001813PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (s == NULL) {
1818 null_error();
1819 return -1;
1820 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001821
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001822 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (m && m->sq_ass_item) {
1824 if (i < 0) {
1825 if (m->sq_length) {
1826 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001827 if (l < 0) {
1828 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001830 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 i += l;
1832 }
1833 }
1834 return m->sq_ass_item(s, i, (PyObject *)NULL);
1835 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001836
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001837 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001838 type_error("%.200s is not a sequence", s);
1839 return -1;
1840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 type_error("'%.200s' object doesn't support item deletion", s);
1842 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001843}
1844
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001845int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (s == NULL) {
1851 null_error();
1852 return -1;
1853 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001854
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001855 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001856 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 int res;
1858 PyObject *slice = _PySlice_FromIndices(i1, i2);
1859 if (!slice)
1860 return -1;
1861 res = mp->mp_ass_subscript(s, slice, o);
1862 Py_DECREF(slice);
1863 return res;
1864 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 type_error("'%.200s' object doesn't support slice assignment", s);
1867 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001868}
1869
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001870int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001871PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (s == NULL) {
1876 null_error();
1877 return -1;
1878 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001879
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001880 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001881 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 int res;
1883 PyObject *slice = _PySlice_FromIndices(i1, i2);
1884 if (!slice)
1885 return -1;
1886 res = mp->mp_ass_subscript(s, slice, NULL);
1887 Py_DECREF(slice);
1888 return res;
1889 }
1890 type_error("'%.200s' object doesn't support slice deletion", s);
1891 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001892}
1893
Guido van Rossume15dee51995-07-18 14:12:02 +00001894PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001895PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyObject *it; /* iter(v) */
1898 Py_ssize_t n; /* guess for result tuple size */
1899 PyObject *result = NULL;
1900 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001901
Victor Stinner71aea8e2016-08-19 16:59:55 +02001902 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001904 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 /* Special-case the common tuple and list cases, for efficiency. */
1907 if (PyTuple_CheckExact(v)) {
1908 /* Note that we can't know whether it's safe to return
1909 a tuple *subclass* instance as-is, hence the restriction
1910 to exact tuples here. In contrast, lists always make
1911 a copy, so there's no need for exactness below. */
1912 Py_INCREF(v);
1913 return v;
1914 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001915 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* Get iterator. */
1919 it = PyObject_GetIter(v);
1920 if (it == NULL)
1921 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001924 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (n == -1)
1926 goto Fail;
1927 result = PyTuple_New(n);
1928 if (result == NULL)
1929 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 /* Fill the tuple. */
1932 for (j = 0; ; ++j) {
1933 PyObject *item = PyIter_Next(it);
1934 if (item == NULL) {
1935 if (PyErr_Occurred())
1936 goto Fail;
1937 break;
1938 }
1939 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001940 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* The over-allocation strategy can grow a bit faster
1942 than for lists because unlike lists the
1943 over-allocation isn't permanent -- we reclaim
1944 the excess before the end of this routine.
1945 So, grow by ten and then add 25%.
1946 */
Martin Pantere8db8612016-07-25 02:30:05 +00001947 newn += 10u;
1948 newn += newn >> 2;
1949 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 /* Check for overflow */
1951 PyErr_NoMemory();
1952 Py_DECREF(item);
1953 goto Fail;
1954 }
Martin Pantere8db8612016-07-25 02:30:05 +00001955 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 if (_PyTuple_Resize(&result, n) != 0) {
1957 Py_DECREF(item);
1958 goto Fail;
1959 }
1960 }
1961 PyTuple_SET_ITEM(result, j, item);
1962 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Cut tuple back if guess was too large. */
1965 if (j < n &&
1966 _PyTuple_Resize(&result, j) != 0)
1967 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 Py_DECREF(it);
1970 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00001971
1972Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 Py_XDECREF(result);
1974 Py_DECREF(it);
1975 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001976}
1977
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001978PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001979PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *result; /* result list */
1982 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00001983
Victor Stinner71aea8e2016-08-19 16:59:55 +02001984 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001986 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 result = PyList_New(0);
1989 if (result == NULL)
1990 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 rv = _PyList_Extend((PyListObject *)result, v);
1993 if (rv == NULL) {
1994 Py_DECREF(result);
1995 return NULL;
1996 }
1997 Py_DECREF(rv);
1998 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001999}
2000
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002001PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002002PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002005
Victor Stinner71aea8e2016-08-19 16:59:55 +02002006 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002008 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2011 Py_INCREF(v);
2012 return v;
2013 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 it = PyObject_GetIter(v);
2016 if (it == NULL) {
2017 if (PyErr_ExceptionMatches(PyExc_TypeError))
2018 PyErr_SetString(PyExc_TypeError, m);
2019 return NULL;
2020 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 v = PySequence_List(it);
2023 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002026}
2027
Tim Peters16a77ad2001-09-08 04:00:12 +00002028/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2030 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2031 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002032 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2033*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002034Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002035_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 Py_ssize_t n;
2038 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2039 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (seq == NULL || obj == NULL) {
2042 null_error();
2043 return -1;
2044 }
Tim Peters75f8e352001-05-05 11:33:43 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 it = PyObject_GetIter(seq);
2047 if (it == NULL) {
2048 type_error("argument of type '%.200s' is not iterable", seq);
2049 return -1;
2050 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 n = wrapped = 0;
2053 for (;;) {
2054 int cmp;
2055 PyObject *item = PyIter_Next(it);
2056 if (item == NULL) {
2057 if (PyErr_Occurred())
2058 goto Fail;
2059 break;
2060 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002061
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002062 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 Py_DECREF(item);
2064 if (cmp < 0)
2065 goto Fail;
2066 if (cmp > 0) {
2067 switch (operation) {
2068 case PY_ITERSEARCH_COUNT:
2069 if (n == PY_SSIZE_T_MAX) {
2070 PyErr_SetString(PyExc_OverflowError,
2071 "count exceeds C integer size");
2072 goto Fail;
2073 }
2074 ++n;
2075 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 case PY_ITERSEARCH_INDEX:
2078 if (wrapped) {
2079 PyErr_SetString(PyExc_OverflowError,
2080 "index exceeds C integer size");
2081 goto Fail;
2082 }
2083 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 case PY_ITERSEARCH_CONTAINS:
2086 n = 1;
2087 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002090 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 }
2092 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (operation == PY_ITERSEARCH_INDEX) {
2095 if (n == PY_SSIZE_T_MAX)
2096 wrapped = 1;
2097 ++n;
2098 }
2099 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (operation != PY_ITERSEARCH_INDEX)
2102 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyErr_SetString(PyExc_ValueError,
2105 "sequence.index(x): x not in sequence");
2106 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002107Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 n = -1;
2109 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002110Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 Py_DECREF(it);
2112 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002113
Guido van Rossume15dee51995-07-18 14:12:02 +00002114}
2115
Tim Peters16a77ad2001-09-08 04:00:12 +00002116/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002117Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002118PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002121}
2122
Tim Peterscb8d3682001-05-05 21:05:01 +00002123/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002124 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002125 */
2126int
2127PySequence_Contains(PyObject *seq, PyObject *ob)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 Py_ssize_t result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002130 PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (sqm != NULL && sqm->sq_contains != NULL)
2132 return (*sqm->sq_contains)(seq, ob);
2133 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2134 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002135}
2136
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002137/* Backwards compatibility */
2138#undef PySequence_In
2139int
Fred Drake79912472000-07-09 04:06:11 +00002140PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002143}
2144
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002145Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002146PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002149}
2150
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002151/* Operations on mappings */
2152
2153int
Fred Drake79912472000-07-09 04:06:11 +00002154PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002155{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002156 return o && Py_TYPE(o)->tp_as_mapping &&
2157 Py_TYPE(o)->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002158}
2159
Martin v. Löwis18e16552006-02-15 17:27:45 +00002160Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002161PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (o == NULL) {
2166 null_error();
2167 return -1;
2168 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002169
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002170 m = Py_TYPE(o)->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002171 if (m && m->mp_length) {
2172 Py_ssize_t len = m->mp_length(o);
2173 assert(len >= 0 || PyErr_Occurred());
2174 return len;
2175 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002176
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002177 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002178 type_error("%.200s is not a mapping", o);
2179 return -1;
2180 }
2181 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 type_error("object of type '%.200s' has no len()", o);
2183 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002184}
2185
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002186#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002187Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002188PyMapping_Length(PyObject *o)
2189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002191}
2192#define PyMapping_Length PyMapping_Size
2193
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002194PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002195PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002198
Victor Stinner71aea8e2016-08-19 16:59:55 +02002199 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002201 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 okey = PyUnicode_FromString(key);
2204 if (okey == NULL)
2205 return NULL;
2206 r = PyObject_GetItem(o, okey);
2207 Py_DECREF(okey);
2208 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002209}
2210
2211int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002212PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyObject *okey;
2215 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (key == NULL) {
2218 null_error();
2219 return -1;
2220 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 okey = PyUnicode_FromString(key);
2223 if (okey == NULL)
2224 return -1;
2225 r = PyObject_SetItem(o, okey, value);
2226 Py_DECREF(okey);
2227 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002228}
2229
2230int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002231PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 v = PyMapping_GetItemString(o, key);
2236 if (v) {
2237 Py_DECREF(v);
2238 return 1;
2239 }
2240 PyErr_Clear();
2241 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002242}
2243
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002244int
Fred Drake79912472000-07-09 04:06:11 +00002245PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 v = PyObject_GetItem(o, key);
2250 if (v) {
2251 Py_DECREF(v);
2252 return 1;
2253 }
2254 PyErr_Clear();
2255 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002256}
2257
Oren Milman0ccc0f62017-10-08 11:17:46 +03002258/* This function is quite similar to PySequence_Fast(), but specialized to be
2259 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2260 */
2261static PyObject *
2262method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2263{
2264 PyObject *it, *result, *meth_output;
2265
2266 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002267 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002268 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2269 return meth_output;
2270 }
2271 it = PyObject_GetIter(meth_output);
2272 if (it == NULL) {
2273 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2274 PyErr_Format(PyExc_TypeError,
2275 "%.200s.%U() returned a non-iterable (type %.200s)",
2276 Py_TYPE(o)->tp_name,
2277 meth_id->object,
2278 Py_TYPE(meth_output)->tp_name);
2279 }
2280 Py_DECREF(meth_output);
2281 return NULL;
2282 }
2283 Py_DECREF(meth_output);
2284 result = PySequence_List(it);
2285 Py_DECREF(it);
2286 return result;
2287}
2288
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002289PyObject *
2290PyMapping_Keys(PyObject *o)
2291{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002292 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002293
Oren Milman0ccc0f62017-10-08 11:17:46 +03002294 if (o == NULL) {
2295 return null_error();
2296 }
2297 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002299 }
2300 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002301}
2302
2303PyObject *
2304PyMapping_Items(PyObject *o)
2305{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002306 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002307
Oren Milman0ccc0f62017-10-08 11:17:46 +03002308 if (o == NULL) {
2309 return null_error();
2310 }
2311 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002313 }
2314 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002315}
2316
2317PyObject *
2318PyMapping_Values(PyObject *o)
2319{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002320 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002321
Oren Milman0ccc0f62017-10-08 11:17:46 +03002322 if (o == NULL) {
2323 return null_error();
2324 }
2325 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002327 }
2328 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002329}
2330
Guido van Rossum823649d2001-03-21 18:40:58 +00002331/* isinstance(), issubclass() */
2332
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002333/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002334 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002335 * 1. getattr(cls, '__bases__') could raise an AttributeError
2336 * 2. getattr(cls, '__bases__') could raise some other exception
2337 * 3. getattr(cls, '__bases__') could return a tuple
2338 * 4. getattr(cls, '__bases__') could return something other than a tuple
2339 *
2340 * Only state #3 is a non-error state and only it returns a non-NULL object
2341 * (it returns the retrieved tuple).
2342 *
2343 * Any raised AttributeErrors are masked by clearing the exception and
2344 * returning NULL. If an object other than a tuple comes out of __bases__,
2345 * then again, the return value is NULL. So yes, these two situations
2346 * produce exactly the same results: NULL is returned and no error is set.
2347 *
2348 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002350 * exception to be propagated along.
2351 *
2352 * Callers are expected to test for PyErr_Occurred() when the return value
2353 * is NULL to decide whether a valid exception should be propagated or not.
2354 * When there's no exception to propagate, it's customary for the caller to
2355 * set a TypeError.
2356 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002357static PyObject *
2358abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002359{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002360 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 Py_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002364 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 Py_END_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002366 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 Py_DECREF(bases);
2368 return NULL;
2369 }
2370 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002371}
2372
2373
2374static int
2375abstract_issubclass(PyObject *derived, PyObject *cls)
2376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 PyObject *bases = NULL;
2378 Py_ssize_t i, n;
2379 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 while (1) {
2382 if (derived == cls)
2383 return 1;
2384 bases = abstract_get_bases(derived);
2385 if (bases == NULL) {
2386 if (PyErr_Occurred())
2387 return -1;
2388 return 0;
2389 }
2390 n = PyTuple_GET_SIZE(bases);
2391 if (n == 0) {
2392 Py_DECREF(bases);
2393 return 0;
2394 }
2395 /* Avoid recursivity in the single inheritance case */
2396 if (n == 1) {
2397 derived = PyTuple_GET_ITEM(bases, 0);
2398 Py_DECREF(bases);
2399 continue;
2400 }
2401 for (i = 0; i < n; i++) {
2402 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2403 if (r != 0)
2404 break;
2405 }
2406 Py_DECREF(bases);
2407 return r;
2408 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002409}
2410
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002411static int
2412check_class(PyObject *cls, const char *error)
2413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 PyObject *bases = abstract_get_bases(cls);
2415 if (bases == NULL) {
2416 /* Do not mask errors. */
2417 if (!PyErr_Occurred())
2418 PyErr_SetString(PyExc_TypeError, error);
2419 return 0;
2420 }
2421 Py_DECREF(bases);
2422 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002423}
2424
Brett Cannon4f653312004-03-20 22:52:14 +00002425static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002426object_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002429 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002430 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (PyType_Check(cls)) {
2433 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2434 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002435 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2436 if (icls != NULL) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002437 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002439 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002441 }
2442 else {
2443 retval = 0;
2444 }
2445 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
2447 }
2448 }
2449 else {
2450 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002451 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002453 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2454 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 retval = abstract_issubclass(icls, cls);
2456 Py_DECREF(icls);
2457 }
2458 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002461}
2462
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002463static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002464object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002465{
Benjamin Petersonce798522012-01-22 11:24:29 -05002466 _Py_IDENTIFIER(__instancecheck__);
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Quick test for an exact match */
Victor Stinner850a4bd2020-02-04 13:42:13 +01002469 if (Py_TYPE(inst) == (PyTypeObject *)cls) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return 1;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002471 }
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002472
Georg Brandl72b8a802014-10-03 09:26:37 +02002473 /* We know what type's __instancecheck__ does. */
2474 if (PyType_CheckExact(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002475 return object_isinstance(inst, cls);
Georg Brandl72b8a802014-10-03 09:26:37 +02002476 }
2477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (PyTuple_Check(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002479 /* Not a general sequence -- that opens up the road to
2480 recursion and stack overflow. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002481 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002483 }
2484 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2485 int r = 0;
2486 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002488 r = object_recursive_isinstance(tstate, inst, item);
2489 if (r != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* either found it, or got an error */
2491 break;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002494 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 return r;
2496 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002497
Victor Stinner850a4bd2020-02-04 13:42:13 +01002498 PyObject *checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (checker != NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002500 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002502 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002504
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002505 PyObject *res = _PyObject_CallOneArg(checker, inst);
2506 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002508
2509 if (res == NULL) {
2510 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002512 int ok = PyObject_IsTrue(res);
2513 Py_DECREF(res);
2514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 return ok;
2516 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002517 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002519 }
2520
Victor Stinner850a4bd2020-02-04 13:42:13 +01002521 /* cls has no __instancecheck__() method */
2522 return object_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002523}
2524
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002525
2526int
2527PyObject_IsInstance(PyObject *inst, PyObject *cls)
2528{
2529 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner850a4bd2020-02-04 13:42:13 +01002530 return object_recursive_isinstance(tstate, inst, cls);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002531}
2532
2533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002535recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (PyType_Check(cls) && PyType_Check(derived)) {
2538 /* Fast path (non-recursive) */
2539 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2540 }
2541 if (!check_class(derived,
2542 "issubclass() arg 1 must be a class"))
2543 return -1;
2544 if (!check_class(cls,
2545 "issubclass() arg 2 must be a class"
2546 " or tuple of classes"))
2547 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002550}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002551
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002552static int
2553object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002554{
Benjamin Petersonce798522012-01-22 11:24:29 -05002555 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002557
Georg Brandl72b8a802014-10-03 09:26:37 +02002558 /* We know what type's __subclasscheck__ does. */
2559 if (PyType_CheckExact(cls)) {
2560 /* Quick test for an exact match */
2561 if (derived == cls)
2562 return 1;
2563 return recursive_issubclass(derived, cls);
2564 }
2565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 if (PyTuple_Check(cls)) {
Antoine Pitrouec569b72008-08-26 22:40:48 +00002567
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002568 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002570 }
2571 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2572 int r = 0;
2573 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002575 r = object_issubclass(tstate, derived, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (r != 0)
2577 /* either found it, or got an error */
2578 break;
2579 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002580 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return r;
2582 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002583
Benjamin Petersonce798522012-01-22 11:24:29 -05002584 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 if (checker != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 int ok = -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002587 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 Py_DECREF(checker);
2589 return ok;
2590 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002591 PyObject *res = _PyObject_CallOneArg(checker, derived);
2592 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 Py_DECREF(checker);
2594 if (res != NULL) {
2595 ok = PyObject_IsTrue(res);
2596 Py_DECREF(res);
2597 }
2598 return ok;
2599 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002600 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002602 }
2603
Georg Brandl72b8a802014-10-03 09:26:37 +02002604 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002606}
2607
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002608
2609int
2610PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2611{
2612 PyThreadState *tstate = _PyThreadState_GET();
2613 return object_issubclass(tstate, derived, cls);
2614}
2615
2616
Antoine Pitrouec569b72008-08-26 22:40:48 +00002617int
2618_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2619{
Victor Stinner850a4bd2020-02-04 13:42:13 +01002620 return object_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002621}
2622
2623int
2624_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002627}
2628
2629
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002630PyObject *
2631PyObject_GetIter(PyObject *o)
2632{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002633 PyTypeObject *t = Py_TYPE(o);
Victor Stinner14e6d092016-12-09 17:08:59 +01002634 getiterfunc f;
2635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 f = t->tp_iter;
2637 if (f == NULL) {
2638 if (PySequence_Check(o))
2639 return PySeqIter_New(o);
2640 return type_error("'%.200s' object is not iterable", o);
2641 }
2642 else {
2643 PyObject *res = (*f)(o);
2644 if (res != NULL && !PyIter_Check(res)) {
2645 PyErr_Format(PyExc_TypeError,
2646 "iter() returned non-iterator "
2647 "of type '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002648 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 Py_DECREF(res);
2650 res = NULL;
2651 }
2652 return res;
2653 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002654}
2655
Christian Tismerea62ce72018-06-09 20:32:25 +02002656#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002657
Christian Tismerea62ce72018-06-09 20:32:25 +02002658int PyIter_Check(PyObject *obj)
2659{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002660 return Py_TYPE(obj)->tp_iternext != NULL &&
2661 Py_TYPE(obj)->tp_iternext != &_PyObject_NextNotImplemented;
Christian Tismerea62ce72018-06-09 20:32:25 +02002662}
2663
Tim Petersf4848da2001-05-05 00:14:56 +00002664/* Return next item.
2665 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2666 * If the iteration terminates normally, return NULL and clear the
2667 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2668 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002670 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002671PyObject *
2672PyIter_Next(PyObject *iter)
2673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyObject *result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002675 result = (*Py_TYPE(iter)->tp_iternext)(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (result == NULL &&
2677 PyErr_Occurred() &&
2678 PyErr_ExceptionMatches(PyExc_StopIteration))
2679 PyErr_Clear();
2680 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002681}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002682
2683
2684/*
2685 * Flatten a sequence of bytes() objects into a C array of
2686 * NULL terminated string pointers with a NULL char* terminating the array.
2687 * (ie: an argv or env list)
2688 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002689 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2690 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002691 */
2692char *const *
2693_PySequence_BytesToCharpArray(PyObject* self)
2694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 char **array;
2696 Py_ssize_t i, argc;
2697 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002698 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 argc = PySequence_Size(self);
2701 if (argc == -1)
2702 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002703
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002704 assert(argc >= 0);
2705
2706 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2707 PyErr_NoMemory();
2708 return NULL;
2709 }
2710
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002711 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 if (array == NULL) {
2713 PyErr_NoMemory();
2714 return NULL;
2715 }
2716 for (i = 0; i < argc; ++i) {
2717 char *data;
2718 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002719 if (item == NULL) {
2720 /* NULL terminate before freeing. */
2721 array[i] = NULL;
2722 goto fail;
2723 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002724 /* check for embedded null bytes */
2725 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 /* NULL terminate before freeing. */
2727 array[i] = NULL;
2728 goto fail;
2729 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002730 size = PyBytes_GET_SIZE(item) + 1;
2731 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 if (!array[i]) {
2733 PyErr_NoMemory();
2734 goto fail;
2735 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002736 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 Py_DECREF(item);
2738 }
2739 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002742
2743fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 Py_XDECREF(item);
2745 _Py_FreeCharPArray(array);
2746 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002747}
2748
2749
2750/* Free's a NULL terminated char** array of C strings. */
2751void
2752_Py_FreeCharPArray(char *const array[])
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 Py_ssize_t i;
2755 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002756 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002758 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002759}