Coverage Report

Created: 2026-07-14 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Parser/pegen.c
Line
Count
Source
1
#include <Python.h>
2
#include "pycore_ast.h"           // _PyAST_Validate(),
3
#include "pycore_pystate.h"       // _PyThreadState_GET()
4
#include "pycore_parser.h"        // _PYPEGEN_NSTATISTICS
5
#include "pycore_pyerrors.h"      // PyExc_IncompleteInputError
6
#include "pycore_runtime.h"       // _PyRuntime
7
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal
8
#include <errcode.h>
9
10
#include "lexer/lexer.h"
11
#include "tokenizer/tokenizer.h"
12
#include "tokenizer/helpers.h"
13
#include "pegen.h"
14
15
// Internal parser functions
16
17
asdl_stmt_seq*
18
_PyPegen_interactive_exit(Parser *p)
19
0
{
20
0
    if (p->errcode) {
21
0
        *(p->errcode) = E_EOF;
22
0
    }
23
0
    return NULL;
24
0
}
25
26
Py_ssize_t
27
_PyPegen_byte_offset_to_character_offset_line(PyObject *line, Py_ssize_t col_offset, Py_ssize_t end_col_offset)
28
2.38k
{
29
2.38k
    const unsigned char *data = (const unsigned char*)PyUnicode_AsUTF8(line);
30
31
2.38k
    Py_ssize_t len = 0;
32
12.3k
    while (col_offset < end_col_offset) {
33
9.96k
        Py_UCS4 ch = data[col_offset];
34
9.96k
        if (ch < 0x80) {
35
9.96k
            col_offset += 1;
36
9.96k
        } else if ((ch & 0xe0) == 0xc0) {
37
0
            col_offset += 2;
38
0
        } else if ((ch & 0xf0) == 0xe0) {
39
0
            col_offset += 3;
40
0
        } else if ((ch & 0xf8) == 0xf0) {
41
0
            col_offset += 4;
42
0
        } else {
43
0
            PyErr_SetString(PyExc_ValueError, "Invalid UTF-8 sequence");
44
0
            return -1;
45
0
        }
46
9.96k
        len++;
47
9.96k
    }
48
2.38k
    return len;
49
2.38k
}
50
51
Py_ssize_t
52
_PyPegen_byte_offset_to_character_offset_raw(const char* str, Py_ssize_t col_offset)
53
178k
{
54
178k
    Py_ssize_t len = (Py_ssize_t)strlen(str);
55
178k
    if (col_offset > len + 1) {
56
8
        col_offset = len + 1;
57
8
    }
58
178k
    assert(col_offset >= 0);
59
178k
    PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
60
178k
    if (!text) {
61
0
        return -1;
62
0
    }
63
178k
    Py_ssize_t size = PyUnicode_GET_LENGTH(text);
64
178k
    Py_DECREF(text);
65
178k
    return size;
66
178k
}
67
68
Py_ssize_t
69
_PyPegen_byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
70
178k
{
71
178k
    const char *str = PyUnicode_AsUTF8(line);
72
178k
    if (!str) {
73
0
        return -1;
74
0
    }
75
178k
    return _PyPegen_byte_offset_to_character_offset_raw(str, col_offset);
76
178k
}
77
78
// Here, mark is the start of the node, while p->mark is the end.
79
// If node==NULL, they should be the same.
80
int
81
_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
82
15.4M
{
83
    // Insert in front
84
15.4M
    Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
85
15.4M
    if (m == NULL) {
86
0
        return -1;
87
0
    }
88
15.4M
    m->type = type;
89
15.4M
    m->node = node;
90
15.4M
    m->mark = p->mark;
91
15.4M
    m->next = p->tokens[mark]->memo;
92
15.4M
    p->tokens[mark]->memo = m;
93
15.4M
    return 0;
94
15.4M
}
95
96
// Like _PyPegen_insert_memo(), but updates an existing node if found.
97
int
98
_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
99
10.4M
{
100
51.5M
    for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
101
44.0M
        if (m->type == type) {
102
            // Update existing node.
103
2.87M
            m->node = node;
104
2.87M
            m->mark = p->mark;
105
2.87M
            return 0;
106
2.87M
        }
107
44.0M
    }
108
    // Insert new node.
109
7.54M
    return _PyPegen_insert_memo(p, mark, type, node);
110
10.4M
}
111
112
static int
113
init_normalization(Parser *p)
114
65.0k
{
115
65.0k
    if (p->normalize) {
116
63.3k
        return 1;
117
63.3k
    }
118
1.64k
    p->normalize = PyImport_ImportModuleAttrString("unicodedata", "normalize");
119
1.64k
    if (!p->normalize)
120
0
    {
121
0
        return 0;
122
0
    }
123
1.64k
    return 1;
124
1.64k
}
125
126
static int
127
100k
growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
128
100k
    assert(initial_size > 0);
129
100k
    arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
130
100k
    arr->size = initial_size;
131
100k
    arr->num_items = 0;
132
133
100k
    return arr->items != NULL;
134
100k
}
135
136
static int
137
0
growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
138
0
    if (arr->num_items >= arr->size) {
139
0
        size_t new_size = arr->size * 2;
140
0
        void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
141
0
        if (!new_items_array) {
142
0
            return 0;
143
0
        }
144
0
        arr->items = new_items_array;
145
0
        arr->size = new_size;
146
0
    }
