blob: 761e035da3ca66a5f8b183120383548f170c4e59 [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 static PyObject * str__format__ = NULL;
727 PyObject *empty = NULL;
728 PyObject *result = NULL;
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000729#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000730 int spec_is_unicode;
731 int result_is_unicode;
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000732#endif
Eric Smitha9f7d622008-02-17 19:46:49 +0000733
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 /* Initialize cached value */
735 if (str__format__ == NULL) {
736 /* Initialize static variable needed by _PyType_Lookup */
737 str__format__ = PyString_InternFromString("__format__");
738 if (str__format__ == NULL)
739 goto done;
740 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000741
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 /* If no format_spec is provided, use an empty string */
743 if (format_spec == NULL) {
744 empty = PyString_FromStringAndSize(NULL, 0);
745 format_spec = empty;
746 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000747
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000748 /* Check the format_spec type, and make sure it's str or unicode */
Hirokazu Yamamoto1e234e82009-01-25 17:46:48 +0000749#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 if (PyUnicode_Check(format_spec))
751 spec_is_unicode = 1;
752 else if (PyString_Check(format_spec))
753 spec_is_unicode = 0;
754 else {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000755#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000756 if (!PyString_Check(format_spec)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000757#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 PyErr_Format(PyExc_TypeError,
759 "format expects arg 2 to be string "
760 "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
761 goto done;
762 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000763
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 /* Make sure the type is initialized. float gets initialized late */
765 if (Py_TYPE(obj)->tp_dict == NULL)
766 if (PyType_Ready(Py_TYPE(obj)) < 0)
767 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000768
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000769 /* Check for a __format__ method and call it. */
770 if (PyInstance_Check(obj)) {
771 /* We're an instance of a classic class */
772 PyObject *bound_method = PyObject_GetAttr(obj,
773 str__format__);
774 if (bound_method != NULL) {
775 result = PyObject_CallFunctionObjArgs(bound_method,
776 format_spec,
777 NULL);
778 Py_DECREF(bound_method);
779 } else {
780 PyObject *self_as_str = NULL;
781 PyObject *format_method = NULL;
782 Py_ssize_t format_len;
Eric Smitha9f7d622008-02-17 19:46:49 +0000783
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 PyErr_Clear();
785 /* Per the PEP, convert to str (or unicode,
786 depending on the type of the format
787 specifier). For new-style classes, this
788 logic is done by object.__format__(). */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000789#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 if (spec_is_unicode) {
791 format_len = PyUnicode_GET_SIZE(format_spec);
792 self_as_str = PyObject_Unicode(obj);
793 } else
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000794#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000795 {
796 format_len = PyString_GET_SIZE(format_spec);
797 self_as_str = PyObject_Str(obj);
798 }
799 if (self_as_str == NULL)
800 goto done1;
Eric Smithd44b2fc2010-04-02 12:30:56 +0000801
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 if (format_len > 0) {
803 /* See the almost identical code in
804 typeobject.c for new-style
805 classes. */
806 if (PyErr_WarnEx(
807 PyExc_PendingDeprecationWarning,
808 "object.__format__ with a non-empty "
809 "format string is deprecated", 1)
810 < 0) {
811 goto done1;
812 }
813 /* Eventually this will become an
814 error:
815 PyErr_Format(PyExc_TypeError,
816 "non-empty format string passed to "
817 "object.__format__");
818 goto done1;
819 */
820 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000821
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000822 /* Then call str.__format__ on that result */
823 format_method = PyObject_GetAttr(self_as_str,
824 str__format__);
825 if (format_method == NULL) {
826 goto done1;
827 }
828 result = PyObject_CallFunctionObjArgs(format_method,
829 format_spec,
830 NULL);
Eric Smithd44b2fc2010-04-02 12:30:56 +0000831done1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000832 Py_XDECREF(self_as_str);
833 Py_XDECREF(format_method);
834 if (result == NULL)
835 goto done;
836 }
837 } else {
838 /* Not an instance of a classic class, use the code
839 from py3k */
Eric Smitha9f7d622008-02-17 19:46:49 +0000840
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000841 /* Find the (unbound!) __format__ method (a borrowed
842 reference) */
843 PyObject *method = _PyType_Lookup(Py_TYPE(obj),
844 str__format__);
845 if (method == NULL) {
846 PyErr_Format(PyExc_TypeError,
847 "Type %.100s doesn't define __format__",
848 Py_TYPE(obj)->tp_name);
849 goto done;
850 }
851 /* And call it, binding it to the value */
852 result = PyObject_CallFunctionObjArgs(method, obj,
853 format_spec, NULL);
854 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000855
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000856 if (result == NULL)
857 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000858
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 /* Check the result type, and make sure it's str or unicode */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000860#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000861 if (PyUnicode_Check(result))
862 result_is_unicode = 1;
863 else if (PyString_Check(result))
864 result_is_unicode = 0;
865 else {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000866#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 if (!PyString_Check(result)) {
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000868#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000869 PyErr_Format(PyExc_TypeError,
870 "%.100s.__format__ must return string or "
871 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
872 Py_TYPE(result)->tp_name);
873 Py_DECREF(result);
874 result = NULL;
875 goto done;
876 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000877
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000878 /* Convert to unicode, if needed. Required if spec is unicode
879 and result is str */
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000880#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000881 if (spec_is_unicode && !result_is_unicode) {
882 PyObject *tmp = PyObject_Unicode(result);
883 /* This logic works whether or not tmp is NULL */
884 Py_DECREF(result);
885 result = tmp;
886 }
Benjamin Peterson78821dd2009-01-25 17:15:10 +0000887#endif
Eric Smitha9f7d622008-02-17 19:46:49 +0000888
889done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000890 Py_XDECREF(empty);
891 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +0000892}
893
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000894/* Operations on numbers */
895
896int
Fred Drake79912472000-07-09 04:06:11 +0000897PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 return o && o->ob_type->tp_as_number &&
900 (o->ob_type->tp_as_number->nb_int ||
901 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000902}
903
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000904/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000905
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000906/* New style number protocol support */
Guido van Rossume15dee51995-07-18 14:12:02 +0000907
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000908#define NB_SLOT(x) offsetof(PyNumberMethods, x)
909#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000910 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000911#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000912 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000913
914/*
915 Calling scheme used for binary operations:
916
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000917 v w Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000918 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
920 new old v.op(v,w), coerce(v,w), v.op(v,w)
921 old new w.op(v,w), coerce(v,w), v.op(v,w)
922 old old coerce(v,w), v.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000923
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000924 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
925 v->ob_type
926
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000927 Legend:
928 -------
929 * new == new style number
930 * old == old style number
931 * Action indicates the order in which operations are tried until either
932 a valid result is produced or an error occurs.
933
934 */
935
936static PyObject *
937binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000938{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 PyObject *x;
940 binaryfunc slotv = NULL;
941 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000942
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
944 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
945 if (w->ob_type != v->ob_type &&
946 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
947 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
948 if (slotw == slotv)
949 slotw = NULL;
950 }
951 if (slotv) {
952 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
953 x = slotw(v, w);
954 if (x != Py_NotImplemented)
955 return x;
956 Py_DECREF(x); /* can't do it */
957 slotw = NULL;
958 }
959 x = slotv(v, w);
960 if (x != Py_NotImplemented)
961 return x;
962 Py_DECREF(x); /* can't do it */
963 }
964 if (slotw) {
965 x = slotw(v, w);
966 if (x != Py_NotImplemented)
967 return x;
968 Py_DECREF(x); /* can't do it */
969 }
970 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
971 int err = PyNumber_CoerceEx(&v, &w);
972 if (err < 0) {
973 return NULL;
974 }
975 if (err == 0) {
976 PyNumberMethods *mv = v->ob_type->tp_as_number;
977 if (mv) {
978 binaryfunc slot;
979 slot = NB_BINOP(mv, op_slot);
980 if (slot) {
981 x = slot(v, w);
982 Py_DECREF(v);
983 Py_DECREF(w);
984 return x;
985 }
986 }
987 /* CoerceEx incremented the reference counts */
988 Py_DECREF(v);
989 Py_DECREF(w);
990 }
991 }
992 Py_INCREF(Py_NotImplemented);
993 return Py_NotImplemented;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000994}
Guido van Rossum77660912002-04-16 16:32:50 +0000995
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000996static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000997binop_type_error(PyObject *v, PyObject *w, const char *op_name)
998{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 PyErr_Format(PyExc_TypeError,
1000 "unsupported operand type(s) for %.100s: "
1001 "'%.100s' and '%.100s'",
1002 op_name,
1003 v->ob_type->tp_name,
1004 w->ob_type->tp_name);
1005 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001006}
1007
1008static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001009binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
1010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 PyObject *result = binary_op1(v, w, op_slot);
1012 if (result == Py_NotImplemented) {
1013 Py_DECREF(result);
1014 return binop_type_error(v, w, op_name);
1015 }
1016 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001017}
1018
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001019
1020/*
1021 Calling scheme used for ternary operations:
1022
Guido van Rossum84675ac2001-09-29 01:05:03 +00001023 *** In some cases, w.op is called before v.op; see binary_op1. ***
1024
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001025 v w z Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001026 -------------------------------------------------------------------
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1028 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1029 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1030 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1031 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1032 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1033 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1034 old old old coerce(v,w,z), v.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001035
1036 Legend:
1037 -------
1038 * new == new style number
1039 * old == old style number
1040 * Action indicates the order in which operations are tried until either
1041 a valid result is produced or an error occurs.
1042 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1043 only if z != Py_None; if z == Py_None, then it is treated as absent
1044 variable and only coerce(v,w) is tried.
1045
1046 */
1047
1048static PyObject *
1049ternary_op(PyObject *v,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 PyObject *w,
1051 PyObject *z,
1052 const int op_slot,
1053 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +00001054{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001055 PyNumberMethods *mv, *mw, *mz;
1056 PyObject *x = NULL;
1057 ternaryfunc slotv = NULL;
1058 ternaryfunc slotw = NULL;
1059 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +00001060
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001061 mv = v->ob_type->tp_as_number;
1062 mw = w->ob_type->tp_as_number;
1063 if (mv != NULL && NEW_STYLE_NUMBER(v))
1064 slotv = NB_TERNOP(mv, op_slot);
1065 if (w->ob_type != v->ob_type &&
1066 mw != NULL && NEW_STYLE_NUMBER(w)) {
1067 slotw = NB_TERNOP(mw, op_slot);
1068 if (slotw == slotv)
1069 slotw = NULL;
1070 }
1071 if (slotv) {
1072 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1073 x = slotw(v, w, z);
1074 if (x != Py_NotImplemented)
1075 return x;
1076 Py_DECREF(x); /* can't do it */
1077 slotw = NULL;
1078 }
1079 x = slotv(v, w, z);
1080 if (x != Py_NotImplemented)
1081 return x;
1082 Py_DECREF(x); /* can't do it */
1083 }
1084 if (slotw) {
1085 x = slotw(v, w, z);
1086 if (x != Py_NotImplemented)
1087 return x;
1088 Py_DECREF(x); /* can't do it */
1089 }
1090 mz = z->ob_type->tp_as_number;
1091 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1092 slotz = NB_TERNOP(mz, op_slot);
1093 if (slotz == slotv || slotz == slotw)
1094 slotz = NULL;
1095 if (slotz) {
1096 x = slotz(v, w, z);
1097 if (x != Py_NotImplemented)
1098 return x;
1099 Py_DECREF(x); /* can't do it */
1100 }
1101 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001103 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1104 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1105 /* we have an old style operand, coerce */
1106 PyObject *v1, *z1, *w2, *z2;
1107 int c;
Guido van Rossum77660912002-04-16 16:32:50 +00001108
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001109 c = PyNumber_Coerce(&v, &w);
1110 if (c != 0)
1111 goto error3;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001112
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 /* Special case: if the third argument is None, it is
1114 treated as absent argument and not coerced. */
1115 if (z == Py_None) {
1116 if (v->ob_type->tp_as_number) {
1117 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1118 op_slot);
1119 if (slotz)
1120 x = slotz(v, w, z);
1121 else
1122 c = -1;
1123 }
1124 else
1125 c = -1;
1126 goto error2;
1127 }
1128 v1 = v;
1129 z1 = z;
1130 c = PyNumber_Coerce(&v1, &z1);
1131 if (c != 0)
1132 goto error2;
1133 w2 = w;
1134 z2 = z1;
1135 c = PyNumber_Coerce(&w2, &z2);
1136 if (c != 0)
1137 goto error1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001139 if (v1->ob_type->tp_as_number != NULL) {
1140 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1141 op_slot);
1142 if (slotv)
1143 x = slotv(v1, w2, z2);
1144 else
1145 c = -1;
1146 }
1147 else
1148 c = -1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001149
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001150 Py_DECREF(w2);
1151 Py_DECREF(z2);
1152 error1:
1153 Py_DECREF(v1);
1154 Py_DECREF(z1);
1155 error2:
1156 Py_DECREF(v);
1157 Py_DECREF(w);
1158 error3:
1159 if (c >= 0)
1160 return x;
1161 }
Guido van Rossum5c66a262001-10-22 04:12:44 +00001162
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001163 if (z == Py_None)
1164 PyErr_Format(
1165 PyExc_TypeError,
1166 "unsupported operand type(s) for ** or pow(): "
1167 "'%.100s' and '%.100s'",
1168 v->ob_type->tp_name,
1169 w->ob_type->tp_name);
1170 else
1171 PyErr_Format(
1172 PyExc_TypeError,
1173 "unsupported operand type(s) for pow(): "
1174 "'%.100s', '%.100s', '%.100s'",
1175 v->ob_type->tp_name,
1176 w->ob_type->tp_name,
1177 z->ob_type->tp_name);
1178 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001179}
1180
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001181#define BINARY_FUNC(func, op, op_name) \
1182 PyObject * \
1183 func(PyObject *v, PyObject *w) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001184 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001185 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001186
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001187BINARY_FUNC(PyNumber_Or, nb_or, "|")
1188BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1189BINARY_FUNC(PyNumber_And, nb_and, "&")
1190BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1191BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1192BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001193BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1194BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001195
1196PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001197PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001198{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001199 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1200 if (result == Py_NotImplemented) {
1201 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1202 Py_DECREF(result);
1203 if (m && m->sq_concat) {
1204 return (*m->sq_concat)(v, w);
1205 }
1206 result = binop_type_error(v, w, "+");
1207 }
1208 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001209}
1210
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001211static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001213{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001214 Py_ssize_t count;
1215 if (PyIndex_Check(n)) {
1216 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1217 if (count == -1 && PyErr_Occurred())
1218 return NULL;
1219 }
1220 else {
1221 return type_error("can't multiply sequence by "
1222 "non-int of type '%.200s'", n);
1223 }
1224 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001225}
1226
1227PyObject *
1228PyNumber_Multiply(PyObject *v, PyObject *w)
1229{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1231 if (result == Py_NotImplemented) {
1232 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1233 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1234 Py_DECREF(result);
1235 if (mv && mv->sq_repeat) {
1236 return sequence_repeat(mv->sq_repeat, v, w);
1237 }
1238 else if (mw && mw->sq_repeat) {
1239 return sequence_repeat(mw->sq_repeat, w, v);
1240 }
1241 result = binop_type_error(v, w, "*");
1242 }
1243 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001244}
1245
Guido van Rossume15dee51995-07-18 14:12:02 +00001246PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001247PyNumber_FloorDivide(PyObject *v, PyObject *w)
1248{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001249 /* XXX tp_flags test */
1250 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001251}
1252
1253PyObject *
1254PyNumber_TrueDivide(PyObject *v, PyObject *w)
1255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 /* XXX tp_flags test */
1257 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001258}
1259
1260PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001261PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001262{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001263 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001264}
1265
1266PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001267PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001268{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001269 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001270}
1271
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001272/* Binary in-place operators */
1273
1274/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001275 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001276
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001277 - If the left hand object has the appropriate struct members, and
1278 they are filled, call the appropriate function and return the
1279 result. No coercion is done on the arguments; the left-hand object
1280 is the one the operation is performed on, and it's up to the
1281 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001282
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001283 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001284 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001285
1286 */
1287
Guido van Rossum77660912002-04-16 16:32:50 +00001288#define HASINPLACE(t) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001289 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001290
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001291static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001292binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001293{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001294 PyNumberMethods *mv = v->ob_type->tp_as_number;
1295 if (mv != NULL && HASINPLACE(v)) {
1296 binaryfunc slot = NB_BINOP(mv, iop_slot);
1297 if (slot) {
1298 PyObject *x = (slot)(v, w);
1299 if (x != Py_NotImplemented) {
1300 return x;
1301 }
1302 Py_DECREF(x);
1303 }
1304 }
1305 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001306}
1307
1308static PyObject *
1309binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001310 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001311{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001312 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1313 if (result == Py_NotImplemented) {
1314 Py_DECREF(result);
1315 return binop_type_error(v, w, op_name);
1316 }
1317 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001318}
1319
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001320#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001321 PyObject * \
1322 func(PyObject *v, PyObject *w) { \
1323 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1324 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001325
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001326INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1327INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1328INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1329INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1330INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1331INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1332INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001333
1334PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001335PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 /* XXX tp_flags test */
1338 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1339 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001340}
1341
1342PyObject *
1343PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001345 /* XXX tp_flags test */
1346 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1347 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001348}
1349
1350PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001351PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1352{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1354 NB_SLOT(nb_add));
1355 if (result == Py_NotImplemented) {
1356 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1357 Py_DECREF(result);
1358 if (m != NULL) {
1359 binaryfunc f = NULL;
1360 if (HASINPLACE(v))
1361 f = m->sq_inplace_concat;
1362 if (f == NULL)
1363 f = m->sq_concat;
1364 if (f != NULL)
1365 return (*f)(v, w);
1366 }
1367 result = binop_type_error(v, w, "+=");
1368 }
1369 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001370}
1371
1372PyObject *
1373PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1374{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1376 NB_SLOT(nb_multiply));
1377 if (result == Py_NotImplemented) {
1378 ssizeargfunc f = NULL;
1379 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1380 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1381 Py_DECREF(result);
1382 if (mv != NULL) {
1383 if (HASINPLACE(v))
1384 f = mv->sq_inplace_repeat;
1385 if (f == NULL)
1386 f = mv->sq_repeat;
1387 if (f != NULL)
1388 return sequence_repeat(f, v, w);
1389 }
1390 else if (mw != NULL) {
1391 /* Note that the right hand operand should not be
1392 * mutated in this case so sq_inplace_repeat is not
1393 * used. */
1394 if (mw->sq_repeat)
1395 return sequence_repeat(mw->sq_repeat, w, v);
1396 }
1397 result = binop_type_error(v, w, "*=");
1398 }
1399 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001400}
1401
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001402PyObject *
1403PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1404{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001405 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1406 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001407}
1408
1409PyObject *
1410PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1411{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1413 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1414 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1415 }
1416 else {
1417 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1418 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001419}
1420
1421
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001422/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001423
1424PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001425PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001426{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001428
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001429 if (o == NULL)
1430 return null_error();
1431 m = o->ob_type->tp_as_number;
1432 if (m && m->nb_negative)
1433 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001434
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001436}
1437
1438PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001439PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001441 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 if (o == NULL)
1444 return null_error();
1445 m = o->ob_type->tp_as_number;
1446 if (m && m->nb_positive)
1447 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001450}
1451
1452PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001453PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001454{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 if (o == NULL)
1458 return null_error();
1459 m = o->ob_type->tp_as_number;
1460 if (m && m->nb_invert)
1461 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001464}
1465
1466PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001467PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001468{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001469 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001471 if (o == NULL)
1472 return null_error();
1473 m = o->ob_type->tp_as_number;
1474 if (m && m->nb_absolute)
1475 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001478}
1479
Guido van Rossum9e896b32000-04-05 20:11:21 +00001480/* Add a check for embedded NULL-bytes in the argument. */
1481static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001482int_from_string(const char *s, Py_ssize_t len)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001483{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484 char *end;
1485 PyObject *x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001487 x = PyInt_FromString((char*)s, &end, 10);
1488 if (x == NULL)
1489 return NULL;
1490 if (end != s + len) {
1491 PyErr_SetString(PyExc_ValueError,
1492 "null byte in argument for int()");
1493 Py_DECREF(x);
1494 return NULL;
1495 }
1496 return x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001497}
1498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499/* Return a Python Int or Long from the object item
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001500 Raise TypeError if the result is not an int-or-long
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 or if the object cannot be interpreted as an index.
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001502*/
1503PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001504PyNumber_Index(PyObject *item)
1505{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 PyObject *result = NULL;
1507 if (item == NULL)
1508 return null_error();
1509 if (PyInt_Check(item) || PyLong_Check(item)) {
1510 Py_INCREF(item);
1511 return item;
1512 }
1513 if (PyIndex_Check(item)) {
1514 result = item->ob_type->tp_as_number->nb_index(item);
1515 if (result &&
1516 !PyInt_Check(result) && !PyLong_Check(result)) {
1517 PyErr_Format(PyExc_TypeError,
1518 "__index__ returned non-(int,long) " \
1519 "(type %.200s)",
1520 result->ob_type->tp_name);
1521 Py_DECREF(result);
1522 return NULL;
1523 }
1524 }
1525 else {
1526 PyErr_Format(PyExc_TypeError,
1527 "'%.200s' object cannot be interpreted "
1528 "as an index", item->ob_type->tp_name);
1529 }
1530 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001531}
1532
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001533/* Return an error on Overflow only if err is not NULL*/
1534
1535Py_ssize_t
1536PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1537{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 Py_ssize_t result;
1539 PyObject *runerr;
1540 PyObject *value = PyNumber_Index(item);
1541 if (value == NULL)
1542 return -1;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001543
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001544 /* We're done if PyInt_AsSsize_t() returns without error. */
1545 result = PyInt_AsSsize_t(value);
1546 if (result != -1 || !(runerr = PyErr_Occurred()))
1547 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 /* Error handling code -- only manage OverflowError differently */
1550 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1551 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 PyErr_Clear();
1554 /* If no error-handling desired then the default clipping
1555 is sufficient.
1556 */
1557 if (!err) {
1558 assert(PyLong_Check(value));
1559 /* Whether or not it is less than or equal to
1560 zero is determined by the sign of ob_size
1561 */
1562 if (_PyLong_Sign(value) < 0)
1563 result = PY_SSIZE_T_MIN;
1564 else
1565 result = PY_SSIZE_T_MAX;
1566 }
1567 else {
1568 /* Otherwise replace the error with caller's error object. */
1569 PyErr_Format(err,
1570 "cannot fit '%.200s' into an index-sized integer",
1571 item->ob_type->tp_name);
1572 }
1573
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001574 finish:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001575 Py_DECREF(value);
1576 return result;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001577}
1578
1579
Guido van Rossume15dee51995-07-18 14:12:02 +00001580PyObject *
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001581_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1582{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 const char *type_name;
1584 static PyObject *int_name = NULL;
1585 if (int_name == NULL) {
1586 int_name = PyString_InternFromString("__int__");
1587 if (int_name == NULL)
1588 return NULL;
1589 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001591 if (integral && (!PyInt_Check(integral) &&
1592 !PyLong_Check(integral))) {
1593 /* Don't go through tp_as_number->nb_int to avoid
1594 hitting the classic class fallback to __trunc__. */
1595 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1596 if (int_func == NULL) {
1597 PyErr_Clear(); /* Raise a different error. */
1598 goto non_integral_error;
1599 }
1600 Py_DECREF(integral);
1601 integral = PyEval_CallObject(int_func, NULL);
1602 Py_DECREF(int_func);
1603 if (integral && (!PyInt_Check(integral) &&
1604 !PyLong_Check(integral))) {
1605 goto non_integral_error;
1606 }
1607 }
1608 return integral;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001609
1610non_integral_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001611 if (PyInstance_Check(integral)) {
1612 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1613 ->in_class->cl_name);
1614 }
1615 else {
1616 type_name = integral->ob_type->tp_name;
1617 }
1618 PyErr_Format(PyExc_TypeError, error_format, type_name);
1619 Py_DECREF(integral);
1620 return NULL;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001621}
1622
1623
1624PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001625PyNumber_Int(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001626{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001627 PyNumberMethods *m;
1628 static PyObject *trunc_name = NULL;
1629 PyObject *trunc_func;
1630 const char *buffer;
1631 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001632
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001633 if (trunc_name == NULL) {
1634 trunc_name = PyString_InternFromString("__trunc__");
1635 if (trunc_name == NULL)
1636 return NULL;
1637 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001639 if (o == NULL)
1640 return null_error();
1641 if (PyInt_CheckExact(o)) {
1642 Py_INCREF(o);
1643 return o;
1644 }
1645 m = o->ob_type->tp_as_number;
1646 if (m && m->nb_int) { /* This should include subclasses of int */
1647 /* Classic classes always take this branch. */
1648 PyObject *res = m->nb_int(o);
1649 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1650 PyErr_Format(PyExc_TypeError,
1651 "__int__ returned non-int (type %.200s)",
1652 res->ob_type->tp_name);
1653 Py_DECREF(res);
1654 return NULL;
1655 }
1656 return res;
1657 }
1658 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1659 PyIntObject *io = (PyIntObject*)o;
1660 return PyInt_FromLong(io->ob_ival);
1661 }
1662 trunc_func = PyObject_GetAttr(o, trunc_name);
1663 if (trunc_func) {
1664 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1665 Py_DECREF(trunc_func);
1666 /* __trunc__ is specified to return an Integral type, but
1667 int() needs to return an int. */
1668 return _PyNumber_ConvertIntegralToInt(
1669 truncated,
1670 "__trunc__ returned non-Integral (type %.200s)");
1671 }
1672 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001673
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001674 if (PyString_Check(o))
1675 return int_from_string(PyString_AS_STRING(o),
1676 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001677#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001678 if (PyUnicode_Check(o))
1679 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1680 PyUnicode_GET_SIZE(o),
1681 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001682#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001683 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1684 return int_from_string((char*)buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001686 return type_error("int() argument must be a string or a "
1687 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001688}
1689
Guido van Rossum9e896b32000-04-05 20:11:21 +00001690/* Add a check for embedded NULL-bytes in the argument. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001691static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001692long_from_string(const char *s, Py_ssize_t len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001693{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001694 char *end;
1695 PyObject *x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001696
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001697 x = PyLong_FromString((char*)s, &end, 10);
1698 if (x == NULL)
1699 return NULL;
1700 if (end != s + len) {
1701 PyErr_SetString(PyExc_ValueError,
1702 "null byte in argument for long()");
1703 Py_DECREF(x);
1704 return NULL;
1705 }
1706 return x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001707}
1708
Guido van Rossume15dee51995-07-18 14:12:02 +00001709PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001710PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 PyNumberMethods *m;
1713 static PyObject *trunc_name = NULL;
1714 PyObject *trunc_func;
1715 const char *buffer;
1716 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if (trunc_name == NULL) {
1719 trunc_name = PyString_InternFromString("__trunc__");
1720 if (trunc_name == NULL)
1721 return NULL;
1722 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 if (o == NULL)
1725 return null_error();
1726 m = o->ob_type->tp_as_number;
1727 if (m && m->nb_long) { /* This should include subclasses of long */
1728 /* Classic classes always take this branch. */
1729 PyObject *res = m->nb_long(o);
1730 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1731 PyErr_Format(PyExc_TypeError,
1732 "__long__ returned non-long (type %.200s)",
1733 res->ob_type->tp_name);
1734 Py_DECREF(res);
1735 return NULL;
1736 }
1737 return res;
1738 }
1739 if (PyLong_Check(o)) /* A long subclass without nb_long */
1740 return _PyLong_Copy((PyLongObject *)o);
1741 trunc_func = PyObject_GetAttr(o, trunc_name);
1742 if (trunc_func) {
1743 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1744 PyObject *int_instance;
1745 Py_DECREF(trunc_func);
1746 /* __trunc__ is specified to return an Integral type,
1747 but long() needs to return a long. */
1748 int_instance = _PyNumber_ConvertIntegralToInt(
1749 truncated,
1750 "__trunc__ returned non-Integral (type %.200s)");
1751 if (int_instance && PyInt_Check(int_instance)) {
1752 /* Make sure that long() returns a long instance. */
1753 long value = PyInt_AS_LONG(int_instance);
1754 Py_DECREF(int_instance);
1755 return PyLong_FromLong(value);
1756 }
1757 return int_instance;
1758 }
1759 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001760
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001761 if (PyString_Check(o))
1762 /* need to do extra error checking that PyLong_FromString()
1763 * doesn't do. In particular long('9.5') must raise an
1764 * exception, not truncate the float.
1765 */
1766 return long_from_string(PyString_AS_STRING(o),
1767 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001768#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001769 if (PyUnicode_Check(o))
1770 /* The above check is done in PyLong_FromUnicode(). */
1771 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1772 PyUnicode_GET_SIZE(o),
1773 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001774#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1776 return long_from_string(buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 return type_error("long() argument must be a string or a "
1779 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001780}
1781
1782PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001783PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001784{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001786
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 if (o == NULL)
1788 return null_error();
1789 m = o->ob_type->tp_as_number;
1790 if (m && m->nb_float) { /* This should include subclasses of float */
1791 PyObject *res = m->nb_float(o);
1792 if (res && !PyFloat_Check(res)) {
1793 PyErr_Format(PyExc_TypeError,
1794 "__float__ returned non-float (type %.200s)",
1795 res->ob_type->tp_name);
1796 Py_DECREF(res);
1797 return NULL;
1798 }
1799 return res;
1800 }
1801 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1802 PyFloatObject *po = (PyFloatObject *)o;
1803 return PyFloat_FromDouble(po->ob_fval);
1804 }
1805 return PyFloat_FromString(o, NULL);
Guido van Rossume15dee51995-07-18 14:12:02 +00001806}
1807
Eric Smith5e527eb2008-02-10 01:36:53 +00001808PyObject *
1809PyNumber_ToBase(PyObject *n, int base)
1810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001811 PyObject *res = NULL;
1812 PyObject *index = PyNumber_Index(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 if (!index)
1815 return NULL;
1816 if (PyLong_Check(index))
1817 res = _PyLong_Format(index, base, 0, 1);
1818 else if (PyInt_Check(index))
1819 res = _PyInt_Format((PyIntObject*)index, base, 1);
1820 else
1821 /* It should not be possible to get here, as
1822 PyNumber_Index already has a check for the same
1823 condition */
1824 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1825 "int or long");
1826 Py_DECREF(index);
1827 return res;
Eric Smith5e527eb2008-02-10 01:36:53 +00001828}
1829
1830
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001831/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001832
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001833int
Fred Drake79912472000-07-09 04:06:11 +00001834PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001835{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 if (s == NULL)
1837 return 0;
1838 if (PyInstance_Check(s))
1839 return PyObject_HasAttrString(s, "__getitem__");
1840 if (PyDict_Check(s))
1841 return 0;
1842 return s->ob_type->tp_as_sequence &&
1843 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001844}
1845
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001847PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001848{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001851 if (s == NULL) {
1852 null_error();
1853 return -1;
1854 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001855
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001856 m = s->ob_type->tp_as_sequence;
1857 if (m && m->sq_length)
1858 return m->sq_length(s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001859
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 type_error("object of type '%.200s' has no len()", s);
1861 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001862}
1863
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001864#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001865Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001866PySequence_Length(PyObject *s)
1867{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001868 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001869}
1870#define PySequence_Length PySequence_Size
1871
Guido van Rossume15dee51995-07-18 14:12:02 +00001872PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001873PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001874{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001876
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001877 if (s == NULL || o == NULL)
1878 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 m = s->ob_type->tp_as_sequence;
1881 if (m && m->sq_concat)
1882 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001883
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001884 /* Instances of user classes defining an __add__() method only
1885 have an nb_add slot, not an sq_concat slot. So we fall back
1886 to nb_add if both arguments appear to be sequences. */
1887 if (PySequence_Check(s) && PySequence_Check(o)) {
1888 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1889 if (result != Py_NotImplemented)
1890 return result;
1891 Py_DECREF(result);
1892 }
1893 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001894}
1895
1896PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001897PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001899 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001900
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001901 if (o == NULL)
1902 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001903
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001904 m = o->ob_type->tp_as_sequence;
1905 if (m && m->sq_repeat)
1906 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001907
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001908 /* Instances of user classes defining a __mul__() method only
1909 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1910 to nb_multiply if o appears to be a sequence. */
1911 if (PySequence_Check(o)) {
1912 PyObject *n, *result;
1913 n = PyInt_FromSsize_t(count);
1914 if (n == NULL)
1915 return NULL;
1916 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1917 Py_DECREF(n);
1918 if (result != Py_NotImplemented)
1919 return result;
1920 Py_DECREF(result);
1921 }
1922 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001923}
1924
1925PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001926PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1927{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001929
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001930 if (s == NULL || o == NULL)
1931 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001932
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001933 m = s->ob_type->tp_as_sequence;
1934 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1935 return m->sq_inplace_concat(s, o);
1936 if (m && m->sq_concat)
1937 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001938
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001939 if (PySequence_Check(s) && PySequence_Check(o)) {
1940 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1941 NB_SLOT(nb_add));
1942 if (result != Py_NotImplemented)
1943 return result;
1944 Py_DECREF(result);
1945 }
1946 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001947}
1948
1949PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001950PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001951{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001953
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 if (o == NULL)
1955 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001956
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001957 m = o->ob_type->tp_as_sequence;
1958 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1959 return m->sq_inplace_repeat(o, count);
1960 if (m && m->sq_repeat)
1961 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001962
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001963 if (PySequence_Check(o)) {
1964 PyObject *n, *result;
1965 n = PyInt_FromSsize_t(count);
1966 if (n == NULL)
1967 return NULL;
1968 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1969 NB_SLOT(nb_multiply));
1970 Py_DECREF(n);
1971 if (result != Py_NotImplemented)
1972 return result;
1973 Py_DECREF(result);
1974 }
1975 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001976}
1977
1978PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001979PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001980{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001981 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001982
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001983 if (s == NULL)
1984 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001985
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001986 m = s->ob_type->tp_as_sequence;
1987 if (m && m->sq_item) {
1988 if (i < 0) {
1989 if (m->sq_length) {
1990 Py_ssize_t l = (*m->sq_length)(s);
1991 if (l < 0)
1992 return NULL;
1993 i += l;
1994 }
1995 }
1996 return m->sq_item(s, i);
1997 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001998
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001999 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00002000}
2001
2002PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002003PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00002004{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 PySequenceMethods *m;
2006 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00002007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 if (!s) return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002009
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002010 m = s->ob_type->tp_as_sequence;
2011 if (m && m->sq_slice) {
2012 if (i1 < 0 || i2 < 0) {
2013 if (m->sq_length) {
2014 Py_ssize_t l = (*m->sq_length)(s);
2015 if (l < 0)
2016 return NULL;
2017 if (i1 < 0)
2018 i1 += l;
2019 if (i2 < 0)
2020 i2 += l;
2021 }
2022 }
2023 return m->sq_slice(s, i1, i2);
2024 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
2025 PyObject *res;
2026 PyObject *slice = _PySlice_FromIndices(i1, i2);
2027 if (!slice)
2028 return NULL;
2029 res = mp->mp_subscript(s, slice);
2030 Py_DECREF(slice);
2031 return res;
2032 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00002035}
2036
2037int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002038PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002040 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 if (s == NULL) {
2043 null_error();
2044 return -1;
2045 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002046
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002047 m = s->ob_type->tp_as_sequence;
2048 if (m && m->sq_ass_item) {
2049 if (i < 0) {
2050 if (m->sq_length) {
2051 Py_ssize_t l = (*m->sq_length)(s);
2052 if (l < 0)
2053 return -1;
2054 i += l;
2055 }
2056 }
2057 return m->sq_ass_item(s, i, o);
2058 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002059
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002060 type_error("'%.200s' object does not support item assignment", s);
2061 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002062}
2063
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002064int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002065PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002066{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002067 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002068
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002069 if (s == NULL) {
2070 null_error();
2071 return -1;
2072 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002073
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002074 m = s->ob_type->tp_as_sequence;
2075 if (m && m->sq_ass_item) {
2076 if (i < 0) {
2077 if (m->sq_length) {
2078 Py_ssize_t l = (*m->sq_length)(s);
2079 if (l < 0)
2080 return -1;
2081 i += l;
2082 }
2083 }
2084 return m->sq_ass_item(s, i, (PyObject *)NULL);
2085 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002087 type_error("'%.200s' object doesn't support item deletion", s);
2088 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002089}
2090
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002091int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002092PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002093{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002094 PySequenceMethods *m;
2095 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00002096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002097 if (s == NULL) {
2098 null_error();
2099 return -1;
2100 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002101
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002102 m = s->ob_type->tp_as_sequence;
2103 if (m && m->sq_ass_slice) {
2104 if (i1 < 0 || i2 < 0) {
2105 if (m->sq_length) {
2106 Py_ssize_t l = (*m->sq_length)(s);
2107 if (l < 0)
2108 return -1;
2109 if (i1 < 0)
2110 i1 += l;
2111 if (i2 < 0)
2112 i2 += l;
2113 }
2114 }
2115 return m->sq_ass_slice(s, i1, i2, o);
2116 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2117 int res;
2118 PyObject *slice = _PySlice_FromIndices(i1, i2);
2119 if (!slice)
2120 return -1;
2121 res = mp->mp_ass_subscript(s, slice, o);
2122 Py_DECREF(slice);
2123 return res;
2124 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00002125
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002126 type_error("'%.200s' object doesn't support slice assignment", s);
2127 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002128}
2129
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002130int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002131PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002132{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002134
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002135 if (s == NULL) {
2136 null_error();
2137 return -1;
2138 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002140 m = s->ob_type->tp_as_sequence;
2141 if (m && m->sq_ass_slice) {
2142 if (i1 < 0 || i2 < 0) {
2143 if (m->sq_length) {
2144 Py_ssize_t l = (*m->sq_length)(s);
2145 if (l < 0)
2146 return -1;
2147 if (i1 < 0)
2148 i1 += l;
2149 if (i2 < 0)
2150 i2 += l;
2151 }
2152 }
2153 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2154 }
2155 type_error("'%.200s' object doesn't support slice deletion", s);
2156 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002157}
2158
Guido van Rossume15dee51995-07-18 14:12:02 +00002159PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002160PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00002161{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002162 PyObject *it; /* iter(v) */
2163 Py_ssize_t n; /* guess for result tuple size */
2164 PyObject *result = NULL;
2165 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00002166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 if (v == NULL)
2168 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 /* Special-case the common tuple and list cases, for efficiency. */
2171 if (PyTuple_CheckExact(v)) {
2172 /* Note that we can't know whether it's safe to return
2173 a tuple *subclass* instance as-is, hence the restriction
2174 to exact tuples here. In contrast, lists always make
2175 a copy, so there's no need for exactness below. */
2176 Py_INCREF(v);
2177 return v;
2178 }
2179 if (PyList_Check(v))
2180 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002182 /* Get iterator. */
2183 it = PyObject_GetIter(v);
2184 if (it == NULL)
2185 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002186
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002187 /* Guess result size and allocate space. */
2188 n = _PyObject_LengthHint(v, 10);
2189 if (n == -1)
2190 goto Fail;
2191 result = PyTuple_New(n);
2192 if (result == NULL)
2193 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002195 /* Fill the tuple. */
2196 for (j = 0; ; ++j) {
2197 PyObject *item = PyIter_Next(it);
2198 if (item == NULL) {
2199 if (PyErr_Occurred())
2200 goto Fail;
2201 break;
2202 }
2203 if (j >= n) {
2204 Py_ssize_t oldn = n;
2205 /* The over-allocation strategy can grow a bit faster
2206 than for lists because unlike lists the
2207 over-allocation isn't permanent -- we reclaim
2208 the excess before the end of this routine.
2209 So, grow by ten and then add 25%.
2210 */
2211 n += 10;
2212 n += n >> 2;
2213 if (n < oldn) {
2214 /* Check for overflow */
2215 PyErr_NoMemory();
2216 Py_DECREF(item);
2217 goto Fail;
2218 }
2219 if (_PyTuple_Resize(&result, n) != 0) {
2220 Py_DECREF(item);
2221 goto Fail;
2222 }
2223 }
2224 PyTuple_SET_ITEM(result, j, item);
2225 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002227 /* Cut tuple back if guess was too large. */
2228 if (j < n &&
2229 _PyTuple_Resize(&result, j) != 0)
2230 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002232 Py_DECREF(it);
2233 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002234
2235Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 Py_XDECREF(result);
2237 Py_DECREF(it);
2238 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002239}
2240
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002241PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002242PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002243{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002244 PyObject *result; /* result list */
2245 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 if (v == NULL)
2248 return null_error();
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002249
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002250 result = PyList_New(0);
2251 if (result == NULL)
2252 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002253
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002254 rv = _PyList_Extend((PyListObject *)result, v);
2255 if (rv == NULL) {
2256 Py_DECREF(result);
2257 return NULL;
2258 }
2259 Py_DECREF(rv);
2260 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002261}
2262
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002263PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002264PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002266 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002268 if (v == NULL)
2269 return null_error();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002270
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002271 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2272 Py_INCREF(v);
2273 return v;
2274 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 it = PyObject_GetIter(v);
2277 if (it == NULL) {
2278 if (PyErr_ExceptionMatches(PyExc_TypeError))
2279 PyErr_SetString(PyExc_TypeError, m);
2280 return NULL;
2281 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002283 v = PySequence_List(it);
2284 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002285
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002286 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002287}
2288
Tim Peters16a77ad2001-09-08 04:00:12 +00002289/* Iterate over seq. Result depends on the operation:
2290 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00002291 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002293 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2294*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002295Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002296_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002297{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002298 Py_ssize_t n;
2299 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2300 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002302 if (seq == NULL || obj == NULL) {
2303 null_error();
2304 return -1;
2305 }
Tim Peters75f8e352001-05-05 11:33:43 +00002306
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002307 it = PyObject_GetIter(seq);
2308 if (it == NULL) {
2309 type_error("argument of type '%.200s' is not iterable", seq);
2310 return -1;
2311 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 n = wrapped = 0;
2314 for (;;) {
2315 int cmp;
2316 PyObject *item = PyIter_Next(it);
2317 if (item == NULL) {
2318 if (PyErr_Occurred())
2319 goto Fail;
2320 break;
2321 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002322
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002323 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2324 Py_DECREF(item);
2325 if (cmp < 0)
2326 goto Fail;
2327 if (cmp > 0) {
2328 switch (operation) {
2329 case PY_ITERSEARCH_COUNT:
2330 if (n == PY_SSIZE_T_MAX) {
2331 PyErr_SetString(PyExc_OverflowError,
2332 "count exceeds C integer size");
2333 goto Fail;
2334 }
2335 ++n;
2336 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002337
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002338 case PY_ITERSEARCH_INDEX:
2339 if (wrapped) {
2340 PyErr_SetString(PyExc_OverflowError,
2341 "index exceeds C integer size");
2342 goto Fail;
2343 }
2344 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002345
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002346 case PY_ITERSEARCH_CONTAINS:
2347 n = 1;
2348 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002350 default:
2351 assert(!"unknown operation");
2352 }
2353 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002355 if (operation == PY_ITERSEARCH_INDEX) {
2356 if (n == PY_SSIZE_T_MAX)
2357 wrapped = 1;
2358 ++n;
2359 }
2360 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002362 if (operation != PY_ITERSEARCH_INDEX)
2363 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 PyErr_SetString(PyExc_ValueError,
2366 "sequence.index(x): x not in sequence");
2367 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002368Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002369 n = -1;
2370 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002371Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002372 Py_DECREF(it);
2373 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002374
Guido van Rossume15dee51995-07-18 14:12:02 +00002375}
2376
Tim Peters16a77ad2001-09-08 04:00:12 +00002377/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002378Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002379PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002381 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002382}
2383
Tim Peterscb8d3682001-05-05 21:05:01 +00002384/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002385 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002386 */
2387int
2388PySequence_Contains(PyObject *seq, PyObject *ob)
2389{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002390 Py_ssize_t result;
2391 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2392 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2393 if (sqm != NULL && sqm->sq_contains != NULL)
2394 return (*sqm->sq_contains)(seq, ob);
2395 }
2396 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2397 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002398}
2399
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002400/* Backwards compatibility */
2401#undef PySequence_In
2402int
Fred Drake79912472000-07-09 04:06:11 +00002403PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002404{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002405 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002406}
2407
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002408Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002409PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002410{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002412}
2413
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002414/* Operations on mappings */
2415
2416int
Fred Drake79912472000-07-09 04:06:11 +00002417PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002419 if (o && PyInstance_Check(o))
2420 return PyObject_HasAttrString(o, "__getitem__");
Raymond Hettingere2eda602004-04-04 08:51:41 +00002421
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002422 return o && o->ob_type->tp_as_mapping &&
2423 o->ob_type->tp_as_mapping->mp_subscript &&
2424 !(o->ob_type->tp_as_sequence &&
2425 o->ob_type->tp_as_sequence->sq_slice);
Guido van Rossume15dee51995-07-18 14:12:02 +00002426}
2427
Martin v. Löwis18e16552006-02-15 17:27:45 +00002428Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002429PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002430{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002431 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002432
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002433 if (o == NULL) {
2434 null_error();
2435 return -1;
2436 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002438 m = o->ob_type->tp_as_mapping;
2439 if (m && m->mp_length)
2440 return m->mp_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00002441
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 type_error("object of type '%.200s' has no len()", o);
2443 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002444}
2445
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002446#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002447Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002448PyMapping_Length(PyObject *o)
2449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002450 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002451}
2452#define PyMapping_Length PyMapping_Size
2453
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002454PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002455PyMapping_GetItemString(PyObject *o, char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002456{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002457 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002459 if (key == NULL)
2460 return null_error();
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002462 okey = PyString_FromString(key);
2463 if (okey == NULL)
2464 return NULL;
2465 r = PyObject_GetItem(o, okey);
2466 Py_DECREF(okey);
2467 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002468}
2469
2470int
Fred Drake79912472000-07-09 04:06:11 +00002471PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002472{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002473 PyObject *okey;
2474 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002475
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002476 if (key == NULL) {
2477 null_error();
2478 return -1;
2479 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002481 okey = PyString_FromString(key);
2482 if (okey == NULL)
2483 return -1;
2484 r = PyObject_SetItem(o, okey, value);
2485 Py_DECREF(okey);
2486 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002487}
2488
2489int
Fred Drake79912472000-07-09 04:06:11 +00002490PyMapping_HasKeyString(PyObject *o, char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002491{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002492 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002494 v = PyMapping_GetItemString(o, key);
2495 if (v) {
2496 Py_DECREF(v);
2497 return 1;
2498 }
2499 PyErr_Clear();
2500 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002501}
2502
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002503int
Fred Drake79912472000-07-09 04:06:11 +00002504PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002505{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002506 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002508 v = PyObject_GetItem(o, key);
2509 if (v) {
2510 Py_DECREF(v);
2511 return 1;
2512 }
2513 PyErr_Clear();
2514 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002515}
2516
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002517/* Operations on callable objects */
2518
2519/* XXX PyCallable_Check() is in object.c */
2520
Guido van Rossume15dee51995-07-18 14:12:02 +00002521PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002522PyObject_CallObject(PyObject *o, PyObject *a)
Guido van Rossume15dee51995-07-18 14:12:02 +00002523{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002524 return PyEval_CallObjectWithKeywords(o, a, NULL);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002525}
Guido van Rossume15dee51995-07-18 14:12:02 +00002526
2527PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2529{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002530 ternaryfunc call;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 if ((call = func->ob_type->tp_call) != NULL) {
2533 PyObject *result;
2534 if (Py_EnterRecursiveCall(" while calling a Python object"))
2535 return NULL;
2536 result = (*call)(func, arg, kw);
2537 Py_LeaveRecursiveCall();
2538 if (result == NULL && !PyErr_Occurred())
2539 PyErr_SetString(
2540 PyExc_SystemError,
2541 "NULL result without error in PyObject_Call");
2542 return result;
2543 }
2544 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2545 func->ob_type->tp_name);
2546 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547}
2548
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002549static PyObject*
2550call_function_tail(PyObject *callable, PyObject *args)
2551{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002552 PyObject *retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002553
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002554 if (args == NULL)
2555 return NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 if (!PyTuple_Check(args)) {
2558 PyObject *a;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002560 a = PyTuple_New(1);
2561 if (a == NULL) {
2562 Py_DECREF(args);
2563 return NULL;
2564 }
2565 PyTuple_SET_ITEM(a, 0, args);
2566 args = a;
2567 }
2568 retval = PyObject_Call(callable, args, NULL);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002569
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002570 Py_DECREF(args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002571
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002572 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575PyObject *
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002576PyObject_CallFunction(PyObject *callable, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002577{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002578 va_list va;
2579 PyObject *args;
Guido van Rossume15dee51995-07-18 14:12:02 +00002580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 if (callable == NULL)
2582 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002583
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002584 if (format && *format) {
2585 va_start(va, format);
2586 args = Py_VaBuildValue(format, va);
2587 va_end(va);
2588 }
2589 else
2590 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002592 return call_function_tail(callable, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002593}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002594
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002595PyObject *
2596_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2597{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002598 va_list va;
2599 PyObject *args;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002600
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002601 if (callable == NULL)
2602 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002604 if (format && *format) {
2605 va_start(va, format);
2606 args = _Py_VaBuildValue_SizeT(format, va);
2607 va_end(va);
2608 }
2609 else
2610 args = PyTuple_New(0);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002611
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002612 return call_function_tail(callable, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002613}
2614
2615PyObject *
Guido van Rossume15dee51995-07-18 14:12:02 +00002616PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002617{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002618 va_list va;
2619 PyObject *args;
2620 PyObject *func = NULL;
2621 PyObject *retval = NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002622
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002623 if (o == NULL || name == NULL)
2624 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 func = PyObject_GetAttrString(o, name);
2627 if (func == NULL) {
2628 PyErr_SetString(PyExc_AttributeError, name);
2629 return 0;
2630 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002631
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002632 if (!PyCallable_Check(func)) {
2633 type_error("attribute of type '%.200s' is not callable", func);
2634 goto exit;
2635 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002636
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002637 if (format && *format) {
2638 va_start(va, format);
2639 args = Py_VaBuildValue(format, va);
2640 va_end(va);
2641 }
2642 else
2643 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002645 retval = call_function_tail(func, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002646
Michael W. Hudson0edc7a02005-07-12 10:21:19 +00002647 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 /* args gets consumed in call_function_tail */
2649 Py_XDECREF(func);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002650
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002651 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002652}
2653
2654PyObject *
2655_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2656{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 va_list va;
2658 PyObject *args;
2659 PyObject *func = NULL;
2660 PyObject *retval = NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002661
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002662 if (o == NULL || name == NULL)
2663 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002664
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 func = PyObject_GetAttrString(o, name);
2666 if (func == NULL) {
2667 PyErr_SetString(PyExc_AttributeError, name);
2668 return 0;
2669 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002670
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002671 if (!PyCallable_Check(func)) {
2672 type_error("attribute of type '%.200s' is not callable", func);
2673 goto exit;
2674 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002676 if (format && *format) {
2677 va_start(va, format);
2678 args = _Py_VaBuildValue_SizeT(format, va);
2679 va_end(va);
2680 }
2681 else
2682 args = PyTuple_New(0);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002684 retval = call_function_tail(func, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002685
2686 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 /* args gets consumed in call_function_tail */
2688 Py_XDECREF(func);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002689
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002690 return retval;
Guido van Rossume15dee51995-07-18 14:12:02 +00002691}
Guido van Rossum823649d2001-03-21 18:40:58 +00002692
2693
Fred Drakeb421b8c2001-10-26 16:21:32 +00002694static PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002695objargs_mktuple(va_list va)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002696{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002697 int i, n = 0;
2698 va_list countva;
2699 PyObject *result, *tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002700
2701#ifdef VA_LIST_IS_ARRAY
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 memcpy(countva, va, sizeof(va_list));
Fred Drakeb421b8c2001-10-26 16:21:32 +00002703#else
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002704#ifdef __va_copy
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002705 __va_copy(countva, va);
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002706#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002707 countva = va;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002708#endif
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002709#endif
Fred Drakeb421b8c2001-10-26 16:21:32 +00002710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2712 ++n;
2713 result = PyTuple_New(n);
2714 if (result != NULL && n > 0) {
2715 for (i = 0; i < n; ++i) {
2716 tmp = (PyObject *)va_arg(va, PyObject *);
2717 PyTuple_SET_ITEM(result, i, tmp);
2718 Py_INCREF(tmp);
2719 }
2720 }
2721 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002722}
2723
2724PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002725PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002726{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002727 PyObject *args, *tmp;
2728 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002730 if (callable == NULL || name == NULL)
2731 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002733 callable = PyObject_GetAttr(callable, name);
2734 if (callable == NULL)
2735 return NULL;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 /* count the args */
2738 va_start(vargs, name);
2739 args = objargs_mktuple(vargs);
2740 va_end(vargs);
2741 if (args == NULL) {
2742 Py_DECREF(callable);
2743 return NULL;
2744 }
2745 tmp = PyObject_Call(callable, args, NULL);
2746 Py_DECREF(args);
2747 Py_DECREF(callable);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002749 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002750}
2751
2752PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002753PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002754{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 PyObject *args, *tmp;
2756 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002758 if (callable == NULL)
2759 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002760
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002761 /* count the args */
2762 va_start(vargs, callable);
2763 args = objargs_mktuple(vargs);
2764 va_end(vargs);
2765 if (args == NULL)
2766 return NULL;
2767 tmp = PyObject_Call(callable, args, NULL);
2768 Py_DECREF(args);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002769
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002770 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002771}
2772
2773
Guido van Rossum823649d2001-03-21 18:40:58 +00002774/* isinstance(), issubclass() */
2775
Barry Warsawf16951c2002-04-23 22:45:44 +00002776/* abstract_get_bases() has logically 4 return states, with a sort of 0th
2777 * state that will almost never happen.
2778 *
2779 * 0. creating the __bases__ static string could get a MemoryError
2780 * 1. getattr(cls, '__bases__') could raise an AttributeError
2781 * 2. getattr(cls, '__bases__') could raise some other exception
2782 * 3. getattr(cls, '__bases__') could return a tuple
2783 * 4. getattr(cls, '__bases__') could return something other than a tuple
2784 *
2785 * Only state #3 is a non-error state and only it returns a non-NULL object
2786 * (it returns the retrieved tuple).
2787 *
2788 * Any raised AttributeErrors are masked by clearing the exception and
2789 * returning NULL. If an object other than a tuple comes out of __bases__,
2790 * then again, the return value is NULL. So yes, these two situations
2791 * produce exactly the same results: NULL is returned and no error is set.
2792 *
2793 * If some exception other than AttributeError is raised, then NULL is also
2794 * returned, but the exception is not cleared. That's because we want the
2795 * exception to be propagated along.
2796 *
2797 * Callers are expected to test for PyErr_Occurred() when the return value
2798 * is NULL to decide whether a valid exception should be propagated or not.
2799 * When there's no exception to propagate, it's customary for the caller to
2800 * set a TypeError.
2801 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002802static PyObject *
2803abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002804{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002805 static PyObject *__bases__ = NULL;
2806 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002808 if (__bases__ == NULL) {
2809 __bases__ = PyString_InternFromString("__bases__");
2810 if (__bases__ == NULL)
2811 return NULL;
2812 }
2813 bases = PyObject_GetAttr(cls, __bases__);
2814 if (bases == NULL) {
2815 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2816 PyErr_Clear();
2817 return NULL;
2818 }
2819 if (!PyTuple_Check(bases)) {
2820 Py_DECREF(bases);
2821 return NULL;
2822 }
2823 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002824}
2825
2826
2827static int
2828abstract_issubclass(PyObject *derived, PyObject *cls)
2829{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002830 PyObject *bases = NULL;
2831 Py_ssize_t i, n;
2832 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002833
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002834 while (1) {
2835 if (derived == cls)
2836 return 1;
2837 bases = abstract_get_bases(derived);
2838 if (bases == NULL) {
2839 if (PyErr_Occurred())
2840 return -1;
2841 return 0;
2842 }
2843 n = PyTuple_GET_SIZE(bases);
2844 if (n == 0) {
2845 Py_DECREF(bases);
2846 return 0;
2847 }
2848 /* Avoid recursivity in the single inheritance case */
2849 if (n == 1) {
2850 derived = PyTuple_GET_ITEM(bases, 0);
2851 Py_DECREF(bases);
2852 continue;
2853 }
2854 for (i = 0; i < n; i++) {
2855 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2856 if (r != 0)
2857 break;
2858 }
2859 Py_DECREF(bases);
2860 return r;
2861 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002862}
2863
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002864static int
2865check_class(PyObject *cls, const char *error)
2866{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002867 PyObject *bases = abstract_get_bases(cls);
2868 if (bases == NULL) {
2869 /* Do not mask errors. */
2870 if (!PyErr_Occurred())
2871 PyErr_SetString(PyExc_TypeError, error);
2872 return 0;
2873 }
2874 Py_DECREF(bases);
2875 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002876}
2877
Brett Cannon4f653312004-03-20 22:52:14 +00002878static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002879recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002880{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002881 PyObject *icls;
2882 static PyObject *__class__ = NULL;
2883 int retval = 0;
Guido van Rossum823649d2001-03-21 18:40:58 +00002884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002885 if (__class__ == NULL) {
2886 __class__ = PyString_InternFromString("__class__");
2887 if (__class__ == NULL)
2888 return -1;
2889 }
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002891 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2892 PyObject *inclass =
2893 (PyObject*)((PyInstanceObject*)inst)->in_class;
2894 retval = PyClass_IsSubclass(inclass, cls);
2895 }
2896 else if (PyType_Check(cls)) {
2897 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2898 if (retval == 0) {
2899 PyObject *c = PyObject_GetAttr(inst, __class__);
2900 if (c == NULL) {
2901 PyErr_Clear();
2902 }
2903 else {
2904 if (c != (PyObject *)(inst->ob_type) &&
2905 PyType_Check(c))
2906 retval = PyType_IsSubtype(
2907 (PyTypeObject *)c,
2908 (PyTypeObject *)cls);
2909 Py_DECREF(c);
2910 }
2911 }
2912 }
2913 else {
2914 if (!check_class(cls,
2915 "isinstance() arg 2 must be a class, type,"
2916 " or tuple of classes and types"))
2917 return -1;
2918 icls = PyObject_GetAttr(inst, __class__);
2919 if (icls == NULL) {
2920 PyErr_Clear();
2921 retval = 0;
2922 }
2923 else {
2924 retval = abstract_issubclass(icls, cls);
2925 Py_DECREF(icls);
2926 }
2927 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002928
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002929 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002930}
2931
2932int
Brett Cannon4f653312004-03-20 22:52:14 +00002933PyObject_IsInstance(PyObject *inst, PyObject *cls)
2934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 static PyObject *name = NULL;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002936
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002937 /* Quick test for an exact match */
2938 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2939 return 1;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002940
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002941 if (PyTuple_Check(cls)) {
2942 Py_ssize_t i;
2943 Py_ssize_t n;
2944 int r = 0;
Antoine Pitrou0668c622008-08-26 22:42:08 +00002945
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002946 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2947 return -1;
2948 n = PyTuple_GET_SIZE(cls);
2949 for (i = 0; i < n; ++i) {
2950 PyObject *item = PyTuple_GET_ITEM(cls, i);
2951 r = PyObject_IsInstance(inst, item);
2952 if (r != 0)
2953 /* either found it, or got an error */
2954 break;
2955 }
2956 Py_LeaveRecursiveCall();
2957 return r;
2958 }
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00002959
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002960 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
2961 PyObject *checker;
2962 checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
2963 if (checker != NULL) {
2964 PyObject *res;
2965 int ok = -1;
2966 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2967 Py_DECREF(checker);
2968 return ok;
2969 }
2970 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2971 Py_LeaveRecursiveCall();
2972 Py_DECREF(checker);
2973 if (res != NULL) {
2974 ok = PyObject_IsTrue(res);
2975 Py_DECREF(res);
2976 }
2977 return ok;
2978 }
2979 else if (PyErr_Occurred())
2980 return -1;
2981 }
2982 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002983}
2984
2985static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002986recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002987{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002988 int retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002989
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002990 if (PyType_Check(cls) && PyType_Check(derived)) {
2991 /* Fast path (non-recursive) */
2992 return PyType_IsSubtype(
2993 (PyTypeObject *)derived, (PyTypeObject *)cls);
2994 }
2995 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2996 if (!check_class(derived,
2997 "issubclass() arg 1 must be a class"))
2998 return -1;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003000 if (!check_class(cls,
3001 "issubclass() arg 2 must be a class"
3002 " or tuple of classes"))
3003 return -1;
3004 retval = abstract_issubclass(derived, cls);
3005 }
3006 else {
3007 /* shortcut */
3008 if (!(retval = (derived == cls)))
3009 retval = PyClass_IsSubclass(derived, cls);
3010 }
Guido van Rossum823649d2001-03-21 18:40:58 +00003011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003012 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00003013}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003014
Brett Cannon4f653312004-03-20 22:52:14 +00003015int
3016PyObject_IsSubclass(PyObject *derived, PyObject *cls)
3017{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003018 static PyObject *name = NULL;
3019
3020 if (PyTuple_Check(cls)) {
3021 Py_ssize_t i;
3022 Py_ssize_t n;
3023 int r = 0;
3024
3025 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3026 return -1;
3027 n = PyTuple_GET_SIZE(cls);
3028 for (i = 0; i < n; ++i) {
3029 PyObject *item = PyTuple_GET_ITEM(cls, i);
3030 r = PyObject_IsSubclass(derived, item);
3031 if (r != 0)
3032 /* either found it, or got an error */
3033 break;
3034 }
3035 Py_LeaveRecursiveCall();
3036 return r;
3037 }
3038 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
3039 PyObject *checker;
3040 checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
3041 if (checker != NULL) {
3042 PyObject *res;
3043 int ok = -1;
3044 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3045 Py_DECREF(checker);
3046 return ok;
3047 }
3048 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3049 Py_LeaveRecursiveCall();
3050 Py_DECREF(checker);
3051 if (res != NULL) {
3052 ok = PyObject_IsTrue(res);
3053 Py_DECREF(res);
3054 }
3055 return ok;
3056 }
3057 else if (PyErr_Occurred()) {
3058 return -1;
3059 }
3060 }
3061 return recursive_issubclass(derived, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003062}
3063
3064int
3065_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3066{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003067 return recursive_isinstance(inst, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003068}
3069
3070int
3071_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3072{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003073 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003074}
3075
3076
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003077PyObject *
3078PyObject_GetIter(PyObject *o)
3079{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003080 PyTypeObject *t = o->ob_type;
3081 getiterfunc f = NULL;
3082 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3083 f = t->tp_iter;
3084 if (f == NULL) {
3085 if (PySequence_Check(o))
3086 return PySeqIter_New(o);
3087 return type_error("'%.200s' object is not iterable", o);
3088 }
3089 else {
3090 PyObject *res = (*f)(o);
3091 if (res != NULL && !PyIter_Check(res)) {
3092 PyErr_Format(PyExc_TypeError,
3093 "iter() returned non-iterator "
3094 "of type '%.100s'",
3095 res->ob_type->tp_name);
3096 Py_DECREF(res);
3097 res = NULL;
3098 }
3099 return res;
3100 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00003101}
3102
Tim Petersf4848da2001-05-05 00:14:56 +00003103/* Return next item.
3104 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3105 * If the iteration terminates normally, return NULL and clear the
3106 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3107 * will be false.
3108 * Else return the next object. PyErr_Occurred() will be false.
3109 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00003110PyObject *
3111PyIter_Next(PyObject *iter)
3112{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003113 PyObject *result;
3114 result = (*iter->ob_type->tp_iternext)(iter);
3115 if (result == NULL &&
3116 PyErr_Occurred() &&
3117 PyErr_ExceptionMatches(PyExc_StopIteration))
3118 PyErr_Clear();
3119 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003120}