Coverage Report

Created: 2026-10-31 06:21

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/state.h"
11
#include "tokenizer/tokenizer.h"
12
#include "pegen.h"
13
14
1.22M
#define IDENTIFIER_CACHE_SIZE 2048  // Must be a power of two.
15
582k
#define IDENTIFIER_CACHE_MAX_PROBES 8
16
4.71M
#define PEGEN_ARRAY_GROWTH_FACTOR 2
17
0
#define TYPE_IGNORE_INITIAL_CAPACITY 10
18
19
struct _identifier_cache_entry {
20
    const char *key;   // Borrowed from arena-owned token bytes.
21
    Py_ssize_t len;
22
    Py_hash_t hash;
23
    PyObject *value;   // Borrowed from an arena-owned identifier.
24
};
25
26
// Internal parser functions
27
28
asdl_stmt_seq*
29
_PyPegen_interactive_exit(Parser *p)
30
0
{
31
0
    if (p->errcode) {
32
0
        *(p->errcode) = E_EOF;
33
0
    }
34
0
    return NULL;
35
0
}
36
37
Py_ssize_t
38
_PyPegen_byte_offset_to_character_offset_line(PyObject *line, Py_ssize_t col_offset, Py_ssize_t end_col_offset)
39
2.33k
{
40
2.33k
    const unsigned char *data = (const unsigned char*)PyUnicode_AsUTF8(line);
41
2.33k
    if (data == NULL) {
42
0
        return -1;
43
0
    }
44
45
2.33k
    Py_ssize_t len = 0;
46
12.2k
    while (col_offset < end_col_offset) {
47
9.90k
        Py_UCS4 ch = data[col_offset];
48
9.90k
        if (ch < 0x80) {
49
9.90k
            col_offset += 1;
50
9.90k
        } else if ((ch & 0xe0) == 0xc0) {
51
0
            col_offset += 2;
52
0
        } else if ((ch & 0xf0) == 0xe0) {
53
0
            col_offset += 3;
54
0
        } else if ((ch & 0xf8) == 0xf0) {
55
0
            col_offset += 4;
56
0
        } else {
57
0
            PyErr_SetString(PyExc_ValueError, "Invalid UTF-8 sequence");
58
0
            return -1;
59
0
        }
60
9.90k
        len++;
61
9.90k
    }
62
2.33k
    return len;
63
2.33k
}
64
65
Py_ssize_t
66
_PyPegen_byte_offset_to_character_offset_raw(const char* str, Py_ssize_t col_offset)
67
124k
{
68
124k
    Py_ssize_t len = (Py_ssize_t)strlen(str);
69
124k
    if (col_offset > len + 1) {
70
1
        col_offset = len + 1;
71
1
    }
72
124k
    assert(col_offset >= 0);
73
124k
    PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
74
124k
    if (!text) {
75
0
        return -1;
76
0
    }
77
124k
    Py_ssize_t size = PyUnicode_GET_LENGTH(text);
78
124k
    Py_DECREF(text);
79
124k
    return size;
80
124k
}
81
82
Py_ssize_t
83
_PyPegen_byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
84
124k
{
85
124k
    const char *str = PyUnicode_AsUTF8(line);
86
124k
    if (!str) {
87
0
        return -1;
88
0
    }
89
124k
    return _PyPegen_byte_offset_to_character_offset_raw(str, col_offset);
90
124k
}
91
92
// Here, mark is the start of the node, while p->mark is the end.
93
// If node==NULL, they should be the same.
94
int
95
_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
96
12.1M
{
97
    // Insert in front
98
12.1M
    Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
99
12.1M
    if (m == NULL) {
100
0
        return -1;
101
0
    }
102
12.1M
    m->type = type;
103
12.1M
    m->node = node;
104
12.1M
    m->mark = p->mark;
105
12.1M
    m->next = p->tokens[mark]->memo;
106
12.1M
    p->tokens[mark]->memo = m;
107
12.1M
    p->tokens[mark]->memo_mask |= 1ULL << (type & 63);
108
12.1M
    return 0;
109
12.1M
}
110
111
// Like _PyPegen_insert_memo(), but returns the inserted Memo so callers
112
// can update it in place without re-walking the token's memo list.
113
Memo *
114
_PyPegen_insert_memo_direct(Parser *p, int mark, int type)
115
5.35M
{
116
5.35M
    if (_PyPegen_insert_memo(p, mark, type, NULL) < 0) {
117
0
        return NULL;
118
0
    }
119
5.35M
    return p->tokens[mark]->memo;
120
5.35M
}
121
122
// Like _PyPegen_insert_memo(), but updates an existing node if found.
123
int
124
_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
125
0
{
126
0
    for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
127
0
        if (m->type == type) {
128
            // Update existing node.
129
0
            m->node = node;
130
0
            m->mark = p->mark;
131
0
            return 0;
132
0
        }
133
0
    }
134
    // Insert new node.
135
0
    return _PyPegen_insert_memo(p, mark, type, node);