147
148
0
    arr->items[arr->num_items].lineno = lineno;
149
0
    arr->items[arr->num_items].comment = comment;  // Take ownership
150
0
    arr->num_items++;
151
0
    return 1;
152
0
}
153
154
static void
155
100k
growable_comment_array_deallocate(growable_comment_array *arr) {
156
100k
    for (unsigned i = 0; i < arr->num_items; i++) {
157
0
        PyMem_Free(arr->items[i].comment);
158
0
    }
159
100k
    PyMem_Free(arr->items);
160
100k
}
161
162
static int
163
_get_keyword_or_name_type(Parser *p, struct token *new_token)
164
593k
{
165
593k
    Py_ssize_t name_len = new_token->end_col_offset - new_token->col_offset;
166
593k
    assert(name_len > 0);
167
168
593k
    if (name_len >= p->n_keyword_lists ||
169
570k
        p->keywords[name_len] == NULL ||
170
570k
        p->keywords[name_len]->type == -1) {
171
311k
        return NAME;
172
311k
    }
173
1.51M
    for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
174
1.40M
        if (strncmp(k->str, new_token->start, (size_t)name_len) == 0) {
175
171k
            return k->type;
176
171k
        }
177
1.40M
    }
178
110k
    return NAME;
179
282k
}
180
181
static int
182
1.83M
initialize_token(Parser *p, Token *parser_token, struct token *new_token, int token_type) {
183
1.83M
    assert(parser_token != NULL);
184
185
1.83M
    parser_token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, new_token) : token_type;
186
1.83M
    parser_token->bytes = PyBytes_FromStringAndSize(new_token->start, new_token->end - new_token->start);
187
1.83M
    if (parser_token->bytes == NULL) {
188
0
        return -1;
189
0
    }
190
1.83M
    if (_PyArena_AddPyObject(p->arena, parser_token->bytes) < 0) {
191
0
        Py_DECREF(parser_token->bytes);
192
0
        return -1;
193
0
    }
194
195
1.83M
    parser_token->metadata = NULL;
196
1.83M
    if (new_token->metadata != NULL) {
197
13.3k
        if (_PyArena_AddPyObject(p->arena, new_token->metadata) < 0) {
198
0
            Py_DECREF(new_token->metadata);
199
0
            return -1;
200
0
        }
201
13.3k
        parser_token->metadata = new_token->metadata;
202
13.3k
        new_token->metadata = NULL;
203
13.3k
    }
204
205
1.83M
    parser_token->level = new_token->level;
206
1.83M
    parser_token->lineno = new_token->lineno;
207
1.83M
    parser_token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->col_offset
208
1.83M
                                                                    : new_token->col_offset;
209
1.83M
    parser_token->end_lineno = new_token->end_lineno;
210
1.83M
    parser_token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->end_col_offset
211
1.83M
                                                                 : new_token->end_col_offset;
212
213
1.83M
    p->fill += 1;
214
215
1.83M
    if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
216
0
        return _Pypegen_raise_decode_error(p);
217
0
    }
218
219
1.83M
    return (token_type == ERRORTOKEN ? _Pypegen_tokenizer_error(p) : 0);
220
1.83M
}
221
222
static int
223
240k
_resize_tokens_array(Parser *p) {
224
240k
    int newsize = p->size * 2;
225
240k
    Token **new_tokens = PyMem_Realloc(p->tokens, (size_t)newsize * sizeof(Token *));
226
240k
    if (new_tokens == NULL) {
227
0
        PyErr_NoMemory();
228
0
        return -1;
229
0
    }
230
240k
    p->tokens = new_tokens;
231
232
2.70M
    for (int i = p->size; i < newsize; i++) {
233
2.46M
        p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
234
2.46M
        if (p->tokens[i] == NULL) {
235
0
            p->size = i; // Needed, in order to cleanup correctly after parser fails
236
0
            PyErr_NoMemory();
237
0
            return -1;
238
0
        }
239
2.46M
    }
240
240k
    p->size = newsize;
241
240k
    return 0;
242
240k
}
243
244
int
245
_PyPegen_fill_token(Parser *p)
246
1.83M
{
247
1.83M
    struct token new_token;
248
1.83M
    _PyToken_Init(&new_token);
249
1.83M
    int type = _PyTokenizer_Get(p->tok, &new_token);
250
251
    // Record and skip '# type: ignore' comments
252
1.83M
    while (type == TYPE_IGNORE) {
253
0
        Py_ssize_t len = new_token.end_col_offset - new_token.col_offset;
254
0
        char *tag = PyMem_Malloc((size_t)len + 1);
255
0
        if (tag == NULL) {
256
0
            PyErr_NoMemory();
257
0
            goto error;
258
0
        }
259
0
        strncpy(tag, new_token.start, (size_t)len);
260
0
        tag[len] = '\0';
261
        // Ownership of tag passes to the growable array
262
0
        if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
263
0
            PyErr_NoMemory();
264
0
            goto error;
265
0
        }
266
0
        type = _PyTokenizer_Get(p->tok, &new_token);
267
0
    }
268
269
    // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
270
1.83M
    if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
271
0
        type = NEWLINE; /* Add an extra newline */
272
0
        p->parsing_started = 0;
273
274
0
        if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
275
0
            p->tok->pendin = -p->tok->indent;
