Debian Codegraph @

lib_pypy/hpy/devel/src/runtime/buildvalue.c

raw symbols SCIP
1 /**
2 * Implementation of HPy_BuildValue.
3 *
4 * Note: :c:func:`HPy_BuildValue` is a runtime helper functions, i.e., it is not
5 * a part of the HPy context, but is available to HPy extensions to incorporate
6 * at compile time.
7 *
8 * ``HPy_BuildValue`` creates a new value based on a format string from the
9 * values passed in variadic arguments. Returns ``HPy_NULL`` in case of an error
10 * and raises an exception.
11 *
12 * ``HPy_BuildValue`` does not always build a tuple. It builds a tuple only if
13 * its format string contains two or more format units. If the format string is
14 * empty, it returns ``None``; if it contains exactly one format unit, it
15 * returns whatever object is described by that format unit. To force it to
16 * return a tuple of size ``0`` or one, parenthesize the format string.
17 *
18 * Building complex values with ``HPy_BuildValue`` is more convenient than the
19 * equivalent code that uses more granular APIs with proper error handling and
20 * cleanup. Moreover, ``HPy_BuildValue`` provides straightforward way to port
21 * existing code that uses ``Py_BuildValue``.
22 *
23 * ``HPy_BuildValue`` always returns a new handle that will be owned by the
24 * caller. Even an artificial example ``HPy_BuildValue(ctx, "O", h)`` does not
25 * simply forward the value stored in ``h`` but duplicates the handle.
26 *
27 * Supported Formatting Strings
28 * ----------------------------
29 *
30 * Numbers
31 * ~~~~~~~
32 *
33 * ``i (int) [int]``
34 * Convert a plain C int to a Python integer object.
35 *
36 * ``l (int) [long int]``
37 * Convert a C long int to a Python integer object.
38 *
39 * ``I (int) [unsigned int]``
40 * Convert a C unsigned int to a Python integer object.
41 *
42 * ``k (int) [unsigned long]``
43 * Convert a C unsigned long to a Python integer object.
44 *
45 * ``L (int) [long long]``
46 * Convert a C long long to a Python integer object.
47 *
48 * ``K (int) [unsigned long long]``
49 * Convert a C unsigned long long to a Python integer object.
50 *
51 * ``n (int) [HPy_ssize_t]``
52 * Convert a C HPy_ssize_t to a Python integer object.
53 *
54 * ``f (float) [float]``
55 * Convert a C float to a Python floating point number.
56 *
57 * ``d (float) [double]``
58 * Convert a C double to a Python floating point number.
59 *
60 * Collections
61 * ~~~~~~~~~~~
62 *
63 * ``(items) (tuple) [matching-items]``
64 * Convert a sequence of C values to a Python tuple with the same number of items.
65 *
66 * ``[items] (list) [matching-items]``
67 * Convert a sequence of C values to a Python list with the same number of items.
68 *
69 * ``{key:value} (dict) [matching-items]``
70 * Convert a sequence of C values to a Python dict with the same number of items.
71 *
72 * Misc
73 * ~~~~~~~
74 *
75 * ``O (Python object) [HPy]``
76 * Pass an untouched Python object represented by the handle.
77 *
78 * If the object passed in is a HPy_NULL, it is assumed that this was caused because
79 * the call producing the argument found an error and set an exception. Therefore,
80 * HPy_BuildValue will also immediately stop and return HPy_NULL but will not raise
81 * any new exception. If no exception has been raised yet, SystemError is set.
82 *
83 * Any HPy handle passed to HPy_BuildValue is always owned by the caller. HPy_BuildValue
84 * never closes the handle nor transfers its ownership. If the handle is used, then
85 * HPy_BuildValue creates a duplicate of the handle.
86 *
87 * ``S (Python object) [HPy]``
88 * Alias for 'O'.
89 *
90 * API
91 * ---
92 *
93 */
94
95 #include "hpy.h"
96 #include <stdarg.h>
97 #include <stdio.h>
98
99 #define MESSAGE_BUF_SIZE 128
100
101 static HPy_ssize_t count_items(HPyContext *ctx, const char *fmt, char end);
102 static HPy build_tuple(HPyContext *ctx, const char **fmt, va_list *values, HPy_ssize_t size, char expected_end);
103 static HPy build_list(HPyContext *ctx, const char **fmt, va_list *values, HPy_ssize_t size);
104 static HPy build_dict(HPyContext *ctx, const char **fmt, va_list *values);
105 static HPy build_single(HPyContext *ctx, const char **fmt, va_list *values, int *needs_close);
106
107 /**
108 * Creates a new value based on a format string from the values passed in
109 * variadic arguments.
110 *
111 * :param ctx:
112 * The execution context.
113 * :param fmt:
114 * The format string (ASCII only; must not be ``NULL``). For details, see
115 * :ref:`api-reference/build-value:supported formatting strings`.
116 * :param ...:
117 * Variable arguments according to the provided format string.
118 *
119 * :returns:
120 * A handle to the built Python value or ``HPy_NULL`` in case of errors.
121 */
122 HPyAPI_HELPER
123 HPy HPy_BuildValue(HPyContext *ctx, const char *fmt, ...)
124 {
125 va_list values;
126 HPy result;
127 va_start(values, fmt);
128 HPy_ssize_t size = count_items(ctx, fmt, '\0');
129 if (size < 0) {
130 result = HPy_NULL;
131 } else if (size == 0) {
132 result = HPy_Dup(ctx, ctx->h_None);
133 } else if (size == 1) {
134 int needs_close;
135 result = build_single(ctx, &fmt, &values, &needs_close);
136 if (!needs_close) {
137 result = HPy_Dup(ctx, result);
138 }
139 } else {
140 result = build_tuple(ctx, &fmt, &values, size, '\0');
141 }
142 va_end(values);
143 return result;
144 }
145
146 static HPy_ssize_t count_items(HPyContext *ctx, const char *fmt, char end)
147 {
148 HPy_ssize_t level = 0, result = 0;
149 char top_level_par = 'X';
150 while (level != 0 || *fmt != end) {
151 char c = *fmt++;
152 switch (c) {
153 case '\0': {
154 // Premature end
155 // We try to provide slightly better diagnostics than CPython
156 char msg[MESSAGE_BUF_SIZE];
157 char par_type;
158 if (end == ')') {
159 par_type = '(';
160 } else if (end == ']') {
161 par_type = '[';
162 } else if (end == '}') {
163 par_type = '{';
164 } else {
165 if (level == 0 || top_level_par == 'X') {
166 HPyErr_SetString(ctx, ctx->h_SystemError, "internal error in HPy_BuildValue");
167 return -1;
168 }
169 par_type = top_level_par;
170 }
171 snprintf(msg, sizeof(msg), "unmatched '%c' in the format string passed to HPy_BuildValue", par_type);
172 HPyErr_SetString(ctx, ctx->h_SystemError, msg);
173 return -1;
174 }
175
176 case '[':
177 case '(':
178 case '{':
179 if (level == 0) {
180 top_level_par = c;
181 result++;
182 }
183 level++;
184 break;
185
186 case ']':
187 case ')':
188 case '}':
189 level--;
190 break;
191
192 case ',':
193 case ' ':
194 break;
195
196 default:
197 if (level == 0) {
198 result++;
199 }
200 }
201 }
202 return result;
203 }
204
205 static HPy build_single(HPyContext *ctx, const char **fmt, va_list *values, int *needs_close)
206 {
207 char format_char = *(*fmt)++;
208 *needs_close = 1;
209 switch (format_char) {
210 case '(': {
211 HPy_ssize_t size = count_items(ctx, *fmt, ')');
212 if (size < 0) {
213 return HPy_NULL;
214 }
215 return build_tuple(ctx, fmt, values, size, ')');
216 }
217
218 case '[': {
219 HPy_ssize_t size = count_items(ctx, *fmt, ']');
220 if (size < 0) {
221 return HPy_NULL;
222 }
223 return build_list(ctx, fmt, values, size);
224 }
225
226 case '{': {
227 return build_dict(ctx, fmt, values);
228 }
229
230 case 'i':
231 return HPyLong_FromLong(ctx, (long)va_arg(*values, int));
232
233 case 'I':
234 return HPyLong_FromUnsignedLong(ctx, (unsigned long)va_arg(*values, unsigned int));
235
236 case 'k':
237 return HPyLong_FromUnsignedLong(ctx, va_arg(*values, unsigned long));
238
239 case 'l':
240 return HPyLong_FromLong(ctx, va_arg(*values, long));
241
242 case 'L':
243 return HPyLong_FromLongLong(ctx, va_arg(*values, long long));
244
245 case 'K':
246 return HPyLong_FromUnsignedLongLong(ctx, va_arg(*values, unsigned long long));
247
248 case 'n':
249 return HPyLong_FromSsize_t(ctx, va_arg(*values, HPy_ssize_t));
250
251 case 's':
252 return HPyUnicode_FromString(ctx, va_arg(*values, const char*));
253
254 case 'O':
255 case 'S': {
256 HPy handle = va_arg(*values, HPy);
257 if (HPy_IsNull(handle)) {
258 if (!HPyErr_Occurred(ctx)) {
259 HPyErr_SetString(ctx, ctx->h_SystemError, "HPy_NULL object passed to HPy_BuildValue");
260 }
261 return handle;
262 }
263 *needs_close = 0;
264 return handle;
265 }
266
267 case 'N': {
268 HPyErr_SetString(ctx, ctx->h_SystemError,
269 "HPy_BuildValue does not support the 'N' formatting unit. "
270 "Instead, use the 'O' formatting unit and manually close "
271 "the handle in the caller if necessary. HPy API functions "
272 "never 'steal' handles and always make a duplicate handle if "
273 "needed, the 'ownership' of the original handle is never "
274 "'transferred'. ");
275 return HPy_NULL;
276 }
277
278 case 'f': // Note: floats are promoted to doubles when passed in "..."
279 case 'd':
280 return HPyFloat_FromDouble(ctx, va_arg(*values, double));
281
282 default: {
283 char message[MESSAGE_BUF_SIZE];
284 snprintf(message, sizeof(message), "bad format char '%c' in the format string passed to HPy_BuildValue", format_char);
285 HPyErr_SetString(ctx, ctx->h_SystemError, message);
286 return HPy_NULL;
287 }
288 } // switch
289 }
290
291 static HPy build_dict(HPyContext *ctx, const char **fmt, va_list *values)
292 {
293 HPy dict = HPyDict_New(ctx);
294 int expect_comma = 0;
295 while (**fmt != '}' && **fmt != '\0') {
296 if (**fmt == ' ') {
297 (*fmt)++;
298 continue;
299 }
300 if (**fmt == ',') {
301 if (!expect_comma) {
302 HPyErr_SetString(ctx, ctx->h_SystemError,
303 "unexpected ',' in the format string passed to HPy_BuildValue");
304 HPy_Close(ctx, dict);
305 return HPy_NULL;
306 }
307 (*fmt)++;
308 expect_comma = 0;
309 continue;
310 } else {
311 if (expect_comma) {
312 HPyErr_SetString(ctx, ctx->h_SystemError,
313 "missing ',' in the format string passed to HPy_BuildValue");
314 HPy_Close(ctx, dict);
315 return HPy_NULL;
316 }
317 }
318 int needs_key_close, needs_value_close;
319 HPy key = build_single(ctx, fmt, values, &needs_key_close);
320 if (HPy_IsNull(key)) {
321 HPy_Close(ctx, dict);
322 return HPy_NULL;
323 }
324 if (**fmt != ':') {
325 HPyErr_SetString(ctx, ctx->h_SystemError,
326 "missing ':' in the format string passed to HPy_BuildValue");
327 if (needs_key_close) {
328 HPy_Close(ctx, key);
329 }
330 HPy_Close(ctx, dict);
331 return HPy_NULL;
332 } else {
333 (*fmt)++;
334 }
335 HPy value = build_single(ctx, fmt, values, &needs_value_close);
336 if (HPy_IsNull(value)) {
337 if (needs_key_close) {
338 HPy_Close(ctx, key);
339 }
340 HPy_Close(ctx, dict);
341 return HPy_NULL;
342 }
343 int res = HPy_SetItem(ctx, dict, key, value);
344 if (needs_key_close) {
345 HPy_Close(ctx, key);
346 }
347 if (needs_value_close) {
348 HPy_Close(ctx, value);
349 }
350 if (res < 0) {
351 HPy_Close(ctx, dict);
352 return HPy_NULL;
353 }
354
355 expect_comma = 1;
356 }
357 if (**fmt != '}') {
358 // count_items does not check the type of the matching paren, that's what we do here
359 HPy_Close(ctx, dict);
360 HPyErr_SetString(ctx, ctx->h_SystemError,
361 "unmatched '{' in the format string passed to HPy_BuildValue");
362 return HPy_NULL;
363 }
364 ++*fmt;
365 return dict;
366 }
367
368 static HPy build_list(HPyContext *ctx, const char **fmt, va_list *values, HPy_ssize_t size)
369 {
370 HPyListBuilder builder = HPyListBuilder_New(ctx, size);
371 for (HPy_ssize_t i = 0; i < size; ++i) {
372 int needs_close;
373 HPy item = build_single(ctx, fmt, values, &needs_close);
374 if (HPy_IsNull(item)) {
375 HPyListBuilder_Cancel(ctx, builder);
376 return HPy_NULL;
377 }
378 HPyListBuilder_Set(ctx, builder, i, item);
379 if (needs_close) {
380 HPy_Close(ctx, item);
381 }
382 if (**fmt == ',') {
383 (*fmt)++;
384 }
385 }
386 if (**fmt != ']') {
387 // count_items does not check the type of the matching paren, that's what we do here
388 HPyListBuilder_Cancel(ctx, builder);
389 HPyErr_SetString(ctx, ctx->h_SystemError,
390 "unmatched '[' in the format string passed to HPy_BuildValue");
391 return HPy_NULL;
392 }
393 ++*fmt;
394 return HPyListBuilder_Build(ctx, builder);
395 }
396
397 static HPy build_tuple(HPyContext *ctx, const char **fmt, va_list *values, HPy_ssize_t size, char expected_end)
398 {
399 HPyTupleBuilder builder = HPyTupleBuilder_New(ctx, size);
400 for (HPy_ssize_t i = 0; i < size; ++i) {
401 int needs_close;
402 HPy item = build_single(ctx, fmt, values, &needs_close);
403 if (HPy_IsNull(item)) {
404 HPyTupleBuilder_Cancel(ctx, builder);
405 return HPy_NULL;
406 }
407 HPyTupleBuilder_Set(ctx, builder, i, item);
408 if (needs_close) {
409 HPy_Close(ctx, item);
410 }
411 if (**fmt == ',') {
412 (*fmt)++;
413 }
414 }
415 if (**fmt != expected_end) {
416 // count_items does not check the type of the matching paren, that's what we do here
417 // if expected_end == '\0', then there would have to be a bug in count_items
418 HPyTupleBuilder_Cancel(ctx, builder);
419 if (expected_end == '\0') {
420 HPyErr_SetString(ctx, ctx->h_SystemError, "internal error in HPy_BuildValue");
421 } else {
422 HPyErr_SetString(ctx, ctx->h_SystemError,
423 "unmatched '[' in the format string passed to HPy_BuildValue");
424 }
425 return HPy_NULL;
426 }
427 if (expected_end != '\0') {
428 ++*fmt;
429 }
430 return HPyTupleBuilder_Build(ctx, builder);
431 }