blob: 3db56fab2c8db5fb59dc5cf7f3ab798ceebe5a94 [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 Stinner621cebe2018-11-12 16:53:38 +01004#include "pycore_pystate.h"
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +00005#include <ctype.h>
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00006#include "structmember.h" /* we need the offsetof() macro from there */
Tim Peters64b5ce32001-09-10 20:52:51 +00007#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00008
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000011/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000012
13static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
17 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000018}
19
Guido van Rossum052b7e11996-11-11 15:08:19 +000020static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000021null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 if (!PyErr_Occurred())
24 PyErr_SetString(PyExc_SystemError,
25 "null argument to internal routine");
26 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000027}
28
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000029/* Operations on any object */
30
Guido van Rossume15dee51995-07-18 14:12:02 +000031PyObject *
Fred Drake79912472000-07-09 04:06:11 +000032PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000035
Victor Stinner71aea8e2016-08-19 16:59:55 +020036 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020038 }
39
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 v = (PyObject *)o->ob_type;
41 Py_INCREF(v);
42 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000043}
44
Martin v. Löwis18e16552006-02-15 17:27:45 +000045Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000046PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 if (o == NULL) {
51 null_error();
52 return -1;
53 }
Guido van Rossume15dee51995-07-18 14:12:02 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 m = o->ob_type->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +030056 if (m && m->sq_length) {
57 Py_ssize_t len = m->sq_length(o);
58 assert(len >= 0 || PyErr_Occurred());
59 return len;
60 }
Guido van Rossume15dee51995-07-18 14:12:02 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000063}
64
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000065#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000066Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000067PyObject_Length(PyObject *o)
68{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000070}
71#define PyObject_Length PyObject_Size
72
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020073int
74_PyObject_HasLen(PyObject *o) {
75 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
76 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
77}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000078
Christian Heimes255f53b2007-12-08 15:33:56 +000079/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020080 or o.__length_hint__(). If those methods aren't found the defaultvalue is
81 returned. If one of the calls fails with an exception other than TypeError
82 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000083*/
84
85Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020086PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000087{
Christian Heimesb70e8a12012-10-06 17:16:39 +020088 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020089 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050090 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030091 if (_PyObject_HasLen(o)) {
92 res = PyObject_Length(o);
Serhiy Storchaka813f9432017-04-16 09:21:44 +030093 if (res < 0) {
94 assert(PyErr_Occurred());
Serhiy Storchakaf740d462013-10-24 23:19:51 +030095 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
96 return -1;
97 }
98 PyErr_Clear();
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020099 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300100 else {
101 return res;
102 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 }
Christian Heimes6314d162012-10-06 17:13:29 +0200104 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200105 if (hint == NULL) {
106 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 return defaultvalue;
110 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100111 result = _PyObject_CallNoArg(hint);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200112 Py_DECREF(hint);
113 if (result == NULL) {
114 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
115 PyErr_Clear();
116 return defaultvalue;
117 }
118 return -1;
119 }
120 else if (result == Py_NotImplemented) {
121 Py_DECREF(result);
122 return defaultvalue;
123 }
124 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200125 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200126 Py_TYPE(result)->tp_name);
127 Py_DECREF(result);
128 return -1;
129 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200130 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200131 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200132 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200133 return -1;
134 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200135 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200136 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
137 return -1;
138 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200139 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000140}
141
Guido van Rossume15dee51995-07-18 14:12:02 +0000142PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000143PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 PyMappingMethods *m;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000146 PySequenceMethods *ms;
Guido van Rossume15dee51995-07-18 14:12:02 +0000147
Victor Stinner71aea8e2016-08-19 16:59:55 +0200148 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200150 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 m = o->ob_type->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100153 if (m && m->mp_subscript) {
154 PyObject *item = m->mp_subscript(o, key);
155 assert((item != NULL) ^ (PyErr_Occurred() != NULL));
156 return item;
157 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000158
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000159 ms = o->ob_type->tp_as_sequence;
160 if (ms && ms->sq_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (PyIndex_Check(key)) {
162 Py_ssize_t key_value;
163 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
164 if (key_value == -1 && PyErr_Occurred())
165 return NULL;
166 return PySequence_GetItem(o, key_value);
167 }
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000168 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return type_error("sequence index must "
170 "be integer, not '%.200s'", key);
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000171 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000173
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100174 if (PyType_Check(o)) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200175 PyObject *meth, *result;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100176 _Py_IDENTIFIER(__class_getitem__);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200177 if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
178 return NULL;
179 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100180 if (meth) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200181 result = _PyObject_CallOneArg(meth, key);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100182 Py_DECREF(meth);
183 return result;
184 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100185 }
186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000188}
189
190int
Fred Drake79912472000-07-09 04:06:11 +0000191PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (o == NULL || key == NULL || value == NULL) {
196 null_error();
197 return -1;
198 }
199 m = o->ob_type->tp_as_mapping;
200 if (m && m->mp_ass_subscript)
201 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (o->ob_type->tp_as_sequence) {
204 if (PyIndex_Check(key)) {
205 Py_ssize_t key_value;
206 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
207 if (key_value == -1 && PyErr_Occurred())
208 return -1;
209 return PySequence_SetItem(o, key_value, value);
210 }
211 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
212 type_error("sequence index must be "
213 "integer, not '%.200s'", key);
214 return -1;
215 }
216 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 type_error("'%.200s' object does not support item assignment", o);
219 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000220}
221
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000222int
Fred Drake79912472000-07-09 04:06:11 +0000223PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (o == NULL || key == NULL) {
228 null_error();
229 return -1;
230 }
231 m = o->ob_type->tp_as_mapping;
232 if (m && m->mp_ass_subscript)
233 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (o->ob_type->tp_as_sequence) {
236 if (PyIndex_Check(key)) {
237 Py_ssize_t key_value;
238 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
239 if (key_value == -1 && PyErr_Occurred())
240 return -1;
241 return PySequence_DelItem(o, key_value);
242 }
243 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
244 type_error("sequence index must be "
245 "integer, not '%.200s'", key);
246 return -1;
247 }
248 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 type_error("'%.200s' object does not support item deletion", o);
251 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000252}
253
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000254int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300255PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 PyObject *okey;
258 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (o == NULL || key == NULL) {
261 null_error();
262 return -1;
263 }
264 okey = PyUnicode_FromString(key);
265 if (okey == NULL)
266 return -1;
267 ret = PyObject_DelItem(o, okey);
268 Py_DECREF(okey);
269 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000270}
271
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000272/* We release the buffer right after use of this function which could
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 cause issues later on. Don't use these functions in new code.
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000274 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000275int
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000276PyObject_CheckReadBuffer(PyObject *obj)
277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
279 Py_buffer view;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (pb == NULL ||
282 pb->bf_getbuffer == NULL)
283 return 0;
284 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
285 PyErr_Clear();
286 return 0;
287 }
288 PyBuffer_Release(&view);
289 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000290}
291
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200292static int
293as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
298 null_error();
299 return -1;
300 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200301 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return -1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 *buffer = view.buf;
305 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200306 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000308}
309
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200310int
311PyObject_AsCharBuffer(PyObject *obj,
312 const char **buffer,
313 Py_ssize_t *buffer_len)
314{
315 return as_read_buffer(obj, (const void **)buffer, buffer_len);
316}
317
318int PyObject_AsReadBuffer(PyObject *obj,
319 const void **buffer,
320 Py_ssize_t *buffer_len)
321{
322 return as_read_buffer(obj, buffer, buffer_len);
323}
324
Guido van Rossum4c08d552000-03-10 22:55:18 +0000325int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 void **buffer,
327 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyBufferProcs *pb;
330 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
333 null_error();
334 return -1;
335 }
336 pb = obj->ob_type->tp_as_buffer;
337 if (pb == NULL ||
338 pb->bf_getbuffer == NULL ||
339 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
340 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400341 "expected a writable bytes-like object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return -1;
343 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 *buffer = view.buf;
346 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200347 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000349}
350
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000351/* Buffer C-API for Python 3.0 */
352
353int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000354PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000355{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200356 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
357
358 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400360 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 Py_TYPE(obj)->tp_name);
362 return -1;
363 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200364 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000365}
366
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000367static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100368_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 Py_ssize_t sd, dim;
371 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000372
Stefan Krah363af442015-02-01 14:53:54 +0100373 /* 1) len = product(shape) * itemsize
374 2) itemsize > 0
375 3) len = 0 <==> exists i: shape[i] = 0 */
376 if (view->len == 0) return 1;
377 if (view->strides == NULL) { /* C-contiguous by definition */
378 /* Trivially F-contiguous */
379 if (view->ndim <= 1) return 1;
380
381 /* ndim > 1 implies shape != NULL */
382 assert(view->shape != NULL);
383
384 /* Effectively 1-d */
385 sd = 0;
386 for (i=0; i<view->ndim; i++) {
387 if (view->shape[i] > 1) sd += 1;
388 }
389 return sd <= 1;
390 }
391
392 /* strides != NULL implies both of these */
393 assert(view->ndim > 0);
394 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 for (i=0; i<view->ndim; i++) {
398 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100399 if (dim > 1 && view->strides[i] != sd) {
400 return 0;
401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 sd *= dim;
403 }
404 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000405}
406
407static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100408_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_ssize_t sd, dim;
411 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000412
Stefan Krah363af442015-02-01 14:53:54 +0100413 /* 1) len = product(shape) * itemsize
414 2) itemsize > 0
415 3) len = 0 <==> exists i: shape[i] = 0 */
416 if (view->len == 0) return 1;
417 if (view->strides == NULL) return 1; /* C-contiguous by definition */
418
419 /* strides != NULL implies both of these */
420 assert(view->ndim > 0);
421 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 for (i=view->ndim-1; i>=0; i--) {
425 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100426 if (dim > 1 && view->strides[i] != sd) {
427 return 0;
428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 sd *= dim;
430 }
431 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000432}
433
434int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100435PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000436{
437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000439
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100440 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100442 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100444 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 return (_IsCContiguous(view) || _IsFortranContiguous(view));
446 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000447}
448
449
Guido van Rossum98297ee2007-11-06 21:34:58 +0000450void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000451PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 char* pointer;
454 int i;
455 pointer = (char *)view->buf;
456 for (i = 0; i < view->ndim; i++) {
457 pointer += view->strides[i]*indices[i];
458 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
459 pointer = *((char**)pointer) + view->suboffsets[i];
460 }
461 }
462 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000463}
464
465
Guido van Rossum98297ee2007-11-06 21:34:58 +0000466void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000467_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 +0000468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 for (k=0; k<nd; k++) {
472 if (index[k] < shape[k]-1) {
473 index[k]++;
474 break;
475 }
476 else {
477 index[k] = 0;
478 }
479 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000480}
481
Guido van Rossum98297ee2007-11-06 21:34:58 +0000482void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000483_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 +0000484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 for (k=nd-1; k>=0; k--) {
488 if (index[k] < shape[k]-1) {
489 index[k]++;
490 break;
491 }
492 else {
493 index[k] = 0;
494 }
495 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000496}
497
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -0300498Py_ssize_t
499PyBuffer_SizeFromFormat(const char *format)
500{
501 PyObject *structmodule = NULL;
502 PyObject *calcsize = NULL;
503 PyObject *res = NULL;
504 PyObject *fmt = NULL;
505 Py_ssize_t itemsize = -1;
506
507 structmodule = PyImport_ImportModule("struct");
508 if (structmodule == NULL) {
509 return itemsize;
510 }
511
512 calcsize = PyObject_GetAttrString(structmodule, "calcsize");
513 if (calcsize == NULL) {
514 goto done;
515 }
516
517 fmt = PyUnicode_FromString(format);
518 if (fmt == NULL) {
519 goto done;
520 }
521
522 res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
523 if (res == NULL) {
524 goto done;
525 }
526
527 itemsize = PyLong_AsSsize_t(res);
528 if (itemsize < 0) {
529 goto done;
530 }
531
532done:
533 Py_DECREF(structmodule);
534 Py_XDECREF(calcsize);
535 Py_XDECREF(fmt);
536 Py_XDECREF(res);
537 return itemsize;
538}
539
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000540int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000541PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000544 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 Py_ssize_t *indices, elements;
546 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (len > view->len) {
549 len = view->len;
550 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (PyBuffer_IsContiguous(view, fort)) {
553 /* simplest copy is all that is needed */
554 memcpy(view->buf, buf, len);
555 return 0;
556 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559
Stefan Krah7213fcc2015-02-01 16:19:23 +0100560 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
562 if (indices == NULL) {
563 PyErr_NoMemory();
564 return -1;
565 }
566 for (k=0; k<view->ndim;k++) {
567 indices[k] = 0;
568 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000571 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 }
573 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000574 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 }
576 src = buf;
577 /* XXX : This is not going to be the fastest code in the world
578 several optimizations are possible.
579 */
580 elements = len / view->itemsize;
581 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 ptr = PyBuffer_GetPointer(view, indices);
583 memcpy(ptr, src, view->itemsize);
584 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100585 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 PyMem_Free(indices);
589 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000590}
591
Guido van Rossum98297ee2007-11-06 21:34:58 +0000592int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_buffer view_dest, view_src;
595 int k;
596 Py_ssize_t *indices, elements;
597 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (!PyObject_CheckBuffer(dest) ||
600 !PyObject_CheckBuffer(src)) {
601 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400602 "both destination and source must be "\
603 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return -1;
605 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
608 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
609 PyBuffer_Release(&view_dest);
610 return -1;
611 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (view_dest.len < view_src.len) {
614 PyErr_SetString(PyExc_BufferError,
615 "destination is too small to receive data from source");
616 PyBuffer_Release(&view_dest);
617 PyBuffer_Release(&view_src);
618 return -1;
619 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
622 PyBuffer_IsContiguous(&view_src, 'C')) ||
623 (PyBuffer_IsContiguous(&view_dest, 'F') &&
624 PyBuffer_IsContiguous(&view_src, 'F'))) {
625 /* simplest copy is all that is needed */
626 memcpy(view_dest.buf, view_src.buf, view_src.len);
627 PyBuffer_Release(&view_dest);
628 PyBuffer_Release(&view_src);
629 return 0;
630 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 /* XXX(nnorwitz): need to check for overflow! */
635 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
636 if (indices == NULL) {
637 PyErr_NoMemory();
638 PyBuffer_Release(&view_dest);
639 PyBuffer_Release(&view_src);
640 return -1;
641 }
642 for (k=0; k<view_src.ndim;k++) {
643 indices[k] = 0;
644 }
645 elements = 1;
646 for (k=0; k<view_src.ndim; k++) {
647 /* XXX(nnorwitz): can this overflow? */
648 elements *= view_src.shape[k];
649 }
650 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000651 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 dptr = PyBuffer_GetPointer(&view_dest, indices);
653 sptr = PyBuffer_GetPointer(&view_src, indices);
654 memcpy(dptr, sptr, view_src.itemsize);
655 }
656 PyMem_Free(indices);
657 PyBuffer_Release(&view_dest);
658 PyBuffer_Release(&view_src);
659 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000660}
661
662void
663PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 Py_ssize_t *strides, int itemsize,
665 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 int k;
668 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 sd = itemsize;
671 if (fort == 'F') {
672 for (k=0; k<nd; k++) {
673 strides[k] = sd;
674 sd *= shape[k];
675 }
676 }
677 else {
678 for (k=nd-1; k>=0; k--) {
679 strides[k] = sd;
680 sd *= shape[k];
681 }
682 }
683 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000684}
685
686int
Martin v. Löwis423be952008-08-13 15:53:07 +0000687PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100688 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000689{
Stefan Krah5178d912015-02-03 16:57:21 +0100690 if (view == NULL) {
691 PyErr_SetString(PyExc_BufferError,
692 "PyBuffer_FillInfo: view==NULL argument is obsolete");
693 return -1;
694 }
695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
697 (readonly == 1)) {
698 PyErr_SetString(PyExc_BufferError,
699 "Object is not writable.");
700 return -1;
701 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 view->obj = obj;
704 if (obj)
705 Py_INCREF(obj);
706 view->buf = buf;
707 view->len = len;
708 view->readonly = readonly;
709 view->itemsize = 1;
710 view->format = NULL;
711 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
712 view->format = "B";
713 view->ndim = 1;
714 view->shape = NULL;
715 if ((flags & PyBUF_ND) == PyBUF_ND)
716 view->shape = &(view->len);
717 view->strides = NULL;
718 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
719 view->strides = &(view->itemsize);
720 view->suboffsets = NULL;
721 view->internal = NULL;
722 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000723}
724
Martin v. Löwis423be952008-08-13 15:53:07 +0000725void
726PyBuffer_Release(Py_buffer *view)
727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200729 PyBufferProcs *pb;
730 if (obj == NULL)
731 return;
732 pb = Py_TYPE(obj)->tp_as_buffer;
733 if (pb && pb->bf_releasebuffer)
734 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200736 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000737}
738
Eric Smith8fd3eba2008-02-17 19:48:00 +0000739PyObject *
740PyObject_Format(PyObject *obj, PyObject *format_spec)
741{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000742 PyObject *meth;
743 PyObject *empty = NULL;
744 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500745 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000746
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300747 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
748 PyErr_Format(PyExc_SystemError,
749 "Format specifier must be a string, not %.200s",
750 Py_TYPE(format_spec)->tp_name);
751 return NULL;
752 }
753
754 /* Fast path for common types. */
755 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
756 if (PyUnicode_CheckExact(obj)) {
757 Py_INCREF(obj);
758 return obj;
759 }
760 if (PyLong_CheckExact(obj)) {
761 return PyObject_Str(obj);
762 }
763 }
764
Eric Smith8fd3eba2008-02-17 19:48:00 +0000765 /* If no format_spec is provided, use an empty string */
766 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100767 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000768 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000769 }
770
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300771 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500772 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000773 if (meth == NULL) {
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000774 if (!PyErr_Occurred())
775 PyErr_Format(PyExc_TypeError,
776 "Type %.100s doesn't define __format__",
777 Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000779 }
780
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000781 /* And call it. */
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200782 result = _PyObject_CallOneArg(meth, format_spec);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000783 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000784
785 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800786 PyErr_Format(PyExc_TypeError,
787 "__format__ must return a str, not %.200s",
788 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000789 Py_DECREF(result);
790 result = NULL;
791 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000792 }
793
794done:
795 Py_XDECREF(empty);
796 return result;
797}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000798/* Operations on numbers */
799
800int
Fred Drake79912472000-07-09 04:06:11 +0000801PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return o && o->ob_type->tp_as_number &&
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200804 (o->ob_type->tp_as_number->nb_index ||
805 o->ob_type->tp_as_number->nb_int ||
806 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000807}
808
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000809/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000810
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000811#define NB_SLOT(x) offsetof(PyNumberMethods, x)
812#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000814#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000816
817/*
818 Calling scheme used for binary operations:
819
Neal Norwitz4886cc32006-08-21 17:06:07 +0000820 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000822
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000823 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
824 v->ob_type
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000825 */
826
827static PyObject *
828binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *x;
831 binaryfunc slotv = NULL;
832 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (v->ob_type->tp_as_number != NULL)
835 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
836 if (w->ob_type != v->ob_type &&
837 w->ob_type->tp_as_number != NULL) {
838 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
839 if (slotw == slotv)
840 slotw = NULL;
841 }
842 if (slotv) {
843 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
844 x = slotw(v, w);
845 if (x != Py_NotImplemented)
846 return x;
847 Py_DECREF(x); /* can't do it */
848 slotw = NULL;
849 }
850 x = slotv(v, w);
851 if (x != Py_NotImplemented)
852 return x;
853 Py_DECREF(x); /* can't do it */
854 }
855 if (slotw) {
856 x = slotw(v, w);
857 if (x != Py_NotImplemented)
858 return x;
859 Py_DECREF(x); /* can't do it */
860 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500861 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000862}
Guido van Rossum77660912002-04-16 16:32:50 +0000863
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000864static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000865binop_type_error(PyObject *v, PyObject *w, const char *op_name)
866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 PyErr_Format(PyExc_TypeError,
868 "unsupported operand type(s) for %.100s: "
869 "'%.100s' and '%.100s'",
870 op_name,
871 v->ob_type->tp_name,
872 w->ob_type->tp_name);
873 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000874}
875
876static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000877binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyObject *result = binary_op1(v, w, op_slot);
880 if (result == Py_NotImplemented) {
881 Py_DECREF(result);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530882
883 if (op_slot == NB_SLOT(nb_rshift) &&
884 PyCFunction_Check(v) &&
885 strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
886 {
887 PyErr_Format(PyExc_TypeError,
888 "unsupported operand type(s) for %.100s: "
889 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
Sanyam Khuranaa7c449b2017-08-18 17:48:14 +0530890 "file=<output_stream>)\"?",
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530891 op_name,
892 v->ob_type->tp_name,
893 w->ob_type->tp_name);
894 return NULL;
895 }
896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return binop_type_error(v, w, op_name);
898 }
899 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000900}
901
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000902
903/*
904 Calling scheme used for ternary operations:
905
Neal Norwitz4886cc32006-08-21 17:06:07 +0000906 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000908 */
909
910static PyObject *
911ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 PyObject *w,
913 PyObject *z,
914 const int op_slot,
915 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyNumberMethods *mv, *mw, *mz;
918 PyObject *x = NULL;
919 ternaryfunc slotv = NULL;
920 ternaryfunc slotw = NULL;
921 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 mv = v->ob_type->tp_as_number;
924 mw = w->ob_type->tp_as_number;
925 if (mv != NULL)
926 slotv = NB_TERNOP(mv, op_slot);
927 if (w->ob_type != v->ob_type &&
928 mw != NULL) {
929 slotw = NB_TERNOP(mw, op_slot);
930 if (slotw == slotv)
931 slotw = NULL;
932 }
933 if (slotv) {
934 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
935 x = slotw(v, w, z);
936 if (x != Py_NotImplemented)
937 return x;
938 Py_DECREF(x); /* can't do it */
939 slotw = NULL;
940 }
941 x = slotv(v, w, z);
942 if (x != Py_NotImplemented)
943 return x;
944 Py_DECREF(x); /* can't do it */
945 }
946 if (slotw) {
947 x = slotw(v, w, z);
948 if (x != Py_NotImplemented)
949 return x;
950 Py_DECREF(x); /* can't do it */
951 }
952 mz = z->ob_type->tp_as_number;
953 if (mz != NULL) {
954 slotz = NB_TERNOP(mz, op_slot);
955 if (slotz == slotv || slotz == slotw)
956 slotz = NULL;
957 if (slotz) {
958 x = slotz(v, w, z);
959 if (x != Py_NotImplemented)
960 return x;
961 Py_DECREF(x); /* can't do it */
962 }
963 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (z == Py_None)
966 PyErr_Format(
967 PyExc_TypeError,
968 "unsupported operand type(s) for ** or pow(): "
969 "'%.100s' and '%.100s'",
970 v->ob_type->tp_name,
971 w->ob_type->tp_name);
972 else
973 PyErr_Format(
974 PyExc_TypeError,
975 "unsupported operand type(s) for pow(): "
976 "'%.100s', '%.100s', '%.100s'",
977 v->ob_type->tp_name,
978 w->ob_type->tp_name,
979 z->ob_type->tp_name);
980 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +0000981}
982
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000983#define BINARY_FUNC(func, op, op_name) \
984 PyObject * \
985 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000987 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000988
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000989BINARY_FUNC(PyNumber_Or, nb_or, "|")
990BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
991BINARY_FUNC(PyNumber_And, nb_and, "&")
992BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
993BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
994BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000995BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +0000996
997PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000998PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1001 if (result == Py_NotImplemented) {
1002 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1003 Py_DECREF(result);
1004 if (m && m->sq_concat) {
1005 return (*m->sq_concat)(v, w);
1006 }
1007 result = binop_type_error(v, w, "+");
1008 }
1009 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001010}
1011
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001012static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001013sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Py_ssize_t count;
1016 if (PyIndex_Check(n)) {
1017 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1018 if (count == -1 && PyErr_Occurred())
1019 return NULL;
1020 }
1021 else {
1022 return type_error("can't multiply sequence by "
1023 "non-int of type '%.200s'", n);
1024 }
1025 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001026}
1027
1028PyObject *
1029PyNumber_Multiply(PyObject *v, PyObject *w)
1030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1032 if (result == Py_NotImplemented) {
1033 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1034 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1035 Py_DECREF(result);
1036 if (mv && mv->sq_repeat) {
1037 return sequence_repeat(mv->sq_repeat, v, w);
1038 }
1039 else if (mw && mw->sq_repeat) {
1040 return sequence_repeat(mw->sq_repeat, w, v);
1041 }
1042 result = binop_type_error(v, w, "*");
1043 }
1044 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001045}
1046
Guido van Rossume15dee51995-07-18 14:12:02 +00001047PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001048PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1049{
1050 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1051}
1052
1053PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001054PyNumber_FloorDivide(PyObject *v, PyObject *w)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001057}
1058
1059PyObject *
1060PyNumber_TrueDivide(PyObject *v, PyObject *w)
1061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001063}
1064
1065PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001066PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001069}
1070
1071PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001072PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001075}
1076
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001077/* Binary in-place operators */
1078
1079/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001080 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001081
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001082 - If the left hand object has the appropriate struct members, and
1083 they are filled, call the appropriate function and return the
1084 result. No coercion is done on the arguments; the left-hand object
1085 is the one the operation is performed on, and it's up to the
1086 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001087
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001088 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001089 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001090
1091 */
1092
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001093static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001094binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyNumberMethods *mv = v->ob_type->tp_as_number;
1097 if (mv != NULL) {
1098 binaryfunc slot = NB_BINOP(mv, iop_slot);
1099 if (slot) {
1100 PyObject *x = (slot)(v, w);
1101 if (x != Py_NotImplemented) {
1102 return x;
1103 }
1104 Py_DECREF(x);
1105 }
1106 }
1107 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001108}
1109
1110static PyObject *
1111binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1115 if (result == Py_NotImplemented) {
1116 Py_DECREF(result);
1117 return binop_type_error(v, w, op_name);
1118 }
1119 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001120}
1121
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001122#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyObject * \
1124 func(PyObject *v, PyObject *w) { \
1125 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1126 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001127
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001128INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1129INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1130INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1131INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1132INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1133INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001134INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001135
1136PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001137PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1140 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001141}
1142
1143PyObject *
1144PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1147 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001148}
1149
1150PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001151PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1154 NB_SLOT(nb_add));
1155 if (result == Py_NotImplemented) {
1156 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1157 Py_DECREF(result);
1158 if (m != NULL) {
1159 binaryfunc f = NULL;
1160 f = m->sq_inplace_concat;
1161 if (f == NULL)
1162 f = m->sq_concat;
1163 if (f != NULL)
1164 return (*f)(v, w);
1165 }
1166 result = binop_type_error(v, w, "+=");
1167 }
1168 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001169}
1170
1171PyObject *
1172PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1175 NB_SLOT(nb_multiply));
1176 if (result == Py_NotImplemented) {
1177 ssizeargfunc f = NULL;
1178 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1179 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1180 Py_DECREF(result);
1181 if (mv != NULL) {
1182 f = mv->sq_inplace_repeat;
1183 if (f == NULL)
1184 f = mv->sq_repeat;
1185 if (f != NULL)
1186 return sequence_repeat(f, v, w);
1187 }
1188 else if (mw != NULL) {
1189 /* Note that the right hand operand should not be
1190 * mutated in this case so sq_inplace_repeat is not
1191 * used. */
1192 if (mw->sq_repeat)
1193 return sequence_repeat(mw->sq_repeat, w, v);
1194 }
1195 result = binop_type_error(v, w, "*=");
1196 }
1197 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001198}
1199
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001200PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001201PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1202{
1203 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1204 NB_SLOT(nb_matrix_multiply), "@=");
1205}
1206
1207PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001208PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1211 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001212}
1213
1214PyObject *
1215PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (v->ob_type->tp_as_number &&
1218 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1219 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1220 }
1221 else {
1222 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1223 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001224}
1225
1226
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001227/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001228
1229PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001230PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001233
Victor Stinner71aea8e2016-08-19 16:59:55 +02001234 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001236 }
1237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 m = o->ob_type->tp_as_number;
1239 if (m && m->nb_negative)
1240 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001243}
1244
1245PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001246PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001249
Victor Stinner71aea8e2016-08-19 16:59:55 +02001250 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001252 }
1253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 m = o->ob_type->tp_as_number;
1255 if (m && m->nb_positive)
1256 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001259}
1260
1261PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001262PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001265
Victor Stinner71aea8e2016-08-19 16:59:55 +02001266 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001268 }
1269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 m = o->ob_type->tp_as_number;
1271 if (m && m->nb_invert)
1272 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001275}
1276
1277PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001278PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001281
Victor Stinner71aea8e2016-08-19 16:59:55 +02001282 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001284 }
1285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 m = o->ob_type->tp_as_number;
1287 if (m && m->nb_absolute)
1288 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001291}
1292
Christian Tismerea62ce72018-06-09 20:32:25 +02001293#undef PyIndex_Check
Christian Tismer83987132018-06-11 00:48:28 +02001294
Christian Tismerea62ce72018-06-09 20:32:25 +02001295int
1296PyIndex_Check(PyObject *obj)
1297{
1298 return obj->ob_type->tp_as_number != NULL &&
1299 obj->ob_type->tp_as_number->nb_index != NULL;
1300}
1301
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001302/* Return a Python int from the object item.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001303 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001304 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001305*/
1306PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001307PyNumber_Index(PyObject *item)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001310 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001312 }
1313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (PyLong_Check(item)) {
1315 Py_INCREF(item);
1316 return item;
1317 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001318 if (!PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyErr_Format(PyExc_TypeError,
1320 "'%.200s' object cannot be interpreted "
1321 "as an integer", item->ob_type->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001322 return NULL;
1323 }
1324 result = item->ob_type->tp_as_number->nb_index(item);
1325 if (!result || PyLong_CheckExact(result))
1326 return result;
1327 if (!PyLong_Check(result)) {
1328 PyErr_Format(PyExc_TypeError,
1329 "__index__ returned non-int (type %.200s)",
1330 result->ob_type->tp_name);
1331 Py_DECREF(result);
1332 return NULL;
1333 }
1334 /* Issue #17576: warn if 'result' not of exact type int. */
1335 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1336 "__index__ returned non-int (type %.200s). "
1337 "The ability to return an instance of a strict subclass of int "
1338 "is deprecated, and may be removed in a future version of Python.",
1339 result->ob_type->tp_name)) {
1340 Py_DECREF(result);
1341 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 }
1343 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001344}
1345
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001346/* Return an error on Overflow only if err is not NULL*/
1347
1348Py_ssize_t
1349PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 Py_ssize_t result;
1352 PyObject *runerr;
1353 PyObject *value = PyNumber_Index(item);
1354 if (value == NULL)
1355 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* We're done if PyLong_AsSsize_t() returns without error. */
1358 result = PyLong_AsSsize_t(value);
1359 if (result != -1 || !(runerr = PyErr_Occurred()))
1360 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* Error handling code -- only manage OverflowError differently */
1363 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1364 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyErr_Clear();
1367 /* If no error-handling desired then the default clipping
1368 is sufficient.
1369 */
1370 if (!err) {
1371 assert(PyLong_Check(value));
1372 /* Whether or not it is less than or equal to
1373 zero is determined by the sign of ob_size
1374 */
1375 if (_PyLong_Sign(value) < 0)
1376 result = PY_SSIZE_T_MIN;
1377 else
1378 result = PY_SSIZE_T_MAX;
1379 }
1380 else {
1381 /* Otherwise replace the error with caller's error object. */
1382 PyErr_Format(err,
1383 "cannot fit '%.200s' into an index-sized integer",
1384 item->ob_type->tp_name);
1385 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001386
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001387 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_DECREF(value);
1389 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001390}
1391
1392
Guido van Rossume15dee51995-07-18 14:12:02 +00001393PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001394PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001395{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001396 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001399 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001400 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001401
Victor Stinner71aea8e2016-08-19 16:59:55 +02001402 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001404 }
1405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (PyLong_CheckExact(o)) {
1407 Py_INCREF(o);
1408 return o;
1409 }
1410 m = o->ob_type->tp_as_number;
1411 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001412 result = _PyLong_FromNbInt(o);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001413 if (result != NULL && !PyLong_CheckExact(result)) {
1414 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1415 }
1416 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001418 if (m && m->nb_index) {
1419 result = _PyLong_FromNbIndexOrNbInt(o);
1420 if (result != NULL && !PyLong_CheckExact(result)) {
1421 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1422 }
1423 return result;
1424 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001425 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001427 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001429 if (result == NULL || PyLong_CheckExact(result)) {
1430 return result;
1431 }
1432 if (PyLong_Check(result)) {
1433 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1434 return result;
1435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001437 but int() needs to return an int. */
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001438 m = result->ob_type->tp_as_number;
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001439 if (m == NULL || (m->nb_index == NULL && m->nb_int == NULL)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001440 PyErr_Format(
1441 PyExc_TypeError,
1442 "__trunc__ returned non-Integral (type %.200s)",
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001443 result->ob_type->tp_name);
1444 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001445 return NULL;
1446 }
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001447 Py_SETREF(result, _PyLong_FromNbIndexOrNbInt(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001448 if (result != NULL && !PyLong_CheckExact(result)) {
1449 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1450 }
1451 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001453 if (PyErr_Occurred())
1454 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001455
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001456 if (PyUnicode_Check(o))
1457 /* The below check is done in PyLong_FromUnicode(). */
1458 return PyLong_FromUnicodeObject(o, 10);
1459
Martin Pantereeb896c2015-11-07 02:32:21 +00001460 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001462 * doesn't do. In particular int('9\x005') must raise an
1463 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001465 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1466 PyBytes_GET_SIZE(o), 10);
1467
1468 if (PyByteArray_Check(o))
1469 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1470 PyByteArray_GET_SIZE(o), 10);
1471
1472 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001473 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001474
1475 /* Copy to NUL-terminated buffer. */
1476 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1477 if (bytes == NULL) {
1478 PyBuffer_Release(&view);
1479 return NULL;
1480 }
1481 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1482 PyBytes_GET_SIZE(bytes), 10);
1483 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001484 PyBuffer_Release(&view);
1485 return result;
1486 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001487
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001488 return type_error("int() argument must be a string, a bytes-like object "
1489 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001490}
1491
1492PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001493PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001496
Victor Stinner71aea8e2016-08-19 16:59:55 +02001497 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001499 }
1500
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001501 if (PyFloat_CheckExact(o)) {
1502 Py_INCREF(o);
1503 return o;
1504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 m = o->ob_type->tp_as_number;
1506 if (m && m->nb_float) { /* This should include subclasses of float */
1507 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001508 double val;
1509 if (!res || PyFloat_CheckExact(res)) {
1510 return res;
1511 }
1512 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001514 "%.50s.__float__ returned non-float (type %.50s)",
1515 o->ob_type->tp_name, res->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 Py_DECREF(res);
1517 return NULL;
1518 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001519 /* Issue #26983: warn if 'res' not of exact type float. */
1520 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1521 "%.50s.__float__ returned non-float (type %.50s). "
1522 "The ability to return an instance of a strict subclass of float "
1523 "is deprecated, and may be removed in a future version of Python.",
1524 o->ob_type->tp_name, res->ob_type->tp_name)) {
1525 Py_DECREF(res);
1526 return NULL;
1527 }
1528 val = PyFloat_AS_DOUBLE(res);
1529 Py_DECREF(res);
1530 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001532 if (m && m->nb_index) {
1533 PyObject *res = PyNumber_Index(o);
1534 if (!res) {
1535 return NULL;
1536 }
1537 double val = PyLong_AsDouble(res);
1538 Py_DECREF(res);
1539 if (val == -1.0 && PyErr_Occurred()) {
1540 return NULL;
1541 }
1542 return PyFloat_FromDouble(val);
1543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001545 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 }
1547 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001548}
1549
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001550
1551PyObject *
1552PyNumber_ToBase(PyObject *n, int base)
1553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyObject *res = NULL;
1555 PyObject *index = PyNumber_Index(n);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (!index)
1558 return NULL;
1559 if (PyLong_Check(index))
1560 res = _PyLong_Format(index, base);
1561 else
1562 /* It should not be possible to get here, as
1563 PyNumber_Index already has a check for the same
1564 condition */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001565 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 Py_DECREF(index);
1567 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001568}
1569
1570
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001571/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001572
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001573int
Fred Drake79912472000-07-09 04:06:11 +00001574PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (PyDict_Check(s))
1577 return 0;
Alexey Izbyshevb57b4ac2018-08-26 02:52:27 +03001578 return s->ob_type->tp_as_sequence &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001580}
1581
Martin v. Löwis18e16552006-02-15 17:27:45 +00001582Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001583PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (s == NULL) {
1588 null_error();
1589 return -1;
1590 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 m = s->ob_type->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001593 if (m && m->sq_length) {
1594 Py_ssize_t len = m->sq_length(s);
1595 assert(len >= 0 || PyErr_Occurred());
1596 return len;
1597 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001598
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001599 if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_length) {
1600 type_error("%.200s is not a sequence", s);
1601 return -1;
1602 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 type_error("object of type '%.200s' has no len()", s);
1604 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001605}
1606
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001607#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001608Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001609PySequence_Length(PyObject *s)
1610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001612}
1613#define PySequence_Length PySequence_Size
1614
Guido van Rossume15dee51995-07-18 14:12:02 +00001615PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001616PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001619
Victor Stinner71aea8e2016-08-19 16:59:55 +02001620 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001622 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 m = s->ob_type->tp_as_sequence;
1625 if (m && m->sq_concat)
1626 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 /* Instances of user classes defining an __add__() method only
1629 have an nb_add slot, not an sq_concat slot. So we fall back
1630 to nb_add if both arguments appear to be sequences. */
1631 if (PySequence_Check(s) && PySequence_Check(o)) {
1632 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1633 if (result != Py_NotImplemented)
1634 return result;
1635 Py_DECREF(result);
1636 }
1637 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001638}
1639
1640PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001641PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001644
Victor Stinner71aea8e2016-08-19 16:59:55 +02001645 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001647 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 m = o->ob_type->tp_as_sequence;
1650 if (m && m->sq_repeat)
1651 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* Instances of user classes defining a __mul__() method only
1654 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1655 to nb_multiply if o appears to be a sequence. */
1656 if (PySequence_Check(o)) {
1657 PyObject *n, *result;
1658 n = PyLong_FromSsize_t(count);
1659 if (n == NULL)
1660 return NULL;
1661 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1662 Py_DECREF(n);
1663 if (result != Py_NotImplemented)
1664 return result;
1665 Py_DECREF(result);
1666 }
1667 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001668}
1669
1670PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001671PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001674
Victor Stinner71aea8e2016-08-19 16:59:55 +02001675 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001677 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 m = s->ob_type->tp_as_sequence;
1680 if (m && m->sq_inplace_concat)
1681 return m->sq_inplace_concat(s, o);
1682 if (m && m->sq_concat)
1683 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (PySequence_Check(s) && PySequence_Check(o)) {
1686 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1687 NB_SLOT(nb_add));
1688 if (result != Py_NotImplemented)
1689 return result;
1690 Py_DECREF(result);
1691 }
1692 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001693}
1694
1695PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001696PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001699
Victor Stinner71aea8e2016-08-19 16:59:55 +02001700 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001702 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 m = o->ob_type->tp_as_sequence;
1705 if (m && m->sq_inplace_repeat)
1706 return m->sq_inplace_repeat(o, count);
1707 if (m && m->sq_repeat)
1708 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (PySequence_Check(o)) {
1711 PyObject *n, *result;
1712 n = PyLong_FromSsize_t(count);
1713 if (n == NULL)
1714 return NULL;
1715 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1716 NB_SLOT(nb_multiply));
1717 Py_DECREF(n);
1718 if (result != Py_NotImplemented)
1719 return result;
1720 Py_DECREF(result);
1721 }
1722 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001723}
1724
1725PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001726PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001729
Victor Stinner71aea8e2016-08-19 16:59:55 +02001730 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001732 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 m = s->ob_type->tp_as_sequence;
1735 if (m && m->sq_item) {
1736 if (i < 0) {
1737 if (m->sq_length) {
1738 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001739 if (l < 0) {
1740 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 i += l;
1744 }
1745 }
1746 return m->sq_item(s, i);
1747 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001748
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001749 if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_subscript) {
1750 return type_error("%.200s is not a sequence", s);
1751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001753}
1754
1755PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001756PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001759
Victor Stinner71aea8e2016-08-19 16:59:55 +02001760 if (!s) {
1761 return null_error();
1762 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001765 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *res;
1767 PyObject *slice = _PySlice_FromIndices(i1, i2);
1768 if (!slice)
1769 return NULL;
1770 res = mp->mp_subscript(s, slice);
1771 Py_DECREF(slice);
1772 return res;
1773 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001776}
1777
1778int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001779PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (s == NULL) {
1784 null_error();
1785 return -1;
1786 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 m = s->ob_type->tp_as_sequence;
1789 if (m && m->sq_ass_item) {
1790 if (i < 0) {
1791 if (m->sq_length) {
1792 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001793 if (l < 0) {
1794 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001796 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 i += l;
1798 }
1799 }
1800 return m->sq_ass_item(s, i, o);
1801 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001802
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001803 if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_ass_subscript) {
1804 type_error("%.200s is not a sequence", s);
1805 return -1;
1806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 type_error("'%.200s' object does not support item assignment", s);
1808 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001809}
1810
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001811int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001812PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (s == NULL) {
1817 null_error();
1818 return -1;
1819 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 m = s->ob_type->tp_as_sequence;
1822 if (m && m->sq_ass_item) {
1823 if (i < 0) {
1824 if (m->sq_length) {
1825 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001826 if (l < 0) {
1827 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 i += l;
1831 }
1832 }
1833 return m->sq_ass_item(s, i, (PyObject *)NULL);
1834 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001835
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001836 if (s->ob_type->tp_as_mapping && s->ob_type->tp_as_mapping->mp_ass_subscript) {
1837 type_error("%.200s is not a sequence", s);
1838 return -1;
1839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 type_error("'%.200s' object doesn't support item deletion", s);
1841 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001842}
1843
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001844int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001845PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (s == NULL) {
1850 null_error();
1851 return -1;
1852 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001855 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int res;
1857 PyObject *slice = _PySlice_FromIndices(i1, i2);
1858 if (!slice)
1859 return -1;
1860 res = mp->mp_ass_subscript(s, slice, o);
1861 Py_DECREF(slice);
1862 return res;
1863 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 type_error("'%.200s' object doesn't support slice assignment", s);
1866 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001867}
1868
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001869int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001870PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (s == NULL) {
1875 null_error();
1876 return -1;
1877 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001880 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 int res;
1882 PyObject *slice = _PySlice_FromIndices(i1, i2);
1883 if (!slice)
1884 return -1;
1885 res = mp->mp_ass_subscript(s, slice, NULL);
1886 Py_DECREF(slice);
1887 return res;
1888 }
1889 type_error("'%.200s' object doesn't support slice deletion", s);
1890 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001891}
1892
Guido van Rossume15dee51995-07-18 14:12:02 +00001893PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001894PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyObject *it; /* iter(v) */
1897 Py_ssize_t n; /* guess for result tuple size */
1898 PyObject *result = NULL;
1899 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001900
Victor Stinner71aea8e2016-08-19 16:59:55 +02001901 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001903 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Special-case the common tuple and list cases, for efficiency. */
1906 if (PyTuple_CheckExact(v)) {
1907 /* Note that we can't know whether it's safe to return
1908 a tuple *subclass* instance as-is, hence the restriction
1909 to exact tuples here. In contrast, lists always make
1910 a copy, so there's no need for exactness below. */
1911 Py_INCREF(v);
1912 return v;
1913 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001914 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 /* Get iterator. */
1918 it = PyObject_GetIter(v);
1919 if (it == NULL)
1920 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001923 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (n == -1)
1925 goto Fail;
1926 result = PyTuple_New(n);
1927 if (result == NULL)
1928 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* Fill the tuple. */
1931 for (j = 0; ; ++j) {
1932 PyObject *item = PyIter_Next(it);
1933 if (item == NULL) {
1934 if (PyErr_Occurred())
1935 goto Fail;
1936 break;
1937 }
1938 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001939 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* The over-allocation strategy can grow a bit faster
1941 than for lists because unlike lists the
1942 over-allocation isn't permanent -- we reclaim
1943 the excess before the end of this routine.
1944 So, grow by ten and then add 25%.
1945 */
Martin Pantere8db8612016-07-25 02:30:05 +00001946 newn += 10u;
1947 newn += newn >> 2;
1948 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* Check for overflow */
1950 PyErr_NoMemory();
1951 Py_DECREF(item);
1952 goto Fail;
1953 }
Martin Pantere8db8612016-07-25 02:30:05 +00001954 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (_PyTuple_Resize(&result, n) != 0) {
1956 Py_DECREF(item);
1957 goto Fail;
1958 }
1959 }
1960 PyTuple_SET_ITEM(result, j, item);
1961 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* Cut tuple back if guess was too large. */
1964 if (j < n &&
1965 _PyTuple_Resize(&result, j) != 0)
1966 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 Py_DECREF(it);
1969 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00001970
1971Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 Py_XDECREF(result);
1973 Py_DECREF(it);
1974 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001975}
1976
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001977PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001978PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *result; /* result list */
1981 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00001982
Victor Stinner71aea8e2016-08-19 16:59:55 +02001983 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001985 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 result = PyList_New(0);
1988 if (result == NULL)
1989 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 rv = _PyList_Extend((PyListObject *)result, v);
1992 if (rv == NULL) {
1993 Py_DECREF(result);
1994 return NULL;
1995 }
1996 Py_DECREF(rv);
1997 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001998}
1999
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002000PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002001PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002004
Victor Stinner71aea8e2016-08-19 16:59:55 +02002005 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002007 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2010 Py_INCREF(v);
2011 return v;
2012 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 it = PyObject_GetIter(v);
2015 if (it == NULL) {
2016 if (PyErr_ExceptionMatches(PyExc_TypeError))
2017 PyErr_SetString(PyExc_TypeError, m);
2018 return NULL;
2019 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 v = PySequence_List(it);
2022 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002025}
2026
Tim Peters16a77ad2001-09-08 04:00:12 +00002027/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2029 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2030 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002031 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2032*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002033Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002034_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 Py_ssize_t n;
2037 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2038 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (seq == NULL || obj == NULL) {
2041 null_error();
2042 return -1;
2043 }
Tim Peters75f8e352001-05-05 11:33:43 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 it = PyObject_GetIter(seq);
2046 if (it == NULL) {
2047 type_error("argument of type '%.200s' is not iterable", seq);
2048 return -1;
2049 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 n = wrapped = 0;
2052 for (;;) {
2053 int cmp;
2054 PyObject *item = PyIter_Next(it);
2055 if (item == NULL) {
2056 if (PyErr_Occurred())
2057 goto Fail;
2058 break;
2059 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002060
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002061 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 Py_DECREF(item);
2063 if (cmp < 0)
2064 goto Fail;
2065 if (cmp > 0) {
2066 switch (operation) {
2067 case PY_ITERSEARCH_COUNT:
2068 if (n == PY_SSIZE_T_MAX) {
2069 PyErr_SetString(PyExc_OverflowError,
2070 "count exceeds C integer size");
2071 goto Fail;
2072 }
2073 ++n;
2074 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 case PY_ITERSEARCH_INDEX:
2077 if (wrapped) {
2078 PyErr_SetString(PyExc_OverflowError,
2079 "index exceeds C integer size");
2080 goto Fail;
2081 }
2082 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 case PY_ITERSEARCH_CONTAINS:
2085 n = 1;
2086 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002089 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 }
2091 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (operation == PY_ITERSEARCH_INDEX) {
2094 if (n == PY_SSIZE_T_MAX)
2095 wrapped = 1;
2096 ++n;
2097 }
2098 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (operation != PY_ITERSEARCH_INDEX)
2101 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyErr_SetString(PyExc_ValueError,
2104 "sequence.index(x): x not in sequence");
2105 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002106Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 n = -1;
2108 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002109Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 Py_DECREF(it);
2111 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002112
Guido van Rossume15dee51995-07-18 14:12:02 +00002113}
2114
Tim Peters16a77ad2001-09-08 04:00:12 +00002115/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002116Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002117PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002120}
2121
Tim Peterscb8d3682001-05-05 21:05:01 +00002122/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002123 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002124 */
2125int
2126PySequence_Contains(PyObject *seq, PyObject *ob)
2127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 Py_ssize_t result;
2129 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2130 if (sqm != NULL && sqm->sq_contains != NULL)
2131 return (*sqm->sq_contains)(seq, ob);
2132 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2133 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002134}
2135
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002136/* Backwards compatibility */
2137#undef PySequence_In
2138int
Fred Drake79912472000-07-09 04:06:11 +00002139PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002142}
2143
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002144Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002145PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002148}
2149
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002150/* Operations on mappings */
2151
2152int
Fred Drake79912472000-07-09 04:06:11 +00002153PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002154{
Benjamin Peterson21992272011-12-28 12:01:31 -06002155 return o && o->ob_type->tp_as_mapping &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 o->ob_type->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002157}
2158
Martin v. Löwis18e16552006-02-15 17:27:45 +00002159Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002160PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (o == NULL) {
2165 null_error();
2166 return -1;
2167 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 m = o->ob_type->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002170 if (m && m->mp_length) {
2171 Py_ssize_t len = m->mp_length(o);
2172 assert(len >= 0 || PyErr_Occurred());
2173 return len;
2174 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002175
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002176 if (o->ob_type->tp_as_sequence && o->ob_type->tp_as_sequence->sq_length) {
2177 type_error("%.200s is not a mapping", o);
2178 return -1;
2179 }
2180 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 type_error("object of type '%.200s' has no len()", o);
2182 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002183}
2184
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002185#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002186Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002187PyMapping_Length(PyObject *o)
2188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002190}
2191#define PyMapping_Length PyMapping_Size
2192
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002193PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002194PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002197
Victor Stinner71aea8e2016-08-19 16:59:55 +02002198 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002200 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 okey = PyUnicode_FromString(key);
2203 if (okey == NULL)
2204 return NULL;
2205 r = PyObject_GetItem(o, okey);
2206 Py_DECREF(okey);
2207 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002208}
2209
2210int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002211PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyObject *okey;
2214 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (key == NULL) {
2217 null_error();
2218 return -1;
2219 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 okey = PyUnicode_FromString(key);
2222 if (okey == NULL)
2223 return -1;
2224 r = PyObject_SetItem(o, okey, value);
2225 Py_DECREF(okey);
2226 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002227}
2228
2229int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002230PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 v = PyMapping_GetItemString(o, key);
2235 if (v) {
2236 Py_DECREF(v);
2237 return 1;
2238 }
2239 PyErr_Clear();
2240 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002241}
2242
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002243int
Fred Drake79912472000-07-09 04:06:11 +00002244PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 v = PyObject_GetItem(o, key);
2249 if (v) {
2250 Py_DECREF(v);
2251 return 1;
2252 }
2253 PyErr_Clear();
2254 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002255}
2256
Oren Milman0ccc0f62017-10-08 11:17:46 +03002257/* This function is quite similar to PySequence_Fast(), but specialized to be
2258 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2259 */
2260static PyObject *
2261method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2262{
2263 PyObject *it, *result, *meth_output;
2264
2265 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002266 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002267 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2268 return meth_output;
2269 }
2270 it = PyObject_GetIter(meth_output);
2271 if (it == NULL) {
2272 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2273 PyErr_Format(PyExc_TypeError,
2274 "%.200s.%U() returned a non-iterable (type %.200s)",
2275 Py_TYPE(o)->tp_name,
2276 meth_id->object,
2277 Py_TYPE(meth_output)->tp_name);
2278 }
2279 Py_DECREF(meth_output);
2280 return NULL;
2281 }
2282 Py_DECREF(meth_output);
2283 result = PySequence_List(it);
2284 Py_DECREF(it);
2285 return result;
2286}
2287
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002288PyObject *
2289PyMapping_Keys(PyObject *o)
2290{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002291 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002292
Oren Milman0ccc0f62017-10-08 11:17:46 +03002293 if (o == NULL) {
2294 return null_error();
2295 }
2296 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002298 }
2299 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002300}
2301
2302PyObject *
2303PyMapping_Items(PyObject *o)
2304{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002305 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002306
Oren Milman0ccc0f62017-10-08 11:17:46 +03002307 if (o == NULL) {
2308 return null_error();
2309 }
2310 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002312 }
2313 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002314}
2315
2316PyObject *
2317PyMapping_Values(PyObject *o)
2318{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002319 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002320
Oren Milman0ccc0f62017-10-08 11:17:46 +03002321 if (o == NULL) {
2322 return null_error();
2323 }
2324 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002326 }
2327 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002328}
2329
Guido van Rossum823649d2001-03-21 18:40:58 +00002330/* isinstance(), issubclass() */
2331
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002332/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002333 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002334 * 1. getattr(cls, '__bases__') could raise an AttributeError
2335 * 2. getattr(cls, '__bases__') could raise some other exception
2336 * 3. getattr(cls, '__bases__') could return a tuple
2337 * 4. getattr(cls, '__bases__') could return something other than a tuple
2338 *
2339 * Only state #3 is a non-error state and only it returns a non-NULL object
2340 * (it returns the retrieved tuple).
2341 *
2342 * Any raised AttributeErrors are masked by clearing the exception and
2343 * returning NULL. If an object other than a tuple comes out of __bases__,
2344 * then again, the return value is NULL. So yes, these two situations
2345 * produce exactly the same results: NULL is returned and no error is set.
2346 *
2347 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002349 * exception to be propagated along.
2350 *
2351 * Callers are expected to test for PyErr_Occurred() when the return value
2352 * is NULL to decide whether a valid exception should be propagated or not.
2353 * When there's no exception to propagate, it's customary for the caller to
2354 * set a TypeError.
2355 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002356static PyObject *
2357abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002358{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002359 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 Py_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002363 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 Py_END_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002365 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_DECREF(bases);
2367 return NULL;
2368 }
2369 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002370}
2371
2372
2373static int
2374abstract_issubclass(PyObject *derived, PyObject *cls)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 PyObject *bases = NULL;
2377 Py_ssize_t i, n;
2378 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 while (1) {
2381 if (derived == cls)
2382 return 1;
2383 bases = abstract_get_bases(derived);
2384 if (bases == NULL) {
2385 if (PyErr_Occurred())
2386 return -1;
2387 return 0;
2388 }
2389 n = PyTuple_GET_SIZE(bases);
2390 if (n == 0) {
2391 Py_DECREF(bases);
2392 return 0;
2393 }
2394 /* Avoid recursivity in the single inheritance case */
2395 if (n == 1) {
2396 derived = PyTuple_GET_ITEM(bases, 0);
2397 Py_DECREF(bases);
2398 continue;
2399 }
2400 for (i = 0; i < n; i++) {
2401 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2402 if (r != 0)
2403 break;
2404 }
2405 Py_DECREF(bases);
2406 return r;
2407 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002408}
2409
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002410static int
2411check_class(PyObject *cls, const char *error)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 PyObject *bases = abstract_get_bases(cls);
2414 if (bases == NULL) {
2415 /* Do not mask errors. */
2416 if (!PyErr_Occurred())
2417 PyErr_SetString(PyExc_TypeError, error);
2418 return 0;
2419 }
2420 Py_DECREF(bases);
2421 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002422}
2423
Brett Cannon4f653312004-03-20 22:52:14 +00002424static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002425recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002428 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002429 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 if (PyType_Check(cls)) {
2432 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2433 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002434 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2435 if (icls != NULL) {
2436 if (icls != (PyObject *)(inst->ob_type) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002438 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002440 }
2441 else {
2442 retval = 0;
2443 }
2444 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 }
2446 }
2447 }
2448 else {
2449 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002450 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002452 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2453 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 retval = abstract_issubclass(icls, cls);
2455 Py_DECREF(icls);
2456 }
2457 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002460}
2461
2462int
Brett Cannon4f653312004-03-20 22:52:14 +00002463PyObject_IsInstance(PyObject *inst, PyObject *cls)
2464{
Benjamin Petersonce798522012-01-22 11:24:29 -05002465 _Py_IDENTIFIER(__instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 PyObject *checker;
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Quick test for an exact match */
2469 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2470 return 1;
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002471
Georg Brandl72b8a802014-10-03 09:26:37 +02002472 /* We know what type's __instancecheck__ does. */
2473 if (PyType_CheckExact(cls)) {
2474 return recursive_isinstance(inst, cls);
2475 }
2476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (PyTuple_Check(cls)) {
2478 Py_ssize_t i;
2479 Py_ssize_t n;
2480 int r = 0;
Antoine Pitrouec569b72008-08-26 22:40:48 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2483 return -1;
2484 n = PyTuple_GET_SIZE(cls);
2485 for (i = 0; i < n; ++i) {
2486 PyObject *item = PyTuple_GET_ITEM(cls, i);
2487 r = PyObject_IsInstance(inst, item);
2488 if (r != 0)
2489 /* either found it, or got an error */
2490 break;
2491 }
2492 Py_LeaveRecursiveCall();
2493 return r;
2494 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002495
Benjamin Petersonce798522012-01-22 11:24:29 -05002496 checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 if (checker != NULL) {
2498 PyObject *res;
2499 int ok = -1;
2500 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2501 Py_DECREF(checker);
2502 return ok;
2503 }
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002504 res = _PyObject_CallOneArg(checker, inst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 Py_LeaveRecursiveCall();
2506 Py_DECREF(checker);
2507 if (res != NULL) {
2508 ok = PyObject_IsTrue(res);
2509 Py_DECREF(res);
2510 }
2511 return ok;
2512 }
2513 else if (PyErr_Occurred())
2514 return -1;
Georg Brandl72b8a802014-10-03 09:26:37 +02002515 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002517}
2518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002520recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (PyType_Check(cls) && PyType_Check(derived)) {
2523 /* Fast path (non-recursive) */
2524 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2525 }
2526 if (!check_class(derived,
2527 "issubclass() arg 1 must be a class"))
2528 return -1;
2529 if (!check_class(cls,
2530 "issubclass() arg 2 must be a class"
2531 " or tuple of classes"))
2532 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002535}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002536
Brett Cannon4f653312004-03-20 22:52:14 +00002537int
2538PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2539{
Benjamin Petersonce798522012-01-22 11:24:29 -05002540 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002542
Georg Brandl72b8a802014-10-03 09:26:37 +02002543 /* We know what type's __subclasscheck__ does. */
2544 if (PyType_CheckExact(cls)) {
2545 /* Quick test for an exact match */
2546 if (derived == cls)
2547 return 1;
2548 return recursive_issubclass(derived, cls);
2549 }
2550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (PyTuple_Check(cls)) {
2552 Py_ssize_t i;
2553 Py_ssize_t n;
2554 int r = 0;
Antoine Pitrouec569b72008-08-26 22:40:48 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2557 return -1;
2558 n = PyTuple_GET_SIZE(cls);
2559 for (i = 0; i < n; ++i) {
2560 PyObject *item = PyTuple_GET_ITEM(cls, i);
2561 r = PyObject_IsSubclass(derived, item);
2562 if (r != 0)
2563 /* either found it, or got an error */
2564 break;
2565 }
2566 Py_LeaveRecursiveCall();
2567 return r;
2568 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002569
Benjamin Petersonce798522012-01-22 11:24:29 -05002570 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (checker != NULL) {
2572 PyObject *res;
2573 int ok = -1;
2574 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
2575 Py_DECREF(checker);
2576 return ok;
2577 }
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002578 res = _PyObject_CallOneArg(checker, derived);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 Py_LeaveRecursiveCall();
2580 Py_DECREF(checker);
2581 if (res != NULL) {
2582 ok = PyObject_IsTrue(res);
2583 Py_DECREF(res);
2584 }
2585 return ok;
2586 }
2587 else if (PyErr_Occurred())
2588 return -1;
Georg Brandl72b8a802014-10-03 09:26:37 +02002589 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002591}
2592
2593int
2594_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 return recursive_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002597}
2598
2599int
2600_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002603}
2604
2605
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002606PyObject *
2607PyObject_GetIter(PyObject *o)
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 PyTypeObject *t = o->ob_type;
Victor Stinner14e6d092016-12-09 17:08:59 +01002610 getiterfunc f;
2611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 f = t->tp_iter;
2613 if (f == NULL) {
2614 if (PySequence_Check(o))
2615 return PySeqIter_New(o);
2616 return type_error("'%.200s' object is not iterable", o);
2617 }
2618 else {
2619 PyObject *res = (*f)(o);
2620 if (res != NULL && !PyIter_Check(res)) {
2621 PyErr_Format(PyExc_TypeError,
2622 "iter() returned non-iterator "
2623 "of type '%.100s'",
2624 res->ob_type->tp_name);
2625 Py_DECREF(res);
2626 res = NULL;
2627 }
2628 return res;
2629 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002630}
2631
Christian Tismerea62ce72018-06-09 20:32:25 +02002632#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002633
Christian Tismerea62ce72018-06-09 20:32:25 +02002634int PyIter_Check(PyObject *obj)
2635{
2636 return obj->ob_type->tp_iternext != NULL &&
2637 obj->ob_type->tp_iternext != &_PyObject_NextNotImplemented;
2638}
2639
Tim Petersf4848da2001-05-05 00:14:56 +00002640/* Return next item.
2641 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2642 * If the iteration terminates normally, return NULL and clear the
2643 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2644 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002646 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002647PyObject *
2648PyIter_Next(PyObject *iter)
2649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 PyObject *result;
2651 result = (*iter->ob_type->tp_iternext)(iter);
2652 if (result == NULL &&
2653 PyErr_Occurred() &&
2654 PyErr_ExceptionMatches(PyExc_StopIteration))
2655 PyErr_Clear();
2656 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002657}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002658
2659
2660/*
2661 * Flatten a sequence of bytes() objects into a C array of
2662 * NULL terminated string pointers with a NULL char* terminating the array.
2663 * (ie: an argv or env list)
2664 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002665 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2666 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002667 */
2668char *const *
2669_PySequence_BytesToCharpArray(PyObject* self)
2670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 char **array;
2672 Py_ssize_t i, argc;
2673 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002674 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 argc = PySequence_Size(self);
2677 if (argc == -1)
2678 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002679
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002680 assert(argc >= 0);
2681
2682 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2683 PyErr_NoMemory();
2684 return NULL;
2685 }
2686
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002687 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 if (array == NULL) {
2689 PyErr_NoMemory();
2690 return NULL;
2691 }
2692 for (i = 0; i < argc; ++i) {
2693 char *data;
2694 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002695 if (item == NULL) {
2696 /* NULL terminate before freeing. */
2697 array[i] = NULL;
2698 goto fail;
2699 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002700 /* check for embedded null bytes */
2701 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 /* NULL terminate before freeing. */
2703 array[i] = NULL;
2704 goto fail;
2705 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002706 size = PyBytes_GET_SIZE(item) + 1;
2707 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 if (!array[i]) {
2709 PyErr_NoMemory();
2710 goto fail;
2711 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002712 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 Py_DECREF(item);
2714 }
2715 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002718
2719fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 Py_XDECREF(item);
2721 _Py_FreeCharPArray(array);
2722 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002723}
2724
2725
2726/* Free's a NULL terminated char** array of C strings. */
2727void
2728_Py_FreeCharPArray(char *const array[])
2729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 Py_ssize_t i;
2731 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002732 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002734 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002735}