136
0
}
137
138
static int
139
init_normalization(Parser *p)
140
3.65k
{
141
3.65k
    if (p->normalize) {
142
2.11k
        return 1;
143
2.11k
    }
144
1.53k
    p->normalize = PyImport_ImportModuleAttrString("unicodedata", "normalize");
145
1.53k
    if (!p->normalize)
146
0
    {
147
0
        return 0;
148
0
    }
149
1.53k
    return 1;
150
1.53k
}
151
152
int
153
_PyPegen_grow_loop_buffer(void ***buffer, Py_ssize_t *capacity)
154
3.65M
{
155
3.65M
    if ((size_t)*capacity > (size_t)PY_SSIZE_T_MAX /
156
3.65M
            (PEGEN_ARRAY_GROWTH_FACTOR * sizeof(**buffer))) {
157
0
        return -1;
158
0
    }
159
3.65M
    Py_ssize_t new_capacity = *capacity == 0
160
3.65M
        ? 1 : *capacity * PEGEN_ARRAY_GROWTH_FACTOR;
161
3.65M
    void **new_buffer = PyMem_Realloc(*buffer, new_capacity * sizeof(**buffer));
162
3.65M
    if (new_buffer == NULL) {
163
0
        return -1;
164
0
    }
165
3.65M
    *buffer = new_buffer;
166
3.65M
    *capacity = new_capacity;
167
3.65M
    return 0;
168
3.65M
}
169
170
static int
171
growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment)
172
0
{
173
0
    if (arr->num_items >= arr->size) {
174
0
        if (arr->size > (size_t)PY_SSIZE_T_MAX /
175
0
                (PEGEN_ARRAY_GROWTH_FACTOR * sizeof(*arr->items))) {
176
0
            return 0;
177
0
        }
178
0
        size_t new_size = arr->size == 0
179
0
            ? TYPE_IGNORE_INITIAL_CAPACITY
180
0
            : arr->size * PEGEN_ARRAY_GROWTH_FACTOR;
181
0
        void *new_items_array = PyMem_Realloc(
182
0
            arr->items, new_size * sizeof(*arr->items));
183
0
        if (!new_items_array) {
184
0
            return 0;
185
0
        }
186
0
        arr->items = new_items_array;
187
0
        arr->size = new_size;
188
0
    }
189
190
0
    arr->items[arr->num_items].lineno = lineno;
191
0
    arr->items[arr->num_items].comment = comment;  // Take ownership
192
0
    arr->num_items++;
193
0
    return 1;
194
0
}
195
196
static void
197
growable_comment_array_deallocate(growable_comment_array *arr)
198
73.3k
{
199
73.3k
    for (size_t i = 0; i < arr->num_items; i++) {
200
0
        PyMem_Free(arr->items[i].comment);
201
0
    }
202
73.3k
    PyMem_Free(arr->items);
203
73.3k
}
204
205
static int
206
_get_keyword_or_name_type(Parser *p, const char *text, Py_ssize_t length)
207
561k
{
208
561k
    assert(length > 0);
209
210
561k
    if (length >= p->n_keyword_lists ||
211
538k
        p->keywords[length] == NULL ||
212
538k
        p->keywords[length]->type == -1) {
213
304k
        return NAME;
214
304k
    }
215
1.33M
    for (KeywordToken *k = p->keywords[length]; k != NULL && k->type != -1; k++) {
216
1.23M
        if (memcmp(k->str, text, (size_t)length) == 0) {
217
149k
            return k->type;
218
149k
        }
219
1.23M
    }
220
107k
    return NAME;
221
256k
}
222
223
// Keep text only where grammar actions or helpers read it. Keyword error
224
// actions use fixed spellings, so keywords do not need their text.
225
static inline int
226
token_needs_text(int type)
227
1.74M
{
228
1.74M
    switch (type) {
229
561k
        case NAME:
230
664k
        case NUMBER:
231
703k
        case STRING:
232
718k
        case FSTRING_START:
233
737k
        case FSTRING_MIDDLE:
234
748k
        case FSTRING_END:
235
753k
        case TSTRING_START:
236
761k
        case TSTRING_MIDDLE:
237
764k
        case TSTRING_END:
238
764k
        case TYPE_COMMENT:
239
765k
        case NOTEQUAL:  // _PyPegen_check_barry_as_flufl() distinguishes != and <>.
240
765k
            return 1;
241
978k
        default:
242
978k
            return 0;
243
1.74M
    }
244
1.74M
}
245
246
static int
247
1.74M
initialize_token(Parser *p, Token *parser_token, struct token *new_token, int token_type) {
248
1.74M
    assert(parser_token != NULL);
249
250
1.74M
    parser_token->type = token_type;
251
1.74M
    parser_token->bytes = NULL;
252
1.74M
    if (token_needs_text(token_type) && new_token->span.start >= 0) {
253
765k
        Py_ssize_t length;
254
765k
        const char *text = _PyToken_TextView(p->tok, new_token, &length);
255
765k
        if (token_type == NAME) {
256
561k
            parser_token->type = _get_keyword_or_name_type(p, text, length);
257
561k
        }
258
        // A name reclassified as a keyword does not need its text.
259
765k
        if (parser_token->type == token_type) {
260
615k
            parser_token->bytes = PyBytes_FromStringAndSize(text, length);
261
615k
            if (parser_token->bytes == NULL) {
262
0
                return -1;
263
0
            }
264
615k
            if (_PyArena_AddPyObject(p->arena, parser_token->bytes) < 0) {
265
0
                Py_DECREF(parser_token->bytes);
266
0
                return -1;
267
0
            }
268
615k
        }
269
765k
    }
270
271
1.74M
    parser_token->metadata = NULL;
272
1.74M
    if (new_token->metadata != NULL) {
273
12.3k
        if (_PyArena_AddPyObject(p->arena, new_token->metadata) < 0) {
274
0
            return -1;
275
0
        }
276
12.3k
        parser_token->metadata = new_token->metadata;
277
12.3k
        new_token->metadata = NULL;
278
12.3k
    }
279
280
1.74M
    parser_token->level = new_token->level;
281
1.74M
    parser_token->is_raw = new_token->is_raw;
282
1.74M
    parser_token->is_incomplete = new_token->is_incomplete;
283
1.74M
    parser_token->lineno = new_token->start_loc.lineno;
284
1.74M
    parser_token->col_offset = new_token->end_loc.lineno == p->starting_lineno
285
1.74M
        ? p->starting_col_offset + new_token->start_loc.byte_col
286
1.74M
        : new_token->start_loc.byte_col;
287
1.74M
    parser_token->end_lineno = new_token->end_loc.lineno;
288
1.74M
    parser_token->end_col_offset = new_token->end_loc.lineno == p->starting_lineno
289
1.74M
        ? p->starting_col_offset + new_token->end_loc.byte_col
290
1.74M
        : new_token->end_loc.byte_col;
291
292
1.74M
    p->fill += 1;
293
294
1.74M
    if (token_type == ERRORTOKEN && _PyTokenizer_GetStatus(p->tok) == E_DECODE) {
295
0
        return _Pypegen_raise_decode_error(p);
296
0
    }
297
298
1.74M
    return (token_type == ERRORTOKEN ? _Pypegen_tokenizer_error(p) : 0);
299
1.74M
}
300
301
static int
302
187k
_resize_tokens_array(Parser *p) {
303
187k
    if (p->size > INT_MAX / PEGEN_ARRAY_GROWTH_FACTOR ||
304
187k
            (size_t)p->size > PY_SSIZE_T_MAX /
305
187k
                (PEGEN_ARRAY_GROWTH_FACTOR * sizeof(*p->tokens))) {
306
0
        PyErr_NoMemory();
307
0
        return -1;
308
0
    }
309
187k
    int newsize = p->size * PEGEN_ARRAY_GROWTH_FACTOR;
310
187k
    Token **new_tokens = PyMem_Realloc(p->tokens, (size_t)newsize * sizeof(Token *));
311
187k
    if (new_tokens == NULL) {
312
0
        PyErr_NoMemory();
313
0
        return -1;
314
0
    }
315
187k
    p->tokens = new_tokens;
316
317
    // Allocate new tokens together without moving existing ones: parser rules
318
    // may still hold pointers into earlier blocks. Parser_Free frees each block.
319
187k
    Token *chunk = PyMem_Calloc((size_t)(newsize - p->size), sizeof(Token));
320
187k
    if (chunk == NULL) {
321
0
        PyErr_NoMemory();
322
0
        return -1;
323
0
    }
324
2.59M
    for (int i = p->size; i < newsize; i++) {
325
2.41M
        p->tokens[i] = &chunk[i - p->size];
326
2.41M
    }
327
187k
    p->size = newsize;
328
187k
    return 0;
329
187k
}
330
331
// Fast path attached to the expression precedence chain's entry rules.
332
// A bare NAME/NUMBER atom followed by a token that cannot start or
333
// continue a binary/postfix expression is a complete expression, so it is
334
// built directly instead of descending the whole chain.
335
//
336
// Returns 1 if it produced a result (stored in *result), 0 to fall through to
337
// the rule's alternatives.
338
int
339
_PyPegen_atom_fast_path(Parser *p, void *result)
340
4.28M
{
341
4.28M
    if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) {
342
30
        p->error_indicator = 1;
343
30
        *(void **)result = NULL;
344
30
        return 1;
345
30
    }
