blob: 898becd24580e6eedddc6680dad92063f2bdda4d [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
8#define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00009 Py_TPFLAGS_CHECKTYPES)
Guido van Rossume15dee51995-07-18 14:12:02 +000010
Martin v. Löwis5cb69362006-04-14 09:08:42 +000011
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000012/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000013
14static PyObject *
Georg Brandlccff7852006-06-18 22:17:29 +000015type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000016{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000017 PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
18 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000019}
20
Guido van Rossum052b7e11996-11-11 15:08:19 +000021static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000022null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000023{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000024 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError,
26 "null argument to internal routine");
27 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000028}
29
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000030/* Operations on any object */
31
32int
Fred Drake79912472000-07-09 04:06:11 +000033PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000034{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000035 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000036
Antoine Pitrouc83ea132010-05-09 14:46:46 +000037 if (o1 == NULL || o2 == NULL) {
38 null_error();
39 return -1;
40 }
41 r = PyObject_Compare(o1, o2);
42 if (PyErr_Occurred())
43 return -1;
44 *result = r;
45 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +000046}
Guido van Rossume15dee51995-07-18 14:12:02 +000047
48PyObject *
Fred Drake79912472000-07-09 04:06:11 +000049PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000050{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000051 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000052
Antoine Pitrouc83ea132010-05-09 14:46:46 +000053 if (o == NULL)
54 return null_error();
55 v = (PyObject *)o->ob_type;
56 Py_INCREF(v);
57 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000058}
59
Martin v. Löwis18e16552006-02-15 17:27:45 +000060Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000061PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000062{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000063 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000064
Antoine Pitrouc83ea132010-05-09 14:46:46 +000065 if (o == NULL) {
66 null_error();
67 return -1;
68 }
Guido van Rossume15dee51995-07-18 14:12:02 +000069
Antoine Pitrouc83ea132010-05-09 14:46:46 +000070 m = o->ob_type->tp_as_sequence;
71 if (m && m->sq_length)
72 return m->sq_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000073
Antoine Pitrouc83ea132010-05-09 14:46:46 +000074 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000075}
76
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000077#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000078Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000079PyObject_Length(PyObject *o)
80{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000081 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000082}
83#define PyObject_Length PyObject_Size
84
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000085
Raymond Hettinger4e2f7142007-12-06 00:56:53 +000086/* The length hint function returns a non-negative value from o.__len__()
87 or o.__length_hint__(). If those methods aren't found or return a negative
Raymond Hettingerb5163702009-02-02 21:50:13 +000088 value, then the defaultvalue is returned. If one of the calls fails,
89 this function returns -1.
Raymond Hettinger4e2f7142007-12-06 00:56:53 +000090*/
91
92Py_ssize_t
93_PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
94{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095 static PyObject *hintstrobj = NULL;
96 PyObject *ro, *hintmeth;
97 Py_ssize_t rv;
Raymond Hettinger4e2f7142007-12-06 00:56:53 +000098
Antoine Pitrouc83ea132010-05-09 14:46:46 +000099 /* try o.__len__() */
100 rv = PyObject_Size(o);
101 if (rv >= 0)
102 return rv;
103 if (PyErr_Occurred()) {
104 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
105 !PyErr_ExceptionMatches(PyExc_AttributeError))
106 return -1;
107 PyErr_Clear();
108 }
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000109
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000110 if (PyInstance_Check(o))
111 return defaultvalue;
112 /* try o.__length_hint__() */
113 hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
114 if (hintmeth == NULL) {
115 if (PyErr_Occurred())
116 return -1;
117 else
118 return defaultvalue;
119 }
120 ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
121 Py_DECREF(hintmeth);
122 if (ro == NULL) {
123 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
124 !PyErr_ExceptionMatches(PyExc_AttributeError))
125 return -1;
126 PyErr_Clear();
127 return defaultvalue;
128 }
129 rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
130 Py_DECREF(ro);
131 return rv;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000132}
133
Guido van Rossume15dee51995-07-18 14:12:02 +0000134PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000135PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000138
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000139 if (o == NULL || key == NULL)
140 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +0000141
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000142 m = o->ob_type->tp_as_mapping;
143 if (m && m->mp_subscript)
144 return m->mp_subscript(o, key);
Guido van Rossume15dee51995-07-18 14:12:02 +0000145
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000146 if (o->ob_type->tp_as_sequence) {
147 if (PyIndex_Check(key)) {
148 Py_ssize_t key_value;
149 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
150 if (key_value == -1 && PyErr_Occurred())
151 return NULL;
152 return PySequence_GetItem(o, key_value);
153 }
154 else if (o->ob_type->tp_as_sequence->sq_item)
155 return type_error("sequence index must "
156 "be integer, not '%.200s'", key);
157 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000160}
161
162int
Fred Drake79912472000-07-09 04:06:11 +0000163PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000165 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000166
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000167 if (o == NULL || key == NULL || value == NULL) {
168 null_error();
169 return -1;
170 }
171 m = o->ob_type->tp_as_mapping;
172 if (m && m->mp_ass_subscript)
173 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000174
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000175 if (o->ob_type->tp_as_sequence) {
176 if (PyIndex_Check(key)) {
177 Py_ssize_t key_value;
178 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
179 if (key_value == -1 && PyErr_Occurred())
180 return -1;
181 return PySequence_SetItem(o, key_value, value);
182 }
183 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
184 type_error("sequence index must be "
185 "integer, not '%.200s'", key);
186 return -1;
187 }
188 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000189
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000190 type_error("'%.200s' object does not support item assignment", o);
191 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000192}
193
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000194int
Fred Drake79912472000-07-09 04:06:11 +0000195PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000196{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000197 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000198
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000199 if (o == NULL || key == NULL) {
200 null_error();
201 return -1;
202 }
203 m = o->ob_type->tp_as_mapping;
204 if (m && m->mp_ass_subscript)
205 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 if (o->ob_type->tp_as_sequence) {
208 if (PyIndex_Check(key)) {
209 Py_ssize_t key_value;
210 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
211 if (key_value == -1 && PyErr_Occurred())
212 return -1;
213 return PySequence_DelItem(o, key_value);
214 }
215 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
216 type_error("sequence index must be "
217 "integer, not '%.200s'", key);
218 return -1;
219 }
220 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000221
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000222 type_error("'%.200s' object does not support item deletion", o);
223 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000224}
225
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000226int
227PyObject_DelItemString(PyObject *o, char *key)
228{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 PyObject *okey;
230 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000231
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 if (o == NULL || key == NULL) {
233 null_error();
234 return -1;
235 }
236 okey = PyString_FromString(key);
237 if (okey == NULL)
238 return -1;
239 ret = PyObject_DelItem(o, okey);
240 Py_DECREF(okey);
241 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000242}
243
Brett Cannonea229bd2006-06-06 18:08:16 +0000244int
245PyObject_AsCharBuffer(PyObject *obj,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 const char **buffer,
247 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000248{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 PyBufferProcs *pb;
250 char *pp;
251 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
254 null_error();
255 return -1;
256 }
257 pb = obj->ob_type->tp_as_buffer;
258 if (pb == NULL ||
259 pb->bf_getcharbuffer == NULL ||
260 pb->bf_getsegcount == NULL) {
261 PyErr_SetString(PyExc_TypeError,
262 "expected a character buffer object");
263 return -1;
264 }
265 if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
266 PyErr_SetString(PyExc_TypeError,
267 "expected a single-segment buffer object");
268 return -1;
269 }
270 len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
271 if (len < 0)
272 return -1;
273 *buffer = pp;
274 *buffer_len = len;
275 return 0;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000276}
Guido van Rossum4c08d552000-03-10 22:55:18 +0000277
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000278int
279PyObject_CheckReadBuffer(PyObject *obj)
280{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000281 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 if (pb == NULL ||
284 pb->bf_getreadbuffer == NULL ||
285 pb->bf_getsegcount == NULL ||
286 (*pb->bf_getsegcount)(obj, NULL) != 1)
287 return 0;
288 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000289}
290
291int PyObject_AsReadBuffer(PyObject *obj,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 const void **buffer,
293 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000294{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000295 PyBufferProcs *pb;
296 void *pp;
297 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000298
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
300 null_error();
301 return -1;
302 }
303 pb = obj->ob_type->tp_as_buffer;
304 if (pb == NULL ||
305 pb->bf_getreadbuffer == NULL ||
306 pb->bf_getsegcount == NULL) {
307 PyErr_SetString(PyExc_TypeError,
308 "expected a readable buffer object");
309 return -1;
310 }
311 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
312 PyErr_SetString(PyExc_TypeError,
313 "expected a single-segment buffer object");
314 return -1;
315 }
316 len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
317 if (len < 0)
318 return -1;
319 *buffer = pp;
320 *buffer_len = len;
321 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000322}
323
324int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 void **buffer,
326 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 PyBufferProcs *pb;
329 void*pp;
330 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
333 null_error();
334 return -1;
335 }
336 pb = obj->ob_type->tp_as_buffer;
337 if (pb == NULL ||
338 pb->bf_getwritebuffer == NULL ||
339 pb->bf_getsegcount == NULL) {
340 PyErr_SetString(PyExc_TypeError,
341 "expected a writeable buffer object");
342 return -1;
343 }
344 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
345 PyErr_SetString(PyExc_TypeError,
346 "expected a single-segment buffer object");
347 return -1;
348 }
349 len = (*pb->bf_getwritebuffer)(obj,0,&pp);
350 if (len < 0)
351 return -1;
352 *buffer = pp;
353 *buffer_len = len;
354 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000355}
356
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000357/* Buffer C-API for Python 3.0 */
358
359int
360PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
361{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 if (!PyObject_CheckBuffer(obj)) {
363 PyErr_Format(PyExc_TypeError,
364 "'%100s' does not have the buffer interface",
365 Py_TYPE(obj)->tp_name);
366 return -1;
367 }
368 return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000369}
370
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000371static int
372_IsFortranContiguous(Py_buffer *view)
373{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000374 Py_ssize_t sd, dim;
375 int i;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000376
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 if (view->ndim == 0) return 1;
378 if (view->strides == NULL) return (view->ndim == 1);
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000379
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 sd = view->itemsize;
381 if (view->ndim == 1) return (view->shape[0] == 1 ||
382 sd == view->strides[0]);
383 for (i=0; i<view->ndim; i++) {
384 dim = view->shape[i];
385 if (dim == 0) return 1;
386 if (view->strides[i] != sd) return 0;
387 sd *= dim;
388 }
389 return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000390}
391
392static int
393_IsCContiguous(Py_buffer *view)
394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 Py_ssize_t sd, dim;
396 int i;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000397
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 if (view->ndim == 0) return 1;
399 if (view->strides == NULL) return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000400
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000401 sd = view->itemsize;
402 if (view->ndim == 1) return (view->shape[0] == 1 ||
403 sd == view->strides[0]);
404 for (i=view->ndim-1; i>=0; i--) {
405 dim = view->shape[i];
406 if (dim == 0) return 1;
407 if (view->strides[i] != sd) return 0;
408 sd *= dim;
409 }
410 return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000411}
412
413int
414PyBuffer_IsContiguous(Py_buffer *view, char fort)
415{
416
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 if (view->suboffsets != NULL) return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000418
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 if (fort == 'C')
420 return _IsCContiguous(view);
421 else if (fort == 'F')
422 return _IsFortranContiguous(view);
423 else if (fort == 'A')
424 return (_IsCContiguous(view) || _IsFortranContiguous(view));
425 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000426}
427
428
429void*
430PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
431{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 char* pointer;
433 int i;
434 pointer = (char *)view->buf;
435 for (i = 0; i < view->ndim; i++) {
436 pointer += view->strides[i]*indices[i];
437 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
438 pointer = *((char**)pointer) + view->suboffsets[i];
439 }
440 }
441 return (void*)pointer;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000442}
443
444
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000445void
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000446_add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000448 int k;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000449
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000450 for (k=0; k<nd; k++) {
451 if (index[k] < shape[k]-1) {
452 index[k]++;
453 break;
454 }
455 else {
456 index[k] = 0;
457 }
458 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000459}
460
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000461void
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000462_add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 int k;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000465
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000466 for (k=nd-1; k>=0; k--) {
467 if (index[k] < shape[k]-1) {
468 index[k]++;
469 break;
470 }
471 else {
472 index[k] = 0;
473 }
474 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000475}
476
477 /* view is not checked for consistency in either of these. It is
478 assumed that the size of the buffer is view->len in
479 view->len / view->itemsize elements.
480 */
481
482int
483PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
484{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 int k;
486 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
487 Py_ssize_t *indices, elements;
488 char *dest, *ptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 if (len > view->len) {
491 len = view->len;
492 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000493
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000494 if (PyBuffer_IsContiguous(view, fort)) {
495 /* simplest copy is all that is needed */
496 memcpy(buf, view->buf, len);
497 return 0;
498 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000499
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 /* Otherwise a more elaborate scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000501
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 /* XXX(nnorwitz): need to check for overflow! */
503 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
504 if (indices == NULL) {
505 PyErr_NoMemory();
506 return -1;
507 }
508 for (k=0; k<view->ndim;k++) {
509 indices[k] = 0;
510 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000511
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000512 if (fort == 'F') {
513 addone = _add_one_to_index_F;
514 }
515 else {
516 addone = _add_one_to_index_C;
517 }
518 dest = buf;
519 /* XXX : This is not going to be the fastest code in the world
520 several optimizations are possible.
521 */
522 elements = len / view->itemsize;
523 while (elements--) {
524 addone(view->ndim, indices, view->shape);
525 ptr = PyBuffer_GetPointer(view, indices);
526 memcpy(dest, ptr, view->itemsize);
527 dest += view->itemsize;
528 }
529 PyMem_Free(indices);
530 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000531}
532
533int
534PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
535{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000536 int k;
537 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
538 Py_ssize_t *indices, elements;
539 char *src, *ptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000540
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 if (len > view->len) {
542 len = view->len;
543 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000544
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 if (PyBuffer_IsContiguous(view, fort)) {
546 /* simplest copy is all that is needed */
547 memcpy(view->buf, buf, len);
548 return 0;
549 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000550
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 /* Otherwise a more elaborate scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000552
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 /* XXX(nnorwitz): need to check for overflow! */
554 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
555 if (indices == NULL) {
556 PyErr_NoMemory();
557 return -1;
558 }
559 for (k=0; k<view->ndim;k++) {
560 indices[k] = 0;
561 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000562
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 if (fort == 'F') {
564 addone = _add_one_to_index_F;
565 }
566 else {
567 addone = _add_one_to_index_C;
568 }
569 src = buf;
570 /* XXX : This is not going to be the fastest code in the world
571 several optimizations are possible.
572 */
573 elements = len / view->itemsize;
574 while (elements--) {
575 addone(view->ndim, indices, view->shape);
576 ptr = PyBuffer_GetPointer(view, indices);
577 memcpy(ptr, src, view->itemsize);
578 src += view->itemsize;
579 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000580
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 PyMem_Free(indices);
582 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000583}
584
585int PyObject_CopyData(PyObject *dest, PyObject *src)
586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 Py_buffer view_dest, view_src;
588 int k;
589 Py_ssize_t *indices, elements;
590 char *dptr, *sptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000591
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000592 if (!PyObject_CheckBuffer(dest) ||
593 !PyObject_CheckBuffer(src)) {
594 PyErr_SetString(PyExc_TypeError,
595 "both destination and source must have the "\
596 "buffer interface");
597 return -1;
598 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000599
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
601 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
602 PyBuffer_Release(&view_dest);
603 return -1;
604 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000605
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 if (view_dest.len < view_src.len) {
607 PyErr_SetString(PyExc_BufferError,
608 "destination is too small to receive data from source");
609 PyBuffer_Release(&view_dest);
610 PyBuffer_Release(&view_src);
611 return -1;
612 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000613
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000614 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
615 PyBuffer_IsContiguous(&view_src, 'C')) ||
616 (PyBuffer_IsContiguous(&view_dest, 'F') &&
617 PyBuffer_IsContiguous(&view_src, 'F'))) {
618 /* simplest copy is all that is needed */
619 memcpy(view_dest.buf, view_src.buf, view_src.len);
620 PyBuffer_Release(&view_dest);
621 PyBuffer_Release(&view_src);
622 return 0;
623 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000624
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000625 /* Otherwise a more elaborate copy scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000626
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000627 /* XXX(nnorwitz): need to check for overflow! */
628 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
629 if (indices == NULL) {
630 PyErr_NoMemory();
631 PyBuffer_Release(&view_dest);
632 PyBuffer_Release(&view_src);
633 return -1;
634 }
635 for (k=0; k<view_src.ndim;k++) {
636 indices[k] = 0;
637 }
638 elements = 1;
639 for (k=0; k<view_src.ndim; k++) {
640 /* XXX(nnorwitz): can this overflow? */
641 elements *= view_src.shape[k];
642 }
643 while (elements--) {
644 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
645 dptr = PyBuffer_GetPointer(&view_dest, indices);
646 sptr = PyBuffer_GetPointer(&view_src, indices);
647 memcpy(dptr, sptr, view_src.itemsize);
648 }
649 PyMem_Free(indices);
650 PyBuffer_Release(&view_dest);
651 PyBuffer_Release(&view_src);
652 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000653}
654
655void
656PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 Py_ssize_t *strides, int itemsize,
658 char fort)
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000659{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000660 int k;
661 Py_ssize_t sd;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000662
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 sd = itemsize;
664 if (fort == 'F') {
665 for (k=0; k<nd; k++) {
666 strides[k] = sd;
667 sd *= shape[k];
668 }
669 }
670 else {
671 for (k=nd-1; k>=0; k--) {
672 strides[k] = sd;
673 sd *= shape[k];
674 }
675 }
676 return;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000677}
678
679int
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000680PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 int readonly, int flags)
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000682{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 if (view == NULL) return 0;
684 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
685 (readonly == 1)) {
686 PyErr_SetString(PyExc_BufferError,
687 "Object is not writable.");
688 return -1;
689 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000690
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000691 view->obj = obj;
692 if (obj)
693 Py_INCREF(obj);
694 view->buf = buf;
695 view->len = len;
696 view->readonly = readonly;
697 view->itemsize = 1;
698 view->format = NULL;
699 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
700 view->format = "B";
701 view->ndim = 1;
702 view->shape = NULL;
703 if ((flags & PyBUF_ND) == PyBUF_ND)
704 view->shape = &(view->len);
705 view->strides = NULL;
706 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
707 view->strides = &(view->itemsize);
708 view->suboffsets = NULL;
709 view->internal = NULL;
710 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000711}
712
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000713void
714PyBuffer_Release(Py_buffer *view)
715{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 PyObject *obj = view->obj;
717 if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
718 Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
719 Py_XDECREF(obj);
720 view->obj = NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000721}
722
Eric Smitha9f7d622008-02-17 19:46:49 +0000723PyObject *
724PyObject_Format(PyObject* obj, PyObject *format_spec)
725{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 PyObject *empty = NULL;
727 PyObject *result = NULL;
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000728#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000729 int spec_is_unicode;
730 int result_is_unicode;
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000731#endif
Eric Smitha9f7d622008-02-17 19:46:49 +0000732
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 /* If no format_spec is provided, use an empty string */
734 if (format_spec == NULL) {
735 empty = PyString_FromStringAndSize(NULL, 0);
736 format_spec = empty;
737 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000738
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 /* Check the format_spec type, and make sure it's str or unicode */
Hirokazu Yamamoto1e234e82009-01-25 17:46:48 +0000740#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 if (PyUnicode_Check(format_spec))
742 spec_is_unicode = 1;
743 else if (PyString_Check(format_spec))
744 spec_is_unicode = 0;
745 else {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000746#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000747 if (!PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000748#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000749 PyErr_Format(PyExc_TypeError,
750 "format expects arg 2 to be string "
751 "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
752 goto done;
753 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000754
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000755 /* Make sure the type is initialized. float gets initialized late */
756 if (Py_TYPE(obj)->tp_dict == NULL)
757 if (PyType_Ready(Py_TYPE(obj)) < 0)
758 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000759
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000760 /* Check for a __format__ method and call it. */
761 if (PyInstance_Check(obj)) {
762 /* We're an instance of a classic class */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000763 PyObject *bound_method = PyObject_GetAttrString(obj, "__format__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 if (bound_method != NULL) {
765 result = PyObject_CallFunctionObjArgs(bound_method,
766 format_spec,
767 NULL);
768 Py_DECREF(bound_method);
769 } else {
770 PyObject *self_as_str = NULL;
771 PyObject *format_method = NULL;
772 Py_ssize_t format_len;
Eric Smitha9f7d622008-02-17 19:46:49 +0000773
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000774 PyErr_Clear();
775 /* Per the PEP, convert to str (or unicode,
776 depending on the type of the format
777 specifier). For new-style classes, this
778 logic is done by object.__format__(). */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000779#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000780 if (spec_is_unicode) {
781 format_len = PyUnicode_GET_SIZE(format_spec);
782 self_as_str = PyObject_Unicode(obj);
783 } else
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000784#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 {
786 format_len = PyString_GET_SIZE(format_spec);
787 self_as_str = PyObject_Str(obj);
788 }
789 if (self_as_str == NULL)
790 goto done1;
Eric Smithd44b2fc2010-04-02 12:30:56 +0000791
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 if (format_len > 0) {
793 /* See the almost identical code in
794 typeobject.c for new-style
795 classes. */
796 if (PyErr_WarnEx(
797 PyExc_PendingDeprecationWarning,
798 "object.__format__ with a non-empty "
799 "format string is deprecated", 1)
800 < 0) {
801 goto done1;
802 }
803 /* Eventually this will become an
804 error:
805 PyErr_Format(PyExc_TypeError,
806 "non-empty format string passed to "
807 "object.__format__");
808 goto done1;
809 */
810 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000811
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 /* Then call str.__format__ on that result */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000813 format_method = PyObject_GetAttrString(self_as_str, "__format__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 if (format_method == NULL) {
815 goto done1;
816 }
817 result = PyObject_CallFunctionObjArgs(format_method,
818 format_spec,
819 NULL);
Eric Smithd44b2fc2010-04-02 12:30:56 +0000820done1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 Py_XDECREF(self_as_str);
822 Py_XDECREF(format_method);
823 if (result == NULL)
824 goto done;
825 }
826 } else {
827 /* Not an instance of a classic class, use the code
828 from py3k */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000829 static PyObject *format_cache;
Eric Smitha9f7d622008-02-17 19:46:49 +0000830
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 /* Find the (unbound!) __format__ method (a borrowed
832 reference) */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000833 PyObject *method = _PyObject_LookupSpecial(obj, "__format__",
834 &format_cache);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 if (method == NULL) {
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000836 if (!PyErr_Occurred())
837 PyErr_Format(PyExc_TypeError,
838 "Type %.100s doesn't define __format__",
839 Py_TYPE(obj)->tp_name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000840 goto done;
841 }
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000842 /* And call it. */
843 result = PyObject_CallFunctionObjArgs(method, format_spec, NULL);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000844 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000845
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000846 if (result == NULL)
847 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000848
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 /* Check the result type, and make sure it's str or unicode */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000850#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000851 if (PyUnicode_Check(result))
852 result_is_unicode = 1;
853 else if (PyString_Check(result))
854 result_is_unicode = 0;
855 else {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000856#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000857 if (!PyString_Check(result)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000858#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 PyErr_Format(PyExc_TypeError,
860 "%.100s.__format__ must return string or "
861 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
862 Py_TYPE(result)->tp_name);
863 Py_DECREF(result);
864 result = NULL;
865 goto done;
866 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000867
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000868 /* Convert to unicode, if needed. Required if spec is unicode
869 and result is str */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000870#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 if (spec_is_unicode && !result_is_unicode) {
872 PyObject *tmp = PyObject_Unicode(result);
873 /* This logic works whether or not tmp is NULL */
874 Py_DECREF(result);
875 result = tmp;
876 }
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000877#endif
Eric Smitha9f7d622008-02-17 19:46:49 +0000878
879done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000880 Py_XDECREF(empty);
881 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +0000882}
883
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000884/* Operations on numbers */
885
886int
Fred Drake79912472000-07-09 04:06:11 +0000887PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000888{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000889 return o && o->ob_type->tp_as_number &&
890 (o->ob_type->tp_as_number->nb_int ||
891 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000892}
893
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000894/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000895
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000896/* New style number protocol support */
Guido van Rossume15dee51995-07-18 14:12:02 +0000897
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000898#define NB_SLOT(x) offsetof(PyNumberMethods, x)
899#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000900 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000901#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000902 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000903
904/*
905 Calling scheme used for binary operations:
906
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000907 v w Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000908 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
910 new old v.op(v,w), coerce(v,w), v.op(v,w)
911 old new w.op(v,w), coerce(v,w), v.op(v,w)
912 old old coerce(v,w), v.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000913
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000914 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
915 v->ob_type
916
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000917 Legend:
918 -------
919 * new == new style number
920 * old == old style number
921 * Action indicates the order in which operations are tried until either
922 a valid result is produced or an error occurs.
923
924 */
925
926static PyObject *
927binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 PyObject *x;
930 binaryfunc slotv = NULL;
931 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000932
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
934 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
935 if (w->ob_type != v->ob_type &&
936 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
937 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
938 if (slotw == slotv)
939 slotw = NULL;
940 }
941 if (slotv) {
942 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
943 x = slotw(v, w);
944 if (x != Py_NotImplemented)
945 return x;
946 Py_DECREF(x); /* can't do it */
947 slotw = NULL;
948 }
949 x = slotv(v, w);
950 if (x != Py_NotImplemented)
951 return x;
952 Py_DECREF(x); /* can't do it */
953 }
954 if (slotw) {
955 x = slotw(v, w);
956 if (x != Py_NotImplemented)
957 return x;
958 Py_DECREF(x); /* can't do it */
959 }
960 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
961 int err = PyNumber_CoerceEx(&v, &w);
962 if (err < 0) {
963 return NULL;
964 }
965 if (err == 0) {
966 PyNumberMethods *mv = v->ob_type->tp_as_number;
967 if (mv) {
968 binaryfunc slot;
969 slot = NB_BINOP(mv, op_slot);
970 if (slot) {
971 x = slot(v, w);
972 Py_DECREF(v);
973 Py_DECREF(w);
974 return x;
975 }
976 }
977 /* CoerceEx incremented the reference counts */
978 Py_DECREF(v);
979 Py_DECREF(w);
980 }
981 }
982 Py_INCREF(Py_NotImplemented);
983 return Py_NotImplemented;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000984}
Guido van Rossum77660912002-04-16 16:32:50 +0000985
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000986static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000987binop_type_error(PyObject *v, PyObject *w, const char *op_name)
988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000989 PyErr_Format(PyExc_TypeError,
990 "unsupported operand type(s) for %.100s: "
991 "'%.100s' and '%.100s'",
992 op_name,
993 v->ob_type->tp_name,
994 w->ob_type->tp_name);
995 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000996}
997
998static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000999binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
1000{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 PyObject *result = binary_op1(v, w, op_slot);
1002 if (result == Py_NotImplemented) {
1003 Py_DECREF(result);
1004 return binop_type_error(v, w, op_name);
1005 }
1006 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001007}
1008
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001009
1010/*
1011 Calling scheme used for ternary operations:
1012
Guido van Rossum84675ac2001-09-29 01:05:03 +00001013 *** In some cases, w.op is called before v.op; see binary_op1. ***
1014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 v w z Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001016 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1018 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1019 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1020 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1021 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1022 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1023 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1024 old old old coerce(v,w,z), v.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001025
1026 Legend:
1027 -------
1028 * new == new style number
1029 * old == old style number
1030 * Action indicates the order in which operations are tried until either
1031 a valid result is produced or an error occurs.
1032 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1033 only if z != Py_None; if z == Py_None, then it is treated as absent
1034 variable and only coerce(v,w) is tried.
1035
1036 */
1037
1038static PyObject *
1039ternary_op(PyObject *v,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 PyObject *w,
1041 PyObject *z,
1042 const int op_slot,
1043 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +00001044{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001045 PyNumberMethods *mv, *mw, *mz;
1046 PyObject *x = NULL;
1047 ternaryfunc slotv = NULL;
1048 ternaryfunc slotw = NULL;
1049 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +00001050
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 mv = v->ob_type->tp_as_number;
1052 mw = w->ob_type->tp_as_number;
1053 if (mv != NULL && NEW_STYLE_NUMBER(v))
1054 slotv = NB_TERNOP(mv, op_slot);
1055 if (w->ob_type != v->ob_type &&
1056 mw != NULL && NEW_STYLE_NUMBER(w)) {
1057 slotw = NB_TERNOP(mw, op_slot);
1058 if (slotw == slotv)
1059 slotw = NULL;
1060 }
1061 if (slotv) {
1062 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1063 x = slotw(v, w, z);
1064 if (x != Py_NotImplemented)
1065 return x;
1066 Py_DECREF(x); /* can't do it */
1067 slotw = NULL;
1068 }
1069 x = slotv(v, w, z);
1070 if (x != Py_NotImplemented)
1071 return x;
1072 Py_DECREF(x); /* can't do it */
1073 }
1074 if (slotw) {
1075 x = slotw(v, w, z);
1076 if (x != Py_NotImplemented)
1077 return x;
1078 Py_DECREF(x); /* can't do it */
1079 }
1080 mz = z->ob_type->tp_as_number;
1081 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1082 slotz = NB_TERNOP(mz, op_slot);
1083 if (slotz == slotv || slotz == slotw)
1084 slotz = NULL;
1085 if (slotz) {
1086 x = slotz(v, w, z);
1087 if (x != Py_NotImplemented)
1088 return x;
1089 Py_DECREF(x); /* can't do it */
1090 }
1091 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001092
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001093 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1094 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1095 /* we have an old style operand, coerce */
1096 PyObject *v1, *z1, *w2, *z2;
1097 int c;
Guido van Rossum77660912002-04-16 16:32:50 +00001098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 c = PyNumber_Coerce(&v, &w);
1100 if (c != 0)
1101 goto error3;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001103 /* Special case: if the third argument is None, it is
1104 treated as absent argument and not coerced. */
1105 if (z == Py_None) {
1106 if (v->ob_type->tp_as_number) {
1107 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1108 op_slot);
1109 if (slotz)
1110 x = slotz(v, w, z);
1111 else
1112 c = -1;
1113 }
1114 else
1115 c = -1;
1116 goto error2;
1117 }
1118 v1 = v;
1119 z1 = z;
1120 c = PyNumber_Coerce(&v1, &z1);
1121 if (c != 0)
1122 goto error2;
1123 w2 = w;
1124 z2 = z1;
1125 c = PyNumber_Coerce(&w2, &z2);
1126 if (c != 0)
1127 goto error1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 if (v1->ob_type->tp_as_number != NULL) {
1130 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1131 op_slot);
1132 if (slotv)
1133 x = slotv(v1, w2, z2);
1134 else
1135 c = -1;
1136 }
1137 else
1138 c = -1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 Py_DECREF(w2);
1141 Py_DECREF(z2);
1142 error1:
1143 Py_DECREF(v1);
1144 Py_DECREF(z1);
1145 error2:
1146 Py_DECREF(v);
1147 Py_DECREF(w);
1148 error3:
1149 if (c >= 0)
1150 return x;
1151 }
Guido van Rossum5c66a262001-10-22 04:12:44 +00001152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 if (z == Py_None)
1154 PyErr_Format(
1155 PyExc_TypeError,
1156 "unsupported operand type(s) for ** or pow(): "
1157 "'%.100s' and '%.100s'",
1158 v->ob_type->tp_name,
1159 w->ob_type->tp_name);
1160 else
1161 PyErr_Format(
1162 PyExc_TypeError,
1163 "unsupported operand type(s) for pow(): "
1164 "'%.100s', '%.100s', '%.100s'",
1165 v->ob_type->tp_name,
1166 w->ob_type->tp_name,
1167 z->ob_type->tp_name);
1168 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001169}
1170
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001171#define BINARY_FUNC(func, op, op_name) \
1172 PyObject * \
1173 func(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001175 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001176
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001177BINARY_FUNC(PyNumber_Or, nb_or, "|")
1178BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1179BINARY_FUNC(PyNumber_And, nb_and, "&")
1180BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1181BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1182BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001183BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1184BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001185
1186PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001187PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001189 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1190 if (result == Py_NotImplemented) {
1191 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1192 Py_DECREF(result);
1193 if (m && m->sq_concat) {
1194 return (*m->sq_concat)(v, w);
1195 }
1196 result = binop_type_error(v, w, "+");
1197 }
1198 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001199}
1200
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001201static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001202sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001204 Py_ssize_t count;
1205 if (PyIndex_Check(n)) {
1206 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1207 if (count == -1 && PyErr_Occurred())
1208 return NULL;
1209 }
1210 else {
1211 return type_error("can't multiply sequence by "
1212 "non-int of type '%.200s'", n);
1213 }
1214 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001215}
1216
1217PyObject *
1218PyNumber_Multiply(PyObject *v, PyObject *w)
1219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1221 if (result == Py_NotImplemented) {
1222 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1223 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1224 Py_DECREF(result);
1225 if (mv && mv->sq_repeat) {
1226 return sequence_repeat(mv->sq_repeat, v, w);
1227 }
1228 else if (mw && mw->sq_repeat) {
1229 return sequence_repeat(mw->sq_repeat, w, v);
1230 }
1231 result = binop_type_error(v, w, "*");
1232 }
1233 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001234}
1235
Guido van Rossume15dee51995-07-18 14:12:02 +00001236PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001237PyNumber_FloorDivide(PyObject *v, PyObject *w)
1238{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001239 /* XXX tp_flags test */
1240 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001241}
1242
1243PyObject *
1244PyNumber_TrueDivide(PyObject *v, PyObject *w)
1245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001246 /* XXX tp_flags test */
1247 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001248}
1249
1250PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001251PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001253 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001254}
1255
1256PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001257PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001258{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001259 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001260}
1261
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001262/* Binary in-place operators */
1263
1264/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001265 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001266
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001267 - If the left hand object has the appropriate struct members, and
1268 they are filled, call the appropriate function and return the
1269 result. No coercion is done on the arguments; the left-hand object
1270 is the one the operation is performed on, and it's up to the
1271 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001272
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001273 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001274 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001275
1276 */
1277
Guido van Rossum77660912002-04-16 16:32:50 +00001278#define HASINPLACE(t) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001279 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001280
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001281static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001282binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 PyNumberMethods *mv = v->ob_type->tp_as_number;
1285 if (mv != NULL && HASINPLACE(v)) {
1286 binaryfunc slot = NB_BINOP(mv, iop_slot);
1287 if (slot) {
1288 PyObject *x = (slot)(v, w);
1289 if (x != Py_NotImplemented) {
1290 return x;
1291 }
1292 Py_DECREF(x);
1293 }
1294 }
1295 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001296}
1297
1298static PyObject *
1299binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001301{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1303 if (result == Py_NotImplemented) {
1304 Py_DECREF(result);
1305 return binop_type_error(v, w, op_name);
1306 }
1307 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001308}
1309
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001310#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 PyObject * \
1312 func(PyObject *v, PyObject *w) { \
1313 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1314 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001315
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001316INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1317INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1318INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1319INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1320INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1321INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1322INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001323
1324PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001325PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1326{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001327 /* XXX tp_flags test */
1328 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1329 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001330}
1331
1332PyObject *
1333PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1334{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001335 /* XXX tp_flags test */
1336 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1337 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001338}
1339
1340PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001341PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1342{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1344 NB_SLOT(nb_add));
1345 if (result == Py_NotImplemented) {
1346 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1347 Py_DECREF(result);
1348 if (m != NULL) {
1349 binaryfunc f = NULL;
1350 if (HASINPLACE(v))
1351 f = m->sq_inplace_concat;
1352 if (f == NULL)
1353 f = m->sq_concat;
1354 if (f != NULL)
1355 return (*f)(v, w);
1356 }
1357 result = binop_type_error(v, w, "+=");
1358 }
1359 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001360}
1361
1362PyObject *
1363PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1364{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001365 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1366 NB_SLOT(nb_multiply));
1367 if (result == Py_NotImplemented) {
1368 ssizeargfunc f = NULL;
1369 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1370 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1371 Py_DECREF(result);
1372 if (mv != NULL) {
1373 if (HASINPLACE(v))
1374 f = mv->sq_inplace_repeat;
1375 if (f == NULL)
1376 f = mv->sq_repeat;
1377 if (f != NULL)
1378 return sequence_repeat(f, v, w);
1379 }
1380 else if (mw != NULL) {
1381 /* Note that the right hand operand should not be
1382 * mutated in this case so sq_inplace_repeat is not
1383 * used. */
1384 if (mw->sq_repeat)
1385 return sequence_repeat(mw->sq_repeat, w, v);
1386 }
1387 result = binop_type_error(v, w, "*=");
1388 }
1389 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001390}
1391
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001392PyObject *
1393PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001395 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1396 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001397}
1398
1399PyObject *
1400PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1401{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001402 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1403 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1404 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1405 }
1406 else {
1407 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1408 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001409}
1410
1411
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001412/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001413
1414PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001415PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001418
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001419 if (o == NULL)
1420 return null_error();
1421 m = o->ob_type->tp_as_number;
1422 if (m && m->nb_negative)
1423 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001424
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001425 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001426}
1427
1428PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001429PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001430{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001431 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001432
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001433 if (o == NULL)
1434 return null_error();
1435 m = o->ob_type->tp_as_number;
1436 if (m && m->nb_positive)
1437 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001438
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001439 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001440}
1441
1442PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001443PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001444{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001445 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001446
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001447 if (o == NULL)
1448 return null_error();
1449 m = o->ob_type->tp_as_number;
1450 if (m && m->nb_invert)
1451 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001452
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001454}
1455
1456PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001457PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001458{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001460
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 if (o == NULL)
1462 return null_error();
1463 m = o->ob_type->tp_as_number;
1464 if (m && m->nb_absolute)
1465 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001466
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001467 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001468}
1469
Guido van Rossum9e896b32000-04-05 20:11:21 +00001470/* Add a check for embedded NULL-bytes in the argument. */
1471static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001472int_from_string(const char *s, Py_ssize_t len)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474 char *end;
1475 PyObject *x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 x = PyInt_FromString((char*)s, &end, 10);
1478 if (x == NULL)
1479 return NULL;
1480 if (end != s + len) {
1481 PyErr_SetString(PyExc_ValueError,
1482 "null byte in argument for int()");
1483 Py_DECREF(x);
1484 return NULL;
1485 }
1486 return x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001487}
1488
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001489/* Return a Python Int or Long from the object item
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001490 Raise TypeError if the result is not an int-or-long
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 or if the object cannot be interpreted as an index.
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001492*/
1493PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001494PyNumber_Index(PyObject *item)
1495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 PyObject *result = NULL;
1497 if (item == NULL)
1498 return null_error();
1499 if (PyInt_Check(item) || PyLong_Check(item)) {
1500 Py_INCREF(item);
1501 return item;
1502 }
1503 if (PyIndex_Check(item)) {
1504 result = item->ob_type->tp_as_number->nb_index(item);
1505 if (result &&
1506 !PyInt_Check(result) && !PyLong_Check(result)) {
1507 PyErr_Format(PyExc_TypeError,
1508 "__index__ returned non-(int,long) " \
1509 "(type %.200s)",
1510 result->ob_type->tp_name);
1511 Py_DECREF(result);
1512 return NULL;
1513 }
1514 }
1515 else {
1516 PyErr_Format(PyExc_TypeError,
1517 "'%.200s' object cannot be interpreted "
1518 "as an index", item->ob_type->tp_name);
1519 }
1520 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001521}
1522
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001523/* Return an error on Overflow only if err is not NULL*/
1524
1525Py_ssize_t
1526PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001528 Py_ssize_t result;
1529 PyObject *runerr;
1530 PyObject *value = PyNumber_Index(item);
1531 if (value == NULL)
1532 return -1;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001534 /* We're done if PyInt_AsSsize_t() returns without error. */
1535 result = PyInt_AsSsize_t(value);
1536 if (result != -1 || !(runerr = PyErr_Occurred()))
1537 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 /* Error handling code -- only manage OverflowError differently */
1540 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1541 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 PyErr_Clear();
1544 /* If no error-handling desired then the default clipping
1545 is sufficient.
1546 */
1547 if (!err) {
1548 assert(PyLong_Check(value));
1549 /* Whether or not it is less than or equal to
1550 zero is determined by the sign of ob_size
1551 */
1552 if (_PyLong_Sign(value) < 0)
1553 result = PY_SSIZE_T_MIN;
1554 else
1555 result = PY_SSIZE_T_MAX;
1556 }
1557 else {
1558 /* Otherwise replace the error with caller's error object. */
1559 PyErr_Format(err,
1560 "cannot fit '%.200s' into an index-sized integer",
1561 item->ob_type->tp_name);
1562 }
1563
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001564 finish:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001565 Py_DECREF(value);
1566 return result;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001567}
1568
1569
Guido van Rossume15dee51995-07-18 14:12:02 +00001570PyObject *
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001571_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1572{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001573 const char *type_name;
1574 static PyObject *int_name = NULL;
1575 if (int_name == NULL) {
1576 int_name = PyString_InternFromString("__int__");
1577 if (int_name == NULL)
1578 return NULL;
1579 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001581 if (integral && (!PyInt_Check(integral) &&
1582 !PyLong_Check(integral))) {
1583 /* Don't go through tp_as_number->nb_int to avoid
1584 hitting the classic class fallback to __trunc__. */
1585 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1586 if (int_func == NULL) {
1587 PyErr_Clear(); /* Raise a different error. */
1588 goto non_integral_error;
1589 }
1590 Py_DECREF(integral);
1591 integral = PyEval_CallObject(int_func, NULL);
1592 Py_DECREF(int_func);
1593 if (integral && (!PyInt_Check(integral) &&
1594 !PyLong_Check(integral))) {
1595 goto non_integral_error;
1596 }
1597 }
1598 return integral;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001599
1600non_integral_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001601 if (PyInstance_Check(integral)) {
1602 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1603 ->in_class->cl_name);
1604 }
1605 else {
1606 type_name = integral->ob_type->tp_name;
1607 }
1608 PyErr_Format(PyExc_TypeError, error_format, type_name);
1609 Py_DECREF(integral);
1610 return NULL;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001611}
1612
1613
1614PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001615PyNumber_Int(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001616{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001617 PyNumberMethods *m;
1618 static PyObject *trunc_name = NULL;
1619 PyObject *trunc_func;
1620 const char *buffer;
1621 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001622
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001623 if (trunc_name == NULL) {
1624 trunc_name = PyString_InternFromString("__trunc__");
1625 if (trunc_name == NULL)
1626 return NULL;
1627 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001628
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001629 if (o == NULL)
1630 return null_error();
1631 if (PyInt_CheckExact(o)) {
1632 Py_INCREF(o);
1633 return o;
1634 }
1635 m = o->ob_type->tp_as_number;
1636 if (m && m->nb_int) { /* This should include subclasses of int */
1637 /* Classic classes always take this branch. */
1638 PyObject *res = m->nb_int(o);
1639 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1640 PyErr_Format(PyExc_TypeError,
1641 "__int__ returned non-int (type %.200s)",
1642 res->ob_type->tp_name);
1643 Py_DECREF(res);
1644 return NULL;
1645 }
1646 return res;
1647 }
1648 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1649 PyIntObject *io = (PyIntObject*)o;
1650 return PyInt_FromLong(io->ob_ival);
1651 }
1652 trunc_func = PyObject_GetAttr(o, trunc_name);
1653 if (trunc_func) {
1654 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1655 Py_DECREF(trunc_func);
1656 /* __trunc__ is specified to return an Integral type, but
1657 int() needs to return an int. */
1658 return _PyNumber_ConvertIntegralToInt(
1659 truncated,
1660 "__trunc__ returned non-Integral (type %.200s)");
1661 }
1662 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001663
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001664 if (PyString_Check(o))
1665 return int_from_string(PyString_AS_STRING(o),
1666 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001667#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 if (PyUnicode_Check(o))
1669 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1670 PyUnicode_GET_SIZE(o),
1671 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001672#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001673 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1674 return int_from_string((char*)buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001676 return type_error("int() argument must be a string or a "
1677 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001678}
1679
Guido van Rossum9e896b32000-04-05 20:11:21 +00001680/* Add a check for embedded NULL-bytes in the argument. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001681static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001682long_from_string(const char *s, Py_ssize_t len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001683{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001684 char *end;
1685 PyObject *x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001687 x = PyLong_FromString((char*)s, &end, 10);
1688 if (x == NULL)
1689 return NULL;
1690 if (end != s + len) {
1691 PyErr_SetString(PyExc_ValueError,
1692 "null byte in argument for long()");
1693 Py_DECREF(x);
1694 return NULL;
1695 }
1696 return x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001697}
1698
Guido van Rossume15dee51995-07-18 14:12:02 +00001699PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001700PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001702 PyNumberMethods *m;
1703 static PyObject *trunc_name = NULL;
1704 PyObject *trunc_func;
1705 const char *buffer;
1706 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001708 if (trunc_name == NULL) {
1709 trunc_name = PyString_InternFromString("__trunc__");
1710 if (trunc_name == NULL)
1711 return NULL;
1712 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001714 if (o == NULL)
1715 return null_error();
1716 m = o->ob_type->tp_as_number;
1717 if (m && m->nb_long) { /* This should include subclasses of long */
1718 /* Classic classes always take this branch. */
1719 PyObject *res = m->nb_long(o);
1720 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1721 PyErr_Format(PyExc_TypeError,
1722 "__long__ returned non-long (type %.200s)",
1723 res->ob_type->tp_name);
1724 Py_DECREF(res);
1725 return NULL;
1726 }
1727 return res;
1728 }
1729 if (PyLong_Check(o)) /* A long subclass without nb_long */
1730 return _PyLong_Copy((PyLongObject *)o);
1731 trunc_func = PyObject_GetAttr(o, trunc_name);
1732 if (trunc_func) {
1733 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1734 PyObject *int_instance;
1735 Py_DECREF(trunc_func);
1736 /* __trunc__ is specified to return an Integral type,
1737 but long() needs to return a long. */
1738 int_instance = _PyNumber_ConvertIntegralToInt(
1739 truncated,
1740 "__trunc__ returned non-Integral (type %.200s)");
1741 if (int_instance && PyInt_Check(int_instance)) {
1742 /* Make sure that long() returns a long instance. */
1743 long value = PyInt_AS_LONG(int_instance);
1744 Py_DECREF(int_instance);
1745 return PyLong_FromLong(value);
1746 }
1747 return int_instance;
1748 }
1749 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 if (PyString_Check(o))
1752 /* need to do extra error checking that PyLong_FromString()
1753 * doesn't do. In particular long('9.5') must raise an
1754 * exception, not truncate the float.
1755 */
1756 return long_from_string(PyString_AS_STRING(o),
1757 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001758#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 if (PyUnicode_Check(o))
1760 /* The above check is done in PyLong_FromUnicode(). */
1761 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1762 PyUnicode_GET_SIZE(o),
1763 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001764#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1766 return long_from_string(buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 return type_error("long() argument must be a string or a "
1769 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001770}
1771
1772PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001773PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001774{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001776
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 if (o == NULL)
1778 return null_error();
1779 m = o->ob_type->tp_as_number;
1780 if (m && m->nb_float) { /* This should include subclasses of float */
1781 PyObject *res = m->nb_float(o);
1782 if (res && !PyFloat_Check(res)) {
1783 PyErr_Format(PyExc_TypeError,
1784 "__float__ returned non-float (type %.200s)",
1785 res->ob_type->tp_name);
1786 Py_DECREF(res);
1787 return NULL;
1788 }
1789 return res;
1790 }
1791 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1792 PyFloatObject *po = (PyFloatObject *)o;
1793 return PyFloat_FromDouble(po->ob_fval);
1794 }
1795 return PyFloat_FromString(o, NULL);
Guido van Rossume15dee51995-07-18 14:12:02 +00001796}
1797
Eric Smith5e527eb2008-02-10 01:36:53 +00001798PyObject *
1799PyNumber_ToBase(PyObject *n, int base)
1800{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 PyObject *res = NULL;
1802 PyObject *index = PyNumber_Index(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001804 if (!index)
1805 return NULL;
1806 if (PyLong_Check(index))
1807 res = _PyLong_Format(index, base, 0, 1);
1808 else if (PyInt_Check(index))
1809 res = _PyInt_Format((PyIntObject*)index, base, 1);
1810 else
1811 /* It should not be possible to get here, as
1812 PyNumber_Index already has a check for the same
1813 condition */
1814 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1815 "int or long");
1816 Py_DECREF(index);
1817 return res;
Eric Smith5e527eb2008-02-10 01:36:53 +00001818}
1819
1820
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001821/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001822
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001823int
Fred Drake79912472000-07-09 04:06:11 +00001824PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001825{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001826 if (s == NULL)
1827 return 0;
1828 if (PyInstance_Check(s))
1829 return PyObject_HasAttrString(s, "__getitem__");
1830 if (PyDict_Check(s))
1831 return 0;
1832 return s->ob_type->tp_as_sequence &&
1833 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001834}
1835
Martin v. Löwis18e16552006-02-15 17:27:45 +00001836Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001837PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001838{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001839 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001841 if (s == NULL) {
1842 null_error();
1843 return -1;
1844 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001845
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001846 m = s->ob_type->tp_as_sequence;
1847 if (m && m->sq_length)
1848 return m->sq_length(s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001849
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001850 type_error("object of type '%.200s' has no len()", s);
1851 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001852}
1853
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001854#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001855Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001856PySequence_Length(PyObject *s)
1857{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001859}
1860#define PySequence_Length PySequence_Size
1861
Guido van Rossume15dee51995-07-18 14:12:02 +00001862PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001863PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001864{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001865 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001866
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 if (s == NULL || o == NULL)
1868 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001870 m = s->ob_type->tp_as_sequence;
1871 if (m && m->sq_concat)
1872 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 /* Instances of user classes defining an __add__() method only
1875 have an nb_add slot, not an sq_concat slot. So we fall back
1876 to nb_add if both arguments appear to be sequences. */
1877 if (PySequence_Check(s) && PySequence_Check(o)) {
1878 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1879 if (result != Py_NotImplemented)
1880 return result;
1881 Py_DECREF(result);
1882 }
1883 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001884}
1885
1886PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001887PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001888{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 if (o == NULL)
1892 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 m = o->ob_type->tp_as_sequence;
1895 if (m && m->sq_repeat)
1896 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 /* Instances of user classes defining a __mul__() method only
1899 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1900 to nb_multiply if o appears to be a sequence. */
1901 if (PySequence_Check(o)) {
1902 PyObject *n, *result;
1903 n = PyInt_FromSsize_t(count);
1904 if (n == NULL)
1905 return NULL;
1906 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1907 Py_DECREF(n);
1908 if (result != Py_NotImplemented)
1909 return result;
1910 Py_DECREF(result);
1911 }
1912 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001913}
1914
1915PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001916PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1917{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001919
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 if (s == NULL || o == NULL)
1921 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001923 m = s->ob_type->tp_as_sequence;
1924 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1925 return m->sq_inplace_concat(s, o);
1926 if (m && m->sq_concat)
1927 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001928
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 if (PySequence_Check(s) && PySequence_Check(o)) {
1930 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1931 NB_SLOT(nb_add));
1932 if (result != Py_NotImplemented)
1933 return result;
1934 Py_DECREF(result);
1935 }
1936 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001937}
1938
1939PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001940PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001943
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001944 if (o == NULL)
1945 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001947 m = o->ob_type->tp_as_sequence;
1948 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1949 return m->sq_inplace_repeat(o, count);
1950 if (m && m->sq_repeat)
1951 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 if (PySequence_Check(o)) {
1954 PyObject *n, *result;
1955 n = PyInt_FromSsize_t(count);
1956 if (n == NULL)
1957 return NULL;
1958 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1959 NB_SLOT(nb_multiply));
1960 Py_DECREF(n);
1961 if (result != Py_NotImplemented)
1962 return result;
1963 Py_DECREF(result);
1964 }
1965 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001966}
1967
1968PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001969PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001970{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001972
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001973 if (s == NULL)
1974 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001975
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001976 m = s->ob_type->tp_as_sequence;
1977 if (m && m->sq_item) {
1978 if (i < 0) {
1979 if (m->sq_length) {
1980 Py_ssize_t l = (*m->sq_length)(s);
1981 if (l < 0)
1982 return NULL;
1983 i += l;
1984 }
1985 }
1986 return m->sq_item(s, i);
1987 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001988
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001989 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001990}
1991
1992PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001993PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001994{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001995 PySequenceMethods *m;
1996 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001997
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001998 if (!s) return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002000 m = s->ob_type->tp_as_sequence;
2001 if (m && m->sq_slice) {
2002 if (i1 < 0 || i2 < 0) {
2003 if (m->sq_length) {
2004 Py_ssize_t l = (*m->sq_length)(s);
2005 if (l < 0)
2006 return NULL;
2007 if (i1 < 0)
2008 i1 += l;
2009 if (i2 < 0)
2010 i2 += l;
2011 }
2012 }
2013 return m->sq_slice(s, i1, i2);
2014 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
2015 PyObject *res;
2016 PyObject *slice = _PySlice_FromIndices(i1, i2);
2017 if (!slice)
2018 return NULL;
2019 res = mp->mp_subscript(s, slice);
2020 Py_DECREF(slice);
2021 return res;
2022 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002024 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00002025}
2026
2027int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002028PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002029{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002032 if (s == NULL) {
2033 null_error();
2034 return -1;
2035 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002037 m = s->ob_type->tp_as_sequence;
2038 if (m && m->sq_ass_item) {
2039 if (i < 0) {
2040 if (m->sq_length) {
2041 Py_ssize_t l = (*m->sq_length)(s);
2042 if (l < 0)
2043 return -1;
2044 i += l;
2045 }
2046 }
2047 return m->sq_ass_item(s, i, o);
2048 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002049
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002050 type_error("'%.200s' object does not support item assignment", s);
2051 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002052}
2053
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002054int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002055PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002056{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002057 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002058
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 if (s == NULL) {
2060 null_error();
2061 return -1;
2062 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 m = s->ob_type->tp_as_sequence;
2065 if (m && m->sq_ass_item) {
2066 if (i < 0) {
2067 if (m->sq_length) {
2068 Py_ssize_t l = (*m->sq_length)(s);
2069 if (l < 0)
2070 return -1;
2071 i += l;
2072 }
2073 }
2074 return m->sq_ass_item(s, i, (PyObject *)NULL);
2075 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002077 type_error("'%.200s' object doesn't support item deletion", s);
2078 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002079}
2080
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002081int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002082PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002083{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002084 PySequenceMethods *m;
2085 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00002086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002087 if (s == NULL) {
2088 null_error();
2089 return -1;
2090 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002091
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002092 m = s->ob_type->tp_as_sequence;
2093 if (m && m->sq_ass_slice) {
2094 if (i1 < 0 || i2 < 0) {
2095 if (m->sq_length) {
2096 Py_ssize_t l = (*m->sq_length)(s);
2097 if (l < 0)
2098 return -1;
2099 if (i1 < 0)
2100 i1 += l;
2101 if (i2 < 0)
2102 i2 += l;
2103 }
2104 }
2105 return m->sq_ass_slice(s, i1, i2, o);
2106 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2107 int res;
2108 PyObject *slice = _PySlice_FromIndices(i1, i2);
2109 if (!slice)
2110 return -1;
2111 res = mp->mp_ass_subscript(s, slice, o);
2112 Py_DECREF(slice);
2113 return res;
2114 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00002115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002116 type_error("'%.200s' object doesn't support slice assignment", s);
2117 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002118}
2119
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002120int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002121PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002122{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002123 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 if (s == NULL) {
2126 null_error();
2127 return -1;
2128 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002129
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002130 m = s->ob_type->tp_as_sequence;
2131 if (m && m->sq_ass_slice) {
2132 if (i1 < 0 || i2 < 0) {
2133 if (m->sq_length) {
2134 Py_ssize_t l = (*m->sq_length)(s);
2135 if (l < 0)
2136 return -1;
2137 if (i1 < 0)
2138 i1 += l;
2139 if (i2 < 0)
2140 i2 += l;
2141 }
2142 }
2143 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2144 }
2145 type_error("'%.200s' object doesn't support slice deletion", s);
2146 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002147}
2148
Guido van Rossume15dee51995-07-18 14:12:02 +00002149PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002150PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00002151{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002152 PyObject *it; /* iter(v) */
2153 Py_ssize_t n; /* guess for result tuple size */
2154 PyObject *result = NULL;
2155 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00002156
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002157 if (v == NULL)
2158 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002159
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002160 /* Special-case the common tuple and list cases, for efficiency. */
2161 if (PyTuple_CheckExact(v)) {
2162 /* Note that we can't know whether it's safe to return
2163 a tuple *subclass* instance as-is, hence the restriction
2164 to exact tuples here. In contrast, lists always make
2165 a copy, so there's no need for exactness below. */
2166 Py_INCREF(v);
2167 return v;
2168 }
2169 if (PyList_Check(v))
2170 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002172 /* Get iterator. */
2173 it = PyObject_GetIter(v);
2174 if (it == NULL)
2175 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002177 /* Guess result size and allocate space. */
2178 n = _PyObject_LengthHint(v, 10);
2179 if (n == -1)
2180 goto Fail;
2181 result = PyTuple_New(n);
2182 if (result == NULL)
2183 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002185 /* Fill the tuple. */
2186 for (j = 0; ; ++j) {
2187 PyObject *item = PyIter_Next(it);
2188 if (item == NULL) {
2189 if (PyErr_Occurred())
2190 goto Fail;
2191 break;
2192 }
2193 if (j >= n) {
2194 Py_ssize_t oldn = n;
2195 /* The over-allocation strategy can grow a bit faster
2196 than for lists because unlike lists the
2197 over-allocation isn't permanent -- we reclaim
2198 the excess before the end of this routine.
2199 So, grow by ten and then add 25%.
2200 */
2201 n += 10;
2202 n += n >> 2;
2203 if (n < oldn) {
2204 /* Check for overflow */
2205 PyErr_NoMemory();
2206 Py_DECREF(item);
2207 goto Fail;
2208 }
2209 if (_PyTuple_Resize(&result, n) != 0) {
2210 Py_DECREF(item);
2211 goto Fail;
2212 }
2213 }
2214 PyTuple_SET_ITEM(result, j, item);
2215 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002216
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 /* Cut tuple back if guess was too large. */
2218 if (j < n &&
2219 _PyTuple_Resize(&result, j) != 0)
2220 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002222 Py_DECREF(it);
2223 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002224
2225Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 Py_XDECREF(result);
2227 Py_DECREF(it);
2228 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002229}
2230
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002231PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002232PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002233{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002234 PyObject *result; /* result list */
2235 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002236
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002237 if (v == NULL)
2238 return null_error();
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002240 result = PyList_New(0);
2241 if (result == NULL)
2242 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002243
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002244 rv = _PyList_Extend((PyListObject *)result, v);
2245 if (rv == NULL) {
2246 Py_DECREF(result);
2247 return NULL;
2248 }
2249 Py_DECREF(rv);
2250 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002251}
2252
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002253PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002254PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002257
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002258 if (v == NULL)
2259 return null_error();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002260
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002261 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2262 Py_INCREF(v);
2263 return v;
2264 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002265
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002266 it = PyObject_GetIter(v);
2267 if (it == NULL) {
2268 if (PyErr_ExceptionMatches(PyExc_TypeError))
2269 PyErr_SetString(PyExc_TypeError, m);
2270 return NULL;
2271 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002272
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002273 v = PySequence_List(it);
2274 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002277}
2278
Tim Peters16a77ad2001-09-08 04:00:12 +00002279/* Iterate over seq. Result depends on the operation:
2280 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00002281 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002282 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002283 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2284*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002285Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002286_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002287{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002288 Py_ssize_t n;
2289 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2290 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002291
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 if (seq == NULL || obj == NULL) {
2293 null_error();
2294 return -1;
2295 }
Tim Peters75f8e352001-05-05 11:33:43 +00002296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002297 it = PyObject_GetIter(seq);
2298 if (it == NULL) {
2299 type_error("argument of type '%.200s' is not iterable", seq);
2300 return -1;
2301 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002302
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002303 n = wrapped = 0;
2304 for (;;) {
2305 int cmp;
2306 PyObject *item = PyIter_Next(it);
2307 if (item == NULL) {
2308 if (PyErr_Occurred())
2309 goto Fail;
2310 break;
2311 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2314 Py_DECREF(item);
2315 if (cmp < 0)
2316 goto Fail;
2317 if (cmp > 0) {
2318 switch (operation) {
2319 case PY_ITERSEARCH_COUNT:
2320 if (n == PY_SSIZE_T_MAX) {
2321 PyErr_SetString(PyExc_OverflowError,
2322 "count exceeds C integer size");
2323 goto Fail;
2324 }
2325 ++n;
2326 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002327
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002328 case PY_ITERSEARCH_INDEX:
2329 if (wrapped) {
2330 PyErr_SetString(PyExc_OverflowError,
2331 "index exceeds C integer size");
2332 goto Fail;
2333 }
2334 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002335
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002336 case PY_ITERSEARCH_CONTAINS:
2337 n = 1;
2338 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 default:
2341 assert(!"unknown operation");
2342 }
2343 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002344
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002345 if (operation == PY_ITERSEARCH_INDEX) {
2346 if (n == PY_SSIZE_T_MAX)
2347 wrapped = 1;
2348 ++n;
2349 }
2350 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002352 if (operation != PY_ITERSEARCH_INDEX)
2353 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002355 PyErr_SetString(PyExc_ValueError,
2356 "sequence.index(x): x not in sequence");
2357 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002358Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 n = -1;
2360 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002361Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002362 Py_DECREF(it);
2363 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002364
Guido van Rossume15dee51995-07-18 14:12:02 +00002365}
2366
Tim Peters16a77ad2001-09-08 04:00:12 +00002367/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002368Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002369PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002370{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002372}
2373
Tim Peterscb8d3682001-05-05 21:05:01 +00002374/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002375 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002376 */
2377int
2378PySequence_Contains(PyObject *seq, PyObject *ob)
2379{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002380 Py_ssize_t result;
2381 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2382 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2383 if (sqm != NULL && sqm->sq_contains != NULL)
2384 return (*sqm->sq_contains)(seq, ob);
2385 }
2386 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2387 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002388}
2389
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002390/* Backwards compatibility */
2391#undef PySequence_In
2392int
Fred Drake79912472000-07-09 04:06:11 +00002393PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002396}
2397
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002398Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002399PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002400{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002401 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002402}
2403
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002404/* Operations on mappings */
2405
2406int
Fred Drake79912472000-07-09 04:06:11 +00002407PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002408{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002409 if (o && PyInstance_Check(o))
2410 return PyObject_HasAttrString(o, "__getitem__");
Raymond Hettingere2eda602004-04-04 08:51:41 +00002411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002412 return o && o->ob_type->tp_as_mapping &&
2413 o->ob_type->tp_as_mapping->mp_subscript &&
2414 !(o->ob_type->tp_as_sequence &&
2415 o->ob_type->tp_as_sequence->sq_slice);
Guido van Rossume15dee51995-07-18 14:12:02 +00002416}
2417
Martin v. Löwis18e16552006-02-15 17:27:45 +00002418Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002419PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002420{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002421 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002423 if (o == NULL) {
2424 null_error();
2425 return -1;
2426 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002428 m = o->ob_type->tp_as_mapping;
2429 if (m && m->mp_length)
2430 return m->mp_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00002431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002432 type_error("object of type '%.200s' has no len()", o);
2433 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002434}
2435
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002436#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002437Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002438PyMapping_Length(PyObject *o)
2439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002441}
2442#define PyMapping_Length PyMapping_Size
2443
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002444PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002445PyMapping_GetItemString(PyObject *o, char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002446{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002447 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002449 if (key == NULL)
2450 return null_error();
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002451
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002452 okey = PyString_FromString(key);
2453 if (okey == NULL)
2454 return NULL;
2455 r = PyObject_GetItem(o, okey);
2456 Py_DECREF(okey);
2457 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002458}
2459
2460int
Fred Drake79912472000-07-09 04:06:11 +00002461PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002463 PyObject *okey;
2464 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 if (key == NULL) {
2467 null_error();
2468 return -1;
2469 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 okey = PyString_FromString(key);
2472 if (okey == NULL)
2473 return -1;
2474 r = PyObject_SetItem(o, okey, value);
2475 Py_DECREF(okey);
2476 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002477}
2478
2479int
Fred Drake79912472000-07-09 04:06:11 +00002480PyMapping_HasKeyString(PyObject *o, char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002481{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002482 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002483
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002484 v = PyMapping_GetItemString(o, key);
2485 if (v) {
2486 Py_DECREF(v);
2487 return 1;
2488 }
2489 PyErr_Clear();
2490 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002491}
2492
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002493int
Fred Drake79912472000-07-09 04:06:11 +00002494PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 v = PyObject_GetItem(o, key);
2499 if (v) {
2500 Py_DECREF(v);
2501 return 1;
2502 }
2503 PyErr_Clear();
2504 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002505}
2506
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002507/* Operations on callable objects */
2508
2509/* XXX PyCallable_Check() is in object.c */
2510
Guido van Rossume15dee51995-07-18 14:12:02 +00002511PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002512PyObject_CallObject(PyObject *o, PyObject *a)
Guido van Rossume15dee51995-07-18 14:12:02 +00002513{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002514 return PyEval_CallObjectWithKeywords(o, a, NULL);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002515}
Guido van Rossume15dee51995-07-18 14:12:02 +00002516
2517PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2519{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002520 ternaryfunc call;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 if ((call = func->ob_type->tp_call) != NULL) {
2523 PyObject *result;
2524 if (Py_EnterRecursiveCall(" while calling a Python object"))
2525 return NULL;
2526 result = (*call)(func, arg, kw);
2527 Py_LeaveRecursiveCall();
2528 if (result == NULL && !PyErr_Occurred())
2529 PyErr_SetString(
2530 PyExc_SystemError,
2531 "NULL result without error in PyObject_Call");
2532 return result;
2533 }
2534 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2535 func->ob_type->tp_name);
2536 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537}
2538
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002539static PyObject*
2540call_function_tail(PyObject *callable, PyObject *args)
2541{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002542 PyObject *retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002543
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002544 if (args == NULL)
2545 return NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002546
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002547 if (!PyTuple_Check(args)) {
2548 PyObject *a;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002549
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002550 a = PyTuple_New(1);
2551 if (a == NULL) {
2552 Py_DECREF(args);
2553 return NULL;
2554 }
2555 PyTuple_SET_ITEM(a, 0, args);
2556 args = a;
2557 }
2558 retval = PyObject_Call(callable, args, NULL);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002560 Py_DECREF(args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002561
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002562 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002563}
2564
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565PyObject *
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002566PyObject_CallFunction(PyObject *callable, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002568 va_list va;
2569 PyObject *args;
Guido van Rossume15dee51995-07-18 14:12:02 +00002570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002571 if (callable == NULL)
2572 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002574 if (format && *format) {
2575 va_start(va, format);
2576 args = Py_VaBuildValue(format, va);
2577 va_end(va);
2578 }
2579 else
2580 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002581
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002582 return call_function_tail(callable, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002583}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002584
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002585PyObject *
2586_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2587{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002588 va_list va;
2589 PyObject *args;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002591 if (callable == NULL)
2592 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002593
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002594 if (format && *format) {
2595 va_start(va, format);
2596 args = _Py_VaBuildValue_SizeT(format, va);
2597 va_end(va);
2598 }
2599 else
2600 args = PyTuple_New(0);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002601
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 return call_function_tail(callable, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002603}
2604
2605PyObject *
Guido van Rossume15dee51995-07-18 14:12:02 +00002606PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002608 va_list va;
2609 PyObject *args;
2610 PyObject *func = NULL;
2611 PyObject *retval = NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002612
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002613 if (o == NULL || name == NULL)
2614 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002615
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002616 func = PyObject_GetAttrString(o, name);
2617 if (func == NULL) {
2618 PyErr_SetString(PyExc_AttributeError, name);
2619 return 0;
2620 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002622 if (!PyCallable_Check(func)) {
2623 type_error("attribute of type '%.200s' is not callable", func);
2624 goto exit;
2625 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002627 if (format && *format) {
2628 va_start(va, format);
2629 args = Py_VaBuildValue(format, va);
2630 va_end(va);
2631 }
2632 else
2633 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002634
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002635 retval = call_function_tail(func, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002636
Michael W. Hudson0edc7a02005-07-12 10:21:19 +00002637 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002638 /* args gets consumed in call_function_tail */
2639 Py_XDECREF(func);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002641 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002642}
2643
2644PyObject *
2645_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2646{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002647 va_list va;
2648 PyObject *args;
2649 PyObject *func = NULL;
2650 PyObject *retval = NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002652 if (o == NULL || name == NULL)
2653 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002655 func = PyObject_GetAttrString(o, name);
2656 if (func == NULL) {
2657 PyErr_SetString(PyExc_AttributeError, name);
2658 return 0;
2659 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 if (!PyCallable_Check(func)) {
2662 type_error("attribute of type '%.200s' is not callable", func);
2663 goto exit;
2664 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 if (format && *format) {
2667 va_start(va, format);
2668 args = _Py_VaBuildValue_SizeT(format, va);
2669 va_end(va);
2670 }
2671 else
2672 args = PyTuple_New(0);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002673
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002674 retval = call_function_tail(func, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002675
2676 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002677 /* args gets consumed in call_function_tail */
2678 Py_XDECREF(func);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002679
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002680 return retval;
Guido van Rossume15dee51995-07-18 14:12:02 +00002681}
Guido van Rossum823649d2001-03-21 18:40:58 +00002682
2683
Fred Drakeb421b8c2001-10-26 16:21:32 +00002684static PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002685objargs_mktuple(va_list va)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002686{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 int i, n = 0;
2688 va_list countva;
2689 PyObject *result, *tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002690
2691#ifdef VA_LIST_IS_ARRAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 memcpy(countva, va, sizeof(va_list));
Fred Drakeb421b8c2001-10-26 16:21:32 +00002693#else
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002694#ifdef __va_copy
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002695 __va_copy(countva, va);
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002696#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002697 countva = va;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002698#endif
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002699#endif
Fred Drakeb421b8c2001-10-26 16:21:32 +00002700
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002701 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2702 ++n;
2703 result = PyTuple_New(n);
2704 if (result != NULL && n > 0) {
2705 for (i = 0; i < n; ++i) {
2706 tmp = (PyObject *)va_arg(va, PyObject *);
2707 PyTuple_SET_ITEM(result, i, tmp);
2708 Py_INCREF(tmp);
2709 }
2710 }
2711 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002712}
2713
2714PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002715PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002716{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002717 PyObject *args, *tmp;
2718 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002719
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 if (callable == NULL || name == NULL)
2721 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002723 callable = PyObject_GetAttr(callable, name);
2724 if (callable == NULL)
2725 return NULL;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002727 /* count the args */
2728 va_start(vargs, name);
2729 args = objargs_mktuple(vargs);
2730 va_end(vargs);
2731 if (args == NULL) {
2732 Py_DECREF(callable);
2733 return NULL;
2734 }
2735 tmp = PyObject_Call(callable, args, NULL);
2736 Py_DECREF(args);
2737 Py_DECREF(callable);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002739 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002740}
2741
2742PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002743PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002744{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002745 PyObject *args, *tmp;
2746 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002748 if (callable == NULL)
2749 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 /* count the args */
2752 va_start(vargs, callable);
2753 args = objargs_mktuple(vargs);
2754 va_end(vargs);
2755 if (args == NULL)
2756 return NULL;
2757 tmp = PyObject_Call(callable, args, NULL);
2758 Py_DECREF(args);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002761}
2762
2763
Guido van Rossum823649d2001-03-21 18:40:58 +00002764/* isinstance(), issubclass() */
2765
Barry Warsawf16951c2002-04-23 22:45:44 +00002766/* abstract_get_bases() has logically 4 return states, with a sort of 0th
2767 * state that will almost never happen.
2768 *
2769 * 0. creating the __bases__ static string could get a MemoryError
2770 * 1. getattr(cls, '__bases__') could raise an AttributeError
2771 * 2. getattr(cls, '__bases__') could raise some other exception
2772 * 3. getattr(cls, '__bases__') could return a tuple
2773 * 4. getattr(cls, '__bases__') could return something other than a tuple
2774 *
2775 * Only state #3 is a non-error state and only it returns a non-NULL object
2776 * (it returns the retrieved tuple).
2777 *
2778 * Any raised AttributeErrors are masked by clearing the exception and
2779 * returning NULL. If an object other than a tuple comes out of __bases__,
2780 * then again, the return value is NULL. So yes, these two situations
2781 * produce exactly the same results: NULL is returned and no error is set.
2782 *
2783 * If some exception other than AttributeError is raised, then NULL is also
2784 * returned, but the exception is not cleared. That's because we want the
2785 * exception to be propagated along.
2786 *
2787 * Callers are expected to test for PyErr_Occurred() when the return value
2788 * is NULL to decide whether a valid exception should be propagated or not.
2789 * When there's no exception to propagate, it's customary for the caller to
2790 * set a TypeError.
2791 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002792static PyObject *
2793abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002794{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002795 static PyObject *__bases__ = NULL;
2796 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002797
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002798 if (__bases__ == NULL) {
2799 __bases__ = PyString_InternFromString("__bases__");
2800 if (__bases__ == NULL)
2801 return NULL;
2802 }
2803 bases = PyObject_GetAttr(cls, __bases__);
2804 if (bases == NULL) {
2805 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2806 PyErr_Clear();
2807 return NULL;
2808 }
2809 if (!PyTuple_Check(bases)) {
2810 Py_DECREF(bases);
2811 return NULL;
2812 }
2813 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002814}
2815
2816
2817static int
2818abstract_issubclass(PyObject *derived, PyObject *cls)
2819{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002820 PyObject *bases = NULL;
2821 Py_ssize_t i, n;
2822 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002824 while (1) {
2825 if (derived == cls)
2826 return 1;
2827 bases = abstract_get_bases(derived);
2828 if (bases == NULL) {
2829 if (PyErr_Occurred())
2830 return -1;
2831 return 0;
2832 }
2833 n = PyTuple_GET_SIZE(bases);
2834 if (n == 0) {
2835 Py_DECREF(bases);
2836 return 0;
2837 }
2838 /* Avoid recursivity in the single inheritance case */
2839 if (n == 1) {
2840 derived = PyTuple_GET_ITEM(bases, 0);
2841 Py_DECREF(bases);
2842 continue;
2843 }
2844 for (i = 0; i < n; i++) {
2845 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2846 if (r != 0)
2847 break;
2848 }
2849 Py_DECREF(bases);
2850 return r;
2851 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002852}
2853
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002854static int
2855check_class(PyObject *cls, const char *error)
2856{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002857 PyObject *bases = abstract_get_bases(cls);
2858 if (bases == NULL) {
2859 /* Do not mask errors. */
2860 if (!PyErr_Occurred())
2861 PyErr_SetString(PyExc_TypeError, error);
2862 return 0;
2863 }
2864 Py_DECREF(bases);
2865 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002866}
2867
Brett Cannon4f653312004-03-20 22:52:14 +00002868static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002869recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002871 PyObject *icls;
2872 static PyObject *__class__ = NULL;
2873 int retval = 0;
Guido van Rossum823649d2001-03-21 18:40:58 +00002874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002875 if (__class__ == NULL) {
2876 __class__ = PyString_InternFromString("__class__");
2877 if (__class__ == NULL)
2878 return -1;
2879 }
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002881 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2882 PyObject *inclass =
2883 (PyObject*)((PyInstanceObject*)inst)->in_class;
2884 retval = PyClass_IsSubclass(inclass, cls);
2885 }
2886 else if (PyType_Check(cls)) {
2887 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2888 if (retval == 0) {
2889 PyObject *c = PyObject_GetAttr(inst, __class__);
2890 if (c == NULL) {
2891 PyErr_Clear();
2892 }
2893 else {
2894 if (c != (PyObject *)(inst->ob_type) &&
2895 PyType_Check(c))
2896 retval = PyType_IsSubtype(
2897 (PyTypeObject *)c,
2898 (PyTypeObject *)cls);
2899 Py_DECREF(c);
2900 }
2901 }
2902 }
2903 else {
2904 if (!check_class(cls,
2905 "isinstance() arg 2 must be a class, type,"
2906 " or tuple of classes and types"))
2907 return -1;
2908 icls = PyObject_GetAttr(inst, __class__);
2909 if (icls == NULL) {
2910 PyErr_Clear();
2911 retval = 0;
2912 }
2913 else {
2914 retval = abstract_issubclass(icls, cls);
2915 Py_DECREF(icls);
2916 }
2917 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002919 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002920}
2921
2922int
Brett Cannon4f653312004-03-20 22:52:14 +00002923PyObject_IsInstance(PyObject *inst, PyObject *cls)
2924{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 static PyObject *name = NULL;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002927 /* Quick test for an exact match */
2928 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2929 return 1;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002930
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002931 if (PyTuple_Check(cls)) {
2932 Py_ssize_t i;
2933 Py_ssize_t n;
2934 int r = 0;
Antoine Pitrou0668c622008-08-26 22:42:08 +00002935
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002936 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2937 return -1;
2938 n = PyTuple_GET_SIZE(cls);
2939 for (i = 0; i < n; ++i) {
2940 PyObject *item = PyTuple_GET_ITEM(cls, i);
2941 r = PyObject_IsInstance(inst, item);
2942 if (r != 0)
2943 /* either found it, or got an error */
2944 break;
2945 }
2946 Py_LeaveRecursiveCall();
2947 return r;
2948 }
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00002949
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002950 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
2951 PyObject *checker;
2952 checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
2953 if (checker != NULL) {
2954 PyObject *res;
2955 int ok = -1;
2956 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2957 Py_DECREF(checker);
2958 return ok;
2959 }
2960 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2961 Py_LeaveRecursiveCall();
2962 Py_DECREF(checker);
2963 if (res != NULL) {
2964 ok = PyObject_IsTrue(res);
2965 Py_DECREF(res);
2966 }
2967 return ok;
2968 }
2969 else if (PyErr_Occurred())
2970 return -1;
2971 }
2972 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002973}
2974
2975static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002976recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002978 int retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002979
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002980 if (PyType_Check(cls) && PyType_Check(derived)) {
2981 /* Fast path (non-recursive) */
2982 return PyType_IsSubtype(
2983 (PyTypeObject *)derived, (PyTypeObject *)cls);
2984 }
2985 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2986 if (!check_class(derived,
2987 "issubclass() arg 1 must be a class"))
2988 return -1;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002989
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002990 if (!check_class(cls,
2991 "issubclass() arg 2 must be a class"
2992 " or tuple of classes"))
2993 return -1;
2994 retval = abstract_issubclass(derived, cls);
2995 }
2996 else {
2997 /* shortcut */
2998 if (!(retval = (derived == cls)))
2999 retval = PyClass_IsSubclass(derived, cls);
3000 }
Guido van Rossum823649d2001-03-21 18:40:58 +00003001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003002 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00003003}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003004
Brett Cannon4f653312004-03-20 22:52:14 +00003005int
3006PyObject_IsSubclass(PyObject *derived, PyObject *cls)
3007{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003008 static PyObject *name = NULL;
3009
3010 if (PyTuple_Check(cls)) {
3011 Py_ssize_t i;
3012 Py_ssize_t n;
3013 int r = 0;
3014
3015 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3016 return -1;
3017 n = PyTuple_GET_SIZE(cls);
3018 for (i = 0; i < n; ++i) {
3019 PyObject *item = PyTuple_GET_ITEM(cls, i);
3020 r = PyObject_IsSubclass(derived, item);
3021 if (r != 0)
3022 /* either found it, or got an error */
3023 break;
3024 }
3025 Py_LeaveRecursiveCall();
3026 return r;
3027 }
3028 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
3029 PyObject *checker;
3030 checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
3031 if (checker != NULL) {
3032 PyObject *res;
3033 int ok = -1;
3034 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3035 Py_DECREF(checker);
3036 return ok;
3037 }
3038 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3039 Py_LeaveRecursiveCall();
3040 Py_DECREF(checker);
3041 if (res != NULL) {
3042 ok = PyObject_IsTrue(res);
3043 Py_DECREF(res);
3044 }
3045 return ok;
3046 }
3047 else if (PyErr_Occurred()) {
3048 return -1;
3049 }
3050 }
3051 return recursive_issubclass(derived, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003052}
3053
3054int
3055_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3056{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003057 return recursive_isinstance(inst, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003058}
3059
3060int
3061_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3062{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003063 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003064}
3065
3066
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003067PyObject *
3068PyObject_GetIter(PyObject *o)
3069{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003070 PyTypeObject *t = o->ob_type;
3071 getiterfunc f = NULL;
3072 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3073 f = t->tp_iter;
3074 if (f == NULL) {
3075 if (PySequence_Check(o))
3076 return PySeqIter_New(o);
3077 return type_error("'%.200s' object is not iterable", o);
3078 }
3079 else {
3080 PyObject *res = (*f)(o);
3081 if (res != NULL && !PyIter_Check(res)) {
3082 PyErr_Format(PyExc_TypeError,
3083 "iter() returned non-iterator "
3084 "of type '%.100s'",
3085 res->ob_type->tp_name);
3086 Py_DECREF(res);
3087 res = NULL;
3088 }
3089 return res;
3090 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00003091}
3092
Tim Petersf4848da2001-05-05 00:14:56 +00003093/* Return next item.
3094 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3095 * If the iteration terminates normally, return NULL and clear the
3096 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3097 * will be false.
3098 * Else return the next object. PyErr_Occurred() will be false.
3099 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00003100PyObject *
3101PyIter_Next(PyObject *iter)
3102{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003103 PyObject *result;
3104 result = (*iter->ob_type->tp_iternext)(iter);
3105 if (result == NULL &&
3106 PyErr_Occurred() &&
3107 PyErr_ExceptionMatches(PyExc_StopIteration))
3108 PyErr_Clear();
3109 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003110}