276
0
            p->tok->indent = 0;
277
0
        }
278
0
    }
279
1.83M
    else {
280
1.83M
        p->parsing_started = 1;
281
1.83M
    }
282
283
    // Check if we are at the limit of the token array capacity and resize if needed
284
1.83M
    if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
285
0
        goto error;
286
0
    }
287
288
1.83M
    Token *t = p->tokens[p->fill];
289
1.83M
    return initialize_token(p, t, &new_token, type);
290
0
error:
291
0
    _PyToken_Free(&new_token);
292
0
    return -1;
293
1.83M
}
294
295
#if defined(Py_DEBUG)
296
// Instrumentation to count the effectiveness of memoization.
297
// The array counts the number of tokens skipped by memoization,
298
// indexed by type.
299
300
#define NSTATISTICS _PYPEGEN_NSTATISTICS
301
#define memo_statistics _PyRuntime.parser.memo_statistics
302
303
void
304
_PyPegen_clear_memo_statistics(void)
305
{
306
    PyMutex_Lock(&_PyRuntime.parser.mutex);
307
    for (int i = 0; i < NSTATISTICS; i++) {
308
        memo_statistics[i] = 0;
309
    }
310
    PyMutex_Unlock(&_PyRuntime.parser.mutex);
311
}
312
313
PyObject *
314
_PyPegen_get_memo_statistics(void)
315
{
316
    PyObject *ret = PyList_New(NSTATISTICS);
317
    if (ret == NULL) {
318
        return NULL;
319
    }
320
321
    PyMutex_Lock(&_PyRuntime.parser.mutex);
322
    for (int i = 0; i < NSTATISTICS; i++) {
323
        PyObject *value = PyLong_FromLong(memo_statistics[i]);
324
        if (value == NULL) {
325
            PyMutex_Unlock(&_PyRuntime.parser.mutex);
326
            Py_DECREF(ret);
327
            return NULL;
328
        }
329
        // PyList_SetItem borrows a reference to value.
330
        if (PyList_SetItem(ret, i, value) < 0) {
331
            PyMutex_Unlock(&_PyRuntime.parser.mutex);
332
            Py_DECREF(ret);
333
            return NULL;
334
        }
335
    }
336
    PyMutex_Unlock(&_PyRuntime.parser.mutex);
337
    return ret;
338
}
339
#endif
340
341
int  // bool
342
_PyPegen_is_memoized(Parser *p, int type, void *pres)
343
57.1M
{
344
57.1M
    if (p->mark == p->fill) {
345
504k
        if (_PyPegen_fill_token(p) < 0) {
346
786
            p->error_indicator = 1;
347
786
            return -1;
348
786
        }
349
504k
    }
350
351
57.1M
    Token *t = p->tokens[p->mark];
352
353
161M
    for (Memo *m = t->memo; m != NULL; m = m->next) {
354
146M
        if (m->type == type) {
355
#if defined(Py_DEBUG)
356
            if (0 <= type && type < NSTATISTICS) {
357
                long count = m->mark - p->mark;
358
                // A memoized negative result counts for one.
359
                if (count <= 0) {
360
                    count = 1;
361
                }
362
                PyMutex_Lock(&_PyRuntime.parser.mutex);
363
                memo_statistics[type] += count;
364
                PyMutex_Unlock(&_PyRuntime.parser.mutex);
365
            }
366
#endif
367
41.4M
            p->mark = m->mark;
368
41.4M
            *(void **)(pres) = m->node;
369
41.4M
            return 1;
370
41.4M
        }
371
146M
    }
372
15.6M
    return 0;
373
57.1M
}
374
375
#define LOOKAHEAD1(NAME, RES_TYPE)                                  \
376
    int                                                             \
377
    NAME (int positive, RES_TYPE (func)(Parser *), Parser *p)       \
378
3.56M
    {                                                               \
379
3.56M
        int mark = p->mark;                                         \
380
3.56M
        void *res = func(p);                                        \
381
3.56M
        p->mark = mark;                                             \
382
3.56M
        return (res != NULL) == positive;                           \
383
3.56M
    }
384
385
3.56M
LOOKAHEAD1(_PyPegen_lookahead, void *)
386
1.07k
LOOKAHEAD1(_PyPegen_lookahead_for_expr, expr_ty)
387
0
LOOKAHEAD1(_PyPegen_lookahead_for_stmt, stmt_ty)
388
#undef LOOKAHEAD1
389
390
#define LOOKAHEAD2(NAME, RES_TYPE, T)                                   \
391
    int                                                                 \
392
    NAME (int positive, RES_TYPE (func)(Parser *, T), Parser *p, T arg) \
393
11.7M
    {                                                                   \
394
11.7M
        int mark = p->mark;                                             \
395
11.7M
        void *res = func(p, arg);                                       \
396
11.7M
        p->mark = mark;                                                 \
397
11.7M
        return (res != NULL) == positive;                               \
398
11.7M
    }