346
4.28M
    Token *t = p->tokens[p->mark];
347
4.28M
    if (t->type != NAME && t->type != NUMBER) {
348
3.03M
        return 0;
349
3.03M
    }
350
1.25M
    if (p->mark + 1 == p->fill && _PyPegen_fill_token(p) < 0) {
351
321
        p->error_indicator = 1;
352
321
        *(void **)result = NULL;
353
321
        return 1;
354
321
    }
355
1.25M
    switch (p->tokens[p->mark + 1]->type) {
356
282k
        case COMMA:
357
309k
        case RPAR:
358
321k
        case RSQB:
359
352k
        case RBRACE:
360
473k
        case COLON:
361
686k
        case NEWLINE:
362
774k
        case SEMI:
363
813k
        case EQUAL:
364
813k
        case ENDMARKER:
365
813k
            break;
366
437k
        default:
367
437k
            return 0;
368
1.25M
    }
369
813k
    expr_ty res = (t->type == NAME)
370
813k
        ? _PyPegen_name_token(p) : _PyPegen_number_token(p);
371
813k
    *(void **)result = res;
372
813k
    return 1;
373
1.25M
}
374
375
int
376
_PyPegen_fill_token(Parser *p)
377
1.74M
{
378
1.74M
    struct token new_token;
379
1.74M
    _PyToken_Init(&new_token);
380
1.74M
    _PyTokenizer_Get(p->tok, &new_token);
381
382
    // Record and skip '# type: ignore' comments
383
1.74M
    while (new_token.type == TYPE_IGNORE) {
384
0
        Py_ssize_t len;
385
0
        const char *text = _PyToken_TextView(p->tok, &new_token, &len);
386
0
        char *tag = PyMem_Malloc((size_t)len + 1);
387
0
        if (tag == NULL) {
388
0
            PyErr_NoMemory();
389
0
            goto error;
390
0
        }
391
0
        memcpy(tag, text, (size_t)len);
392
0
        tag[len] = '\0';
393
        // Ownership of tag passes to the growable array
394
0
        if (!growable_comment_array_add(&p->type_ignore_comments, new_token.end_loc.lineno, tag)) {
395
0
            PyMem_Free(tag);
396
0
            PyErr_NoMemory();
397
0
            goto error;
398
0
        }
399
0
        _PyTokenizer_Get(p->tok, &new_token);
400
0
    }
401
402
1.74M
    int type = new_token.type;
403
    // EOF can finish an ordinary token. Only a boundary token means that
404
    // the grammar requested input beyond the last physical line.
405
1.74M
    if (type == ENDMARKER ||
406
1.73M
        (type == DEDENT && (p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) &&
407
8.43k
         _PyTokenizer_GetStatus(p->tok) == E_EOF)) {
408
8.43k
        p->input_exhausted = 1;
409
8.43k
    }
410
411
    // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
412
1.74M
    if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
413
0
        type = NEWLINE; /* Add an extra newline */
414
0
        p->parsing_started = 0;
415
416
0
        if (!(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
417
0
            _PyTokenizer_ImplyDedents(p->tok);
418
0
        }
419
0
    }
420
1.74M
    else {
421
1.74M
        p->parsing_started = 1;
422
1.74M
    }
423
424
    // Check if we are at the limit of the token array capacity and resize if needed
425
1.74M
    if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
426
0
        goto error;
427
0
    }
428
429
1.74M
    Token *t = p->tokens[p->fill];
430
1.74M
    int result = initialize_token(p, t, &new_token, type);
431
1.74M
    _PyToken_Free(&new_token);
432
1.74M
    return result;
433
0
error:
434
0
    _PyToken_Free(&new_token);
435
0
    return -1;
436
1.74M
}
437
438
#if defined(Py_DEBUG)
439
// Instrumentation to count the effectiveness of memoization.
440
// The array counts the number of tokens skipped by memoization,
441
// indexed by type.
442
443
#define NSTATISTICS _PYPEGEN_NSTATISTICS
444
#define memo_statistics _PyRuntime.parser.memo_statistics
445
446
void
447
_PyPegen_clear_memo_statistics(void)
448
{
449
    PyMutex_Lock(&_PyRuntime.parser.mutex);
450
    for (int i = 0; i < NSTATISTICS; i++) {
451
        memo_statistics[i] = 0;
452
    }
453
    PyMutex_Unlock(&_PyRuntime.parser.mutex);
454
}
455
456
PyObject *
457
_PyPegen_get_memo_statistics(void)
458
{
459
    PyObject *ret = PyList_New(NSTATISTICS);
460
    if (ret == NULL) {
461
        return NULL;
462
    }
463
464
    PyMutex_Lock(&_PyRuntime.parser.mutex);
465
    for (int i = 0; i < NSTATISTICS; i++) {
466
        PyObject *value = PyLong_FromLong(memo_statistics[i]);
467
        if (value == NULL) {
468
            PyMutex_Unlock(&_PyRuntime.parser.mutex);
469
            Py_DECREF(ret);
470
            return NULL;
471
        }
472
        // PyList_SetItem borrows a reference to value.
473
        if (PyList_SetItem(ret, i, value) < 0) {
474
            PyMutex_Unlock(&_PyRuntime.parser.mutex);
475
            Py_DECREF(ret);
476
            return NULL;
477
        }
478
    }
479
    PyMutex_Unlock(&_PyRuntime.parser.mutex);
480
    return ret;
481
}
482
#endif
483
484
int  // bool
485
_PyPegen_is_memoized(Parser *p, int type, void *pres)
486
41.5M
{
487
41.5M
    if (p->mark == p->fill) {
488
448k
        if (_PyPegen_fill_token(p) < 0) {
489
767
            p->error_indicator = 1;
490
767
            return -1;
491
767
        }
492
448k
    }
493
494
41.5M
    Token *t = p->tokens[p->mark];
495
496
41.5M
    if (!(t->memo_mask & (1ULL << (type & 63)))) {
497
12.1M
        return 0;
498
12.1M
    }
499
500
62.9M
    for (Memo *m = t->memo; m != NULL; m = m->next) {
501
62.7M
        if (m->type == type) {
502
#if defined(Py_DEBUG)
503
            if (0 <= type && type < NSTATISTICS) {
504
                long count = m->mark - p->mark;
505
                // A memoized negative result counts for one.
506
                if (count <= 0) {
507
                    count = 1;
508
                }
509
                PyMutex_Lock(&_PyRuntime.parser.mutex);
510
                memo_statistics[type] += count;
511
                PyMutex_Unlock(&_PyRuntime.parser.mutex);
512
            }
513
#endif
514
29.2M
            p->mark = m->mark;
515
29.2M
            *(void **)(pres) = m->node;
516
29.2M
            return 1;
517
29.2M
        }
518
62.7M
    }
519
189k
    return 0;
520
29.4M
}
521
522
#define LOOKAHEAD1(NAME, RES_TYPE)                                  \
523
    int                                                             \
