blob: cc452eaaf3daaf2dc1be9d1584a0cb2277452cb3 [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"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_abstract.h" // _PyIndex_Check()
5#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01006#include "pycore_object.h" // _Py_CheckSlotResult()
Victor Stinner61b64922020-06-23 15:55:06 +02007#include "pycore_pyerrors.h" // _PyErr_Occurred()
Victor Stinner4a21e572020-04-15 02:35:41 +02008#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01009#include "pycore_unionobject.h" // _Py_UnionType && _Py_Union()
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +000010#include <ctype.h>
Victor Stinner4a21e572020-04-15 02:35:41 +020011#include <stddef.h> // offsetof()
Tim Peters64b5ce32001-09-10 20:52:51 +000012#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +000013
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000015
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000016/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000017
18static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000020{
Victor Stinner0d76d2b2020-02-07 01:53:23 +010021 PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000023}
24
Guido van Rossum052b7e11996-11-11 15:08:19 +000025static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000026null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000027{
Victor Stinner61b64922020-06-23 15:55:06 +020028 PyThreadState *tstate = _PyThreadState_GET();
29 if (!_PyErr_Occurred(tstate)) {
30 _PyErr_SetString(tstate, PyExc_SystemError,
31 "null argument to internal routine");
32 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000034}
35
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000036/* Operations on any object */
37
Guido van Rossume15dee51995-07-18 14:12:02 +000038PyObject *
Fred Drake79912472000-07-09 04:06:11 +000039PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000042
Victor Stinner71aea8e2016-08-19 16:59:55 +020043 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020045 }
46
Victor Stinner0d76d2b2020-02-07 01:53:23 +010047 v = (PyObject *)Py_TYPE(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 Py_INCREF(v);
49 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000050}
51
Martin v. Löwis18e16552006-02-15 17:27:45 +000052Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000053PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (o == NULL) {
58 null_error();
59 return -1;
60 }
Guido van Rossume15dee51995-07-18 14:12:02 +000061
Victor Stinner0d76d2b2020-02-07 01:53:23 +010062 m = Py_TYPE(o)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +030063 if (m && m->sq_length) {
64 Py_ssize_t len = m->sq_length(o);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +010065 assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
Serhiy Storchaka813f9432017-04-16 09:21:44 +030066 return len;
67 }
Guido van Rossume15dee51995-07-18 14:12:02 +000068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000070}
71
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000072#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000073Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000074PyObject_Length(PyObject *o)
75{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000077}
78#define PyObject_Length PyObject_Size
79
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020080int
81_PyObject_HasLen(PyObject *o) {
82 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
83 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
84}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000085
Christian Heimes255f53b2007-12-08 15:33:56 +000086/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020087 or o.__length_hint__(). If those methods aren't found the defaultvalue is
88 returned. If one of the calls fails with an exception other than TypeError
89 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000090*/
91
92Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020093PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000094{
Christian Heimesb70e8a12012-10-06 17:16:39 +020095 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020096 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050097 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030098 if (_PyObject_HasLen(o)) {
99 res = PyObject_Length(o);
Serhiy Storchaka813f9432017-04-16 09:21:44 +0300100 if (res < 0) {
Victor Stinner61b64922020-06-23 15:55:06 +0200101 PyThreadState *tstate = _PyThreadState_GET();
102 assert(_PyErr_Occurred(tstate));
103 if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300104 return -1;
105 }
Victor Stinner61b64922020-06-23 15:55:06 +0200106 _PyErr_Clear(tstate);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200107 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300108 else {
109 return res;
110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
Christian Heimes6314d162012-10-06 17:13:29 +0200112 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200113 if (hint == NULL) {
114 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 return defaultvalue;
118 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100119 result = _PyObject_CallNoArg(hint);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200120 Py_DECREF(hint);
121 if (result == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +0200122 PyThreadState *tstate = _PyThreadState_GET();
123 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
124 _PyErr_Clear(tstate);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200125 return defaultvalue;
126 }
127 return -1;
128 }
129 else if (result == Py_NotImplemented) {
130 Py_DECREF(result);
131 return defaultvalue;
132 }
133 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200134 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200135 Py_TYPE(result)->tp_name);
136 Py_DECREF(result);
137 return -1;
138 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200139 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200140 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200141 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200142 return -1;
143 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200144 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200145 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
146 return -1;
147 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200148 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000149}
150
Guido van Rossume15dee51995-07-18 14:12:02 +0000151PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000152PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 PyMappingMethods *m;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000155 PySequenceMethods *ms;
Guido van Rossume15dee51995-07-18 14:12:02 +0000156
Victor Stinner71aea8e2016-08-19 16:59:55 +0200157 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200159 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000160
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100161 m = Py_TYPE(o)->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100162 if (m && m->mp_subscript) {
163 PyObject *item = m->mp_subscript(o, key);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +0100164 assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
Victor Stinnere20310f2015-11-05 13:56:58 +0100165 return item;
166 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000167
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100168 ms = Py_TYPE(o)->tp_as_sequence;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000169 if (ms && ms->sq_item) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200170 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 Py_ssize_t key_value;
172 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
173 if (key_value == -1 && PyErr_Occurred())
174 return NULL;
175 return PySequence_GetItem(o, key_value);
176 }
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000177 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 return type_error("sequence index must "
179 "be integer, not '%.200s'", key);
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000182
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100183 if (PyType_Check(o)) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200184 PyObject *meth, *result;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100185 _Py_IDENTIFIER(__class_getitem__);
Victor Stinnera15e2602020-04-08 02:01:56 +0200186
Guido van Rossum48b069a2020-04-07 09:50:06 -0700187 // Special case type[int], but disallow other types so str[int] fails
188 if ((PyTypeObject*)o == &PyType_Type) {
189 return Py_GenericAlias(o, key);
190 }
191
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200192 if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
193 return NULL;
194 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100195 if (meth) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100196 result = PyObject_CallOneArg(meth, key);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100197 Py_DECREF(meth);
198 return result;
199 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100200 }
201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000203}
204
205int
Fred Drake79912472000-07-09 04:06:11 +0000206PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (o == NULL || key == NULL || value == NULL) {
211 null_error();
212 return -1;
213 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100214 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if (m && m->mp_ass_subscript)
216 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000217
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100218 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200219 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_ssize_t key_value;
221 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
222 if (key_value == -1 && PyErr_Occurred())
223 return -1;
224 return PySequence_SetItem(o, key_value, value);
225 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100226 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 type_error("sequence index must be "
228 "integer, not '%.200s'", key);
229 return -1;
230 }
231 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 type_error("'%.200s' object does not support item assignment", o);
234 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000235}
236
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000237int
Fred Drake79912472000-07-09 04:06:11 +0000238PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if (o == NULL || key == NULL) {
243 null_error();
244 return -1;
245 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100246 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (m && m->mp_ass_subscript)
248 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000249
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100250 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200251 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_ssize_t key_value;
253 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
254 if (key_value == -1 && PyErr_Occurred())
255 return -1;
256 return PySequence_DelItem(o, key_value);
257 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100258 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 type_error("sequence index must be "
260 "integer, not '%.200s'", key);
261 return -1;
262 }
263 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 type_error("'%.200s' object does not support item deletion", o);
266 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000267}
268
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000269int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300270PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyObject *okey;
273 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (o == NULL || key == NULL) {
276 null_error();
277 return -1;
278 }
279 okey = PyUnicode_FromString(key);
280 if (okey == NULL)
281 return -1;
282 ret = PyObject_DelItem(o, okey);
283 Py_DECREF(okey);
284 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000285}
286
Victor Stinneref5c6152020-04-08 01:13:53 +0200287
288/* Return 1 if the getbuffer function is available, otherwise return 0. */
289int
290PyObject_CheckBuffer(PyObject *obj)
291{
292 PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
293 return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
294}
295
296
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000297/* Buffer C-API for Python 3.0 */
298
299int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000300PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000301{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100302 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200303
304 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400306 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 Py_TYPE(obj)->tp_name);
308 return -1;
309 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200310 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000311}
312
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000313static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100314_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 Py_ssize_t sd, dim;
317 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000318
Stefan Krah363af442015-02-01 14:53:54 +0100319 /* 1) len = product(shape) * itemsize
320 2) itemsize > 0
321 3) len = 0 <==> exists i: shape[i] = 0 */
322 if (view->len == 0) return 1;
323 if (view->strides == NULL) { /* C-contiguous by definition */
324 /* Trivially F-contiguous */
325 if (view->ndim <= 1) return 1;
326
327 /* ndim > 1 implies shape != NULL */
328 assert(view->shape != NULL);
329
330 /* Effectively 1-d */
331 sd = 0;
332 for (i=0; i<view->ndim; i++) {
333 if (view->shape[i] > 1) sd += 1;
334 }
335 return sd <= 1;
336 }
337
338 /* strides != NULL implies both of these */
339 assert(view->ndim > 0);
340 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 for (i=0; i<view->ndim; i++) {
344 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100345 if (dim > 1 && view->strides[i] != sd) {
346 return 0;
347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 sd *= dim;
349 }
350 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000351}
352
353static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100354_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 Py_ssize_t sd, dim;
357 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000358
Stefan Krah363af442015-02-01 14:53:54 +0100359 /* 1) len = product(shape) * itemsize
360 2) itemsize > 0
361 3) len = 0 <==> exists i: shape[i] = 0 */
362 if (view->len == 0) return 1;
363 if (view->strides == NULL) return 1; /* C-contiguous by definition */
364
365 /* strides != NULL implies both of these */
366 assert(view->ndim > 0);
367 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 for (i=view->ndim-1; i>=0; i--) {
371 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100372 if (dim > 1 && view->strides[i] != sd) {
373 return 0;
374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 sd *= dim;
376 }
377 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000378}
379
380int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100381PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000382{
383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000385
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100386 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100388 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100390 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 return (_IsCContiguous(view) || _IsFortranContiguous(view));
392 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000393}
394
395
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000397PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 char* pointer;
400 int i;
401 pointer = (char *)view->buf;
402 for (i = 0; i < view->ndim; i++) {
403 pointer += view->strides[i]*indices[i];
404 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
405 pointer = *((char**)pointer) + view->suboffsets[i];
406 }
407 }
408 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000409}
410
411
Guido van Rossum98297ee2007-11-06 21:34:58 +0000412void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000413_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 for (k=0; k<nd; k++) {
418 if (index[k] < shape[k]-1) {
419 index[k]++;
420 break;
421 }
422 else {
423 index[k] = 0;
424 }
425 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000426}
427
Guido van Rossum98297ee2007-11-06 21:34:58 +0000428void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000429_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 for (k=nd-1; k>=0; k--) {
434 if (index[k] < shape[k]-1) {
435 index[k]++;
436 break;
437 }
438 else {
439 index[k] = 0;
440 }
441 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000442}
443
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -0300444Py_ssize_t
445PyBuffer_SizeFromFormat(const char *format)
446{
447 PyObject *structmodule = NULL;
448 PyObject *calcsize = NULL;
449 PyObject *res = NULL;
450 PyObject *fmt = NULL;
451 Py_ssize_t itemsize = -1;
452
453 structmodule = PyImport_ImportModule("struct");
454 if (structmodule == NULL) {
455 return itemsize;
456 }
457
458 calcsize = PyObject_GetAttrString(structmodule, "calcsize");
459 if (calcsize == NULL) {
460 goto done;
461 }
462
463 fmt = PyUnicode_FromString(format);
464 if (fmt == NULL) {
465 goto done;
466 }
467
468 res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
469 if (res == NULL) {
470 goto done;
471 }
472
473 itemsize = PyLong_AsSsize_t(res);
474 if (itemsize < 0) {
475 goto done;
476 }
477
478done:
479 Py_DECREF(structmodule);
480 Py_XDECREF(calcsize);
481 Py_XDECREF(fmt);
482 Py_XDECREF(res);
483 return itemsize;
484}
485
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000486int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000487PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000490 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_ssize_t *indices, elements;
492 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (len > view->len) {
495 len = view->len;
496 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (PyBuffer_IsContiguous(view, fort)) {
499 /* simplest copy is all that is needed */
500 memcpy(view->buf, buf, len);
501 return 0;
502 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505
Stefan Krah7213fcc2015-02-01 16:19:23 +0100506 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
508 if (indices == NULL) {
509 PyErr_NoMemory();
510 return -1;
511 }
512 for (k=0; k<view->ndim;k++) {
513 indices[k] = 0;
514 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000517 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 }
519 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000520 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 }
522 src = buf;
523 /* XXX : This is not going to be the fastest code in the world
524 several optimizations are possible.
525 */
526 elements = len / view->itemsize;
527 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 ptr = PyBuffer_GetPointer(view, indices);
529 memcpy(ptr, src, view->itemsize);
530 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100531 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 PyMem_Free(indices);
535 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000536}
537
Guido van Rossum98297ee2007-11-06 21:34:58 +0000538int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_buffer view_dest, view_src;
541 int k;
542 Py_ssize_t *indices, elements;
543 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (!PyObject_CheckBuffer(dest) ||
546 !PyObject_CheckBuffer(src)) {
547 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400548 "both destination and source must be "\
549 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return -1;
551 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
554 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
555 PyBuffer_Release(&view_dest);
556 return -1;
557 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (view_dest.len < view_src.len) {
560 PyErr_SetString(PyExc_BufferError,
561 "destination is too small to receive data from source");
562 PyBuffer_Release(&view_dest);
563 PyBuffer_Release(&view_src);
564 return -1;
565 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
568 PyBuffer_IsContiguous(&view_src, 'C')) ||
569 (PyBuffer_IsContiguous(&view_dest, 'F') &&
570 PyBuffer_IsContiguous(&view_src, 'F'))) {
571 /* simplest copy is all that is needed */
572 memcpy(view_dest.buf, view_src.buf, view_src.len);
573 PyBuffer_Release(&view_dest);
574 PyBuffer_Release(&view_src);
575 return 0;
576 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* XXX(nnorwitz): need to check for overflow! */
581 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
582 if (indices == NULL) {
583 PyErr_NoMemory();
584 PyBuffer_Release(&view_dest);
585 PyBuffer_Release(&view_src);
586 return -1;
587 }
588 for (k=0; k<view_src.ndim;k++) {
589 indices[k] = 0;
590 }
591 elements = 1;
592 for (k=0; k<view_src.ndim; k++) {
593 /* XXX(nnorwitz): can this overflow? */
594 elements *= view_src.shape[k];
595 }
596 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000597 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 dptr = PyBuffer_GetPointer(&view_dest, indices);
599 sptr = PyBuffer_GetPointer(&view_src, indices);
600 memcpy(dptr, sptr, view_src.itemsize);
601 }
602 PyMem_Free(indices);
603 PyBuffer_Release(&view_dest);
604 PyBuffer_Release(&view_src);
605 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000606}
607
608void
609PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 Py_ssize_t *strides, int itemsize,
611 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 int k;
614 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 sd = itemsize;
617 if (fort == 'F') {
618 for (k=0; k<nd; k++) {
619 strides[k] = sd;
620 sd *= shape[k];
621 }
622 }
623 else {
624 for (k=nd-1; k>=0; k--) {
625 strides[k] = sd;
626 sd *= shape[k];
627 }
628 }
629 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000630}
631
632int
Martin v. Löwis423be952008-08-13 15:53:07 +0000633PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100634 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000635{
Stefan Krah5178d912015-02-03 16:57:21 +0100636 if (view == NULL) {
637 PyErr_SetString(PyExc_BufferError,
Victor Stinner61b64922020-06-23 15:55:06 +0200638 "PyBuffer_FillInfo: view==NULL argument is obsolete");
Stefan Krah5178d912015-02-03 16:57:21 +0100639 return -1;
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
643 (readonly == 1)) {
644 PyErr_SetString(PyExc_BufferError,
645 "Object is not writable.");
646 return -1;
647 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 view->obj = obj;
650 if (obj)
651 Py_INCREF(obj);
652 view->buf = buf;
653 view->len = len;
654 view->readonly = readonly;
655 view->itemsize = 1;
656 view->format = NULL;
657 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
658 view->format = "B";
659 view->ndim = 1;
660 view->shape = NULL;
661 if ((flags & PyBUF_ND) == PyBUF_ND)
662 view->shape = &(view->len);
663 view->strides = NULL;
664 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
665 view->strides = &(view->itemsize);
666 view->suboffsets = NULL;
667 view->internal = NULL;
668 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000669}
670
Martin v. Löwis423be952008-08-13 15:53:07 +0000671void
672PyBuffer_Release(Py_buffer *view)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200675 PyBufferProcs *pb;
676 if (obj == NULL)
677 return;
678 pb = Py_TYPE(obj)->tp_as_buffer;
679 if (pb && pb->bf_releasebuffer)
680 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200682 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000683}
684
Eric Smith8fd3eba2008-02-17 19:48:00 +0000685PyObject *
686PyObject_Format(PyObject *obj, PyObject *format_spec)
687{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000688 PyObject *meth;
689 PyObject *empty = NULL;
690 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500691 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000692
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300693 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
694 PyErr_Format(PyExc_SystemError,
695 "Format specifier must be a string, not %.200s",
696 Py_TYPE(format_spec)->tp_name);
697 return NULL;
698 }
699
700 /* Fast path for common types. */
701 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
702 if (PyUnicode_CheckExact(obj)) {
703 Py_INCREF(obj);
704 return obj;
705 }
706 if (PyLong_CheckExact(obj)) {
707 return PyObject_Str(obj);
708 }
709 }
710
Eric Smith8fd3eba2008-02-17 19:48:00 +0000711 /* If no format_spec is provided, use an empty string */
712 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100713 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000714 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000715 }
716
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300717 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500718 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000719 if (meth == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +0200720 PyThreadState *tstate = _PyThreadState_GET();
721 if (!_PyErr_Occurred(tstate)) {
722 _PyErr_Format(tstate, PyExc_TypeError,
723 "Type %.100s doesn't define __format__",
724 Py_TYPE(obj)->tp_name);
725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000727 }
728
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000729 /* And call it. */
Petr Viktorinffd97532020-02-11 17:46:57 +0100730 result = PyObject_CallOneArg(meth, format_spec);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000731 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000732
733 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800734 PyErr_Format(PyExc_TypeError,
Victor Stinner61b64922020-06-23 15:55:06 +0200735 "__format__ must return a str, not %.200s",
736 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000737 Py_DECREF(result);
738 result = NULL;
739 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000740 }
741
742done:
743 Py_XDECREF(empty);
744 return result;
745}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000746/* Operations on numbers */
747
748int
Fred Drake79912472000-07-09 04:06:11 +0000749PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000750{
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300751 if (o == NULL)
752 return 0;
753 PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
754 return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
Guido van Rossume15dee51995-07-18 14:12:02 +0000755}
756
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000757/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000758
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000759#define NB_SLOT(x) offsetof(PyNumberMethods, x)
760#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000762#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000764
765/*
766 Calling scheme used for binary operations:
767
Neal Norwitz4886cc32006-08-21 17:06:07 +0000768 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000770
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100771 [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
772 Py_TYPE(v)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000773 */
774
775static PyObject *
776binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *x;
779 binaryfunc slotv = NULL;
780 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000781
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100782 if (Py_TYPE(v)->tp_as_number != NULL)
783 slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600784 if (!Py_IS_TYPE(w, Py_TYPE(v)) &&
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100785 Py_TYPE(w)->tp_as_number != NULL) {
786 slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (slotw == slotv)
788 slotw = NULL;
789 }
790 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100791 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 x = slotw(v, w);
793 if (x != Py_NotImplemented)
794 return x;
795 Py_DECREF(x); /* can't do it */
796 slotw = NULL;
797 }
798 x = slotv(v, w);
799 if (x != Py_NotImplemented)
800 return x;
801 Py_DECREF(x); /* can't do it */
802 }
803 if (slotw) {
804 x = slotw(v, w);
805 if (x != Py_NotImplemented)
806 return x;
807 Py_DECREF(x); /* can't do it */
808 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500809 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000810}
Guido van Rossum77660912002-04-16 16:32:50 +0000811
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000812static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000813binop_type_error(PyObject *v, PyObject *w, const char *op_name)
814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyErr_Format(PyExc_TypeError,
816 "unsupported operand type(s) for %.100s: "
817 "'%.100s' and '%.100s'",
818 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100819 Py_TYPE(v)->tp_name,
820 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000822}
823
824static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000825binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *result = binary_op1(v, w, op_slot);
828 if (result == Py_NotImplemented) {
829 Py_DECREF(result);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530830
831 if (op_slot == NB_SLOT(nb_rshift) &&
scoder4c9ea092020-05-12 16:12:41 +0200832 PyCFunction_CheckExact(v) &&
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530833 strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
834 {
835 PyErr_Format(PyExc_TypeError,
836 "unsupported operand type(s) for %.100s: "
837 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
Sanyam Khuranaa7c449b2017-08-18 17:48:14 +0530838 "file=<output_stream>)\"?",
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530839 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100840 Py_TYPE(v)->tp_name,
841 Py_TYPE(w)->tp_name);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530842 return NULL;
843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return binop_type_error(v, w, op_name);
845 }
846 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000847}
848
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000849
850/*
851 Calling scheme used for ternary operations:
852
Neal Norwitz4886cc32006-08-21 17:06:07 +0000853 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000855 */
856
857static PyObject *
858ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *w,
860 PyObject *z,
861 const int op_slot,
862 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyNumberMethods *mv, *mw, *mz;
865 PyObject *x = NULL;
866 ternaryfunc slotv = NULL;
867 ternaryfunc slotw = NULL;
868 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000869
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100870 mv = Py_TYPE(v)->tp_as_number;
871 mw = Py_TYPE(w)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (mv != NULL)
873 slotv = NB_TERNOP(mv, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600874 if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 slotw = NB_TERNOP(mw, op_slot);
876 if (slotw == slotv)
877 slotw = NULL;
878 }
879 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100880 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 x = slotw(v, w, z);
882 if (x != Py_NotImplemented)
883 return x;
884 Py_DECREF(x); /* can't do it */
885 slotw = NULL;
886 }
887 x = slotv(v, w, z);
888 if (x != Py_NotImplemented)
889 return x;
890 Py_DECREF(x); /* can't do it */
891 }
892 if (slotw) {
893 x = slotw(v, w, z);
894 if (x != Py_NotImplemented)
895 return x;
896 Py_DECREF(x); /* can't do it */
897 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100898 mz = Py_TYPE(z)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (mz != NULL) {
900 slotz = NB_TERNOP(mz, op_slot);
901 if (slotz == slotv || slotz == slotw)
902 slotz = NULL;
903 if (slotz) {
904 x = slotz(v, w, z);
905 if (x != Py_NotImplemented)
906 return x;
907 Py_DECREF(x); /* can't do it */
908 }
909 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (z == Py_None)
912 PyErr_Format(
913 PyExc_TypeError,
914 "unsupported operand type(s) for ** or pow(): "
915 "'%.100s' and '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100916 Py_TYPE(v)->tp_name,
917 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 else
919 PyErr_Format(
920 PyExc_TypeError,
921 "unsupported operand type(s) for pow(): "
922 "'%.100s', '%.100s', '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100923 Py_TYPE(v)->tp_name,
924 Py_TYPE(w)->tp_name,
925 Py_TYPE(z)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +0000927}
928
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000929#define BINARY_FUNC(func, op, op_name) \
930 PyObject * \
931 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000933 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000934
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000935BINARY_FUNC(PyNumber_Or, nb_or, "|")
936BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
937BINARY_FUNC(PyNumber_And, nb_and, "&")
938BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
939BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
940BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000941BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +0000942
943PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000944PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
947 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100948 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 Py_DECREF(result);
950 if (m && m->sq_concat) {
951 return (*m->sq_concat)(v, w);
952 }
953 result = binop_type_error(v, w, "+");
954 }
955 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000956}
957
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000958static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000959sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 Py_ssize_t count;
Victor Stinnera15e2602020-04-08 02:01:56 +0200962 if (_PyIndex_Check(n)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
964 if (count == -1 && PyErr_Occurred())
965 return NULL;
966 }
967 else {
968 return type_error("can't multiply sequence by "
969 "non-int of type '%.200s'", n);
970 }
971 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000972}
973
974PyObject *
975PyNumber_Multiply(PyObject *v, PyObject *w)
976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
978 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100979 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
980 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 Py_DECREF(result);
982 if (mv && mv->sq_repeat) {
983 return sequence_repeat(mv->sq_repeat, v, w);
984 }
985 else if (mw && mw->sq_repeat) {
986 return sequence_repeat(mw->sq_repeat, w, v);
987 }
988 result = binop_type_error(v, w, "*");
989 }
990 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000991}
992
Guido van Rossume15dee51995-07-18 14:12:02 +0000993PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -0400994PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
995{
996 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
997}
998
999PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001000PyNumber_FloorDivide(PyObject *v, PyObject *w)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001003}
1004
1005PyObject *
1006PyNumber_TrueDivide(PyObject *v, PyObject *w)
1007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001009}
1010
1011PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001012PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001015}
1016
1017PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001018PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001021}
1022
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001023/* Binary in-place operators */
1024
1025/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001026 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001027
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001028 - If the left hand object has the appropriate struct members, and
1029 they are filled, call the appropriate function and return the
1030 result. No coercion is done on the arguments; the left-hand object
1031 is the one the operation is performed on, and it's up to the
1032 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001033
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001034 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001035 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001036
1037 */
1038
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001039static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001040binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001041{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001042 PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (mv != NULL) {
1044 binaryfunc slot = NB_BINOP(mv, iop_slot);
1045 if (slot) {
1046 PyObject *x = (slot)(v, w);
1047 if (x != Py_NotImplemented) {
1048 return x;
1049 }
1050 Py_DECREF(x);
1051 }
1052 }
1053 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001054}
1055
1056static PyObject *
1057binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1061 if (result == Py_NotImplemented) {
1062 Py_DECREF(result);
1063 return binop_type_error(v, w, op_name);
1064 }
1065 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001066}
1067
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001068#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject * \
1070 func(PyObject *v, PyObject *w) { \
1071 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1072 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001073
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001074INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1075INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1076INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1077INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1078INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1079INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001080INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001081
1082PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001083PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1086 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001087}
1088
1089PyObject *
1090PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1093 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001094}
1095
1096PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001097PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1100 NB_SLOT(nb_add));
1101 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001102 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 Py_DECREF(result);
1104 if (m != NULL) {
1105 binaryfunc f = NULL;
1106 f = m->sq_inplace_concat;
1107 if (f == NULL)
1108 f = m->sq_concat;
1109 if (f != NULL)
1110 return (*f)(v, w);
1111 }
1112 result = binop_type_error(v, w, "+=");
1113 }
1114 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001115}
1116
1117PyObject *
1118PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1121 NB_SLOT(nb_multiply));
1122 if (result == Py_NotImplemented) {
1123 ssizeargfunc f = NULL;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001124 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1125 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 Py_DECREF(result);
1127 if (mv != NULL) {
1128 f = mv->sq_inplace_repeat;
1129 if (f == NULL)
1130 f = mv->sq_repeat;
1131 if (f != NULL)
1132 return sequence_repeat(f, v, w);
1133 }
1134 else if (mw != NULL) {
1135 /* Note that the right hand operand should not be
1136 * mutated in this case so sq_inplace_repeat is not
1137 * used. */
1138 if (mw->sq_repeat)
1139 return sequence_repeat(mw->sq_repeat, w, v);
1140 }
1141 result = binop_type_error(v, w, "*=");
1142 }
1143 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001144}
1145
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001146PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001147PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1148{
1149 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1150 NB_SLOT(nb_matrix_multiply), "@=");
1151}
1152
1153PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001154PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1157 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001158}
1159
1160PyObject *
1161PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1162{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001163 if (Py_TYPE(v)->tp_as_number &&
1164 Py_TYPE(v)->tp_as_number->nb_inplace_power != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1166 }
1167 else {
1168 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1169 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001170}
1171
1172
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001173/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001174
1175PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001176PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001179
Victor Stinner71aea8e2016-08-19 16:59:55 +02001180 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001182 }
1183
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001184 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (m && m->nb_negative)
1186 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001189}
1190
1191PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001192PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001195
Victor Stinner71aea8e2016-08-19 16:59:55 +02001196 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001198 }
1199
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001200 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (m && m->nb_positive)
1202 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001205}
1206
1207PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001208PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001211
Victor Stinner71aea8e2016-08-19 16:59:55 +02001212 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001214 }
1215
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001216 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (m && m->nb_invert)
1218 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001221}
1222
1223PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001224PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001227
Victor Stinner71aea8e2016-08-19 16:59:55 +02001228 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001230 }
1231
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001232 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (m && m->nb_absolute)
1234 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001237}
1238
Victor Stinnera15e2602020-04-08 02:01:56 +02001239
Christian Tismerea62ce72018-06-09 20:32:25 +02001240int
1241PyIndex_Check(PyObject *obj)
1242{
Victor Stinnera15e2602020-04-08 02:01:56 +02001243 return _PyIndex_Check(obj);
Christian Tismerea62ce72018-06-09 20:32:25 +02001244}
1245
Victor Stinnera15e2602020-04-08 02:01:56 +02001246
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001247/* Return a Python int from the object item.
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001248 Can return an instance of int subclass.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001249 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001250 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001251*/
1252PyObject *
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001253_PyNumber_Index(PyObject *item)
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001256 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001258 }
1259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (PyLong_Check(item)) {
1261 Py_INCREF(item);
1262 return item;
1263 }
Victor Stinnera15e2602020-04-08 02:01:56 +02001264 if (!_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyErr_Format(PyExc_TypeError,
1266 "'%.200s' object cannot be interpreted "
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001267 "as an integer", Py_TYPE(item)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001268 return NULL;
1269 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001270 result = Py_TYPE(item)->tp_as_number->nb_index(item);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001271 if (!result || PyLong_CheckExact(result))
1272 return result;
1273 if (!PyLong_Check(result)) {
1274 PyErr_Format(PyExc_TypeError,
1275 "__index__ returned non-int (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001276 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001277 Py_DECREF(result);
1278 return NULL;
1279 }
1280 /* Issue #17576: warn if 'result' not of exact type int. */
1281 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1282 "__index__ returned non-int (type %.200s). "
1283 "The ability to return an instance of a strict subclass of int "
1284 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001285 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001286 Py_DECREF(result);
1287 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 }
1289 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001290}
1291
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001292/* Return an exact Python int from the object item.
1293 Raise TypeError if the result is not an int
1294 or if the object cannot be interpreted as an index.
1295*/
1296PyObject *
1297PyNumber_Index(PyObject *item)
1298{
1299 PyObject *result = _PyNumber_Index(item);
1300 if (result != NULL && !PyLong_CheckExact(result)) {
1301 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1302 }
1303 return result;
1304}
1305
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001306/* Return an error on Overflow only if err is not NULL*/
1307
1308Py_ssize_t
1309PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_ssize_t result;
1312 PyObject *runerr;
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001313 PyObject *value = _PyNumber_Index(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (value == NULL)
1315 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* We're done if PyLong_AsSsize_t() returns without error. */
1318 result = PyLong_AsSsize_t(value);
Victor Stinner61b64922020-06-23 15:55:06 +02001319 if (result != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001321
Victor Stinner61b64922020-06-23 15:55:06 +02001322 PyThreadState *tstate = _PyThreadState_GET();
1323 runerr = _PyErr_Occurred(tstate);
1324 if (!runerr) {
1325 goto finish;
1326 }
1327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* Error handling code -- only manage OverflowError differently */
Victor Stinner61b64922020-06-23 15:55:06 +02001329 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 goto finish;
Victor Stinner61b64922020-06-23 15:55:06 +02001331 }
1332 _PyErr_Clear(tstate);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /* If no error-handling desired then the default clipping
Victor Stinner61b64922020-06-23 15:55:06 +02001335 is sufficient. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (!err) {
1337 assert(PyLong_Check(value));
1338 /* Whether or not it is less than or equal to
1339 zero is determined by the sign of ob_size
1340 */
1341 if (_PyLong_Sign(value) < 0)
1342 result = PY_SSIZE_T_MIN;
1343 else
1344 result = PY_SSIZE_T_MAX;
1345 }
1346 else {
1347 /* Otherwise replace the error with caller's error object. */
Victor Stinner61b64922020-06-23 15:55:06 +02001348 _PyErr_Format(tstate, err,
1349 "cannot fit '%.200s' into an index-sized integer",
1350 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001352
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001353 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 Py_DECREF(value);
1355 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001356}
1357
1358
Guido van Rossume15dee51995-07-18 14:12:02 +00001359PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001360PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001361{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001362 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001365 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001366 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001367
Victor Stinner71aea8e2016-08-19 16:59:55 +02001368 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001370 }
1371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 if (PyLong_CheckExact(o)) {
1373 Py_INCREF(o);
1374 return o;
1375 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001376 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001378 /* Convert using the nb_int slot, which should return something
1379 of exact type int. */
1380 result = m->nb_int(o);
1381 if (!result || PyLong_CheckExact(result))
1382 return result;
1383 if (!PyLong_Check(result)) {
1384 PyErr_Format(PyExc_TypeError,
Victor Stinner61b64922020-06-23 15:55:06 +02001385 "__int__ returned non-int (type %.200s)",
Victor Stinner8182cc22020-07-10 12:40:38 +02001386 Py_TYPE(result)->tp_name);
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001387 Py_DECREF(result);
1388 return NULL;
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001389 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001390 /* Issue #17576: warn if 'result' not of exact type int. */
1391 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1392 "__int__ returned non-int (type %.200s). "
1393 "The ability to return an instance of a strict subclass of int "
1394 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner8182cc22020-07-10 12:40:38 +02001395 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001396 Py_DECREF(result);
1397 return NULL;
1398 }
1399 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001400 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001402 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001403 return PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001404 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001405 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001407 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001409 if (result == NULL || PyLong_CheckExact(result)) {
1410 return result;
1411 }
1412 if (PyLong_Check(result)) {
1413 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1414 return result;
1415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001417 but int() needs to return an int. */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001418 if (!PyIndex_Check(result)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001419 PyErr_Format(
1420 PyExc_TypeError,
1421 "__trunc__ returned non-Integral (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001422 Py_TYPE(result)->tp_name);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001423 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001424 return NULL;
1425 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001426 Py_SETREF(result, PyNumber_Index(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001427 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001429 if (PyErr_Occurred())
1430 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001431
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001432 if (PyUnicode_Check(o))
Inada Naokie4f1fe62020-06-29 13:00:43 +09001433 /* The below check is done in PyLong_FromUnicodeObject(). */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001434 return PyLong_FromUnicodeObject(o, 10);
1435
Martin Pantereeb896c2015-11-07 02:32:21 +00001436 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001438 * doesn't do. In particular int('9\x005') must raise an
1439 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001441 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1442 PyBytes_GET_SIZE(o), 10);
1443
1444 if (PyByteArray_Check(o))
1445 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1446 PyByteArray_GET_SIZE(o), 10);
1447
1448 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001449 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001450
1451 /* Copy to NUL-terminated buffer. */
1452 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1453 if (bytes == NULL) {
1454 PyBuffer_Release(&view);
1455 return NULL;
1456 }
1457 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1458 PyBytes_GET_SIZE(bytes), 10);
1459 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001460 PyBuffer_Release(&view);
1461 return result;
1462 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001463
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001464 return type_error("int() argument must be a string, a bytes-like object "
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001465 "or a real number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001466}
1467
1468PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001469PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001472
Victor Stinner71aea8e2016-08-19 16:59:55 +02001473 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001475 }
1476
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001477 if (PyFloat_CheckExact(o)) {
1478 Py_INCREF(o);
1479 return o;
1480 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001481 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (m && m->nb_float) { /* This should include subclasses of float */
1483 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001484 double val;
1485 if (!res || PyFloat_CheckExact(res)) {
1486 return res;
1487 }
1488 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001490 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001491 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_DECREF(res);
1493 return NULL;
1494 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001495 /* Issue #26983: warn if 'res' not of exact type float. */
1496 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1497 "%.50s.__float__ returned non-float (type %.50s). "
1498 "The ability to return an instance of a strict subclass of float "
1499 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001500 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001501 Py_DECREF(res);
1502 return NULL;
1503 }
1504 val = PyFloat_AS_DOUBLE(res);
1505 Py_DECREF(res);
1506 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001508 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001509 PyObject *res = _PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001510 if (!res) {
1511 return NULL;
1512 }
1513 double val = PyLong_AsDouble(res);
1514 Py_DECREF(res);
1515 if (val == -1.0 && PyErr_Occurred()) {
1516 return NULL;
1517 }
1518 return PyFloat_FromDouble(val);
1519 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001521 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 }
1523 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001524}
1525
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001526
1527PyObject *
1528PyNumber_ToBase(PyObject *n, int base)
1529{
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001530 if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1531 PyErr_SetString(PyExc_SystemError,
1532 "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1533 return NULL;
1534 }
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001535 PyObject *index = _PyNumber_Index(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (!index)
1537 return NULL;
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001538 PyObject *res = _PyLong_Format(index, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 Py_DECREF(index);
1540 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001541}
1542
1543
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001544/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001545
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001546int
Fred Drake79912472000-07-09 04:06:11 +00001547PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (PyDict_Check(s))
1550 return 0;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001551 return Py_TYPE(s)->tp_as_sequence &&
1552 Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001553}
1554
Martin v. Löwis18e16552006-02-15 17:27:45 +00001555Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001556PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (s == NULL) {
1561 null_error();
1562 return -1;
1563 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001564
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001565 m = Py_TYPE(s)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001566 if (m && m->sq_length) {
1567 Py_ssize_t len = m->sq_length(s);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01001568 assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001569 return len;
1570 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001571
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001572 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001573 type_error("%.200s is not a sequence", s);
1574 return -1;
1575 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 type_error("object of type '%.200s' has no len()", s);
1577 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001578}
1579
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001580#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001581Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001582PySequence_Length(PyObject *s)
1583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001585}
1586#define PySequence_Length PySequence_Size
1587
Guido van Rossume15dee51995-07-18 14:12:02 +00001588PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001589PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001592
Victor Stinner71aea8e2016-08-19 16:59:55 +02001593 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001595 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001596
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001597 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (m && m->sq_concat)
1599 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* Instances of user classes defining an __add__() method only
1602 have an nb_add slot, not an sq_concat slot. So we fall back
1603 to nb_add if both arguments appear to be sequences. */
1604 if (PySequence_Check(s) && PySequence_Check(o)) {
1605 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1606 if (result != Py_NotImplemented)
1607 return result;
1608 Py_DECREF(result);
1609 }
1610 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001611}
1612
1613PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001614PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001617
Victor Stinner71aea8e2016-08-19 16:59:55 +02001618 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001620 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001621
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001622 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (m && m->sq_repeat)
1624 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* Instances of user classes defining a __mul__() method only
1627 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1628 to nb_multiply if o appears to be a sequence. */
1629 if (PySequence_Check(o)) {
1630 PyObject *n, *result;
1631 n = PyLong_FromSsize_t(count);
1632 if (n == NULL)
1633 return NULL;
1634 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1635 Py_DECREF(n);
1636 if (result != Py_NotImplemented)
1637 return result;
1638 Py_DECREF(result);
1639 }
1640 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001641}
1642
1643PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001644PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001647
Victor Stinner71aea8e2016-08-19 16:59:55 +02001648 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001650 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001651
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001652 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (m && m->sq_inplace_concat)
1654 return m->sq_inplace_concat(s, o);
1655 if (m && m->sq_concat)
1656 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (PySequence_Check(s) && PySequence_Check(o)) {
1659 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1660 NB_SLOT(nb_add));
1661 if (result != Py_NotImplemented)
1662 return result;
1663 Py_DECREF(result);
1664 }
1665 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001666}
1667
1668PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001669PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001672
Victor Stinner71aea8e2016-08-19 16:59:55 +02001673 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001675 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001676
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001677 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (m && m->sq_inplace_repeat)
1679 return m->sq_inplace_repeat(o, count);
1680 if (m && m->sq_repeat)
1681 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 if (PySequence_Check(o)) {
1684 PyObject *n, *result;
1685 n = PyLong_FromSsize_t(count);
1686 if (n == NULL)
1687 return NULL;
1688 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1689 NB_SLOT(nb_multiply));
1690 Py_DECREF(n);
1691 if (result != Py_NotImplemented)
1692 return result;
1693 Py_DECREF(result);
1694 }
1695 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001696}
1697
1698PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001699PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001702
Victor Stinner71aea8e2016-08-19 16:59:55 +02001703 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001705 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001706
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001707 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (m && m->sq_item) {
1709 if (i < 0) {
1710 if (m->sq_length) {
1711 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01001712 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
Victor Stinnere20310f2015-11-05 13:56:58 +01001713 if (l < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001715 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 i += l;
1717 }
1718 }
1719 return m->sq_item(s, i);
1720 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001721
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001722 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001723 return type_error("%.200s is not a sequence", s);
1724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001726}
1727
1728PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001729PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001732
Victor Stinner71aea8e2016-08-19 16:59:55 +02001733 if (!s) {
1734 return null_error();
1735 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001736
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001737 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001738 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyObject *res;
1740 PyObject *slice = _PySlice_FromIndices(i1, i2);
1741 if (!slice)
1742 return NULL;
1743 res = mp->mp_subscript(s, slice);
1744 Py_DECREF(slice);
1745 return res;
1746 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001749}
1750
1751int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001752PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (s == NULL) {
1757 null_error();
1758 return -1;
1759 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001760
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001761 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (m && m->sq_ass_item) {
1763 if (i < 0) {
1764 if (m->sq_length) {
1765 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01001766 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001767 if (l < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001769 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 i += l;
1771 }
1772 }
1773 return m->sq_ass_item(s, i, o);
1774 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001775
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001776 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001777 type_error("%.200s is not a sequence", s);
1778 return -1;
1779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 type_error("'%.200s' object does not support item assignment", s);
1781 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001782}
1783
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001784int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001785PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (s == NULL) {
1790 null_error();
1791 return -1;
1792 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001793
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001794 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (m && m->sq_ass_item) {
1796 if (i < 0) {
1797 if (m->sq_length) {
1798 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01001799 assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001800 if (l < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 i += l;
1804 }
1805 }
1806 return m->sq_ass_item(s, i, (PyObject *)NULL);
1807 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001808
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001809 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001810 type_error("%.200s is not a sequence", s);
1811 return -1;
1812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 type_error("'%.200s' object doesn't support item deletion", s);
1814 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001815}
1816
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001817int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001818PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (s == NULL) {
1823 null_error();
1824 return -1;
1825 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001826
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001827 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001828 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 int res;
1830 PyObject *slice = _PySlice_FromIndices(i1, i2);
1831 if (!slice)
1832 return -1;
1833 res = mp->mp_ass_subscript(s, slice, o);
1834 Py_DECREF(slice);
1835 return res;
1836 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 type_error("'%.200s' object doesn't support slice assignment", s);
1839 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001840}
1841
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001842int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001843PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (s == NULL) {
1848 null_error();
1849 return -1;
1850 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001851
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001852 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001853 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 int res;
1855 PyObject *slice = _PySlice_FromIndices(i1, i2);
1856 if (!slice)
1857 return -1;
1858 res = mp->mp_ass_subscript(s, slice, NULL);
1859 Py_DECREF(slice);
1860 return res;
1861 }
1862 type_error("'%.200s' object doesn't support slice deletion", s);
1863 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001864}
1865
Guido van Rossume15dee51995-07-18 14:12:02 +00001866PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001867PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 PyObject *it; /* iter(v) */
1870 Py_ssize_t n; /* guess for result tuple size */
1871 PyObject *result = NULL;
1872 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001873
Victor Stinner71aea8e2016-08-19 16:59:55 +02001874 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001876 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 /* Special-case the common tuple and list cases, for efficiency. */
1879 if (PyTuple_CheckExact(v)) {
1880 /* Note that we can't know whether it's safe to return
1881 a tuple *subclass* instance as-is, hence the restriction
1882 to exact tuples here. In contrast, lists always make
1883 a copy, so there's no need for exactness below. */
1884 Py_INCREF(v);
1885 return v;
1886 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001887 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* Get iterator. */
1891 it = PyObject_GetIter(v);
1892 if (it == NULL)
1893 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001896 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (n == -1)
1898 goto Fail;
1899 result = PyTuple_New(n);
1900 if (result == NULL)
1901 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* Fill the tuple. */
1904 for (j = 0; ; ++j) {
1905 PyObject *item = PyIter_Next(it);
1906 if (item == NULL) {
1907 if (PyErr_Occurred())
1908 goto Fail;
1909 break;
1910 }
1911 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001912 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* The over-allocation strategy can grow a bit faster
1914 than for lists because unlike lists the
1915 over-allocation isn't permanent -- we reclaim
1916 the excess before the end of this routine.
1917 So, grow by ten and then add 25%.
1918 */
Martin Pantere8db8612016-07-25 02:30:05 +00001919 newn += 10u;
1920 newn += newn >> 2;
1921 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* Check for overflow */
1923 PyErr_NoMemory();
1924 Py_DECREF(item);
1925 goto Fail;
1926 }
Martin Pantere8db8612016-07-25 02:30:05 +00001927 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (_PyTuple_Resize(&result, n) != 0) {
1929 Py_DECREF(item);
1930 goto Fail;
1931 }
1932 }
1933 PyTuple_SET_ITEM(result, j, item);
1934 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Cut tuple back if guess was too large. */
1937 if (j < n &&
1938 _PyTuple_Resize(&result, j) != 0)
1939 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 Py_DECREF(it);
1942 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00001943
1944Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 Py_XDECREF(result);
1946 Py_DECREF(it);
1947 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001948}
1949
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001950PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001951PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyObject *result; /* result list */
1954 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00001955
Victor Stinner71aea8e2016-08-19 16:59:55 +02001956 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001958 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 result = PyList_New(0);
1961 if (result == NULL)
1962 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 rv = _PyList_Extend((PyListObject *)result, v);
1965 if (rv == NULL) {
1966 Py_DECREF(result);
1967 return NULL;
1968 }
1969 Py_DECREF(rv);
1970 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00001971}
1972
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001973PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001974PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00001977
Victor Stinner71aea8e2016-08-19 16:59:55 +02001978 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001980 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
1983 Py_INCREF(v);
1984 return v;
1985 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 it = PyObject_GetIter(v);
1988 if (it == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +02001989 PyThreadState *tstate = _PyThreadState_GET();
1990 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1991 _PyErr_SetString(tstate, PyExc_TypeError, m);
1992 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 return NULL;
1994 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 v = PySequence_List(it);
1997 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002000}
2001
Tim Peters16a77ad2001-09-08 04:00:12 +00002002/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2004 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2005 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002006 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2007*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002008Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002009_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 Py_ssize_t n;
2012 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2013 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (seq == NULL || obj == NULL) {
2016 null_error();
2017 return -1;
2018 }
Tim Peters75f8e352001-05-05 11:33:43 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 it = PyObject_GetIter(seq);
2021 if (it == NULL) {
Serhiy Storchakacafe1b62020-06-22 10:43:35 +03002022 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2023 type_error("argument of type '%.200s' is not iterable", seq);
2024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 return -1;
2026 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 n = wrapped = 0;
2029 for (;;) {
2030 int cmp;
2031 PyObject *item = PyIter_Next(it);
2032 if (item == NULL) {
2033 if (PyErr_Occurred())
2034 goto Fail;
2035 break;
2036 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002037
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002038 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 Py_DECREF(item);
2040 if (cmp < 0)
2041 goto Fail;
2042 if (cmp > 0) {
2043 switch (operation) {
2044 case PY_ITERSEARCH_COUNT:
2045 if (n == PY_SSIZE_T_MAX) {
2046 PyErr_SetString(PyExc_OverflowError,
2047 "count exceeds C integer size");
2048 goto Fail;
2049 }
2050 ++n;
2051 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 case PY_ITERSEARCH_INDEX:
2054 if (wrapped) {
2055 PyErr_SetString(PyExc_OverflowError,
2056 "index exceeds C integer size");
2057 goto Fail;
2058 }
2059 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 case PY_ITERSEARCH_CONTAINS:
2062 n = 1;
2063 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002066 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
2068 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (operation == PY_ITERSEARCH_INDEX) {
2071 if (n == PY_SSIZE_T_MAX)
2072 wrapped = 1;
2073 ++n;
2074 }
2075 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (operation != PY_ITERSEARCH_INDEX)
2078 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyErr_SetString(PyExc_ValueError,
2081 "sequence.index(x): x not in sequence");
2082 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002083Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 n = -1;
2085 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002086Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 Py_DECREF(it);
2088 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002089
Guido van Rossume15dee51995-07-18 14:12:02 +00002090}
2091
Tim Peters16a77ad2001-09-08 04:00:12 +00002092/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002093Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002094PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002097}
2098
Tim Peterscb8d3682001-05-05 21:05:01 +00002099/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002100 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002101 */
2102int
2103PySequence_Contains(PyObject *seq, PyObject *ob)
2104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 Py_ssize_t result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002106 PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (sqm != NULL && sqm->sq_contains != NULL)
2108 return (*sqm->sq_contains)(seq, ob);
2109 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2110 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002111}
2112
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002113/* Backwards compatibility */
2114#undef PySequence_In
2115int
Fred Drake79912472000-07-09 04:06:11 +00002116PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002119}
2120
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002121Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002122PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002125}
2126
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002127/* Operations on mappings */
2128
2129int
Fred Drake79912472000-07-09 04:06:11 +00002130PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002131{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002132 return o && Py_TYPE(o)->tp_as_mapping &&
2133 Py_TYPE(o)->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002134}
2135
Martin v. Löwis18e16552006-02-15 17:27:45 +00002136Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002137PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (o == NULL) {
2142 null_error();
2143 return -1;
2144 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002145
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002146 m = Py_TYPE(o)->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002147 if (m && m->mp_length) {
2148 Py_ssize_t len = m->mp_length(o);
Victor Stinnerc9b8e9c2021-01-27 17:39:16 +01002149 assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002150 return len;
2151 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002152
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002153 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002154 type_error("%.200s is not a mapping", o);
2155 return -1;
2156 }
2157 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 type_error("object of type '%.200s' has no len()", o);
2159 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002160}
2161
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002162#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002163Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002164PyMapping_Length(PyObject *o)
2165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002167}
2168#define PyMapping_Length PyMapping_Size
2169
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002170PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002171PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002174
Victor Stinner71aea8e2016-08-19 16:59:55 +02002175 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002177 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 okey = PyUnicode_FromString(key);
2180 if (okey == NULL)
2181 return NULL;
2182 r = PyObject_GetItem(o, okey);
2183 Py_DECREF(okey);
2184 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002185}
2186
2187int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002188PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyObject *okey;
2191 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (key == NULL) {
2194 null_error();
2195 return -1;
2196 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 okey = PyUnicode_FromString(key);
2199 if (okey == NULL)
2200 return -1;
2201 r = PyObject_SetItem(o, okey, value);
2202 Py_DECREF(okey);
2203 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002204}
2205
2206int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002207PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 v = PyMapping_GetItemString(o, key);
2212 if (v) {
2213 Py_DECREF(v);
2214 return 1;
2215 }
2216 PyErr_Clear();
2217 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002218}
2219
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002220int
Fred Drake79912472000-07-09 04:06:11 +00002221PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 v = PyObject_GetItem(o, key);
2226 if (v) {
2227 Py_DECREF(v);
2228 return 1;
2229 }
2230 PyErr_Clear();
2231 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002232}
2233
Oren Milman0ccc0f62017-10-08 11:17:46 +03002234/* This function is quite similar to PySequence_Fast(), but specialized to be
2235 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2236 */
2237static PyObject *
2238method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2239{
2240 PyObject *it, *result, *meth_output;
2241
2242 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002243 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002244 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2245 return meth_output;
2246 }
2247 it = PyObject_GetIter(meth_output);
2248 if (it == NULL) {
Victor Stinner61b64922020-06-23 15:55:06 +02002249 PyThreadState *tstate = _PyThreadState_GET();
2250 if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2251 _PyErr_Format(tstate, PyExc_TypeError,
2252 "%.200s.%U() returned a non-iterable (type %.200s)",
2253 Py_TYPE(o)->tp_name,
2254 _PyUnicode_FromId(meth_id),
2255 Py_TYPE(meth_output)->tp_name);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002256 }
2257 Py_DECREF(meth_output);
2258 return NULL;
2259 }
2260 Py_DECREF(meth_output);
2261 result = PySequence_List(it);
2262 Py_DECREF(it);
2263 return result;
2264}
2265
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002266PyObject *
2267PyMapping_Keys(PyObject *o)
2268{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002269 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002270
Oren Milman0ccc0f62017-10-08 11:17:46 +03002271 if (o == NULL) {
2272 return null_error();
2273 }
2274 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002276 }
2277 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002278}
2279
2280PyObject *
2281PyMapping_Items(PyObject *o)
2282{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002283 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002284
Oren Milman0ccc0f62017-10-08 11:17:46 +03002285 if (o == NULL) {
2286 return null_error();
2287 }
2288 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002290 }
2291 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002292}
2293
2294PyObject *
2295PyMapping_Values(PyObject *o)
2296{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002297 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002298
Oren Milman0ccc0f62017-10-08 11:17:46 +03002299 if (o == NULL) {
2300 return null_error();
2301 }
2302 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002304 }
2305 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002306}
2307
Guido van Rossum823649d2001-03-21 18:40:58 +00002308/* isinstance(), issubclass() */
2309
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002310/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002311 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002312 * 1. getattr(cls, '__bases__') could raise an AttributeError
2313 * 2. getattr(cls, '__bases__') could raise some other exception
2314 * 3. getattr(cls, '__bases__') could return a tuple
2315 * 4. getattr(cls, '__bases__') could return something other than a tuple
2316 *
2317 * Only state #3 is a non-error state and only it returns a non-NULL object
2318 * (it returns the retrieved tuple).
2319 *
2320 * Any raised AttributeErrors are masked by clearing the exception and
2321 * returning NULL. If an object other than a tuple comes out of __bases__,
2322 * then again, the return value is NULL. So yes, these two situations
2323 * produce exactly the same results: NULL is returned and no error is set.
2324 *
2325 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002327 * exception to be propagated along.
2328 *
2329 * Callers are expected to test for PyErr_Occurred() when the return value
2330 * is NULL to decide whether a valid exception should be propagated or not.
2331 * When there's no exception to propagate, it's customary for the caller to
2332 * set a TypeError.
2333 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002334static PyObject *
2335abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002336{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002337 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002339
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002340 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002341 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 Py_DECREF(bases);
2343 return NULL;
2344 }
2345 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002346}
2347
2348
2349static int
2350abstract_issubclass(PyObject *derived, PyObject *cls)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 PyObject *bases = NULL;
2353 Py_ssize_t i, n;
2354 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 while (1) {
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002357 if (derived == cls) {
2358 Py_XDECREF(bases); /* See below comment */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return 1;
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002360 }
2361 /* Use XSETREF to drop bases reference *after* finishing with
2362 derived; bases might be the only reference to it.
2363 XSETREF is used instead of SETREF, because bases is NULL on the
2364 first iteration of the loop.
2365 */
2366 Py_XSETREF(bases, abstract_get_bases(derived));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 if (bases == NULL) {
2368 if (PyErr_Occurred())
2369 return -1;
2370 return 0;
2371 }
2372 n = PyTuple_GET_SIZE(bases);
2373 if (n == 0) {
2374 Py_DECREF(bases);
2375 return 0;
2376 }
2377 /* Avoid recursivity in the single inheritance case */
2378 if (n == 1) {
2379 derived = PyTuple_GET_ITEM(bases, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 continue;
2381 }
2382 for (i = 0; i < n; i++) {
2383 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2384 if (r != 0)
2385 break;
2386 }
2387 Py_DECREF(bases);
2388 return r;
2389 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002390}
2391
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002392static int
2393check_class(PyObject *cls, const char *error)
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 PyObject *bases = abstract_get_bases(cls);
2396 if (bases == NULL) {
2397 /* Do not mask errors. */
Victor Stinner61b64922020-06-23 15:55:06 +02002398 PyThreadState *tstate = _PyThreadState_GET();
2399 if (!_PyErr_Occurred(tstate)) {
2400 _PyErr_SetString(tstate, PyExc_TypeError, error);
2401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return 0;
2403 }
2404 Py_DECREF(bases);
2405 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002406}
2407
Brett Cannon4f653312004-03-20 22:52:14 +00002408static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002409object_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002412 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002413 _Py_IDENTIFIER(__class__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 if (PyType_Check(cls)) {
2415 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2416 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002417 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2418 if (icls != NULL) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002419 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002421 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002423 }
2424 else {
2425 retval = 0;
2426 }
2427 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 }
2429 }
2430 }
2431 else {
2432 if (!check_class(cls,
Maggie Moss1b4552c2020-09-09 13:23:24 -07002433 "isinstance() arg 2 must be a type, a tuple of types or a union"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002435 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2436 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 retval = abstract_issubclass(icls, cls);
2438 Py_DECREF(icls);
2439 }
2440 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002443}
2444
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002445static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002446object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002447{
Benjamin Petersonce798522012-01-22 11:24:29 -05002448 _Py_IDENTIFIER(__instancecheck__);
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Quick test for an exact match */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002451 if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 return 1;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002453 }
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002454
Georg Brandl72b8a802014-10-03 09:26:37 +02002455 /* We know what type's __instancecheck__ does. */
2456 if (PyType_CheckExact(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002457 return object_isinstance(inst, cls);
Georg Brandl72b8a802014-10-03 09:26:37 +02002458 }
2459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (PyTuple_Check(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002461 /* Not a general sequence -- that opens up the road to
2462 recursion and stack overflow. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002463 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002465 }
2466 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2467 int r = 0;
2468 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002470 r = object_recursive_isinstance(tstate, inst, item);
2471 if (r != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* either found it, or got an error */
2473 break;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002476 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 return r;
2478 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002479
Victor Stinner850a4bd2020-02-04 13:42:13 +01002480 PyObject *checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (checker != NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002482 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002484 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002486
Petr Viktorinffd97532020-02-11 17:46:57 +01002487 PyObject *res = PyObject_CallOneArg(checker, inst);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002488 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002490
2491 if (res == NULL) {
2492 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002494 int ok = PyObject_IsTrue(res);
2495 Py_DECREF(res);
2496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 return ok;
2498 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002499 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002501 }
2502
Victor Stinner850a4bd2020-02-04 13:42:13 +01002503 /* cls has no __instancecheck__() method */
2504 return object_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002505}
2506
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002507
2508int
2509PyObject_IsInstance(PyObject *inst, PyObject *cls)
2510{
2511 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner850a4bd2020-02-04 13:42:13 +01002512 return object_recursive_isinstance(tstate, inst, cls);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002513}
2514
2515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002517recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (PyType_Check(cls) && PyType_Check(derived)) {
2520 /* Fast path (non-recursive) */
2521 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2522 }
2523 if (!check_class(derived,
2524 "issubclass() arg 1 must be a class"))
2525 return -1;
Maggie Moss1b4552c2020-09-09 13:23:24 -07002526
2527 PyTypeObject *type = Py_TYPE(cls);
2528 int is_union = (PyType_Check(type) && type == &_Py_UnionType);
2529 if (!is_union && !check_class(cls,
2530 "issubclass() arg 2 must be a class,"
2531 " a tuple of classes, or a union.")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 return -1;
Maggie Moss1b4552c2020-09-09 13:23:24 -07002533 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002536}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002537
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002538static int
2539object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002540{
Benjamin Petersonce798522012-01-22 11:24:29 -05002541 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002543
Georg Brandl72b8a802014-10-03 09:26:37 +02002544 /* We know what type's __subclasscheck__ does. */
2545 if (PyType_CheckExact(cls)) {
2546 /* Quick test for an exact match */
2547 if (derived == cls)
2548 return 1;
2549 return recursive_issubclass(derived, cls);
2550 }
2551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 if (PyTuple_Check(cls)) {
Antoine Pitrouec569b72008-08-26 22:40:48 +00002553
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002554 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002556 }
2557 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2558 int r = 0;
2559 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002561 r = object_issubclass(tstate, derived, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (r != 0)
2563 /* either found it, or got an error */
2564 break;
2565 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002566 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 return r;
2568 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002569
Benjamin Petersonce798522012-01-22 11:24:29 -05002570 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (checker != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 int ok = -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002573 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_DECREF(checker);
2575 return ok;
2576 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002577 PyObject *res = PyObject_CallOneArg(checker, derived);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002578 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 Py_DECREF(checker);
2580 if (res != NULL) {
2581 ok = PyObject_IsTrue(res);
2582 Py_DECREF(res);
2583 }
2584 return ok;
2585 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002586 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002588 }
2589
Georg Brandl72b8a802014-10-03 09:26:37 +02002590 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002592}
2593
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002594
2595int
2596PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2597{
2598 PyThreadState *tstate = _PyThreadState_GET();
2599 return object_issubclass(tstate, derived, cls);
2600}
2601
2602
Antoine Pitrouec569b72008-08-26 22:40:48 +00002603int
2604_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2605{
Victor Stinner850a4bd2020-02-04 13:42:13 +01002606 return object_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002607}
2608
2609int
2610_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002613}
2614
2615
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002616PyObject *
2617PyObject_GetIter(PyObject *o)
2618{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002619 PyTypeObject *t = Py_TYPE(o);
Victor Stinner14e6d092016-12-09 17:08:59 +01002620 getiterfunc f;
2621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 f = t->tp_iter;
2623 if (f == NULL) {
2624 if (PySequence_Check(o))
2625 return PySeqIter_New(o);
2626 return type_error("'%.200s' object is not iterable", o);
2627 }
2628 else {
2629 PyObject *res = (*f)(o);
2630 if (res != NULL && !PyIter_Check(res)) {
2631 PyErr_Format(PyExc_TypeError,
2632 "iter() returned non-iterator "
2633 "of type '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002634 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 Py_DECREF(res);
2636 res = NULL;
2637 }
2638 return res;
2639 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002640}
2641
Christian Tismerea62ce72018-06-09 20:32:25 +02002642#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002643
Christian Tismerea62ce72018-06-09 20:32:25 +02002644int PyIter_Check(PyObject *obj)
2645{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002646 return Py_TYPE(obj)->tp_iternext != NULL &&
2647 Py_TYPE(obj)->tp_iternext != &_PyObject_NextNotImplemented;
Christian Tismerea62ce72018-06-09 20:32:25 +02002648}
2649
Tim Petersf4848da2001-05-05 00:14:56 +00002650/* Return next item.
2651 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2652 * If the iteration terminates normally, return NULL and clear the
2653 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2654 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002656 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002657PyObject *
2658PyIter_Next(PyObject *iter)
2659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 PyObject *result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002661 result = (*Py_TYPE(iter)->tp_iternext)(iter);
Victor Stinner61b64922020-06-23 15:55:06 +02002662 if (result == NULL) {
2663 PyThreadState *tstate = _PyThreadState_GET();
2664 if (_PyErr_Occurred(tstate)
2665 && _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2666 {
2667 _PyErr_Clear(tstate);
2668 }
2669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002671}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002672
Vladimir Matveev1e996c32020-11-10 12:09:55 -08002673PySendResult
2674PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
2675{
2676 _Py_IDENTIFIER(send);
2677 assert(arg != NULL);
2678 assert(result != NULL);
2679 if (PyType_HasFeature(Py_TYPE(iter), Py_TPFLAGS_HAVE_AM_SEND)) {
2680 assert (Py_TYPE(iter)->tp_as_async != NULL);
2681 assert (Py_TYPE(iter)->tp_as_async->am_send != NULL);
2682 return Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
2683 }
2684 if (arg == Py_None && PyIter_Check(iter)) {
2685 *result = Py_TYPE(iter)->tp_iternext(iter);
2686 }
2687 else {
2688 *result = _PyObject_CallMethodIdOneArg(iter, &PyId_send, arg);
2689 }
2690 if (*result != NULL) {
2691 return PYGEN_NEXT;
2692 }
2693 if (_PyGen_FetchStopIterationValue(result) == 0) {
2694 return PYGEN_RETURN;
2695 }
2696 return PYGEN_ERROR;
2697}
2698
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002699/*
2700 * Flatten a sequence of bytes() objects into a C array of
2701 * NULL terminated string pointers with a NULL char* terminating the array.
2702 * (ie: an argv or env list)
2703 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002704 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2705 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002706 */
2707char *const *
2708_PySequence_BytesToCharpArray(PyObject* self)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 char **array;
2711 Py_ssize_t i, argc;
2712 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002713 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 argc = PySequence_Size(self);
2716 if (argc == -1)
2717 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002718
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002719 assert(argc >= 0);
2720
2721 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2722 PyErr_NoMemory();
2723 return NULL;
2724 }
2725
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002726 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (array == NULL) {
2728 PyErr_NoMemory();
2729 return NULL;
2730 }
2731 for (i = 0; i < argc; ++i) {
2732 char *data;
2733 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002734 if (item == NULL) {
2735 /* NULL terminate before freeing. */
2736 array[i] = NULL;
2737 goto fail;
2738 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002739 /* check for embedded null bytes */
2740 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 /* NULL terminate before freeing. */
2742 array[i] = NULL;
2743 goto fail;
2744 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002745 size = PyBytes_GET_SIZE(item) + 1;
2746 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 if (!array[i]) {
2748 PyErr_NoMemory();
2749 goto fail;
2750 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002751 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 Py_DECREF(item);
2753 }
2754 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002757
2758fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 Py_XDECREF(item);
2760 _Py_FreeCharPArray(array);
2761 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002762}
2763
2764
2765/* Free's a NULL terminated char** array of C strings. */
2766void
2767_Py_FreeCharPArray(char *const array[])
2768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 Py_ssize_t i;
2770 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002771 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002773 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002774}