Coverage Report

Created: 2026-02-26 06:53

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