524
    NAME (int positive, RES_TYPE (func)(Parser *), Parser *p)       \
525
3.01M
    {                                                               \
526
3.01M
        int mark = p->mark;                                         \
527
3.01M
        void *res = func(p);                                        \
528
3.01M
        p->mark = mark;                                             \
529
3.01M
        return (res != NULL) == positive;                           \
530
3.01M
    }
531
532
3.01M
LOOKAHEAD1(_PyPegen_lookahead, void *)
533
983
LOOKAHEAD1(_PyPegen_lookahead_for_expr, expr_ty)
534
0
LOOKAHEAD1(_PyPegen_lookahead_for_stmt, stmt_ty)
535
#undef LOOKAHEAD1
536
537
#define LOOKAHEAD2(NAME, RES_TYPE, T)                                   \
538
    int                                                                 \
539
    NAME (int positive, RES_TYPE (func)(Parser *, T), Parser *p, T arg) \
540
8.21M
    {                                                                   \
541
8.21M
        int mark = p->mark;                                             \
542
8.21M
        void *res = func(p, arg);                                       \
543
8.21M
        p->mark = mark;                                                 \
544
8.21M
        return (res != NULL) == positive;                               \
545
8.21M
    }
546
547
7.89M
LOOKAHEAD2(_PyPegen_lookahead_with_int, Token *, int)
548
317k
LOOKAHEAD2(_PyPegen_lookahead_with_string, expr_ty, const char *)
549
#undef LOOKAHEAD2
550
551
Token *
552
_PyPegen_expect_token(Parser *p, int type)
553
79.8M
{
554
79.8M
    if (p->mark == p->fill) {
555
774k
        if (_PyPegen_fill_token(p) < 0) {
556
1.72k
            p->error_indicator = 1;
557
1.72k
            return NULL;
558
1.72k
        }
559
774k
    }
560
79.8M
    Token *t = p->tokens[p->mark];
561
79.8M
    if (t->type != type) {
562
63.6M
       return NULL;
563
63.6M
    }
564
16.2M
    p->mark += 1;
565
16.2M
    return t;
566
79.8M
}
567
568
void*
569
0
_PyPegen_expect_forced_result(Parser *p, void* result, const char* expected) {
570
571
0
    if (p->error_indicator == 1) {
572
0
        return NULL;
573
0
    }
574
0
    if (result == NULL) {
575
0
        RAISE_SYNTAX_ERROR("expected (%s)", expected);
576
0
        return NULL;
577
0
    }
578
0
    return result;
579
0
}
580
581
Token *
582
16.8k
_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
583
584
16.8k
    if (p->error_indicator == 1) {
585
0
        return NULL;
586
0
    }
587
588
16.8k
    if (p->mark == p->fill) {
589
4.27k
        if (_PyPegen_fill_token(p) < 0) {
590
2
            p->error_indicator = 1;
591
2
            return NULL;
592
2
        }
593
4.27k
    }
594
16.8k
    Token *t = p->tokens[p->mark];
595
16.8k
    if (t->type != type) {
596
145
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
597
145
        return NULL;
598
145
    }
599
16.7k
    p->mark += 1;
600
16.7k
    return t;
601
16.8k
}
602
603
expr_ty
604
_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
605
1.09M
{
606
1.09M
    if (p->mark == p->fill) {
607
5.20k
        if (_PyPegen_fill_token(p) < 0) {
608
8
            p->error_indicator = 1;
609
8
            return NULL;
610
8
        }
611
5.20k
    }
612
1.09M
    Token *t = p->tokens[p->mark];
613
1.09M
    if (t->type != NAME) {
614
804k
        return NULL;
615
804k
    }
616
286k
    const char *s = PyBytes_AsString(t->bytes);
617
286k
    if (!s) {
618
0
        p->error_indicator = 1;
619
0
        return NULL;
620
0
    }
621
286k
    if (strcmp(s, keyword) != 0) {
622
252k
        return NULL;
623
252k
    }
624
33.9k
    return _PyPegen_name_token(p);
625
286k
}
626
627
Token *
628
_PyPegen_get_last_nonnwhitespace_token(Parser *p)
629
7.94M
{
630
7.94M
    assert(p->mark >= 0);
631
7.94M
    Token *token = NULL;
632
7.99M
    for (int m = p->mark - 1; m >= 0; m--) {
633
7.99M
        token = p->tokens[m];
634
7.99M
        if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
635
7.94M
            break;
636
7.94M
        }
637
7.99M
    }
638
7.94M
    return token;
