Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Python/getargs.c
12 views
1
2
/* New getargs implementation */
3
4
#include "Python.h"
5
#include "pycore_tuple.h" // _PyTuple_ITEMS()
6
#include "pycore_pylifecycle.h" // _PyArg_Fini
7
8
#include <ctype.h>
9
#include <float.h>
10
11
12
#ifdef __cplusplus
13
extern "C" {
14
#endif
15
16
/* Export Stable ABIs (abi only) */
17
PyAPI_FUNC(int) _PyArg_Parse_SizeT(PyObject *, const char *, ...);
18
PyAPI_FUNC(int) _PyArg_ParseTuple_SizeT(PyObject *, const char *, ...);
19
PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
20
const char *, char **, ...);
21
PyAPI_FUNC(int) _PyArg_VaParse_SizeT(PyObject *, const char *, va_list);
22
PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
23
const char *, char **, va_list);
24
25
#define FLAG_COMPAT 1
26
27
typedef int (*destr_t)(PyObject *, void *);
28
29
30
/* Keep track of "objects" that have been allocated or initialized and
31
which will need to be deallocated or cleaned up somehow if overall
32
parsing fails.
33
*/
34
typedef struct {
35
void *item;
36
destr_t destructor;
37
} freelistentry_t;
38
39
typedef struct {
40
freelistentry_t *entries;
41
int first_available;
42
int entries_malloced;
43
} freelist_t;
44
45
#define STATIC_FREELIST_ENTRIES 8
46
47
/* Forward */
48
static int vgetargs1_impl(PyObject *args, PyObject *const *stack, Py_ssize_t nargs,
49
const char *format, va_list *p_va, int flags);
50
static int vgetargs1(PyObject *, const char *, va_list *, int);
51
static void seterror(Py_ssize_t, const char *, int *, const char *, const char *);
52
static const char *convertitem(PyObject *, const char **, va_list *, int, int *,
53
char *, size_t, freelist_t *);
54
static const char *converttuple(PyObject *, const char **, va_list *, int,
55
int *, char *, size_t, int, freelist_t *);
56
static const char *convertsimple(PyObject *, const char **, va_list *, int,
57
char *, size_t, freelist_t *);
58
static Py_ssize_t convertbuffer(PyObject *, const void **p, const char **);
59
static int getbuffer(PyObject *, Py_buffer *, const char**);
60
61
static int vgetargskeywords(PyObject *, PyObject *,
62
const char *, char **, va_list *, int);
63
static int vgetargskeywordsfast(PyObject *, PyObject *,
64
struct _PyArg_Parser *, va_list *, int);
65
static int vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
66
PyObject *keywords, PyObject *kwnames,
67
struct _PyArg_Parser *parser,
68
va_list *p_va, int flags);
69
static const char *skipitem(const char **, va_list *, int);
70
71
int
72
PyArg_Parse(PyObject *args, const char *format, ...)
73
{
74
int retval;
75
va_list va;
76
77
va_start(va, format);
78
retval = vgetargs1(args, format, &va, FLAG_COMPAT);
79
va_end(va);
80
return retval;
81
}
82
83
PyAPI_FUNC(int)
84
_PyArg_Parse_SizeT(PyObject *args, const char *format, ...)
85
{
86
int retval;
87
va_list va;
88
89
va_start(va, format);
90
retval = vgetargs1(args, format, &va, FLAG_COMPAT);
91
va_end(va);
92
return retval;
93
}
94
95
96
int
97
PyArg_ParseTuple(PyObject *args, const char *format, ...)
98
{
99
int retval;
100
va_list va;
101
102
va_start(va, format);
103
retval = vgetargs1(args, format, &va, 0);
104
va_end(va);
105
return retval;
106
}
107
108
int
109
_PyArg_ParseTuple_SizeT(PyObject *args, const char *format, ...)
110
{
111
int retval;
112
va_list va;
113
114
va_start(va, format);
115
retval = vgetargs1(args, format, &va, 0);
116
va_end(va);
117
return retval;
118
}
119
120
121
int
122
_PyArg_ParseStack(PyObject *const *args, Py_ssize_t nargs, const char *format, ...)
123
{
124
int retval;
125
va_list va;
126
127
va_start(va, format);
128
retval = vgetargs1_impl(NULL, args, nargs, format, &va, 0);
129
va_end(va);
130
return retval;
131
}
132
133
int
134
PyArg_VaParse(PyObject *args, const char *format, va_list va)
135
{
136
va_list lva;
137
int retval;
138
139
va_copy(lva, va);
140
141
retval = vgetargs1(args, format, &lva, 0);
142
va_end(lva);
143
return retval;
144
}
145
146
int
147
_PyArg_VaParse_SizeT(PyObject *args, const char *format, va_list va)
148
{
149
va_list lva;
150
int retval;
151
152
va_copy(lva, va);
153
154
retval = vgetargs1(args, format, &lva, 0);
155
va_end(lva);
156
return retval;
157
}
158
159
160
/* Handle cleanup of allocated memory in case of exception */
161
162
static int
163
cleanup_ptr(PyObject *self, void *ptr)
164
{
165
void **pptr = (void **)ptr;
166
PyMem_Free(*pptr);
167
*pptr = NULL;
168
return 0;
169
}
170
171
static int
172
cleanup_buffer(PyObject *self, void *ptr)
173
{
174
Py_buffer *buf = (Py_buffer *)ptr;
175
if (buf) {
176
PyBuffer_Release(buf);
177
}
178
return 0;
179
}
180
181
static int
182
addcleanup(void *ptr, freelist_t *freelist, destr_t destructor)
183
{
184
int index;
185
186
index = freelist->first_available;
187
freelist->first_available += 1;
188
189
freelist->entries[index].item = ptr;
190
freelist->entries[index].destructor = destructor;
191
192
return 0;
193
}
194
195
static int
196
cleanreturn(int retval, freelist_t *freelist)
197
{
198
int index;
199
200
if (retval == 0) {
201
/* A failure occurred, therefore execute all of the cleanup
202
functions.
203
*/
204
for (index = 0; index < freelist->first_available; ++index) {
205
freelist->entries[index].destructor(NULL,
206
freelist->entries[index].item);
207
}
208
}
209
if (freelist->entries_malloced)
210
PyMem_Free(freelist->entries);
211
return retval;
212
}
213
214
215
static int
216
vgetargs1_impl(PyObject *compat_args, PyObject *const *stack, Py_ssize_t nargs, const char *format,
217
va_list *p_va, int flags)
218
{
219
char msgbuf[256];
220
int levels[32];
221
const char *fname = NULL;
222
const char *message = NULL;
223
int min = -1;
224
int max = 0;
225
int level = 0;
226
int endfmt = 0;
227
const char *formatsave = format;
228
Py_ssize_t i;
229
const char *msg;
230
int compat = flags & FLAG_COMPAT;
231
freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
232
freelist_t freelist;
233
234
assert(nargs == 0 || stack != NULL);
235
236
freelist.entries = static_entries;
237
freelist.first_available = 0;
238
freelist.entries_malloced = 0;
239
240
flags = flags & ~FLAG_COMPAT;
241
242
while (endfmt == 0) {
243
int c = *format++;
244
switch (c) {
245
case '(':
246
if (level == 0)
247
max++;
248
level++;
249
if (level >= 30)
250
Py_FatalError("too many tuple nesting levels "
251
"in argument format string");
252
break;
253
case ')':
254
if (level == 0)
255
Py_FatalError("excess ')' in getargs format");
256
else
257
level--;
258
break;
259
case '\0':
260
endfmt = 1;
261
break;
262
case ':':
263
fname = format;
264
endfmt = 1;
265
break;
266
case ';':
267
message = format;
268
endfmt = 1;
269
break;
270
case '|':
271
if (level == 0)
272
min = max;
273
break;
274
default:
275
if (level == 0) {
276
if (Py_ISALPHA(c))
277
if (c != 'e') /* skip encoded */
278
max++;
279
}
280
break;
281
}
282
}
283
284
if (level != 0)
285
Py_FatalError(/* '(' */ "missing ')' in getargs format");
286
287
if (min < 0)
288
min = max;
289
290
format = formatsave;
291
292
if (max > STATIC_FREELIST_ENTRIES) {
293
freelist.entries = PyMem_NEW(freelistentry_t, max);
294
if (freelist.entries == NULL) {
295
PyErr_NoMemory();
296
return 0;
297
}
298
freelist.entries_malloced = 1;
299
}
300
301
if (compat) {
302
if (max == 0) {
303
if (compat_args == NULL)
304
return 1;
305
PyErr_Format(PyExc_TypeError,
306
"%.200s%s takes no arguments",
307
fname==NULL ? "function" : fname,
308
fname==NULL ? "" : "()");
309
return cleanreturn(0, &freelist);
310
}
311
else if (min == 1 && max == 1) {
312
if (compat_args == NULL) {
313
PyErr_Format(PyExc_TypeError,
314
"%.200s%s takes at least one argument",
315
fname==NULL ? "function" : fname,
316
fname==NULL ? "" : "()");
317
return cleanreturn(0, &freelist);
318
}
319
msg = convertitem(compat_args, &format, p_va, flags, levels,
320
msgbuf, sizeof(msgbuf), &freelist);
321
if (msg == NULL)
322
return cleanreturn(1, &freelist);
323
seterror(levels[0], msg, levels+1, fname, message);
324
return cleanreturn(0, &freelist);
325
}
326
else {
327
PyErr_SetString(PyExc_SystemError,
328
"old style getargs format uses new features");
329
return cleanreturn(0, &freelist);
330
}
331
}
332
333
if (nargs < min || max < nargs) {
334
if (message == NULL)
335
PyErr_Format(PyExc_TypeError,
336
"%.150s%s takes %s %d argument%s (%zd given)",
337
fname==NULL ? "function" : fname,
338
fname==NULL ? "" : "()",
339
min==max ? "exactly"
340
: nargs < min ? "at least" : "at most",
341
nargs < min ? min : max,
342
(nargs < min ? min : max) == 1 ? "" : "s",
343
nargs);
344
else
345
PyErr_SetString(PyExc_TypeError, message);
346
return cleanreturn(0, &freelist);
347
}
348
349
for (i = 0; i < nargs; i++) {
350
if (*format == '|')
351
format++;
352
msg = convertitem(stack[i], &format, p_va,
353
flags, levels, msgbuf,
354
sizeof(msgbuf), &freelist);
355
if (msg) {
356
seterror(i+1, msg, levels, fname, message);
357
return cleanreturn(0, &freelist);
358
}
359
}
360
361
if (*format != '\0' && !Py_ISALPHA(*format) &&
362
*format != '(' &&
363
*format != '|' && *format != ':' && *format != ';') {
364
PyErr_Format(PyExc_SystemError,
365
"bad format string: %.200s", formatsave);
366
return cleanreturn(0, &freelist);
367
}
368
369
return cleanreturn(1, &freelist);
370
}
371
372
static int
373
vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags)
374
{
375
PyObject **stack;
376
Py_ssize_t nargs;
377
378
if (!(flags & FLAG_COMPAT)) {
379
assert(args != NULL);
380
381
if (!PyTuple_Check(args)) {
382
PyErr_SetString(PyExc_SystemError,
383
"new style getargs format but argument is not a tuple");
384
return 0;
385
}
386
387
stack = _PyTuple_ITEMS(args);
388
nargs = PyTuple_GET_SIZE(args);
389
}
390
else {
391
stack = NULL;
392
nargs = 0;
393
}
394
395
return vgetargs1_impl(args, stack, nargs, format, p_va, flags);
396
}
397
398
399
static void
400
seterror(Py_ssize_t iarg, const char *msg, int *levels, const char *fname,
401
const char *message)
402
{
403
char buf[512];
404
int i;
405
char *p = buf;
406
407
if (PyErr_Occurred())
408
return;
409
else if (message == NULL) {
410
if (fname != NULL) {
411
PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
412
p += strlen(p);
413
}
414
if (iarg != 0) {
415
PyOS_snprintf(p, sizeof(buf) - (p - buf),
416
"argument %zd", iarg);
417
i = 0;
418
p += strlen(p);
419
while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
420
PyOS_snprintf(p, sizeof(buf) - (p - buf),
421
", item %d", levels[i]-1);
422
p += strlen(p);
423
i++;
424
}
425
}
426
else {
427
PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
428
p += strlen(p);
429
}
430
PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
431
message = buf;
432
}
433
if (msg[0] == '(') {
434
PyErr_SetString(PyExc_SystemError, message);
435
}
436
else {
437
PyErr_SetString(PyExc_TypeError, message);
438
}
439
}
440
441
442
/* Convert a tuple argument.
443
On entry, *p_format points to the character _after_ the opening '('.
444
On successful exit, *p_format points to the closing ')'.
445
If successful:
446
*p_format and *p_va are updated,
447
*levels and *msgbuf are untouched,
448
and NULL is returned.
449
If the argument is invalid:
450
*p_format is unchanged,
451
*p_va is undefined,
452
*levels is a 0-terminated list of item numbers,
453
*msgbuf contains an error message, whose format is:
454
"must be <typename1>, not <typename2>", where:
455
<typename1> is the name of the expected type, and
456
<typename2> is the name of the actual type,
457
and msgbuf is returned.
458
*/
459
460
static const char *
461
converttuple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
462
int *levels, char *msgbuf, size_t bufsize, int toplevel,
463
freelist_t *freelist)
464
{
465
int level = 0;
466
int n = 0;
467
const char *format = *p_format;
468
int i;
469
Py_ssize_t len;
470
471
for (;;) {
472
int c = *format++;
473
if (c == '(') {
474
if (level == 0)
475
n++;
476
level++;
477
}
478
else if (c == ')') {
479
if (level == 0)
480
break;
481
level--;
482
}
483
else if (c == ':' || c == ';' || c == '\0')
484
break;
485
else if (level == 0 && Py_ISALPHA(c))
486
n++;
487
}
488
489
if (!PySequence_Check(arg) || PyBytes_Check(arg)) {
490
levels[0] = 0;
491
PyOS_snprintf(msgbuf, bufsize,
492
toplevel ? "expected %d arguments, not %.50s" :
493
"must be %d-item sequence, not %.50s",
494
n,
495
arg == Py_None ? "None" : Py_TYPE(arg)->tp_name);
496
return msgbuf;
497
}
498
499
len = PySequence_Size(arg);
500
if (len != n) {
501
levels[0] = 0;
502
if (toplevel) {
503
PyOS_snprintf(msgbuf, bufsize,
504
"expected %d argument%s, not %zd",
505
n,
506
n == 1 ? "" : "s",
507
len);
508
}
509
else {
510
PyOS_snprintf(msgbuf, bufsize,
511
"must be sequence of length %d, not %zd",
512
n, len);
513
}
514
return msgbuf;
515
}
516
517
format = *p_format;
518
for (i = 0; i < n; i++) {
519
const char *msg;
520
PyObject *item;
521
item = PySequence_GetItem(arg, i);
522
if (item == NULL) {
523
PyErr_Clear();
524
levels[0] = i+1;
525
levels[1] = 0;
526
strncpy(msgbuf, "is not retrievable", bufsize);
527
return msgbuf;
528
}
529
msg = convertitem(item, &format, p_va, flags, levels+1,
530
msgbuf, bufsize, freelist);
531
/* PySequence_GetItem calls tp->sq_item, which INCREFs */
532
Py_XDECREF(item);
533
if (msg != NULL) {
534
levels[0] = i+1;
535
return msg;
536
}
537
}
538
539
*p_format = format;
540
return NULL;
541
}
542
543
544
/* Convert a single item. */
545
546
static const char *
547
convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags,
548
int *levels, char *msgbuf, size_t bufsize, freelist_t *freelist)
549
{
550
const char *msg;
551
const char *format = *p_format;
552
553
if (*format == '(' /* ')' */) {
554
format++;
555
msg = converttuple(arg, &format, p_va, flags, levels, msgbuf,
556
bufsize, 0, freelist);
557
if (msg == NULL)
558
format++;
559
}
560
else {
561
msg = convertsimple(arg, &format, p_va, flags,
562
msgbuf, bufsize, freelist);
563
if (msg != NULL)
564
levels[0] = 0;
565
}
566
if (msg == NULL)
567
*p_format = format;
568
return msg;
569
}
570
571
572
573
/* Format an error message generated by convertsimple().
574
displayname must be UTF-8 encoded.
575
*/
576
577
void
578
_PyArg_BadArgument(const char *fname, const char *displayname,
579
const char *expected, PyObject *arg)
580
{
581
PyErr_Format(PyExc_TypeError,
582
"%.200s() %.200s must be %.50s, not %.50s",
583
fname, displayname, expected,
584
arg == Py_None ? "None" : Py_TYPE(arg)->tp_name);
585
}
586
587
static const char *
588
converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
589
{
590
assert(expected != NULL);
591
assert(arg != NULL);
592
if (expected[0] == '(') {
593
PyOS_snprintf(msgbuf, bufsize,
594
"%.100s", expected);
595
}
596
else {
597
PyOS_snprintf(msgbuf, bufsize,
598
"must be %.50s, not %.50s", expected,
599
arg == Py_None ? "None" : Py_TYPE(arg)->tp_name);
600
}
601
return msgbuf;
602
}
603
604
#define CONV_UNICODE "(unicode conversion error)"
605
606
/* Convert a non-tuple argument. Return NULL if conversion went OK,
607
or a string with a message describing the failure. The message is
608
formatted as "must be <desired type>, not <actual type>".
609
When failing, an exception may or may not have been raised.
610
Don't call if a tuple is expected.
611
612
When you add new format codes, please don't forget poor skipitem() below.
613
*/
614
615
static const char *
616
convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
617
char *msgbuf, size_t bufsize, freelist_t *freelist)
618
{
619
#define RETURN_ERR_OCCURRED return msgbuf
620
621
const char *format = *p_format;
622
char c = *format++;
623
const char *sarg;
624
625
switch (c) {
626
627
case 'b': { /* unsigned byte -- very short int */
628
char *p = va_arg(*p_va, char *);
629
long ival = PyLong_AsLong(arg);
630
if (ival == -1 && PyErr_Occurred())
631
RETURN_ERR_OCCURRED;
632
else if (ival < 0) {
633
PyErr_SetString(PyExc_OverflowError,
634
"unsigned byte integer is less than minimum");
635
RETURN_ERR_OCCURRED;
636
}
637
else if (ival > UCHAR_MAX) {
638
PyErr_SetString(PyExc_OverflowError,
639
"unsigned byte integer is greater than maximum");
640
RETURN_ERR_OCCURRED;
641
}
642
else
643
*p = (unsigned char) ival;
644
break;
645
}
646
647
case 'B': {/* byte sized bitfield - both signed and unsigned
648
values allowed */
649
char *p = va_arg(*p_va, char *);
650
unsigned long ival = PyLong_AsUnsignedLongMask(arg);
651
if (ival == (unsigned long)-1 && PyErr_Occurred())
652
RETURN_ERR_OCCURRED;
653
else
654
*p = (unsigned char) ival;
655
break;
656
}
657
658
case 'h': {/* signed short int */
659
short *p = va_arg(*p_va, short *);
660
long ival = PyLong_AsLong(arg);
661
if (ival == -1 && PyErr_Occurred())
662
RETURN_ERR_OCCURRED;
663
else if (ival < SHRT_MIN) {
664
PyErr_SetString(PyExc_OverflowError,
665
"signed short integer is less than minimum");
666
RETURN_ERR_OCCURRED;
667
}
668
else if (ival > SHRT_MAX) {
669
PyErr_SetString(PyExc_OverflowError,
670
"signed short integer is greater than maximum");
671
RETURN_ERR_OCCURRED;
672
}
673
else
674
*p = (short) ival;
675
break;
676
}
677
678
case 'H': { /* short int sized bitfield, both signed and
679
unsigned allowed */
680
unsigned short *p = va_arg(*p_va, unsigned short *);
681
unsigned long ival = PyLong_AsUnsignedLongMask(arg);
682
if (ival == (unsigned long)-1 && PyErr_Occurred())
683
RETURN_ERR_OCCURRED;
684
else
685
*p = (unsigned short) ival;
686
break;
687
}
688
689
case 'i': {/* signed int */
690
int *p = va_arg(*p_va, int *);
691
long ival = PyLong_AsLong(arg);
692
if (ival == -1 && PyErr_Occurred())
693
RETURN_ERR_OCCURRED;
694
else if (ival > INT_MAX) {
695
PyErr_SetString(PyExc_OverflowError,
696
"signed integer is greater than maximum");
697
RETURN_ERR_OCCURRED;
698
}
699
else if (ival < INT_MIN) {
700
PyErr_SetString(PyExc_OverflowError,
701
"signed integer is less than minimum");
702
RETURN_ERR_OCCURRED;
703
}
704
else
705
*p = ival;
706
break;
707
}
708
709
case 'I': { /* int sized bitfield, both signed and
710
unsigned allowed */
711
unsigned int *p = va_arg(*p_va, unsigned int *);
712
unsigned long ival = PyLong_AsUnsignedLongMask(arg);
713
if (ival == (unsigned long)-1 && PyErr_Occurred())
714
RETURN_ERR_OCCURRED;
715
else
716
*p = (unsigned int) ival;
717
break;
718
}
719
720
case 'n': /* Py_ssize_t */
721
{
722
PyObject *iobj;
723
Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
724
Py_ssize_t ival = -1;
725
iobj = _PyNumber_Index(arg);
726
if (iobj != NULL) {
727
ival = PyLong_AsSsize_t(iobj);
728
Py_DECREF(iobj);
729
}
730
if (ival == -1 && PyErr_Occurred())
731
RETURN_ERR_OCCURRED;
732
*p = ival;
733
break;
734
}
735
case 'l': {/* long int */
736
long *p = va_arg(*p_va, long *);
737
long ival = PyLong_AsLong(arg);
738
if (ival == -1 && PyErr_Occurred())
739
RETURN_ERR_OCCURRED;
740
else
741
*p = ival;
742
break;
743
}
744
745
case 'k': { /* long sized bitfield */
746
unsigned long *p = va_arg(*p_va, unsigned long *);
747
unsigned long ival;
748
if (PyLong_Check(arg))
749
ival = PyLong_AsUnsignedLongMask(arg);
750
else
751
return converterr("int", arg, msgbuf, bufsize);
752
*p = ival;
753
break;
754
}
755
756
case 'L': {/* long long */
757
long long *p = va_arg( *p_va, long long * );
758
long long ival = PyLong_AsLongLong(arg);
759
if (ival == (long long)-1 && PyErr_Occurred())
760
RETURN_ERR_OCCURRED;
761
else
762
*p = ival;
763
break;
764
}
765
766
case 'K': { /* long long sized bitfield */
767
unsigned long long *p = va_arg(*p_va, unsigned long long *);
768
unsigned long long ival;
769
if (PyLong_Check(arg))
770
ival = PyLong_AsUnsignedLongLongMask(arg);
771
else
772
return converterr("int", arg, msgbuf, bufsize);
773
*p = ival;
774
break;
775
}
776
777
case 'f': {/* float */
778
float *p = va_arg(*p_va, float *);
779
double dval = PyFloat_AsDouble(arg);
780
if (dval == -1.0 && PyErr_Occurred())
781
RETURN_ERR_OCCURRED;
782
else
783
*p = (float) dval;
784
break;
785
}
786
787
case 'd': {/* double */
788
double *p = va_arg(*p_va, double *);
789
double dval = PyFloat_AsDouble(arg);
790
if (dval == -1.0 && PyErr_Occurred())
791
RETURN_ERR_OCCURRED;
792
else
793
*p = dval;
794
break;
795
}
796
797
case 'D': {/* complex double */
798
Py_complex *p = va_arg(*p_va, Py_complex *);
799
Py_complex cval;
800
cval = PyComplex_AsCComplex(arg);
801
if (PyErr_Occurred())
802
RETURN_ERR_OCCURRED;
803
else
804
*p = cval;
805
break;
806
}
807
808
case 'c': {/* char */
809
char *p = va_arg(*p_va, char *);
810
if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1)
811
*p = PyBytes_AS_STRING(arg)[0];
812
else if (PyByteArray_Check(arg) && PyByteArray_Size(arg) == 1)
813
*p = PyByteArray_AS_STRING(arg)[0];
814
else
815
return converterr("a byte string of length 1", arg, msgbuf, bufsize);
816
break;
817
}
818
819
case 'C': {/* unicode char */
820
int *p = va_arg(*p_va, int *);
821
int kind;
822
const void *data;
823
824
if (!PyUnicode_Check(arg))
825
return converterr("a unicode character", arg, msgbuf, bufsize);
826
827
if (PyUnicode_GET_LENGTH(arg) != 1)
828
return converterr("a unicode character", arg, msgbuf, bufsize);
829
830
kind = PyUnicode_KIND(arg);
831
data = PyUnicode_DATA(arg);
832
*p = PyUnicode_READ(kind, data, 0);
833
break;
834
}
835
836
case 'p': {/* boolean *p*redicate */
837
int *p = va_arg(*p_va, int *);
838
int val = PyObject_IsTrue(arg);
839
if (val > 0)
840
*p = 1;
841
else if (val == 0)
842
*p = 0;
843
else
844
RETURN_ERR_OCCURRED;
845
break;
846
}
847
848
/* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w' codes all
849
need to be cleaned up! */
850
851
case 'y': {/* any bytes-like object */
852
void **p = (void **)va_arg(*p_va, char **);
853
const char *buf;
854
Py_ssize_t count;
855
if (*format == '*') {
856
if (getbuffer(arg, (Py_buffer*)p, &buf) < 0)
857
return converterr(buf, arg, msgbuf, bufsize);
858
format++;
859
if (addcleanup(p, freelist, cleanup_buffer)) {
860
return converterr(
861
"(cleanup problem)",
862
arg, msgbuf, bufsize);
863
}
864
break;
865
}
866
count = convertbuffer(arg, (const void **)p, &buf);
867
if (count < 0)
868
return converterr(buf, arg, msgbuf, bufsize);
869
if (*format == '#') {
870
Py_ssize_t *psize = va_arg(*p_va, Py_ssize_t*);
871
*psize = count;
872
format++;
873
} else {
874
if (strlen(*p) != (size_t)count) {
875
PyErr_SetString(PyExc_ValueError, "embedded null byte");
876
RETURN_ERR_OCCURRED;
877
}
878
}
879
break;
880
}
881
882
case 's': /* text string or bytes-like object */
883
case 'z': /* text string, bytes-like object or None */
884
{
885
if (*format == '*') {
886
/* "s*" or "z*" */
887
Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
888
889
if (c == 'z' && arg == Py_None)
890
PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
891
else if (PyUnicode_Check(arg)) {
892
Py_ssize_t len;
893
sarg = PyUnicode_AsUTF8AndSize(arg, &len);
894
if (sarg == NULL)
895
return converterr(CONV_UNICODE,
896
arg, msgbuf, bufsize);
897
PyBuffer_FillInfo(p, arg, (void *)sarg, len, 1, 0);
898
}
899
else { /* any bytes-like object */
900
const char *buf;
901
if (getbuffer(arg, p, &buf) < 0)
902
return converterr(buf, arg, msgbuf, bufsize);
903
}
904
if (addcleanup(p, freelist, cleanup_buffer)) {
905
return converterr(
906
"(cleanup problem)",
907
arg, msgbuf, bufsize);
908
}
909
format++;
910
} else if (*format == '#') { /* a string or read-only bytes-like object */
911
/* "s#" or "z#" */
912
const void **p = (const void **)va_arg(*p_va, const char **);
913
Py_ssize_t *psize = va_arg(*p_va, Py_ssize_t*);
914
915
if (c == 'z' && arg == Py_None) {
916
*p = NULL;
917
*psize = 0;
918
}
919
else if (PyUnicode_Check(arg)) {
920
Py_ssize_t len;
921
sarg = PyUnicode_AsUTF8AndSize(arg, &len);
922
if (sarg == NULL)
923
return converterr(CONV_UNICODE,
924
arg, msgbuf, bufsize);
925
*p = sarg;
926
*psize = len;
927
}
928
else { /* read-only bytes-like object */
929
/* XXX Really? */
930
const char *buf;
931
Py_ssize_t count = convertbuffer(arg, p, &buf);
932
if (count < 0)
933
return converterr(buf, arg, msgbuf, bufsize);
934
*psize = count;
935
}
936
format++;
937
} else {
938
/* "s" or "z" */
939
const char **p = va_arg(*p_va, const char **);
940
Py_ssize_t len;
941
sarg = NULL;
942
943
if (c == 'z' && arg == Py_None)
944
*p = NULL;
945
else if (PyUnicode_Check(arg)) {
946
sarg = PyUnicode_AsUTF8AndSize(arg, &len);
947
if (sarg == NULL)
948
return converterr(CONV_UNICODE,
949
arg, msgbuf, bufsize);
950
if (strlen(sarg) != (size_t)len) {
951
PyErr_SetString(PyExc_ValueError, "embedded null character");
952
RETURN_ERR_OCCURRED;
953
}
954
*p = sarg;
955
}
956
else
957
return converterr(c == 'z' ? "str or None" : "str",
958
arg, msgbuf, bufsize);
959
}
960
break;
961
}
962
963
case 'e': {/* encoded string */
964
char **buffer;
965
const char *encoding;
966
PyObject *s;
967
int recode_strings;
968
Py_ssize_t size;
969
const char *ptr;
970
971
/* Get 'e' parameter: the encoding name */
972
encoding = (const char *)va_arg(*p_va, const char *);
973
if (encoding == NULL)
974
encoding = PyUnicode_GetDefaultEncoding();
975
976
/* Get output buffer parameter:
977
's' (recode all objects via Unicode) or
978
't' (only recode non-string objects)
979
*/
980
if (*format == 's')
981
recode_strings = 1;
982
else if (*format == 't')
983
recode_strings = 0;
984
else
985
return converterr(
986
"(unknown parser marker combination)",
987
arg, msgbuf, bufsize);
988
buffer = (char **)va_arg(*p_va, char **);
989
format++;
990
if (buffer == NULL)
991
return converterr("(buffer is NULL)",
992
arg, msgbuf, bufsize);
993
994
/* Encode object */
995
if (!recode_strings &&
996
(PyBytes_Check(arg) || PyByteArray_Check(arg))) {
997
s = Py_NewRef(arg);
998
if (PyBytes_Check(arg)) {
999
size = PyBytes_GET_SIZE(s);
1000
ptr = PyBytes_AS_STRING(s);
1001
}
1002
else {
1003
size = PyByteArray_GET_SIZE(s);
1004
ptr = PyByteArray_AS_STRING(s);
1005
}
1006
}
1007
else if (PyUnicode_Check(arg)) {
1008
/* Encode object; use default error handling */
1009
s = PyUnicode_AsEncodedString(arg,
1010
encoding,
1011
NULL);
1012
if (s == NULL)
1013
return converterr("(encoding failed)",
1014
arg, msgbuf, bufsize);
1015
assert(PyBytes_Check(s));
1016
size = PyBytes_GET_SIZE(s);
1017
ptr = PyBytes_AS_STRING(s);
1018
if (ptr == NULL)
1019
ptr = "";
1020
}
1021
else {
1022
return converterr(
1023
recode_strings ? "str" : "str, bytes or bytearray",
1024
arg, msgbuf, bufsize);
1025
}
1026
1027
/* Write output; output is guaranteed to be 0-terminated */
1028
if (*format == '#') {
1029
/* Using buffer length parameter '#':
1030
1031
- if *buffer is NULL, a new buffer of the
1032
needed size is allocated and the data
1033
copied into it; *buffer is updated to point
1034
to the new buffer; the caller is
1035
responsible for PyMem_Free()ing it after
1036
usage
1037
1038
- if *buffer is not NULL, the data is
1039
copied to *buffer; *buffer_len has to be
1040
set to the size of the buffer on input;
1041
buffer overflow is signalled with an error;
1042
buffer has to provide enough room for the
1043
encoded string plus the trailing 0-byte
1044
1045
- in both cases, *buffer_len is updated to
1046
the size of the buffer /excluding/ the
1047
trailing 0-byte
1048
1049
*/
1050
Py_ssize_t *psize = va_arg(*p_va, Py_ssize_t*);
1051
1052
format++;
1053
if (psize == NULL) {
1054
Py_DECREF(s);
1055
return converterr(
1056
"(buffer_len is NULL)",
1057
arg, msgbuf, bufsize);
1058
}
1059
if (*buffer == NULL) {
1060
*buffer = PyMem_NEW(char, size + 1);
1061
if (*buffer == NULL) {
1062
Py_DECREF(s);
1063
PyErr_NoMemory();
1064
RETURN_ERR_OCCURRED;
1065
}
1066
if (addcleanup(buffer, freelist, cleanup_ptr)) {
1067
Py_DECREF(s);
1068
return converterr(
1069
"(cleanup problem)",
1070
arg, msgbuf, bufsize);
1071
}
1072
} else {
1073
if (size + 1 > *psize) {
1074
Py_DECREF(s);
1075
PyErr_Format(PyExc_ValueError,
1076
"encoded string too long "
1077
"(%zd, maximum length %zd)",
1078
(Py_ssize_t)size, (Py_ssize_t)(*psize - 1));
1079
RETURN_ERR_OCCURRED;
1080
}
1081
}
1082
memcpy(*buffer, ptr, size+1);
1083
1084
*psize = size;
1085
}
1086
else {
1087
/* Using a 0-terminated buffer:
1088
1089
- the encoded string has to be 0-terminated
1090
for this variant to work; if it is not, an
1091
error raised
1092
1093
- a new buffer of the needed size is
1094
allocated and the data copied into it;
1095
*buffer is updated to point to the new
1096
buffer; the caller is responsible for
1097
PyMem_Free()ing it after usage
1098
1099
*/
1100
if ((Py_ssize_t)strlen(ptr) != size) {
1101
Py_DECREF(s);
1102
return converterr(
1103
"encoded string without null bytes",
1104
arg, msgbuf, bufsize);
1105
}
1106
*buffer = PyMem_NEW(char, size + 1);
1107
if (*buffer == NULL) {
1108
Py_DECREF(s);
1109
PyErr_NoMemory();
1110
RETURN_ERR_OCCURRED;
1111
}
1112
if (addcleanup(buffer, freelist, cleanup_ptr)) {
1113
Py_DECREF(s);
1114
return converterr("(cleanup problem)",
1115
arg, msgbuf, bufsize);
1116
}
1117
memcpy(*buffer, ptr, size+1);
1118
}
1119
Py_DECREF(s);
1120
break;
1121
}
1122
1123
case 'S': { /* PyBytes object */
1124
PyObject **p = va_arg(*p_va, PyObject **);
1125
if (PyBytes_Check(arg))
1126
*p = arg;
1127
else
1128
return converterr("bytes", arg, msgbuf, bufsize);
1129
break;
1130
}
1131
1132
case 'Y': { /* PyByteArray object */
1133
PyObject **p = va_arg(*p_va, PyObject **);
1134
if (PyByteArray_Check(arg))
1135
*p = arg;
1136
else
1137
return converterr("bytearray", arg, msgbuf, bufsize);
1138
break;
1139
}
1140
1141
case 'U': { /* PyUnicode object */
1142
PyObject **p = va_arg(*p_va, PyObject **);
1143
if (PyUnicode_Check(arg)) {
1144
*p = arg;
1145
}
1146
else
1147
return converterr("str", arg, msgbuf, bufsize);
1148
break;
1149
}
1150
1151
case 'O': { /* object */
1152
PyTypeObject *type;
1153
PyObject **p;
1154
if (*format == '!') {
1155
type = va_arg(*p_va, PyTypeObject*);
1156
p = va_arg(*p_va, PyObject **);
1157
format++;
1158
if (PyType_IsSubtype(Py_TYPE(arg), type))
1159
*p = arg;
1160
else
1161
return converterr(type->tp_name, arg, msgbuf, bufsize);
1162
1163
}
1164
else if (*format == '&') {
1165
typedef int (*converter)(PyObject *, void *);
1166
converter convert = va_arg(*p_va, converter);
1167
void *addr = va_arg(*p_va, void *);
1168
int res;
1169
format++;
1170
if (! (res = (*convert)(arg, addr)))
1171
return converterr("(unspecified)",
1172
arg, msgbuf, bufsize);
1173
if (res == Py_CLEANUP_SUPPORTED &&
1174
addcleanup(addr, freelist, convert) == -1)
1175
return converterr("(cleanup problem)",
1176
arg, msgbuf, bufsize);
1177
}
1178
else {
1179
p = va_arg(*p_va, PyObject **);
1180
*p = arg;
1181
}
1182
break;
1183
}
1184
1185
1186
case 'w': { /* "w*": memory buffer, read-write access */
1187
void **p = va_arg(*p_va, void **);
1188
1189
if (*format != '*')
1190
return converterr(
1191
"(invalid use of 'w' format character)",
1192
arg, msgbuf, bufsize);
1193
format++;
1194
1195
/* Caller is interested in Py_buffer, and the object
1196
supports it directly. */
1197
if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
1198
PyErr_Clear();
1199
return converterr("read-write bytes-like object",
1200
arg, msgbuf, bufsize);
1201
}
1202
if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) {
1203
PyBuffer_Release((Py_buffer*)p);
1204
return converterr("contiguous buffer", arg, msgbuf, bufsize);
1205
}
1206
if (addcleanup(p, freelist, cleanup_buffer)) {
1207
return converterr(
1208
"(cleanup problem)",
1209
arg, msgbuf, bufsize);
1210
}
1211
break;
1212
}
1213
1214
default:
1215
return converterr("(impossible<bad format char>)", arg, msgbuf, bufsize);
1216
1217
}
1218
1219
*p_format = format;
1220
return NULL;
1221
1222
#undef RETURN_ERR_OCCURRED
1223
}
1224
1225
static Py_ssize_t
1226
convertbuffer(PyObject *arg, const void **p, const char **errmsg)
1227
{
1228
PyBufferProcs *pb = Py_TYPE(arg)->tp_as_buffer;
1229
Py_ssize_t count;
1230
Py_buffer view;
1231
1232
*errmsg = NULL;
1233
*p = NULL;
1234
if (pb != NULL && pb->bf_releasebuffer != NULL) {
1235
*errmsg = "read-only bytes-like object";
1236
return -1;
1237
}
1238
1239
if (getbuffer(arg, &view, errmsg) < 0)
1240
return -1;
1241
count = view.len;
1242
*p = view.buf;
1243
PyBuffer_Release(&view);
1244
return count;
1245
}
1246
1247
static int
1248
getbuffer(PyObject *arg, Py_buffer *view, const char **errmsg)
1249
{
1250
if (PyObject_GetBuffer(arg, view, PyBUF_SIMPLE) != 0) {
1251
*errmsg = "bytes-like object";
1252
return -1;
1253
}
1254
if (!PyBuffer_IsContiguous(view, 'C')) {
1255
PyBuffer_Release(view);
1256
*errmsg = "contiguous buffer";
1257
return -1;
1258
}
1259
return 0;
1260
}
1261
1262
/* Support for keyword arguments donated by
1263
Geoff Philbrick <[email protected]> */
1264
1265
/* Return false (0) for error, else true. */
1266
int
1267
PyArg_ParseTupleAndKeywords(PyObject *args,
1268
PyObject *keywords,
1269
const char *format,
1270
char **kwlist, ...)
1271
{
1272
int retval;
1273
va_list va;
1274
1275
if ((args == NULL || !PyTuple_Check(args)) ||
1276
(keywords != NULL && !PyDict_Check(keywords)) ||
1277
format == NULL ||
1278
kwlist == NULL)
1279
{
1280
PyErr_BadInternalCall();
1281
return 0;
1282
}
1283
1284
va_start(va, kwlist);
1285
retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
1286
va_end(va);
1287
return retval;
1288
}
1289
1290
int
1291
_PyArg_ParseTupleAndKeywords_SizeT(PyObject *args,
1292
PyObject *keywords,
1293
const char *format,
1294
char **kwlist, ...)
1295
{
1296
int retval;
1297
va_list va;
1298
1299
if ((args == NULL || !PyTuple_Check(args)) ||
1300
(keywords != NULL && !PyDict_Check(keywords)) ||
1301
format == NULL ||
1302
kwlist == NULL)
1303
{
1304
PyErr_BadInternalCall();
1305
return 0;
1306
}
1307
1308
va_start(va, kwlist);
1309
retval = vgetargskeywords(args, keywords, format,
1310
kwlist, &va, 0);
1311
va_end(va);
1312
return retval;
1313
}
1314
1315
1316
int
1317
PyArg_VaParseTupleAndKeywords(PyObject *args,
1318
PyObject *keywords,
1319
const char *format,
1320
char **kwlist, va_list va)
1321
{
1322
int retval;
1323
va_list lva;
1324
1325
if ((args == NULL || !PyTuple_Check(args)) ||
1326
(keywords != NULL && !PyDict_Check(keywords)) ||
1327
format == NULL ||
1328
kwlist == NULL)
1329
{
1330
PyErr_BadInternalCall();
1331
return 0;
1332
}
1333
1334
va_copy(lva, va);
1335
1336
retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
1337
va_end(lva);
1338
return retval;
1339
}
1340
1341
int
1342
_PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args,
1343
PyObject *keywords,
1344
const char *format,
1345
char **kwlist, va_list va)
1346
{
1347
int retval;
1348
va_list lva;
1349
1350
if ((args == NULL || !PyTuple_Check(args)) ||
1351
(keywords != NULL && !PyDict_Check(keywords)) ||
1352
format == NULL ||
1353
kwlist == NULL)
1354
{
1355
PyErr_BadInternalCall();
1356
return 0;
1357
}
1358
1359
va_copy(lva, va);
1360
1361
retval = vgetargskeywords(args, keywords, format,
1362
kwlist, &lva, 0);
1363
va_end(lva);
1364
return retval;
1365
}
1366
1367
PyAPI_FUNC(int)
1368
_PyArg_ParseTupleAndKeywordsFast(PyObject *args, PyObject *keywords,
1369
struct _PyArg_Parser *parser, ...)
1370
{
1371
int retval;
1372
va_list va;
1373
1374
va_start(va, parser);
1375
retval = vgetargskeywordsfast(args, keywords, parser, &va, 0);
1376
va_end(va);
1377
return retval;
1378
}
1379
1380
int
1381
_PyArg_ParseTupleAndKeywordsFast_SizeT(PyObject *args, PyObject *keywords,
1382
struct _PyArg_Parser *parser, ...)
1383
{
1384
int retval;
1385
va_list va;
1386
1387
va_start(va, parser);
1388
retval = vgetargskeywordsfast(args, keywords, parser, &va, 0);
1389
va_end(va);
1390
return retval;
1391
}
1392
1393
int
1394
_PyArg_ParseStackAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
1395
struct _PyArg_Parser *parser, ...)
1396
{
1397
int retval;
1398
va_list va;
1399
1400
va_start(va, parser);
1401
retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, 0);
1402
va_end(va);
1403
return retval;
1404
}
1405
1406
int
1407
_PyArg_ParseStackAndKeywords_SizeT(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,
1408
struct _PyArg_Parser *parser, ...)
1409
{
1410
int retval;
1411
va_list va;
1412
1413
va_start(va, parser);
1414
retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va, 0);
1415
va_end(va);
1416
return retval;
1417
}
1418
1419
1420
PyAPI_FUNC(int)
1421
_PyArg_VaParseTupleAndKeywordsFast(PyObject *args, PyObject *keywords,
1422
struct _PyArg_Parser *parser, va_list va)
1423
{
1424
int retval;
1425
va_list lva;
1426
1427
va_copy(lva, va);
1428
1429
retval = vgetargskeywordsfast(args, keywords, parser, &lva, 0);
1430
va_end(lva);
1431
return retval;
1432
}
1433
1434
static void
1435
error_unexpected_keyword_arg(PyObject *kwargs, PyObject *kwnames, PyObject *kwtuple, const char *fname)
1436
{
1437
/* make sure there are no extraneous keyword arguments */
1438
Py_ssize_t j = 0;
1439
while (1) {
1440
PyObject *keyword;
1441
if (kwargs != NULL) {
1442
if (!PyDict_Next(kwargs, &j, &keyword, NULL))
1443
break;
1444
}
1445
else {
1446
if (j >= PyTuple_GET_SIZE(kwnames))
1447
break;
1448
keyword = PyTuple_GET_ITEM(kwnames, j);
1449
j++;
1450
}
1451
if (!PyUnicode_Check(keyword)) {
1452
PyErr_SetString(PyExc_TypeError,
1453
"keywords must be strings");
1454
return;
1455
}
1456
1457
int match = PySequence_Contains(kwtuple, keyword);
1458
if (match <= 0) {
1459
if (!match) {
1460
PyErr_Format(PyExc_TypeError,
1461
"'%S' is an invalid keyword "
1462
"argument for %.200s%s",
1463
keyword,
1464
(fname == NULL) ? "this function" : fname,
1465
(fname == NULL) ? "" : "()");
1466
}
1467
return;
1468
}
1469
}
1470
/* Something wrong happened. There are extraneous keyword arguments,
1471
* but we don't know what. And we don't bother. */
1472
PyErr_Format(PyExc_TypeError,
1473
"invalid keyword argument for %.200s%s",
1474
(fname == NULL) ? "this function" : fname,
1475
(fname == NULL) ? "" : "()");
1476
}
1477
1478
int
1479
PyArg_ValidateKeywordArguments(PyObject *kwargs)
1480
{
1481
if (!PyDict_Check(kwargs)) {
1482
PyErr_BadInternalCall();
1483
return 0;
1484
}
1485
if (!_PyDict_HasOnlyStringKeys(kwargs)) {
1486
PyErr_SetString(PyExc_TypeError,
1487
"keywords must be strings");
1488
return 0;
1489
}
1490
return 1;
1491
}
1492
1493
#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')
1494
1495
static int
1496
vgetargskeywords(PyObject *args, PyObject *kwargs, const char *format,
1497
char **kwlist, va_list *p_va, int flags)
1498
{
1499
char msgbuf[512];
1500
int levels[32];
1501
const char *fname, *msg, *custom_msg;
1502
int min = INT_MAX;
1503
int max = INT_MAX;
1504
int i, pos, len;
1505
int skip = 0;
1506
Py_ssize_t nargs, nkwargs;
1507
PyObject *current_arg;
1508
freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
1509
freelist_t freelist;
1510
1511
freelist.entries = static_entries;
1512
freelist.first_available = 0;
1513
freelist.entries_malloced = 0;
1514
1515
assert(args != NULL && PyTuple_Check(args));
1516
assert(kwargs == NULL || PyDict_Check(kwargs));
1517
assert(format != NULL);
1518
assert(kwlist != NULL);
1519
assert(p_va != NULL);
1520
1521
/* grab the function name or custom error msg first (mutually exclusive) */
1522
fname = strchr(format, ':');
1523
if (fname) {
1524
fname++;
1525
custom_msg = NULL;
1526
}
1527
else {
1528
custom_msg = strchr(format,';');
1529
if (custom_msg)
1530
custom_msg++;
1531
}
1532
1533
/* scan kwlist and count the number of positional-only parameters */
1534
for (pos = 0; kwlist[pos] && !*kwlist[pos]; pos++) {
1535
}
1536
/* scan kwlist and get greatest possible nbr of args */
1537
for (len = pos; kwlist[len]; len++) {
1538
if (!*kwlist[len]) {
1539
PyErr_SetString(PyExc_SystemError,
1540
"Empty keyword parameter name");
1541
return cleanreturn(0, &freelist);
1542
}
1543
}
1544
1545
if (len > STATIC_FREELIST_ENTRIES) {
1546
freelist.entries = PyMem_NEW(freelistentry_t, len);
1547
if (freelist.entries == NULL) {
1548
PyErr_NoMemory();
1549
return 0;
1550
}
1551
freelist.entries_malloced = 1;
1552
}
1553
1554
nargs = PyTuple_GET_SIZE(args);
1555
nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);
1556
if (nargs + nkwargs > len) {
1557
/* Adding "keyword" (when nargs == 0) prevents producing wrong error
1558
messages in some special cases (see bpo-31229). */
1559
PyErr_Format(PyExc_TypeError,
1560
"%.200s%s takes at most %d %sargument%s (%zd given)",
1561
(fname == NULL) ? "function" : fname,
1562
(fname == NULL) ? "" : "()",
1563
len,
1564
(nargs == 0) ? "keyword " : "",
1565
(len == 1) ? "" : "s",
1566
nargs + nkwargs);
1567
return cleanreturn(0, &freelist);
1568
}
1569
1570
/* convert tuple args and keyword args in same loop, using kwlist to drive process */
1571
for (i = 0; i < len; i++) {
1572
if (*format == '|') {
1573
if (min != INT_MAX) {
1574
PyErr_SetString(PyExc_SystemError,
1575
"Invalid format string (| specified twice)");
1576
return cleanreturn(0, &freelist);
1577
}
1578
1579
min = i;
1580
format++;
1581
1582
if (max != INT_MAX) {
1583
PyErr_SetString(PyExc_SystemError,
1584
"Invalid format string ($ before |)");
1585
return cleanreturn(0, &freelist);
1586
}
1587
}
1588
if (*format == '$') {
1589
if (max != INT_MAX) {
1590
PyErr_SetString(PyExc_SystemError,
1591
"Invalid format string ($ specified twice)");
1592
return cleanreturn(0, &freelist);
1593
}
1594
1595
max = i;
1596
format++;
1597
1598
if (max < pos) {
1599
PyErr_SetString(PyExc_SystemError,
1600
"Empty parameter name after $");
1601
return cleanreturn(0, &freelist);
1602
}
1603
if (skip) {
1604
/* Now we know the minimal and the maximal numbers of
1605
* positional arguments and can raise an exception with
1606
* informative message (see below). */
1607
break;
1608
}
1609
if (max < nargs) {
1610
if (max == 0) {
1611
PyErr_Format(PyExc_TypeError,
1612
"%.200s%s takes no positional arguments",
1613
(fname == NULL) ? "function" : fname,
1614
(fname == NULL) ? "" : "()");
1615
}
1616
else {
1617
PyErr_Format(PyExc_TypeError,
1618
"%.200s%s takes %s %d positional argument%s"
1619
" (%zd given)",
1620
(fname == NULL) ? "function" : fname,
1621
(fname == NULL) ? "" : "()",
1622
(min != INT_MAX) ? "at most" : "exactly",
1623
max,
1624
max == 1 ? "" : "s",
1625
nargs);
1626
}
1627
return cleanreturn(0, &freelist);
1628
}
1629
}
1630
if (IS_END_OF_FORMAT(*format)) {
1631
PyErr_Format(PyExc_SystemError,
1632
"More keyword list entries (%d) than "
1633
"format specifiers (%d)", len, i);
1634
return cleanreturn(0, &freelist);
1635
}
1636
if (!skip) {
1637
if (i < nargs) {
1638
current_arg = PyTuple_GET_ITEM(args, i);
1639
}
1640
else if (nkwargs && i >= pos) {
1641
current_arg = _PyDict_GetItemStringWithError(kwargs, kwlist[i]);
1642
if (current_arg) {
1643
--nkwargs;
1644
}
1645
else if (PyErr_Occurred()) {
1646
return cleanreturn(0, &freelist);
1647
}
1648
}
1649
else {
1650
current_arg = NULL;
1651
}
1652
1653
if (current_arg) {
1654
msg = convertitem(current_arg, &format, p_va, flags,
1655
levels, msgbuf, sizeof(msgbuf), &freelist);
1656
if (msg) {
1657
seterror(i+1, msg, levels, fname, custom_msg);
1658
return cleanreturn(0, &freelist);
1659
}
1660
continue;
1661
}
1662
1663
if (i < min) {
1664
if (i < pos) {
1665
assert (min == INT_MAX);
1666
assert (max == INT_MAX);
1667
skip = 1;
1668
/* At that moment we still don't know the minimal and
1669
* the maximal numbers of positional arguments. Raising
1670
* an exception is deferred until we encounter | and $
1671
* or the end of the format. */
1672
}
1673
else {
1674
PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
1675
"argument '%s' (pos %d)",
1676
(fname == NULL) ? "function" : fname,
1677
(fname == NULL) ? "" : "()",
1678
kwlist[i], i+1);
1679
return cleanreturn(0, &freelist);
1680
}
1681
}
1682
/* current code reports success when all required args
1683
* fulfilled and no keyword args left, with no further
1684
* validation. XXX Maybe skip this in debug build ?
1685
*/
1686
if (!nkwargs && !skip) {
1687
return cleanreturn(1, &freelist);
1688
}
1689
}
1690
1691
/* We are into optional args, skip through to any remaining
1692
* keyword args */
1693
msg = skipitem(&format, p_va, flags);
1694
if (msg) {
1695
PyErr_Format(PyExc_SystemError, "%s: '%s'", msg,
1696
format);
1697
return cleanreturn(0, &freelist);
1698
}
1699
}
1700
1701
if (skip) {
1702
PyErr_Format(PyExc_TypeError,
1703
"%.200s%s takes %s %d positional argument%s"
1704
" (%zd given)",
1705
(fname == NULL) ? "function" : fname,
1706
(fname == NULL) ? "" : "()",
1707
(Py_MIN(pos, min) < i) ? "at least" : "exactly",
1708
Py_MIN(pos, min),
1709
Py_MIN(pos, min) == 1 ? "" : "s",
1710
nargs);
1711
return cleanreturn(0, &freelist);
1712
}
1713
1714
if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {
1715
PyErr_Format(PyExc_SystemError,
1716
"more argument specifiers than keyword list entries "
1717
"(remaining format:'%s')", format);
1718
return cleanreturn(0, &freelist);
1719
}
1720
1721
if (nkwargs > 0) {
1722
PyObject *key;
1723
Py_ssize_t j;
1724
/* make sure there are no arguments given by name and position */
1725
for (i = pos; i < nargs; i++) {
1726
current_arg = _PyDict_GetItemStringWithError(kwargs, kwlist[i]);
1727
if (current_arg) {
1728
/* arg present in tuple and in dict */
1729
PyErr_Format(PyExc_TypeError,
1730
"argument for %.200s%s given by name ('%s') "
1731
"and position (%d)",
1732
(fname == NULL) ? "function" : fname,
1733
(fname == NULL) ? "" : "()",
1734
kwlist[i], i+1);
1735
return cleanreturn(0, &freelist);
1736
}
1737
else if (PyErr_Occurred()) {
1738
return cleanreturn(0, &freelist);
1739
}
1740
}
1741
/* make sure there are no extraneous keyword arguments */
1742
j = 0;
1743
while (PyDict_Next(kwargs, &j, &key, NULL)) {
1744
int match = 0;
1745
if (!PyUnicode_Check(key)) {
1746
PyErr_SetString(PyExc_TypeError,
1747
"keywords must be strings");
1748
return cleanreturn(0, &freelist);
1749
}
1750
for (i = pos; i < len; i++) {
1751
if (_PyUnicode_EqualToASCIIString(key, kwlist[i])) {
1752
match = 1;
1753
break;
1754
}
1755
}
1756
if (!match) {
1757
PyErr_Format(PyExc_TypeError,
1758
"'%U' is an invalid keyword "
1759
"argument for %.200s%s",
1760
key,
1761
(fname == NULL) ? "this function" : fname,
1762
(fname == NULL) ? "" : "()");
1763
return cleanreturn(0, &freelist);
1764
}
1765
}
1766
/* Something wrong happened. There are extraneous keyword arguments,
1767
* but we don't know what. And we don't bother. */
1768
PyErr_Format(PyExc_TypeError,
1769
"invalid keyword argument for %.200s%s",
1770
(fname == NULL) ? "this function" : fname,
1771
(fname == NULL) ? "" : "()");
1772
return cleanreturn(0, &freelist);
1773
}
1774
1775
return cleanreturn(1, &freelist);
1776
}
1777
1778
1779
static int
1780
scan_keywords(const char * const *keywords, int *ptotal, int *pposonly)
1781
{
1782
/* scan keywords and count the number of positional-only parameters */
1783
int i;
1784
for (i = 0; keywords[i] && !*keywords[i]; i++) {
1785
}
1786
*pposonly = i;
1787
1788
/* scan keywords and get greatest possible nbr of args */
1789
for (; keywords[i]; i++) {
1790
if (!*keywords[i]) {
1791
PyErr_SetString(PyExc_SystemError,
1792
"Empty keyword parameter name");
1793
return -1;
1794
}
1795
}
1796
*ptotal = i;
1797
return 0;
1798
}
1799
1800
static int
1801
parse_format(const char *format, int total, int npos,
1802
const char **pfname, const char **pcustommsg,
1803
int *pmin, int *pmax)
1804
{
1805
/* grab the function name or custom error msg first (mutually exclusive) */
1806
const char *custommsg;
1807
const char *fname = strchr(format, ':');
1808
if (fname) {
1809
fname++;
1810
custommsg = NULL;
1811
}
1812
else {
1813
custommsg = strchr(format,';');
1814
if (custommsg) {
1815
custommsg++;
1816
}
1817
}
1818
1819
int min = INT_MAX;
1820
int max = INT_MAX;
1821
for (int i = 0; i < total; i++) {
1822
if (*format == '|') {
1823
if (min != INT_MAX) {
1824
PyErr_SetString(PyExc_SystemError,
1825
"Invalid format string (| specified twice)");
1826
return -1;
1827
}
1828
if (max != INT_MAX) {
1829
PyErr_SetString(PyExc_SystemError,
1830
"Invalid format string ($ before |)");
1831
return -1;
1832
}
1833
min = i;
1834
format++;
1835
}
1836
if (*format == '$') {
1837
if (max != INT_MAX) {
1838
PyErr_SetString(PyExc_SystemError,
1839
"Invalid format string ($ specified twice)");
1840
return -1;
1841
}
1842
if (i < npos) {
1843
PyErr_SetString(PyExc_SystemError,
1844
"Empty parameter name after $");
1845
return -1;
1846
}
1847
max = i;
1848
format++;
1849
}
1850
if (IS_END_OF_FORMAT(*format)) {
1851
PyErr_Format(PyExc_SystemError,
1852
"More keyword list entries (%d) than "
1853
"format specifiers (%d)", total, i);
1854
return -1;
1855
}
1856
1857
const char *msg = skipitem(&format, NULL, 0);
1858
if (msg) {
1859
PyErr_Format(PyExc_SystemError, "%s: '%s'", msg,
1860
format);
1861
return -1;
1862
}
1863
}
1864
min = Py_MIN(min, total);
1865
max = Py_MIN(max, total);
1866
1867
if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {
1868
PyErr_Format(PyExc_SystemError,
1869
"more argument specifiers than keyword list entries "
1870
"(remaining format:'%s')", format);
1871
return -1;
1872
}
1873
1874
*pfname = fname;
1875
*pcustommsg = custommsg;
1876
*pmin = min;
1877
*pmax = max;
1878
return 0;
1879
}
1880
1881
static PyObject *
1882
new_kwtuple(const char * const *keywords, int total, int pos)
1883
{
1884
int nkw = total - pos;
1885
PyObject *kwtuple = PyTuple_New(nkw);
1886
if (kwtuple == NULL) {
1887
return NULL;
1888
}
1889
keywords += pos;
1890
for (int i = 0; i < nkw; i++) {
1891
PyObject *str = PyUnicode_FromString(keywords[i]);
1892
if (str == NULL) {
1893
Py_DECREF(kwtuple);
1894
return NULL;
1895
}
1896
PyUnicode_InternInPlace(&str);
1897
PyTuple_SET_ITEM(kwtuple, i, str);
1898
}
1899
return kwtuple;
1900
}
1901
1902
static int
1903
_parser_init(struct _PyArg_Parser *parser)
1904
{
1905
const char * const *keywords = parser->keywords;
1906
assert(keywords != NULL);
1907
assert(parser->pos == 0 &&
1908
(parser->format == NULL || parser->fname == NULL) &&
1909
parser->custom_msg == NULL &&
1910
parser->min == 0 &&
1911
parser->max == 0);
1912
1913
int len, pos;
1914
if (scan_keywords(keywords, &len, &pos) < 0) {
1915
return 0;
1916
}
1917
1918
const char *fname, *custommsg = NULL;
1919
int min = 0, max = 0;
1920
if (parser->format) {
1921
assert(parser->fname == NULL);
1922
if (parse_format(parser->format, len, pos,
1923
&fname, &custommsg, &min, &max) < 0) {
1924
return 0;
1925
}
1926
}
1927
else {
1928
assert(parser->fname != NULL);
1929
fname = parser->fname;
1930
}
1931
1932
int owned;
1933
PyObject *kwtuple = parser->kwtuple;
1934
if (kwtuple == NULL) {
1935
kwtuple = new_kwtuple(keywords, len, pos);
1936
if (kwtuple == NULL) {
1937
return 0;
1938
}
1939
owned = 1;
1940
}
1941
else {
1942
owned = 0;
1943
}
1944
1945
parser->pos = pos;
1946
parser->fname = fname;
1947
parser->custom_msg = custommsg;
1948
parser->min = min;
1949
parser->max = max;
1950
parser->kwtuple = kwtuple;
1951
parser->initialized = owned ? 1 : -1;
1952
1953
assert(parser->next == NULL);
1954
parser->next = _PyRuntime.getargs.static_parsers;
1955
_PyRuntime.getargs.static_parsers = parser;
1956
return 1;
1957
}
1958
1959
static int
1960
parser_init(struct _PyArg_Parser *parser)
1961
{
1962
// volatile as it can be modified by other threads
1963
// and should not be optimized or reordered by compiler
1964
if (*((volatile int *)&parser->initialized)) {
1965
assert(parser->kwtuple != NULL);
1966
return 1;
1967
}
1968
PyThread_acquire_lock(_PyRuntime.getargs.mutex, WAIT_LOCK);
1969
// Check again if another thread initialized the parser
1970
// while we were waiting for the lock.
1971
if (*((volatile int *)&parser->initialized)) {
1972
assert(parser->kwtuple != NULL);
1973
PyThread_release_lock(_PyRuntime.getargs.mutex);
1974
return 1;
1975
}
1976
int ret = _parser_init(parser);
1977
PyThread_release_lock(_PyRuntime.getargs.mutex);
1978
return ret;
1979
}
1980
1981
static void
1982
parser_clear(struct _PyArg_Parser *parser)
1983
{
1984
if (parser->initialized == 1) {
1985
Py_CLEAR(parser->kwtuple);
1986
}
1987
}
1988
1989
static PyObject*
1990
find_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)
1991
{
1992
Py_ssize_t i, nkwargs;
1993
1994
nkwargs = PyTuple_GET_SIZE(kwnames);
1995
for (i = 0; i < nkwargs; i++) {
1996
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
1997
1998
/* kwname == key will normally find a match in since keyword keys
1999
should be interned strings; if not retry below in a new loop. */
2000
if (kwname == key) {
2001
return kwstack[i];
2002
}
2003
}
2004
2005
for (i = 0; i < nkwargs; i++) {
2006
PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);
2007
assert(PyUnicode_Check(kwname));
2008
if (_PyUnicode_EQ(kwname, key)) {
2009
return kwstack[i];
2010
}
2011
}
2012
return NULL;
2013
}
2014
2015
static int
2016
vgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,
2017
PyObject *kwargs, PyObject *kwnames,
2018
struct _PyArg_Parser *parser,
2019
va_list *p_va, int flags)
2020
{
2021
PyObject *kwtuple;
2022
char msgbuf[512];
2023
int levels[32];
2024
const char *format;
2025
const char *msg;
2026
PyObject *keyword;
2027
int i, pos, len;
2028
Py_ssize_t nkwargs;
2029
PyObject *current_arg;
2030
freelistentry_t static_entries[STATIC_FREELIST_ENTRIES];
2031
freelist_t freelist;
2032
PyObject *const *kwstack = NULL;
2033
2034
freelist.entries = static_entries;
2035
freelist.first_available = 0;
2036
freelist.entries_malloced = 0;
2037
2038
assert(kwargs == NULL || PyDict_Check(kwargs));
2039
assert(kwargs == NULL || kwnames == NULL);
2040
assert(p_va != NULL);
2041
2042
if (parser == NULL) {
2043
PyErr_BadInternalCall();
2044
return 0;
2045
}
2046
2047
if (kwnames != NULL && !PyTuple_Check(kwnames)) {
2048
PyErr_BadInternalCall();
2049
return 0;
2050
}
2051
2052
if (!parser_init(parser)) {
2053
return 0;
2054
}
2055
2056
kwtuple = parser->kwtuple;
2057
pos = parser->pos;
2058
len = pos + (int)PyTuple_GET_SIZE(kwtuple);
2059
2060
if (len > STATIC_FREELIST_ENTRIES) {
2061
freelist.entries = PyMem_NEW(freelistentry_t, len);
2062
if (freelist.entries == NULL) {
2063
PyErr_NoMemory();
2064
return 0;
2065
}
2066
freelist.entries_malloced = 1;
2067
}
2068
2069
if (kwargs != NULL) {
2070
nkwargs = PyDict_GET_SIZE(kwargs);
2071
}
2072
else if (kwnames != NULL) {
2073
nkwargs = PyTuple_GET_SIZE(kwnames);
2074
kwstack = args + nargs;
2075
}
2076
else {
2077
nkwargs = 0;
2078
}
2079
if (nargs + nkwargs > len) {
2080
/* Adding "keyword" (when nargs == 0) prevents producing wrong error
2081
messages in some special cases (see bpo-31229). */
2082
PyErr_Format(PyExc_TypeError,
2083
"%.200s%s takes at most %d %sargument%s (%zd given)",
2084
(parser->fname == NULL) ? "function" : parser->fname,
2085
(parser->fname == NULL) ? "" : "()",
2086
len,
2087
(nargs == 0) ? "keyword " : "",
2088
(len == 1) ? "" : "s",
2089
nargs + nkwargs);
2090
return cleanreturn(0, &freelist);
2091
}
2092
if (parser->max < nargs) {
2093
if (parser->max == 0) {
2094
PyErr_Format(PyExc_TypeError,
2095
"%.200s%s takes no positional arguments",
2096
(parser->fname == NULL) ? "function" : parser->fname,
2097
(parser->fname == NULL) ? "" : "()");
2098
}
2099
else {
2100
PyErr_Format(PyExc_TypeError,
2101
"%.200s%s takes %s %d positional argument%s (%zd given)",
2102
(parser->fname == NULL) ? "function" : parser->fname,
2103
(parser->fname == NULL) ? "" : "()",
2104
(parser->min < parser->max) ? "at most" : "exactly",
2105
parser->max,
2106
parser->max == 1 ? "" : "s",
2107
nargs);
2108
}
2109
return cleanreturn(0, &freelist);
2110
}
2111
2112
format = parser->format;
2113
assert(format != NULL || len == 0);
2114
/* convert tuple args and keyword args in same loop, using kwtuple to drive process */
2115
for (i = 0; i < len; i++) {
2116
if (*format == '|') {
2117
format++;
2118
}
2119
if (*format == '$') {
2120
format++;
2121
}
2122
assert(!IS_END_OF_FORMAT(*format));
2123
2124
if (i < nargs) {
2125
current_arg = args[i];
2126
}
2127
else if (nkwargs && i >= pos) {
2128
keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2129
if (kwargs != NULL) {
2130
current_arg = PyDict_GetItemWithError(kwargs, keyword);
2131
if (!current_arg && PyErr_Occurred()) {
2132
return cleanreturn(0, &freelist);
2133
}
2134
}
2135
else {
2136
current_arg = find_keyword(kwnames, kwstack, keyword);
2137
}
2138
if (current_arg) {
2139
--nkwargs;
2140
}
2141
}
2142
else {
2143
current_arg = NULL;
2144
}
2145
2146
if (current_arg) {
2147
msg = convertitem(current_arg, &format, p_va, flags,
2148
levels, msgbuf, sizeof(msgbuf), &freelist);
2149
if (msg) {
2150
seterror(i+1, msg, levels, parser->fname, parser->custom_msg);
2151
return cleanreturn(0, &freelist);
2152
}
2153
continue;
2154
}
2155
2156
if (i < parser->min) {
2157
/* Less arguments than required */
2158
if (i < pos) {
2159
Py_ssize_t min = Py_MIN(pos, parser->min);
2160
PyErr_Format(PyExc_TypeError,
2161
"%.200s%s takes %s %d positional argument%s"
2162
" (%zd given)",
2163
(parser->fname == NULL) ? "function" : parser->fname,
2164
(parser->fname == NULL) ? "" : "()",
2165
min < parser->max ? "at least" : "exactly",
2166
min,
2167
min == 1 ? "" : "s",
2168
nargs);
2169
}
2170
else {
2171
keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2172
PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
2173
"argument '%U' (pos %d)",
2174
(parser->fname == NULL) ? "function" : parser->fname,
2175
(parser->fname == NULL) ? "" : "()",
2176
keyword, i+1);
2177
}
2178
return cleanreturn(0, &freelist);
2179
}
2180
/* current code reports success when all required args
2181
* fulfilled and no keyword args left, with no further
2182
* validation. XXX Maybe skip this in debug build ?
2183
*/
2184
if (!nkwargs) {
2185
return cleanreturn(1, &freelist);
2186
}
2187
2188
/* We are into optional args, skip through to any remaining
2189
* keyword args */
2190
msg = skipitem(&format, p_va, flags);
2191
assert(msg == NULL);
2192
}
2193
2194
assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$'));
2195
2196
if (nkwargs > 0) {
2197
/* make sure there are no arguments given by name and position */
2198
for (i = pos; i < nargs; i++) {
2199
keyword = PyTuple_GET_ITEM(kwtuple, i - pos);
2200
if (kwargs != NULL) {
2201
current_arg = PyDict_GetItemWithError(kwargs, keyword);
2202
if (!current_arg && PyErr_Occurred()) {
2203
return cleanreturn(0, &freelist);
2204
}
2205
}
2206
else {
2207
current_arg = find_keyword(kwnames, kwstack, keyword);
2208
}
2209
if (current_arg) {
2210
/* arg present in tuple and in dict */
2211
PyErr_Format(PyExc_TypeError,
2212
"argument for %.200s%s given by name ('%U') "
2213
"and position (%d)",
2214
(parser->fname == NULL) ? "function" : parser->fname,
2215
(parser->fname == NULL) ? "" : "()",
2216
keyword, i+1);
2217
return cleanreturn(0, &freelist);
2218
}
2219
}
2220
2221
error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
2222
return cleanreturn(0, &freelist);
2223
}
2224
2225
return cleanreturn(1, &freelist);
2226
}
2227
2228
static int
2229
vgetargskeywordsfast(PyObject *args, PyObject *keywords,
2230
struct _PyArg_Parser *parser, va_list *p_va, int flags)
2231
{
2232
PyObject **stack;
2233
Py_ssize_t nargs;
2234
2235
if (args == NULL
2236
|| !PyTuple_Check(args)
2237
|| (keywords != NULL && !PyDict_Check(keywords)))
2238
{
2239
PyErr_BadInternalCall();
2240
return 0;
2241
}
2242
2243
stack = _PyTuple_ITEMS(args);
2244
nargs = PyTuple_GET_SIZE(args);
2245
return vgetargskeywordsfast_impl(stack, nargs, keywords, NULL,
2246
parser, p_va, flags);
2247
}
2248
2249
2250
#undef _PyArg_UnpackKeywords
2251
2252
PyObject * const *
2253
_PyArg_UnpackKeywords(PyObject *const *args, Py_ssize_t nargs,
2254
PyObject *kwargs, PyObject *kwnames,
2255
struct _PyArg_Parser *parser,
2256
int minpos, int maxpos, int minkw,
2257
PyObject **buf)
2258
{
2259
PyObject *kwtuple;
2260
PyObject *keyword;
2261
int i, posonly, minposonly, maxargs;
2262
int reqlimit = minkw ? maxpos + minkw : minpos;
2263
Py_ssize_t nkwargs;
2264
PyObject *current_arg;
2265
PyObject * const *kwstack = NULL;
2266
2267
assert(kwargs == NULL || PyDict_Check(kwargs));
2268
assert(kwargs == NULL || kwnames == NULL);
2269
2270
if (parser == NULL) {
2271
PyErr_BadInternalCall();
2272
return NULL;
2273
}
2274
2275
if (kwnames != NULL && !PyTuple_Check(kwnames)) {
2276
PyErr_BadInternalCall();
2277
return NULL;
2278
}
2279
2280
if (args == NULL && nargs == 0) {
2281
args = buf;
2282
}
2283
2284
if (!parser_init(parser)) {
2285
return NULL;
2286
}
2287
2288
kwtuple = parser->kwtuple;
2289
posonly = parser->pos;
2290
minposonly = Py_MIN(posonly, minpos);
2291
maxargs = posonly + (int)PyTuple_GET_SIZE(kwtuple);
2292
2293
if (kwargs != NULL) {
2294
nkwargs = PyDict_GET_SIZE(kwargs);
2295
}
2296
else if (kwnames != NULL) {
2297
nkwargs = PyTuple_GET_SIZE(kwnames);
2298
kwstack = args + nargs;
2299
}
2300
else {
2301
nkwargs = 0;
2302
}
2303
if (nkwargs == 0 && minkw == 0 && minpos <= nargs && nargs <= maxpos) {
2304
/* Fast path. */
2305
return args;
2306
}
2307
if (nargs + nkwargs > maxargs) {
2308
/* Adding "keyword" (when nargs == 0) prevents producing wrong error
2309
messages in some special cases (see bpo-31229). */
2310
PyErr_Format(PyExc_TypeError,
2311
"%.200s%s takes at most %d %sargument%s (%zd given)",
2312
(parser->fname == NULL) ? "function" : parser->fname,
2313
(parser->fname == NULL) ? "" : "()",
2314
maxargs,
2315
(nargs == 0) ? "keyword " : "",
2316
(maxargs == 1) ? "" : "s",
2317
nargs + nkwargs);
2318
return NULL;
2319
}
2320
if (nargs > maxpos) {
2321
if (maxpos == 0) {
2322
PyErr_Format(PyExc_TypeError,
2323
"%.200s%s takes no positional arguments",
2324
(parser->fname == NULL) ? "function" : parser->fname,
2325
(parser->fname == NULL) ? "" : "()");
2326
}
2327
else {
2328
PyErr_Format(PyExc_TypeError,
2329
"%.200s%s takes %s %d positional argument%s (%zd given)",
2330
(parser->fname == NULL) ? "function" : parser->fname,
2331
(parser->fname == NULL) ? "" : "()",
2332
(minpos < maxpos) ? "at most" : "exactly",
2333
maxpos,
2334
(maxpos == 1) ? "" : "s",
2335
nargs);
2336
}
2337
return NULL;
2338
}
2339
if (nargs < minposonly) {
2340
PyErr_Format(PyExc_TypeError,
2341
"%.200s%s takes %s %d positional argument%s"
2342
" (%zd given)",
2343
(parser->fname == NULL) ? "function" : parser->fname,
2344
(parser->fname == NULL) ? "" : "()",
2345
minposonly < maxpos ? "at least" : "exactly",
2346
minposonly,
2347
minposonly == 1 ? "" : "s",
2348
nargs);
2349
return NULL;
2350
}
2351
2352
/* copy tuple args */
2353
for (i = 0; i < nargs; i++) {
2354
buf[i] = args[i];
2355
}
2356
2357
/* copy keyword args using kwtuple to drive process */
2358
for (i = Py_MAX((int)nargs, posonly); i < maxargs; i++) {
2359
if (nkwargs) {
2360
keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2361
if (kwargs != NULL) {
2362
current_arg = PyDict_GetItemWithError(kwargs, keyword);
2363
if (!current_arg && PyErr_Occurred()) {
2364
return NULL;
2365
}
2366
}
2367
else {
2368
current_arg = find_keyword(kwnames, kwstack, keyword);
2369
}
2370
}
2371
else if (i >= reqlimit) {
2372
break;
2373
}
2374
else {
2375
current_arg = NULL;
2376
}
2377
2378
buf[i] = current_arg;
2379
2380
if (current_arg) {
2381
--nkwargs;
2382
}
2383
else if (i < minpos || (maxpos <= i && i < reqlimit)) {
2384
/* Less arguments than required */
2385
keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2386
PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
2387
"argument '%U' (pos %d)",
2388
(parser->fname == NULL) ? "function" : parser->fname,
2389
(parser->fname == NULL) ? "" : "()",
2390
keyword, i+1);
2391
return NULL;
2392
}
2393
}
2394
2395
if (nkwargs > 0) {
2396
/* make sure there are no arguments given by name and position */
2397
for (i = posonly; i < nargs; i++) {
2398
keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2399
if (kwargs != NULL) {
2400
current_arg = PyDict_GetItemWithError(kwargs, keyword);
2401
if (!current_arg && PyErr_Occurred()) {
2402
return NULL;
2403
}
2404
}
2405
else {
2406
current_arg = find_keyword(kwnames, kwstack, keyword);
2407
}
2408
if (current_arg) {
2409
/* arg present in tuple and in dict */
2410
PyErr_Format(PyExc_TypeError,
2411
"argument for %.200s%s given by name ('%U') "
2412
"and position (%d)",
2413
(parser->fname == NULL) ? "function" : parser->fname,
2414
(parser->fname == NULL) ? "" : "()",
2415
keyword, i+1);
2416
return NULL;
2417
}
2418
}
2419
2420
error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
2421
return NULL;
2422
}
2423
2424
return buf;
2425
}
2426
2427
PyObject * const *
2428
_PyArg_UnpackKeywordsWithVararg(PyObject *const *args, Py_ssize_t nargs,
2429
PyObject *kwargs, PyObject *kwnames,
2430
struct _PyArg_Parser *parser,
2431
int minpos, int maxpos, int minkw,
2432
int vararg, PyObject **buf)
2433
{
2434
PyObject *kwtuple;
2435
PyObject *keyword;
2436
Py_ssize_t varargssize = 0;
2437
int i, posonly, minposonly, maxargs;
2438
int reqlimit = minkw ? maxpos + minkw : minpos;
2439
Py_ssize_t nkwargs;
2440
PyObject *current_arg;
2441
PyObject * const *kwstack = NULL;
2442
2443
assert(kwargs == NULL || PyDict_Check(kwargs));
2444
assert(kwargs == NULL || kwnames == NULL);
2445
2446
if (parser == NULL) {
2447
PyErr_BadInternalCall();
2448
return NULL;
2449
}
2450
2451
if (kwnames != NULL && !PyTuple_Check(kwnames)) {
2452
PyErr_BadInternalCall();
2453
return NULL;
2454
}
2455
2456
if (args == NULL && nargs == 0) {
2457
args = buf;
2458
}
2459
2460
if (!parser_init(parser)) {
2461
return NULL;
2462
}
2463
2464
kwtuple = parser->kwtuple;
2465
posonly = parser->pos;
2466
minposonly = Py_MIN(posonly, minpos);
2467
maxargs = posonly + (int)PyTuple_GET_SIZE(kwtuple);
2468
if (kwargs != NULL) {
2469
nkwargs = PyDict_GET_SIZE(kwargs);
2470
}
2471
else if (kwnames != NULL) {
2472
nkwargs = PyTuple_GET_SIZE(kwnames);
2473
kwstack = args + nargs;
2474
}
2475
else {
2476
nkwargs = 0;
2477
}
2478
if (nargs < minposonly) {
2479
PyErr_Format(PyExc_TypeError,
2480
"%.200s%s takes %s %d positional argument%s"
2481
" (%zd given)",
2482
(parser->fname == NULL) ? "function" : parser->fname,
2483
(parser->fname == NULL) ? "" : "()",
2484
minposonly < maxpos ? "at least" : "exactly",
2485
minposonly,
2486
minposonly == 1 ? "" : "s",
2487
nargs);
2488
return NULL;
2489
}
2490
2491
/* create varargs tuple */
2492
varargssize = nargs - maxpos;
2493
if (varargssize < 0) {
2494
varargssize = 0;
2495
}
2496
buf[vararg] = PyTuple_New(varargssize);
2497
if (!buf[vararg]) {
2498
return NULL;
2499
}
2500
2501
/* copy tuple args */
2502
for (i = 0; i < nargs; i++) {
2503
if (i >= vararg) {
2504
PyTuple_SET_ITEM(buf[vararg], i - vararg, Py_NewRef(args[i]));
2505
continue;
2506
}
2507
else {
2508
buf[i] = args[i];
2509
}
2510
}
2511
2512
/* copy keyword args using kwtuple to drive process */
2513
for (i = Py_MAX((int)nargs, posonly) -
2514
Py_SAFE_DOWNCAST(varargssize, Py_ssize_t, int); i < maxargs; i++) {
2515
if (nkwargs) {
2516
keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2517
if (kwargs != NULL) {
2518
current_arg = PyDict_GetItemWithError(kwargs, keyword);
2519
if (!current_arg && PyErr_Occurred()) {
2520
goto exit;
2521
}
2522
}
2523
else {
2524
current_arg = find_keyword(kwnames, kwstack, keyword);
2525
}
2526
}
2527
else {
2528
current_arg = NULL;
2529
}
2530
2531
/* If an arguments is passed in as a keyword argument,
2532
* it should be placed before `buf[vararg]`.
2533
*
2534
* For example:
2535
* def f(a, /, b, *args):
2536
* pass
2537
* f(1, b=2)
2538
*
2539
* This `buf` array should be: [1, 2, NULL].
2540
* In this case, nargs < vararg.
2541
*
2542
* Otherwise, we leave a place at `buf[vararg]` for vararg tuple
2543
* so the index is `i + 1`. */
2544
if (nargs < vararg) {
2545
buf[i] = current_arg;
2546
}
2547
else {
2548
buf[i + 1] = current_arg;
2549
}
2550
2551
if (current_arg) {
2552
--nkwargs;
2553
}
2554
else if (i < minpos || (maxpos <= i && i < reqlimit)) {
2555
/* Less arguments than required */
2556
keyword = PyTuple_GET_ITEM(kwtuple, i - posonly);
2557
PyErr_Format(PyExc_TypeError, "%.200s%s missing required "
2558
"argument '%U' (pos %d)",
2559
(parser->fname == NULL) ? "function" : parser->fname,
2560
(parser->fname == NULL) ? "" : "()",
2561
keyword, i+1);
2562
goto exit;
2563
}
2564
}
2565
2566
if (nkwargs > 0) {
2567
error_unexpected_keyword_arg(kwargs, kwnames, kwtuple, parser->fname);
2568
goto exit;
2569
}
2570
2571
return buf;
2572
2573
exit:
2574
Py_XDECREF(buf[vararg]);
2575
return NULL;
2576
}
2577
2578
2579
static const char *
2580
skipitem(const char **p_format, va_list *p_va, int flags)
2581
{
2582
const char *format = *p_format;
2583
char c = *format++;
2584
2585
switch (c) {
2586
2587
/*
2588
* codes that take a single data pointer as an argument
2589
* (the type of the pointer is irrelevant)
2590
*/
2591
2592
case 'b': /* byte -- very short int */
2593
case 'B': /* byte as bitfield */
2594
case 'h': /* short int */
2595
case 'H': /* short int as bitfield */
2596
case 'i': /* int */
2597
case 'I': /* int sized bitfield */
2598
case 'l': /* long int */
2599
case 'k': /* long int sized bitfield */
2600
case 'L': /* long long */
2601
case 'K': /* long long sized bitfield */
2602
case 'n': /* Py_ssize_t */
2603
case 'f': /* float */
2604
case 'd': /* double */
2605
case 'D': /* complex double */
2606
case 'c': /* char */
2607
case 'C': /* unicode char */
2608
case 'p': /* boolean predicate */
2609
case 'S': /* string object */
2610
case 'Y': /* string object */
2611
case 'U': /* unicode string object */
2612
{
2613
if (p_va != NULL) {
2614
(void) va_arg(*p_va, void *);
2615
}
2616
break;
2617
}
2618
2619
/* string codes */
2620
2621
case 'e': /* string with encoding */
2622
{
2623
if (p_va != NULL) {
2624
(void) va_arg(*p_va, const char *);
2625
}
2626
if (!(*format == 's' || *format == 't'))
2627
/* after 'e', only 's' and 't' is allowed */
2628
goto err;
2629
format++;
2630
}
2631
/* fall through */
2632
2633
case 's': /* string */
2634
case 'z': /* string or None */
2635
case 'y': /* bytes */
2636
case 'w': /* buffer, read-write */
2637
{
2638
if (p_va != NULL) {
2639
(void) va_arg(*p_va, char **);
2640
}
2641
if (*format == '#') {
2642
if (p_va != NULL) {
2643
(void) va_arg(*p_va, Py_ssize_t *);
2644
}
2645
format++;
2646
} else if ((c == 's' || c == 'z' || c == 'y' || c == 'w')
2647
&& *format == '*')
2648
{
2649
format++;
2650
}
2651
break;
2652
}
2653
2654
case 'O': /* object */
2655
{
2656
if (*format == '!') {
2657
format++;
2658
if (p_va != NULL) {
2659
(void) va_arg(*p_va, PyTypeObject*);
2660
(void) va_arg(*p_va, PyObject **);
2661
}
2662
}
2663
else if (*format == '&') {
2664
typedef int (*converter)(PyObject *, void *);
2665
if (p_va != NULL) {
2666
(void) va_arg(*p_va, converter);
2667
(void) va_arg(*p_va, void *);
2668
}
2669
format++;
2670
}
2671
else {
2672
if (p_va != NULL) {
2673
(void) va_arg(*p_va, PyObject **);
2674
}
2675
}
2676
break;
2677
}
2678
2679
case '(': /* bypass tuple, not handled at all previously */
2680
{
2681
const char *msg;
2682
for (;;) {
2683
if (*format==')')
2684
break;
2685
if (IS_END_OF_FORMAT(*format))
2686
return "Unmatched left paren in format "
2687
"string";
2688
msg = skipitem(&format, p_va, flags);
2689
if (msg)
2690
return msg;
2691
}
2692
format++;
2693
break;
2694
}
2695
2696
case ')':
2697
return "Unmatched right paren in format string";
2698
2699
default:
2700
err:
2701
return "impossible<bad format char>";
2702
2703
}
2704
2705
*p_format = format;
2706
return NULL;
2707
}
2708
2709
2710
#undef _PyArg_CheckPositional
2711
2712
int
2713
_PyArg_CheckPositional(const char *name, Py_ssize_t nargs,
2714
Py_ssize_t min, Py_ssize_t max)
2715
{
2716
assert(min >= 0);
2717
assert(min <= max);
2718
2719
if (nargs < min) {
2720
if (name != NULL)
2721
PyErr_Format(
2722
PyExc_TypeError,
2723
"%.200s expected %s%zd argument%s, got %zd",
2724
name, (min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
2725
else
2726
PyErr_Format(
2727
PyExc_TypeError,
2728
"unpacked tuple should have %s%zd element%s,"
2729
" but has %zd",
2730
(min == max ? "" : "at least "), min, min == 1 ? "" : "s", nargs);
2731
return 0;
2732
}
2733
2734
if (nargs == 0) {
2735
return 1;
2736
}
2737
2738
if (nargs > max) {
2739
if (name != NULL)
2740
PyErr_Format(
2741
PyExc_TypeError,
2742
"%.200s expected %s%zd argument%s, got %zd",
2743
name, (min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
2744
else
2745
PyErr_Format(
2746
PyExc_TypeError,
2747
"unpacked tuple should have %s%zd element%s,"
2748
" but has %zd",
2749
(min == max ? "" : "at most "), max, max == 1 ? "" : "s", nargs);
2750
return 0;
2751
}
2752
2753
return 1;
2754
}
2755
2756
static int
2757
unpack_stack(PyObject *const *args, Py_ssize_t nargs, const char *name,
2758
Py_ssize_t min, Py_ssize_t max, va_list vargs)
2759
{
2760
Py_ssize_t i;
2761
PyObject **o;
2762
2763
if (!_PyArg_CheckPositional(name, nargs, min, max)) {
2764
return 0;
2765
}
2766
2767
for (i = 0; i < nargs; i++) {
2768
o = va_arg(vargs, PyObject **);
2769
*o = args[i];
2770
}
2771
return 1;
2772
}
2773
2774
int
2775
PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
2776
{
2777
PyObject **stack;
2778
Py_ssize_t nargs;
2779
int retval;
2780
va_list vargs;
2781
2782
if (!PyTuple_Check(args)) {
2783
PyErr_SetString(PyExc_SystemError,
2784
"PyArg_UnpackTuple() argument list is not a tuple");
2785
return 0;
2786
}
2787
stack = _PyTuple_ITEMS(args);
2788
nargs = PyTuple_GET_SIZE(args);
2789
2790
va_start(vargs, max);
2791
retval = unpack_stack(stack, nargs, name, min, max, vargs);
2792
va_end(vargs);
2793
return retval;
2794
}
2795
2796
int
2797
_PyArg_UnpackStack(PyObject *const *args, Py_ssize_t nargs, const char *name,
2798
Py_ssize_t min, Py_ssize_t max, ...)
2799
{
2800
int retval;
2801
va_list vargs;
2802
2803
va_start(vargs, max);
2804
retval = unpack_stack(args, nargs, name, min, max, vargs);
2805
va_end(vargs);
2806
return retval;
2807
}
2808
2809
2810
#undef _PyArg_NoKeywords
2811
#undef _PyArg_NoKwnames
2812
#undef _PyArg_NoPositional
2813
2814
/* For type constructors that don't take keyword args
2815
*
2816
* Sets a TypeError and returns 0 if the args/kwargs is
2817
* not empty, returns 1 otherwise
2818
*/
2819
int
2820
_PyArg_NoKeywords(const char *funcname, PyObject *kwargs)
2821
{
2822
if (kwargs == NULL) {
2823
return 1;
2824
}
2825
if (!PyDict_CheckExact(kwargs)) {
2826
PyErr_BadInternalCall();
2827
return 0;
2828
}
2829
if (PyDict_GET_SIZE(kwargs) == 0) {
2830
return 1;
2831
}
2832
2833
PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
2834
funcname);
2835
return 0;
2836
}
2837
2838
int
2839
_PyArg_NoPositional(const char *funcname, PyObject *args)
2840
{
2841
if (args == NULL)
2842
return 1;
2843
if (!PyTuple_CheckExact(args)) {
2844
PyErr_BadInternalCall();
2845
return 0;
2846
}
2847
if (PyTuple_GET_SIZE(args) == 0)
2848
return 1;
2849
2850
PyErr_Format(PyExc_TypeError, "%.200s() takes no positional arguments",
2851
funcname);
2852
return 0;
2853
}
2854
2855
int
2856
_PyArg_NoKwnames(const char *funcname, PyObject *kwnames)
2857
{
2858
if (kwnames == NULL) {
2859
return 1;
2860
}
2861
2862
assert(PyTuple_CheckExact(kwnames));
2863
2864
if (PyTuple_GET_SIZE(kwnames) == 0) {
2865
return 1;
2866
}
2867
2868
PyErr_Format(PyExc_TypeError, "%s() takes no keyword arguments", funcname);
2869
return 0;
2870
}
2871
2872
void
2873
_PyArg_Fini(void)
2874
{
2875
struct _PyArg_Parser *tmp, *s = _PyRuntime.getargs.static_parsers;
2876
while (s) {
2877
tmp = s->next;
2878
s->next = NULL;
2879
parser_clear(s);
2880
s = tmp;
2881
}
2882
_PyRuntime.getargs.static_parsers = NULL;
2883
}
2884
2885
#ifdef __cplusplus
2886
};
2887
#endif
2888
2889