blob: 20d241ddc6880ac9f5b43f54d281b37c2ab31437 [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 /* Check for a __format__ method and call it. */
756 if (PyInstance_Check(obj)) {
757 /* We're an instance of a classic class */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000758 PyObject *bound_method = PyObject_GetAttrString(obj, "__format__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000759 if (bound_method != NULL) {
760 result = PyObject_CallFunctionObjArgs(bound_method,
761 format_spec,
762 NULL);
763 Py_DECREF(bound_method);
764 } else {
765 PyObject *self_as_str = NULL;
766 PyObject *format_method = NULL;
767 Py_ssize_t format_len;
Eric Smitha9f7d622008-02-17 19:46:49 +0000768
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000769 PyErr_Clear();
770 /* Per the PEP, convert to str (or unicode,
771 depending on the type of the format
772 specifier). For new-style classes, this
773 logic is done by object.__format__(). */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000774#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000775 if (spec_is_unicode) {
776 format_len = PyUnicode_GET_SIZE(format_spec);
777 self_as_str = PyObject_Unicode(obj);
778 } else
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000779#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000780 {
781 format_len = PyString_GET_SIZE(format_spec);
782 self_as_str = PyObject_Str(obj);
783 }
784 if (self_as_str == NULL)
785 goto done1;
Eric Smithd44b2fc2010-04-02 12:30:56 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 if (format_len > 0) {
788 /* See the almost identical code in
789 typeobject.c for new-style
790 classes. */
791 if (PyErr_WarnEx(
792 PyExc_PendingDeprecationWarning,
793 "object.__format__ with a non-empty "
794 "format string is deprecated", 1)
795 < 0) {
796 goto done1;
797 }
798 /* Eventually this will become an
799 error:
800 PyErr_Format(PyExc_TypeError,
801 "non-empty format string passed to "
802 "object.__format__");
803 goto done1;
804 */
805 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000806
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000807 /* Then call str.__format__ on that result */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000808 format_method = PyObject_GetAttrString(self_as_str, "__format__");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000809 if (format_method == NULL) {
810 goto done1;
811 }
812 result = PyObject_CallFunctionObjArgs(format_method,
813 format_spec,
814 NULL);
Eric Smithd44b2fc2010-04-02 12:30:56 +0000815done1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000816 Py_XDECREF(self_as_str);
817 Py_XDECREF(format_method);
818 if (result == NULL)
819 goto done;
820 }
821 } else {
822 /* Not an instance of a classic class, use the code
823 from py3k */
Benjamin Peterson3a2acb52010-06-05 00:38:22 +0000824 static PyObject *format_cache = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000825
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000826 /* Find the (unbound!) __format__ method (a borrowed
827 reference) */
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000828 PyObject *method = _PyObject_LookupSpecial(obj, "__format__",
829 &format_cache);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 if (method == NULL) {
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000831 if (!PyErr_Occurred())
832 PyErr_Format(PyExc_TypeError,
833 "Type %.100s doesn't define __format__",
834 Py_TYPE(obj)->tp_name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 goto done;
836 }
Benjamin Peterson2aa6c382010-06-05 00:32:50 +0000837 /* And call it. */
838 result = PyObject_CallFunctionObjArgs(method, format_spec, NULL);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000839 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000840
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000841 if (result == NULL)
842 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000843
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000844 /* Check the result type, and make sure it's str or unicode */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000845#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000846 if (PyUnicode_Check(result))
847 result_is_unicode = 1;
848 else if (PyString_Check(result))
849 result_is_unicode = 0;
850 else {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000851#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 if (!PyString_Check(result)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000853#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000854 PyErr_Format(PyExc_TypeError,
855 "%.100s.__format__ must return string or "
856 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
857 Py_TYPE(result)->tp_name);
858 Py_DECREF(result);
859 result = NULL;
860 goto done;
861 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000862
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 /* Convert to unicode, if needed. Required if spec is unicode
864 and result is str */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000865#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 if (spec_is_unicode && !result_is_unicode) {
867 PyObject *tmp = PyObject_Unicode(result);
868 /* This logic works whether or not tmp is NULL */
869 Py_DECREF(result);
870 result = tmp;
871 }
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000872#endif
Eric Smitha9f7d622008-02-17 19:46:49 +0000873
874done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 Py_XDECREF(empty);
876 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +0000877}
878
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000879/* Operations on numbers */
880
881int
Fred Drake79912472000-07-09 04:06:11 +0000882PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000883{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 return o && o->ob_type->tp_as_number &&
885 (o->ob_type->tp_as_number->nb_int ||
886 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000887}
888
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000889/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000890
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000891/* New style number protocol support */
Guido van Rossume15dee51995-07-18 14:12:02 +0000892
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000893#define NB_SLOT(x) offsetof(PyNumberMethods, x)
894#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000896#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000898
899/*
900 Calling scheme used for binary operations:
901
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000902 v w Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000903 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000904 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
905 new old v.op(v,w), coerce(v,w), v.op(v,w)
906 old new w.op(v,w), coerce(v,w), v.op(v,w)
907 old old coerce(v,w), v.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000908
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000909 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
910 v->ob_type
911
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000912 Legend:
913 -------
914 * new == new style number
915 * old == old style number
916 * Action indicates the order in which operations are tried until either
917 a valid result is produced or an error occurs.
918
919 */
920
921static PyObject *
922binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 PyObject *x;
925 binaryfunc slotv = NULL;
926 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000927
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
929 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
930 if (w->ob_type != v->ob_type &&
931 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
932 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
933 if (slotw == slotv)
934 slotw = NULL;
935 }
936 if (slotv) {
937 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
938 x = slotw(v, w);
939 if (x != Py_NotImplemented)
940 return x;
941 Py_DECREF(x); /* can't do it */
942 slotw = NULL;
943 }
944 x = slotv(v, w);
945 if (x != Py_NotImplemented)
946 return x;
947 Py_DECREF(x); /* can't do it */
948 }
949 if (slotw) {
950 x = slotw(v, w);
951 if (x != Py_NotImplemented)
952 return x;
953 Py_DECREF(x); /* can't do it */
954 }
955 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
956 int err = PyNumber_CoerceEx(&v, &w);
957 if (err < 0) {
958 return NULL;
959 }
960 if (err == 0) {
961 PyNumberMethods *mv = v->ob_type->tp_as_number;
962 if (mv) {
963 binaryfunc slot;
964 slot = NB_BINOP(mv, op_slot);
965 if (slot) {
966 x = slot(v, w);
967 Py_DECREF(v);
968 Py_DECREF(w);
969 return x;
970 }
971 }
972 /* CoerceEx incremented the reference counts */
973 Py_DECREF(v);
974 Py_DECREF(w);
975 }
976 }
977 Py_INCREF(Py_NotImplemented);
978 return Py_NotImplemented;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000979}
Guido van Rossum77660912002-04-16 16:32:50 +0000980
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000981static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000982binop_type_error(PyObject *v, PyObject *w, const char *op_name)
983{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 PyErr_Format(PyExc_TypeError,
985 "unsupported operand type(s) for %.100s: "
986 "'%.100s' and '%.100s'",
987 op_name,
988 v->ob_type->tp_name,
989 w->ob_type->tp_name);
990 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000991}
992
993static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000994binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 PyObject *result = binary_op1(v, w, op_slot);
997 if (result == Py_NotImplemented) {
998 Py_DECREF(result);
999 return binop_type_error(v, w, op_name);
1000 }
1001 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001002}
1003
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001004
1005/*
1006 Calling scheme used for ternary operations:
1007
Guido van Rossum84675ac2001-09-29 01:05:03 +00001008 *** In some cases, w.op is called before v.op; see binary_op1. ***
1009
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 v w z Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001011 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001012 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1013 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1014 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1015 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1016 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1017 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1018 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1019 old old old coerce(v,w,z), v.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001020
1021 Legend:
1022 -------
1023 * new == new style number
1024 * old == old style number
1025 * Action indicates the order in which operations are tried until either
1026 a valid result is produced or an error occurs.
1027 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1028 only if z != Py_None; if z == Py_None, then it is treated as absent
1029 variable and only coerce(v,w) is tried.
1030
1031 */
1032
1033static PyObject *
1034ternary_op(PyObject *v,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001035 PyObject *w,
1036 PyObject *z,
1037 const int op_slot,
1038 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +00001039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 PyNumberMethods *mv, *mw, *mz;
1041 PyObject *x = NULL;
1042 ternaryfunc slotv = NULL;
1043 ternaryfunc slotw = NULL;
1044 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +00001045
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 mv = v->ob_type->tp_as_number;
1047 mw = w->ob_type->tp_as_number;
1048 if (mv != NULL && NEW_STYLE_NUMBER(v))
1049 slotv = NB_TERNOP(mv, op_slot);
1050 if (w->ob_type != v->ob_type &&
1051 mw != NULL && NEW_STYLE_NUMBER(w)) {
1052 slotw = NB_TERNOP(mw, op_slot);
1053 if (slotw == slotv)
1054 slotw = NULL;
1055 }
1056 if (slotv) {
1057 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1058 x = slotw(v, w, z);
1059 if (x != Py_NotImplemented)
1060 return x;
1061 Py_DECREF(x); /* can't do it */
1062 slotw = NULL;
1063 }
1064 x = slotv(v, w, z);
1065 if (x != Py_NotImplemented)
1066 return x;
1067 Py_DECREF(x); /* can't do it */
1068 }
1069 if (slotw) {
1070 x = slotw(v, w, z);
1071 if (x != Py_NotImplemented)
1072 return x;
1073 Py_DECREF(x); /* can't do it */
1074 }
1075 mz = z->ob_type->tp_as_number;
1076 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1077 slotz = NB_TERNOP(mz, op_slot);
1078 if (slotz == slotv || slotz == slotw)
1079 slotz = NULL;
1080 if (slotz) {
1081 x = slotz(v, w, z);
1082 if (x != Py_NotImplemented)
1083 return x;
1084 Py_DECREF(x); /* can't do it */
1085 }
1086 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1089 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1090 /* we have an old style operand, coerce */
1091 PyObject *v1, *z1, *w2, *z2;
1092 int c;
Guido van Rossum77660912002-04-16 16:32:50 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 c = PyNumber_Coerce(&v, &w);
1095 if (c != 0)
1096 goto error3;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001097
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001098 /* Special case: if the third argument is None, it is
1099 treated as absent argument and not coerced. */
1100 if (z == Py_None) {
1101 if (v->ob_type->tp_as_number) {
1102 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1103 op_slot);
1104 if (slotz)
1105 x = slotz(v, w, z);
1106 else
1107 c = -1;
1108 }
1109 else
1110 c = -1;
1111 goto error2;
1112 }
1113 v1 = v;
1114 z1 = z;
1115 c = PyNumber_Coerce(&v1, &z1);
1116 if (c != 0)
1117 goto error2;
1118 w2 = w;
1119 z2 = z1;
1120 c = PyNumber_Coerce(&w2, &z2);
1121 if (c != 0)
1122 goto error1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001124 if (v1->ob_type->tp_as_number != NULL) {
1125 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1126 op_slot);
1127 if (slotv)
1128 x = slotv(v1, w2, z2);
1129 else
1130 c = -1;
1131 }
1132 else
1133 c = -1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001135 Py_DECREF(w2);
1136 Py_DECREF(z2);
1137 error1:
1138 Py_DECREF(v1);
1139 Py_DECREF(z1);
1140 error2:
1141 Py_DECREF(v);
1142 Py_DECREF(w);
1143 error3:
1144 if (c >= 0)
1145 return x;
1146 }
Guido van Rossum5c66a262001-10-22 04:12:44 +00001147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001148 if (z == Py_None)
1149 PyErr_Format(
1150 PyExc_TypeError,
1151 "unsupported operand type(s) for ** or pow(): "
1152 "'%.100s' and '%.100s'",
1153 v->ob_type->tp_name,
1154 w->ob_type->tp_name);
1155 else
1156 PyErr_Format(
1157 PyExc_TypeError,
1158 "unsupported operand type(s) for pow(): "
1159 "'%.100s', '%.100s', '%.100s'",
1160 v->ob_type->tp_name,
1161 w->ob_type->tp_name,
1162 z->ob_type->tp_name);
1163 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001164}
1165
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001166#define BINARY_FUNC(func, op, op_name) \
1167 PyObject * \
1168 func(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001169 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001170 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001171
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001172BINARY_FUNC(PyNumber_Or, nb_or, "|")
1173BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1174BINARY_FUNC(PyNumber_And, nb_and, "&")
1175BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1176BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1177BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001178BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1179BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001180
1181PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001182PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001183{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001184 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1185 if (result == Py_NotImplemented) {
1186 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1187 Py_DECREF(result);
1188 if (m && m->sq_concat) {
1189 return (*m->sq_concat)(v, w);
1190 }
1191 result = binop_type_error(v, w, "+");
1192 }
1193 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001194}
1195
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001196static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001197sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001198{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001199 Py_ssize_t count;
1200 if (PyIndex_Check(n)) {
1201 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1202 if (count == -1 && PyErr_Occurred())
1203 return NULL;
1204 }
1205 else {
1206 return type_error("can't multiply sequence by "
1207 "non-int of type '%.200s'", n);
1208 }
1209 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001210}
1211
1212PyObject *
1213PyNumber_Multiply(PyObject *v, PyObject *w)
1214{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001215 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1216 if (result == Py_NotImplemented) {
1217 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1218 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1219 Py_DECREF(result);
1220 if (mv && mv->sq_repeat) {
1221 return sequence_repeat(mv->sq_repeat, v, w);
1222 }
1223 else if (mw && mw->sq_repeat) {
1224 return sequence_repeat(mw->sq_repeat, w, v);
1225 }
1226 result = binop_type_error(v, w, "*");
1227 }
1228 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001229}
1230
Guido van Rossume15dee51995-07-18 14:12:02 +00001231PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001232PyNumber_FloorDivide(PyObject *v, PyObject *w)
1233{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001234 /* XXX tp_flags test */
1235 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001236}
1237
1238PyObject *
1239PyNumber_TrueDivide(PyObject *v, PyObject *w)
1240{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001241 /* XXX tp_flags test */
1242 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001243}
1244
1245PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001246PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001247{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001248 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001249}
1250
1251PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001252PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001253{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001254 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001255}
1256
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001257/* Binary in-place operators */
1258
1259/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001260 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001261
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001262 - If the left hand object has the appropriate struct members, and
1263 they are filled, call the appropriate function and return the
1264 result. No coercion is done on the arguments; the left-hand object
1265 is the one the operation is performed on, and it's up to the
1266 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001267
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001268 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001269 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001270
1271 */
1272
Guido van Rossum77660912002-04-16 16:32:50 +00001273#define HASINPLACE(t) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001274 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001275
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001276static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001277binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001278{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001279 PyNumberMethods *mv = v->ob_type->tp_as_number;
1280 if (mv != NULL && HASINPLACE(v)) {
1281 binaryfunc slot = NB_BINOP(mv, iop_slot);
1282 if (slot) {
1283 PyObject *x = (slot)(v, w);
1284 if (x != Py_NotImplemented) {
1285 return x;
1286 }
1287 Py_DECREF(x);
1288 }
1289 }
1290 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001291}
1292
1293static PyObject *
1294binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001295 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001296{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001297 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1298 if (result == Py_NotImplemented) {
1299 Py_DECREF(result);
1300 return binop_type_error(v, w, op_name);
1301 }
1302 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001303}
1304
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001305#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 PyObject * \
1307 func(PyObject *v, PyObject *w) { \
1308 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1309 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001310
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001311INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1312INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1313INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1314INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1315INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1316INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1317INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001318
1319PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001320PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1321{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001322 /* XXX tp_flags test */
1323 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1324 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001325}
1326
1327PyObject *
1328PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 /* XXX tp_flags test */
1331 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1332 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001333}
1334
1335PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001336PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1337{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001338 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1339 NB_SLOT(nb_add));
1340 if (result == Py_NotImplemented) {
1341 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1342 Py_DECREF(result);
1343 if (m != NULL) {
1344 binaryfunc f = NULL;
1345 if (HASINPLACE(v))
1346 f = m->sq_inplace_concat;
1347 if (f == NULL)
1348 f = m->sq_concat;
1349 if (f != NULL)
1350 return (*f)(v, w);
1351 }
1352 result = binop_type_error(v, w, "+=");
1353 }
1354 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001355}
1356
1357PyObject *
1358PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1361 NB_SLOT(nb_multiply));
1362 if (result == Py_NotImplemented) {
1363 ssizeargfunc f = NULL;
1364 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1365 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1366 Py_DECREF(result);
1367 if (mv != NULL) {
1368 if (HASINPLACE(v))
1369 f = mv->sq_inplace_repeat;
1370 if (f == NULL)
1371 f = mv->sq_repeat;
1372 if (f != NULL)
1373 return sequence_repeat(f, v, w);
1374 }
1375 else if (mw != NULL) {
1376 /* Note that the right hand operand should not be
1377 * mutated in this case so sq_inplace_repeat is not
1378 * used. */
1379 if (mw->sq_repeat)
1380 return sequence_repeat(mw->sq_repeat, w, v);
1381 }
1382 result = binop_type_error(v, w, "*=");
1383 }
1384 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001385}
1386
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001387PyObject *
1388PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1391 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001392}
1393
1394PyObject *
1395PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1396{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1398 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1399 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1400 }
1401 else {
1402 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1403 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001404}
1405
1406
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001407/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001408
1409PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001410PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001411{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001414 if (o == NULL)
1415 return null_error();
1416 m = o->ob_type->tp_as_number;
1417 if (m && m->nb_negative)
1418 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001419
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001420 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001421}
1422
1423PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001424PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001426 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001428 if (o == NULL)
1429 return null_error();
1430 m = o->ob_type->tp_as_number;
1431 if (m && m->nb_positive)
1432 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001433
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001434 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001435}
1436
1437PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001438PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001441
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 if (o == NULL)
1443 return null_error();
1444 m = o->ob_type->tp_as_number;
1445 if (m && m->nb_invert)
1446 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001448 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001449}
1450
1451PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001452PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001453{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001454 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001455
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001456 if (o == NULL)
1457 return null_error();
1458 m = o->ob_type->tp_as_number;
1459 if (m && m->nb_absolute)
1460 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001462 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001463}
1464
Guido van Rossum9e896b32000-04-05 20:11:21 +00001465/* Add a check for embedded NULL-bytes in the argument. */
1466static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001467int_from_string(const char *s, Py_ssize_t len)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001468{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001469 char *end;
1470 PyObject *x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001471
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001472 x = PyInt_FromString((char*)s, &end, 10);
1473 if (x == NULL)
1474 return NULL;
1475 if (end != s + len) {
1476 PyErr_SetString(PyExc_ValueError,
1477 "null byte in argument for int()");
1478 Py_DECREF(x);
1479 return NULL;
1480 }
1481 return x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001482}
1483
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484/* Return a Python Int or Long from the object item
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001485 Raise TypeError if the result is not an int-or-long
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 or if the object cannot be interpreted as an index.
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001487*/
1488PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001489PyNumber_Index(PyObject *item)
1490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 PyObject *result = NULL;
1492 if (item == NULL)
1493 return null_error();
1494 if (PyInt_Check(item) || PyLong_Check(item)) {
1495 Py_INCREF(item);
1496 return item;
1497 }
1498 if (PyIndex_Check(item)) {
1499 result = item->ob_type->tp_as_number->nb_index(item);
1500 if (result &&
1501 !PyInt_Check(result) && !PyLong_Check(result)) {
1502 PyErr_Format(PyExc_TypeError,
1503 "__index__ returned non-(int,long) " \
1504 "(type %.200s)",
1505 result->ob_type->tp_name);
1506 Py_DECREF(result);
1507 return NULL;
1508 }
1509 }
1510 else {
1511 PyErr_Format(PyExc_TypeError,
1512 "'%.200s' object cannot be interpreted "
1513 "as an index", item->ob_type->tp_name);
1514 }
1515 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001516}
1517
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001518/* Return an error on Overflow only if err is not NULL*/
1519
1520Py_ssize_t
1521PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1522{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001523 Py_ssize_t result;
1524 PyObject *runerr;
1525 PyObject *value = PyNumber_Index(item);
1526 if (value == NULL)
1527 return -1;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001529 /* We're done if PyInt_AsSsize_t() returns without error. */
1530 result = PyInt_AsSsize_t(value);
1531 if (result != -1 || !(runerr = PyErr_Occurred()))
1532 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001534 /* Error handling code -- only manage OverflowError differently */
1535 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1536 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 PyErr_Clear();
1539 /* If no error-handling desired then the default clipping
1540 is sufficient.
1541 */
1542 if (!err) {
1543 assert(PyLong_Check(value));
1544 /* Whether or not it is less than or equal to
1545 zero is determined by the sign of ob_size
1546 */
1547 if (_PyLong_Sign(value) < 0)
1548 result = PY_SSIZE_T_MIN;
1549 else
1550 result = PY_SSIZE_T_MAX;
1551 }
1552 else {
1553 /* Otherwise replace the error with caller's error object. */
1554 PyErr_Format(err,
1555 "cannot fit '%.200s' into an index-sized integer",
1556 item->ob_type->tp_name);
1557 }
1558
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001559 finish:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 Py_DECREF(value);
1561 return result;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001562}
1563
1564
Guido van Rossume15dee51995-07-18 14:12:02 +00001565PyObject *
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001566_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 const char *type_name;
1569 static PyObject *int_name = NULL;
1570 if (int_name == NULL) {
1571 int_name = PyString_InternFromString("__int__");
1572 if (int_name == NULL)
1573 return NULL;
1574 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001575
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001576 if (integral && (!PyInt_Check(integral) &&
1577 !PyLong_Check(integral))) {
1578 /* Don't go through tp_as_number->nb_int to avoid
1579 hitting the classic class fallback to __trunc__. */
1580 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1581 if (int_func == NULL) {
1582 PyErr_Clear(); /* Raise a different error. */
1583 goto non_integral_error;
1584 }
1585 Py_DECREF(integral);
1586 integral = PyEval_CallObject(int_func, NULL);
1587 Py_DECREF(int_func);
1588 if (integral && (!PyInt_Check(integral) &&
1589 !PyLong_Check(integral))) {
1590 goto non_integral_error;
1591 }
1592 }
1593 return integral;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001594
1595non_integral_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001596 if (PyInstance_Check(integral)) {
1597 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1598 ->in_class->cl_name);
1599 }
1600 else {
1601 type_name = integral->ob_type->tp_name;
1602 }
1603 PyErr_Format(PyExc_TypeError, error_format, type_name);
1604 Py_DECREF(integral);
1605 return NULL;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001606}
1607
1608
1609PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001610PyNumber_Int(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001611{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001612 PyNumberMethods *m;
1613 static PyObject *trunc_name = NULL;
1614 PyObject *trunc_func;
1615 const char *buffer;
1616 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001617
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001618 if (trunc_name == NULL) {
1619 trunc_name = PyString_InternFromString("__trunc__");
1620 if (trunc_name == NULL)
1621 return NULL;
1622 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001623
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001624 if (o == NULL)
1625 return null_error();
1626 if (PyInt_CheckExact(o)) {
1627 Py_INCREF(o);
1628 return o;
1629 }
1630 m = o->ob_type->tp_as_number;
1631 if (m && m->nb_int) { /* This should include subclasses of int */
1632 /* Classic classes always take this branch. */
1633 PyObject *res = m->nb_int(o);
1634 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1635 PyErr_Format(PyExc_TypeError,
1636 "__int__ returned non-int (type %.200s)",
1637 res->ob_type->tp_name);
1638 Py_DECREF(res);
1639 return NULL;
1640 }
1641 return res;
1642 }
1643 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1644 PyIntObject *io = (PyIntObject*)o;
1645 return PyInt_FromLong(io->ob_ival);
1646 }
1647 trunc_func = PyObject_GetAttr(o, trunc_name);
1648 if (trunc_func) {
1649 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1650 Py_DECREF(trunc_func);
1651 /* __trunc__ is specified to return an Integral type, but
1652 int() needs to return an int. */
1653 return _PyNumber_ConvertIntegralToInt(
1654 truncated,
1655 "__trunc__ returned non-Integral (type %.200s)");
1656 }
1657 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001658
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001659 if (PyString_Check(o))
1660 return int_from_string(PyString_AS_STRING(o),
1661 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001662#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001663 if (PyUnicode_Check(o))
1664 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1665 PyUnicode_GET_SIZE(o),
1666 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001667#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1669 return int_from_string((char*)buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001670
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001671 return type_error("int() argument must be a string or a "
1672 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001673}
1674
Guido van Rossum9e896b32000-04-05 20:11:21 +00001675/* Add a check for embedded NULL-bytes in the argument. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001676static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001677long_from_string(const char *s, Py_ssize_t len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 char *end;
1680 PyObject *x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 x = PyLong_FromString((char*)s, &end, 10);
1683 if (x == NULL)
1684 return NULL;
1685 if (end != s + len) {
1686 PyErr_SetString(PyExc_ValueError,
1687 "null byte in argument for long()");
1688 Py_DECREF(x);
1689 return NULL;
1690 }
1691 return x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001692}
1693
Guido van Rossume15dee51995-07-18 14:12:02 +00001694PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001695PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001696{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001697 PyNumberMethods *m;
1698 static PyObject *trunc_name = NULL;
1699 PyObject *trunc_func;
1700 const char *buffer;
1701 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001702
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 if (trunc_name == NULL) {
1704 trunc_name = PyString_InternFromString("__trunc__");
1705 if (trunc_name == NULL)
1706 return NULL;
1707 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001708
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001709 if (o == NULL)
1710 return null_error();
1711 m = o->ob_type->tp_as_number;
1712 if (m && m->nb_long) { /* This should include subclasses of long */
1713 /* Classic classes always take this branch. */
1714 PyObject *res = m->nb_long(o);
1715 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1716 PyErr_Format(PyExc_TypeError,
1717 "__long__ returned non-long (type %.200s)",
1718 res->ob_type->tp_name);
1719 Py_DECREF(res);
1720 return NULL;
1721 }
1722 return res;
1723 }
1724 if (PyLong_Check(o)) /* A long subclass without nb_long */
1725 return _PyLong_Copy((PyLongObject *)o);
1726 trunc_func = PyObject_GetAttr(o, trunc_name);
1727 if (trunc_func) {
1728 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1729 PyObject *int_instance;
1730 Py_DECREF(trunc_func);
1731 /* __trunc__ is specified to return an Integral type,
1732 but long() needs to return a long. */
1733 int_instance = _PyNumber_ConvertIntegralToInt(
1734 truncated,
1735 "__trunc__ returned non-Integral (type %.200s)");
1736 if (int_instance && PyInt_Check(int_instance)) {
1737 /* Make sure that long() returns a long instance. */
1738 long value = PyInt_AS_LONG(int_instance);
1739 Py_DECREF(int_instance);
1740 return PyLong_FromLong(value);
1741 }
1742 return int_instance;
1743 }
1744 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 if (PyString_Check(o))
1747 /* need to do extra error checking that PyLong_FromString()
1748 * doesn't do. In particular long('9.5') must raise an
1749 * exception, not truncate the float.
1750 */
1751 return long_from_string(PyString_AS_STRING(o),
1752 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001753#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 if (PyUnicode_Check(o))
1755 /* The above check is done in PyLong_FromUnicode(). */
1756 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1757 PyUnicode_GET_SIZE(o),
1758 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001759#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1761 return long_from_string(buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001763 return type_error("long() argument must be a string or a "
1764 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001765}
1766
1767PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001768PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001769{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001770 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001771
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 if (o == NULL)
1773 return null_error();
1774 m = o->ob_type->tp_as_number;
1775 if (m && m->nb_float) { /* This should include subclasses of float */
1776 PyObject *res = m->nb_float(o);
1777 if (res && !PyFloat_Check(res)) {
1778 PyErr_Format(PyExc_TypeError,
1779 "__float__ returned non-float (type %.200s)",
1780 res->ob_type->tp_name);
1781 Py_DECREF(res);
1782 return NULL;
1783 }
1784 return res;
1785 }
1786 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1787 PyFloatObject *po = (PyFloatObject *)o;
1788 return PyFloat_FromDouble(po->ob_fval);
1789 }
1790 return PyFloat_FromString(o, NULL);
Guido van Rossume15dee51995-07-18 14:12:02 +00001791}
1792
Eric Smith5e527eb2008-02-10 01:36:53 +00001793PyObject *
1794PyNumber_ToBase(PyObject *n, int base)
1795{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 PyObject *res = NULL;
1797 PyObject *index = PyNumber_Index(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001798
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 if (!index)
1800 return NULL;
1801 if (PyLong_Check(index))
1802 res = _PyLong_Format(index, base, 0, 1);
1803 else if (PyInt_Check(index))
1804 res = _PyInt_Format((PyIntObject*)index, base, 1);
1805 else
1806 /* It should not be possible to get here, as
1807 PyNumber_Index already has a check for the same
1808 condition */
1809 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1810 "int or long");
1811 Py_DECREF(index);
1812 return res;
Eric Smith5e527eb2008-02-10 01:36:53 +00001813}
1814
1815
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001816/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001817
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001818int
Fred Drake79912472000-07-09 04:06:11 +00001819PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001820{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001821 if (s == NULL)
1822 return 0;
1823 if (PyInstance_Check(s))
1824 return PyObject_HasAttrString(s, "__getitem__");
1825 if (PyDict_Check(s))
1826 return 0;
1827 return s->ob_type->tp_as_sequence &&
1828 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001829}
1830
Martin v. Löwis18e16552006-02-15 17:27:45 +00001831Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001832PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001833{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001834 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001835
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 if (s == NULL) {
1837 null_error();
1838 return -1;
1839 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001841 m = s->ob_type->tp_as_sequence;
1842 if (m && m->sq_length)
1843 return m->sq_length(s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001844
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001845 type_error("object of type '%.200s' has no len()", s);
1846 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001847}
1848
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001849#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001850Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001851PySequence_Length(PyObject *s)
1852{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001854}
1855#define PySequence_Length PySequence_Size
1856
Guido van Rossume15dee51995-07-18 14:12:02 +00001857PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001858PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001859{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001862 if (s == NULL || o == NULL)
1863 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001865 m = s->ob_type->tp_as_sequence;
1866 if (m && m->sq_concat)
1867 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001868
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001869 /* Instances of user classes defining an __add__() method only
1870 have an nb_add slot, not an sq_concat slot. So we fall back
1871 to nb_add if both arguments appear to be sequences. */
1872 if (PySequence_Check(s) && PySequence_Check(o)) {
1873 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1874 if (result != Py_NotImplemented)
1875 return result;
1876 Py_DECREF(result);
1877 }
1878 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001879}
1880
1881PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001882PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001883{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001884 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 if (o == NULL)
1887 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 m = o->ob_type->tp_as_sequence;
1890 if (m && m->sq_repeat)
1891 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001892
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 /* Instances of user classes defining a __mul__() method only
1894 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1895 to nb_multiply if o appears to be a sequence. */
1896 if (PySequence_Check(o)) {
1897 PyObject *n, *result;
1898 n = PyInt_FromSsize_t(count);
1899 if (n == NULL)
1900 return NULL;
1901 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1902 Py_DECREF(n);
1903 if (result != Py_NotImplemented)
1904 return result;
1905 Py_DECREF(result);
1906 }
1907 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001908}
1909
1910PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001911PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1912{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001914
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 if (s == NULL || o == NULL)
1916 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 m = s->ob_type->tp_as_sequence;
1919 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1920 return m->sq_inplace_concat(s, o);
1921 if (m && m->sq_concat)
1922 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001923
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001924 if (PySequence_Check(s) && PySequence_Check(o)) {
1925 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1926 NB_SLOT(nb_add));
1927 if (result != Py_NotImplemented)
1928 return result;
1929 Py_DECREF(result);
1930 }
1931 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001932}
1933
1934PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001935PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001937 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001938
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001939 if (o == NULL)
1940 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001941
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 m = o->ob_type->tp_as_sequence;
1943 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1944 return m->sq_inplace_repeat(o, count);
1945 if (m && m->sq_repeat)
1946 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001947
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001948 if (PySequence_Check(o)) {
1949 PyObject *n, *result;
1950 n = PyInt_FromSsize_t(count);
1951 if (n == NULL)
1952 return NULL;
1953 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1954 NB_SLOT(nb_multiply));
1955 Py_DECREF(n);
1956 if (result != Py_NotImplemented)
1957 return result;
1958 Py_DECREF(result);
1959 }
1960 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001961}
1962
1963PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001964PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001965{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001966 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001967
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001968 if (s == NULL)
1969 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001970
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 m = s->ob_type->tp_as_sequence;
1972 if (m && m->sq_item) {
1973 if (i < 0) {
1974 if (m->sq_length) {
1975 Py_ssize_t l = (*m->sq_length)(s);
1976 if (l < 0)
1977 return NULL;
1978 i += l;
1979 }
1980 }
1981 return m->sq_item(s, i);
1982 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001983
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001985}
1986
1987PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001988PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001989{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001990 PySequenceMethods *m;
1991 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001992
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001993 if (!s) return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001994
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001995 m = s->ob_type->tp_as_sequence;
1996 if (m && m->sq_slice) {
1997 if (i1 < 0 || i2 < 0) {
1998 if (m->sq_length) {
1999 Py_ssize_t l = (*m->sq_length)(s);
2000 if (l < 0)
2001 return NULL;
2002 if (i1 < 0)
2003 i1 += l;
2004 if (i2 < 0)
2005 i2 += l;
2006 }
2007 }
2008 return m->sq_slice(s, i1, i2);
2009 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
2010 PyObject *res;
2011 PyObject *slice = _PySlice_FromIndices(i1, i2);
2012 if (!slice)
2013 return NULL;
2014 res = mp->mp_subscript(s, slice);
2015 Py_DECREF(slice);
2016 return res;
2017 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002019 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00002020}
2021
2022int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002023PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002024{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002025 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002027 if (s == NULL) {
2028 null_error();
2029 return -1;
2030 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002032 m = s->ob_type->tp_as_sequence;
2033 if (m && m->sq_ass_item) {
2034 if (i < 0) {
2035 if (m->sq_length) {
2036 Py_ssize_t l = (*m->sq_length)(s);
2037 if (l < 0)
2038 return -1;
2039 i += l;
2040 }
2041 }
2042 return m->sq_ass_item(s, i, o);
2043 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002044
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002045 type_error("'%.200s' object does not support item assignment", s);
2046 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002047}
2048
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002049int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002050PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002052 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002053
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002054 if (s == NULL) {
2055 null_error();
2056 return -1;
2057 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002058
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002059 m = s->ob_type->tp_as_sequence;
2060 if (m && m->sq_ass_item) {
2061 if (i < 0) {
2062 if (m->sq_length) {
2063 Py_ssize_t l = (*m->sq_length)(s);
2064 if (l < 0)
2065 return -1;
2066 i += l;
2067 }
2068 }
2069 return m->sq_ass_item(s, i, (PyObject *)NULL);
2070 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002071
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002072 type_error("'%.200s' object doesn't support item deletion", s);
2073 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002074}
2075
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002076int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002077PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002078{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002079 PySequenceMethods *m;
2080 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00002081
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002082 if (s == NULL) {
2083 null_error();
2084 return -1;
2085 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002087 m = s->ob_type->tp_as_sequence;
2088 if (m && m->sq_ass_slice) {
2089 if (i1 < 0 || i2 < 0) {
2090 if (m->sq_length) {
2091 Py_ssize_t l = (*m->sq_length)(s);
2092 if (l < 0)
2093 return -1;
2094 if (i1 < 0)
2095 i1 += l;
2096 if (i2 < 0)
2097 i2 += l;
2098 }
2099 }
2100 return m->sq_ass_slice(s, i1, i2, o);
2101 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2102 int res;
2103 PyObject *slice = _PySlice_FromIndices(i1, i2);
2104 if (!slice)
2105 return -1;
2106 res = mp->mp_ass_subscript(s, slice, o);
2107 Py_DECREF(slice);
2108 return res;
2109 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00002110
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002111 type_error("'%.200s' object doesn't support slice assignment", s);
2112 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002113}
2114
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002115int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002116PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002120 if (s == NULL) {
2121 null_error();
2122 return -1;
2123 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 m = s->ob_type->tp_as_sequence;
2126 if (m && m->sq_ass_slice) {
2127 if (i1 < 0 || i2 < 0) {
2128 if (m->sq_length) {
2129 Py_ssize_t l = (*m->sq_length)(s);
2130 if (l < 0)
2131 return -1;
2132 if (i1 < 0)
2133 i1 += l;
2134 if (i2 < 0)
2135 i2 += l;
2136 }
2137 }
2138 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2139 }
2140 type_error("'%.200s' object doesn't support slice deletion", s);
2141 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002142}
2143
Guido van Rossume15dee51995-07-18 14:12:02 +00002144PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002145PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00002146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002147 PyObject *it; /* iter(v) */
2148 Py_ssize_t n; /* guess for result tuple size */
2149 PyObject *result = NULL;
2150 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00002151
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002152 if (v == NULL)
2153 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 /* Special-case the common tuple and list cases, for efficiency. */
2156 if (PyTuple_CheckExact(v)) {
2157 /* Note that we can't know whether it's safe to return
2158 a tuple *subclass* instance as-is, hence the restriction
2159 to exact tuples here. In contrast, lists always make
2160 a copy, so there's no need for exactness below. */
2161 Py_INCREF(v);
2162 return v;
2163 }
2164 if (PyList_Check(v))
2165 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 /* Get iterator. */
2168 it = PyObject_GetIter(v);
2169 if (it == NULL)
2170 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002172 /* Guess result size and allocate space. */
2173 n = _PyObject_LengthHint(v, 10);
2174 if (n == -1)
2175 goto Fail;
2176 result = PyTuple_New(n);
2177 if (result == NULL)
2178 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002179
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002180 /* Fill the tuple. */
2181 for (j = 0; ; ++j) {
2182 PyObject *item = PyIter_Next(it);
2183 if (item == NULL) {
2184 if (PyErr_Occurred())
2185 goto Fail;
2186 break;
2187 }
2188 if (j >= n) {
2189 Py_ssize_t oldn = n;
2190 /* The over-allocation strategy can grow a bit faster
2191 than for lists because unlike lists the
2192 over-allocation isn't permanent -- we reclaim
2193 the excess before the end of this routine.
2194 So, grow by ten and then add 25%.
2195 */
2196 n += 10;
2197 n += n >> 2;
2198 if (n < oldn) {
2199 /* Check for overflow */
2200 PyErr_NoMemory();
2201 Py_DECREF(item);
2202 goto Fail;
2203 }
2204 if (_PyTuple_Resize(&result, n) != 0) {
2205 Py_DECREF(item);
2206 goto Fail;
2207 }
2208 }
2209 PyTuple_SET_ITEM(result, j, item);
2210 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002211
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002212 /* Cut tuple back if guess was too large. */
2213 if (j < n &&
2214 _PyTuple_Resize(&result, j) != 0)
2215 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002216
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 Py_DECREF(it);
2218 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002219
2220Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 Py_XDECREF(result);
2222 Py_DECREF(it);
2223 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002224}
2225
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002226PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002227PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002228{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002229 PyObject *result; /* result list */
2230 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002232 if (v == NULL)
2233 return null_error();
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002234
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 result = PyList_New(0);
2236 if (result == NULL)
2237 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002238
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002239 rv = _PyList_Extend((PyListObject *)result, v);
2240 if (rv == NULL) {
2241 Py_DECREF(result);
2242 return NULL;
2243 }
2244 Py_DECREF(rv);
2245 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002246}
2247
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002248PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002249PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002251 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002252
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002253 if (v == NULL)
2254 return null_error();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2257 Py_INCREF(v);
2258 return v;
2259 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002260
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002261 it = PyObject_GetIter(v);
2262 if (it == NULL) {
2263 if (PyErr_ExceptionMatches(PyExc_TypeError))
2264 PyErr_SetString(PyExc_TypeError, m);
2265 return NULL;
2266 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002268 v = PySequence_List(it);
2269 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002270
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002271 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002272}
2273
Tim Peters16a77ad2001-09-08 04:00:12 +00002274/* Iterate over seq. Result depends on the operation:
2275 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00002276 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002277 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002278 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2279*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002280Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002281_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002282{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002283 Py_ssize_t n;
2284 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2285 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002287 if (seq == NULL || obj == NULL) {
2288 null_error();
2289 return -1;
2290 }
Tim Peters75f8e352001-05-05 11:33:43 +00002291
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 it = PyObject_GetIter(seq);
2293 if (it == NULL) {
2294 type_error("argument of type '%.200s' is not iterable", seq);
2295 return -1;
2296 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002297
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002298 n = wrapped = 0;
2299 for (;;) {
2300 int cmp;
2301 PyObject *item = PyIter_Next(it);
2302 if (item == NULL) {
2303 if (PyErr_Occurred())
2304 goto Fail;
2305 break;
2306 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002308 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2309 Py_DECREF(item);
2310 if (cmp < 0)
2311 goto Fail;
2312 if (cmp > 0) {
2313 switch (operation) {
2314 case PY_ITERSEARCH_COUNT:
2315 if (n == PY_SSIZE_T_MAX) {
2316 PyErr_SetString(PyExc_OverflowError,
2317 "count exceeds C integer size");
2318 goto Fail;
2319 }
2320 ++n;
2321 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002322
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002323 case PY_ITERSEARCH_INDEX:
2324 if (wrapped) {
2325 PyErr_SetString(PyExc_OverflowError,
2326 "index exceeds C integer size");
2327 goto Fail;
2328 }
2329 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002331 case PY_ITERSEARCH_CONTAINS:
2332 n = 1;
2333 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002334
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002335 default:
2336 assert(!"unknown operation");
2337 }
2338 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 if (operation == PY_ITERSEARCH_INDEX) {
2341 if (n == PY_SSIZE_T_MAX)
2342 wrapped = 1;
2343 ++n;
2344 }
2345 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002347 if (operation != PY_ITERSEARCH_INDEX)
2348 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002350 PyErr_SetString(PyExc_ValueError,
2351 "sequence.index(x): x not in sequence");
2352 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002353Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 n = -1;
2355 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002356Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002357 Py_DECREF(it);
2358 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002359
Guido van Rossume15dee51995-07-18 14:12:02 +00002360}
2361
Tim Peters16a77ad2001-09-08 04:00:12 +00002362/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002363Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002364PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002365{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002366 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002367}
2368
Tim Peterscb8d3682001-05-05 21:05:01 +00002369/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002370 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002371 */
2372int
2373PySequence_Contains(PyObject *seq, PyObject *ob)
2374{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002375 Py_ssize_t result;
2376 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2377 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2378 if (sqm != NULL && sqm->sq_contains != NULL)
2379 return (*sqm->sq_contains)(seq, ob);
2380 }
2381 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2382 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002383}
2384
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002385/* Backwards compatibility */
2386#undef PySequence_In
2387int
Fred Drake79912472000-07-09 04:06:11 +00002388PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002390 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002391}
2392
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002393Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002394PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002395{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002397}
2398
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002399/* Operations on mappings */
2400
2401int
Fred Drake79912472000-07-09 04:06:11 +00002402PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002403{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002404 if (o && PyInstance_Check(o))
2405 return PyObject_HasAttrString(o, "__getitem__");
Raymond Hettingere2eda602004-04-04 08:51:41 +00002406
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002407 return o && o->ob_type->tp_as_mapping &&
2408 o->ob_type->tp_as_mapping->mp_subscript &&
2409 !(o->ob_type->tp_as_sequence &&
2410 o->ob_type->tp_as_sequence->sq_slice);
Guido van Rossume15dee51995-07-18 14:12:02 +00002411}
2412
Martin v. Löwis18e16552006-02-15 17:27:45 +00002413Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002414PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002415{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002416 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002417
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002418 if (o == NULL) {
2419 null_error();
2420 return -1;
2421 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002423 m = o->ob_type->tp_as_mapping;
2424 if (m && m->mp_length)
2425 return m->mp_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00002426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002427 type_error("object of type '%.200s' has no len()", o);
2428 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002429}
2430
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002431#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002432Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002433PyMapping_Length(PyObject *o)
2434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002435 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002436}
2437#define PyMapping_Length PyMapping_Size
2438
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002439PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002440PyMapping_GetItemString(PyObject *o, char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002444 if (key == NULL)
2445 return null_error();
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002446
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002447 okey = PyString_FromString(key);
2448 if (okey == NULL)
2449 return NULL;
2450 r = PyObject_GetItem(o, okey);
2451 Py_DECREF(okey);
2452 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002453}
2454
2455int
Fred Drake79912472000-07-09 04:06:11 +00002456PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002457{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002458 PyObject *okey;
2459 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002460
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002461 if (key == NULL) {
2462 null_error();
2463 return -1;
2464 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 okey = PyString_FromString(key);
2467 if (okey == NULL)
2468 return -1;
2469 r = PyObject_SetItem(o, okey, value);
2470 Py_DECREF(okey);
2471 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002472}
2473
2474int
Fred Drake79912472000-07-09 04:06:11 +00002475PyMapping_HasKeyString(PyObject *o, char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002476{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002477 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002479 v = PyMapping_GetItemString(o, key);
2480 if (v) {
2481 Py_DECREF(v);
2482 return 1;
2483 }
2484 PyErr_Clear();
2485 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002486}
2487
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002488int
Fred Drake79912472000-07-09 04:06:11 +00002489PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002492
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002493 v = PyObject_GetItem(o, key);
2494 if (v) {
2495 Py_DECREF(v);
2496 return 1;
2497 }
2498 PyErr_Clear();
2499 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002500}
2501
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002502/* Operations on callable objects */
2503
2504/* XXX PyCallable_Check() is in object.c */
2505
Guido van Rossume15dee51995-07-18 14:12:02 +00002506PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002507PyObject_CallObject(PyObject *o, PyObject *a)
Guido van Rossume15dee51995-07-18 14:12:02 +00002508{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002509 return PyEval_CallObjectWithKeywords(o, a, NULL);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002510}
Guido van Rossume15dee51995-07-18 14:12:02 +00002511
2512PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2514{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002515 ternaryfunc call;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002517 if ((call = func->ob_type->tp_call) != NULL) {
2518 PyObject *result;
2519 if (Py_EnterRecursiveCall(" while calling a Python object"))
2520 return NULL;
2521 result = (*call)(func, arg, kw);
2522 Py_LeaveRecursiveCall();
2523 if (result == NULL && !PyErr_Occurred())
2524 PyErr_SetString(
2525 PyExc_SystemError,
2526 "NULL result without error in PyObject_Call");
2527 return result;
2528 }
2529 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2530 func->ob_type->tp_name);
2531 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532}
2533
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002534static PyObject*
2535call_function_tail(PyObject *callable, PyObject *args)
2536{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002537 PyObject *retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002539 if (args == NULL)
2540 return NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002542 if (!PyTuple_Check(args)) {
2543 PyObject *a;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002544
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002545 a = PyTuple_New(1);
2546 if (a == NULL) {
2547 Py_DECREF(args);
2548 return NULL;
2549 }
2550 PyTuple_SET_ITEM(a, 0, args);
2551 args = a;
2552 }
2553 retval = PyObject_Call(callable, args, NULL);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002554
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002555 Py_DECREF(args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002558}
2559
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560PyObject *
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002561PyObject_CallFunction(PyObject *callable, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002563 va_list va;
2564 PyObject *args;
Guido van Rossume15dee51995-07-18 14:12:02 +00002565
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002566 if (callable == NULL)
2567 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002568
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002569 if (format && *format) {
2570 va_start(va, format);
2571 args = Py_VaBuildValue(format, va);
2572 va_end(va);
2573 }
2574 else
2575 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002577 return call_function_tail(callable, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002578}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002579
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002580PyObject *
2581_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2582{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 va_list va;
2584 PyObject *args;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002585
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002586 if (callable == NULL)
2587 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002588
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002589 if (format && *format) {
2590 va_start(va, format);
2591 args = _Py_VaBuildValue_SizeT(format, va);
2592 va_end(va);
2593 }
2594 else
2595 args = PyTuple_New(0);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002596
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002597 return call_function_tail(callable, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002598}
2599
2600PyObject *
Guido van Rossume15dee51995-07-18 14:12:02 +00002601PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002603 va_list va;
2604 PyObject *args;
2605 PyObject *func = NULL;
2606 PyObject *retval = NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002607
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002608 if (o == NULL || name == NULL)
2609 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002610
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002611 func = PyObject_GetAttrString(o, name);
2612 if (func == NULL) {
2613 PyErr_SetString(PyExc_AttributeError, name);
2614 return 0;
2615 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002616
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002617 if (!PyCallable_Check(func)) {
2618 type_error("attribute of type '%.200s' is not callable", func);
2619 goto exit;
2620 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002622 if (format && *format) {
2623 va_start(va, format);
2624 args = Py_VaBuildValue(format, va);
2625 va_end(va);
2626 }
2627 else
2628 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002629
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002630 retval = call_function_tail(func, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002631
Michael W. Hudson0edc7a02005-07-12 10:21:19 +00002632 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002633 /* args gets consumed in call_function_tail */
2634 Py_XDECREF(func);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002636 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002637}
2638
2639PyObject *
2640_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2641{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002642 va_list va;
2643 PyObject *args;
2644 PyObject *func = NULL;
2645 PyObject *retval = NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002646
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002647 if (o == NULL || name == NULL)
2648 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002650 func = PyObject_GetAttrString(o, name);
2651 if (func == NULL) {
2652 PyErr_SetString(PyExc_AttributeError, name);
2653 return 0;
2654 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002656 if (!PyCallable_Check(func)) {
2657 type_error("attribute of type '%.200s' is not callable", func);
2658 goto exit;
2659 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 if (format && *format) {
2662 va_start(va, format);
2663 args = _Py_VaBuildValue_SizeT(format, va);
2664 va_end(va);
2665 }
2666 else
2667 args = PyTuple_New(0);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002668
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 retval = call_function_tail(func, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002670
2671 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002672 /* args gets consumed in call_function_tail */
2673 Py_XDECREF(func);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 return retval;
Guido van Rossume15dee51995-07-18 14:12:02 +00002676}
Guido van Rossum823649d2001-03-21 18:40:58 +00002677
2678
Fred Drakeb421b8c2001-10-26 16:21:32 +00002679static PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002680objargs_mktuple(va_list va)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 int i, n = 0;
2683 va_list countva;
2684 PyObject *result, *tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002685
2686#ifdef VA_LIST_IS_ARRAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 memcpy(countva, va, sizeof(va_list));
Fred Drakeb421b8c2001-10-26 16:21:32 +00002688#else
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002689#ifdef __va_copy
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002690 __va_copy(countva, va);
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002691#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 countva = va;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002693#endif
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002694#endif
Fred Drakeb421b8c2001-10-26 16:21:32 +00002695
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002696 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2697 ++n;
2698 result = PyTuple_New(n);
2699 if (result != NULL && n > 0) {
2700 for (i = 0; i < n; ++i) {
2701 tmp = (PyObject *)va_arg(va, PyObject *);
2702 PyTuple_SET_ITEM(result, i, tmp);
2703 Py_INCREF(tmp);
2704 }
2705 }
2706 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002707}
2708
2709PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002710PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002712 PyObject *args, *tmp;
2713 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002714
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002715 if (callable == NULL || name == NULL)
2716 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002718 callable = PyObject_GetAttr(callable, name);
2719 if (callable == NULL)
2720 return NULL;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002722 /* count the args */
2723 va_start(vargs, name);
2724 args = objargs_mktuple(vargs);
2725 va_end(vargs);
2726 if (args == NULL) {
2727 Py_DECREF(callable);
2728 return NULL;
2729 }
2730 tmp = PyObject_Call(callable, args, NULL);
2731 Py_DECREF(args);
2732 Py_DECREF(callable);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002734 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002735}
2736
2737PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002738PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002739{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 PyObject *args, *tmp;
2741 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 if (callable == NULL)
2744 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002746 /* count the args */
2747 va_start(vargs, callable);
2748 args = objargs_mktuple(vargs);
2749 va_end(vargs);
2750 if (args == NULL)
2751 return NULL;
2752 tmp = PyObject_Call(callable, args, NULL);
2753 Py_DECREF(args);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002756}
2757
2758
Guido van Rossum823649d2001-03-21 18:40:58 +00002759/* isinstance(), issubclass() */
2760
Barry Warsawf16951c2002-04-23 22:45:44 +00002761/* abstract_get_bases() has logically 4 return states, with a sort of 0th
2762 * state that will almost never happen.
2763 *
2764 * 0. creating the __bases__ static string could get a MemoryError
2765 * 1. getattr(cls, '__bases__') could raise an AttributeError
2766 * 2. getattr(cls, '__bases__') could raise some other exception
2767 * 3. getattr(cls, '__bases__') could return a tuple
2768 * 4. getattr(cls, '__bases__') could return something other than a tuple
2769 *
2770 * Only state #3 is a non-error state and only it returns a non-NULL object
2771 * (it returns the retrieved tuple).
2772 *
2773 * Any raised AttributeErrors are masked by clearing the exception and
2774 * returning NULL. If an object other than a tuple comes out of __bases__,
2775 * then again, the return value is NULL. So yes, these two situations
2776 * produce exactly the same results: NULL is returned and no error is set.
2777 *
2778 * If some exception other than AttributeError is raised, then NULL is also
2779 * returned, but the exception is not cleared. That's because we want the
2780 * exception to be propagated along.
2781 *
2782 * Callers are expected to test for PyErr_Occurred() when the return value
2783 * is NULL to decide whether a valid exception should be propagated or not.
2784 * When there's no exception to propagate, it's customary for the caller to
2785 * set a TypeError.
2786 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002787static PyObject *
2788abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002789{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002790 static PyObject *__bases__ = NULL;
2791 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002792
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002793 if (__bases__ == NULL) {
2794 __bases__ = PyString_InternFromString("__bases__");
2795 if (__bases__ == NULL)
2796 return NULL;
2797 }
2798 bases = PyObject_GetAttr(cls, __bases__);
2799 if (bases == NULL) {
2800 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2801 PyErr_Clear();
2802 return NULL;
2803 }
2804 if (!PyTuple_Check(bases)) {
2805 Py_DECREF(bases);
2806 return NULL;
2807 }
2808 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002809}
2810
2811
2812static int
2813abstract_issubclass(PyObject *derived, PyObject *cls)
2814{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002815 PyObject *bases = NULL;
2816 Py_ssize_t i, n;
2817 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002819 while (1) {
2820 if (derived == cls)
2821 return 1;
2822 bases = abstract_get_bases(derived);
2823 if (bases == NULL) {
2824 if (PyErr_Occurred())
2825 return -1;
2826 return 0;
2827 }
2828 n = PyTuple_GET_SIZE(bases);
2829 if (n == 0) {
2830 Py_DECREF(bases);
2831 return 0;
2832 }
2833 /* Avoid recursivity in the single inheritance case */
2834 if (n == 1) {
2835 derived = PyTuple_GET_ITEM(bases, 0);
2836 Py_DECREF(bases);
2837 continue;
2838 }
2839 for (i = 0; i < n; i++) {
2840 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2841 if (r != 0)
2842 break;
2843 }
2844 Py_DECREF(bases);
2845 return r;
2846 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002847}
2848
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002849static int
2850check_class(PyObject *cls, const char *error)
2851{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002852 PyObject *bases = abstract_get_bases(cls);
2853 if (bases == NULL) {
2854 /* Do not mask errors. */
2855 if (!PyErr_Occurred())
2856 PyErr_SetString(PyExc_TypeError, error);
2857 return 0;
2858 }
2859 Py_DECREF(bases);
2860 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002861}
2862
Brett Cannon4f653312004-03-20 22:52:14 +00002863static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002864recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002865{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002866 PyObject *icls;
2867 static PyObject *__class__ = NULL;
2868 int retval = 0;
Guido van Rossum823649d2001-03-21 18:40:58 +00002869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002870 if (__class__ == NULL) {
2871 __class__ = PyString_InternFromString("__class__");
2872 if (__class__ == NULL)
2873 return -1;
2874 }
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002876 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2877 PyObject *inclass =
2878 (PyObject*)((PyInstanceObject*)inst)->in_class;
2879 retval = PyClass_IsSubclass(inclass, cls);
2880 }
2881 else if (PyType_Check(cls)) {
2882 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2883 if (retval == 0) {
2884 PyObject *c = PyObject_GetAttr(inst, __class__);
2885 if (c == NULL) {
2886 PyErr_Clear();
2887 }
2888 else {
2889 if (c != (PyObject *)(inst->ob_type) &&
2890 PyType_Check(c))
2891 retval = PyType_IsSubtype(
2892 (PyTypeObject *)c,
2893 (PyTypeObject *)cls);
2894 Py_DECREF(c);
2895 }
2896 }
2897 }
2898 else {
2899 if (!check_class(cls,
2900 "isinstance() arg 2 must be a class, type,"
2901 " or tuple of classes and types"))
2902 return -1;
2903 icls = PyObject_GetAttr(inst, __class__);
2904 if (icls == NULL) {
2905 PyErr_Clear();
2906 retval = 0;
2907 }
2908 else {
2909 retval = abstract_issubclass(icls, cls);
2910 Py_DECREF(icls);
2911 }
2912 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002913
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002914 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002915}
2916
2917int
Brett Cannon4f653312004-03-20 22:52:14 +00002918PyObject_IsInstance(PyObject *inst, PyObject *cls)
2919{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002920 static PyObject *name = NULL;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002922 /* Quick test for an exact match */
2923 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2924 return 1;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002925
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002926 if (PyTuple_Check(cls)) {
2927 Py_ssize_t i;
2928 Py_ssize_t n;
2929 int r = 0;
Antoine Pitrou0668c622008-08-26 22:42:08 +00002930
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002931 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2932 return -1;
2933 n = PyTuple_GET_SIZE(cls);
2934 for (i = 0; i < n; ++i) {
2935 PyObject *item = PyTuple_GET_ITEM(cls, i);
2936 r = PyObject_IsInstance(inst, item);
2937 if (r != 0)
2938 /* either found it, or got an error */
2939 break;
2940 }
2941 Py_LeaveRecursiveCall();
2942 return r;
2943 }
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00002944
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002945 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
2946 PyObject *checker;
2947 checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
2948 if (checker != NULL) {
2949 PyObject *res;
2950 int ok = -1;
2951 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2952 Py_DECREF(checker);
2953 return ok;
2954 }
2955 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2956 Py_LeaveRecursiveCall();
2957 Py_DECREF(checker);
2958 if (res != NULL) {
2959 ok = PyObject_IsTrue(res);
2960 Py_DECREF(res);
2961 }
2962 return ok;
2963 }
2964 else if (PyErr_Occurred())
2965 return -1;
2966 }
2967 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002968}
2969
2970static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002971recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002972{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002973 int retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002975 if (PyType_Check(cls) && PyType_Check(derived)) {
2976 /* Fast path (non-recursive) */
2977 return PyType_IsSubtype(
2978 (PyTypeObject *)derived, (PyTypeObject *)cls);
2979 }
2980 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2981 if (!check_class(derived,
2982 "issubclass() arg 1 must be a class"))
2983 return -1;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002984
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002985 if (!check_class(cls,
2986 "issubclass() arg 2 must be a class"
2987 " or tuple of classes"))
2988 return -1;
2989 retval = abstract_issubclass(derived, cls);
2990 }
2991 else {
2992 /* shortcut */
2993 if (!(retval = (derived == cls)))
2994 retval = PyClass_IsSubclass(derived, cls);
2995 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002997 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002998}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002999
Brett Cannon4f653312004-03-20 22:52:14 +00003000int
3001PyObject_IsSubclass(PyObject *derived, PyObject *cls)
3002{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003003 static PyObject *name = NULL;
3004
3005 if (PyTuple_Check(cls)) {
3006 Py_ssize_t i;
3007 Py_ssize_t n;
3008 int r = 0;
3009
3010 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3011 return -1;
3012 n = PyTuple_GET_SIZE(cls);
3013 for (i = 0; i < n; ++i) {
3014 PyObject *item = PyTuple_GET_ITEM(cls, i);
3015 r = PyObject_IsSubclass(derived, item);
3016 if (r != 0)
3017 /* either found it, or got an error */
3018 break;
3019 }
3020 Py_LeaveRecursiveCall();
3021 return r;
3022 }
3023 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
3024 PyObject *checker;
3025 checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
3026 if (checker != NULL) {
3027 PyObject *res;
3028 int ok = -1;
3029 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3030 Py_DECREF(checker);
3031 return ok;
3032 }
3033 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3034 Py_LeaveRecursiveCall();
3035 Py_DECREF(checker);
3036 if (res != NULL) {
3037 ok = PyObject_IsTrue(res);
3038 Py_DECREF(res);
3039 }
3040 return ok;
3041 }
3042 else if (PyErr_Occurred()) {
3043 return -1;
3044 }
3045 }
3046 return recursive_issubclass(derived, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003047}
3048
3049int
3050_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003052 return recursive_isinstance(inst, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003053}
3054
3055int
3056_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003058 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003059}
3060
3061
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003062PyObject *
3063PyObject_GetIter(PyObject *o)
3064{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003065 PyTypeObject *t = o->ob_type;
3066 getiterfunc f = NULL;
3067 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3068 f = t->tp_iter;
3069 if (f == NULL) {
3070 if (PySequence_Check(o))
3071 return PySeqIter_New(o);
3072 return type_error("'%.200s' object is not iterable", o);
3073 }
3074 else {
3075 PyObject *res = (*f)(o);
3076 if (res != NULL && !PyIter_Check(res)) {
3077 PyErr_Format(PyExc_TypeError,
3078 "iter() returned non-iterator "
3079 "of type '%.100s'",
3080 res->ob_type->tp_name);
3081 Py_DECREF(res);
3082 res = NULL;
3083 }
3084 return res;
3085 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00003086}
3087
Tim Petersf4848da2001-05-05 00:14:56 +00003088/* Return next item.
3089 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3090 * If the iteration terminates normally, return NULL and clear the
3091 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3092 * will be false.
3093 * Else return the next object. PyErr_Occurred() will be false.
3094 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00003095PyObject *
3096PyIter_Next(PyObject *iter)
3097{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003098 PyObject *result;
3099 result = (*iter->ob_type->tp_iternext)(iter);
3100 if (result == NULL &&
3101 PyErr_Occurred() &&
3102 PyErr_ExceptionMatches(PyExc_StopIteration))
3103 PyErr_Clear();
3104 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003105}