639
7.94M
}
640
641
PyObject *
642
_PyPegen_new_identifier(Parser *p, const char *n)
643
116k
{
644
116k
    PyObject *id = PyUnicode_DecodeUTF8(n, (Py_ssize_t)strlen(n), NULL);
645
116k
    if (!id) {
646
0
        goto error;
647
0
    }
648
    /* Check whether there are non-ASCII characters in the
649
       identifier; if so, normalize to NFKC. */
650
116k
    if (!PyUnicode_IS_ASCII(id))
651
3.65k
    {
652
3.65k
        if (!init_normalization(p))
653
0
        {
654
0
            Py_DECREF(id);
655
0
            goto error;
656
0
        }
657
3.65k
        PyObject *form = PyUnicode_InternFromString("NFKC");
658
3.65k
        if (form == NULL)
659
0
        {
660
0
            Py_DECREF(id);
661
0
            goto error;
662
0
        }
663
3.65k
        PyObject *args[2] = {form, id};
664
3.65k
        PyObject *id2 = PyObject_Vectorcall(p->normalize, args, 2, NULL);
665
3.65k
        Py_DECREF(id);
666
3.65k
        Py_DECREF(form);
667
3.65k
        if (!id2) {
668
0
            goto error;
669
0
        }
670
671
3.65k
        if (!PyUnicode_Check(id2))
672
0
        {
673
0
            PyErr_Format(PyExc_TypeError,
674
0
                         "unicodedata.normalize() must return a string, not "
675
0
                         "%.200s",
676
0
                         _PyType_Name(Py_TYPE(id2)));
677
0
            Py_DECREF(id2);
678
0
            goto error;
679
0
        }
680
3.65k
        id = id2;
681
3.65k
    }
682
116k
    static const char * const forbidden[] = {
683
116k
        "None",
684
116k
        "True",
685
116k
        "False",
686
116k
        NULL
687
116k
    };
688
465k
    for (int i = 0; forbidden[i] != NULL; i++) {
689
349k
        if (_PyUnicode_EqualToASCIIString(id, forbidden[i])) {
690
2
            PyErr_Format(PyExc_ValueError,
691
2
                         "identifier field can't represent '%s' constant",
692
2
                         forbidden[i]);
693
2
            Py_DECREF(id);
694
2
            goto error;
695
2
        }
696
349k
    }
697
116k
    PyInterpreterState *interp = _PyInterpreterState_GET();
698
116k
    _PyUnicode_InternImmortal(interp, &id);
699
116k
    if (_PyArena_AddPyObject(p->arena, id) < 0)
700
0
    {
701
0
        Py_DECREF(id);
702
0
        goto error;
703
0
    }
704
116k
    return id;
705
706
2
error:
707
2
    p->error_indicator = 1;
708
2
    return NULL;
709
116k
}
710
711
// Return an arena-owned identifier; callers borrow the reference.
712
static PyObject *
713
get_cached_identifier(Parser *p, PyObject *bytes)
714
580k
{
715
580k
    const char *s = PyBytes_AsString(bytes);
716
580k
    if (!s) {
717
0
        p->error_indicator = 1;
718
0
        return NULL;
719
0
    }
720
    // Identifiers repeat constantly; a small span-keyed cache skips the
721
    // UTF-8 decode + intern for repeated occurrences. Keys point into
722
    // arena-owned token bytes and values are arena-owned interned strings,
723
    // so borrowed references are valid for the lifetime of the parse
724
    // (including the second error pass, which reuses parser and arena).
725
580k
    Py_ssize_t len = PyBytes_GET_SIZE(bytes);
726
580k
    Py_hash_t hash = PyObject_Hash(bytes);
727
580k
    if (hash == -1) {
728
0
        p->error_indicator = 1;
729
0
        return NULL;
730
0
    }
731
    // Parses without identifiers do not need this cache.
732
580k
    if (p->identifier_cache == NULL) {
733
64.9k
        p->identifier_cache = PyMem_Calloc(
734
64.9k
            IDENTIFIER_CACHE_SIZE, sizeof(*p->identifier_cache));
735
64.9k
        if (p->identifier_cache == NULL) {
736
0
            p->error_indicator = 1;
737
0
            return PyErr_NoMemory();
738
0
        }
739
64.9k
    }
740
580k
    IdentifierCacheEntry *free_slot = NULL;
741
580k
    size_t idx = (size_t)hash & (IDENTIFIER_CACHE_SIZE - 1);
742
582k
    for (int probe = 0; probe < IDENTIFIER_CACHE_MAX_PROBES; probe++) {
743
582k
        IdentifierCacheEntry *entry = &p->identifier_cache[
744
582k
            (idx + probe) & (IDENTIFIER_CACHE_SIZE - 1)];
745
582k
        if (entry->key == NULL) {
746
112k
            free_slot = entry;
747
112k
            break;
748
112k
        }
749
469k
        if (entry->hash == hash && entry->len == len &&
750
467k
            memcmp(entry->key, s, len) == 0)
751
467k
        {
752
467k
            return entry->value;
753
467k
        }
754
469k
    }
755
112k
    PyObject *id = _PyPegen_new_identifier(p, s);
756
112k
    if (id == NULL) {
757
2
        p->error_indicator = 1;
758
2
        return NULL;
759
2
    }
760
112k
    if (free_slot != NULL) {
761
112k
        free_slot->key = s;
762
112k
        free_slot->len = len;
763
112k
        free_slot->hash = hash;
764
112k
        free_slot->value = id;
765
112k
    }
766
112k
    return id;
767
112k
}
768
769
static expr_ty
770
_PyPegen_name_from_token(Parser *p, Token* t)
771
22.7M
{
772
22.7M
    if (t == NULL) {
773
13.8M
        return NULL;
774
13.8M
    }
775
    // Reuse the AST node when backtracking revisits this token. Memo lookup
776
    // starts before the token and restores the position after it on a hit.
777
    // Token kinds can be memo keys: generated grammar rule IDs start at 1000.
778
8.91M
    int mark = p->mark - 1;
779
8.91M
    p->mark = mark;
780
8.91M
    expr_ty cached = NULL;
781
8.91M
    if (_PyPegen_is_memoized(p, NAME, &cached)) {
782
8.33M
        return cached;
783
8.33M
    }
784
580k
    p->mark = mark + 1;
785
580k
    PyObject *id = get_cached_identifier(p, t->bytes);
786
580k
    if (id == NULL) {
787
2
        return NULL;
788
2
    }
789
580k
    expr_ty result = _PyAST_Name(id, Load, t->lineno, t->col_offset,
790
580k
                                t->end_lineno, t->end_col_offset, p->arena);
791
580k
    if (result != NULL && _PyPegen_insert_memo(p, mark, NAME, result) < 0) {
792
0
        p->error_indicator = 1;
793
0
        return NULL;
794
0
    }
795
580k
    return result;
796
580k
}
797
798
expr_ty
799
_PyPegen_name_token(Parser *p)
800
22.7M
{
801
22.7M
    Token *t = _PyPegen_expect_token(p, NAME);
802
22.7M
    return _PyPegen_name_from_token(p, t);
803
22.7M
}
804
805
void *
806
_PyPegen_string_token(Parser *p)
807
1.42M
{
808
1.42M
    return _PyPegen_expect_token(p, STRING);
809
1.42M
}
810
811
342k
expr_ty _PyPegen_soft_keyword_token(Parser *p) {
812
342k
    Token *t = _PyPegen_expect_token(p, NAME);
813
342k
    if (t == NULL) {
814
264k
        return NULL;
815
264k
    }
816
78.4k
    char *the_token;
817
78.4k
    Py_ssize_t size;
818
78.4k
    PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
819
447k
    for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
820
374k
        if (strlen(*keyword) == (size_t)size &&
821
70.5k
            strncmp(*keyword, the_token, (size_t)size) == 0) {
822
6.17k
            return _PyPegen_name_from_token(p, t);
823
6.17k
        }
824
374k
    }
825
72.3k
    return NULL;