399
400
11.4M
LOOKAHEAD2(_PyPegen_lookahead_with_int, Token *, int)
401
349k
LOOKAHEAD2(_PyPegen_lookahead_with_string, expr_ty, const char *)
402
#undef LOOKAHEAD2
403
404
Token *
405
_PyPegen_expect_token(Parser *p, int type)
406
109M
{
407
109M
    if (p->mark == p->fill) {
408
916k
        if (_PyPegen_fill_token(p) < 0) {
409
2.02k
            p->error_indicator = 1;
410
2.02k
            return NULL;
411
2.02k
        }
412
916k
    }
413
109M
    Token *t = p->tokens[p->mark];
414
109M
    if (t->type != type) {
415
87.9M
       return NULL;
416
87.9M
    }
417
21.6M
    p->mark += 1;
418
21.6M
    return t;
419
109M
}
420
421
void*
422
0
_PyPegen_expect_forced_result(Parser *p, void* result, const char* expected) {
423
424
0
    if (p->error_indicator == 1) {
425
0
        return NULL;
426
0
    }
427
0
    if (result == NULL) {
428
0
        RAISE_SYNTAX_ERROR("expected (%s)", expected);
429
0
        return NULL;
430
0
    }
431
0
    return result;
432
0
}
433
434
Token *
435
14.8k
_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
436
437
14.8k
    if (p->error_indicator == 1) {
438
0
        return NULL;
439
0
    }
440
441
14.8k
    if (p->mark == p->fill) {
442
3.75k
        if (_PyPegen_fill_token(p) < 0) {
443
2
            p->error_indicator = 1;
444
2
            return NULL;
445
2
        }
446
3.75k
    }
447
14.8k
    Token *t = p->tokens[p->mark];
448
14.8k
    if (t->type != type) {
449
122
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
450
122
        return NULL;
451
122
    }
452
14.7k
    p->mark += 1;
453
14.7k
    return t;
454
14.8k
}
455
456
expr_ty
457
_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
458
1.27M
{
459
1.27M
    if (p->mark == p->fill) {
460
4.80k
        if (_PyPegen_fill_token(p) < 0) {
461
5
            p->error_indicator = 1;
462
5
            return NULL;
463
5
        }
464
4.80k
    }
465
1.27M
    Token *t = p->tokens[p->mark];
466
1.27M
    if (t->type != NAME) {
467
1.00M
        return NULL;
468
1.00M
    }
469
266k
    const char *s = PyBytes_AsString(t->bytes);
470
266k
    if (!s) {
471
0
        p->error_indicator = 1;
472
0
        return NULL;
473
0
    }
474
266k
    if (strcmp(s, keyword) != 0) {
475
235k
        return NULL;
476
235k
    }
477
30.3k
    return _PyPegen_name_token(p);
478
266k
}
479
480
Token *
481
_PyPegen_get_last_nonnwhitespace_token(Parser *p)
482
11.4M
{
483
11.4M
    assert(p->mark >= 0);
484
11.4M
    Token *token = NULL;
485
11.4M
    for (int m = p->mark - 1; m >= 0; m--) {
486
11.4M
        token = p->tokens[m];
487
11.4M
        if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
488
11.4M
            break;
489
11.4M
        }
490
11.4M
    }
491
11.4M
    return token;
492
11.4M
}
493
494
PyObject *
495
_PyPegen_new_identifier(Parser *p, const char *n)
496
12.1M
{
497
12.1M
    PyObject *id = PyUnicode_DecodeUTF8(n, (Py_ssize_t)strlen(n), NULL);
498
12.1M
    if (!id) {
499
0
        goto error;
500
0
    }
501
    /* Check whether there are non-ASCII characters in the
502
       identifier; if so, normalize to NFKC. */
503
12.1M
    if (!PyUnicode_IS_ASCII(id))
504
65.0k
    {
505
65.0k
        if (!init_normalization(p))
506
0
        {
507
0
            Py_DECREF(id);
508
0
            goto error;
509
0
        }
510
65.0k
        PyObject *form = PyUnicode_InternFromString("NFKC");
511
65.0k
        if (form == NULL)
512
0
        {
513
0
            Py_DECREF(id);
514
0
            goto error;
515
0
        }
516
65.0k
        PyObject *args[2] = {form, id};
517
65.0k
        PyObject *id2 = PyObject_Vectorcall(p->normalize, args, 2, NULL);
518
65.0k
        Py_DECREF(id);
519
65.0k
        Py_DECREF(form);
520
65.0k
        if (!id2) {
521
0
            goto error;
522
0
        }
523
524
65.0k
        if (!PyUnicode_Check(id2))
525
0
        {
526
0
            PyErr_Format(PyExc_TypeError,
527
0
                         "unicodedata.normalize() must return a string, not "
528
0
                         "%.200s",
529
0
                         _PyType_Name(Py_TYPE(id2)));
530
0
            Py_DECREF(id2);
531
0
            goto error;
532
0
        }
533
65.0k
        id = id2;
534
65.0k
    }
535
12.1M
    static const char * const forbidden[] = {
536
12.1M
        "None",
537
12.1M
        "True",
538
12.1M
        "False",
539
12.1M
        NULL
540
12.1M
    };
541
48.5M
    for (int i = 0; forbidden[i] != NULL; i++) {
542
36.4M
        if (_PyUnicode_EqualToASCIIString(id, forbidden[i])) {
543
0
            PyErr_Format(PyExc_ValueError,
544
0
                         "identifier field can't represent '%s' constant",
545
0
                         forbidden[i]);
546
0
            Py_DECREF(id);
547
0
            goto error;
548
0
        }
549
36.4M
    }
550
12.1M
    PyInterpreterState *interp = _PyInterpreterState_GET();
551
12.1M
    _PyUnicode_InternImmortal(interp, &id);
552
12.1M
    if (_PyArena_AddPyObject(p->arena, id) < 0)
553
0
    {
554
0
        Py_DECREF(id);
555
0
        goto error;
556
0
    }
557
12.1M
    return id;
558
559
0
error:
560
0
    p->error_indicator = 1;
561
0
    return NULL;
562
12.1M
}
563
564
static expr_ty
565
_PyPegen_name_from_token(Parser *p, Token* t)
566
32.7M
{
567
32.7M
    if (t == NULL) {
568
20.6M
        return NULL;
569
20.6M
    }
570
12.1M
    const char *s = PyBytes_AsString(t->bytes);
571
12.1M
    if (!s) {
572
0
        p->error_indicator = 1;
573
0
        return NULL;
574
0
    }
575
12.1M
    PyObject *id = _PyPegen_new_identifier(p, s);
576
12.1M
    if (id == NULL) {
577
0
        p->error_indicator = 1;
578
0
        return NULL;
579
0
    }
580
12.1M
    return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
581
12.1M
                       t->end_col_offset, p->arena);
