Debian Codegraph @

mypyc/lib-rt/getargsfast.c

raw
1 /* getargskeywordsfast implementation copied from Python 3.9 and stripped down to
2 * only include the functionality we need.
3 *
4 * We also add support for required kwonly args and accepting *args / **kwargs.
5 *
6 * DOCUMENTATION OF THE EXTENSIONS:
7 * - Arguments given after a @ format specify required keyword-only arguments.
8 * The | and $ specifiers must both appear before @.
9 * - If the first character of a format string is %, then the function can support
10 * *args and/or **kwargs. In this case the parser will consume two arguments,
11 * which should be pointers to variables to store the *args and **kwargs, respectively.
12 * Either pointer can be NULL, in which case the function doesn't take that
13 * variety of vararg.
14 * Unlike most format specifiers, the caller takes ownership of these objects
15 * and is responsible for decrefing them.
16 */
17
18 #include <Python.h>
19 #include "CPy.h"
20
21 // The kwtuple field doubles as the "parser has been initialized" flag: it is
22 // written last (after all other parser fields) and read first. On free-threaded
23 // builds the fast paths read it without holding any lock, so the write must be a
24 // release store and the reads acquire loads. That way a thread that observes a
25 // non-NULL kwtuple is guaranteed to also see the fully-initialized min/max/etc.
26 // fields. On GIL builds these are plain accesses with no overhead.
27 #ifdef Py_GIL_DISABLED
28 #define PARSER_KWTUPLE(parser) _Py_atomic_load_ptr_acquire(&(parser)->kwtuple)
29 #define SET_PARSER_KWTUPLE(parser, value) \
30 _Py_atomic_store_ptr_release(&(parser)->kwtuple, (value))
31 #else
32 #define PARSER_KWTUPLE(parser) ((parser)->kwtuple)
33 #define SET_PARSER_KWTUPLE(parser, value) ((parser)->kwtuple = (value))
34 #endif
35
36 #define PARSER_INITED(parser) (PARSER_KWTUPLE(parser) != NULL)
37
38 /* Forward */
39 static int
40 vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
41 PyObject *kwargs, PyObject *kwnames,
42 CPyArg_Parser *parser,
43 va_list *p_va);
44 static void skipitem_fast(const char **, va_list *);
45
46 /* Parse args for an arbitrary signature */
47 int
48 CPyArg_ParseStackAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
49 CPyArg_Parser *parser, ...)
50 {
51 int retval;
52 va_list va;
53
54 va_start(va, parser);
55 retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);
56 va_end(va);
57 return retval;
58 }
59
60 /* Parse args for a function that takes no args */
61 int
62 CPyArg_ParseStackAndKeywordsNoArgs(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
63 CPyArg_Parser *parser, ...)
64 {
65 int retval;
66 va_list va;
67
68 va_start(va, parser);
69 if (nargs == 0 && kwnames == NULL) {
70 // Fast path: no arguments
71 retval = 1;
72 } else {
73 retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);
74 }
75 va_end(va);
76 return retval;
77 }
78
79 /* Parse args for a function that takes one arg */
80 int
81 CPyArg_ParseStackAndKeywordsOneArg(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
82 CPyArg_Parser *parser, ...)
83 {
84 int retval;
85 va_list va;
86
87 va_start(va, parser);
88 if (kwnames == NULL && nargs == 1) {
89 // Fast path: one positional argument
90 PyObject **p;
91 p = va_arg(va, PyObject **);
92 *p = args[0];
93 retval = 1;
94 } else {
95 retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);
96 }
97 va_end(va);
98 return retval;
99 }
100
101 /* Parse args for a function that takes no keyword-only args, *args or **kwargs */
102 int
103 CPyArg_ParseStackAndKeywordsSimple(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
104 CPyArg_Parser *parser, ...)
105 {
106 int retval;
107 va_list va;
108
109 va_start(va, parser);
110 if (kwnames == NULL && PARSER_INITED(parser) &&
111 nargs >= parser->min && nargs <= parser->max) {
112 // Fast path: correct number of positional arguments only
113 PyObject **p;
114 Py_ssize_t i;
115 for (i = 0; i < nargs; i++) {
116 p = va_arg(va, PyObject **);
117 *p = args[i];
118 }
119 retval = 1;
120 } else {
121 retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);
122 }
123 va_end(va);
124 return retval;
125 }
126
127 #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')
128
129
130 /* List of static parsers. */
131 static struct CPyArg_Parser *static_arg_parsers = NULL;
132
133 #ifdef Py_GIL_DISABLED
134 // Serializes one-time initialization of parsers and insertion into the
135 // static_arg_parsers list. Only contended the first time a given compiled
136 // function is called; once a parser is initialized the fast paths never lock.
137 static PyMutex static_arg_parsers_mutex;
138 #endif
139
140 static int
141 parser_init_locked(CPyArg_Parser *parser)
142 {
143 const char * const *keywords;
144 const char *format;
145 int i, len, min, max, nkw;
146 PyObject *kwtuple;
147
148 keywords = parser->keywords;
149 /* scan keywords and count the number of positional-only parameters */
150 for (i = 0; keywords[i] && !*keywords[i]; i++) {
151 }
152 parser->pos = i;
153 /* scan keywords and get greatest possible nbr of args */
154 for (; keywords[i]; i++) {
155 if (!*keywords[i]) {
156 PyErr_SetString(PyExc_SystemError,
157 "Empty keyword parameter name");
158 return 0;
159 }
160 }
161 len = i;
162
163 parser->required_kwonly_start = INT_MAX;
164 if (*parser->format == '%') {
165 parser->format++;
166 parser->varargs = 1;
167 }
168
169 format = parser->format;
170 if (format) {
171 /* grab the function name or custom error msg first (mutually exclusive) */
172 parser->fname = strchr(parser->format, ':');
173 if (parser->fname) {
174 parser->fname++;
175 parser->custom_msg = NULL;
176 }
177 else {
178 parser->custom_msg = strchr(parser->format,';');
179 if (parser->custom_msg)
180 parser->custom_msg++;
181 }
182
183 min = max = INT_MAX;
184 for (i = 0; i < len; i++) {
185 if (*format == '|') {
186 if (min != INT_MAX) {
187 PyErr_SetString(PyExc_SystemError,
188 "Invalid format string (| specified twice)");
189 return 0;
190 }
191 if (max != INT_MAX) {
192 PyErr_SetString(PyExc_SystemError,
193 "Invalid format string ($ before |)");
194 return 0;
195 }
196 min = i;
197 format++;
198 }
199 if (*format == '$') {
200 if (max != INT_MAX) {
201 PyErr_SetString(PyExc_SystemError,
202 "Invalid format string ($ specified twice)");
203 return 0;
204 }
205 if (i < parser->pos) {
206 PyErr_SetString(PyExc_SystemError,
207 "Empty parameter name after $");
208 return 0;
209 }
210 max = i;
211 format++;
212 }
213 if (*format == '@') {
214 if (parser->required_kwonly_start != INT_MAX) {
215 PyErr_SetString(PyExc_SystemError,
216 "Invalid format string (@ specified twice)");
217 return 0;
218 }
219 if (min == INT_MAX && max == INT_MAX) {
220 PyErr_SetString(PyExc_SystemError,
221 "Invalid format string "
222 "(@ without preceding | and $)");
223 return 0;
224 }
225 format++;
226 parser->has_required_kws = 1;
227 parser->required_kwonly_start = i;
228 }
229 if (IS_END_OF_FORMAT(*format)) {
230 PyErr_Format(PyExc_SystemError,
231 "More keyword list entries (%d) than "
232 "format specifiers (%d)", len, i);
233 return 0;
234 }
235
236 skipitem_fast(&format, NULL);
237 }
238 parser->min = Py_MIN(min, len);
239 parser->max = Py_MIN(max, len);
240
241 if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {
242 PyErr_Format(PyExc_SystemError,
243 "more argument specifiers than keyword list entries "
244 "(remaining format:'%s')", format);
245 return 0;
246 }
247 }
248
249 nkw = len - parser->pos;
250 kwtuple = PyTuple_New(nkw);
251 if (kwtuple == NULL) {
252 return 0;
253 }
254 keywords = parser->keywords + parser->pos;
255 for (i = 0; i < nkw; i++) {
256 PyObject *str = PyUnicode_FromString(keywords[i]);
257 if (str == NULL) {
258 Py_DECREF(kwtuple);
259 return 0;
260 }
261 PyUnicode_InternInPlace(&str);
262 PyTuple_SET_ITEM(kwtuple, i, str);
263 }
264
265 assert(parser->next == NULL);
266 parser->next = static_arg_parsers;
267 static_arg_parsers = parser;
268
269 // Publish the parser last: storing kwtuple marks it as initialized, so all
270 // other fields (and the list insertion above) must already be in place. On
271 // free-threaded builds this is a release store paired with the acquire loads
272 // in PARSER_INITED/PARSER_KWTUPLE.
273 SET_PARSER_KWTUPLE(parser, kwtuple);
274 return 1;
275 }
276
277 // Cold path of parser_init: perform the one-time initialization. On
278 // free-threaded builds this is serialized so that only one thread builds the
279 // parser and inserts it into the static_arg_parsers list.
280 static CPy_NOINLINE int
281 parser_init_slow(CPyArg_Parser *parser)
282 {
283 #ifdef Py_GIL_DISABLED
284 PyMutex_Lock(&static_arg_parsers_mutex);
285 // Re-check now that we hold the lock: another thread may have initialized
286 // the parser while we were waiting.
287 if (PARSER_INITED(parser)) {
288 PyMutex_Unlock(&static_arg_parsers_mutex);
289 return 1;
290 }
291 int retval = parser_init_locked(parser);
292 PyMutex_Unlock(&static_arg_parsers_mutex);
293 return retval;
294 #else
295 return parser_init_locked(parser);
296 #endif
297 }
298
299 // Hot path: a parser is almost always already initialized, so keep the common
300 // case inline and branch out to parser_init_slow only on first use.
301 static inline int
302 parser_init(CPyArg_Parser *parser)
303 {
304 assert(parser->keywords != NULL);
305 if (likely(PARSER_INITED(parser))) {
306 return 1;
307 }
308 return parser_init_slow(parser);
309 }
310
311 static PyObject*
312 find_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)
313 {
314 Py_ssize_t i, nkwargs;
315
316 nkwargs = PyTuple_GET_SIZE(kwnames);
317 for (i = 0; i < nkwargs; i++) {
318 PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
319
320 /* kwname == key will normally find a match in since keyword keys
321 should be interned strings; if not retry below in a new loop. */
322 if (kwname == key) {
323 return kwstack[i];
324 }
325 }
326
327 for (i = 0; i < nkwargs; i++) {
328 PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
329 assert(PyUnicode_Check(kwname));
330 if (PyUnicode_Equal(kwname, key)) {
331 return kwstack[i];
332 }
333 }
334 return NULL;
335 }
336
337 static int
338 vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
339 PyObject *kwargs, PyObject *kwnames,
340 CPyArg_Parser *parser,
341 va_list *p_va)
342 {
343 PyObject *kwtuple;
344 const char *format;
345 PyObject *keyword;
346 int i, pos, len;
347 Py_ssize_t nkwargs;
348 PyObject *current_arg;
349 PyObject *const *kwstack = NULL;
350 int bound_pos_args;
351 PyObject **p_args = NULL, **p_kwargs = NULL;
352
353 assert(kwargs == NULL || PyDict_Check(kwargs));
354 assert(kwargs == NULL || kwnames == NULL);
355 assert(p_va != NULL);
356
357 if (!parser_init(parser)) {
358 return 0;
359 }
360
361 kwtuple = parser->kwtuple;
362 pos = parser->pos;
363 len = pos + (int)PyTuple_GET_SIZE(kwtuple);
364
365 if (parser->varargs) {
366 p_args = va_arg(*p_va, PyObject **);
367 p_kwargs = va_arg(*p_va, PyObject **);
368 }
369
370 if (kwargs != NULL) {
371 nkwargs = PyDict_GET_SIZE(kwargs);
372 }
373 else if (kwnames != NULL) {
374 nkwargs = PyTuple_GET_SIZE(kwnames);
375 kwstack = args + nargs;
376 }
377 else {
378 nkwargs = 0;
379 }
380 if (nargs + nkwargs > len && !p_args && !p_kwargs) {
381 /* Adding "keyword" (when nargs == 0) prevents producing wrong error
382 messages in some special cases (see bpo-31229). */
383 PyErr_Format(PyExc_TypeError,
384 "%.200s%s takes at most %d %sargument%s (%zd given)",
385 (parser->fname == NULL) ? "function" : parser->fname,
386 (parser->fname == NULL) ? "" : "()",
387 len,
388 (nargs == 0) ? "keyword " : "",
389 (len == 1) ? "" : "s",
390 nargs + nkwargs);
391 return 0;
392 }
393 if (parser->max < nargs && !p_args) {
394 if (parser->max == 0) {
395 PyErr_Format(PyExc_TypeError,
396 "%.200s%s takes no positional arguments",
397 (parser->fname == NULL) ? "function" : parser->fname,
398 (parser->fname == NULL) ? "" : "()");
399 }
400 else {
401 PyErr_Format(PyExc_TypeError,
402 "%.200s%s takes %s %d positional argument%s (%zd given)",
403 (parser->fname == NULL) ? "function" : parser->fname,
404 (parser->fname == NULL) ? "" : "()",
405 (parser->min < parser->max) ? "at most" : "exactly",
406 parser->max,
407 parser->max == 1 ? "" : "s",
408 nargs);
409 }
410 return 0;
411 }
412
413 format = parser->format;
414
415 /* convert tuple args and keyword args in same loop, using kwtuple to drive process */
416 for (i = 0; i < len; i++) {
417 if (*format == '|') {
418 format++;
419 }
420 if (*format == '$') {
421 format++;
422 }
423 if (*format == '@') {
424 format++;
425 }
426 assert(!IS_END_OF_FORMAT(*format));
427
428 if (i < nargs && i < parser->max) {
429 current_arg = args[i];
430 }
431 else if (nkwargs && i >= pos) {
432 keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
433 if (kwargs != NULL) {
434 current_arg = PyDict_GetItemWithError(kwargs, keyword);
435 if (!current_arg && PyErr_Occurred()) {
436 return 0;
437 }
438 }
439 else {
440 current_arg = find_keyword(kwnames, kwstack, keyword);
441 }
442 if (current_arg) {
443 --nkwargs;
444 }
445 }
446 else {
447 current_arg = NULL;
448 }
449
450 if (current_arg) {
451 PyObject **p = va_arg(*p_va, PyObject **);
452 *p = current_arg;
453 format++;
454 continue;
455 }
456
457 if (i < parser->min || i >= parser->required_kwonly_start) {
458 /* Less arguments than required */
459 if (i < pos) {
460 Py_ssize_t min = Py_MIN(pos, parser->min);
461 PyErr_Format(PyExc_TypeError,
462 "%.200s%s takes %s %d positional argument%s"
463 " (%zd given)",
464 (parser->fname == NULL) ? "function" : parser->fname,
465 (parser->fname == NULL) ? "" : "()",
466 min < parser->max ? "at least" : "exactly",
467 min,
468 min == 1 ? "" : "s",
469 nargs);
470 }
471 else {
472 keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
473 if (i >= parser->max) {
474 PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
475 "keyword-only argument '%U'",
476 (parser->fname == NULL) ? "function" : parser->fname,
477 (parser->fname == NULL) ? "" : "()",
478 keyword);
479 }
480 else {
481 PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
482 "argument '%U' (pos %d)",
483 (parser->fname == NULL) ? "function" : parser->fname,
484 (parser->fname == NULL) ? "" : "()",
485 keyword, i+1);
486 }
487 }
488 return 0;
489 }
490 /* current code reports success when all required args
491 * fulfilled and no keyword args left, with no further
492 * validation. XXX Maybe skip this in debug build ?
493 */
494 if (!nkwargs && !parser->has_required_kws && !p_args && !p_kwargs) {
495 return 1;
496 }
497
498 /* We are into optional args, skip through to any remaining
499 * keyword args */
500 skipitem_fast(&format, p_va);
501 }
502
503 assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$'));
504
505 bound_pos_args = Py_MIN(nargs, Py_MIN(parser->max, len));
506 if (p_args) {
507 *p_args = PyTuple_New(nargs - bound_pos_args);
508 if (!*p_args) {
509 return 0;
510 }
511 for (i = bound_pos_args; i < nargs; i++) {
512 PyObject *arg = args[i];
513 Py_INCREF(arg);
514 PyTuple_SET_ITEM(*p_args, i - bound_pos_args, arg);
515 }
516 }
517
518 if (p_kwargs) {
519 /* This unfortunately needs to be special cased because if len is 0 then we
520 * never go through the main loop. */
521 if (nargs > 0 && len == 0 && !p_args) {
522 PyErr_Format(PyExc_TypeError,
523 "%.200s%s takes no positional arguments",
524 (parser->fname == NULL) ? "function" : parser->fname,
525 (parser->fname == NULL) ? "" : "()");
526
527 return 0;
528 }
529
530 *p_kwargs = PyDict_New();
531 if (!*p_kwargs) {
532 goto latefail;
533 }
534 }
535
536 if (nkwargs > 0) {
537 Py_ssize_t j;
538 PyObject *value;
539 /* make sure there are no arguments given by name and position */
540 for (i = pos; i < bound_pos_args; i++) {
541 keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
542 if (kwargs != NULL) {
543 current_arg = PyDict_GetItemWithError(kwargs, keyword);
544 if (!current_arg && PyErr_Occurred()) {
545 goto latefail;
546 }
547 }
548 else {
549 current_arg = find_keyword(kwnames, kwstack, keyword);
550 }
551 if (current_arg) {
552 /* arg present in tuple and in dict */
553 PyErr_Format(PyExc_TypeError,
554 "argument for %.200s%s given by name ('%U') "
555 "and position (%d)",
556 (parser->fname == NULL) ? "function" : parser->fname,
557 (parser->fname == NULL) ? "" : "()",
558 keyword, i+1);
559 goto latefail;
560 }
561 }
562 /* make sure there are no extraneous keyword arguments */
563 j = 0;
564 while (1) {
565 int match;
566 if (kwargs != NULL) {
567 if (!PyDict_Next(kwargs, &j, &keyword, &value))
568 break;
569 }
570 else {
571 if (j >= PyTuple_GET_SIZE(kwnames))
572 break;
573 keyword = PyTuple_GET_ITEM(kwnames, j);
574 value = kwstack[j];
575 j++;
576 }
577
578 match = PySequence_Contains(kwtuple, keyword);
579 if (match <= 0) {
580 if (!match) {
581 if (!p_kwargs) {
582 PyErr_Format(PyExc_TypeError,
583 "'%S' is an invalid keyword "
584 "argument for %.200s%s",
585 keyword,
586 (parser->fname == NULL) ? "this function" : parser->fname,
587 (parser->fname == NULL) ? "" : "()");
588 goto latefail;
589 } else {
590 if (PyDict_SetItem(*p_kwargs, keyword, value) < 0) {
591 goto latefail;
592 }
593 }
594 } else {
595 goto latefail;
596 }
597 }
598 }
599 }
600
601 return 1;
602 /* Handle failures that have happened after we have tried to
603 * create *args and **kwargs, if they exist. */
604 latefail:
605 if (p_args) {
606 Py_XDECREF(*p_args);
607 }
608 if (p_kwargs) {
609 Py_XDECREF(*p_kwargs);
610 }
611 return 0;
612 }
613
614 static void
615 skipitem_fast(const char **p_format, va_list *p_va)
616 {
617 const char *format = *p_format;
618 char c = *format++;
619
620 if (p_va != NULL) {
621 (void) va_arg(*p_va, PyObject **);
622 }
623
624 *p_format = format;
625 }