1 #ifndef Py_CPYTHON_ABSTRACTOBJECT_H
2 # error "this header file must not be included directly"
3 #endif
4
5 #ifdef __cplusplus
6 extern "C" {
7 #endif
8
9 /* === Object Protocol ================================================== */
10
11 #ifdef PY_SSIZE_T_CLEAN
12 # define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT
13 #endif
14
15 /* Convert keyword arguments from the FASTCALL (stack: C array, kwnames: tuple)
16 format to a Python dictionary ("kwargs" dict).
17
18 The type of kwnames keys is not checked. The final function getting
19 arguments is responsible to check if all keys are strings, for example using
20 PyArg_ParseTupleAndKeywords() or PyArg_ValidateKeywordArguments().
21
22 Duplicate keys are merged using the last value. If duplicate keys must raise
23 an exception, the caller is responsible to implement an explicit keys on
24 kwnames. */
25 PyAPI_FUNC(PyObject *) _PyStack_AsDict(
26 PyObject *const *values,
27 PyObject *kwnames);
28
29 /* Convert (args, nargs, kwargs: dict) into a (stack, nargs, kwnames: tuple).
30
31 Return 0 on success, raise an exception and return -1 on error.
32
33 Write the new stack into *p_stack. If *p_stack is differen than args, it
34 must be released by PyMem_Free().
35
36 The stack uses borrowed references.
37
38 The type of keyword keys is not checked, these checks should be done
39 later (ex: _PyArg_ParseStackAndKeywords). */
40 PyAPI_FUNC(int) _PyStack_UnpackDict(
41 PyObject *const *args,
42 Py_ssize_t nargs,
43 PyObject *kwargs,
44 PyObject *const **p_stack,
45 PyObject **p_kwnames);
46
47 /* Suggested size (number of positional arguments) for arrays of PyObject*
48 allocated on a C stack to avoid allocating memory on the heap memory. Such
49 array is used to pass positional arguments to call functions of the
50 _PyObject_Vectorcall() family.
51
52 The size is chosen to not abuse the C stack and so limit the risk of stack
53 overflow. The size is also chosen to allow using the small stack for most
54 function calls of the Python standard library. On 64-bit CPU, it allocates
55 40 bytes on the stack. */
56 #define _PY_FASTCALL_SMALL_STACK 5
57
58 PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(PyObject *callable,
59 PyObject *result,
60 const char *where);
61
62 /* === Vectorcall protocol (PEP 590) ============================= */
63
64 /* Call callable using tp_call. Arguments are like _PyObject_Vectorcall()
65 or _PyObject_FastCallDict() (both forms are supported),
66 except that nargs is plainly the number of arguments without flags. */
67 PyAPI_FUNC(PyObject *) _PyObject_MakeTpCall(
68 PyObject *callable,
69 PyObject *const *args, Py_ssize_t nargs,
70 PyObject *keywords);
71
72 #define PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1))
73
74 static inline Py_ssize_t
PyVectorcall_NARGS(size_t n)75 PyVectorcall_NARGS(size_t n)
76 {
77 return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;
78 }
79
80 static inline vectorcallfunc
_PyVectorcall_Function(PyObject * callable)81 _PyVectorcall_Function(PyObject *callable)
82 {
83 PyTypeObject *tp = Py_TYPE(callable);
84 Py_ssize_t offset = tp->tp_vectorcall_offset;
85 vectorcallfunc *ptr;
86 if (!PyType_HasFeature(tp, _Py_TPFLAGS_HAVE_VECTORCALL)) {
87 return NULL;
88 }
89 assert(PyCallable_Check(callable));
90 assert(offset > 0);
91 ptr = (vectorcallfunc*)(((char *)callable) + offset);
92 return *ptr;
93 }
94
95 /* Call the callable object 'callable' with the "vectorcall" calling
96 convention.
97
98 args is a C array for positional arguments.
99
100 nargsf is the number of positional arguments plus optionally the flag
101 PY_VECTORCALL_ARGUMENTS_OFFSET which means that the caller is allowed to
102 modify args[-1].
103
104 kwnames is a tuple of keyword names. The values of the keyword arguments
105 are stored in "args" after the positional arguments (note that the number
106 of keyword arguments does not change nargsf). kwnames can also be NULL if
107 there are no keyword arguments.
108
109 keywords must only contains str strings (no subclass), and all keys must
110 be unique.
111
112 Return the result on success. Raise an exception and return NULL on
113 error. */
114 static inline PyObject *
_PyObject_Vectorcall(PyObject * callable,PyObject * const * args,size_t nargsf,PyObject * kwnames)115 _PyObject_Vectorcall(PyObject *callable, PyObject *const *args,
116 size_t nargsf, PyObject *kwnames)
117 {
118 PyObject *res;
119 vectorcallfunc func;
120 assert(kwnames == NULL || PyTuple_Check(kwnames));
121 assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);
122 func = _PyVectorcall_Function(callable);
123 if (func == NULL) {
124 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
125 return _PyObject_MakeTpCall(callable, args, nargs, kwnames);
126 }
127 res = func(callable, args, nargsf, kwnames);
128 return _Py_CheckFunctionResult(callable, res, NULL);
129 }
130
131 /* Same as _PyObject_Vectorcall except that keyword arguments are passed as
132 dict, which may be NULL if there are no keyword arguments. */
133 PyAPI_FUNC(PyObject *) _PyObject_FastCallDict(
134 PyObject *callable,
135 PyObject *const *args,
136 size_t nargsf,
137 PyObject *kwargs);
138
139 /* Call "callable" (which must support vectorcall) with positional arguments
140 "tuple" and keyword arguments "dict". "dict" may also be NULL */
141 PyAPI_FUNC(PyObject *) PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict);
142
143 /* Same as _PyObject_Vectorcall except without keyword arguments */
144 static inline PyObject *
_PyObject_FastCall(PyObject * func,PyObject * const * args,Py_ssize_t nargs)145 _PyObject_FastCall(PyObject *func, PyObject *const *args, Py_ssize_t nargs)
146 {
147 return _PyObject_Vectorcall(func, args, (size_t)nargs, NULL);
148 }
149
150 /* Call a callable without any arguments */
151 static inline PyObject *
_PyObject_CallNoArg(PyObject * func)152 _PyObject_CallNoArg(PyObject *func) {
153 return _PyObject_Vectorcall(func, NULL, 0, NULL);
154 }
155
156 PyAPI_FUNC(PyObject *) _PyObject_Call_Prepend(
157 PyObject *callable,
158 PyObject *obj,
159 PyObject *args,
160 PyObject *kwargs);
161
162 PyAPI_FUNC(PyObject *) _PyObject_FastCall_Prepend(
163 PyObject *callable,
164 PyObject *obj,
165 PyObject *const *args,
166 Py_ssize_t nargs);
167
168 /* Like PyObject_CallMethod(), but expect a _Py_Identifier*
169 as the method name. */
170 PyAPI_FUNC(PyObject *) _PyObject_CallMethodId(PyObject *obj,
171 _Py_Identifier *name,
172 const char *format, ...);
173
174 PyAPI_FUNC(PyObject *) _PyObject_CallMethodId_SizeT(PyObject *obj,
175 _Py_Identifier *name,
176 const char *format,
177 ...);
178
179 PyAPI_FUNC(PyObject *) _PyObject_CallMethodIdObjArgs(
180 PyObject *obj,
181 struct _Py_Identifier *name,
182 ...);
183
184 PyAPI_FUNC(int) _PyObject_HasLen(PyObject *o);
185
186 /* Guess the size of object 'o' using len(o) or o.__length_hint__().
187 If neither of those return a non-negative value, then return the default
188 value. If one of the calls fails, this function returns -1. */
189 PyAPI_FUNC(Py_ssize_t) PyObject_LengthHint(PyObject *o, Py_ssize_t);
190
191 /* === New Buffer API ============================================ */
192
193 /* Return 1 if the getbuffer function is available, otherwise return 0. */
194 #define PyObject_CheckBuffer(obj) \
195 (((obj)->ob_type->tp_as_buffer != NULL) && \
196 ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL))
197
198 /* This is a C-API version of the getbuffer function call. It checks
199 to make sure object has the required function pointer and issues the
200 call.
201
202 Returns -1 and raises an error on failure and returns 0 on success. */
203 PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
204 int flags);
205
206 /* Get the memory area pointed to by the indices for the buffer given.
207 Note that view->ndim is the assumed size of indices. */
208 PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices);
209
210 /* Return the implied itemsize of the data-format area from a
211 struct-style description. */
212 PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *);
213
214 /* Implementation in memoryobject.c */
215 PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view,
216 Py_ssize_t len, char order);
217
218 PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
219 Py_ssize_t len, char order);
220
221 /* Copy len bytes of data from the contiguous chunk of memory
222 pointed to by buf into the buffer exported by obj. Return
223 0 on success and return -1 and raise a PyBuffer_Error on
224 error (i.e. the object does not have a buffer interface or
225 it is not working).
226
227 If fort is 'F', then if the object is multi-dimensional,
228 then the data will be copied into the array in
229 Fortran-style (first dimension varies the fastest). If
230 fort is 'C', then the data will be copied into the array
231 in C-style (last dimension varies the fastest). If fort
232 is 'A', then it does not matter and the copy will be made
233 in whatever way is more efficient. */
234 PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src);
235
236 /* Copy the data from the src buffer to the buffer of destination. */
237 PyAPI_FUNC(int) PyBuffer_IsContiguous(const Py_buffer *view, char fort);
238
239 /*Fill the strides array with byte-strides of a contiguous
240 (Fortran-style if fort is 'F' or C-style otherwise)
241 array of the given shape with the given number of bytes
242 per element. */
243 PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
244 Py_ssize_t *shape,
245 Py_ssize_t *strides,
246 int itemsize,
247 char fort);
248
249 /* Fills in a buffer-info structure correctly for an exporter
250 that can only share a contiguous chunk of memory of
251 "unsigned bytes" of the given length.
252
253 Returns 0 on success and -1 (with raising an error) on error. */
254 PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf,
255 Py_ssize_t len, int readonly,
256 int flags);
257
258 /* Releases a Py_buffer obtained from getbuffer ParseTuple's "s*". */
259 PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view);
260
261 /* ==== Iterators ================================================ */
262
263 #define PyIter_Check(obj) \
264 ((obj)->ob_type->tp_iternext != NULL && \
265 (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)
266
267 /* === Number Protocol ================================================== */
268
269 #define PyIndex_Check(obj) \
270 ((obj)->ob_type->tp_as_number != NULL && \
271 (obj)->ob_type->tp_as_number->nb_index != NULL)
272
273 /* === Sequence protocol ================================================ */
274
275 /* Assume tp_as_sequence and sq_item exist and that 'i' does not
276 need to be corrected for a negative index. */
277 #define PySequence_ITEM(o, i)\
278 ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
279
280 #define PY_ITERSEARCH_COUNT 1
281 #define PY_ITERSEARCH_INDEX 2
282 #define PY_ITERSEARCH_CONTAINS 3
283
284 /* Iterate over seq.
285
286 Result depends on the operation:
287
288 PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
289 error.
290 PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
291 obj in seq; set ValueError and return -1 if none found;
292 also return -1 on error.
293 PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
294 error. */
295 PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
296 PyObject *obj, int operation);
297
298 /* === Mapping protocol ================================================= */
299
300 PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls);
301
302 PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
303
304 PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self);
305
306 PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]);
307
308 /* For internal use by buffer API functions */
309 PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,
310 const Py_ssize_t *shape);
311 PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index,
312 const Py_ssize_t *shape);
313
314 /* Convert Python int to Py_ssize_t. Do nothing if the argument is None. */
315 PyAPI_FUNC(int) _Py_convert_optional_to_ssize_t(PyObject *, void *);
316
317 #ifdef __cplusplus
318 }
319 #endif
320