582
12.1M
}
583
584
expr_ty
585
_PyPegen_name_token(Parser *p)
586
32.7M
{
587
32.7M
    Token *t = _PyPegen_expect_token(p, NAME);
588
32.7M
    return _PyPegen_name_from_token(p, t);
589
32.7M
}
590
591
void *
592
_PyPegen_string_token(Parser *p)
593
1.85M
{
594
1.85M
    return _PyPegen_expect_token(p, STRING);
595
1.85M
}
596
597
379k
expr_ty _PyPegen_soft_keyword_token(Parser *p) {
598
379k
    Token *t = _PyPegen_expect_token(p, NAME);
599
379k
    if (t == NULL) {
600
307k
        return NULL;
601
307k
    }
602
71.5k
    char *the_token;
603
71.5k
    Py_ssize_t size;
604
71.5k
    PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
605
406k
    for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
606
341k
        if (strlen(*keyword) == (size_t)size &&
607
62.8k
            strncmp(*keyword, the_token, (size_t)size) == 0) {
608
5.70k
            return _PyPegen_name_from_token(p, t);
609
5.70k
        }
610
341k
    }
611
65.8k
    return NULL;
612
71.5k
}
613
614
static PyObject *
615
parsenumber_raw(const char *s)
616
250k
{
617
250k
    const char *end;
618
250k
    long x;
619
250k
    double dx;
620
250k
    Py_complex compl;
621
250k
    int imflag;
622
623
250k
    assert(s != NULL);
624
250k
    errno = 0;
625
250k
    end = s + strlen(s) - 1;
626
250k
    imflag = *end == 'j' || *end == 'J';
627
250k
    if (s[0] == '0') {
628
66.6k
        x = (long)PyOS_strtoul(s, (char **)&end, 0);
629
66.6k
        if (x < 0 && errno == 0) {
630
857
            return PyLong_FromString(s, (char **)0, 0);
631
857
        }
632
66.6k
    }
633
183k
    else {
634
183k
        x = PyOS_strtol(s, (char **)&end, 0);
635
183k
    }
636
249k
    if (*end == '\0') {
637
188k
        if (errno != 0) {
638
3.26k
            return PyLong_FromString(s, (char **)0, 0);
639
3.26k
        }
640
184k
        return PyLong_FromLong(x);
641
188k
    }
642
    /* XXX Huge floats may silently fail */
643
61.0k
    if (imflag) {
644
11.9k
        compl.real = 0.;
645
11.9k
        compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
646
11.9k
        if (compl.imag == -1.0 && PyErr_Occurred()) {
647
0
            return NULL;
648
0
        }
649
11.9k
        return PyComplex_FromCComplex(compl);
650
11.9k
    }
651
49.0k
    dx = PyOS_string_to_double(s, NULL, NULL);
652
49.0k
    if (dx == -1.0 && PyErr_Occurred()) {
653
0
        return NULL;
654
0
    }
655
49.0k
    return PyFloat_FromDouble(dx);
656
49.0k
}
657
658
static PyObject *
659
parsenumber(const char *s)
660
250k
{
661
250k
    char *dup;
662
250k
    char *end;
663
250k
    PyObject *res = NULL;
664
665
250k
    assert(s != NULL);
666
667
250k
    if (strchr(s, '_') == NULL) {
668
248k
        return parsenumber_raw(s);
669
248k
    }
670
    /* Create a duplicate without underscores. */
671
1.81k
    dup = PyMem_Malloc(strlen(s) + 1);
672
1.81k
    if (dup == NULL) {
673
0
        return PyErr_NoMemory();
674
0
    }
675
1.81k
    end = dup;
676
73.2k
    for (; *s; s++) {
677
71.4k
        if (*s != '_') {
678
54.0k
            *end++ = *s;
679
54.0k
        }
680
71.4k
    }
681
1.81k
    *end = '\0';
682
1.81k
    res = parsenumber_raw(dup);
683
1.81k
    PyMem_Free(dup);
684
1.81k
    return res;
685
1.81k
}
686
687
expr_ty
688
_PyPegen_number_token(Parser *p)
689
1.32M
{
690
1.32M
    Token *t = _PyPegen_expect_token(p, NUMBER);
691
1.32M
    if (t == NULL) {
692
1.07M
        return NULL;
693
1.07M
    }
694
695
250k
    const char *num_raw = PyBytes_AsString(t->bytes);
696
250k
    if (num_raw == NULL) {
697
0
        p->error_indicator = 1;
698
0
        return NULL;
699
0
    }
700
701
250k
    if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
702
0
        p->error_indicator = 1;
703
0
        return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
704
0
                                  "in Python 3.6 and greater");