826
78.4k
}
827
828
static PyObject *
829
parsenumber_raw(const char *s)
830
133k
{
831
133k
    const char *end;
832
133k
    long x;
833
133k
    double dx;
834
133k
    Py_complex compl;
835
133k
    int imflag;
836
837
133k
    assert(s != NULL);
838
133k
    errno = 0;
839
133k
    end = s + strlen(s) - 1;
840
133k
    imflag = *end == 'j' || *end == 'J';
841
133k
    if (s[0] == '0') {
842
36.7k
        x = (long)PyOS_strtoul(s, (char **)&end, 0);
843
36.7k
        if (x < 0 && errno == 0) {
844
609
            return PyLong_FromString(s, (char **)0, 0);
845
609
        }
846
36.7k
    }
847
96.7k
    else {
848
96.7k
        x = PyOS_strtol(s, (char **)&end, 0);
849
96.7k
    }
850
132k
    if (*end == '\0') {
851
93.7k
        if (errno != 0) {
852
2.36k
            return PyLong_FromString(s, (char **)0, 0);
853
2.36k
        }
854
91.3k
        return PyLong_FromLong(x);
855
93.7k
    }
856
    /* XXX Huge floats may silently fail */
857
39.1k
    if (imflag) {
858
7.49k
        compl.real = 0.;
859
7.49k
        compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
860
7.49k
        if (compl.imag == -1.0 && PyErr_Occurred()) {
861
0
            return NULL;
862
0
        }
863
7.49k
        return PyComplex_FromCComplex(compl);
864
7.49k
    }
865
31.6k
    dx = PyOS_string_to_double(s, NULL, NULL);
866
31.6k
    if (dx == -1.0 && PyErr_Occurred()) {
867
0
        return NULL;
868
0
    }
869
31.6k
    return PyFloat_FromDouble(dx);
870
31.6k
}
871
872
static PyObject *
873
parsenumber(const char *s)
874
133k
{
875
133k
    char *dup;
876
133k
    char *end;
877
133k
    PyObject *res = NULL;
878
879
133k
    assert(s != NULL);
880
881
133k
    if (strchr(s, '_') == NULL) {
882
132k
        return parsenumber_raw(s);
883
132k
    }
884
    /* Create a duplicate without underscores. */
885
1.32k
    dup = PyMem_Malloc(strlen(s) + 1);
886
1.32k
    if (dup == NULL) {
887
0
        return PyErr_NoMemory();
888
0
    }
889
1.32k
    end = dup;
890
34.0k
    for (; *s; s++) {
891
32.7k
        if (*s != '_') {
892
28.1k
            *end++ = *s;
893
28.1k
        }
894
32.7k
    }
895
1.32k
    *end = '\0';
896
1.32k
    res = parsenumber_raw(dup);
897
1.32k
    PyMem_Free(dup);
898
1.32k
    return res;
899
1.32k
}
900
901
expr_ty
902
_PyPegen_number_token(Parser *p)
903
1.11M
{
904
1.11M
    int mark = p->mark;
905
1.11M
    Token *t = _PyPegen_expect_token(p, NUMBER);
906
1.11M
    if (t == NULL) {
907
742k
        return NULL;
908
742k
    }
909
910
    // Look up the node at the token's start, as for NAME tokens. A memo hit
911
    // advances the mark; on a miss, restore the position after the token.
912
376k
    p->mark = mark;
913
376k
    expr_ty cached = NULL;
914
376k
    if (_PyPegen_is_memoized(p, NUMBER, &cached)) {
915
242k
        return cached;
916
242k
    }
917
133k
    p->mark = mark + 1;
918
919
133k
    const char *num_raw = PyBytes_AsString(t->bytes);
920
133k
    if (num_raw == NULL) {
921
0
        p->error_indicator = 1;
922
0
        return NULL;
923
0
    }
924
925
133k
    if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
926
0
        p->error_indicator = 1;
927
0
        return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
928
0
                                  "in Python 3.6 and greater");
929
0
    }
930
931
133k
    PyObject *c = parsenumber(num_raw);
932
933
133k
    if (c == NULL) {
934
0
        p->error_indicator = 1;
935
0
        PyThreadState *tstate = _PyThreadState_GET();
936
        // The only way a ValueError should happen in _this_ code is via
937
        // PyLong_FromString hitting a length limit.
938
0
        if (tstate->current_exception != NULL &&
939
0
            Py_TYPE(tstate->current_exception) == (PyTypeObject *)PyExc_ValueError
940
0
        ) {
941
0
            PyObject *exc = PyErr_GetRaisedException();
942
            /* Intentionally omitting columns to avoid a wall of 1000s of '^'s
943
             * on the error message. Nobody is going to overlook their huge
944
             * numeric literal once given the line. */
945
0
            RAISE_ERROR_KNOWN_LOCATION(
946
0
                p, PyExc_SyntaxError,
947
0
                t->lineno, -1 /* col_offset */,
948
0
                t->end_lineno, -1 /* end_col_offset */,
949
0
                "%S - Consider hexadecimal for huge integer literals "
950
0
                "to avoid decimal conversion limits.",
951
0
                exc);
952
0
            Py_DECREF(exc);
953
0
        }
954
0
        return NULL;
955
0
    }
956
957
133k
    if (_PyArena_AddPyObject(p->arena, c) < 0) {
958
0
        Py_DECREF(c);
959
0
        p->error_indicator = 1;
960
0
        return NULL;
961
0
    }
962
963
133k
    expr_ty result = _PyAST_Constant(c, NULL, t->lineno, t->col_offset,
964
133k
                                    t->end_lineno, t->end_col_offset, p->arena);
965
133k
    if (result != NULL && _PyPegen_insert_memo(p, mark, NUMBER, result) < 0) {
966
0
        p->error_indicator = 1;
967
0
        return NULL;
968
0
    }
969
133k
    return result;
970
133k
}
971
972
973
974
static int
975
compute_parser_flags(PyCompilerFlags *flags)
976
76.0k
{
977
76.0k
    int parser_flags = 0;
978
76.0k
    if (!flags) {
979
111
        return 0;
980
111
    }
981
75.9k
    if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
982
0
        parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
983
0
    }
984
75.9k
    if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
985
53.0k
        parser_flags |= PyPARSE_IGNORE_COOKIE;
986
53.0k
    }
987
75.9k
    if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
988
0
        parser_flags |= PyPARSE_BARRY_AS_BDFL;
989
0
    }
990
75.9k
    if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
991
0
        parser_flags |= PyPARSE_TYPE_COMMENTS;
992
0
    }
993
75.9k
    if (flags->cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT) {
994
0
        parser_flags |= PyPARSE_ALLOW_INCOMPLETE_INPUT;
995
0
    }
996
75.9k
    return parser_flags;
997
76.0k
}
998
999
// Parser API
1000
1001
Parser *
1002
_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
1003
                    int feature_version, int *errcode, const char* source, PyArena *arena)
