blob: f9e5009f78a0862725d81a5260cb26c84189e176 [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"
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +00004#include <ctype.h>
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00005#include "structmember.h" /* we need the offsetof() macro from there */
Tim Peters64b5ce32001-09-10 20:52:51 +00006#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00007
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000010/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000011
12static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000015 PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
16 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000017}
18
Guido van Rossum052b7e11996-11-11 15:08:19 +000019static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000020null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 if (!PyErr_Occurred())
23 PyErr_SetString(PyExc_SystemError,
24 "null argument to internal routine");
25 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000026}
27
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000028/* Operations on any object */
29
Guido van Rossume15dee51995-07-18 14:12:02 +000030PyObject *
Fred Drake79912472000-07-09 04:06:11 +000031PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000034
Victor Stinner71aea8e2016-08-19 16:59:55 +020035 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020037 }
38
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 v = (PyObject *)o->ob_type;
40 Py_INCREF(v);
41 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000042}
43
Martin v. Löwis18e16552006-02-15 17:27:45 +000044Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000045PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 if (o == NULL) {
50 null_error();
51 return -1;
52 }
Guido van Rossume15dee51995-07-18 14:12:02 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 m = o->ob_type->tp_as_sequence;
55 if (m && m->sq_length)
56 return m->sq_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000059}
60
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000061#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000062Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000063PyObject_Length(PyObject *o)
64{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000066}
67#define PyObject_Length PyObject_Size
68
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020069int
70_PyObject_HasLen(PyObject *o) {
71 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
72 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
73}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000074
Christian Heimes255f53b2007-12-08 15:33:56 +000075/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020076 or o.__length_hint__(). If those methods aren't found the defaultvalue is
77 returned. If one of the calls fails with an exception other than TypeError
78 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000079*/
80
81Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020082PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000083{
Christian Heimesb70e8a12012-10-06 17:16:39 +020084 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020085 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050086 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030087 if (_PyObject_HasLen(o)) {
88 res = PyObject_Length(o);
89 if (res < 0 && PyErr_Occurred()) {
90 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
91 return -1;
92 }
93 PyErr_Clear();
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020094 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +030095 else {
96 return res;
97 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 }
Christian Heimes6314d162012-10-06 17:13:29 +020099 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200100 if (hint == NULL) {
101 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 return defaultvalue;
105 }
Christian Heimesb70e8a12012-10-06 17:16:39 +0200106 result = PyObject_CallFunctionObjArgs(hint, NULL);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200107 Py_DECREF(hint);
108 if (result == NULL) {
109 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
110 PyErr_Clear();
111 return defaultvalue;
112 }
113 return -1;
114 }
115 else if (result == Py_NotImplemented) {
116 Py_DECREF(result);
117 return defaultvalue;
118 }
119 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200120 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200121 Py_TYPE(result)->tp_name);
122 Py_DECREF(result);
123 return -1;
124 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200125 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200126 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200127 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200128 return -1;
129 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200130 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200131 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
132 return -1;
133 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200134 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000135}
136
Guido van Rossume15dee51995-07-18 14:12:02 +0000137PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000138PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000141
Victor Stinner71aea8e2016-08-19 16:59:55 +0200142 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200144 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 m = o->ob_type->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100147 if (m && m->mp_subscript) {
148 PyObject *item = m->mp_subscript(o, key);
149 assert((item != NULL) ^ (PyErr_Occurred() != NULL));
150 return item;
151 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (o->ob_type->tp_as_sequence) {
154 if (PyIndex_Check(key)) {
155 Py_ssize_t key_value;
156 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
157 if (key_value == -1 && PyErr_Occurred())
158 return NULL;
159 return PySequence_GetItem(o, key_value);
160 }
161 else if (o->ob_type->tp_as_sequence->sq_item)
162 return type_error("sequence index must "
163 "be integer, not '%.200s'", key);
164 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000167}
168
169int
Fred Drake79912472000-07-09 04:06:11 +0000170PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (o == NULL || key == NULL || value == NULL) {
175 null_error();
176 return -1;
177 }
178 m = o->ob_type->tp_as_mapping;
179 if (m && m->mp_ass_subscript)
180 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (o->ob_type->tp_as_sequence) {
183 if (PyIndex_Check(key)) {
184 Py_ssize_t key_value;
185 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
186 if (key_value == -1 && PyErr_Occurred())
187 return -1;
188 return PySequence_SetItem(o, key_value, value);
189 }
190 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
191 type_error("sequence index must be "
192 "integer, not '%.200s'", key);
193 return -1;
194 }
195 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 type_error("'%.200s' object does not support item assignment", o);
198 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000199}
200
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000201int
Fred Drake79912472000-07-09 04:06:11 +0000202PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (o == NULL || key == NULL) {
207 null_error();
208 return -1;
209 }
210 m = o->ob_type->tp_as_mapping;
211 if (m && m->mp_ass_subscript)
212 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (o->ob_type->tp_as_sequence) {
215 if (PyIndex_Check(key)) {
216 Py_ssize_t key_value;
217 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
218 if (key_value == -1 && PyErr_Occurred())
219 return -1;
220 return PySequence_DelItem(o, key_value);
221 }
222 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
223 type_error("sequence index must be "
224 "integer, not '%.200s'", key);
225 return -1;
226 }
227 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 type_error("'%.200s' object does not support item deletion", o);
230 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000231}
232
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000233int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300234PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyObject *okey;
237 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (o == NULL || key == NULL) {
240 null_error();
241 return -1;
242 }
243 okey = PyUnicode_FromString(key);
244 if (okey == NULL)
245 return -1;
246 ret = PyObject_DelItem(o, okey);
247 Py_DECREF(okey);
248 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000249}
250
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000251/* We release the buffer right after use of this function which could
Guido van Rossum98297ee2007-11-06 21:34:58 +0000252 cause issues later on. Don't use these functions in new code.
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000253 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000254int
255PyObject_AsCharBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 const char **buffer,
257 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000258{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200259 return PyObject_AsReadBuffer(obj, (const void **)buffer, buffer_len);
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000260}
Guido van Rossum4c08d552000-03-10 22:55:18 +0000261
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000262int
263PyObject_CheckReadBuffer(PyObject *obj)
264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
266 Py_buffer view;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 if (pb == NULL ||
269 pb->bf_getbuffer == NULL)
270 return 0;
271 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
272 PyErr_Clear();
273 return 0;
274 }
275 PyBuffer_Release(&view);
276 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000277}
278
279int PyObject_AsReadBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 const void **buffer,
281 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
286 null_error();
287 return -1;
288 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200289 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return -1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 *buffer = view.buf;
293 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200294 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000296}
297
298int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 void **buffer,
300 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyBufferProcs *pb;
303 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
306 null_error();
307 return -1;
308 }
309 pb = obj->ob_type->tp_as_buffer;
310 if (pb == NULL ||
311 pb->bf_getbuffer == NULL ||
312 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
313 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400314 "expected a writable bytes-like object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return -1;
316 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 *buffer = view.buf;
319 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200320 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000322}
323
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000324/* Buffer C-API for Python 3.0 */
325
326int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000327PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000328{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200329 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
330
331 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400333 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 Py_TYPE(obj)->tp_name);
335 return -1;
336 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200337 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000338}
339
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000340static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100341_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 Py_ssize_t sd, dim;
344 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000345
Stefan Krah363af442015-02-01 14:53:54 +0100346 /* 1) len = product(shape) * itemsize
347 2) itemsize > 0
348 3) len = 0 <==> exists i: shape[i] = 0 */
349 if (view->len == 0) return 1;
350 if (view->strides == NULL) { /* C-contiguous by definition */
351 /* Trivially F-contiguous */
352 if (view->ndim <= 1) return 1;
353
354 /* ndim > 1 implies shape != NULL */
355 assert(view->shape != NULL);
356
357 /* Effectively 1-d */
358 sd = 0;
359 for (i=0; i<view->ndim; i++) {
360 if (view->shape[i] > 1) sd += 1;
361 }
362 return sd <= 1;
363 }
364
365 /* strides != NULL implies both of these */
366 assert(view->ndim > 0);
367 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 for (i=0; i<view->ndim; i++) {
371 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100372 if (dim > 1 && view->strides[i] != sd) {
373 return 0;
374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 sd *= dim;
376 }
377 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000378}
379
380static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100381_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_ssize_t sd, dim;
384 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000385
Stefan Krah363af442015-02-01 14:53:54 +0100386 /* 1) len = product(shape) * itemsize
387 2) itemsize > 0
388 3) len = 0 <==> exists i: shape[i] = 0 */
389 if (view->len == 0) return 1;
390 if (view->strides == NULL) return 1; /* C-contiguous by definition */
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=view->ndim-1; i>=0; 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
407int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100408PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000409{
410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000412
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100413 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100415 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100417 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 return (_IsCContiguous(view) || _IsFortranContiguous(view));
419 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000420}
421
422
Guido van Rossum98297ee2007-11-06 21:34:58 +0000423void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000424PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 char* pointer;
427 int i;
428 pointer = (char *)view->buf;
429 for (i = 0; i < view->ndim; i++) {
430 pointer += view->strides[i]*indices[i];
431 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
432 pointer = *((char**)pointer) + view->suboffsets[i];
433 }
434 }
435 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000436}
437
438
Guido van Rossum98297ee2007-11-06 21:34:58 +0000439void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000440_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 +0000441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 for (k=0; k<nd; k++) {
445 if (index[k] < shape[k]-1) {
446 index[k]++;
447 break;
448 }
449 else {
450 index[k] = 0;
451 }
452 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000453}
454
Guido van Rossum98297ee2007-11-06 21:34:58 +0000455void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000456_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 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 for (k=nd-1; k>=0; k--) {
461 if (index[k] < shape[k]-1) {
462 index[k]++;
463 break;
464 }
465 else {
466 index[k] = 0;
467 }
468 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000469}
470
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000471int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000472PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000475 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_ssize_t *indices, elements;
477 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (len > view->len) {
480 len = view->len;
481 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (PyBuffer_IsContiguous(view, fort)) {
484 /* simplest copy is all that is needed */
485 memcpy(view->buf, buf, len);
486 return 0;
487 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000490
Stefan Krah7213fcc2015-02-01 16:19:23 +0100491 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
493 if (indices == NULL) {
494 PyErr_NoMemory();
495 return -1;
496 }
497 for (k=0; k<view->ndim;k++) {
498 indices[k] = 0;
499 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000502 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
504 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000505 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 }
507 src = buf;
508 /* XXX : This is not going to be the fastest code in the world
509 several optimizations are possible.
510 */
511 elements = len / view->itemsize;
512 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 ptr = PyBuffer_GetPointer(view, indices);
514 memcpy(ptr, src, view->itemsize);
515 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100516 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyMem_Free(indices);
520 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000521}
522
Guido van Rossum98297ee2007-11-06 21:34:58 +0000523int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 Py_buffer view_dest, view_src;
526 int k;
527 Py_ssize_t *indices, elements;
528 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (!PyObject_CheckBuffer(dest) ||
531 !PyObject_CheckBuffer(src)) {
532 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400533 "both destination and source must be "\
534 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return -1;
536 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
539 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
540 PyBuffer_Release(&view_dest);
541 return -1;
542 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (view_dest.len < view_src.len) {
545 PyErr_SetString(PyExc_BufferError,
546 "destination is too small to receive data from source");
547 PyBuffer_Release(&view_dest);
548 PyBuffer_Release(&view_src);
549 return -1;
550 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
553 PyBuffer_IsContiguous(&view_src, 'C')) ||
554 (PyBuffer_IsContiguous(&view_dest, 'F') &&
555 PyBuffer_IsContiguous(&view_src, 'F'))) {
556 /* simplest copy is all that is needed */
557 memcpy(view_dest.buf, view_src.buf, view_src.len);
558 PyBuffer_Release(&view_dest);
559 PyBuffer_Release(&view_src);
560 return 0;
561 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* XXX(nnorwitz): need to check for overflow! */
566 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
567 if (indices == NULL) {
568 PyErr_NoMemory();
569 PyBuffer_Release(&view_dest);
570 PyBuffer_Release(&view_src);
571 return -1;
572 }
573 for (k=0; k<view_src.ndim;k++) {
574 indices[k] = 0;
575 }
576 elements = 1;
577 for (k=0; k<view_src.ndim; k++) {
578 /* XXX(nnorwitz): can this overflow? */
579 elements *= view_src.shape[k];
580 }
581 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000582 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 dptr = PyBuffer_GetPointer(&view_dest, indices);
584 sptr = PyBuffer_GetPointer(&view_src, indices);
585 memcpy(dptr, sptr, view_src.itemsize);
586 }
587 PyMem_Free(indices);
588 PyBuffer_Release(&view_dest);
589 PyBuffer_Release(&view_src);
590 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000591}
592
593void
594PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 Py_ssize_t *strides, int itemsize,
596 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 int k;
599 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 sd = itemsize;
602 if (fort == 'F') {
603 for (k=0; k<nd; k++) {
604 strides[k] = sd;
605 sd *= shape[k];
606 }
607 }
608 else {
609 for (k=nd-1; k>=0; k--) {
610 strides[k] = sd;
611 sd *= shape[k];
612 }
613 }
614 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000615}
616
617int
Martin v. Löwis423be952008-08-13 15:53:07 +0000618PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100619 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000620{
Stefan Krah5178d912015-02-03 16:57:21 +0100621 if (view == NULL) {
622 PyErr_SetString(PyExc_BufferError,
623 "PyBuffer_FillInfo: view==NULL argument is obsolete");
624 return -1;
625 }
626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
628 (readonly == 1)) {
629 PyErr_SetString(PyExc_BufferError,
630 "Object is not writable.");
631 return -1;
632 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 view->obj = obj;
635 if (obj)
636 Py_INCREF(obj);
637 view->buf = buf;
638 view->len = len;
639 view->readonly = readonly;
640 view->itemsize = 1;
641 view->format = NULL;
642 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
643 view->format = "B";
644 view->ndim = 1;
645 view->shape = NULL;
646 if ((flags & PyBUF_ND) == PyBUF_ND)
647 view->shape = &(view->len);
648 view->strides = NULL;
649 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
650 view->strides = &(view->itemsize);
651 view->suboffsets = NULL;
652 view->internal = NULL;
653 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000654}
655
Martin v. Löwis423be952008-08-13 15:53:07 +0000656void
657PyBuffer_Release(Py_buffer *view)
658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200660 PyBufferProcs *pb;
661 if (obj == NULL)
662 return;
663 pb = Py_TYPE(obj)->tp_as_buffer;
664 if (pb && pb->bf_releasebuffer)
665 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200667 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000668}
669
Eric Smith8fd3eba2008-02-17 19:48:00 +0000670PyObject *
671PyObject_Format(PyObject *obj, PyObject *format_spec)
672{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000673 PyObject *meth;
674 PyObject *empty = NULL;
675 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500676 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000677
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300678 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
679 PyErr_Format(PyExc_SystemError,
680 "Format specifier must be a string, not %.200s",
681 Py_TYPE(format_spec)->tp_name);
682 return NULL;
683 }
684
685 /* Fast path for common types. */
686 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
687 if (PyUnicode_CheckExact(obj)) {
688 Py_INCREF(obj);
689 return obj;
690 }
691 if (PyLong_CheckExact(obj)) {
692 return PyObject_Str(obj);
693 }
694 }
695
Eric Smith8fd3eba2008-02-17 19:48:00 +0000696 /* If no format_spec is provided, use an empty string */
697 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100698 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000699 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000700 }
701
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300702 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500703 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000704 if (meth == NULL) {
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000705 if (!PyErr_Occurred())
706 PyErr_Format(PyExc_TypeError,
707 "Type %.100s doesn't define __format__",
708 Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000710 }
711
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000712 /* And call it. */
713 result = PyObject_CallFunctionObjArgs(meth, format_spec, NULL);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000714 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000715
716 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800717 PyErr_Format(PyExc_TypeError,
718 "__format__ must return a str, not %.200s",
719 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000720 Py_DECREF(result);
721 result = NULL;
722 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000723 }
724
725done:
726 Py_XDECREF(empty);
727 return result;
728}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000729/* Operations on numbers */
730
731int
Fred Drake79912472000-07-09 04:06:11 +0000732PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return o && o->ob_type->tp_as_number &&
735 (o->ob_type->tp_as_number->nb_int ||
736 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000737}
738
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000739/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000740
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000741#define NB_SLOT(x) offsetof(PyNumberMethods, x)
742#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000744#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000746
747/*
748 Calling scheme used for binary operations:
749
Neal Norwitz4886cc32006-08-21 17:06:07 +0000750 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000752
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000753 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
754 v->ob_type
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000755 */
756
757static PyObject *
758binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *x;
761 binaryfunc slotv = NULL;
762 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (v->ob_type->tp_as_number != NULL)
765 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
766 if (w->ob_type != v->ob_type &&
767 w->ob_type->tp_as_number != NULL) {
768 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
769 if (slotw == slotv)
770 slotw = NULL;
771 }
772 if (slotv) {
773 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
774 x = slotw(v, w);
775 if (x != Py_NotImplemented)
776 return x;
777 Py_DECREF(x); /* can't do it */
778 slotw = NULL;
779 }
780 x = slotv(v, w);
781 if (x != Py_NotImplemented)
782 return x;
783 Py_DECREF(x); /* can't do it */
784 }
785 if (slotw) {
786 x = slotw(v, w);
787 if (x != Py_NotImplemented)
788 return x;
789 Py_DECREF(x); /* can't do it */
790 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500791 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000792}
Guido van Rossum77660912002-04-16 16:32:50 +0000793
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000794static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000795binop_type_error(PyObject *v, PyObject *w, const char *op_name)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyErr_Format(PyExc_TypeError,
798 "unsupported operand type(s) for %.100s: "
799 "'%.100s' and '%.100s'",
800 op_name,
801 v->ob_type->tp_name,
802 w->ob_type->tp_name);
803 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000804}
805
806static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000807binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyObject *result = binary_op1(v, w, op_slot);
810 if (result == Py_NotImplemented) {
811 Py_DECREF(result);
812 return binop_type_error(v, w, op_name);
813 }
814 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000815}
816
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000817
818/*
819 Calling scheme used for ternary operations:
820
Neal Norwitz4886cc32006-08-21 17:06:07 +0000821 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000823 */
824
825static PyObject *
826ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *w,
828 PyObject *z,
829 const int op_slot,
830 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 PyNumberMethods *mv, *mw, *mz;
833 PyObject *x = NULL;
834 ternaryfunc slotv = NULL;
835 ternaryfunc slotw = NULL;
836 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 mv = v->ob_type->tp_as_number;
839 mw = w->ob_type->tp_as_number;
840 if (mv != NULL)
841 slotv = NB_TERNOP(mv, op_slot);
842 if (w->ob_type != v->ob_type &&
843 mw != NULL) {
844 slotw = NB_TERNOP(mw, op_slot);
845 if (slotw == slotv)
846 slotw = NULL;
847 }
848 if (slotv) {
849 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
850 x = slotw(v, w, z);
851 if (x != Py_NotImplemented)
852 return x;
853 Py_DECREF(x); /* can't do it */
854 slotw = NULL;
855 }
856 x = slotv(v, w, z);
857 if (x != Py_NotImplemented)
858 return x;
859 Py_DECREF(x); /* can't do it */
860 }
861 if (slotw) {
862 x = slotw(v, w, z);
863 if (x != Py_NotImplemented)
864 return x;
865 Py_DECREF(x); /* can't do it */
866 }
867 mz = z->ob_type->tp_as_number;
868 if (mz != NULL) {
869 slotz = NB_TERNOP(mz, op_slot);
870 if (slotz == slotv || slotz == slotw)
871 slotz = NULL;
872 if (slotz) {
873 x = slotz(v, w, z);
874 if (x != Py_NotImplemented)
875 return x;
876 Py_DECREF(x); /* can't do it */
877 }
878 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 if (z == Py_None)
881 PyErr_Format(
882 PyExc_TypeError,
883 "unsupported operand type(s) for ** or pow(): "
884 "'%.100s' and '%.100s'",
885 v->ob_type->tp_name,
886 w->ob_type->tp_name);
887 else
888 PyErr_Format(
889 PyExc_TypeError,
890 "unsupported operand type(s) for pow(): "
891 "'%.100s', '%.100s', '%.100s'",
892 v->ob_type->tp_name,
893 w->ob_type->tp_name,
894 z->ob_type->tp_name);
895 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +0000896}
897
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000898#define BINARY_FUNC(func, op, op_name) \
899 PyObject * \
900 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000902 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000903
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000904BINARY_FUNC(PyNumber_Or, nb_or, "|")
905BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
906BINARY_FUNC(PyNumber_And, nb_and, "&")
907BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
908BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
909BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000910BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +0000911
912PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000913PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
916 if (result == Py_NotImplemented) {
917 PySequenceMethods *m = v->ob_type->tp_as_sequence;
918 Py_DECREF(result);
919 if (m && m->sq_concat) {
920 return (*m->sq_concat)(v, w);
921 }
922 result = binop_type_error(v, w, "+");
923 }
924 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000925}
926
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000927static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000928sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 Py_ssize_t count;
931 if (PyIndex_Check(n)) {
932 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
933 if (count == -1 && PyErr_Occurred())
934 return NULL;
935 }
936 else {
937 return type_error("can't multiply sequence by "
938 "non-int of type '%.200s'", n);
939 }
940 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000941}
942
943PyObject *
944PyNumber_Multiply(PyObject *v, PyObject *w)
945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
947 if (result == Py_NotImplemented) {
948 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
949 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
950 Py_DECREF(result);
951 if (mv && mv->sq_repeat) {
952 return sequence_repeat(mv->sq_repeat, v, w);
953 }
954 else if (mw && mw->sq_repeat) {
955 return sequence_repeat(mw->sq_repeat, w, v);
956 }
957 result = binop_type_error(v, w, "*");
958 }
959 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000960}
961
Guido van Rossume15dee51995-07-18 14:12:02 +0000962PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -0400963PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
964{
965 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
966}
967
968PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +0000969PyNumber_FloorDivide(PyObject *v, PyObject *w)
970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +0000972}
973
974PyObject *
975PyNumber_TrueDivide(PyObject *v, PyObject *w)
976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +0000978}
979
980PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000981PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +0000982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +0000984}
985
986PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000987PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +0000990}
991
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000992/* Binary in-place operators */
993
994/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000995 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000996
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000997 - If the left hand object has the appropriate struct members, and
998 they are filled, call the appropriate function and return the
999 result. No coercion is done on the arguments; the left-hand object
1000 is the one the operation is performed on, and it's up to the
1001 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001002
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001003 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001004 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001005
1006 */
1007
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001008static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001009binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyNumberMethods *mv = v->ob_type->tp_as_number;
1012 if (mv != NULL) {
1013 binaryfunc slot = NB_BINOP(mv, iop_slot);
1014 if (slot) {
1015 PyObject *x = (slot)(v, w);
1016 if (x != Py_NotImplemented) {
1017 return x;
1018 }
1019 Py_DECREF(x);
1020 }
1021 }
1022 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001023}
1024
1025static PyObject *
1026binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1030 if (result == Py_NotImplemented) {
1031 Py_DECREF(result);
1032 return binop_type_error(v, w, op_name);
1033 }
1034 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001035}
1036
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001037#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject * \
1039 func(PyObject *v, PyObject *w) { \
1040 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1041 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001042
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001043INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1044INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1045INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1046INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1047INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1048INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001049INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001050
1051PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001052PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1055 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001056}
1057
1058PyObject *
1059PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1062 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001063}
1064
1065PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001066PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1069 NB_SLOT(nb_add));
1070 if (result == Py_NotImplemented) {
1071 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1072 Py_DECREF(result);
1073 if (m != NULL) {
1074 binaryfunc f = NULL;
1075 f = m->sq_inplace_concat;
1076 if (f == NULL)
1077 f = m->sq_concat;
1078 if (f != NULL)
1079 return (*f)(v, w);
1080 }
1081 result = binop_type_error(v, w, "+=");
1082 }
1083 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001084}
1085
1086PyObject *
1087PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1090 NB_SLOT(nb_multiply));
1091 if (result == Py_NotImplemented) {
1092 ssizeargfunc f = NULL;
1093 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1094 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1095 Py_DECREF(result);
1096 if (mv != NULL) {
1097 f = mv->sq_inplace_repeat;
1098 if (f == NULL)
1099 f = mv->sq_repeat;
1100 if (f != NULL)
1101 return sequence_repeat(f, v, w);
1102 }
1103 else if (mw != NULL) {
1104 /* Note that the right hand operand should not be
1105 * mutated in this case so sq_inplace_repeat is not
1106 * used. */
1107 if (mw->sq_repeat)
1108 return sequence_repeat(mw->sq_repeat, w, v);
1109 }
1110 result = binop_type_error(v, w, "*=");
1111 }
1112 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001113}
1114
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001115PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001116PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1117{
1118 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1119 NB_SLOT(nb_matrix_multiply), "@=");
1120}
1121
1122PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001123PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1126 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001127}
1128
1129PyObject *
1130PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (v->ob_type->tp_as_number &&
1133 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1134 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1135 }
1136 else {
1137 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1138 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001139}
1140
1141
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001142/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001143
1144PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001145PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001148
Victor Stinner71aea8e2016-08-19 16:59:55 +02001149 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001151 }
1152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 m = o->ob_type->tp_as_number;
1154 if (m && m->nb_negative)
1155 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001158}
1159
1160PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001161PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001164
Victor Stinner71aea8e2016-08-19 16:59:55 +02001165 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001167 }
1168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 m = o->ob_type->tp_as_number;
1170 if (m && m->nb_positive)
1171 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001174}
1175
1176PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001177PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001180
Victor Stinner71aea8e2016-08-19 16:59:55 +02001181 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001183 }
1184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 m = o->ob_type->tp_as_number;
1186 if (m && m->nb_invert)
1187 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001190}
1191
1192PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001193PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001196
Victor Stinner71aea8e2016-08-19 16:59:55 +02001197 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001199 }
1200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 m = o->ob_type->tp_as_number;
1202 if (m && m->nb_absolute)
1203 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001206}
1207
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001208/* Return a Python int from the object item.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001209 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001210 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001211*/
1212PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001213PyNumber_Index(PyObject *item)
1214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001216 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001218 }
1219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (PyLong_Check(item)) {
1221 Py_INCREF(item);
1222 return item;
1223 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001224 if (!PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyErr_Format(PyExc_TypeError,
1226 "'%.200s' object cannot be interpreted "
1227 "as an integer", item->ob_type->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001228 return NULL;
1229 }
1230 result = item->ob_type->tp_as_number->nb_index(item);
1231 if (!result || PyLong_CheckExact(result))
1232 return result;
1233 if (!PyLong_Check(result)) {
1234 PyErr_Format(PyExc_TypeError,
1235 "__index__ returned non-int (type %.200s)",
1236 result->ob_type->tp_name);
1237 Py_DECREF(result);
1238 return NULL;
1239 }
1240 /* Issue #17576: warn if 'result' not of exact type int. */
1241 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1242 "__index__ returned non-int (type %.200s). "
1243 "The ability to return an instance of a strict subclass of int "
1244 "is deprecated, and may be removed in a future version of Python.",
1245 result->ob_type->tp_name)) {
1246 Py_DECREF(result);
1247 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 }
1249 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001250}
1251
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001252/* Return an error on Overflow only if err is not NULL*/
1253
1254Py_ssize_t
1255PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 Py_ssize_t result;
1258 PyObject *runerr;
1259 PyObject *value = PyNumber_Index(item);
1260 if (value == NULL)
1261 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* We're done if PyLong_AsSsize_t() returns without error. */
1264 result = PyLong_AsSsize_t(value);
1265 if (result != -1 || !(runerr = PyErr_Occurred()))
1266 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* Error handling code -- only manage OverflowError differently */
1269 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1270 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyErr_Clear();
1273 /* If no error-handling desired then the default clipping
1274 is sufficient.
1275 */
1276 if (!err) {
1277 assert(PyLong_Check(value));
1278 /* Whether or not it is less than or equal to
1279 zero is determined by the sign of ob_size
1280 */
1281 if (_PyLong_Sign(value) < 0)
1282 result = PY_SSIZE_T_MIN;
1283 else
1284 result = PY_SSIZE_T_MAX;
1285 }
1286 else {
1287 /* Otherwise replace the error with caller's error object. */
1288 PyErr_Format(err,
1289 "cannot fit '%.200s' into an index-sized integer",
1290 item->ob_type->tp_name);
1291 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001292
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001293 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 Py_DECREF(value);
1295 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001296}
1297
1298
Guido van Rossume15dee51995-07-18 14:12:02 +00001299PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001300PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001301{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001302 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001305 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001306 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001307
Victor Stinner71aea8e2016-08-19 16:59:55 +02001308 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001310 }
1311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (PyLong_CheckExact(o)) {
1313 Py_INCREF(o);
1314 return o;
1315 }
1316 m = o->ob_type->tp_as_number;
1317 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001318 result = (PyObject *)_PyLong_FromNbInt(o);
1319 if (result != NULL && !PyLong_CheckExact(result)) {
1320 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1321 }
1322 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001324 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (trunc_func) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001326 result = PyEval_CallObject(trunc_func, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001328 if (result == NULL || PyLong_CheckExact(result)) {
1329 return result;
1330 }
1331 if (PyLong_Check(result)) {
1332 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1333 return result;
1334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001336 but int() needs to return an int. */
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001337 m = result->ob_type->tp_as_number;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001338 if (m == NULL || m->nb_int == NULL) {
1339 PyErr_Format(
1340 PyExc_TypeError,
1341 "__trunc__ returned non-Integral (type %.200s)",
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001342 result->ob_type->tp_name);
1343 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001344 return NULL;
1345 }
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001346 Py_SETREF(result, (PyObject *)_PyLong_FromNbInt(result));
1347 if (result != NULL && !PyLong_CheckExact(result)) {
1348 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1349 }
1350 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001352 if (PyErr_Occurred())
1353 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001354
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001355 if (PyUnicode_Check(o))
1356 /* The below check is done in PyLong_FromUnicode(). */
1357 return PyLong_FromUnicodeObject(o, 10);
1358
Martin Pantereeb896c2015-11-07 02:32:21 +00001359 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001361 * doesn't do. In particular int('9\x005') must raise an
1362 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001364 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1365 PyBytes_GET_SIZE(o), 10);
1366
1367 if (PyByteArray_Check(o))
1368 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1369 PyByteArray_GET_SIZE(o), 10);
1370
1371 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001372 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001373
1374 /* Copy to NUL-terminated buffer. */
1375 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1376 if (bytes == NULL) {
1377 PyBuffer_Release(&view);
1378 return NULL;
1379 }
1380 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1381 PyBytes_GET_SIZE(bytes), 10);
1382 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001383 PyBuffer_Release(&view);
1384 return result;
1385 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001386
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001387 return type_error("int() argument must be a string, a bytes-like object "
1388 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001389}
1390
1391PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001392PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001395
Victor Stinner71aea8e2016-08-19 16:59:55 +02001396 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001398 }
1399
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001400 if (PyFloat_CheckExact(o)) {
1401 Py_INCREF(o);
1402 return o;
1403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 m = o->ob_type->tp_as_number;
1405 if (m && m->nb_float) { /* This should include subclasses of float */
1406 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001407 double val;
1408 if (!res || PyFloat_CheckExact(res)) {
1409 return res;
1410 }
1411 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001413 "%.50s.__float__ returned non-float (type %.50s)",
1414 o->ob_type->tp_name, res->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_DECREF(res);
1416 return NULL;
1417 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001418 /* Issue #26983: warn if 'res' not of exact type float. */
1419 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1420 "%.50s.__float__ returned non-float (type %.50s). "
1421 "The ability to return an instance of a strict subclass of float "
1422 "is deprecated, and may be removed in a future version of Python.",
1423 o->ob_type->tp_name, res->ob_type->tp_name)) {
1424 Py_DECREF(res);
1425 return NULL;
1426 }
1427 val = PyFloat_AS_DOUBLE(res);
1428 Py_DECREF(res);
1429 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 }
1431 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001432 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 }
1434 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001435}
1436
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001437
1438PyObject *
1439PyNumber_ToBase(PyObject *n, int base)
1440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *res = NULL;
1442 PyObject *index = PyNumber_Index(n);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!index)
1445 return NULL;
1446 if (PyLong_Check(index))
1447 res = _PyLong_Format(index, base);
1448 else
1449 /* It should not be possible to get here, as
1450 PyNumber_Index already has a check for the same
1451 condition */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001452 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 Py_DECREF(index);
1454 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001455}
1456
1457
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001458/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001459
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001460int
Fred Drake79912472000-07-09 04:06:11 +00001461PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (PyDict_Check(s))
1464 return 0;
1465 return s != NULL && s->ob_type->tp_as_sequence &&
1466 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001467}
1468
Martin v. Löwis18e16552006-02-15 17:27:45 +00001469Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001470PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (s == NULL) {
1475 null_error();
1476 return -1;
1477 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 m = s->ob_type->tp_as_sequence;
1480 if (m && m->sq_length)
1481 return m->sq_length(s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 type_error("object of type '%.200s' has no len()", s);
1484 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001485}
1486
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001487#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001488Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001489PySequence_Length(PyObject *s)
1490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001492}
1493#define PySequence_Length PySequence_Size
1494
Guido van Rossume15dee51995-07-18 14:12:02 +00001495PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001496PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001499
Victor Stinner71aea8e2016-08-19 16:59:55 +02001500 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001502 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 m = s->ob_type->tp_as_sequence;
1505 if (m && m->sq_concat)
1506 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* Instances of user classes defining an __add__() method only
1509 have an nb_add slot, not an sq_concat slot. So we fall back
1510 to nb_add if both arguments appear to be sequences. */
1511 if (PySequence_Check(s) && PySequence_Check(o)) {
1512 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1513 if (result != Py_NotImplemented)
1514 return result;
1515 Py_DECREF(result);
1516 }
1517 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001518}
1519
1520PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001524
Victor Stinner71aea8e2016-08-19 16:59:55 +02001525 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001527 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 m = o->ob_type->tp_as_sequence;
1530 if (m && m->sq_repeat)
1531 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 /* Instances of user classes defining a __mul__() method only
1534 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1535 to nb_multiply if o appears to be a sequence. */
1536 if (PySequence_Check(o)) {
1537 PyObject *n, *result;
1538 n = PyLong_FromSsize_t(count);
1539 if (n == NULL)
1540 return NULL;
1541 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1542 Py_DECREF(n);
1543 if (result != Py_NotImplemented)
1544 return result;
1545 Py_DECREF(result);
1546 }
1547 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001548}
1549
1550PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001551PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001554
Victor Stinner71aea8e2016-08-19 16:59:55 +02001555 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001557 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 m = s->ob_type->tp_as_sequence;
1560 if (m && m->sq_inplace_concat)
1561 return m->sq_inplace_concat(s, o);
1562 if (m && m->sq_concat)
1563 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (PySequence_Check(s) && PySequence_Check(o)) {
1566 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1567 NB_SLOT(nb_add));
1568 if (result != Py_NotImplemented)
1569 return result;
1570 Py_DECREF(result);
1571 }
1572 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001573}
1574
1575PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001576PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001579
Victor Stinner71aea8e2016-08-19 16:59:55 +02001580 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001582 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 m = o->ob_type->tp_as_sequence;
1585 if (m && m->sq_inplace_repeat)
1586 return m->sq_inplace_repeat(o, count);
1587 if (m && m->sq_repeat)
1588 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (PySequence_Check(o)) {
1591 PyObject *n, *result;
1592 n = PyLong_FromSsize_t(count);
1593 if (n == NULL)
1594 return NULL;
1595 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1596 NB_SLOT(nb_multiply));
1597 Py_DECREF(n);
1598 if (result != Py_NotImplemented)
1599 return result;
1600 Py_DECREF(result);
1601 }
1602 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001603}
1604
1605PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001606PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001609
Victor Stinner71aea8e2016-08-19 16:59:55 +02001610 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001612 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 m = s->ob_type->tp_as_sequence;
1615 if (m && m->sq_item) {
1616 if (i < 0) {
1617 if (m->sq_length) {
1618 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001619 if (l < 0) {
1620 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001622 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 i += l;
1624 }
1625 }
1626 return m->sq_item(s, i);
1627 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001630}
1631
1632PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001636
Victor Stinner71aea8e2016-08-19 16:59:55 +02001637 if (!s) {
1638 return null_error();
1639 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001642 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 PyObject *res;
1644 PyObject *slice = _PySlice_FromIndices(i1, i2);
1645 if (!slice)
1646 return NULL;
1647 res = mp->mp_subscript(s, slice);
1648 Py_DECREF(slice);
1649 return res;
1650 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001653}
1654
1655int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001656PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (s == NULL) {
1661 null_error();
1662 return -1;
1663 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 m = s->ob_type->tp_as_sequence;
1666 if (m && m->sq_ass_item) {
1667 if (i < 0) {
1668 if (m->sq_length) {
1669 Py_ssize_t l = (*m->sq_length)(s);
1670 if (l < 0)
1671 return -1;
1672 i += l;
1673 }
1674 }
1675 return m->sq_ass_item(s, i, o);
1676 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 type_error("'%.200s' object does not support item assignment", s);
1679 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001680}
1681
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001682int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001683PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (s == NULL) {
1688 null_error();
1689 return -1;
1690 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 m = s->ob_type->tp_as_sequence;
1693 if (m && m->sq_ass_item) {
1694 if (i < 0) {
1695 if (m->sq_length) {
1696 Py_ssize_t l = (*m->sq_length)(s);
1697 if (l < 0)
1698 return -1;
1699 i += l;
1700 }
1701 }
1702 return m->sq_ass_item(s, i, (PyObject *)NULL);
1703 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 type_error("'%.200s' object doesn't support item deletion", s);
1706 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001707}
1708
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001709int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001710PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (s == NULL) {
1715 null_error();
1716 return -1;
1717 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001720 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 int res;
1722 PyObject *slice = _PySlice_FromIndices(i1, i2);
1723 if (!slice)
1724 return -1;
1725 res = mp->mp_ass_subscript(s, slice, o);
1726 Py_DECREF(slice);
1727 return res;
1728 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 type_error("'%.200s' object doesn't support slice assignment", s);
1731 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001732}
1733
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001734int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001735PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (s == NULL) {
1740 null_error();
1741 return -1;
1742 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 mp = s->ob_type->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001745 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 int res;
1747 PyObject *slice = _PySlice_FromIndices(i1, i2);
1748 if (!slice)
1749 return -1;
1750 res = mp->mp_ass_subscript(s, slice, NULL);
1751 Py_DECREF(slice);
1752 return res;
1753 }
1754 type_error("'%.200s' object doesn't support slice deletion", s);
1755 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001756}
1757
Guido van Rossume15dee51995-07-18 14:12:02 +00001758PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001759PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyObject *it; /* iter(v) */
1762 Py_ssize_t n; /* guess for result tuple size */
1763 PyObject *result = NULL;
1764 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001765
Victor Stinner71aea8e2016-08-19 16:59:55 +02001766 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001768 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Special-case the common tuple and list cases, for efficiency. */
1771 if (PyTuple_CheckExact(v)) {
1772 /* Note that we can't know whether it's safe to return
1773 a tuple *subclass* instance as-is, hence the restriction
1774 to exact tuples here. In contrast, lists always make
1775 a copy, so there's no need for exactness below. */
1776 Py_INCREF(v);
1777 return v;
1778 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001779 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* Get iterator. */
1783 it = PyObject_GetIter(v);
1784 if (it == NULL)
1785 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001788 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (n == -1)
1790 goto Fail;
1791 result = PyTuple_New(n);
1792 if (result == NULL)
1793 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* Fill the tuple. */
1796 for (j = 0; ; ++j) {
1797 PyObject *item = PyIter_Next(it);
1798 if (item == NULL) {
1799 if (PyErr_Occurred())
1800 goto Fail;
1801 break;
1802 }
1803 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001804 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* The over-allocation strategy can grow a bit faster
1806 than for lists because unlike lists the
1807 over-allocation isn't permanent -- we reclaim
1808 the excess before the end of this routine.
1809 So, grow by ten and then add 25%.
1810 */
Martin Pantere8db8612016-07-25 02:30:05 +00001811 newn += 10u;
1812 newn += newn >> 2;
1813 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 /* Check for overflow */
1815 PyErr_NoMemory();
1816 Py_DECREF(item);
1817 goto Fail;
1818 }
Martin Pantere8db8612016-07-25 02:30:05 +00001819 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (_PyTuple_Resize(&result, n) != 0) {
1821 Py_DECREF(item);
1822 goto Fail;
1823 }
1824 }
1825 PyTuple_SET_ITEM(result, j, item);
1826 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 /* Cut tuple back if guess was too large. */
1829 if (j < n &&
1830 _PyTuple_Resize(&result, j) != 0)
1831 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 Py_DECREF(it);
1834 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00001835
1836Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 Py_XDECREF(result);
1838 Py_DECREF(it);
1839 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001840}
1841
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001842PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001843PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyObject *result; /* result list */
1846 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00001847
Victor Stinner71aea8e2016-08-19 16:59:55 +02001848 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001850 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 result = PyList_New(0);
1853 if (result == NULL)
1854 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 rv = _PyList_Extend((PyListObject *)result, v);
1857 if (rv == NULL) {
1858 Py_DECREF(result);
1859 return NULL;
1860 }
1861 Py_DECREF(rv);
1862 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001863}
1864
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001865PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001866PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00001869
Victor Stinner71aea8e2016-08-19 16:59:55 +02001870 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001872 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
1875 Py_INCREF(v);
1876 return v;
1877 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 it = PyObject_GetIter(v);
1880 if (it == NULL) {
1881 if (PyErr_ExceptionMatches(PyExc_TypeError))
1882 PyErr_SetString(PyExc_TypeError, m);
1883 return NULL;
1884 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 v = PySequence_List(it);
1887 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001890}
1891
Tim Peters16a77ad2001-09-08 04:00:12 +00001892/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1894 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
1895 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00001896 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1897*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00001898Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00001899_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00001900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_ssize_t n;
1902 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1903 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (seq == NULL || obj == NULL) {
1906 null_error();
1907 return -1;
1908 }
Tim Peters75f8e352001-05-05 11:33:43 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 it = PyObject_GetIter(seq);
1911 if (it == NULL) {
1912 type_error("argument of type '%.200s' is not iterable", seq);
1913 return -1;
1914 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 n = wrapped = 0;
1917 for (;;) {
1918 int cmp;
1919 PyObject *item = PyIter_Next(it);
1920 if (item == NULL) {
1921 if (PyErr_Occurred())
1922 goto Fail;
1923 break;
1924 }
Tim Peters16a77ad2001-09-08 04:00:12 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
1927 Py_DECREF(item);
1928 if (cmp < 0)
1929 goto Fail;
1930 if (cmp > 0) {
1931 switch (operation) {
1932 case PY_ITERSEARCH_COUNT:
1933 if (n == PY_SSIZE_T_MAX) {
1934 PyErr_SetString(PyExc_OverflowError,
1935 "count exceeds C integer size");
1936 goto Fail;
1937 }
1938 ++n;
1939 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 case PY_ITERSEARCH_INDEX:
1942 if (wrapped) {
1943 PyErr_SetString(PyExc_OverflowError,
1944 "index exceeds C integer size");
1945 goto Fail;
1946 }
1947 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 case PY_ITERSEARCH_CONTAINS:
1950 n = 1;
1951 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 default:
1954 assert(!"unknown operation");
1955 }
1956 }
Tim Peters16a77ad2001-09-08 04:00:12 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (operation == PY_ITERSEARCH_INDEX) {
1959 if (n == PY_SSIZE_T_MAX)
1960 wrapped = 1;
1961 ++n;
1962 }
1963 }
Tim Peters16a77ad2001-09-08 04:00:12 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (operation != PY_ITERSEARCH_INDEX)
1966 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 PyErr_SetString(PyExc_ValueError,
1969 "sequence.index(x): x not in sequence");
1970 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00001971Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 n = -1;
1973 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00001974Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_DECREF(it);
1976 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00001977
Guido van Rossume15dee51995-07-18 14:12:02 +00001978}
1979
Tim Peters16a77ad2001-09-08 04:00:12 +00001980/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00001981Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00001982PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00001985}
1986
Tim Peterscb8d3682001-05-05 21:05:01 +00001987/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00001988 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00001989 */
1990int
1991PySequence_Contains(PyObject *seq, PyObject *ob)
1992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 Py_ssize_t result;
1994 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
1995 if (sqm != NULL && sqm->sq_contains != NULL)
1996 return (*sqm->sq_contains)(seq, ob);
1997 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
1998 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00001999}
2000
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002001/* Backwards compatibility */
2002#undef PySequence_In
2003int
Fred Drake79912472000-07-09 04:06:11 +00002004PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002007}
2008
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002009Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002010PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002013}
2014
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002015/* Operations on mappings */
2016
2017int
Fred Drake79912472000-07-09 04:06:11 +00002018PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002019{
Benjamin Peterson21992272011-12-28 12:01:31 -06002020 return o && o->ob_type->tp_as_mapping &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 o->ob_type->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002022}
2023
Martin v. Löwis18e16552006-02-15 17:27:45 +00002024Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002025PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (o == NULL) {
2030 null_error();
2031 return -1;
2032 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 m = o->ob_type->tp_as_mapping;
2035 if (m && m->mp_length)
2036 return m->mp_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 type_error("object of type '%.200s' has no len()", o);
2039 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002040}
2041
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002042#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002043Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002044PyMapping_Length(PyObject *o)
2045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002047}
2048#define PyMapping_Length PyMapping_Size
2049
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002050PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002051PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002054
Victor Stinner71aea8e2016-08-19 16:59:55 +02002055 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002057 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 okey = PyUnicode_FromString(key);
2060 if (okey == NULL)
2061 return NULL;
2062 r = PyObject_GetItem(o, okey);
2063 Py_DECREF(okey);
2064 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002065}
2066
2067int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002068PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyObject *okey;
2071 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (key == NULL) {
2074 null_error();
2075 return -1;
2076 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 okey = PyUnicode_FromString(key);
2079 if (okey == NULL)
2080 return -1;
2081 r = PyObject_SetItem(o, okey, value);
2082 Py_DECREF(okey);
2083 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002084}
2085
2086int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002087PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 v = PyMapping_GetItemString(o, key);
2092 if (v) {
2093 Py_DECREF(v);
2094 return 1;
2095 }
2096 PyErr_Clear();
2097 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002098}
2099
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002100int
Fred Drake79912472000-07-09 04:06:11 +00002101PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 v = PyObject_GetItem(o, key);
2106 if (v) {
2107 Py_DECREF(v);
2108 return 1;
2109 }
2110 PyErr_Clear();
2111 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002112}
2113
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002114PyObject *
2115PyMapping_Keys(PyObject *o)
2116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyObject *keys;
2118 PyObject *fast;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002119 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (PyDict_CheckExact(o))
2122 return PyDict_Keys(o);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002123 keys = _PyObject_CallMethodId(o, &PyId_keys, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (keys == NULL)
2125 return NULL;
2126 fast = PySequence_Fast(keys, "o.keys() are not iterable");
2127 Py_DECREF(keys);
2128 return fast;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002129}
2130
2131PyObject *
2132PyMapping_Items(PyObject *o)
2133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *items;
2135 PyObject *fast;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002136 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (PyDict_CheckExact(o))
2139 return PyDict_Items(o);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002140 items = _PyObject_CallMethodId(o, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (items == NULL)
2142 return NULL;
2143 fast = PySequence_Fast(items, "o.items() are not iterable");
2144 Py_DECREF(items);
2145 return fast;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002146}
2147
2148PyObject *
2149PyMapping_Values(PyObject *o)
2150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyObject *values;
2152 PyObject *fast;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002153 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (PyDict_CheckExact(o))
2156 return PyDict_Values(o);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002157 values = _PyObject_CallMethodId(o, &PyId_values, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (values == NULL)
2159 return NULL;
2160 fast = PySequence_Fast(values, "o.values() are not iterable");
2161 Py_DECREF(values);
2162 return fast;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002163}
2164
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002165/* Operations on callable objects */
2166
2167/* XXX PyCallable_Check() is in object.c */
2168
Guido van Rossume15dee51995-07-18 14:12:02 +00002169PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002170PyObject_CallObject(PyObject *o, PyObject *a)
Guido van Rossume15dee51995-07-18 14:12:02 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return PyEval_CallObjectWithKeywords(o, a, NULL);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002173}
Guido van Rossume15dee51995-07-18 14:12:02 +00002174
Victor Stinner4a7cc882015-03-06 23:35:27 +01002175PyObject*
Victor Stinnerefde1462015-03-21 15:04:43 +01002176_Py_CheckFunctionResult(PyObject *func, PyObject *result, const char *where)
Victor Stinner4a7cc882015-03-06 23:35:27 +01002177{
2178 int err_occurred = (PyErr_Occurred() != NULL);
2179
Victor Stinnerefde1462015-03-21 15:04:43 +01002180 assert((func != NULL) ^ (where != NULL));
2181
Victor Stinner4a7cc882015-03-06 23:35:27 +01002182 if (result == NULL) {
2183 if (!err_occurred) {
Victor Stinnerefde1462015-03-21 15:04:43 +01002184 if (func)
2185 PyErr_Format(PyExc_SystemError,
2186 "%R returned NULL without setting an error",
2187 func);
2188 else
2189 PyErr_Format(PyExc_SystemError,
2190 "%s returned NULL without setting an error",
2191 where);
Victor Stinner944fbcc2015-03-24 16:28:52 +01002192#ifdef Py_DEBUG
Serhiy Storchaka5697c4b2016-06-12 17:02:10 +03002193 /* Ensure that the bug is caught in debug mode */
Victor Stinner944fbcc2015-03-24 16:28:52 +01002194 Py_FatalError("a function returned NULL without setting an error");
2195#endif
2196 return NULL;
Victor Stinner4a7cc882015-03-06 23:35:27 +01002197 }
2198 }
2199 else {
2200 if (err_occurred) {
2201 PyObject *exc, *val, *tb;
2202 PyErr_Fetch(&exc, &val, &tb);
2203
2204 Py_DECREF(result);
2205
Victor Stinnerefde1462015-03-21 15:04:43 +01002206 if (func)
2207 PyErr_Format(PyExc_SystemError,
2208 "%R returned a result with an error set",
2209 func);
2210 else
2211 PyErr_Format(PyExc_SystemError,
2212 "%s returned a result with an error set",
2213 where);
Victor Stinner4a7cc882015-03-06 23:35:27 +01002214 _PyErr_ChainExceptions(exc, val, tb);
Victor Stinner944fbcc2015-03-24 16:28:52 +01002215#ifdef Py_DEBUG
Martin Panter2275e622016-06-20 07:52:50 +00002216 /* Ensure that the bug is caught in debug mode */
Victor Stinner944fbcc2015-03-24 16:28:52 +01002217 Py_FatalError("a function returned a result with an error set");
2218#endif
2219 return NULL;
Victor Stinner4a7cc882015-03-06 23:35:27 +01002220 }
2221 }
2222 return result;
2223}
2224
Guido van Rossume15dee51995-07-18 14:12:02 +00002225PyObject *
Victor Stinner8a31c822016-08-19 17:12:23 +02002226PyObject_Call(PyObject *func, PyObject *args, PyObject *kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 ternaryfunc call;
Victor Stinner4a7cc882015-03-06 23:35:27 +01002229 PyObject *result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230
Victor Stinner8f4ec8d2014-09-05 01:10:29 +02002231 /* PyObject_Call() must not be called with an exception set,
2232 because it may clear it (directly or indirectly) and so the
Martin Panterec1aa5c2015-10-07 11:03:53 +00002233 caller loses its exception */
Victor Stinner8f4ec8d2014-09-05 01:10:29 +02002234 assert(!PyErr_Occurred());
Victor Stinner8a31c822016-08-19 17:12:23 +02002235 assert(PyTuple_Check(args));
2236 assert(kwargs == NULL || PyDict_Check(kwargs));
Victor Stinner8f4ec8d2014-09-05 01:10:29 +02002237
Victor Stinner4a7cc882015-03-06 23:35:27 +01002238 call = func->ob_type->tp_call;
2239 if (call == NULL) {
2240 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2241 func->ob_type->tp_name);
2242 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 }
Victor Stinner4a7cc882015-03-06 23:35:27 +01002244
2245 if (Py_EnterRecursiveCall(" while calling a Python object"))
2246 return NULL;
2247
Victor Stinner8a31c822016-08-19 17:12:23 +02002248 result = (*call)(func, args, kwargs);
Victor Stinner4a7cc882015-03-06 23:35:27 +01002249
2250 Py_LeaveRecursiveCall();
2251
Victor Stinnerefde1462015-03-21 15:04:43 +01002252 return _Py_CheckFunctionResult(func, result, NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253}
2254
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002255PyObject*
2256_PyStack_AsTuple(PyObject **stack, Py_ssize_t nargs)
2257{
2258 PyObject *args;
2259 Py_ssize_t i;
2260
2261 args = PyTuple_New(nargs);
2262 if (args == NULL) {
2263 return NULL;
2264 }
2265
2266 for (i=0; i < nargs; i++) {
2267 PyObject *item = stack[i];
2268 Py_INCREF(item);
2269 PyTuple_SET_ITEM(args, i, item);
2270 }
2271
2272 return args;
2273}
2274
2275PyObject *
Victor Stinner74319ae2016-08-25 00:04:09 +02002276_PyObject_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs,
Victor Stinnerb9009392016-08-22 23:15:44 +02002277 PyObject *kwargs)
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002278{
2279 ternaryfunc call;
2280 PyObject *result = NULL;
2281
Victor Stinner559bb6a2016-08-22 22:48:54 +02002282 /* _PyObject_FastCallDict() must not be called with an exception set,
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002283 because it may clear it (directly or indirectly) and so the
2284 caller loses its exception */
2285 assert(!PyErr_Occurred());
2286
2287 assert(func != NULL);
2288 assert(nargs >= 0);
2289 assert(nargs == 0 || args != NULL);
Victor Stinnerb9009392016-08-22 23:15:44 +02002290 assert(kwargs == NULL || PyDict_Check(kwargs));
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002291
2292 if (Py_EnterRecursiveCall(" while calling a Python object")) {
2293 return NULL;
2294 }
2295
2296 if (PyFunction_Check(func)) {
Victor Stinnerb9009392016-08-22 23:15:44 +02002297 result = _PyFunction_FastCallDict(func, args, nargs, kwargs);
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002298 }
2299 else if (PyCFunction_Check(func)) {
Victor Stinnerb9009392016-08-22 23:15:44 +02002300 result = _PyCFunction_FastCallDict(func, args, nargs, kwargs);
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002301 }
2302 else {
2303 PyObject *tuple;
2304
2305 /* Slow-path: build a temporary tuple */
2306 call = func->ob_type->tp_call;
2307 if (call == NULL) {
2308 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2309 func->ob_type->tp_name);
2310 goto exit;
2311 }
2312
2313 tuple = _PyStack_AsTuple(args, nargs);
2314 if (tuple == NULL) {
2315 goto exit;
2316 }
2317
2318 result = (*call)(func, tuple, kwargs);
2319 Py_DECREF(tuple);
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002320
Victor Stinner53cb4892016-08-25 00:39:34 +02002321 result = _Py_CheckFunctionResult(func, result, NULL);
2322 }
Victor Stinner9be7e7b2016-08-19 16:11:43 +02002323
2324exit:
2325 Py_LeaveRecursiveCall();
2326
2327 return result;
2328}
2329
Victor Stinner3f1057a2016-08-25 01:04:14 +02002330/* Positional arguments are obj followed args. */
2331PyObject *
2332_PyObject_Call_Prepend(PyObject *func,
2333 PyObject *obj, PyObject *args, PyObject *kwargs)
2334{
2335 PyObject *small_stack[8];
2336 PyObject **stack;
2337 Py_ssize_t argcount;
2338 PyObject *result;
2339
2340 assert(PyTuple_Check(args));
2341
2342 argcount = PyTuple_GET_SIZE(args);
2343 if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
2344 stack = small_stack;
2345 }
2346 else {
2347 stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *));
2348 if (stack == NULL) {
2349 PyErr_NoMemory();
2350 return NULL;
2351 }
2352 }
2353
2354 /* use borrowed references */
2355 stack[0] = obj;
2356 Py_MEMCPY(&stack[1],
2357 &PyTuple_GET_ITEM(args, 0),
2358 argcount * sizeof(PyObject *));
2359
2360 result = _PyObject_FastCallDict(func,
2361 stack, argcount + 1,
2362 kwargs);
2363 if (stack != small_stack) {
2364 PyMem_Free(stack);
2365 }
2366 return result;
2367}
2368
Victor Stinnerae8b69c2016-09-09 14:07:44 -07002369PyObject *
Victor Stinnerd8735722016-09-09 12:36:44 -07002370_PyStack_AsDict(PyObject **values, Py_ssize_t nkwargs, PyObject *kwnames,
2371 PyObject *func)
2372{
2373 PyObject *kwdict;
2374 Py_ssize_t i;
2375
2376 kwdict = PyDict_New();
2377 if (kwdict == NULL) {
2378 return NULL;
2379 }
2380
2381 for (i=0; i < nkwargs; i++) {
2382 int err;
2383 PyObject *key = PyTuple_GET_ITEM(kwnames, i);
2384 PyObject *value = *values++;
2385
2386 if (PyDict_GetItem(kwdict, key) != NULL) {
2387 PyErr_Format(PyExc_TypeError,
2388 "%.200s%s got multiple values "
2389 "for keyword argument '%U'",
2390 PyEval_GetFuncName(func),
2391 PyEval_GetFuncDesc(func),
2392 key);
2393 Py_DECREF(kwdict);
2394 return NULL;
2395 }
2396
2397 err = PyDict_SetItem(kwdict, key, value);
2398 if (err) {
2399 Py_DECREF(kwdict);
2400 return NULL;
2401 }
2402 }
2403 return kwdict;
2404}
2405
Victor Stinnera9efb2f2016-09-09 17:40:22 -07002406PyObject **
2407_PyStack_UnpackDict(PyObject **args, Py_ssize_t nargs, PyObject *kwargs,
2408 PyObject **p_kwnames, PyObject *func)
2409{
2410 PyObject **stack, **kwstack;
2411 Py_ssize_t nkwargs;
2412 Py_ssize_t pos, i;
2413 PyObject *key, *value;
2414 PyObject *kwnames;
2415
2416 assert(nargs >= 0);
2417 assert(kwargs == NULL || PyDict_CheckExact(kwargs));
2418
2419 nkwargs = (kwargs != NULL) ? PyDict_Size(kwargs) : 0;
2420 if (!nkwargs) {
2421 *p_kwnames = NULL;
2422 return args;
2423 }
2424
2425 if ((size_t)nargs > PY_SSIZE_T_MAX / sizeof(stack[0]) - (size_t)nkwargs) {
2426 PyErr_NoMemory();
2427 return NULL;
2428 }
2429
2430 stack = PyMem_Malloc((nargs + nkwargs) * sizeof(stack[0]));
2431 if (stack == NULL) {
2432 PyErr_NoMemory();
2433 return NULL;
2434 }
2435
2436 kwnames = PyTuple_New(nkwargs);
2437 if (kwnames == NULL) {
2438 PyMem_Free(stack);
2439 return NULL;
2440 }
2441
2442 /* Copy position arguments (borrowed references) */
2443 Py_MEMCPY(stack, args, nargs * sizeof(stack[0]));
2444
2445 kwstack = stack + nargs;
2446 pos = i = 0;
2447 /* This loop doesn't support lookup function mutating the dictionary
2448 to change its size. It's a deliberate choice for speed, this function is
2449 called in the performance critical hot code. */
2450 while (PyDict_Next(kwargs, &pos, &key, &value)) {
2451 Py_INCREF(key);
2452 PyTuple_SET_ITEM(kwnames, i, key);
2453 /* The stack contains borrowed references */
2454 kwstack[i] = value;
2455 i++;
2456 }
2457
2458 *p_kwnames = kwnames;
2459 return stack;
2460}
2461
Victor Stinnerd8735722016-09-09 12:36:44 -07002462PyObject *
2463_PyObject_FastCallKeywords(PyObject *func, PyObject **stack, Py_ssize_t nargs,
2464 PyObject *kwnames)
2465{
2466 PyObject *kwdict, *result;
2467 Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames);
2468
2469 assert(nargs >= 0);
2470 assert(kwnames == NULL || PyTuple_CheckExact(kwnames));
2471 assert((nargs == 0 && nkwargs == 0) || stack != NULL);
2472
2473 if (PyFunction_Check(func)) {
Victor Stinnerd8735722016-09-09 12:36:44 -07002474 return _PyFunction_FastCallKeywords(func, stack, nargs, kwnames);
2475 }
2476
Victor Stinnerae8b69c2016-09-09 14:07:44 -07002477 if (PyCFunction_Check(func)) {
2478 return _PyCFunction_FastCallKeywords(func, stack, nargs, kwnames);
2479 }
2480
Victor Stinnerd8735722016-09-09 12:36:44 -07002481 if (nkwargs > 0) {
2482 kwdict = _PyStack_AsDict(stack + nargs, nkwargs, kwnames, func);
2483 if (kwdict == NULL) {
2484 return NULL;
2485 }
2486 }
2487 else {
2488 kwdict = NULL;
2489 }
2490
2491 result = _PyObject_FastCallDict(func, stack, nargs, kwdict);
2492 Py_XDECREF(kwdict);
2493 return result;
2494}
2495
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002496static PyObject*
2497call_function_tail(PyObject *callable, PyObject *args)
2498{
Victor Stinner88807082016-08-19 16:44:19 +02002499 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500
Victor Stinner64faad62016-08-19 16:50:49 +02002501 assert(args != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (!PyTuple_Check(args)) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02002504 result = _PyObject_CallArg1(callable, args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 }
Victor Stinner88807082016-08-19 16:44:19 +02002506 else {
2507 result = PyObject_Call(callable, args, NULL);
2508 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002509
Victor Stinner88807082016-08-19 16:44:19 +02002510 return result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002511}
2512
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002514PyObject_CallFunction(PyObject *callable, const char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 va_list va;
Victor Stinner64faad62016-08-19 16:50:49 +02002517 PyObject *args, *result;
Guido van Rossume15dee51995-07-18 14:12:02 +00002518
Victor Stinner71aea8e2016-08-19 16:59:55 +02002519 if (callable == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002521 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002522
Victor Stinner0d1a7992016-08-19 17:04:54 +02002523 if (!format || !*format) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02002524 return _PyObject_CallNoArg(callable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 }
Victor Stinner0d1a7992016-08-19 17:04:54 +02002526
2527 va_start(va, format);
2528 args = Py_VaBuildValue(format, va);
2529 va_end(va);
Victor Stinner64faad62016-08-19 16:50:49 +02002530 if (args == NULL) {
Victor Stinner0b0c8672013-10-29 19:29:52 +01002531 return NULL;
Victor Stinner64faad62016-08-19 16:50:49 +02002532 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002533
Victor Stinner64faad62016-08-19 16:50:49 +02002534 result = call_function_tail(callable, args);
2535 Py_DECREF(args);
2536 return result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002537}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002538
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002539PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002540_PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 va_list va;
Victor Stinner64faad62016-08-19 16:50:49 +02002543 PyObject *args, *result;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002544
Victor Stinner71aea8e2016-08-19 16:59:55 +02002545 if (callable == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002547 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002548
Victor Stinner0d1a7992016-08-19 17:04:54 +02002549 if (!format || !*format) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02002550 return _PyObject_CallNoArg(callable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 }
Victor Stinner0d1a7992016-08-19 17:04:54 +02002552
2553 va_start(va, format);
2554 args = _Py_VaBuildValue_SizeT(format, va);
2555 va_end(va);
Victor Stinner64faad62016-08-19 16:50:49 +02002556 if (args == NULL) {
2557 return NULL;
2558 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002559
Victor Stinner64faad62016-08-19 16:50:49 +02002560 result = call_function_tail(callable, args);
2561 Py_DECREF(args);
2562 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00002563}
2564
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002565static PyObject*
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002566callmethod(PyObject* func, const char *format, va_list va, int is_size_t)
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002567{
Victor Stinner64faad62016-08-19 16:50:49 +02002568 PyObject *args, *result;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002569
Victor Stinnerd042f1f2016-08-19 16:56:49 +02002570 assert(func != NULL);
2571
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002572 if (!PyCallable_Check(func)) {
2573 type_error("attribute of type '%.200s' is not callable", func);
Victor Stinner64faad62016-08-19 16:50:49 +02002574 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002575 }
2576
Victor Stinner0d1a7992016-08-19 17:04:54 +02002577 if (!format || !*format) {
Victor Stinner559bb6a2016-08-22 22:48:54 +02002578 return _PyObject_CallNoArg(func);
Victor Stinner0d1a7992016-08-19 17:04:54 +02002579 }
2580
2581 if (is_size_t) {
2582 args = _Py_VaBuildValue_SizeT(format, va);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002583 }
Victor Stinner64faad62016-08-19 16:50:49 +02002584 else {
Victor Stinner0d1a7992016-08-19 17:04:54 +02002585 args = Py_VaBuildValue(format, va);
Victor Stinner64faad62016-08-19 16:50:49 +02002586 }
2587 if (args == NULL) {
2588 return NULL;
2589 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002590
Victor Stinner64faad62016-08-19 16:50:49 +02002591 result = call_function_tail(func, args);
Victor Stinner64faad62016-08-19 16:50:49 +02002592 Py_DECREF(args);
2593 return result;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002594}
2595
Guido van Rossume15dee51995-07-18 14:12:02 +00002596PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002597PyObject_CallMethod(PyObject *o, const char *name, const char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 va_list va;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyObject *func = NULL;
2601 PyObject *retval = NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002602
Victor Stinner71aea8e2016-08-19 16:59:55 +02002603 if (o == NULL || name == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002605 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 func = PyObject_GetAttrString(o, name);
Benjamin Peterson1791c222014-06-26 23:29:13 -07002608 if (func == NULL)
2609 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002610
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002611 va_start(va, format);
2612 retval = callmethod(func, format, va, 0);
2613 va_end(va);
Victor Stinnerd042f1f2016-08-19 16:56:49 +02002614 Py_DECREF(func);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002615 return retval;
2616}
2617
2618PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002619_PyObject_CallMethodId(PyObject *o, _Py_Identifier *name,
2620 const char *format, ...)
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002621{
2622 va_list va;
2623 PyObject *func = NULL;
2624 PyObject *retval = NULL;
2625
Victor Stinner71aea8e2016-08-19 16:59:55 +02002626 if (o == NULL || name == NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002627 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002628 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002629
2630 func = _PyObject_GetAttrId(o, name);
Benjamin Peterson1791c222014-06-26 23:29:13 -07002631 if (func == NULL)
2632 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002633
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002634 va_start(va, format);
2635 retval = callmethod(func, format, va, 0);
2636 va_end(va);
Victor Stinnerd042f1f2016-08-19 16:56:49 +02002637 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return retval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639}
2640
2641PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002642_PyObject_CallMethod_SizeT(PyObject *o, const char *name,
2643 const char *format, ...)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 va_list va;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 PyObject *func = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002647 PyObject *retval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002648
Victor Stinner71aea8e2016-08-19 16:59:55 +02002649 if (o == NULL || name == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002651 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 func = PyObject_GetAttrString(o, name);
Benjamin Peterson1791c222014-06-26 23:29:13 -07002654 if (func == NULL)
2655 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002656 va_start(va, format);
2657 retval = callmethod(func, format, va, 1);
2658 va_end(va);
Victor Stinnerd042f1f2016-08-19 16:56:49 +02002659 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 return retval;
Guido van Rossume15dee51995-07-18 14:12:02 +00002661}
Guido van Rossum823649d2001-03-21 18:40:58 +00002662
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002663PyObject *
Serhiy Storchaka1cfebc72013-05-29 18:50:54 +03002664_PyObject_CallMethodId_SizeT(PyObject *o, _Py_Identifier *name,
2665 const char *format, ...)
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002666{
2667 va_list va;
2668 PyObject *func = NULL;
2669 PyObject *retval;
2670
Victor Stinner71aea8e2016-08-19 16:59:55 +02002671 if (o == NULL || name == NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002672 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002673 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002674
2675 func = _PyObject_GetAttrId(o, name);
2676 if (func == NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002677 return NULL;
2678 }
2679 va_start(va, format);
2680 retval = callmethod(func, format, va, 1);
2681 va_end(va);
Victor Stinnerd042f1f2016-08-19 16:56:49 +02002682 Py_DECREF(func);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002683 return retval;
2684}
Guido van Rossum823649d2001-03-21 18:40:58 +00002685
Victor Stinnerdd695642016-08-24 01:14:54 +02002686static PyObject **
2687objargs_mkstack(PyObject **small_stack, Py_ssize_t small_stack_size,
2688 va_list va, Py_ssize_t *p_nargs)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002689{
Victor Stinnerdd695642016-08-24 01:14:54 +02002690 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 va_list countva;
Victor Stinnerdd695642016-08-24 01:14:54 +02002692 PyObject **stack;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002693
Victor Stinnerdd695642016-08-24 01:14:54 +02002694 /* Count the number of arguments */
2695 Py_VA_COPY(countva, va);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002696
Victor Stinnerdd695642016-08-24 01:14:54 +02002697 n = 0;
2698 while (1) {
2699 PyObject *arg = (PyObject *)va_arg(countva, PyObject *);
2700 if (arg == NULL) {
2701 break;
2702 }
2703 n++;
2704 }
2705 *p_nargs = n;
2706
2707 /* Copy arguments */
2708 if (n <= small_stack_size) {
2709 stack = small_stack;
2710 }
2711 else {
2712 stack = PyMem_Malloc(n * sizeof(stack[0]));
2713 if (stack == NULL) {
2714 PyErr_NoMemory();
2715 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 }
2717 }
Victor Stinnerdd695642016-08-24 01:14:54 +02002718
2719 for (i = 0; i < n; ++i) {
2720 stack[i] = va_arg(va, PyObject *);
2721 }
2722 return stack;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002723}
2724
2725PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002726PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002727{
Victor Stinnerdd695642016-08-24 01:14:54 +02002728 PyObject *small_stack[5];
2729 PyObject **stack;
2730 Py_ssize_t nargs;
2731 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002733
Victor Stinner71aea8e2016-08-19 16:59:55 +02002734 if (callable == NULL || name == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002736 }
Fred Drakeb421b8c2001-10-26 16:21:32 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 callable = PyObject_GetAttr(callable, name);
2739 if (callable == NULL)
2740 return NULL;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 /* count the args */
2743 va_start(vargs, name);
Victor Stinnerdd695642016-08-24 01:14:54 +02002744 stack = objargs_mkstack(small_stack, Py_ARRAY_LENGTH(small_stack),
2745 vargs, &nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 va_end(vargs);
Victor Stinnerdd695642016-08-24 01:14:54 +02002747 if (stack == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 Py_DECREF(callable);
2749 return NULL;
2750 }
Victor Stinnere62b8522016-08-24 00:01:56 +02002751
Victor Stinnerdd695642016-08-24 01:14:54 +02002752 result = _PyObject_FastCall(callable, stack, nargs);
2753 Py_DECREF(callable);
2754 if (stack != small_stack) {
2755 PyMem_Free(stack);
2756 }
2757
2758 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002759}
2760
2761PyObject *
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07002762_PyObject_CallMethodIdObjArgs(PyObject *callable,
Brett Cannonfd074152012-04-14 14:10:13 -04002763 struct _Py_Identifier *name, ...)
2764{
Victor Stinnerdd695642016-08-24 01:14:54 +02002765 PyObject *small_stack[5];
2766 PyObject **stack;
2767 Py_ssize_t nargs;
2768 PyObject *result;
Brett Cannonfd074152012-04-14 14:10:13 -04002769 va_list vargs;
2770
Victor Stinner71aea8e2016-08-19 16:59:55 +02002771 if (callable == NULL || name == NULL) {
Brett Cannonfd074152012-04-14 14:10:13 -04002772 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002773 }
Brett Cannonfd074152012-04-14 14:10:13 -04002774
2775 callable = _PyObject_GetAttrId(callable, name);
2776 if (callable == NULL)
2777 return NULL;
2778
2779 /* count the args */
2780 va_start(vargs, name);
Victor Stinnerdd695642016-08-24 01:14:54 +02002781 stack = objargs_mkstack(small_stack, Py_ARRAY_LENGTH(small_stack),
2782 vargs, &nargs);
Brett Cannonfd074152012-04-14 14:10:13 -04002783 va_end(vargs);
Victor Stinnerdd695642016-08-24 01:14:54 +02002784 if (stack == NULL) {
Brett Cannonfd074152012-04-14 14:10:13 -04002785 Py_DECREF(callable);
2786 return NULL;
2787 }
Victor Stinnere62b8522016-08-24 00:01:56 +02002788
Victor Stinnerdd695642016-08-24 01:14:54 +02002789 result = _PyObject_FastCall(callable, stack, nargs);
2790 Py_DECREF(callable);
2791 if (stack != small_stack) {
2792 PyMem_Free(stack);
2793 }
2794
2795 return result;
Brett Cannonfd074152012-04-14 14:10:13 -04002796}
2797
2798PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002799PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002800{
Victor Stinnerdd695642016-08-24 01:14:54 +02002801 PyObject *small_stack[5];
2802 PyObject **stack;
2803 Py_ssize_t nargs;
2804 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002806
Victor Stinner71aea8e2016-08-19 16:59:55 +02002807 if (callable == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002809 }
Fred Drakeb421b8c2001-10-26 16:21:32 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* count the args */
2812 va_start(vargs, callable);
Victor Stinnerdd695642016-08-24 01:14:54 +02002813 stack = objargs_mkstack(small_stack, Py_ARRAY_LENGTH(small_stack),
2814 vargs, &nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 va_end(vargs);
Victor Stinnerdd695642016-08-24 01:14:54 +02002816 if (stack == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return NULL;
Victor Stinnerdd695642016-08-24 01:14:54 +02002818 }
Fred Drakeb421b8c2001-10-26 16:21:32 +00002819
Victor Stinnerdd695642016-08-24 01:14:54 +02002820 result = _PyObject_FastCall(callable, stack, nargs);
2821 if (stack != small_stack) {
2822 PyMem_Free(stack);
2823 }
2824
2825 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002826}
2827
2828
Guido van Rossum823649d2001-03-21 18:40:58 +00002829/* isinstance(), issubclass() */
2830
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002831/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002832 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002833 * 1. getattr(cls, '__bases__') could raise an AttributeError
2834 * 2. getattr(cls, '__bases__') could raise some other exception
2835 * 3. getattr(cls, '__bases__') could return a tuple
2836 * 4. getattr(cls, '__bases__') could return something other than a tuple
2837 *
2838 * Only state #3 is a non-error state and only it returns a non-NULL object
2839 * (it returns the retrieved tuple).
2840 *
2841 * Any raised AttributeErrors are masked by clearing the exception and
2842 * returning NULL. If an object other than a tuple comes out of __bases__,
2843 * then again, the return value is NULL. So yes, these two situations
2844 * produce exactly the same results: NULL is returned and no error is set.
2845 *
2846 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002848 * exception to be propagated along.
2849 *
2850 * Callers are expected to test for PyErr_Occurred() when the return value
2851 * is NULL to decide whether a valid exception should be propagated or not.
2852 * When there's no exception to propagate, it's customary for the caller to
2853 * set a TypeError.
2854 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002855static PyObject *
2856abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002857{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002858 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 Py_ALLOW_RECURSION
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002862 bases = _PyObject_GetAttrId(cls, &PyId___bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 Py_END_ALLOW_RECURSION
2864 if (bases == NULL) {
2865 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2866 PyErr_Clear();
2867 return NULL;
2868 }
2869 if (!PyTuple_Check(bases)) {
2870 Py_DECREF(bases);
2871 return NULL;
2872 }
2873 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002874}
2875
2876
2877static int
2878abstract_issubclass(PyObject *derived, PyObject *cls)
2879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 PyObject *bases = NULL;
2881 Py_ssize_t i, n;
2882 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 while (1) {
2885 if (derived == cls)
2886 return 1;
2887 bases = abstract_get_bases(derived);
2888 if (bases == NULL) {
2889 if (PyErr_Occurred())
2890 return -1;
2891 return 0;
2892 }
2893 n = PyTuple_GET_SIZE(bases);
2894 if (n == 0) {
2895 Py_DECREF(bases);
2896 return 0;
2897 }
2898 /* Avoid recursivity in the single inheritance case */
2899 if (n == 1) {
2900 derived = PyTuple_GET_ITEM(bases, 0);
2901 Py_DECREF(bases);
2902 continue;
2903 }
2904 for (i = 0; i < n; i++) {
2905 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2906 if (r != 0)
2907 break;
2908 }
2909 Py_DECREF(bases);
2910 return r;
2911 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002912}
2913
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002914static int
2915check_class(PyObject *cls, const char *error)
2916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 PyObject *bases = abstract_get_bases(cls);
2918 if (bases == NULL) {
2919 /* Do not mask errors. */
2920 if (!PyErr_Occurred())
2921 PyErr_SetString(PyExc_TypeError, error);
2922 return 0;
2923 }
2924 Py_DECREF(bases);
2925 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002926}
2927
Brett Cannon4f653312004-03-20 22:52:14 +00002928static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002929recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 PyObject *icls;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 int retval = 0;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002933 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 if (PyType_Check(cls)) {
2936 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2937 if (retval == 0) {
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002938 PyObject *c = _PyObject_GetAttrId(inst, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (c == NULL) {
Benjamin Peterson72288d42010-11-20 17:21:08 +00002940 if (PyErr_ExceptionMatches(PyExc_AttributeError))
R. David Murray6bb99892010-11-20 16:33:30 +00002941 PyErr_Clear();
Benjamin Peterson72288d42010-11-20 17:21:08 +00002942 else
R. David Murray6bb99892010-11-20 16:33:30 +00002943 retval = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 }
2945 else {
2946 if (c != (PyObject *)(inst->ob_type) &&
2947 PyType_Check(c))
2948 retval = PyType_IsSubtype(
2949 (PyTypeObject *)c,
2950 (PyTypeObject *)cls);
2951 Py_DECREF(c);
2952 }
2953 }
2954 }
2955 else {
2956 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002957 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return -1;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002959 icls = _PyObject_GetAttrId(inst, &PyId___class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (icls == NULL) {
Benjamin Peterson72288d42010-11-20 17:21:08 +00002961 if (PyErr_ExceptionMatches(PyExc_AttributeError))
R. David Murray6bb99892010-11-20 16:33:30 +00002962 PyErr_Clear();
Benjamin Peterson72288d42010-11-20 17:21:08 +00002963 else
R. David Murray6bb99892010-11-20 16:33:30 +00002964 retval = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 }
2966 else {
2967 retval = abstract_issubclass(icls, cls);
2968 Py_DECREF(icls);
2969 }
2970 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002973}
2974
2975int
Brett Cannon4f653312004-03-20 22:52:14 +00002976PyObject_IsInstance(PyObject *inst, PyObject *cls)
2977{
Benjamin Petersonce798522012-01-22 11:24:29 -05002978 _Py_IDENTIFIER(__instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 PyObject *checker;
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 /* Quick test for an exact match */
2982 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2983 return 1;
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002984
Georg Brandl72b8a802014-10-03 09:26:37 +02002985 /* We know what type's __instancecheck__ does. */
2986 if (PyType_CheckExact(cls)) {
2987 return recursive_isinstance(inst, cls);
2988 }
2989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 if (PyTuple_Check(cls)) {
2991 Py_ssize_t i;
2992 Py_ssize_t n;
2993 int r = 0;
Antoine Pitrouec569b72008-08-26 22:40:48 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2996 return -1;
2997 n = PyTuple_GET_SIZE(cls);
2998 for (i = 0; i < n; ++i) {
2999 PyObject *item = PyTuple_GET_ITEM(cls, i);
3000 r = PyObject_IsInstance(inst, item);
3001 if (r != 0)
3002 /* either found it, or got an error */
3003 break;
3004 }
3005 Py_LeaveRecursiveCall();
3006 return r;
3007 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00003008
Benjamin Petersonce798522012-01-22 11:24:29 -05003009 checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 if (checker != NULL) {
3011 PyObject *res;
3012 int ok = -1;
3013 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
3014 Py_DECREF(checker);
3015 return ok;
3016 }
3017 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
3018 Py_LeaveRecursiveCall();
3019 Py_DECREF(checker);
3020 if (res != NULL) {
3021 ok = PyObject_IsTrue(res);
3022 Py_DECREF(res);
3023 }
3024 return ok;
3025 }
3026 else if (PyErr_Occurred())
3027 return -1;
Georg Brandl72b8a802014-10-03 09:26:37 +02003028 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003030}
3031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00003033recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00003034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 if (PyType_Check(cls) && PyType_Check(derived)) {
3036 /* Fast path (non-recursive) */
3037 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
3038 }
3039 if (!check_class(derived,
3040 "issubclass() arg 1 must be a class"))
3041 return -1;
3042 if (!check_class(cls,
3043 "issubclass() arg 2 must be a class"
3044 " or tuple of classes"))
3045 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00003048}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003049
Brett Cannon4f653312004-03-20 22:52:14 +00003050int
3051PyObject_IsSubclass(PyObject *derived, PyObject *cls)
3052{
Benjamin Petersonce798522012-01-22 11:24:29 -05003053 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00003055
Georg Brandl72b8a802014-10-03 09:26:37 +02003056 /* We know what type's __subclasscheck__ does. */
3057 if (PyType_CheckExact(cls)) {
3058 /* Quick test for an exact match */
3059 if (derived == cls)
3060 return 1;
3061 return recursive_issubclass(derived, cls);
3062 }
3063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 if (PyTuple_Check(cls)) {
3065 Py_ssize_t i;
3066 Py_ssize_t n;
3067 int r = 0;
Antoine Pitrouec569b72008-08-26 22:40:48 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3070 return -1;
3071 n = PyTuple_GET_SIZE(cls);
3072 for (i = 0; i < n; ++i) {
3073 PyObject *item = PyTuple_GET_ITEM(cls, i);
3074 r = PyObject_IsSubclass(derived, item);
3075 if (r != 0)
3076 /* either found it, or got an error */
3077 break;
3078 }
3079 Py_LeaveRecursiveCall();
3080 return r;
3081 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00003082
Benjamin Petersonce798522012-01-22 11:24:29 -05003083 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 if (checker != NULL) {
3085 PyObject *res;
3086 int ok = -1;
3087 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3088 Py_DECREF(checker);
3089 return ok;
3090 }
3091 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3092 Py_LeaveRecursiveCall();
3093 Py_DECREF(checker);
3094 if (res != NULL) {
3095 ok = PyObject_IsTrue(res);
3096 Py_DECREF(res);
3097 }
3098 return ok;
3099 }
3100 else if (PyErr_Occurred())
3101 return -1;
Georg Brandl72b8a802014-10-03 09:26:37 +02003102 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00003104}
3105
3106int
3107_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 return recursive_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00003110}
3111
3112int
3113_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003116}
3117
3118
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003119PyObject *
3120PyObject_GetIter(PyObject *o)
3121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 PyTypeObject *t = o->ob_type;
3123 getiterfunc f = NULL;
3124 f = t->tp_iter;
3125 if (f == NULL) {
3126 if (PySequence_Check(o))
3127 return PySeqIter_New(o);
3128 return type_error("'%.200s' object is not iterable", o);
3129 }
3130 else {
3131 PyObject *res = (*f)(o);
3132 if (res != NULL && !PyIter_Check(res)) {
3133 PyErr_Format(PyExc_TypeError,
3134 "iter() returned non-iterator "
3135 "of type '%.100s'",
3136 res->ob_type->tp_name);
3137 Py_DECREF(res);
3138 res = NULL;
3139 }
3140 return res;
3141 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00003142}
3143
Tim Petersf4848da2001-05-05 00:14:56 +00003144/* Return next item.
3145 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3146 * If the iteration terminates normally, return NULL and clear the
3147 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3148 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00003150 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00003151PyObject *
3152PyIter_Next(PyObject *iter)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 PyObject *result;
3155 result = (*iter->ob_type->tp_iternext)(iter);
3156 if (result == NULL &&
3157 PyErr_Occurred() &&
3158 PyErr_ExceptionMatches(PyExc_StopIteration))
3159 PyErr_Clear();
3160 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003161}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003162
3163
3164/*
3165 * Flatten a sequence of bytes() objects into a C array of
3166 * NULL terminated string pointers with a NULL char* terminating the array.
3167 * (ie: an argv or env list)
3168 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003169 * Memory allocated for the returned list is allocated using PyMem_Malloc()
3170 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003171 */
3172char *const *
3173_PySequence_BytesToCharpArray(PyObject* self)
3174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 char **array;
3176 Py_ssize_t i, argc;
3177 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003178 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 argc = PySequence_Size(self);
3181 if (argc == -1)
3182 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003183
Stefan Krah7cacd2e2012-08-21 08:16:09 +02003184 assert(argc >= 0);
3185
3186 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
3187 PyErr_NoMemory();
3188 return NULL;
3189 }
3190
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003191 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 if (array == NULL) {
3193 PyErr_NoMemory();
3194 return NULL;
3195 }
3196 for (i = 0; i < argc; ++i) {
3197 char *data;
3198 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02003199 if (item == NULL) {
3200 /* NULL terminate before freeing. */
3201 array[i] = NULL;
3202 goto fail;
3203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 data = PyBytes_AsString(item);
3205 if (data == NULL) {
3206 /* NULL terminate before freeing. */
3207 array[i] = NULL;
3208 goto fail;
3209 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003210 size = PyBytes_GET_SIZE(item) + 1;
3211 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (!array[i]) {
3213 PyErr_NoMemory();
3214 goto fail;
3215 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003216 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_DECREF(item);
3218 }
3219 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003222
3223fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 Py_XDECREF(item);
3225 _Py_FreeCharPArray(array);
3226 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003227}
3228
3229
3230/* Free's a NULL terminated char** array of C strings. */
3231void
3232_Py_FreeCharPArray(char *const array[])
3233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 Py_ssize_t i;
3235 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003236 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02003238 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00003239}