705
0
    }
706
707
250k
    PyObject *c = parsenumber(num_raw);
708
709
250k
    if (c == NULL) {
710
0
        p->error_indicator = 1;
711
0
        PyThreadState *tstate = _PyThreadState_GET();
712
        // The only way a ValueError should happen in _this_ code is via
713
        // PyLong_FromString hitting a length limit.
714
0
        if (tstate->current_exception != NULL &&
715
0
            Py_TYPE(tstate->current_exception) == (PyTypeObject *)PyExc_ValueError
716
0
        ) {
717
0
            PyObject *exc = PyErr_GetRaisedException();
718
            /* Intentionally omitting columns to avoid a wall of 1000s of '^'s
719
             * on the error message. Nobody is going to overlook their huge
720
             * numeric literal once given the line. */
721
0
            RAISE_ERROR_KNOWN_LOCATION(
722
0
                p, PyExc_SyntaxError,
723
0
                t->lineno, -1 /* col_offset */,
724
0
                t->end_lineno, -1 /* end_col_offset */,
725
0
                "%S - Consider hexadecimal for huge integer literals "
726
0
                "to avoid decimal conversion limits.",
727
0
                exc);
728
0
            Py_DECREF(exc);
729
0
        }
730
0
        return NULL;
731
0
    }
732
733
250k
    if (_PyArena_AddPyObject(p->arena, c) < 0) {
734
0
        Py_DECREF(c);
735
0
        p->error_indicator = 1;
736
0
        return NULL;
737
0
    }
738
739
250k
    return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
740
250k
                           t->end_col_offset, p->arena);
741
250k
}
742
743
/* Check that the source for a single input statement really is a single
744
   statement by looking at what is left in the buffer after parsing.
745
   Trailing whitespace and comments are OK. */
746
static int // bool
747
bad_single_statement(Parser *p)
748
0
{
749
0
    char *cur = p->tok->cur;
750
0
    char c = *cur;
751
752
0
    for (;;) {
753
0
        while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
754
0
            c = *++cur;
755
0
        }
756
757
0
        if (!c) {
758
0
            return 0;
759
0
        }
760
761
0
        if (c != '#') {
762
0
            return 1;
763
0
        }
764
765
        /* Suck up comment. */
766
0
        while (c && c != '\n') {
767
0
            c = *++cur;
768
0
        }
769
0
    }
770
0
}
771
772
static int
773
compute_parser_flags(PyCompilerFlags *flags)
774
100k
{
775
100k
    int parser_flags = 0;
776
100k
    if (!flags) {
777
108
        return 0;
778
108
    }
779
100k
    if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
780
0
        parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
781
0
    }
782
100k
    if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
783
81.0k
        parser_flags |= PyPARSE_IGNORE_COOKIE;
784
81.0k
    }
785
100k
    if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
786
0
        parser_flags |= PyPARSE_BARRY_AS_BDFL;
787
0
    }
788
100k
    if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
789
0
        parser_flags |= PyPARSE_TYPE_COMMENTS;
790
0
    }
791
100k
    if (flags->cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT) {
792
0
        parser_flags |= PyPARSE_ALLOW_INCOMPLETE_INPUT;
793
0
    }
794
100k
    return parser_flags;
795
100k
}
796
797
// Parser API
798
799
Parser *
800
_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
801
                    int feature_version, int *errcode, const char* source, PyArena *arena)
802
100k
{
803
100k
    Parser *p = PyMem_Malloc(sizeof(Parser));
804
100k
    if (p == NULL) {
805
0
        return (Parser *) PyErr_NoMemory();
806
0
    }
807
100k
    assert(tok != NULL);
808
100k
    tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
809
100k
    p->tok = tok;
810
100k
    p->keywords = NULL;
811
100k
    p->n_keyword_lists = -1;
812
100k
    p->soft_keywords = NULL;
813
100k
    p->tokens = PyMem_Malloc(sizeof(Token *));
814
100k
    if (!p->tokens) {
815
0
        PyMem_Free(p);
816
0
        return (Parser *) PyErr_NoMemory();
817
0
    }
818
100k
    p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
819
100k
    if (!p->tokens[0]) {
820
0
        PyMem_Free(p->tokens);
821
0
        PyMem_Free(p);
822
0
        return (Parser *) PyErr_NoMemory();
823
0
    }
824
100k
    if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
825
0
        PyMem_Free(p->tokens[0]);
826
0
        PyMem_Free(p->tokens);
827
0
        PyMem_Free(p);
828
0
        return (Parser *) PyErr_NoMemory();
829
0
    }
830
831
100k
    p->mark = 0;
832
100k
    p->fill = 0;
833
100k
    p->size = 1;
834
835
100k
    p->errcode = errcode;
836
100k
    p->arena = arena;
837
100k
    p->start_rule = start_rule;
838
100k
    p->parsing_started = 0;
