Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Parser/action_helpers.c
12 views
1
#include <Python.h>
2
3
#include "pegen.h"
4
#include "tokenizer.h"
5
#include "string_parser.h"
6
#include "pycore_runtime.h" // _PyRuntime
7
8
void *
9
_PyPegen_dummy_name(Parser *p, ...)
10
{
11
return &_PyRuntime.parser.dummy_name;
12
}
13
14
/* Creates a single-element asdl_seq* that contains a */
15
asdl_seq *
16
_PyPegen_singleton_seq(Parser *p, void *a)
17
{
18
assert(a != NULL);
19
asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
20
if (!seq) {
21
return NULL;
22
}
23
asdl_seq_SET_UNTYPED(seq, 0, a);
24
return seq;
25
}
26
27
/* Creates a copy of seq and prepends a to it */
28
asdl_seq *
29
_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
30
{
31
assert(a != NULL);
32
if (!seq) {
33
return _PyPegen_singleton_seq(p, a);
34
}
35
36
asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
37
if (!new_seq) {
38
return NULL;
39
}
40
41
asdl_seq_SET_UNTYPED(new_seq, 0, a);
42
for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
43
asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
44
}
45
return new_seq;
46
}
47
48
/* Creates a copy of seq and appends a to it */
49
asdl_seq *
50
_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
51
{
52
assert(a != NULL);
53
if (!seq) {
54
return _PyPegen_singleton_seq(p, a);
55
}
56
57
asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
58
if (!new_seq) {
59
return NULL;
60
}
61
62
for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
63
asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
64
}
65
asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
66
return new_seq;
67
}
68
69
static Py_ssize_t
70
_get_flattened_seq_size(asdl_seq *seqs)
71
{
72
Py_ssize_t size = 0;
73
for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
74
asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
75
size += asdl_seq_LEN(inner_seq);
76
}
77
return size;
78
}
79
80
/* Flattens an asdl_seq* of asdl_seq*s */
81
asdl_seq *
82
_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
83
{
84
Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
85
assert(flattened_seq_size > 0);
86
87
asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
88
if (!flattened_seq) {
89
return NULL;
90
}
91
92
int flattened_seq_idx = 0;
93
for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
94
asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
95
for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
96
asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
97
}
98
}
99
assert(flattened_seq_idx == flattened_seq_size);
100
101
return flattened_seq;
102
}
103
104
void *
105
_PyPegen_seq_last_item(asdl_seq *seq)
106
{
107
Py_ssize_t len = asdl_seq_LEN(seq);
108
return asdl_seq_GET_UNTYPED(seq, len - 1);
109
}
110
111
void *
112
_PyPegen_seq_first_item(asdl_seq *seq)
113
{
114
return asdl_seq_GET_UNTYPED(seq, 0);
115
}
116
117
/* Creates a new name of the form <first_name>.<second_name> */
118
expr_ty
119
_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
120
{
121
assert(first_name != NULL && second_name != NULL);
122
PyObject *first_identifier = first_name->v.Name.id;
123
PyObject *second_identifier = second_name->v.Name.id;
124
125
const char *first_str = PyUnicode_AsUTF8(first_identifier);
126
if (!first_str) {
127
return NULL;
128
}
129
const char *second_str = PyUnicode_AsUTF8(second_identifier);
130
if (!second_str) {
131
return NULL;
132
}
133
Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
134
135
PyObject *str = PyBytes_FromStringAndSize(NULL, len);
136
if (!str) {
137
return NULL;
138
}
139
140
char *s = PyBytes_AS_STRING(str);
141
if (!s) {
142
return NULL;
143
}
144
145
strcpy(s, first_str);
146
s += strlen(first_str);
147
*s++ = '.';
148
strcpy(s, second_str);
149
s += strlen(second_str);
150
*s = '\0';
151
152
PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
153
Py_DECREF(str);
154
if (!uni) {
155
return NULL;
156
}
157
PyUnicode_InternInPlace(&uni);
158
if (_PyArena_AddPyObject(p->arena, uni) < 0) {
159
Py_DECREF(uni);
160
return NULL;
161
}
162
163
return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
164
}
165
166
/* Counts the total number of dots in seq's tokens */
167
int
168
_PyPegen_seq_count_dots(asdl_seq *seq)
169
{
170
int number_of_dots = 0;
171
for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
172
Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
173
switch (current_expr->type) {
174
case ELLIPSIS:
175
number_of_dots += 3;
176
break;
177
case DOT:
178
number_of_dots += 1;
179
break;
180
default:
181
Py_UNREACHABLE();
182
}
183
}
184
185
return number_of_dots;
186
}
187
188
/* Creates an alias with '*' as the identifier name */
189
alias_ty
190
_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
191
int end_col_offset, PyArena *arena) {
192
PyObject *str = PyUnicode_InternFromString("*");
193
if (!str) {
194
return NULL;
195
}
196
if (_PyArena_AddPyObject(p->arena, str) < 0) {
197
Py_DECREF(str);
198
return NULL;
199
}
200
return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
201
}
202
203
/* Creates a new asdl_seq* with the identifiers of all the names in seq */
204
asdl_identifier_seq *
205
_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
206
{
207
Py_ssize_t len = asdl_seq_LEN(seq);
208
assert(len > 0);
209
210
asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
211
if (!new_seq) {
212
return NULL;
213
}
214
for (Py_ssize_t i = 0; i < len; i++) {
215
expr_ty e = asdl_seq_GET(seq, i);
216
asdl_seq_SET(new_seq, i, e->v.Name.id);
217
}
218
return new_seq;
219
}
220
221
/* Constructs a CmpopExprPair */
222
CmpopExprPair *
223
_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
224
{
225
assert(expr != NULL);
226
CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
227
if (!a) {
228
return NULL;
229
}
230
a->cmpop = cmpop;
231
a->expr = expr;
232
return a;
233
}
234
235
asdl_int_seq *
236
_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
237
{
238
Py_ssize_t len = asdl_seq_LEN(seq);
239
assert(len > 0);
240
241
asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
242
if (!new_seq) {
243
return NULL;
244
}
245
for (Py_ssize_t i = 0; i < len; i++) {
246
CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
247
asdl_seq_SET(new_seq, i, pair->cmpop);
248
}
249
return new_seq;
250
}
251
252
asdl_expr_seq *
253
_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
254
{
255
Py_ssize_t len = asdl_seq_LEN(seq);
256
assert(len > 0);
257
258
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
259
if (!new_seq) {
260
return NULL;
261
}
262
for (Py_ssize_t i = 0; i < len; i++) {
263
CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
264
asdl_seq_SET(new_seq, i, pair->expr);
265
}
266
return new_seq;
267
}
268
269
/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
270
static asdl_expr_seq *
271
_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
272
{
273
Py_ssize_t len = asdl_seq_LEN(seq);
274
if (len == 0) {
275
return NULL;
276
}
277
278
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
279
if (!new_seq) {
280
return NULL;
281
}
282
for (Py_ssize_t i = 0; i < len; i++) {
283
expr_ty e = asdl_seq_GET(seq, i);
284
asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
285
}
286
return new_seq;
287
}
288
289
static expr_ty
290
_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
291
{
292
return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
293
}
294
295
static expr_ty
296
_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
297
{
298
return _PyAST_Tuple(
299
_set_seq_context(p, e->v.Tuple.elts, ctx),
300
ctx,
301
EXTRA_EXPR(e, e));
302
}
303
304
static expr_ty
305
_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
306
{
307
return _PyAST_List(
308
_set_seq_context(p, e->v.List.elts, ctx),
309
ctx,
310
EXTRA_EXPR(e, e));
311
}
312
313
static expr_ty
314
_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
315
{
316
return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
317
ctx, EXTRA_EXPR(e, e));
318
}
319
320
static expr_ty
321
_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
322
{
323
return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
324
ctx, EXTRA_EXPR(e, e));
325
}
326
327
static expr_ty
328
_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
329
{
330
return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
331
ctx, EXTRA_EXPR(e, e));
332
}
333
334
/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
335
expr_ty
336
_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
337
{
338
assert(expr != NULL);
339
340
expr_ty new = NULL;
341
switch (expr->kind) {
342
case Name_kind:
343
new = _set_name_context(p, expr, ctx);
344
break;
345
case Tuple_kind:
346
new = _set_tuple_context(p, expr, ctx);
347
break;
348
case List_kind:
349
new = _set_list_context(p, expr, ctx);
350
break;
351
case Subscript_kind:
352
new = _set_subscript_context(p, expr, ctx);
353
break;
354
case Attribute_kind:
355
new = _set_attribute_context(p, expr, ctx);
356
break;
357
case Starred_kind:
358
new = _set_starred_context(p, expr, ctx);
359
break;
360
default:
361
new = expr;
362
}
363
return new;
364
}
365
366
/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
367
KeyValuePair *
368
_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
369
{
370
KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
371
if (!a) {
372
return NULL;
373
}
374
a->key = key;
375
a->value = value;
376
return a;
377
}
378
379
/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
380
asdl_expr_seq *
381
_PyPegen_get_keys(Parser *p, asdl_seq *seq)
382
{
383
Py_ssize_t len = asdl_seq_LEN(seq);
384
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
385
if (!new_seq) {
386
return NULL;
387
}
388
for (Py_ssize_t i = 0; i < len; i++) {
389
KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
390
asdl_seq_SET(new_seq, i, pair->key);
391
}
392
return new_seq;
393
}
394
395
/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
396
asdl_expr_seq *
397
_PyPegen_get_values(Parser *p, asdl_seq *seq)
398
{
399
Py_ssize_t len = asdl_seq_LEN(seq);
400
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
401
if (!new_seq) {
402
return NULL;
403
}
404
for (Py_ssize_t i = 0; i < len; i++) {
405
KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
406
asdl_seq_SET(new_seq, i, pair->value);
407
}
408
return new_seq;
409
}
410
411
/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
412
KeyPatternPair *
413
_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
414
{
415
KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
416
if (!a) {
417
return NULL;
418
}
419
a->key = key;
420
a->pattern = pattern;
421
return a;
422
}
423
424
/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
425
asdl_expr_seq *
426
_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
427
{
428
Py_ssize_t len = asdl_seq_LEN(seq);
429
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
430
if (!new_seq) {
431
return NULL;
432
}
433
for (Py_ssize_t i = 0; i < len; i++) {
434
KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
435
asdl_seq_SET(new_seq, i, pair->key);
436
}
437
return new_seq;
438
}
439
440
/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
441
asdl_pattern_seq *
442
_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
443
{
444
Py_ssize_t len = asdl_seq_LEN(seq);
445
asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
446
if (!new_seq) {
447
return NULL;
448
}
449
for (Py_ssize_t i = 0; i < len; i++) {
450
KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
451
asdl_seq_SET(new_seq, i, pair->pattern);
452
}
453
return new_seq;
454
}
455
456
/* Constructs a NameDefaultPair */
457
NameDefaultPair *
458
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
459
{
460
NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
461
if (!a) {
462
return NULL;
463
}
464
a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
465
a->value = value;
466
return a;
467
}
468
469
/* Constructs a SlashWithDefault */
470
SlashWithDefault *
471
_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
472
{
473
SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
474
if (!a) {
475
return NULL;
476
}
477
a->plain_names = plain_names;
478
a->names_with_defaults = names_with_defaults;
479
return a;
480
}
481
482
/* Constructs a StarEtc */
483
StarEtc *
484
_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
485
{
486
StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
487
if (!a) {
488
return NULL;
489
}
490
a->vararg = vararg;
491
a->kwonlyargs = kwonlyargs;
492
a->kwarg = kwarg;
493
return a;
494
}
495
496
asdl_seq *
497
_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
498
{
499
Py_ssize_t first_len = asdl_seq_LEN(a);
500
Py_ssize_t second_len = asdl_seq_LEN(b);
501
asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
502
if (!new_seq) {
503
return NULL;
504
}
505
506
int k = 0;
507
for (Py_ssize_t i = 0; i < first_len; i++) {
508
asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
509
}
510
for (Py_ssize_t i = 0; i < second_len; i++) {
511
asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
512
}
513
514
return new_seq;
515
}
516
517
static asdl_arg_seq*
518
_get_names(Parser *p, asdl_seq *names_with_defaults)
519
{
520
Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
521
asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
522
if (!seq) {
523
return NULL;
524
}
525
for (Py_ssize_t i = 0; i < len; i++) {
526
NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
527
asdl_seq_SET(seq, i, pair->arg);
528
}
529
return seq;
530
}
531
532
static asdl_expr_seq *
533
_get_defaults(Parser *p, asdl_seq *names_with_defaults)
534
{
535
Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
536
asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
537
if (!seq) {
538
return NULL;
539
}
540
for (Py_ssize_t i = 0; i < len; i++) {
541
NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
542
asdl_seq_SET(seq, i, pair->value);
543
}
544
return seq;
545
}
546
547
static int
548
_make_posonlyargs(Parser *p,
549
asdl_arg_seq *slash_without_default,
550
SlashWithDefault *slash_with_default,
551
asdl_arg_seq **posonlyargs) {
552
if (slash_without_default != NULL) {
553
*posonlyargs = slash_without_default;
554
}
555
else if (slash_with_default != NULL) {
556
asdl_arg_seq *slash_with_default_names =
557
_get_names(p, slash_with_default->names_with_defaults);
558
if (!slash_with_default_names) {
559
return -1;
560
}
561
*posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
562
p,
563
(asdl_seq*)slash_with_default->plain_names,
564
(asdl_seq*)slash_with_default_names);
565
}
566
else {
567
*posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
568
}
569
return *posonlyargs == NULL ? -1 : 0;
570
}
571
572
static int
573
_make_posargs(Parser *p,
574
asdl_arg_seq *plain_names,
575
asdl_seq *names_with_default,
576
asdl_arg_seq **posargs) {
577
if (plain_names != NULL && names_with_default != NULL) {
578
asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
579
if (!names_with_default_names) {
580
return -1;
581
}
582
*posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
583
p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
584
}
585
else if (plain_names == NULL && names_with_default != NULL) {
586
*posargs = _get_names(p, names_with_default);
587
}
588
else if (plain_names != NULL && names_with_default == NULL) {
589
*posargs = plain_names;
590
}
591
else {
592
*posargs = _Py_asdl_arg_seq_new(0, p->arena);
593
}
594
return *posargs == NULL ? -1 : 0;
595
}
596
597
static int
598
_make_posdefaults(Parser *p,
599
SlashWithDefault *slash_with_default,
600
asdl_seq *names_with_default,
601
asdl_expr_seq **posdefaults) {
602
if (slash_with_default != NULL && names_with_default != NULL) {
603
asdl_expr_seq *slash_with_default_values =
604
_get_defaults(p, slash_with_default->names_with_defaults);
605
if (!slash_with_default_values) {
606
return -1;
607
}
608
asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
609
if (!names_with_default_values) {
610
return -1;
611
}
612
*posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
613
p,
614
(asdl_seq*)slash_with_default_values,
615
(asdl_seq*)names_with_default_values);
616
}
617
else if (slash_with_default == NULL && names_with_default != NULL) {
618
*posdefaults = _get_defaults(p, names_with_default);
619
}
620
else if (slash_with_default != NULL && names_with_default == NULL) {
621
*posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
622
}
623
else {
624
*posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
625
}
626
return *posdefaults == NULL ? -1 : 0;
627
}
628
629
static int
630
_make_kwargs(Parser *p, StarEtc *star_etc,
631
asdl_arg_seq **kwonlyargs,
632
asdl_expr_seq **kwdefaults) {
633
if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
634
*kwonlyargs = _get_names(p, star_etc->kwonlyargs);
635
}
636
else {
637
*kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
638
}
639
640
if (*kwonlyargs == NULL) {
641
return -1;
642
}
643
644
if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
645
*kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
646
}
647
else {
648
*kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
649
}
650
651
if (*kwdefaults == NULL) {
652
return -1;
653
}
654
655
return 0;
656
}
657
658
/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
659
arguments_ty
660
_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
661
SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
662
asdl_seq *names_with_default, StarEtc *star_etc)
663
{
664
asdl_arg_seq *posonlyargs;
665
if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
666
return NULL;
667
}
668
669
asdl_arg_seq *posargs;
670
if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
671
return NULL;
672
}
673
674
asdl_expr_seq *posdefaults;
675
if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
676
return NULL;
677
}
678
679
arg_ty vararg = NULL;
680
if (star_etc != NULL && star_etc->vararg != NULL) {
681
vararg = star_etc->vararg;
682
}
683
684
asdl_arg_seq *kwonlyargs;
685
asdl_expr_seq *kwdefaults;
686
if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
687
return NULL;
688
}
689
690
arg_ty kwarg = NULL;
691
if (star_etc != NULL && star_etc->kwarg != NULL) {
692
kwarg = star_etc->kwarg;
693
}
694
695
return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
696
kwdefaults, kwarg, posdefaults, p->arena);
697
}
698
699
700
/* Constructs an empty arguments_ty object, that gets used when a function accepts no
701
* arguments. */
702
arguments_ty
703
_PyPegen_empty_arguments(Parser *p)
704
{
705
asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
706
if (!posonlyargs) {
707
return NULL;
708
}
709
asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
710
if (!posargs) {
711
return NULL;
712
}
713
asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
714
if (!posdefaults) {
715
return NULL;
716
}
717
asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
718
if (!kwonlyargs) {
719
return NULL;
720
}
721
asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
722
if (!kwdefaults) {
723
return NULL;
724
}
725
726
return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
727
kwdefaults, NULL, posdefaults, p->arena);
728
}
729
730
/* Encapsulates the value of an operator_ty into an AugOperator struct */
731
AugOperator *
732
_PyPegen_augoperator(Parser *p, operator_ty kind)
733
{
734
AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
735
if (!a) {
736
return NULL;
737
}
738
a->kind = kind;
739
return a;
740
}
741
742
/* Construct a FunctionDef equivalent to function_def, but with decorators */
743
stmt_ty
744
_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
745
{
746
assert(function_def != NULL);
747
if (function_def->kind == AsyncFunctionDef_kind) {
748
return _PyAST_AsyncFunctionDef(
749
function_def->v.AsyncFunctionDef.name,
750
function_def->v.AsyncFunctionDef.args,
751
function_def->v.AsyncFunctionDef.body, decorators,
752
function_def->v.AsyncFunctionDef.returns,
753
function_def->v.AsyncFunctionDef.type_comment,
754
function_def->v.AsyncFunctionDef.type_params,
755
function_def->lineno, function_def->col_offset,
756
function_def->end_lineno, function_def->end_col_offset, p->arena);
757
}
758
759
return _PyAST_FunctionDef(
760
function_def->v.FunctionDef.name,
761
function_def->v.FunctionDef.args,
762
function_def->v.FunctionDef.body, decorators,
763
function_def->v.FunctionDef.returns,
764
function_def->v.FunctionDef.type_comment,
765
function_def->v.FunctionDef.type_params,
766
function_def->lineno, function_def->col_offset,
767
function_def->end_lineno, function_def->end_col_offset, p->arena);
768
}
769
770
/* Construct a ClassDef equivalent to class_def, but with decorators */
771
stmt_ty
772
_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
773
{
774
assert(class_def != NULL);
775
return _PyAST_ClassDef(
776
class_def->v.ClassDef.name,
777
class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
778
class_def->v.ClassDef.body, decorators,
779
class_def->v.ClassDef.type_params,
780
class_def->lineno, class_def->col_offset, class_def->end_lineno,
781
class_def->end_col_offset, p->arena);
782
}
783
784
/* Construct a KeywordOrStarred */
785
KeywordOrStarred *
786
_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
787
{
788
KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
789
if (!a) {
790
return NULL;
791
}
792
a->element = element;
793
a->is_keyword = is_keyword;
794
return a;
795
}
796
797
/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
798
static int
799
_seq_number_of_starred_exprs(asdl_seq *seq)
800
{
801
int n = 0;
802
for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
803
KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
804
if (!k->is_keyword) {
805
n++;
806
}
807
}
808
return n;
809
}
810
811
/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
812
asdl_expr_seq *
813
_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
814
{
815
int new_len = _seq_number_of_starred_exprs(kwargs);
816
if (new_len == 0) {
817
return NULL;
818
}
819
asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
820
if (!new_seq) {
821
return NULL;
822
}
823
824
int idx = 0;
825
for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
826
KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
827
if (!k->is_keyword) {
828
asdl_seq_SET(new_seq, idx++, k->element);
829
}
830
}
831
return new_seq;
832
}
833
834
/* Return a new asdl_seq* with only the keywords in kwargs */
835
asdl_keyword_seq*
836
_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
837
{
838
Py_ssize_t len = asdl_seq_LEN(kwargs);
839
Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
840
if (new_len == 0) {
841
return NULL;
842
}
843
asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
844
if (!new_seq) {
845
return NULL;
846
}
847
848
int idx = 0;
849
for (Py_ssize_t i = 0; i < len; i++) {
850
KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
851
if (k->is_keyword) {
852
asdl_seq_SET(new_seq, idx++, k->element);
853
}
854
}
855
return new_seq;
856
}
857
858
expr_ty
859
_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
860
{
861
if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
862
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
863
return NULL;
864
}
865
return exp;
866
}
867
868
expr_ty
869
_PyPegen_ensure_real(Parser *p, expr_ty exp)
870
{
871
if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
872
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
873
return NULL;
874
}
875
return exp;
876
}
877
878
mod_ty
879
_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
880
asdl_type_ignore_seq *type_ignores = NULL;
881
Py_ssize_t num = p->type_ignore_comments.num_items;
882
if (num > 0) {
883
// Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
884
type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
885
if (type_ignores == NULL) {
886
return NULL;
887
}
888
for (int i = 0; i < num; i++) {
889
PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
890
if (tag == NULL) {
891
return NULL;
892
}
893
type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
894
tag, p->arena);
895
if (ti == NULL) {
896
return NULL;
897
}
898
asdl_seq_SET(type_ignores, i, ti);
899
}
900
}
901
return _PyAST_Module(a, type_ignores, p->arena);
902
}
903
904
PyObject *
905
_PyPegen_new_type_comment(Parser *p, const char *s)
906
{
907
PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
908
if (res == NULL) {
909
return NULL;
910
}
911
if (_PyArena_AddPyObject(p->arena, res) < 0) {
912
Py_DECREF(res);
913
return NULL;
914
}
915
return res;
916
}
917
918
arg_ty
919
_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
920
{
921
if (tc == NULL) {
922
return a;
923
}
924
const char *bytes = PyBytes_AsString(tc->bytes);
925
if (bytes == NULL) {
926
return NULL;
927
}
928
PyObject *tco = _PyPegen_new_type_comment(p, bytes);
929
if (tco == NULL) {
930
return NULL;
931
}
932
return _PyAST_arg(a->arg, a->annotation, tco,
933
a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
934
p->arena);
935
}
936
937
/* Checks if the NOTEQUAL token is valid given the current parser flags
938
0 indicates success and nonzero indicates failure (an exception may be set) */
939
int
940
_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
941
assert(t->bytes != NULL);
942
assert(t->type == NOTEQUAL);
943
944
const char* tok_str = PyBytes_AS_STRING(t->bytes);
945
if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
946
RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
947
return -1;
948
}
949
if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
950
return strcmp(tok_str, "!=");
951
}
952
return 0;
953
}
954
955
int
956
_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
957
if (name->kind != Name_kind) {
958
return 0;
959
}
960
const char* candidates[2] = {"print", "exec"};
961
for (int i=0; i<2; i++) {
962
if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
963
return 1;
964
}
965
}
966
return 0;
967
}
968
969
static ResultTokenWithMetadata *
970
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
971
{
972
ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
973
if (res == NULL) {
974
return NULL;
975
}
976
res->metadata = metadata;
977
res->result = result;
978
return res;
979
}
980
981
ResultTokenWithMetadata *
982
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
983
{
984
if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
985
return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
986
conv_token, conv,
987
"f-string: conversion type must come right after the exclamanation mark"
988
);
989
}
990
return result_token_with_metadata(p, conv, conv_token->metadata);
991
}
992
993
ResultTokenWithMetadata *
994
_PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, int lineno, int col_offset,
995
int end_lineno, int end_col_offset, PyArena *arena)
996
{
997
if (!spec) {
998
return NULL;
999
}
1000
expr_ty res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1001
if (!res) {
1002
return NULL;
1003
}
1004
return result_token_with_metadata(p, res, colon->metadata);
1005
}
1006
1007
const char *
1008
_PyPegen_get_expr_name(expr_ty e)
1009
{
1010
assert(e != NULL);
1011
switch (e->kind) {
1012
case Attribute_kind:
1013
return "attribute";
1014
case Subscript_kind:
1015
return "subscript";
1016
case Starred_kind:
1017
return "starred";
1018
case Name_kind:
1019
return "name";
1020
case List_kind:
1021
return "list";
1022
case Tuple_kind:
1023
return "tuple";
1024
case Lambda_kind:
1025
return "lambda";
1026
case Call_kind:
1027
return "function call";
1028
case BoolOp_kind:
1029
case BinOp_kind:
1030
case UnaryOp_kind:
1031
return "expression";
1032
case GeneratorExp_kind:
1033
return "generator expression";
1034
case Yield_kind:
1035
case YieldFrom_kind:
1036
return "yield expression";
1037
case Await_kind:
1038
return "await expression";
1039
case ListComp_kind:
1040
return "list comprehension";
1041
case SetComp_kind:
1042
return "set comprehension";
1043
case DictComp_kind:
1044
return "dict comprehension";
1045
case Dict_kind:
1046
return "dict literal";
1047
case Set_kind:
1048
return "set display";
1049
case JoinedStr_kind:
1050
case FormattedValue_kind:
1051
return "f-string expression";
1052
case Constant_kind: {
1053
PyObject *value = e->v.Constant.value;
1054
if (value == Py_None) {
1055
return "None";
1056
}
1057
if (value == Py_False) {
1058
return "False";
1059
}
1060
if (value == Py_True) {
1061
return "True";
1062
}
1063
if (value == Py_Ellipsis) {
1064
return "ellipsis";
1065
}
1066
return "literal";
1067
}
1068
case Compare_kind:
1069
return "comparison";
1070
case IfExp_kind:
1071
return "conditional expression";
1072
case NamedExpr_kind:
1073
return "named expression";
1074
default:
1075
PyErr_Format(PyExc_SystemError,
1076
"unexpected expression in assignment %d (line %d)",
1077
e->kind, e->lineno);
1078
return NULL;
1079
}
1080
}
1081
1082
expr_ty
1083
_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
1084
if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
1085
return comprehension->iter;
1086
}
1087
return PyPegen_last_item(comprehension->ifs, expr_ty);
1088
}
1089
1090
expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
1091
int lineno, int col_offset, int end_lineno,
1092
int end_col_offset, PyArena *arena) {
1093
Py_ssize_t args_len = asdl_seq_LEN(a);
1094
Py_ssize_t total_len = args_len;
1095
1096
if (b == NULL) {
1097
return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1098
end_lineno, end_col_offset, arena);
1099
1100
}
1101
1102
asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
1103
asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
1104
1105
if (starreds) {
1106
total_len += asdl_seq_LEN(starreds);
1107
}
1108
1109
asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
1110
1111
Py_ssize_t i = 0;
1112
for (i = 0; i < args_len; i++) {
1113
asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1114
}
1115
for (; i < total_len; i++) {
1116
asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
1117
}
1118
1119
return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
1120
col_offset, end_lineno, end_col_offset, arena);
1121
}
1122
1123
// AST Error reporting helpers
1124
1125
expr_ty
1126
_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
1127
{
1128
if (e == NULL) {
1129
return NULL;
1130
}
1131
1132
#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1133
Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1134
for (Py_ssize_t i = 0; i < len; i++) {\
1135
expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1136
expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1137
if (child != NULL) {\
1138
return child;\
1139
}\
1140
}\
1141
} while (0)
1142
1143
// We only need to visit List and Tuple nodes recursively as those
1144
// are the only ones that can contain valid names in targets when
1145
// they are parsed as expressions. Any other kind of expression
1146
// that is a container (like Sets or Dicts) is directly invalid and
1147
// we don't need to visit it recursively.
1148
1149
switch (e->kind) {
1150
case List_kind:
1151
VISIT_CONTAINER(e, List);
1152
return NULL;
1153
case Tuple_kind:
1154
VISIT_CONTAINER(e, Tuple);
1155
return NULL;
1156
case Starred_kind:
1157
if (targets_type == DEL_TARGETS) {
1158
return e;
1159
}
1160
return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
1161
case Compare_kind:
1162
// This is needed, because the `a in b` in `for a in b` gets parsed
1163
// as a comparison, and so we need to search the left side of the comparison
1164
// for invalid targets.
1165
if (targets_type == FOR_TARGETS) {
1166
cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
1167
if (cmpop == In) {
1168
return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
1169
}
1170
return NULL;
1171
}
1172
return e;
1173
case Name_kind:
1174
case Subscript_kind:
1175
case Attribute_kind:
1176
return NULL;
1177
default:
1178
return e;
1179
}
1180
}
1181
1182
void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
1183
int kwarg_unpacking = 0;
1184
for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
1185
keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
1186
if (!keyword->arg) {
1187
kwarg_unpacking = 1;
1188
}
1189
}
1190
1191
const char *msg = NULL;
1192
if (kwarg_unpacking) {
1193
msg = "positional argument follows keyword argument unpacking";
1194
} else {
1195
msg = "positional argument follows keyword argument";
1196
}
1197
1198
return RAISE_SYNTAX_ERROR(msg);
1199
}
1200
1201
void *
1202
_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
1203
{
1204
/* The rule that calls this function is 'args for_if_clauses'.
1205
For the input f(L, x for x in y), L and x are in args and
1206
the for is parsed as a for_if_clause. We have to check if
1207
len <= 1, so that input like dict((a, b) for a, b in x)
1208
gets successfully parsed and then we pass the last
1209
argument (x in the above example) as the location of the
1210
error */
1211
Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
1212
if (len <= 1) {
1213
return NULL;
1214
}
1215
1216
comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
1217
1218
return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1219
(expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
1220
_PyPegen_get_last_comprehension_item(last_comprehension),
1221
"Generator expression must be parenthesized"
1222
);
1223
}
1224
1225
// Fstring stuff
1226
1227
static expr_ty
1228
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1229
assert(PyUnicode_CheckExact(constant->v.Constant.value));
1230
1231
const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1232
if (bstr == NULL) {
1233
return NULL;
1234
}
1235
1236
size_t len;
1237
if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1238
len = 1;
1239
} else {
1240
len = strlen(bstr);
1241
}
1242
1243
is_raw = is_raw || strchr(bstr, '\\') == NULL;
1244
PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1245
if (str == NULL) {
1246
_Pypegen_raise_decode_error(p);
1247
return NULL;
1248
}
1249
if (_PyArena_AddPyObject(p->arena, str) < 0) {
1250
Py_DECREF(str);
1251
return NULL;
1252
}
1253
return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1254
constant->end_lineno, constant->end_col_offset,
1255
p->arena);
1256
}
1257
1258
static asdl_expr_seq *
1259
unpack_top_level_joined_strs(Parser *p, asdl_expr_seq *raw_expressions)
1260
{
1261
/* The parser might put multiple f-string values into an individual
1262
* JoinedStr node at the top level due to stuff like f-string debugging
1263
* expressions. This function flattens those and promotes them to the
1264
* upper level. Only simplifies AST, but the compiler already takes care
1265
* of the regular output, so this is not necessary if you are not going
1266
* to expose the output AST to Python level. */
1267
1268
Py_ssize_t i, req_size, raw_size;
1269
1270
req_size = raw_size = asdl_seq_LEN(raw_expressions);
1271
expr_ty expr;
1272
for (i = 0; i < raw_size; i++) {
1273
expr = asdl_seq_GET(raw_expressions, i);
1274
if (expr->kind == JoinedStr_kind) {
1275
req_size += asdl_seq_LEN(expr->v.JoinedStr.values) - 1;
1276
}
1277
}
1278
1279
asdl_expr_seq *expressions = _Py_asdl_expr_seq_new(req_size, p->arena);
1280
1281
Py_ssize_t raw_index, req_index = 0;
1282
for (raw_index = 0; raw_index < raw_size; raw_index++) {
1283
expr = asdl_seq_GET(raw_expressions, raw_index);
1284
if (expr->kind == JoinedStr_kind) {
1285
asdl_expr_seq *values = expr->v.JoinedStr.values;
1286
for (Py_ssize_t n = 0; n < asdl_seq_LEN(values); n++) {
1287
asdl_seq_SET(expressions, req_index, asdl_seq_GET(values, n));
1288
req_index++;
1289
}
1290
} else {
1291
asdl_seq_SET(expressions, req_index, expr);
1292
req_index++;
1293
}
1294
}
1295
return expressions;
1296
}
1297
1298
expr_ty
1299
_PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b) {
1300
asdl_expr_seq *expr = unpack_top_level_joined_strs(p, raw_expressions);
1301
Py_ssize_t n_items = asdl_seq_LEN(expr);
1302
1303
const char* quote_str = PyBytes_AsString(a->bytes);
1304
if (quote_str == NULL) {
1305
return NULL;
1306
}
1307
int is_raw = strpbrk(quote_str, "rR") != NULL;
1308
1309
asdl_expr_seq *seq = _Py_asdl_expr_seq_new(n_items, p->arena);
1310
if (seq == NULL) {
1311
return NULL;
1312
}
1313
1314
Py_ssize_t index = 0;
1315
for (Py_ssize_t i = 0; i < n_items; i++) {
1316
expr_ty item = asdl_seq_GET(expr, i);
1317
if (item->kind == Constant_kind) {
1318
item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1319
if (item == NULL) {
1320
return NULL;
1321
}
1322
1323
/* Tokenizer emits string parts even when the underlying string
1324
might become an empty value (e.g. FSTRING_MIDDLE with the value \\n)
1325
so we need to check for them and simplify it here. */
1326
if (PyUnicode_CheckExact(item->v.Constant.value)
1327
&& PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1328
continue;
1329
}
1330
}
1331
asdl_seq_SET(seq, index++, item);
1332
}
1333
1334
asdl_expr_seq *resized_exprs;
1335
if (index != n_items) {
1336
resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
1337
if (resized_exprs == NULL) {
1338
return NULL;
1339
}
1340
for (Py_ssize_t i = 0; i < index; i++) {
1341
asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
1342
}
1343
}
1344
else {
1345
resized_exprs = seq;
1346
}
1347
1348
return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1349
b->end_lineno, b->end_col_offset,
1350
p->arena);
1351
}
1352
1353
expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1354
Py_ssize_t bsize;
1355
char* bstr;
1356
if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
1357
return NULL;
1358
}
1359
PyObject* str = _PyPegen_decode_string(p, 0, bstr, bsize, tok);
1360
if (str == NULL) {
1361
return NULL;
1362
}
1363
if (_PyArena_AddPyObject(p->arena, str) < 0) {
1364
Py_DECREF(str);
1365
return NULL;
1366
}
1367
return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1368
tok->end_lineno, tok->end_col_offset,
1369
p->arena);
1370
}
1371
1372
expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1373
char* bstr = PyBytes_AsString(tok->bytes);
1374
if (bstr == NULL) {
1375
return NULL;
1376
}
1377
PyObject* str = PyUnicode_FromString(bstr);
1378
if (str == NULL) {
1379
return NULL;
1380
}
1381
if (_PyArena_AddPyObject(p->arena, str) < 0) {
1382
Py_DECREF(str);
1383
return NULL;
1384
}
1385
return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1386
tok->end_lineno, tok->end_col_offset,
1387
p->arena);
1388
}
1389
1390
expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1391
char* the_str = PyBytes_AsString(tok->bytes);
1392
if (the_str == NULL) {
1393
return NULL;
1394
}
1395
PyObject *s = _PyPegen_parse_string(p, tok);
1396
if (s == NULL) {
1397
_Pypegen_raise_decode_error(p);
1398
return NULL;
1399
}
1400
if (_PyArena_AddPyObject(p->arena, s) < 0) {
1401
Py_DECREF(s);
1402
return NULL;
1403
}
1404
PyObject *kind = NULL;
1405
if (the_str && the_str[0] == 'u') {
1406
kind = _PyPegen_new_identifier(p, "u");
1407
if (kind == NULL) {
1408
return NULL;
1409
}
1410
}
1411
return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1412
}
1413
1414
expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1415
ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1416
int end_lineno, int end_col_offset, PyArena *arena) {
1417
int conversion_val = -1;
1418
if (conversion != NULL) {
1419
expr_ty conversion_expr = (expr_ty) conversion->result;
1420
assert(conversion_expr->kind == Name_kind);
1421
Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
1422
1423
if (PyUnicode_GET_LENGTH(conversion_expr->v.Name.id) > 1 ||
1424
!(first == 's' || first == 'r' || first == 'a')) {
1425
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion_expr,
1426
"f-string: invalid conversion character %R: expected 's', 'r', or 'a'",
1427
conversion_expr->v.Name.id);
1428
return NULL;
1429
}
1430
1431
conversion_val = Py_SAFE_DOWNCAST(first, Py_UCS4, int);
1432
}
1433
else if (debug && !format) {
1434
/* If no conversion is specified, use !r for debug expressions */
1435
conversion_val = (int)'r';
1436
}
1437
1438
expr_ty formatted_value = _PyAST_FormattedValue(
1439
expression, conversion_val, format ? (expr_ty) format->result : NULL,
1440
lineno, col_offset, end_lineno,
1441
end_col_offset, arena
1442
);
1443
1444
if (debug) {
1445
/* Find the non whitespace token after the "=" */
1446
int debug_end_line, debug_end_offset;
1447
PyObject *debug_metadata;
1448
1449
if (conversion) {
1450
debug_end_line = ((expr_ty) conversion->result)->lineno;
1451
debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1452
debug_metadata = conversion->metadata;
1453
}
1454
else if (format) {
1455
debug_end_line = ((expr_ty) format->result)->lineno;
1456
debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1457
debug_metadata = format->metadata;
1458
}
1459
else {
1460
debug_end_line = end_lineno;
1461
debug_end_offset = end_col_offset;
1462
debug_metadata = closing_brace->metadata;
1463
}
1464
1465
expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1466
debug_end_offset - 1, p->arena);
1467
if (!debug_text) {
1468
return NULL;
1469
}
1470
1471
asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1472
asdl_seq_SET(values, 0, debug_text);
1473
asdl_seq_SET(values, 1, formatted_value);
1474
return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1475
}
1476
else {
1477
return formatted_value;
1478
}
1479
}
1480
1481
expr_ty
1482
_PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
1483
int lineno, int col_offset, int end_lineno,
1484
int end_col_offset, PyArena *arena)
1485
{
1486
Py_ssize_t len = asdl_seq_LEN(strings);
1487
assert(len > 0);
1488
1489
int f_string_found = 0;
1490
int unicode_string_found = 0;
1491
int bytes_found = 0;
1492
1493
Py_ssize_t i = 0;
1494
Py_ssize_t n_flattened_elements = 0;
1495
for (i = 0; i < len; i++) {
1496
expr_ty elem = asdl_seq_GET(strings, i);
1497
if (elem->kind == Constant_kind) {
1498
if (PyBytes_CheckExact(elem->v.Constant.value)) {
1499
bytes_found = 1;
1500
} else {
1501
unicode_string_found = 1;
1502
}
1503
n_flattened_elements++;
1504
} else {
1505
n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1506
f_string_found = 1;
1507
}
1508
}
1509
1510
if ((unicode_string_found || f_string_found) && bytes_found) {
1511
RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1512
return NULL;
1513
}
1514
1515
if (bytes_found) {
1516
PyObject* res = PyBytes_FromString("");
1517
1518
/* Bytes literals never get a kind, but just for consistency
1519
since they are represented as Constant nodes, we'll mirror
1520
the same behavior as unicode strings for determining the
1521
kind. */
1522
PyObject* kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1523
for (i = 0; i < len; i++) {
1524
expr_ty elem = asdl_seq_GET(strings, i);
1525
PyBytes_Concat(&res, elem->v.Constant.value);
1526
}
1527
if (!res || _PyArena_AddPyObject(arena, res) < 0) {
1528
Py_XDECREF(res);
1529
return NULL;
1530
}
1531
return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1532
}
1533
1534
if (!f_string_found && len == 1) {
1535
return asdl_seq_GET(strings, 0);
1536
}
1537
1538
asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1539
if (flattened == NULL) {
1540
return NULL;
1541
}
1542
1543
/* build flattened list */
1544
Py_ssize_t current_pos = 0;
1545
Py_ssize_t j = 0;
1546
for (i = 0; i < len; i++) {
1547
expr_ty elem = asdl_seq_GET(strings, i);
1548
if (elem->kind == Constant_kind) {
1549
asdl_seq_SET(flattened, current_pos++, elem);
1550
} else {
1551
for (j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1552
expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1553
if (subvalue == NULL) {
1554
return NULL;
1555
}
1556
asdl_seq_SET(flattened, current_pos++, subvalue);
1557
}
1558
}
1559
}
1560
1561
/* calculate folded element count */
1562
Py_ssize_t n_elements = 0;
1563
int prev_is_constant = 0;
1564
for (i = 0; i < n_flattened_elements; i++) {
1565
expr_ty elem = asdl_seq_GET(flattened, i);
1566
1567
/* The concatenation of a FormattedValue and an empty Contant should
1568
lead to the FormattedValue itself. Thus, we will not take any empty
1569
constants into account, just as in `_PyPegen_joined_str` */
1570
if (f_string_found && elem->kind == Constant_kind &&
1571
PyUnicode_CheckExact(elem->v.Constant.value) &&
1572
PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1573
continue;
1574
1575
if (!prev_is_constant || elem->kind != Constant_kind) {
1576
n_elements++;
1577
}
1578
prev_is_constant = elem->kind == Constant_kind;
1579
}
1580
1581
asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1582
if (values == NULL) {
1583
return NULL;
1584
}
1585
1586
/* build folded list */
1587
_PyUnicodeWriter writer;
1588
current_pos = 0;
1589
for (i = 0; i < n_flattened_elements; i++) {
1590
expr_ty elem = asdl_seq_GET(flattened, i);
1591
1592
/* if the current elem and the following are constants,
1593
fold them and all consequent constants */
1594
if (elem->kind == Constant_kind) {
1595
if (i + 1 < n_flattened_elements &&
1596
asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1597
expr_ty first_elem = elem;
1598
1599
/* When a string is getting concatenated, the kind of the string
1600
is determined by the first string in the concatenation
1601
sequence.
1602
1603
u"abc" "def" -> u"abcdef"
1604
"abc" u"abc" -> "abcabc" */
1605
PyObject *kind = elem->v.Constant.kind;
1606
1607
_PyUnicodeWriter_Init(&writer);
1608
expr_ty last_elem = elem;
1609
for (j = i; j < n_flattened_elements; j++) {
1610
expr_ty current_elem = asdl_seq_GET(flattened, j);
1611
if (current_elem->kind == Constant_kind) {
1612
if (_PyUnicodeWriter_WriteStr(
1613
&writer, current_elem->v.Constant.value)) {
1614
_PyUnicodeWriter_Dealloc(&writer);
1615
return NULL;
1616
}
1617
last_elem = current_elem;
1618
} else {
1619
break;
1620
}
1621
}
1622
i = j - 1;
1623
1624
PyObject *concat_str = _PyUnicodeWriter_Finish(&writer);
1625
if (concat_str == NULL) {
1626
_PyUnicodeWriter_Dealloc(&writer);
1627
return NULL;
1628
}
1629
if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1630
Py_DECREF(concat_str);
1631
return NULL;
1632
}
1633
elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1634
first_elem->col_offset,
1635
last_elem->end_lineno,
1636
last_elem->end_col_offset, p->arena);
1637
if (elem == NULL) {
1638
return NULL;
1639
}
1640
}
1641
1642
/* Drop all empty contanst strings */
1643
if (f_string_found &&
1644
PyUnicode_CheckExact(elem->v.Constant.value) &&
1645
PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1646
continue;
1647
}
1648
}
1649
1650
asdl_seq_SET(values, current_pos++, elem);
1651
}
1652
1653
if (!f_string_found) {
1654
assert(n_elements == 1);
1655
expr_ty elem = asdl_seq_GET(values, 0);
1656
assert(elem->kind == Constant_kind);
1657
return elem;
1658
}
1659
1660
assert(current_pos == n_elements);
1661
return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1662
}
1663
1664