blob: d53b17ffbfcd49465d24dc1d04d626c0dcb57709 [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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +000035 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000036
Antoine Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +000051 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000052
Antoine Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +000063 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000064
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000065 if (o == NULL) {
66 null_error();
67 return -1;
68 }
Guido van Rossume15dee51995-07-18 14:12:02 +000069
Antoine Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Hettinger24e28722009-02-02 22:44:06 +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 Pitrouc7c96a92010-05-09 15:15:40 +000095 static PyObject *hintstrobj = NULL;
96 PyObject *ro;
97 Py_ssize_t rv;
Raymond Hettinger4e2f7142007-12-06 00:56:53 +000098
Antoine Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +0000110 /* cache a hashed version of the attribute string */
111 if (hintstrobj == NULL) {
112 hintstrobj = PyString_InternFromString("__length_hint__");
113 if (hintstrobj == NULL)
114 return -1;
115 }
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000116
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000117 /* try o.__length_hint__() */
118 ro = PyObject_CallMethodObjArgs(o, hintstrobj, NULL);
119 if (ro == NULL) {
120 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
121 !PyErr_ExceptionMatches(PyExc_AttributeError))
122 return -1;
123 PyErr_Clear();
124 return defaultvalue;
125 }
126 rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
127 Py_DECREF(ro);
128 return rv;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000129}
130
Guido van Rossume15dee51995-07-18 14:12:02 +0000131PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000132PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000133{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000134 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000135
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000136 if (o == NULL || key == NULL)
137 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +0000138
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000139 m = o->ob_type->tp_as_mapping;
140 if (m && m->mp_subscript)
141 return m->mp_subscript(o, key);
Guido van Rossume15dee51995-07-18 14:12:02 +0000142
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000143 if (o->ob_type->tp_as_sequence) {
144 if (PyIndex_Check(key)) {
145 Py_ssize_t key_value;
146 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
147 if (key_value == -1 && PyErr_Occurred())
148 return NULL;
149 return PySequence_GetItem(o, key_value);
150 }
151 else if (o->ob_type->tp_as_sequence->sq_item)
152 return type_error("sequence index must "
153 "be integer, not '%.200s'", key);
154 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000155
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000156 return type_error("'%.200s' object is unsubscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000157}
158
159int
Fred Drake79912472000-07-09 04:06:11 +0000160PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000161{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000162 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000163
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000164 if (o == NULL || key == NULL || value == NULL) {
165 null_error();
166 return -1;
167 }
168 m = o->ob_type->tp_as_mapping;
169 if (m && m->mp_ass_subscript)
170 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000171
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000172 if (o->ob_type->tp_as_sequence) {
173 if (PyIndex_Check(key)) {
174 Py_ssize_t key_value;
175 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
176 if (key_value == -1 && PyErr_Occurred())
177 return -1;
178 return PySequence_SetItem(o, key_value, value);
179 }
180 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
181 type_error("sequence index must be "
182 "integer, not '%.200s'", key);
183 return -1;
184 }
185 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000186
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000187 type_error("'%.200s' object does not support item assignment", o);
188 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000189}
190
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000191int
Fred Drake79912472000-07-09 04:06:11 +0000192PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000193{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000194 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000195
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000196 if (o == NULL || key == NULL) {
197 null_error();
198 return -1;
199 }
200 m = o->ob_type->tp_as_mapping;
201 if (m && m->mp_ass_subscript)
202 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000203
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000204 if (o->ob_type->tp_as_sequence) {
205 if (PyIndex_Check(key)) {
206 Py_ssize_t key_value;
207 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
208 if (key_value == -1 && PyErr_Occurred())
209 return -1;
210 return PySequence_DelItem(o, key_value);
211 }
212 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
213 type_error("sequence index must be "
214 "integer, not '%.200s'", key);
215 return -1;
216 }
217 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000218
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000219 type_error("'%.200s' object does not support item deletion", o);
220 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000221}
222
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000223int
224PyObject_DelItemString(PyObject *o, char *key)
225{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000226 PyObject *okey;
227 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000228
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000229 if (o == NULL || key == NULL) {
230 null_error();
231 return -1;
232 }
233 okey = PyString_FromString(key);
234 if (okey == NULL)
235 return -1;
236 ret = PyObject_DelItem(o, okey);
237 Py_DECREF(okey);
238 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000239}
240
Brett Cannonea229bd2006-06-06 18:08:16 +0000241int
242PyObject_AsCharBuffer(PyObject *obj,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000243 const char **buffer,
244 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000245{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000246 PyBufferProcs *pb;
247 char *pp;
248 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000249
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000250 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
251 null_error();
252 return -1;
253 }
254 pb = obj->ob_type->tp_as_buffer;
255 if (pb == NULL ||
256 pb->bf_getcharbuffer == NULL ||
257 pb->bf_getsegcount == NULL) {
258 PyErr_SetString(PyExc_TypeError,
259 "expected a character buffer object");
260 return -1;
261 }
262 if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
263 PyErr_SetString(PyExc_TypeError,
264 "expected a single-segment buffer object");
265 return -1;
266 }
267 len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
268 if (len < 0)
269 return -1;
270 *buffer = pp;
271 *buffer_len = len;
272 return 0;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000273}
Guido van Rossum4c08d552000-03-10 22:55:18 +0000274
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000275int
276PyObject_CheckReadBuffer(PyObject *obj)
277{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000278 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000279
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000280 if (pb == NULL ||
281 pb->bf_getreadbuffer == NULL ||
282 pb->bf_getsegcount == NULL ||
283 (*pb->bf_getsegcount)(obj, NULL) != 1)
284 return 0;
285 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000286}
287
288int PyObject_AsReadBuffer(PyObject *obj,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000289 const void **buffer,
290 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000291{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000292 PyBufferProcs *pb;
293 void *pp;
294 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000295
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000296 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
297 null_error();
298 return -1;
299 }
300 pb = obj->ob_type->tp_as_buffer;
301 if (pb == NULL ||
302 pb->bf_getreadbuffer == NULL ||
303 pb->bf_getsegcount == NULL) {
304 PyErr_SetString(PyExc_TypeError,
305 "expected a readable buffer object");
306 return -1;
307 }
308 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
309 PyErr_SetString(PyExc_TypeError,
310 "expected a single-segment buffer object");
311 return -1;
312 }
313 len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
314 if (len < 0)
315 return -1;
316 *buffer = pp;
317 *buffer_len = len;
318 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000319}
320
321int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000322 void **buffer,
323 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000324{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000325 PyBufferProcs *pb;
326 void*pp;
327 Py_ssize_t len;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000328
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000329 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
330 null_error();
331 return -1;
332 }
333 pb = obj->ob_type->tp_as_buffer;
334 if (pb == NULL ||
335 pb->bf_getwritebuffer == NULL ||
336 pb->bf_getsegcount == NULL) {
337 PyErr_SetString(PyExc_TypeError,
338 "expected a writeable buffer object");
339 return -1;
340 }
341 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
342 PyErr_SetString(PyExc_TypeError,
343 "expected a single-segment buffer object");
344 return -1;
345 }
346 len = (*pb->bf_getwritebuffer)(obj,0,&pp);
347 if (len < 0)
348 return -1;
349 *buffer = pp;
350 *buffer_len = len;
351 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000352}
353
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000354/* Buffer C-API for Python 3.0 */
355
356int
357PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
358{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000359 if (!PyObject_CheckBuffer(obj)) {
360 PyErr_Format(PyExc_TypeError,
361 "'%100s' does not have the buffer interface",
362 Py_TYPE(obj)->tp_name);
363 return -1;
364 }
365 return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000366}
367
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000368static int
369_IsFortranContiguous(Py_buffer *view)
370{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000371 Py_ssize_t sd, dim;
372 int i;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000373
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000374 if (view->ndim == 0) return 1;
375 if (view->strides == NULL) return (view->ndim == 1);
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000376
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000377 sd = view->itemsize;
378 if (view->ndim == 1) return (view->shape[0] == 1 ||
379 sd == view->strides[0]);
380 for (i=0; i<view->ndim; i++) {
381 dim = view->shape[i];
382 if (dim == 0) return 1;
383 if (view->strides[i] != sd) return 0;
384 sd *= dim;
385 }
386 return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000387}
388
389static int
390_IsCContiguous(Py_buffer *view)
391{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000392 Py_ssize_t sd, dim;
393 int i;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000394
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000395 if (view->ndim == 0) return 1;
396 if (view->strides == NULL) return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000397
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000398 sd = view->itemsize;
399 if (view->ndim == 1) return (view->shape[0] == 1 ||
400 sd == view->strides[0]);
401 for (i=view->ndim-1; i>=0; i--) {
402 dim = view->shape[i];
403 if (dim == 0) return 1;
404 if (view->strides[i] != sd) return 0;
405 sd *= dim;
406 }
407 return 1;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000408}
409
410int
411PyBuffer_IsContiguous(Py_buffer *view, char fort)
412{
413
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000414 if (view->suboffsets != NULL) return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000415
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000416 if (fort == 'C')
417 return _IsCContiguous(view);
418 else if (fort == 'F')
419 return _IsFortranContiguous(view);
420 else if (fort == 'A')
421 return (_IsCContiguous(view) || _IsFortranContiguous(view));
422 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000423}
424
425
426void*
427PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
428{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000429 char* pointer;
430 int i;
431 pointer = (char *)view->buf;
432 for (i = 0; i < view->ndim; i++) {
433 pointer += view->strides[i]*indices[i];
434 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
435 pointer = *((char**)pointer) + view->suboffsets[i];
436 }
437 }
438 return (void*)pointer;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000439}
440
441
Neal Norwitzfddc4692008-04-15 03:46:21 +0000442static void
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000443_add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
444{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000445 int k;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000446
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000447 for (k=0; k<nd; k++) {
448 if (index[k] < shape[k]-1) {
449 index[k]++;
450 break;
451 }
452 else {
453 index[k] = 0;
454 }
455 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000456}
457
Neal Norwitzfddc4692008-04-15 03:46:21 +0000458static void
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000459_add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
460{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000461 int k;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000462
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000463 for (k=nd-1; k>=0; k--) {
464 if (index[k] < shape[k]-1) {
465 index[k]++;
466 break;
467 }
468 else {
469 index[k] = 0;
470 }
471 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000472}
473
474 /* view is not checked for consistency in either of these. It is
475 assumed that the size of the buffer is view->len in
476 view->len / view->itemsize elements.
477 */
478
479int
480PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
481{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000482 int k;
483 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
484 Py_ssize_t *indices, elements;
485 char *dest, *ptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000486
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000487 if (len > view->len) {
488 len = view->len;
489 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000490
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000491 if (PyBuffer_IsContiguous(view, fort)) {
492 /* simplest copy is all that is needed */
493 memcpy(buf, view->buf, len);
494 return 0;
495 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000496
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000497 /* Otherwise a more elaborate scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000498
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000499 /* XXX(nnorwitz): need to check for overflow! */
500 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
501 if (indices == NULL) {
502 PyErr_NoMemory();
503 return -1;
504 }
505 for (k=0; k<view->ndim;k++) {
506 indices[k] = 0;
507 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000508
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000509 if (fort == 'F') {
510 addone = _add_one_to_index_F;
511 }
512 else {
513 addone = _add_one_to_index_C;
514 }
515 dest = buf;
516 /* XXX : This is not going to be the fastest code in the world
517 several optimizations are possible.
518 */
519 elements = len / view->itemsize;
520 while (elements--) {
521 addone(view->ndim, indices, view->shape);
522 ptr = PyBuffer_GetPointer(view, indices);
523 memcpy(dest, ptr, view->itemsize);
524 dest += view->itemsize;
525 }
526 PyMem_Free(indices);
527 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000528}
529
530int
531PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
532{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000533 int k;
534 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
535 Py_ssize_t *indices, elements;
536 char *src, *ptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000537
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000538 if (len > view->len) {
539 len = view->len;
540 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000541
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000542 if (PyBuffer_IsContiguous(view, fort)) {
543 /* simplest copy is all that is needed */
544 memcpy(view->buf, buf, len);
545 return 0;
546 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000547
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000548 /* Otherwise a more elaborate scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000549
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000550 /* XXX(nnorwitz): need to check for overflow! */
551 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
552 if (indices == NULL) {
553 PyErr_NoMemory();
554 return -1;
555 }
556 for (k=0; k<view->ndim;k++) {
557 indices[k] = 0;
558 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000559
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000560 if (fort == 'F') {
561 addone = _add_one_to_index_F;
562 }
563 else {
564 addone = _add_one_to_index_C;
565 }
566 src = buf;
567 /* XXX : This is not going to be the fastest code in the world
568 several optimizations are possible.
569 */
570 elements = len / view->itemsize;
571 while (elements--) {
572 addone(view->ndim, indices, view->shape);
573 ptr = PyBuffer_GetPointer(view, indices);
574 memcpy(ptr, src, view->itemsize);
575 src += view->itemsize;
576 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000577
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000578 PyMem_Free(indices);
579 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000580}
581
582int PyObject_CopyData(PyObject *dest, PyObject *src)
583{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000584 Py_buffer view_dest, view_src;
585 int k;
586 Py_ssize_t *indices, elements;
587 char *dptr, *sptr;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000588
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000589 if (!PyObject_CheckBuffer(dest) ||
590 !PyObject_CheckBuffer(src)) {
591 PyErr_SetString(PyExc_TypeError,
592 "both destination and source must have the "\
593 "buffer interface");
594 return -1;
595 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000596
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000597 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
598 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
599 PyBuffer_Release(&view_dest);
600 return -1;
601 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000602
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000603 if (view_dest.len < view_src.len) {
604 PyErr_SetString(PyExc_BufferError,
605 "destination is too small to receive data from source");
606 PyBuffer_Release(&view_dest);
607 PyBuffer_Release(&view_src);
608 return -1;
609 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000610
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000611 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
612 PyBuffer_IsContiguous(&view_src, 'C')) ||
613 (PyBuffer_IsContiguous(&view_dest, 'F') &&
614 PyBuffer_IsContiguous(&view_src, 'F'))) {
615 /* simplest copy is all that is needed */
616 memcpy(view_dest.buf, view_src.buf, view_src.len);
617 PyBuffer_Release(&view_dest);
618 PyBuffer_Release(&view_src);
619 return 0;
620 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000621
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000622 /* Otherwise a more elaborate copy scheme is needed */
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000623
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000624 /* XXX(nnorwitz): need to check for overflow! */
625 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
626 if (indices == NULL) {
627 PyErr_NoMemory();
628 PyBuffer_Release(&view_dest);
629 PyBuffer_Release(&view_src);
630 return -1;
631 }
632 for (k=0; k<view_src.ndim;k++) {
633 indices[k] = 0;
634 }
635 elements = 1;
636 for (k=0; k<view_src.ndim; k++) {
637 /* XXX(nnorwitz): can this overflow? */
638 elements *= view_src.shape[k];
639 }
640 while (elements--) {
641 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
642 dptr = PyBuffer_GetPointer(&view_dest, indices);
643 sptr = PyBuffer_GetPointer(&view_src, indices);
644 memcpy(dptr, sptr, view_src.itemsize);
645 }
646 PyMem_Free(indices);
647 PyBuffer_Release(&view_dest);
648 PyBuffer_Release(&view_src);
649 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000650}
651
652void
653PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000654 Py_ssize_t *strides, int itemsize,
655 char fort)
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000656{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000657 int k;
658 Py_ssize_t sd;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000659
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000660 sd = itemsize;
661 if (fort == 'F') {
662 for (k=0; k<nd; k++) {
663 strides[k] = sd;
664 sd *= shape[k];
665 }
666 }
667 else {
668 for (k=nd-1; k>=0; k--) {
669 strides[k] = sd;
670 sd *= shape[k];
671 }
672 }
673 return;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000674}
675
676int
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000677PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000678 int readonly, int flags)
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000679{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000680 if (view == NULL) return 0;
681 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
682 (readonly == 1)) {
683 PyErr_SetString(PyExc_BufferError,
684 "Object is not writable.");
685 return -1;
686 }
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000687
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000688 view->obj = obj;
689 if (obj)
690 Py_INCREF(obj);
691 view->buf = buf;
692 view->len = len;
693 view->readonly = readonly;
694 view->itemsize = 1;
695 view->format = NULL;
696 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
697 view->format = "B";
698 view->ndim = 1;
699 view->shape = NULL;
700 if ((flags & PyBUF_ND) == PyBUF_ND)
701 view->shape = &(view->len);
702 view->strides = NULL;
703 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
704 view->strides = &(view->itemsize);
705 view->suboffsets = NULL;
706 view->internal = NULL;
707 return 0;
Travis E. Oliphant3781aef2008-03-18 04:44:57 +0000708}
709
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000710void
711PyBuffer_Release(Py_buffer *view)
712{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000713 PyObject *obj = view->obj;
714 if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
715 Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
716 Py_XDECREF(obj);
717 view->obj = NULL;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000718}
719
Eric Smitha9f7d622008-02-17 19:46:49 +0000720PyObject *
721PyObject_Format(PyObject* obj, PyObject *format_spec)
722{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000723 static PyObject * str__format__ = NULL;
724 PyObject *empty = NULL;
725 PyObject *result = NULL;
726 int spec_is_unicode;
727 int result_is_unicode;
Eric Smitha9f7d622008-02-17 19:46:49 +0000728
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000729 /* Initialize cached value */
730 if (str__format__ == NULL) {
731 /* Initialize static variable needed by _PyType_Lookup */
732 str__format__ = PyString_InternFromString("__format__");
733 if (str__format__ == NULL)
734 goto done;
735 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000736
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000737 /* If no format_spec is provided, use an empty string */
738 if (format_spec == NULL) {
739 empty = PyString_FromStringAndSize(NULL, 0);
740 format_spec = empty;
741 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000742
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000743 /* Check the format_spec type, and make sure it's str or unicode */
744 if (PyUnicode_Check(format_spec))
745 spec_is_unicode = 1;
746 else if (PyString_Check(format_spec))
747 spec_is_unicode = 0;
748 else {
749 PyErr_Format(PyExc_TypeError,
750 "format expects arg 2 to be string "
751 "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
752 goto done;
753 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000754
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000755 /* Make sure the type is initialized. float gets initialized late */
756 if (Py_TYPE(obj)->tp_dict == NULL)
757 if (PyType_Ready(Py_TYPE(obj)) < 0)
758 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000759
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000760 /* Check for a __format__ method and call it. */
761 if (PyInstance_Check(obj)) {
762 /* We're an instance of a classic class */
763 PyObject *bound_method = PyObject_GetAttr(obj,
764 str__format__);
765 if (bound_method != NULL) {
766 result = PyObject_CallFunctionObjArgs(bound_method,
767 format_spec,
768 NULL);
769 Py_DECREF(bound_method);
770 } else {
771 PyObject *self_as_str;
772 PyObject *format_method;
Eric Smitha9f7d622008-02-17 19:46:49 +0000773
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000774 PyErr_Clear();
775 /* Per the PEP, convert to str (or unicode,
776 depending on the type of the format
777 specifier). For new-style classes, this
778 logic is done by object.__format__(). */
779 if (spec_is_unicode)
780 self_as_str = PyObject_Unicode(obj);
781 else
782 self_as_str = PyObject_Str(obj);
783 if (self_as_str == NULL)
784 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000785
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000786 /* Then call str.__format__ on that result */
787 format_method = PyObject_GetAttr(self_as_str,
788 str__format__);
789 if (format_method == NULL) {
790 Py_DECREF(self_as_str);
791 goto done;
792 }
793 result = PyObject_CallFunctionObjArgs(format_method,
794 format_spec,
795 NULL);
796 Py_DECREF(self_as_str);
797 Py_DECREF(format_method);
798 if (result == NULL)
799 goto done;
800 }
801 } else {
802 /* Not an instance of a classic class, use the code
803 from py3k */
Eric Smitha9f7d622008-02-17 19:46:49 +0000804
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000805 /* Find the (unbound!) __format__ method (a borrowed
806 reference) */
807 PyObject *method = _PyType_Lookup(Py_TYPE(obj),
808 str__format__);
809 if (method == NULL) {
810 PyErr_Format(PyExc_TypeError,
811 "Type %.100s doesn't define __format__",
812 Py_TYPE(obj)->tp_name);
813 goto done;
814 }
815 /* And call it, binding it to the value */
816 result = PyObject_CallFunctionObjArgs(method, obj,
817 format_spec, NULL);
818 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000819
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000820 if (result == NULL)
821 goto done;
Eric Smitha9f7d622008-02-17 19:46:49 +0000822
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000823 /* Check the result type, and make sure it's str or unicode */
824 if (PyUnicode_Check(result))
825 result_is_unicode = 1;
826 else if (PyString_Check(result))
827 result_is_unicode = 0;
828 else {
829 PyErr_Format(PyExc_TypeError,
830 "%.100s.__format__ must return string or "
831 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
832 Py_TYPE(result)->tp_name);
833 Py_DECREF(result);
834 result = NULL;
835 goto done;
836 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000837
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000838 /* Convert to unicode, if needed. Required if spec is unicode
839 and result is str */
840 if (spec_is_unicode && !result_is_unicode) {
841 PyObject *tmp = PyObject_Unicode(result);
842 /* This logic works whether or not tmp is NULL */
843 Py_DECREF(result);
844 result = tmp;
845 }
Eric Smitha9f7d622008-02-17 19:46:49 +0000846
847done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000848 Py_XDECREF(empty);
849 return result;
Eric Smitha9f7d622008-02-17 19:46:49 +0000850}
851
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000852/* Operations on numbers */
853
854int
Fred Drake79912472000-07-09 04:06:11 +0000855PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000856{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000857 return o && o->ob_type->tp_as_number &&
858 (o->ob_type->tp_as_number->nb_int ||
859 o->ob_type->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000860}
861
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000862/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000863
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000864/* New style number protocol support */
Guido van Rossume15dee51995-07-18 14:12:02 +0000865
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000866#define NB_SLOT(x) offsetof(PyNumberMethods, x)
867#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000868 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000869#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000870 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000871
872/*
873 Calling scheme used for binary operations:
874
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000875 v w Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000876 -------------------------------------------------------------------
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000877 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
878 new old v.op(v,w), coerce(v,w), v.op(v,w)
879 old new w.op(v,w), coerce(v,w), v.op(v,w)
880 old old coerce(v,w), v.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000881
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000882 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
883 v->ob_type
884
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000885 Legend:
886 -------
887 * new == new style number
888 * old == old style number
889 * Action indicates the order in which operations are tried until either
890 a valid result is produced or an error occurs.
891
892 */
893
894static PyObject *
895binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000896{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000897 PyObject *x;
898 binaryfunc slotv = NULL;
899 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000900
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000901 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
902 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
903 if (w->ob_type != v->ob_type &&
904 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
905 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
906 if (slotw == slotv)
907 slotw = NULL;
908 }
909 if (slotv) {
910 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
911 x = slotw(v, w);
912 if (x != Py_NotImplemented)
913 return x;
914 Py_DECREF(x); /* can't do it */
915 slotw = NULL;
916 }
917 x = slotv(v, w);
918 if (x != Py_NotImplemented)
919 return x;
920 Py_DECREF(x); /* can't do it */
921 }
922 if (slotw) {
923 x = slotw(v, w);
924 if (x != Py_NotImplemented)
925 return x;
926 Py_DECREF(x); /* can't do it */
927 }
928 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
929 int err = PyNumber_CoerceEx(&v, &w);
930 if (err < 0) {
931 return NULL;
932 }
933 if (err == 0) {
934 PyNumberMethods *mv = v->ob_type->tp_as_number;
935 if (mv) {
936 binaryfunc slot;
937 slot = NB_BINOP(mv, op_slot);
938 if (slot) {
939 x = slot(v, w);
940 Py_DECREF(v);
941 Py_DECREF(w);
942 return x;
943 }
944 }
945 /* CoerceEx incremented the reference counts */
946 Py_DECREF(v);
947 Py_DECREF(w);
948 }
949 }
950 Py_INCREF(Py_NotImplemented);
951 return Py_NotImplemented;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000952}
Guido van Rossum77660912002-04-16 16:32:50 +0000953
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000954static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000955binop_type_error(PyObject *v, PyObject *w, const char *op_name)
956{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000957 PyErr_Format(PyExc_TypeError,
958 "unsupported operand type(s) for %.100s: "
959 "'%.100s' and '%.100s'",
960 op_name,
961 v->ob_type->tp_name,
962 w->ob_type->tp_name);
963 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000964}
965
966static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000967binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
968{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000969 PyObject *result = binary_op1(v, w, op_slot);
970 if (result == Py_NotImplemented) {
971 Py_DECREF(result);
972 return binop_type_error(v, w, op_name);
973 }
974 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000975}
976
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000977
978/*
979 Calling scheme used for ternary operations:
980
Guido van Rossum84675ac2001-09-29 01:05:03 +0000981 *** In some cases, w.op is called before v.op; see binary_op1. ***
982
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000983 v w z Action
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000984 -------------------------------------------------------------------
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000985 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
986 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
987 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
988 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
989 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
990 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
991 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
992 old old old coerce(v,w,z), v.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000993
994 Legend:
995 -------
996 * new == new style number
997 * old == old style number
998 * Action indicates the order in which operations are tried until either
999 a valid result is produced or an error occurs.
1000 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1001 only if z != Py_None; if z == Py_None, then it is treated as absent
1002 variable and only coerce(v,w) is tried.
1003
1004 */
1005
1006static PyObject *
1007ternary_op(PyObject *v,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001008 PyObject *w,
1009 PyObject *z,
1010 const int op_slot,
1011 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +00001012{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001013 PyNumberMethods *mv, *mw, *mz;
1014 PyObject *x = NULL;
1015 ternaryfunc slotv = NULL;
1016 ternaryfunc slotw = NULL;
1017 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +00001018
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001019 mv = v->ob_type->tp_as_number;
1020 mw = w->ob_type->tp_as_number;
1021 if (mv != NULL && NEW_STYLE_NUMBER(v))
1022 slotv = NB_TERNOP(mv, op_slot);
1023 if (w->ob_type != v->ob_type &&
1024 mw != NULL && NEW_STYLE_NUMBER(w)) {
1025 slotw = NB_TERNOP(mw, op_slot);
1026 if (slotw == slotv)
1027 slotw = NULL;
1028 }
1029 if (slotv) {
1030 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1031 x = slotw(v, w, z);
1032 if (x != Py_NotImplemented)
1033 return x;
1034 Py_DECREF(x); /* can't do it */
1035 slotw = NULL;
1036 }
1037 x = slotv(v, w, z);
1038 if (x != Py_NotImplemented)
1039 return x;
1040 Py_DECREF(x); /* can't do it */
1041 }
1042 if (slotw) {
1043 x = slotw(v, w, z);
1044 if (x != Py_NotImplemented)
1045 return x;
1046 Py_DECREF(x); /* can't do it */
1047 }
1048 mz = z->ob_type->tp_as_number;
1049 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1050 slotz = NB_TERNOP(mz, op_slot);
1051 if (slotz == slotv || slotz == slotw)
1052 slotz = NULL;
1053 if (slotz) {
1054 x = slotz(v, w, z);
1055 if (x != Py_NotImplemented)
1056 return x;
1057 Py_DECREF(x); /* can't do it */
1058 }
1059 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001060
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001061 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1062 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1063 /* we have an old style operand, coerce */
1064 PyObject *v1, *z1, *w2, *z2;
1065 int c;
Guido van Rossum77660912002-04-16 16:32:50 +00001066
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001067 c = PyNumber_Coerce(&v, &w);
1068 if (c != 0)
1069 goto error3;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001070
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001071 /* Special case: if the third argument is None, it is
1072 treated as absent argument and not coerced. */
1073 if (z == Py_None) {
1074 if (v->ob_type->tp_as_number) {
1075 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1076 op_slot);
1077 if (slotz)
1078 x = slotz(v, w, z);
1079 else
1080 c = -1;
1081 }
1082 else
1083 c = -1;
1084 goto error2;
1085 }
1086 v1 = v;
1087 z1 = z;
1088 c = PyNumber_Coerce(&v1, &z1);
1089 if (c != 0)
1090 goto error2;
1091 w2 = w;
1092 z2 = z1;
1093 c = PyNumber_Coerce(&w2, &z2);
1094 if (c != 0)
1095 goto error1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001096
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001097 if (v1->ob_type->tp_as_number != NULL) {
1098 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1099 op_slot);
1100 if (slotv)
1101 x = slotv(v1, w2, z2);
1102 else
1103 c = -1;
1104 }
1105 else
1106 c = -1;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001107
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001108 Py_DECREF(w2);
1109 Py_DECREF(z2);
1110 error1:
1111 Py_DECREF(v1);
1112 Py_DECREF(z1);
1113 error2:
1114 Py_DECREF(v);
1115 Py_DECREF(w);
1116 error3:
1117 if (c >= 0)
1118 return x;
1119 }
Guido van Rossum5c66a262001-10-22 04:12:44 +00001120
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001121 if (z == Py_None)
1122 PyErr_Format(
1123 PyExc_TypeError,
1124 "unsupported operand type(s) for ** or pow(): "
1125 "'%.100s' and '%.100s'",
1126 v->ob_type->tp_name,
1127 w->ob_type->tp_name);
1128 else
1129 PyErr_Format(
1130 PyExc_TypeError,
1131 "unsupported operand type(s) for pow(): "
1132 "'%.100s', '%.100s', '%.100s'",
1133 v->ob_type->tp_name,
1134 w->ob_type->tp_name,
1135 z->ob_type->tp_name);
1136 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001137}
1138
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001139#define BINARY_FUNC(func, op, op_name) \
1140 PyObject * \
1141 func(PyObject *v, PyObject *w) { \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001142 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001143 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001144
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001145BINARY_FUNC(PyNumber_Or, nb_or, "|")
1146BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1147BINARY_FUNC(PyNumber_And, nb_and, "&")
1148BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1149BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1150BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001151BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1152BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001153
1154PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001155PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001156{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001157 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1158 if (result == Py_NotImplemented) {
1159 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1160 Py_DECREF(result);
1161 if (m && m->sq_concat) {
1162 return (*m->sq_concat)(v, w);
1163 }
1164 result = binop_type_error(v, w, "+");
1165 }
1166 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001167}
1168
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001169static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001170sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001171{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001172 Py_ssize_t count;
1173 if (PyIndex_Check(n)) {
1174 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1175 if (count == -1 && PyErr_Occurred())
1176 return NULL;
1177 }
1178 else {
1179 return type_error("can't multiply sequence by "
1180 "non-int of type '%.200s'", n);
1181 }
1182 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001183}
1184
1185PyObject *
1186PyNumber_Multiply(PyObject *v, PyObject *w)
1187{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001188 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1189 if (result == Py_NotImplemented) {
1190 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1191 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1192 Py_DECREF(result);
1193 if (mv && mv->sq_repeat) {
1194 return sequence_repeat(mv->sq_repeat, v, w);
1195 }
1196 else if (mw && mw->sq_repeat) {
1197 return sequence_repeat(mw->sq_repeat, w, v);
1198 }
1199 result = binop_type_error(v, w, "*");
1200 }
1201 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001202}
1203
Guido van Rossume15dee51995-07-18 14:12:02 +00001204PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001205PyNumber_FloorDivide(PyObject *v, PyObject *w)
1206{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001207 /* XXX tp_flags test */
1208 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001209}
1210
1211PyObject *
1212PyNumber_TrueDivide(PyObject *v, PyObject *w)
1213{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001214 /* XXX tp_flags test */
1215 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001216}
1217
1218PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001219PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001220{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001221 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001222}
1223
1224PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001225PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001226{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001227 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001228}
1229
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001230/* Binary in-place operators */
1231
1232/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001233 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001234
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001235 - If the left hand object has the appropriate struct members, and
1236 they are filled, call the appropriate function and return the
1237 result. No coercion is done on the arguments; the left-hand object
1238 is the one the operation is performed on, and it's up to the
1239 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001240
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001241 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001242 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001243
1244 */
1245
Guido van Rossum77660912002-04-16 16:32:50 +00001246#define HASINPLACE(t) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001247 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001248
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001249static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001250binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001251{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001252 PyNumberMethods *mv = v->ob_type->tp_as_number;
1253 if (mv != NULL && HASINPLACE(v)) {
1254 binaryfunc slot = NB_BINOP(mv, iop_slot);
1255 if (slot) {
1256 PyObject *x = (slot)(v, w);
1257 if (x != Py_NotImplemented) {
1258 return x;
1259 }
1260 Py_DECREF(x);
1261 }
1262 }
1263 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001264}
1265
1266static PyObject *
1267binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001268 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001269{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001270 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1271 if (result == Py_NotImplemented) {
1272 Py_DECREF(result);
1273 return binop_type_error(v, w, op_name);
1274 }
1275 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001276}
1277
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001278#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001279 PyObject * \
1280 func(PyObject *v, PyObject *w) { \
1281 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1282 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001283
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001284INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1285INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1286INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1287INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1288INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1289INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1290INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001291
1292PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001293PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1294{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001295 /* XXX tp_flags test */
1296 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1297 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001298}
1299
1300PyObject *
1301PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1302{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001303 /* XXX tp_flags test */
1304 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1305 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001306}
1307
1308PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001309PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1310{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001311 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1312 NB_SLOT(nb_add));
1313 if (result == Py_NotImplemented) {
1314 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1315 Py_DECREF(result);
1316 if (m != NULL) {
1317 binaryfunc f = NULL;
1318 if (HASINPLACE(v))
1319 f = m->sq_inplace_concat;
1320 if (f == NULL)
1321 f = m->sq_concat;
1322 if (f != NULL)
1323 return (*f)(v, w);
1324 }
1325 result = binop_type_error(v, w, "+=");
1326 }
1327 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001328}
1329
1330PyObject *
1331PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1332{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001333 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1334 NB_SLOT(nb_multiply));
1335 if (result == Py_NotImplemented) {
1336 ssizeargfunc f = NULL;
1337 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1338 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1339 Py_DECREF(result);
1340 if (mv != NULL) {
1341 if (HASINPLACE(v))
1342 f = mv->sq_inplace_repeat;
1343 if (f == NULL)
1344 f = mv->sq_repeat;
1345 if (f != NULL)
1346 return sequence_repeat(f, v, w);
1347 }
1348 else if (mw != NULL) {
1349 /* Note that the right hand operand should not be
1350 * mutated in this case so sq_inplace_repeat is not
1351 * used. */
1352 if (mw->sq_repeat)
1353 return sequence_repeat(mw->sq_repeat, w, v);
1354 }
1355 result = binop_type_error(v, w, "*=");
1356 }
1357 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001358}
1359
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001360PyObject *
1361PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1362{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001363 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1364 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001365}
1366
1367PyObject *
1368PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1369{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001370 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1371 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1372 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1373 }
1374 else {
1375 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1376 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001377}
1378
1379
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001380/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001381
1382PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001383PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001384{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001385 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001386
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001387 if (o == NULL)
1388 return null_error();
1389 m = o->ob_type->tp_as_number;
1390 if (m && m->nb_negative)
1391 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001392
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001393 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001394}
1395
1396PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001397PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001398{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001399 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001400
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001401 if (o == NULL)
1402 return null_error();
1403 m = o->ob_type->tp_as_number;
1404 if (m && m->nb_positive)
1405 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001406
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001407 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001408}
1409
1410PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001411PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001412{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001413 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001414
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001415 if (o == NULL)
1416 return null_error();
1417 m = o->ob_type->tp_as_number;
1418 if (m && m->nb_invert)
1419 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001420
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001421 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001422}
1423
1424PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001425PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001426{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001427 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001428
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001429 if (o == NULL)
1430 return null_error();
1431 m = o->ob_type->tp_as_number;
1432 if (m && m->nb_absolute)
1433 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001434
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001435 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001436}
1437
Guido van Rossum9e896b32000-04-05 20:11:21 +00001438/* Add a check for embedded NULL-bytes in the argument. */
1439static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001440int_from_string(const char *s, Py_ssize_t len)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001441{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001442 char *end;
1443 PyObject *x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001444
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001445 x = PyInt_FromString((char*)s, &end, 10);
1446 if (x == NULL)
1447 return NULL;
1448 if (end != s + len) {
1449 PyErr_SetString(PyExc_ValueError,
1450 "null byte in argument for int()");
1451 Py_DECREF(x);
1452 return NULL;
1453 }
1454 return x;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001455}
1456
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001457/* Return a Python Int or Long from the object item
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001458 Raise TypeError if the result is not an int-or-long
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001459 or if the object cannot be interpreted as an index.
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001460*/
1461PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001462PyNumber_Index(PyObject *item)
1463{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001464 PyObject *result = NULL;
1465 if (item == NULL)
1466 return null_error();
1467 if (PyInt_Check(item) || PyLong_Check(item)) {
1468 Py_INCREF(item);
1469 return item;
1470 }
1471 if (PyIndex_Check(item)) {
1472 result = item->ob_type->tp_as_number->nb_index(item);
1473 if (result &&
1474 !PyInt_Check(result) && !PyLong_Check(result)) {
1475 PyErr_Format(PyExc_TypeError,
1476 "__index__ returned non-(int,long) " \
1477 "(type %.200s)",
1478 result->ob_type->tp_name);
1479 Py_DECREF(result);
1480 return NULL;
1481 }
1482 }
1483 else {
1484 PyErr_Format(PyExc_TypeError,
1485 "'%.200s' object cannot be interpreted "
1486 "as an index", item->ob_type->tp_name);
1487 }
1488 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001489}
1490
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001491/* Return an error on Overflow only if err is not NULL*/
1492
1493Py_ssize_t
1494PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1495{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001496 Py_ssize_t result;
1497 PyObject *runerr;
1498 PyObject *value = PyNumber_Index(item);
1499 if (value == NULL)
1500 return -1;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001501
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001502 /* We're done if PyInt_AsSsize_t() returns without error. */
1503 result = PyInt_AsSsize_t(value);
1504 if (result != -1 || !(runerr = PyErr_Occurred()))
1505 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001506
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001507 /* Error handling code -- only manage OverflowError differently */
1508 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1509 goto finish;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001510
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001511 PyErr_Clear();
1512 /* If no error-handling desired then the default clipping
1513 is sufficient.
1514 */
1515 if (!err) {
1516 assert(PyLong_Check(value));
1517 /* Whether or not it is less than or equal to
1518 zero is determined by the sign of ob_size
1519 */
1520 if (_PyLong_Sign(value) < 0)
1521 result = PY_SSIZE_T_MIN;
1522 else
1523 result = PY_SSIZE_T_MAX;
1524 }
1525 else {
1526 /* Otherwise replace the error with caller's error object. */
1527 PyErr_Format(err,
1528 "cannot fit '%.200s' into an index-sized integer",
1529 item->ob_type->tp_name);
1530 }
1531
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001532 finish:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001533 Py_DECREF(value);
1534 return result;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00001535}
1536
1537
Guido van Rossume15dee51995-07-18 14:12:02 +00001538PyObject *
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001539_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1540{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001541 const char *type_name;
1542 static PyObject *int_name = NULL;
1543 if (int_name == NULL) {
1544 int_name = PyString_InternFromString("__int__");
1545 if (int_name == NULL)
1546 return NULL;
1547 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001548
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001549 if (integral && (!PyInt_Check(integral) &&
1550 !PyLong_Check(integral))) {
1551 /* Don't go through tp_as_number->nb_int to avoid
1552 hitting the classic class fallback to __trunc__. */
1553 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1554 if (int_func == NULL) {
1555 PyErr_Clear(); /* Raise a different error. */
1556 goto non_integral_error;
1557 }
1558 Py_DECREF(integral);
1559 integral = PyEval_CallObject(int_func, NULL);
1560 Py_DECREF(int_func);
1561 if (integral && (!PyInt_Check(integral) &&
1562 !PyLong_Check(integral))) {
1563 goto non_integral_error;
1564 }
1565 }
1566 return integral;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001567
1568non_integral_error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001569 if (PyInstance_Check(integral)) {
1570 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1571 ->in_class->cl_name);
1572 }
1573 else {
1574 type_name = integral->ob_type->tp_name;
1575 }
1576 PyErr_Format(PyExc_TypeError, error_format, type_name);
1577 Py_DECREF(integral);
1578 return NULL;
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001579}
1580
1581
1582PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001583PyNumber_Int(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001584{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001585 PyNumberMethods *m;
1586 static PyObject *trunc_name = NULL;
1587 PyObject *trunc_func;
1588 const char *buffer;
1589 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001590
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001591 if (trunc_name == NULL) {
1592 trunc_name = PyString_InternFromString("__trunc__");
1593 if (trunc_name == NULL)
1594 return NULL;
1595 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001596
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001597 if (o == NULL)
1598 return null_error();
1599 if (PyInt_CheckExact(o)) {
1600 Py_INCREF(o);
1601 return o;
1602 }
1603 m = o->ob_type->tp_as_number;
1604 if (m && m->nb_int) { /* This should include subclasses of int */
1605 /* Classic classes always take this branch. */
1606 PyObject *res = m->nb_int(o);
1607 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1608 PyErr_Format(PyExc_TypeError,
1609 "__int__ returned non-int (type %.200s)",
1610 res->ob_type->tp_name);
1611 Py_DECREF(res);
1612 return NULL;
1613 }
1614 return res;
1615 }
1616 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1617 PyIntObject *io = (PyIntObject*)o;
1618 return PyInt_FromLong(io->ob_ival);
1619 }
1620 trunc_func = PyObject_GetAttr(o, trunc_name);
1621 if (trunc_func) {
1622 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1623 Py_DECREF(trunc_func);
1624 /* __trunc__ is specified to return an Integral type, but
1625 int() needs to return an int. */
1626 return _PyNumber_ConvertIntegralToInt(
1627 truncated,
1628 "__trunc__ returned non-Integral (type %.200s)");
1629 }
1630 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001631
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001632 if (PyString_Check(o))
1633 return int_from_string(PyString_AS_STRING(o),
1634 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001635#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001636 if (PyUnicode_Check(o))
1637 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1638 PyUnicode_GET_SIZE(o),
1639 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001640#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001641 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1642 return int_from_string((char*)buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001643
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001644 return type_error("int() argument must be a string or a "
1645 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001646}
1647
Guido van Rossum9e896b32000-04-05 20:11:21 +00001648/* Add a check for embedded NULL-bytes in the argument. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001649static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001650long_from_string(const char *s, Py_ssize_t len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001651{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001652 char *end;
1653 PyObject *x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001654
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001655 x = PyLong_FromString((char*)s, &end, 10);
1656 if (x == NULL)
1657 return NULL;
1658 if (end != s + len) {
1659 PyErr_SetString(PyExc_ValueError,
1660 "null byte in argument for long()");
1661 Py_DECREF(x);
1662 return NULL;
1663 }
1664 return x;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001665}
1666
Guido van Rossume15dee51995-07-18 14:12:02 +00001667PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001668PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001669{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001670 PyNumberMethods *m;
1671 static PyObject *trunc_name = NULL;
1672 PyObject *trunc_func;
1673 const char *buffer;
1674 Py_ssize_t buffer_len;
Guido van Rossume15dee51995-07-18 14:12:02 +00001675
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001676 if (trunc_name == NULL) {
1677 trunc_name = PyString_InternFromString("__trunc__");
1678 if (trunc_name == NULL)
1679 return NULL;
1680 }
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001681
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001682 if (o == NULL)
1683 return null_error();
1684 m = o->ob_type->tp_as_number;
1685 if (m && m->nb_long) { /* This should include subclasses of long */
1686 /* Classic classes always take this branch. */
1687 PyObject *res = m->nb_long(o);
1688 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1689 PyErr_Format(PyExc_TypeError,
1690 "__long__ returned non-long (type %.200s)",
1691 res->ob_type->tp_name);
1692 Py_DECREF(res);
1693 return NULL;
1694 }
1695 return res;
1696 }
1697 if (PyLong_Check(o)) /* A long subclass without nb_long */
1698 return _PyLong_Copy((PyLongObject *)o);
1699 trunc_func = PyObject_GetAttr(o, trunc_name);
1700 if (trunc_func) {
1701 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1702 PyObject *int_instance;
1703 Py_DECREF(trunc_func);
1704 /* __trunc__ is specified to return an Integral type,
1705 but long() needs to return a long. */
1706 int_instance = _PyNumber_ConvertIntegralToInt(
1707 truncated,
1708 "__trunc__ returned non-Integral (type %.200s)");
1709 if (int_instance && PyInt_Check(int_instance)) {
1710 /* Make sure that long() returns a long instance. */
1711 long value = PyInt_AS_LONG(int_instance);
1712 Py_DECREF(int_instance);
1713 return PyLong_FromLong(value);
1714 }
1715 return int_instance;
1716 }
1717 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
Jeffrey Yasskina26cf9b2008-02-04 01:04:35 +00001718
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001719 if (PyString_Check(o))
1720 /* need to do extra error checking that PyLong_FromString()
1721 * doesn't do. In particular long('9.5') must raise an
1722 * exception, not truncate the float.
1723 */
1724 return long_from_string(PyString_AS_STRING(o),
1725 PyString_GET_SIZE(o));
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001726#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001727 if (PyUnicode_Check(o))
1728 /* The above check is done in PyLong_FromUnicode(). */
1729 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1730 PyUnicode_GET_SIZE(o),
1731 10);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001732#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001733 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1734 return long_from_string(buffer, buffer_len);
Guido van Rossume15dee51995-07-18 14:12:02 +00001735
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001736 return type_error("long() argument must be a string or a "
1737 "number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001738}
1739
1740PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001741PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001742{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001743 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001744
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001745 if (o == NULL)
1746 return null_error();
1747 m = o->ob_type->tp_as_number;
1748 if (m && m->nb_float) { /* This should include subclasses of float */
1749 PyObject *res = m->nb_float(o);
1750 if (res && !PyFloat_Check(res)) {
1751 PyErr_Format(PyExc_TypeError,
1752 "__float__ returned non-float (type %.200s)",
1753 res->ob_type->tp_name);
1754 Py_DECREF(res);
1755 return NULL;
1756 }
1757 return res;
1758 }
1759 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1760 PyFloatObject *po = (PyFloatObject *)o;
1761 return PyFloat_FromDouble(po->ob_fval);
1762 }
1763 return PyFloat_FromString(o, NULL);
Guido van Rossume15dee51995-07-18 14:12:02 +00001764}
1765
Eric Smith5e527eb2008-02-10 01:36:53 +00001766PyObject *
1767PyNumber_ToBase(PyObject *n, int base)
1768{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001769 PyObject *res = NULL;
1770 PyObject *index = PyNumber_Index(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001771
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001772 if (!index)
1773 return NULL;
1774 if (PyLong_Check(index))
1775 res = _PyLong_Format(index, base, 0, 1);
1776 else if (PyInt_Check(index))
1777 res = _PyInt_Format((PyIntObject*)index, base, 1);
1778 else
1779 /* It should not be possible to get here, as
1780 PyNumber_Index already has a check for the same
1781 condition */
1782 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1783 "int or long");
1784 Py_DECREF(index);
1785 return res;
Eric Smith5e527eb2008-02-10 01:36:53 +00001786}
1787
1788
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001789/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001790
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001791int
Fred Drake79912472000-07-09 04:06:11 +00001792PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001793{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001794 if (s && PyInstance_Check(s))
1795 return PyObject_HasAttrString(s, "__getitem__");
1796 if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type))
1797 return 0;
1798 return s != NULL && s->ob_type->tp_as_sequence &&
1799 s->ob_type->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001800}
1801
Martin v. Löwis18e16552006-02-15 17:27:45 +00001802Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001803PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001804{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001805 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001806
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001807 if (s == NULL) {
1808 null_error();
1809 return -1;
1810 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001811
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001812 m = s->ob_type->tp_as_sequence;
1813 if (m && m->sq_length)
1814 return m->sq_length(s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001815
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001816 type_error("object of type '%.200s' has no len()", s);
1817 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001818}
1819
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001820#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001822PySequence_Length(PyObject *s)
1823{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001824 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001825}
1826#define PySequence_Length PySequence_Size
1827
Guido van Rossume15dee51995-07-18 14:12:02 +00001828PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001829PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001830{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001831 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001832
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001833 if (s == NULL || o == NULL)
1834 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001835
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001836 m = s->ob_type->tp_as_sequence;
1837 if (m && m->sq_concat)
1838 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001839
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001840 /* Instances of user classes defining an __add__() method only
1841 have an nb_add slot, not an sq_concat slot. So we fall back
1842 to nb_add if both arguments appear to be sequences. */
1843 if (PySequence_Check(s) && PySequence_Check(o)) {
1844 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1845 if (result != Py_NotImplemented)
1846 return result;
1847 Py_DECREF(result);
1848 }
1849 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001850}
1851
1852PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001853PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001854{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001855 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001856
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001857 if (o == NULL)
1858 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001859
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001860 m = o->ob_type->tp_as_sequence;
1861 if (m && m->sq_repeat)
1862 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001863
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001864 /* Instances of user classes defining a __mul__() method only
1865 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1866 to nb_multiply if o appears to be a sequence. */
1867 if (PySequence_Check(o)) {
1868 PyObject *n, *result;
1869 n = PyInt_FromSsize_t(count);
1870 if (n == NULL)
1871 return NULL;
1872 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1873 Py_DECREF(n);
1874 if (result != Py_NotImplemented)
1875 return result;
1876 Py_DECREF(result);
1877 }
1878 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001879}
1880
1881PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001882PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1883{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001884 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001885
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001886 if (s == NULL || o == NULL)
1887 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001888
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001889 m = s->ob_type->tp_as_sequence;
1890 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1891 return m->sq_inplace_concat(s, o);
1892 if (m && m->sq_concat)
1893 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001894
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001895 if (PySequence_Check(s) && PySequence_Check(o)) {
1896 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1897 NB_SLOT(nb_add));
1898 if (result != Py_NotImplemented)
1899 return result;
1900 Py_DECREF(result);
1901 }
1902 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001903}
1904
1905PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001906PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001907{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001908 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001909
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001910 if (o == NULL)
1911 return null_error();
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001912
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001913 m = o->ob_type->tp_as_sequence;
1914 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1915 return m->sq_inplace_repeat(o, count);
1916 if (m && m->sq_repeat)
1917 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001918
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001919 if (PySequence_Check(o)) {
1920 PyObject *n, *result;
1921 n = PyInt_FromSsize_t(count);
1922 if (n == NULL)
1923 return NULL;
1924 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1925 NB_SLOT(nb_multiply));
1926 Py_DECREF(n);
1927 if (result != Py_NotImplemented)
1928 return result;
1929 Py_DECREF(result);
1930 }
1931 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001932}
1933
1934PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001935PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001936{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001937 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001938
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001939 if (s == NULL)
1940 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001941
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001942 m = s->ob_type->tp_as_sequence;
1943 if (m && m->sq_item) {
1944 if (i < 0) {
1945 if (m->sq_length) {
1946 Py_ssize_t l = (*m->sq_length)(s);
1947 if (l < 0)
1948 return NULL;
1949 i += l;
1950 }
1951 }
1952 return m->sq_item(s, i);
1953 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001954
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001955 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001956}
1957
1958PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001959PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001960{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001961 PySequenceMethods *m;
1962 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001963
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001964 if (!s) return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00001965
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001966 m = s->ob_type->tp_as_sequence;
1967 if (m && m->sq_slice) {
1968 if (i1 < 0 || i2 < 0) {
1969 if (m->sq_length) {
1970 Py_ssize_t l = (*m->sq_length)(s);
1971 if (l < 0)
1972 return NULL;
1973 if (i1 < 0)
1974 i1 += l;
1975 if (i2 < 0)
1976 i2 += l;
1977 }
1978 }
1979 return m->sq_slice(s, i1, i2);
1980 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
1981 PyObject *res;
1982 PyObject *slice = _PySlice_FromIndices(i1, i2);
1983 if (!slice)
1984 return NULL;
1985 res = mp->mp_subscript(s, slice);
1986 Py_DECREF(slice);
1987 return res;
1988 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001989
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001990 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001991}
1992
1993int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001994PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001995{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001996 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001997
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001998 if (s == NULL) {
1999 null_error();
2000 return -1;
2001 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002002
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002003 m = s->ob_type->tp_as_sequence;
2004 if (m && m->sq_ass_item) {
2005 if (i < 0) {
2006 if (m->sq_length) {
2007 Py_ssize_t l = (*m->sq_length)(s);
2008 if (l < 0)
2009 return -1;
2010 i += l;
2011 }
2012 }
2013 return m->sq_ass_item(s, i, o);
2014 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002015
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002016 type_error("'%.200s' object does not support item assignment", s);
2017 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002018}
2019
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002020int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002021PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002022{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002023 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002024
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002025 if (s == NULL) {
2026 null_error();
2027 return -1;
2028 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002029
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002030 m = s->ob_type->tp_as_sequence;
2031 if (m && m->sq_ass_item) {
2032 if (i < 0) {
2033 if (m->sq_length) {
2034 Py_ssize_t l = (*m->sq_length)(s);
2035 if (l < 0)
2036 return -1;
2037 i += l;
2038 }
2039 }
2040 return m->sq_ass_item(s, i, (PyObject *)NULL);
2041 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002042
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002043 type_error("'%.200s' object doesn't support item deletion", s);
2044 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002045}
2046
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002047int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002048PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002049{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002050 PySequenceMethods *m;
2051 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00002052
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002053 if (s == NULL) {
2054 null_error();
2055 return -1;
2056 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002057
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002058 m = s->ob_type->tp_as_sequence;
2059 if (m && m->sq_ass_slice) {
2060 if (i1 < 0 || i2 < 0) {
2061 if (m->sq_length) {
2062 Py_ssize_t l = (*m->sq_length)(s);
2063 if (l < 0)
2064 return -1;
2065 if (i1 < 0)
2066 i1 += l;
2067 if (i2 < 0)
2068 i2 += l;
2069 }
2070 }
2071 return m->sq_ass_slice(s, i1, i2, o);
2072 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2073 int res;
2074 PyObject *slice = _PySlice_FromIndices(i1, i2);
2075 if (!slice)
2076 return -1;
2077 res = mp->mp_ass_subscript(s, slice, o);
2078 Py_DECREF(slice);
2079 return res;
2080 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00002081
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002082 type_error("'%.200s' object doesn't support slice assignment", s);
2083 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002084}
2085
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002086int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002087PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002088{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002089 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002090
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002091 if (s == NULL) {
2092 null_error();
2093 return -1;
2094 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002095
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002096 m = s->ob_type->tp_as_sequence;
2097 if (m && m->sq_ass_slice) {
2098 if (i1 < 0 || i2 < 0) {
2099 if (m->sq_length) {
2100 Py_ssize_t l = (*m->sq_length)(s);
2101 if (l < 0)
2102 return -1;
2103 if (i1 < 0)
2104 i1 += l;
2105 if (i2 < 0)
2106 i2 += l;
2107 }
2108 }
2109 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2110 }
2111 type_error("'%.200s' object doesn't support slice deletion", s);
2112 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00002113}
2114
Guido van Rossume15dee51995-07-18 14:12:02 +00002115PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002116PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00002117{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002118 PyObject *it; /* iter(v) */
2119 Py_ssize_t n; /* guess for result tuple size */
2120 PyObject *result = NULL;
2121 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00002122
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002123 if (v == NULL)
2124 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002125
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002126 /* Special-case the common tuple and list cases, for efficiency. */
2127 if (PyTuple_CheckExact(v)) {
2128 /* Note that we can't know whether it's safe to return
2129 a tuple *subclass* instance as-is, hence the restriction
2130 to exact tuples here. In contrast, lists always make
2131 a copy, so there's no need for exactness below. */
2132 Py_INCREF(v);
2133 return v;
2134 }
2135 if (PyList_Check(v))
2136 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002137
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002138 /* Get iterator. */
2139 it = PyObject_GetIter(v);
2140 if (it == NULL)
2141 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002142
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002143 /* Guess result size and allocate space. */
2144 n = _PyObject_LengthHint(v, 10);
2145 if (n == -1)
2146 goto Fail;
2147 result = PyTuple_New(n);
2148 if (result == NULL)
2149 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002150
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002151 /* Fill the tuple. */
2152 for (j = 0; ; ++j) {
2153 PyObject *item = PyIter_Next(it);
2154 if (item == NULL) {
2155 if (PyErr_Occurred())
2156 goto Fail;
2157 break;
2158 }
2159 if (j >= n) {
2160 Py_ssize_t oldn = n;
2161 /* The over-allocation strategy can grow a bit faster
2162 than for lists because unlike lists the
2163 over-allocation isn't permanent -- we reclaim
2164 the excess before the end of this routine.
2165 So, grow by ten and then add 25%.
2166 */
2167 n += 10;
2168 n += n >> 2;
2169 if (n < oldn) {
2170 /* Check for overflow */
2171 PyErr_NoMemory();
2172 Py_DECREF(item);
2173 goto Fail;
2174 }
2175 if (_PyTuple_Resize(&result, n) != 0) {
2176 Py_DECREF(item);
2177 goto Fail;
2178 }
2179 }
2180 PyTuple_SET_ITEM(result, j, item);
2181 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002182
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002183 /* Cut tuple back if guess was too large. */
2184 if (j < n &&
2185 _PyTuple_Resize(&result, j) != 0)
2186 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002187
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002188 Py_DECREF(it);
2189 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002190
2191Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002192 Py_XDECREF(result);
2193 Py_DECREF(it);
2194 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002195}
2196
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002197PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002198PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002199{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002200 PyObject *result; /* result list */
2201 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002202
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002203 if (v == NULL)
2204 return null_error();
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002205
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002206 result = PyList_New(0);
2207 if (result == NULL)
2208 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002209
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002210 rv = _PyList_Extend((PyListObject *)result, v);
2211 if (rv == NULL) {
2212 Py_DECREF(result);
2213 return NULL;
2214 }
2215 Py_DECREF(rv);
2216 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002217}
2218
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002219PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002220PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002221{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002222 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002223
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002224 if (v == NULL)
2225 return null_error();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002226
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002227 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2228 Py_INCREF(v);
2229 return v;
2230 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002231
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002232 it = PyObject_GetIter(v);
2233 if (it == NULL) {
2234 if (PyErr_ExceptionMatches(PyExc_TypeError))
2235 PyErr_SetString(PyExc_TypeError, m);
2236 return NULL;
2237 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002238
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002239 v = PySequence_List(it);
2240 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002241
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002242 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002243}
2244
Tim Peters16a77ad2001-09-08 04:00:12 +00002245/* Iterate over seq. Result depends on the operation:
2246 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
Jesus Cea585ad8a2009-07-02 15:37:21 +00002247 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002248 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002249 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2250*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002251Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002252_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002253{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002254 Py_ssize_t n;
2255 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2256 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002257
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002258 if (seq == NULL || obj == NULL) {
2259 null_error();
2260 return -1;
2261 }
Tim Peters75f8e352001-05-05 11:33:43 +00002262
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002263 it = PyObject_GetIter(seq);
2264 if (it == NULL) {
2265 type_error("argument of type '%.200s' is not iterable", seq);
2266 return -1;
2267 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002268
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002269 n = wrapped = 0;
2270 for (;;) {
2271 int cmp;
2272 PyObject *item = PyIter_Next(it);
2273 if (item == NULL) {
2274 if (PyErr_Occurred())
2275 goto Fail;
2276 break;
2277 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002278
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002279 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2280 Py_DECREF(item);
2281 if (cmp < 0)
2282 goto Fail;
2283 if (cmp > 0) {
2284 switch (operation) {
2285 case PY_ITERSEARCH_COUNT:
2286 if (n == PY_SSIZE_T_MAX) {
2287 PyErr_SetString(PyExc_OverflowError,
2288 "count exceeds C integer size");
2289 goto Fail;
2290 }
2291 ++n;
2292 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002293
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002294 case PY_ITERSEARCH_INDEX:
2295 if (wrapped) {
2296 PyErr_SetString(PyExc_OverflowError,
2297 "index exceeds C integer size");
2298 goto Fail;
2299 }
2300 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002301
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002302 case PY_ITERSEARCH_CONTAINS:
2303 n = 1;
2304 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002305
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002306 default:
2307 assert(!"unknown operation");
2308 }
2309 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002310
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002311 if (operation == PY_ITERSEARCH_INDEX) {
2312 if (n == PY_SSIZE_T_MAX)
2313 wrapped = 1;
2314 ++n;
2315 }
2316 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002317
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002318 if (operation != PY_ITERSEARCH_INDEX)
2319 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002320
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002321 PyErr_SetString(PyExc_ValueError,
2322 "sequence.index(x): x not in sequence");
2323 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002324Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002325 n = -1;
2326 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002327Done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002328 Py_DECREF(it);
2329 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002330
Guido van Rossume15dee51995-07-18 14:12:02 +00002331}
2332
Tim Peters16a77ad2001-09-08 04:00:12 +00002333/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002334Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002335PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002336{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002337 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002338}
2339
Tim Peterscb8d3682001-05-05 21:05:01 +00002340/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002341 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002342 */
2343int
2344PySequence_Contains(PyObject *seq, PyObject *ob)
2345{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002346 Py_ssize_t result;
2347 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2348 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2349 if (sqm != NULL && sqm->sq_contains != NULL)
2350 return (*sqm->sq_contains)(seq, ob);
2351 }
2352 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2353 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002354}
2355
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002356/* Backwards compatibility */
2357#undef PySequence_In
2358int
Fred Drake79912472000-07-09 04:06:11 +00002359PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002360{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002361 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002362}
2363
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002364Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002365PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002366{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002367 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002368}
2369
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002370/* Operations on mappings */
2371
2372int
Fred Drake79912472000-07-09 04:06:11 +00002373PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002374{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002375 if (o && PyInstance_Check(o))
2376 return PyObject_HasAttrString(o, "__getitem__");
Raymond Hettingere2eda602004-04-04 08:51:41 +00002377
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002378 return o && o->ob_type->tp_as_mapping &&
2379 o->ob_type->tp_as_mapping->mp_subscript &&
2380 !(o->ob_type->tp_as_sequence &&
2381 o->ob_type->tp_as_sequence->sq_slice);
Guido van Rossume15dee51995-07-18 14:12:02 +00002382}
2383
Martin v. Löwis18e16552006-02-15 17:27:45 +00002384Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002385PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002386{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002387 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002388
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002389 if (o == NULL) {
2390 null_error();
2391 return -1;
2392 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002393
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002394 m = o->ob_type->tp_as_mapping;
2395 if (m && m->mp_length)
2396 return m->mp_length(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00002397
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002398 type_error("object of type '%.200s' has no len()", o);
2399 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002400}
2401
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002402#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002403Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002404PyMapping_Length(PyObject *o)
2405{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002406 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002407}
2408#define PyMapping_Length PyMapping_Size
2409
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002410PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002411PyMapping_GetItemString(PyObject *o, char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002412{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002413 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002414
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002415 if (key == NULL)
2416 return null_error();
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002417
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002418 okey = PyString_FromString(key);
2419 if (okey == NULL)
2420 return NULL;
2421 r = PyObject_GetItem(o, okey);
2422 Py_DECREF(okey);
2423 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002424}
2425
2426int
Fred Drake79912472000-07-09 04:06:11 +00002427PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002428{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002429 PyObject *okey;
2430 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002431
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002432 if (key == NULL) {
2433 null_error();
2434 return -1;
2435 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002436
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002437 okey = PyString_FromString(key);
2438 if (okey == NULL)
2439 return -1;
2440 r = PyObject_SetItem(o, okey, value);
2441 Py_DECREF(okey);
2442 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002443}
2444
2445int
Fred Drake79912472000-07-09 04:06:11 +00002446PyMapping_HasKeyString(PyObject *o, char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002447{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002448 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002449
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002450 v = PyMapping_GetItemString(o, key);
2451 if (v) {
2452 Py_DECREF(v);
2453 return 1;
2454 }
2455 PyErr_Clear();
2456 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002457}
2458
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002459int
Fred Drake79912472000-07-09 04:06:11 +00002460PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002461{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002462 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002463
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002464 v = PyObject_GetItem(o, key);
2465 if (v) {
2466 Py_DECREF(v);
2467 return 1;
2468 }
2469 PyErr_Clear();
2470 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002471}
2472
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002473/* Operations on callable objects */
2474
2475/* XXX PyCallable_Check() is in object.c */
2476
Guido van Rossume15dee51995-07-18 14:12:02 +00002477PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002478PyObject_CallObject(PyObject *o, PyObject *a)
Guido van Rossume15dee51995-07-18 14:12:02 +00002479{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002480 return PyEval_CallObjectWithKeywords(o, a, NULL);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002481}
Guido van Rossume15dee51995-07-18 14:12:02 +00002482
2483PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2485{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002486 ternaryfunc call;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002488 if ((call = func->ob_type->tp_call) != NULL) {
2489 PyObject *result;
2490 if (Py_EnterRecursiveCall(" while calling a Python object"))
2491 return NULL;
2492 result = (*call)(func, arg, kw);
2493 Py_LeaveRecursiveCall();
2494 if (result == NULL && !PyErr_Occurred())
2495 PyErr_SetString(
2496 PyExc_SystemError,
2497 "NULL result without error in PyObject_Call");
2498 return result;
2499 }
2500 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2501 func->ob_type->tp_name);
2502 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503}
2504
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002505static PyObject*
2506call_function_tail(PyObject *callable, PyObject *args)
2507{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002508 PyObject *retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002509
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002510 if (args == NULL)
2511 return NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002512
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002513 if (!PyTuple_Check(args)) {
2514 PyObject *a;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002515
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002516 a = PyTuple_New(1);
2517 if (a == NULL) {
2518 Py_DECREF(args);
2519 return NULL;
2520 }
2521 PyTuple_SET_ITEM(a, 0, args);
2522 args = a;
2523 }
2524 retval = PyObject_Call(callable, args, NULL);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002525
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002526 Py_DECREF(args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002527
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002528 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002529}
2530
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531PyObject *
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002532PyObject_CallFunction(PyObject *callable, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002533{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002534 va_list va;
2535 PyObject *args;
Guido van Rossume15dee51995-07-18 14:12:02 +00002536
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002537 if (callable == NULL)
2538 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002539
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002540 if (format && *format) {
2541 va_start(va, format);
2542 args = Py_VaBuildValue(format, va);
2543 va_end(va);
2544 }
2545 else
2546 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002547
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002548 return call_function_tail(callable, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002549}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002550
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002551PyObject *
2552_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2553{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002554 va_list va;
2555 PyObject *args;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002556
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002557 if (callable == NULL)
2558 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002559
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002560 if (format && *format) {
2561 va_start(va, format);
2562 args = _Py_VaBuildValue_SizeT(format, va);
2563 va_end(va);
2564 }
2565 else
2566 args = PyTuple_New(0);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002567
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002568 return call_function_tail(callable, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002569}
2570
2571PyObject *
Guido van Rossume15dee51995-07-18 14:12:02 +00002572PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
Guido van Rossume15dee51995-07-18 14:12:02 +00002573{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002574 va_list va;
2575 PyObject *args;
2576 PyObject *func = NULL;
2577 PyObject *retval = NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002578
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002579 if (o == NULL || name == NULL)
2580 return null_error();
Guido van Rossume15dee51995-07-18 14:12:02 +00002581
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002582 func = PyObject_GetAttrString(o, name);
2583 if (func == NULL) {
2584 PyErr_SetString(PyExc_AttributeError, name);
2585 return 0;
2586 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002587
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002588 if (!PyCallable_Check(func)) {
2589 type_error("attribute of type '%.200s' is not callable", func);
2590 goto exit;
2591 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002592
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002593 if (format && *format) {
2594 va_start(va, format);
2595 args = Py_VaBuildValue(format, va);
2596 va_end(va);
2597 }
2598 else
2599 args = PyTuple_New(0);
Guido van Rossume15dee51995-07-18 14:12:02 +00002600
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002601 retval = call_function_tail(func, args);
Guido van Rossume15dee51995-07-18 14:12:02 +00002602
Michael W. Hudson0edc7a02005-07-12 10:21:19 +00002603 exit:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002604 /* args gets consumed in call_function_tail */
2605 Py_XDECREF(func);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002606
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002607 return retval;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002608}
2609
2610PyObject *
2611_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2612{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002613 va_list va;
2614 PyObject *args;
2615 PyObject *func = NULL;
2616 PyObject *retval = NULL;
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002617
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002618 if (o == NULL || name == NULL)
2619 return null_error();
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002620
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002621 func = PyObject_GetAttrString(o, name);
2622 if (func == NULL) {
2623 PyErr_SetString(PyExc_AttributeError, name);
2624 return 0;
2625 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002626
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002627 if (!PyCallable_Check(func)) {
2628 type_error("attribute of type '%.200s' is not callable", func);
2629 goto exit;
2630 }
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002631
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002632 if (format && *format) {
2633 va_start(va, format);
2634 args = _Py_VaBuildValue_SizeT(format, va);
2635 va_end(va);
2636 }
2637 else
2638 args = PyTuple_New(0);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002639
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002640 retval = call_function_tail(func, args);
Martin v. Löwis5cb69362006-04-14 09:08:42 +00002641
2642 exit:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002643 /* args gets consumed in call_function_tail */
2644 Py_XDECREF(func);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002645
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002646 return retval;
Guido van Rossume15dee51995-07-18 14:12:02 +00002647}
Guido van Rossum823649d2001-03-21 18:40:58 +00002648
2649
Fred Drakeb421b8c2001-10-26 16:21:32 +00002650static PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002651objargs_mktuple(va_list va)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002652{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002653 int i, n = 0;
2654 va_list countva;
2655 PyObject *result, *tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002656
2657#ifdef VA_LIST_IS_ARRAY
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002658 memcpy(countva, va, sizeof(va_list));
Fred Drakeb421b8c2001-10-26 16:21:32 +00002659#else
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002660#ifdef __va_copy
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002661 __va_copy(countva, va);
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002662#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002663 countva = va;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002664#endif
Martin v. Löwis75d2d942002-07-28 10:23:27 +00002665#endif
Fred Drakeb421b8c2001-10-26 16:21:32 +00002666
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002667 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2668 ++n;
2669 result = PyTuple_New(n);
2670 if (result != NULL && n > 0) {
2671 for (i = 0; i < n; ++i) {
2672 tmp = (PyObject *)va_arg(va, PyObject *);
2673 PyTuple_SET_ITEM(result, i, tmp);
2674 Py_INCREF(tmp);
2675 }
2676 }
2677 return result;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002678}
2679
2680PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002681PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002682{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002683 PyObject *args, *tmp;
2684 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002685
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002686 if (callable == NULL || name == NULL)
2687 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002688
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002689 callable = PyObject_GetAttr(callable, name);
2690 if (callable == NULL)
2691 return NULL;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002692
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002693 /* count the args */
2694 va_start(vargs, name);
2695 args = objargs_mktuple(vargs);
2696 va_end(vargs);
2697 if (args == NULL) {
2698 Py_DECREF(callable);
2699 return NULL;
2700 }
2701 tmp = PyObject_Call(callable, args, NULL);
2702 Py_DECREF(args);
2703 Py_DECREF(callable);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002704
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002705 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002706}
2707
2708PyObject *
Fred Drakeb0c079e2001-10-28 02:39:03 +00002709PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Fred Drakeb421b8c2001-10-26 16:21:32 +00002710{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002711 PyObject *args, *tmp;
2712 va_list vargs;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002713
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002714 if (callable == NULL)
2715 return null_error();
Fred Drakeb421b8c2001-10-26 16:21:32 +00002716
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002717 /* count the args */
2718 va_start(vargs, callable);
2719 args = objargs_mktuple(vargs);
2720 va_end(vargs);
2721 if (args == NULL)
2722 return NULL;
2723 tmp = PyObject_Call(callable, args, NULL);
2724 Py_DECREF(args);
Fred Drakeb421b8c2001-10-26 16:21:32 +00002725
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002726 return tmp;
Fred Drakeb421b8c2001-10-26 16:21:32 +00002727}
2728
2729
Guido van Rossum823649d2001-03-21 18:40:58 +00002730/* isinstance(), issubclass() */
2731
Barry Warsawf16951c2002-04-23 22:45:44 +00002732/* abstract_get_bases() has logically 4 return states, with a sort of 0th
2733 * state that will almost never happen.
2734 *
2735 * 0. creating the __bases__ static string could get a MemoryError
2736 * 1. getattr(cls, '__bases__') could raise an AttributeError
2737 * 2. getattr(cls, '__bases__') could raise some other exception
2738 * 3. getattr(cls, '__bases__') could return a tuple
2739 * 4. getattr(cls, '__bases__') could return something other than a tuple
2740 *
2741 * Only state #3 is a non-error state and only it returns a non-NULL object
2742 * (it returns the retrieved tuple).
2743 *
2744 * Any raised AttributeErrors are masked by clearing the exception and
2745 * returning NULL. If an object other than a tuple comes out of __bases__,
2746 * then again, the return value is NULL. So yes, these two situations
2747 * produce exactly the same results: NULL is returned and no error is set.
2748 *
2749 * If some exception other than AttributeError is raised, then NULL is also
2750 * returned, but the exception is not cleared. That's because we want the
2751 * exception to be propagated along.
2752 *
2753 * Callers are expected to test for PyErr_Occurred() when the return value
2754 * is NULL to decide whether a valid exception should be propagated or not.
2755 * When there's no exception to propagate, it's customary for the caller to
2756 * set a TypeError.
2757 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002758static PyObject *
2759abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002760{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002761 static PyObject *__bases__ = NULL;
2762 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002763
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002764 if (__bases__ == NULL) {
2765 __bases__ = PyString_InternFromString("__bases__");
2766 if (__bases__ == NULL)
2767 return NULL;
2768 }
2769 bases = PyObject_GetAttr(cls, __bases__);
2770 if (bases == NULL) {
2771 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2772 PyErr_Clear();
2773 return NULL;
2774 }
2775 if (!PyTuple_Check(bases)) {
2776 Py_DECREF(bases);
2777 return NULL;
2778 }
2779 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002780}
2781
2782
2783static int
2784abstract_issubclass(PyObject *derived, PyObject *cls)
2785{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002786 PyObject *bases = NULL;
2787 Py_ssize_t i, n;
2788 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002789
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002790 while (1) {
2791 if (derived == cls)
2792 return 1;
2793 bases = abstract_get_bases(derived);
2794 if (bases == NULL) {
2795 if (PyErr_Occurred())
2796 return -1;
2797 return 0;
2798 }
2799 n = PyTuple_GET_SIZE(bases);
2800 if (n == 0) {
2801 Py_DECREF(bases);
2802 return 0;
2803 }
2804 /* Avoid recursivity in the single inheritance case */
2805 if (n == 1) {
2806 derived = PyTuple_GET_ITEM(bases, 0);
2807 Py_DECREF(bases);
2808 continue;
2809 }
2810 for (i = 0; i < n; i++) {
2811 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2812 if (r != 0)
2813 break;
2814 }
2815 Py_DECREF(bases);
2816 return r;
2817 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002818}
2819
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002820static int
2821check_class(PyObject *cls, const char *error)
2822{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002823 PyObject *bases = abstract_get_bases(cls);
2824 if (bases == NULL) {
2825 /* Do not mask errors. */
2826 if (!PyErr_Occurred())
2827 PyErr_SetString(PyExc_TypeError, error);
2828 return 0;
2829 }
2830 Py_DECREF(bases);
2831 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002832}
2833
Brett Cannon4f653312004-03-20 22:52:14 +00002834static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002835recursive_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002836{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002837 PyObject *icls;
2838 static PyObject *__class__ = NULL;
2839 int retval = 0;
Guido van Rossum823649d2001-03-21 18:40:58 +00002840
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002841 if (__class__ == NULL) {
2842 __class__ = PyString_InternFromString("__class__");
2843 if (__class__ == NULL)
2844 return -1;
2845 }
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002846
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002847 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2848 PyObject *inclass =
2849 (PyObject*)((PyInstanceObject*)inst)->in_class;
2850 retval = PyClass_IsSubclass(inclass, cls);
2851 }
2852 else if (PyType_Check(cls)) {
2853 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2854 if (retval == 0) {
2855 PyObject *c = PyObject_GetAttr(inst, __class__);
2856 if (c == NULL) {
2857 PyErr_Clear();
2858 }
2859 else {
2860 if (c != (PyObject *)(inst->ob_type) &&
2861 PyType_Check(c))
2862 retval = PyType_IsSubtype(
2863 (PyTypeObject *)c,
2864 (PyTypeObject *)cls);
2865 Py_DECREF(c);
2866 }
2867 }
2868 }
2869 else {
2870 if (!check_class(cls,
2871 "isinstance() arg 2 must be a class, type,"
2872 " or tuple of classes and types"))
2873 return -1;
2874 icls = PyObject_GetAttr(inst, __class__);
2875 if (icls == NULL) {
2876 PyErr_Clear();
2877 retval = 0;
2878 }
2879 else {
2880 retval = abstract_issubclass(icls, cls);
2881 Py_DECREF(icls);
2882 }
2883 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002884
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002885 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002886}
2887
2888int
Brett Cannon4f653312004-03-20 22:52:14 +00002889PyObject_IsInstance(PyObject *inst, PyObject *cls)
2890{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002891 static PyObject *name = NULL;
2892 PyObject *checker;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002893
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002894 /* Quick test for an exact match */
2895 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2896 return 1;
Raymond Hettinger9a47e622008-03-18 23:22:29 +00002897
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002898 if (PyTuple_Check(cls)) {
2899 Py_ssize_t i;
2900 Py_ssize_t n;
2901 int r = 0;
Antoine Pitrou0668c622008-08-26 22:42:08 +00002902
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002903 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2904 return -1;
2905 n = PyTuple_GET_SIZE(cls);
2906 for (i = 0; i < n; ++i) {
2907 PyObject *item = PyTuple_GET_ITEM(cls, i);
2908 r = PyObject_IsInstance(inst, item);
2909 if (r != 0)
2910 /* either found it, or got an error */
2911 break;
2912 }
2913 Py_LeaveRecursiveCall();
2914 return r;
2915 }
2916 if (name == NULL) {
2917 name = PyString_InternFromString("__instancecheck__");
2918 if (name == NULL)
2919 return -1;
2920 }
2921 checker = PyObject_GetAttr(cls, name);
2922 if (checker == NULL && PyErr_Occurred())
2923 PyErr_Clear();
2924 if (checker != NULL) {
2925 PyObject *res;
2926 int ok = -1;
2927 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2928 Py_DECREF(checker);
2929 return ok;
2930 }
2931 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2932 Py_LeaveRecursiveCall();
2933 Py_DECREF(checker);
2934 if (res != NULL) {
2935 ok = PyObject_IsTrue(res);
2936 Py_DECREF(res);
2937 }
2938 return ok;
2939 }
2940 return recursive_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002941}
2942
2943static int
Antoine Pitrou0668c622008-08-26 22:42:08 +00002944recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002945{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002946 int retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002947
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002948 if (PyType_Check(cls) && PyType_Check(derived)) {
2949 /* Fast path (non-recursive) */
2950 return PyType_IsSubtype(
2951 (PyTypeObject *)derived, (PyTypeObject *)cls);
2952 }
2953 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2954 if (!check_class(derived,
2955 "issubclass() arg 1 must be a class"))
2956 return -1;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002957
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002958 if (!check_class(cls,
2959 "issubclass() arg 2 must be a class"
2960 " or tuple of classes"))
2961 return -1;
2962 retval = abstract_issubclass(derived, cls);
2963 }
2964 else {
2965 /* shortcut */
2966 if (!(retval = (derived == cls)))
2967 retval = PyClass_IsSubclass(derived, cls);
2968 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002969
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002970 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002971}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002972
Brett Cannon4f653312004-03-20 22:52:14 +00002973int
2974PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2975{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002976 static PyObject *name = NULL;
2977 PyObject *t, *v, *tb;
2978 PyObject *checker;
2979
2980 if (PyTuple_Check(cls)) {
2981 Py_ssize_t i;
2982 Py_ssize_t n;
2983 int r = 0;
2984
2985 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2986 return -1;
2987 n = PyTuple_GET_SIZE(cls);
2988 for (i = 0; i < n; ++i) {
2989 PyObject *item = PyTuple_GET_ITEM(cls, i);
2990 r = PyObject_IsSubclass(derived, item);
2991 if (r != 0)
2992 /* either found it, or got an error */
2993 break;
2994 }
2995 Py_LeaveRecursiveCall();
2996 return r;
2997 }
2998 if (name == NULL) {
2999 name = PyString_InternFromString("__subclasscheck__");
3000 if (name == NULL)
3001 return -1;
3002 }
3003 PyErr_Fetch(&t, &v, &tb);
3004 checker = PyObject_GetAttr(cls, name);
3005 PyErr_Restore(t, v, tb);
3006 if (checker != NULL) {
3007 PyObject *res;
3008 int ok = -1;
3009 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3010 Py_DECREF(checker);
3011 return ok;
3012 }
3013 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3014 Py_LeaveRecursiveCall();
3015 Py_DECREF(checker);
3016 if (res != NULL) {
3017 ok = PyObject_IsTrue(res);
3018 Py_DECREF(res);
3019 }
3020 return ok;
3021 }
3022 return recursive_issubclass(derived, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003023}
3024
3025int
3026_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3027{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003028 return recursive_isinstance(inst, cls);
Antoine Pitrou0668c622008-08-26 22:42:08 +00003029}
3030
3031int
3032_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3033{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003034 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00003035}
3036
3037
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003038PyObject *
3039PyObject_GetIter(PyObject *o)
3040{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003041 PyTypeObject *t = o->ob_type;
3042 getiterfunc f = NULL;
3043 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3044 f = t->tp_iter;
3045 if (f == NULL) {
3046 if (PySequence_Check(o))
3047 return PySeqIter_New(o);
3048 return type_error("'%.200s' object is not iterable", o);
3049 }
3050 else {
3051 PyObject *res = (*f)(o);
3052 if (res != NULL && !PyIter_Check(res)) {
3053 PyErr_Format(PyExc_TypeError,
3054 "iter() returned non-iterator "
3055 "of type '%.100s'",
3056 res->ob_type->tp_name);
3057 Py_DECREF(res);
3058 res = NULL;
3059 }
3060 return res;
3061 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00003062}
3063
Tim Petersf4848da2001-05-05 00:14:56 +00003064/* Return next item.
3065 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3066 * If the iteration terminates normally, return NULL and clear the
3067 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3068 * will be false.
3069 * Else return the next object. PyErr_Occurred() will be false.
3070 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00003071PyObject *
3072PyIter_Next(PyObject *iter)
3073{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003074 PyObject *result;
3075 assert(PyIter_Check(iter));
3076 result = (*iter->ob_type->tp_iternext)(iter);
3077 if (result == NULL &&
3078 PyErr_Occurred() &&
3079 PyErr_ExceptionMatches(PyExc_StopIteration))
3080 PyErr_Clear();
3081 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003082}