839
100k
    p->normalize = NULL;
840
100k
    p->error_indicator = 0;
841
842
100k
    p->starting_lineno = 0;
843
100k
    p->starting_col_offset = 0;
844
100k
    p->flags = flags;
845
100k
    p->feature_version = feature_version;
846
100k
    p->known_err_token = NULL;
847
100k
    p->level = 0;
848
100k
    p->call_invalid_rules = 0;
849
100k
    p->last_stmt_location.lineno = 0;
850
100k
    p->last_stmt_location.col_offset = 0;
851
100k
    p->last_stmt_location.end_lineno = 0;
852
100k
    p->last_stmt_location.end_col_offset = 0;
853
#ifdef Py_DEBUG
854
    p->debug = _Py_GetConfig()->parser_debug;
855
#endif
856
100k
    return p;
857
100k
}
858
859
void
860
_PyPegen_Parser_Free(Parser *p)
861
100k
{
862
100k
    Py_XDECREF(p->normalize);
863
2.66M
    for (int i = 0; i < p->size; i++) {
864
2.56M
        PyMem_Free(p->tokens[i]);
865
2.56M
    }
866
100k
    PyMem_Free(p->tokens);
867
100k
    growable_comment_array_deallocate(&p->type_ignore_comments);
868
100k
    PyMem_Free(p);
869
100k
}
870
871
static void
872
reset_parser_state_for_error_pass(Parser *p)
873
92.5k
{
874
92.5k
    p->last_stmt_location.lineno = 0;
875
92.5k
    p->last_stmt_location.col_offset = 0;
876
92.5k
    p->last_stmt_location.end_lineno = 0;
877
92.5k
    p->last_stmt_location.end_col_offset = 0;
878
913k
    for (int i = 0; i < p->fill; i++) {
879
821k
        p->tokens[i]->memo = NULL;
880
821k
    }
881
92.5k
    p->mark = 0;
882
92.5k
    p->call_invalid_rules = 1;
883
    // Don't try to get extra tokens in interactive mode when trying to
884
    // raise specialized errors in the second pass.
885
92.5k
    p->tok->interactive_underflow = IUNDERFLOW_STOP;
886
92.5k
}
887
888
static inline int
889
0
_is_end_of_source(Parser *p) {
890
0
    int err = p->tok->done;
891
0
    return err == E_EOF || err == E_EOFS || err == E_EOLS;
892
0
}
893
894
static void
895
92.4k
_PyPegen_set_syntax_error_metadata(Parser *p) {
896
92.4k
    PyObject *exc = PyErr_GetRaisedException();
897
92.4k
    if (!exc || !PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_SyntaxError)) {
898
0
        PyErr_SetRaisedException(exc);
899
0
        return;
900
0
    }
901
92.4k
    const char *source = NULL;
902
92.4k
    if (p->tok->str != NULL) {
903
92.4k
        source = p->tok->str;
904
92.4k
    }
905
92.4k
    if (!source && p->tok->fp_interactive && p->tok->interactive_src_start) {
906
0
        source = p->tok->interactive_src_start;
907
0
    }
908
92.4k
    PyObject* the_source = NULL;
909
92.4k
    if (source) {
910
92.4k
        if (p->tok->encoding == NULL) {
911
10.8k
            the_source = PyUnicode_FromString(source);
912
81.6k
        } else {
913
81.6k
            the_source = PyUnicode_Decode(source, strlen(source), p->tok->encoding, NULL);
914
81.6k
        }
915
92.4k
    }
916
92.4k
    if (!the_source) {
917
553
        PyErr_Clear();
918
553
        the_source = Py_None;
919
553
        Py_INCREF(the_source);
920
553
    }
921
92.4k
    PyObject* metadata = Py_BuildValue(
922
92.4k
        "(iiN)",
923
92.4k
        p->last_stmt_location.lineno,
924
92.4k
        p->last_stmt_location.col_offset,
925
92.4k
        the_source // N gives ownership to metadata
926
92.4k
    );
927
92.4k
    if (!metadata) {
928
0
        PyErr_Clear();
929
0
        return;
930
0
    }
931
92.4k
    PySyntaxErrorObject *syntax_error = (PySyntaxErrorObject *)exc;
932
933
92.4k
    Py_XDECREF(syntax_error->metadata);
934
92.4k
    syntax_error->metadata = metadata;
935
92.4k
    PyErr_SetRaisedException(exc);
936
92.4k
}
937
938
void *
939
_PyPegen_run_parser(Parser *p)
940
100k
{
941
100k
    void *res = _PyPegen_parse(p);
942
100k
    assert(p->level == 0);
943
100k
    if (res != NULL && PyErr_Occurred()) {
944
        // Discard a result returned with an exception still pending
945
        // (e.g. a MemoryError from a recovered-from allocation failure).
946
0
        return NULL;
947
0
    }
948
100k
    if (res == NULL) {
949
92.5k
        if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) &&  _is_end_of_source(p)) {
950
0
            PyErr_Clear();
951
0
            return _PyPegen_raise_error(p, PyExc_IncompleteInputError, 0, "incomplete input");
952
0
        }
953
92.5k
        if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
954
16
            return NULL;
955
16
        }
956
       // Make a second parser pass. In this pass we activate heavier and slower checks
957
        // to produce better error messages and more complete diagnostics. Extra "invalid_*"