1004
73.3k
{
1005
73.3k
    Parser *p = PyMem_Malloc(sizeof(Parser));
1006
73.3k
    if (p == NULL) {
1007
0
        return (Parser *) PyErr_NoMemory();
1008
0
    }
1009
73.3k
    assert(tok != NULL);
1010
73.3k
    _PyTokenizer_SetOptions(tok, 0, (flags & PyPARSE_TYPE_COMMENTS) > 0);
1011
73.3k
    _PyTokenizer_AllowIncompleteInput(tok, flags & PyPARSE_ALLOW_INCOMPLETE_INPUT);
1012
73.3k
    p->tok = tok;
1013
73.3k
    p->keywords = NULL;
1014
73.3k
    p->n_keyword_lists = -1;
1015
73.3k
    p->soft_keywords = NULL;
1016
73.3k
    p->tokens = PyMem_Malloc(sizeof(Token *));
1017
73.3k
    if (!p->tokens) {
1018
0
        PyMem_Free(p);
1019
0
        return (Parser *) PyErr_NoMemory();
1020
0
    }
1021
73.3k
    p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
1022
73.3k
    if (!p->tokens[0]) {
1023
0
        PyMem_Free(p->tokens);
1024
0
        PyMem_Free(p);
1025
0
        return (Parser *) PyErr_NoMemory();
1026
0
    }
1027
73.3k
    p->type_ignore_comments = (growable_comment_array){0};
1028
1029
73.3k
    p->mark = 0;
1030
73.3k
    p->fill = 0;
1031
73.3k
    p->size = 1;
1032
1033
73.3k
    p->errcode = errcode;
1034
73.3k
    p->arena = arena;
1035
73.3k
    p->start_rule = start_rule;
1036
73.3k
    p->parsing_started = 0;
1037
73.3k
    p->normalize = NULL;
1038
73.3k
    p->error_indicator = 0;
1039
1040
73.3k
    p->starting_lineno = 0;
1041
73.3k
    p->starting_col_offset = 0;
1042
73.3k
    p->flags = flags;
1043
73.3k
    p->feature_version = feature_version;
1044
73.3k
    p->known_err_token = NULL;
1045
73.3k
    p->identifier_cache = NULL;
1046
73.3k
    p->tstate = PyThreadState_Get();
1047
    // Stack limits are initialized when the thread state is attached.
1048
73.3k
    assert(((_PyThreadStateImpl *)p->tstate)->c_stack_hard_limit != 0);
1049
73.3k
    p->stack_soft_limit = ((_PyThreadStateImpl *)p->tstate)->c_stack_soft_limit;
1050
73.3k
#if _Py_STACK_GROWS_DOWN
1051
73.3k
    p->stack_soft_limit += _PyOS_STACK_MARGIN_BYTES;
1052
#else
1053
    p->stack_soft_limit -= _PyOS_STACK_MARGIN_BYTES;
1054
#endif
1055
73.3k
    p->level = 0;
1056
73.3k
    p->call_invalid_rules = 0;
1057
73.3k
    p->input_exhausted = 0;
1058
73.3k
    p->last_stmt_location.lineno = 0;
1059
73.3k
    p->last_stmt_location.col_offset = 0;
1060
73.3k
    p->last_stmt_location.end_lineno = 0;
1061
73.3k
    p->last_stmt_location.end_col_offset = 0;
1062
#ifdef Py_DEBUG
1063
    p->debug = _Py_GetConfig()->parser_debug;
1064
#endif
1065
73.3k
    return p;
1066
73.3k
}
1067
1068
void
1069
_PyPegen_Parser_Free(Parser *p)
1070
73.3k
{
1071
73.3k
    PyMem_Free(p->identifier_cache);
1072
73.3k
    Py_XDECREF(p->normalize);
1073
    // Resizes allocate blocks starting at indices 1, 2, 4, and so on.
1074
73.3k
    PyMem_Free(p->tokens[0]);
1075
261k
    for (int i = 1; i < p->size; i *= PEGEN_ARRAY_GROWTH_FACTOR) {
1076
187k
        PyMem_Free(p->tokens[i]);
1077
187k
    }
1078
73.3k
    PyMem_Free(p->tokens);
1079
73.3k
    growable_comment_array_deallocate(&p->type_ignore_comments);
1080
73.3k
    PyMem_Free(p);
1081
73.3k
}
1082
1083
static void
1084
reset_parser_state_for_error_pass(Parser *p)
1085
65.0k
{
1086
65.0k
    p->last_stmt_location.lineno = 0;
1087
65.0k
    p->last_stmt_location.col_offset = 0;
1088
65.0k
    p->last_stmt_location.end_lineno = 0;
1089
65.0k
    p->last_stmt_location.end_col_offset = 0;
1090
816k
    for (int i = 0; i < p->fill; i++) {
1091
751k
        p->tokens[i]->memo = NULL;
1092
751k
        p->tokens[i]->memo_mask = 0;
1093
751k
    }
1094
65.0k
    p->mark = 0;
1095
65.0k
    p->flags &= ~PyPARSE_ALLOW_INCOMPLETE_INPUT;
1096
65.0k
    _PyTokenizer_AllowIncompleteInput(p->tok, 0);
1097
65.0k
    p->call_invalid_rules = 1;
1098
65.0k
    _PyTokenizer_StopInteractive(p->tok);
1099
65.0k
}
1100
1101
static void
1102
65.0k
_PyPegen_set_syntax_error_metadata(Parser *p) {
1103
65.0k
    PyObject *exc = PyErr_GetRaisedException();
1104
65.0k
    if (!exc || !PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_SyntaxError)) {
1105
0
        PyErr_SetRaisedException(exc);
1106
0
        return;
1107
0
    }
1108
65.0k
    const char *source = _PyTokenizer_RetainedSource(p->tok);
1109
65.0k
    const char *encoding = _PyTokenizer_GetInfo(p->tok).encoding;
1110
65.0k
    PyObject* the_source = NULL;
1111
65.0k
    if (source) {
1112
65.0k
        if (encoding == NULL) {
1113
11.0k
            the_source = PyUnicode_FromString(source);
1114
53.9k
        } else {
1115
53.9k
            the_source = PyUnicode_Decode(source, strlen(source), encoding, NULL);
1116
53.9k
        }
1117
65.0k
    }
1118
65.0k
    if (!the_source) {
1119
597
        PyErr_Clear();
1120
597
        the_source = Py_None;
1121
597
        Py_INCREF(the_source);
1122
597
    }
1123
65.0k
    PyObject* metadata = Py_BuildValue(
1124
65.0k
        "(iiN)",
1125
65.0k
        p->last_stmt_location.lineno,
1126
65.0k
        p->last_stmt_location.col_offset,
1127
65.0k
        the_source // N gives ownership to metadata
1128
65.0k
    );
1129
65.0k
    if (!metadata) {
1130
0
        PyErr_Clear();
1131
0
        PyErr_SetRaisedException(exc);
1132
0
        return;
1133
0
    }
1134
65.0k
    PySyntaxErrorObject *syntax_error = (PySyntaxErrorObject *)exc;
1135
1136
65.0k
    Py_XDECREF(syntax_error->metadata);
1137
65.0k
    syntax_error->metadata = metadata;
1138
65.0k
    PyErr_SetRaisedException(exc);
1139
65.0k
}
1140
1141
void *
1142
_PyPegen_run_parser(Parser *p)
1143
73.3k
{
1144
73.3k
    void *res = _PyPegen_parse(p);
1145
73.3k
    assert(p->level == 0);
1146
73.3k
    if (res != NULL && PyErr_Occurred()) {
1147
        // Discard a result returned with an exception still pending
1148
        // (e.g. a MemoryError from a recovered-from allocation failure).
1149
0
        return NULL;
1150
0
    }
1151
73.3k
    if (res == NULL) {
1152
65.1k
        if (PyErr_Occurred() &&
1153
2.58k
            (PyErr_ExceptionMatches(PyExc_IncompleteInputError) ||
1154
2.58k
             !PyErr_ExceptionMatches(PyExc_SyntaxError))) {
1155
5
            return NULL;
1156
5
        }
1157
65.0k
        if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) &&
1158
0
            p->input_exhausted && !PyErr_Occurred()) {
1159
0
            return _PyPegen_raise_incomplete_input(p);
1160
0
        }