958
        // rules will be active during parsing.
959
92.5k
        Token *last_token = p->tokens[p->fill - 1];
960
92.5k
        reset_parser_state_for_error_pass(p);
961
92.5k
        _PyPegen_parse(p);
962
963
        // Set SyntaxErrors accordingly depending on the parser/tokenizer status at the failure
964
        // point.
965
92.5k
        _Pypegen_set_syntax_error(p, last_token);
966
967
        // Set the metadata in the exception from p->last_stmt_location
968
92.5k
        if (PyErr_ExceptionMatches(PyExc_SyntaxError)) {
969
92.4k
            _PyPegen_set_syntax_error_metadata(p);
970
92.4k
        }
971
92.5k
       return NULL;
972
92.5k
    }
973
974
7.78k
    if (p->start_rule == Py_single_input && bad_single_statement(p)) {
975
0
        p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
976
0
        return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
977
0
    }
978
979
    // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
980
#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
981
    if (p->start_rule == Py_single_input ||
982
        p->start_rule == Py_file_input ||
983
        p->start_rule == Py_eval_input)
984
    {
985
        if (!_PyAST_Validate(res)) {
986
            return NULL;
987
        }
988
    }
989
#endif
990
7.78k
    return res;
991
7.78k
}
992
993
mod_ty
994
_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
995
                             const char *enc, const char *ps1, const char *ps2,
996
                             PyCompilerFlags *flags, int *errcode,
997
                             PyObject **interactive_src, PyArena *arena)
998
0
{
999
0
    struct tok_state *tok = _PyTokenizer_FromFile(fp, enc, ps1, ps2);
1000
0
    if (tok == NULL) {
1001
0
        if (PyErr_Occurred()) {
1002
0
            _PyTokenizer_raise_init_error(filename_ob);
1003
0
        }
1004
0
        else {
1005
            // The only silent tokenizer init failure is a failed allocation.
1006
0
            PyErr_NoMemory();
1007
0
        }
1008
0
        return NULL;
1009
0
    }
1010
0
    if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1011
0
        PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1012
0
        tok->fp_interactive = 1;
1013
0
    }
1014
    // This transfers the ownership to the tokenizer
1015
0
    tok->filename = Py_NewRef(filename_ob);
1016
1017
    // From here on we need to clean up even if there's an error
1018
0
    mod_ty result = NULL;
1019
1020
0
    tok->module = PyUnicode_FromString("__main__");
1021
0
    if (tok->module == NULL) {
1022
0
        goto error;
1023
0
    }
1024
1025
0
    int parser_flags = compute_parser_flags(flags);
1026
0
    Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1027
0
                                    errcode, NULL, arena);
1028
0
    if (p == NULL) {
1029
0
        goto error;
1030
0
    }
1031
1032
0
    result = _PyPegen_run_parser(p);
1033
0
    _PyPegen_Parser_Free(p);
1034
1035
0
    if (tok->fp_interactive && tok->interactive_src_start && result && interactive_src != NULL) {
1036
0
        *interactive_src = PyUnicode_FromString(tok->interactive_src_start);
1037
0
        if (!*interactive_src || _PyArena_AddPyObject(arena, *interactive_src) < 0) {
1038
0
            Py_XDECREF(*interactive_src);
1039
0
            result = NULL;
1040
0
            goto error;
1041
0
        }
1042
0
    }
1043
1044
0
error:
1045
0
    _PyTokenizer_Free(tok);
1046
0
    return result;
1047
0
}
1048
1049
mod_ty
1050
_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
1051
                       PyCompilerFlags *flags, PyArena *arena, PyObject *module)
1052
103k
{
1053
103k
    int exec_input = start_rule == Py_file_input;
1054
1055
103k
    struct tok_state *tok;
1056
103k
    if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
1057
81.0k
        tok = _PyTokenizer_FromUTF8(str, exec_input, 0);
1058
81.0k
    } else {
1059
21.9k
        tok = _PyTokenizer_FromString(str, exec_input, 0);
1060
21.9k
    }
1061
103k
    if (tok == NULL) {
1062
2.70k
        if (PyErr_Occurred()) {
1063
2.70k
            _PyTokenizer_raise_init_error(filename_ob);
1064
2.70k
        }
1065
0
        else {
1066
            // The only silent tokenizer init failure is a failed allocation.
1067
0
            PyErr_NoMemory();
1068
0
        }
1069
2.70k
        return NULL;
1070
2.70k
    }
1071
    // This transfers the ownership to the tokenizer
1072
100k
    tok->filename = Py_NewRef(filename_ob);
1073
100k
    tok->module = Py_XNewRef(module);
1074
1075
    // We need to clear up from here on
1076
100k
    mod_ty result = NULL;
1077
1078
100k
    int parser_flags = compute_parser_flags(flags);
1079
100k
    int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1080
99.5k
        flags->cf_feature_version : PY_MINOR_VERSION;
1081
100k
    Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1082
100k
                                    NULL, str, arena);
1083
100k
    if (p == NULL) {
1084
0
        goto error;
1085
0
    }
1086
1087
100k
    result = _PyPegen_run_parser(p);
1088
100k
    _PyPegen_Parser_Free(p);
1089
1090
100k
error:
1091
100k
    _PyTokenizer_Free(tok);
1092
100k
    return result;
1093
100k
}