1161
       // Make a second parser pass. In this pass we activate heavier and slower checks
1162
        // to produce better error messages and more complete diagnostics. Extra "invalid_*"
1163
        // rules will be active during parsing.
1164
65.0k
        Token *last_token = p->tokens[p->fill - 1];
1165
65.0k
        reset_parser_state_for_error_pass(p);
1166
65.0k
        _PyPegen_parse(p);
1167
1168
        // Set SyntaxErrors accordingly depending on the parser/tokenizer status at the failure
1169
        // point.
1170
65.0k
        _Pypegen_set_syntax_error(p, last_token);
1171
1172
        // Set the metadata in the exception from p->last_stmt_location
1173
65.0k
        if (PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1174
65.0k
            _PyPegen_set_syntax_error_metadata(p);
1175
65.0k
        }
1176
65.0k
       return NULL;
1177
65.0k
    }
1178
1179
8.29k
    if (p->start_rule == Py_single_input && _PyTokenizer_HasTrailingStatement(p->tok)) {
1180
0
        return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1181
0
    }
1182
1183
    // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1184
#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
1185
    if (p->start_rule == Py_single_input ||
1186
        p->start_rule == Py_file_input ||
1187
        p->start_rule == Py_eval_input)
1188
    {
1189
        if (!_PyAST_Validate(res)) {
1190
            return NULL;
1191
        }
1192
    }
1193
#endif
1194
8.29k
    return res;
1195
8.29k
}
1196
1197
mod_ty
1198
_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1199
                             const char *enc, const char *ps1, const char *ps2,
1200
                             PyCompilerFlags *flags, int *errcode,
1201
                             PyObject **interactive_src, PyArena *arena)
1202
0
{
1203
0
    int parser_flags = compute_parser_flags(flags);
1204
0
    struct tok_state *tok = _PyTokenizer_FromFile(fp, enc, ps1, ps2);
1205
0
    if (tok == NULL) {
1206
0
        if (PyErr_Occurred()) {
1207
0
            _PyTokenizer_raise_init_error(filename_ob);
1208
0
        }
1209
0
        else {
1210
            // The only silent tokenizer init failure is a failed allocation.
1211
0
            PyErr_NoMemory();
1212
0
        }
1213
0
        return NULL;
1214
0
    }
1215
0
    tok->barry_as_bdfl = parser_flags & PyPARSE_BARRY_AS_BDFL;
1216
1217
    // From here on we need to clean up even if there's an error
1218
0
    mod_ty result = NULL;
1219
1220
0
    PyObject *module = PyUnicode_FromString("__main__");
1221
0
    if (module == NULL) {
1222
0
        goto error;
1223
0
    }
1224
0
    _PyTokenizer_SetContext(tok, filename_ob, module);
1225
0
    Py_DECREF(module);
1226
1227
0
    Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1228
0
                                    errcode, NULL, arena);
1229
0
    if (p == NULL) {
1230
0
        goto error;
1231
0
    }
1232
1233
0
    result = _PyPegen_run_parser(p);
1234
0
    _PyPegen_Parser_Free(p);
1235
1236
0
    const char *source = _PyTokenizer_RetainedSource(tok);
1237
0
    if (source != NULL && result && interactive_src != NULL) {
1238
0
        *interactive_src = PyUnicode_FromString(source);
1239
0
        if (!*interactive_src || _PyArena_AddPyObject(arena, *interactive_src) < 0) {
1240
0
            Py_XDECREF(*interactive_src);
1241
0
            result = NULL;
1242
0
            goto error;
1243
0
        }
1244
0
    }
1245
1246
0
error:
1247
0
    _PyTokenizer_Free(tok);
1248
0
    return result;
1249
0
}
1250
1251
mod_ty
1252
_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
1253
                       PyCompilerFlags *flags, PyArena *arena, PyObject *module,
1254
                       PyObject **incomplete)
1255
76.0k
{
1256
76.0k
    _PyTokenizer_Newline newline_mode = start_rule == Py_file_input
1257
76.0k
        ? _PyTokenizer_IMPLY_NEWLINE : _PyTokenizer_KEEP_NEWLINE;
1258
76.0k
    int parser_flags = compute_parser_flags(flags);
1259
76.0k
    if (parser_flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) {
1260
0
        newline_mode = _PyTokenizer_APPEND_NEWLINE;
1261
0
    }
1262
1263
76.0k
    struct tok_state *tok;
1264
76.0k
    if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
1265
53.0k
        tok = _PyTokenizer_FromUTF8(str, newline_mode, 0);
1266
53.0k
    } else {
1267
22.9k
        tok = _PyTokenizer_FromString(str, newline_mode, 0);
1268
22.9k
    }
1269
76.0k
    if (tok == NULL) {
1270
2.65k
        if (PyErr_Occurred()) {
1271
2.65k
            _PyTokenizer_raise_init_error(filename_ob);
1272
2.65k
        }
1273
0
        else {
1274
            // The only silent tokenizer init failure is a failed allocation.
1275
0
            PyErr_NoMemory();
1276
0
        }
1277
2.65k
        return NULL;
1278
2.65k
    }
1279
73.3k
    tok->barry_as_bdfl = parser_flags & PyPARSE_BARRY_AS_BDFL;
1280
1281
73.3k
    _PyTokenizer_SetContext(tok, filename_ob, module);
1282
1283
    // We need to clear up from here on
1284
73.3k
    mod_ty result = NULL;
1285
1286
73.3k
    int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1287
72.6k
        flags->cf_feature_version : PY_MINOR_VERSION;
1288
73.3k
    Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1289
73.3k
                                    NULL, str, arena);
1290
73.3k
    if (p == NULL) {
1291
0
        goto error;
1292
0
    }
1293
1294
73.3k
    result = _PyPegen_run_parser(p);
1295
73.3k
    if (result != NULL && (parser_flags & PyPARSE_ALLOW_INCOMPLETE_INPUT)) {
1296
0
        int needs_newline = _PyTokenizer_GetNewlineRequirements(tok);
1297
0
        if ((needs_newline & _PyTokenizer_NEWLINE_CONTINUATION) ||
1298
0
            (start_rule != Py_file_input &&
1299
0
             (needs_newline & _PyTokenizer_NEWLINE_INDENT)) ||
1300
0
            (start_rule == Py_single_input && p->input_exhausted &&
1301
0
             (needs_newline & _PyTokenizer_NEWLINE_STATEMENT))) {
1302
0
            _PyPegen_raise_incomplete_input(p);
1303
0
            if (incomplete != NULL && PyErr_ExceptionMatches(PyExc_IncompleteInputError)) {
1304
0
                *incomplete = PyErr_GetRaisedException();
1305
0
            }
1306
0
            else {
1307
0
                result = NULL;
1308
0
            }
1309
0
        }
1310
0
    }
1311
73.3k
    _PyPegen_Parser_Free(p);
1312
1313
73.3k
error:
1314
73.3k
    _PyTokenizer_Free(tok);
1315
73.3k
    return result;
1316
73.3k
}