Coverage Report

Created: 2026-01-10 06:41

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
0
{
28
0
    const unsigned char *data = (const unsigned char*)PyUnicode_AsUTF8(line);
29
30
0
    Py_ssize_t len = 0;
31
0
    while (col_offset < end_col_offset) {
32
0
        Py_UCS4 ch = data[col_offset];
33
0
        if (ch < 0x80) {
34
0
            col_offset += 1;
35
0
        } 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
0
        len++;
46
0
    }
47
0
    return len;
48
0
}
49
50
Py_ssize_t
51
_PyPegen_byte_offset_to_character_offset_raw(const char* str, Py_ssize_t col_offset)
52
18.0k
{
53
18.0k
    Py_ssize_t len = (Py_ssize_t)strlen(str);
54
18.0k
    if (col_offset > len + 1) {
55
15
        col_offset = len + 1;
56
15
    }
57
18.0k
    assert(col_offset >= 0);
58
18.0k
    PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
59
18.0k
    if (!text) {
60
0
        return -1;
61
0
    }
62
18.0k
    Py_ssize_t size = PyUnicode_GET_LENGTH(text);
63
18.0k
    Py_DECREF(text);
64
18.0k
    return size;
65
18.0k
}
66
67
Py_ssize_t
68
_PyPegen_byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
69
18.0k
{
70
18.0k
    const char *str = PyUnicode_AsUTF8(line);
71
18.0k
    if (!str) {
72
0
        return -1;
73
0
    }
74
18.0k
    return _PyPegen_byte_offset_to_character_offset_raw(str, col_offset);
75
18.0k
}
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
11.5M
{
82
    // Insert in front
83
11.5M
    Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
84
11.5M
    if (m == NULL) {
85
0
        return -1;
86
0
    }
87
11.5M
    m->type = type;
88
11.5M
    m->node = node;
89
11.5M
    m->mark = p->mark;
90
11.5M
    m->next = p->tokens[mark]->memo;
91
11.5M
    p->tokens[mark]->memo = m;
92
11.5M
    return 0;
93
11.5M
}
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
9.07M
{
99
44.7M
    for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
100
39.0M
        if (m->type == type) {
101
            // Update existing node.
102
3.39M
            m->node = node;
103
3.39M
            m->mark = p->mark;
104
3.39M
            return 0;
105
3.39M
        }
106
39.0M
    }
107
    // Insert new node.
108
5.67M
    return _PyPegen_insert_memo(p, mark, type, node);
109
9.07M
}
110
111
static int
112
init_normalization(Parser *p)
113
54.1k
{
114
54.1k
    if (p->normalize) {
115
52.6k
        return 1;
116
52.6k
    }
117
1.48k
    p->normalize = PyImport_ImportModuleAttrString("unicodedata", "normalize");
118
1.48k
    if (!p->normalize)
119
0
    {
120
0
        return 0;
121
0
    }
122
1.48k
    return 1;
123
1.48k
}
124
125
static int
126
18.6k
growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
127
18.6k
    assert(initial_size > 0);
128
18.6k
    arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
129
18.6k
    arr->size = initial_size;
130
18.6k
    arr->num_items = 0;
131
132
18.6k
    return arr->items != NULL;
133
18.6k
}
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
18.6k
growable_comment_array_deallocate(growable_comment_array *arr) {
155
18.6k
    for (unsigned i = 0; i < arr->num_items; i++) {
156
0
        PyMem_Free(arr->items[i].comment);
157
0
    }
158
18.6k
    PyMem_Free(arr->items);
159
18.6k
}
160
161
static int
162
_get_keyword_or_name_type(Parser *p, struct token *new_token)
163
548k
{
164
548k
    Py_ssize_t name_len = new_token->end_col_offset - new_token->col_offset;
165
548k
    assert(name_len > 0);
166
167
548k
    if (name_len >= p->n_keyword_lists ||
168
498k
        p->keywords[name_len] == NULL ||
169
498k
        p->keywords[name_len]->type == -1) {
170
232k
        return NAME;
171
232k
    }
172
1.64M
    for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
173
1.46M
        if (strncmp(k->str, new_token->start, (size_t)name_len) == 0) {
174
133k
            return k->type;
175
133k
        }
176
1.46M
    }
177
183k
    return NAME;
178
316k
}
179
180
static int
181
1.72M
initialize_token(Parser *p, Token *parser_token, struct token *new_token, int token_type) {
182
1.72M
    assert(parser_token != NULL);
183
184
1.72M
    parser_token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, new_token) : token_type;
185
1.72M
    parser_token->bytes = PyBytes_FromStringAndSize(new_token->start, new_token->end - new_token->start);
186
1.72M
    if (parser_token->bytes == NULL) {
187
0
        return -1;
188
0
    }
189
1.72M
    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.72M
    parser_token->metadata = NULL;
195
1.72M
    if (new_token->metadata != NULL) {
196
9.59k
        if (_PyArena_AddPyObject(p->arena, new_token->metadata) < 0) {
197
0
            Py_DECREF(new_token->metadata);
198
0
            return -1;
199
0
        }
200
9.59k
        parser_token->metadata = new_token->metadata;
201
9.59k
        new_token->metadata = NULL;
202
9.59k
    }
203
204
1.72M
    parser_token->level = new_token->level;
205
1.72M
    parser_token->lineno = new_token->lineno;
206
1.72M
    parser_token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->col_offset
207
1.72M
                                                                    : new_token->col_offset;
208
1.72M
    parser_token->end_lineno = new_token->end_lineno;
209
1.72M
    parser_token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->end_col_offset
210
1.72M
                                                                 : new_token->end_col_offset;
211
212
1.72M
    p->fill += 1;
213
214
1.72M
    if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
215
0
        return _Pypegen_raise_decode_error(p);
216
0
    }
217
218
1.72M
    return (token_type == ERRORTOKEN ? _Pypegen_tokenizer_error(p) : 0);
219
1.72M
}
220
221
static int
222
74.1k
_resize_tokens_array(Parser *p) {
223
74.1k
    int newsize = p->size * 2;
224
74.1k
    Token **new_tokens = PyMem_Realloc(p->tokens, (size_t)newsize * sizeof(Token *));
225
74.1k
    if (new_tokens == NULL) {
226
0
        PyErr_NoMemory();
227
0
        return -1;
228
0
    }
229
74.1k
    p->tokens = new_tokens;
230
231
2.58M
    for (int i = p->size; i < newsize; i++) {
232
2.50M
        p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
233
2.50M
        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
2.50M
    }
239
74.1k
    p->size = newsize;
240
74.1k
    return 0;
241
74.1k
}
242
243
int
244
_PyPegen_fill_token(Parser *p)
245
1.72M
{
246
1.72M
    struct token new_token;
247
1.72M
    _PyToken_Init(&new_token);
248
1.72M
    int type = _PyTokenizer_Get(p->tok, &new_token);
249
250
    // Record and skip '# type: ignore' comments
251
1.72M
    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.72M
    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.72M
    else {
279
1.72M
        p->parsing_started = 1;
280
1.72M
    }
281
282
    // Check if we are at the limit of the token array capacity and resize if needed
283
1.72M
    if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
284
0
        goto error;
285
0
    }
286
287
1.72M
    Token *t = p->tokens[p->fill];
288
1.72M
    return initialize_token(p, t, &new_token, type);
289
0
error:
290
0
    _PyToken_Free(&new_token);
291
0
    return -1;
292
1.72M
}
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
44.0M
{
343
44.0M
    if (p->mark == p->fill) {
344
333k
        if (_PyPegen_fill_token(p) < 0) {
345
705
            p->error_indicator = 1;
346
705
            return -1;
347
705
        }
348
333k
    }
349
350
44.0M
    Token *t = p->tokens[p->mark];
351
352
129M
    for (Memo *m = t->memo; m != NULL; m = m->next) {
353
117M
        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
32.3M
            p->mark = m->mark;
367
32.3M
            *(void **)(pres) = m->node;
368
32.3M
            return 1;
369
32.3M
        }
370
117M
    }
371
11.6M
    return 0;
372
44.0M
}
373
374
#define LOOKAHEAD1(NAME, RES_TYPE)                                  \
375
    int                                                             \
376
    NAME (int positive, RES_TYPE (func)(Parser *), Parser *p)       \
377
2.27M
    {                                                               \
378
2.27M
        int mark = p->mark;                                         \
379
2.27M
        void *res = func(p);                                        \
380
2.27M
        p->mark = mark;                                             \
381
2.27M
        return (res != NULL) == positive;                           \
382
2.27M
    }
383
384
2.27M
LOOKAHEAD1(_PyPegen_lookahead, void *)
385
1.09k
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
3.55M
    {                                                                   \
393
3.55M
        int mark = p->mark;                                             \
394
3.55M
        void *res = func(p, arg);                                       \
395
3.55M
        p->mark = mark;                                                 \
396
3.55M
        return (res != NULL) == positive;                               \
397
3.55M
    }
398
399
3.34M
LOOKAHEAD2(_PyPegen_lookahead_with_int, Token *, int)
400
209k
LOOKAHEAD2(_PyPegen_lookahead_with_string, expr_ty, const char *)
401
#undef LOOKAHEAD2
402
403
Token *
404
_PyPegen_expect_token(Parser *p, int type)
405
52.7M
{
406
52.7M
    if (p->mark == p->fill) {
407
1.00M
        if (_PyPegen_fill_token(p) < 0) {
408
2.06k
            p->error_indicator = 1;
409
2.06k
            return NULL;
410
2.06k
        }
411
1.00M
    }
412
52.7M
    Token *t = p->tokens[p->mark];
413
52.7M
    if (t->type != type) {
414
46.5M
       return NULL;
415
46.5M
    }
416
6.24M
    p->mark += 1;
417
6.24M
    return t;
418
52.7M
}
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
20.6k
_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
435
436
20.6k
    if (p->error_indicator == 1) {
437
0
        return NULL;
438
0
    }
439
440
20.6k
    if (p->mark == p->fill) {
441
7.25k
        if (_PyPegen_fill_token(p) < 0) {
442
1
            p->error_indicator = 1;
443
1
            return NULL;
444
1
        }
445
7.25k
    }
446
20.6k
    Token *t = p->tokens[p->mark];
447
20.6k
    if (t->type != type) {
448
132
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
449
132
        return NULL;
450
132
    }
451
20.5k
    p->mark += 1;
452
20.5k
    return t;
453
20.6k
}
454
455
expr_ty
456
_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
457
456k
{
458
456k
    if (p->mark == p->fill) {
459
4.42k
        if (_PyPegen_fill_token(p) < 0) {
460
7
            p->error_indicator = 1;
461
7
            return NULL;
462
7
        }
463
4.42k
    }
464
456k
    Token *t = p->tokens[p->mark];
465
456k
    if (t->type != NAME) {
466
253k
        return NULL;
467
253k
    }
468
203k
    const char *s = PyBytes_AsString(t->bytes);
469
203k
    if (!s) {
470
0
        p->error_indicator = 1;
471
0
        return NULL;
472
0
    }
473
203k
    if (strcmp(s, keyword) != 0) {
474
179k
        return NULL;
475
179k
    }
476
24.0k
    return _PyPegen_name_token(p);
477
203k
}
478
479
Token *
480
_PyPegen_get_last_nonnwhitespace_token(Parser *p)
481
1.47M
{
482
1.47M
    assert(p->mark >= 0);
483
1.47M
    Token *token = NULL;
484
1.56M
    for (int m = p->mark - 1; m >= 0; m--) {
485
1.56M
        token = p->tokens[m];
486
1.56M
        if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
487
1.47M
            break;
488
1.47M
        }
489
1.56M
    }
490
1.47M
    return token;
491
1.47M
}
492
493
PyObject *
494
_PyPegen_new_identifier(Parser *p, const char *n)
495
2.29M
{
496
2.29M
    PyObject *id = PyUnicode_DecodeUTF8(n, (Py_ssize_t)strlen(n), NULL);
497
2.29M
    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
2.29M
    if (!PyUnicode_IS_ASCII(id))
503
54.1k
    {
504
54.1k
        if (!init_normalization(p))
505
0
        {
506
0
            Py_DECREF(id);
507
0
            goto error;
508
0
        }
509
54.1k
        PyObject *form = PyUnicode_InternFromString("NFKC");
510
54.1k
        if (form == NULL)
511
0
        {
512
0
            Py_DECREF(id);
513
0
            goto error;
514
0
        }
515
54.1k
        PyObject *args[2] = {form, id};
516
54.1k
        PyObject *id2 = PyObject_Vectorcall(p->normalize, args, 2, NULL);
517
54.1k
        Py_DECREF(id);
518
54.1k
        Py_DECREF(form);
519
54.1k
        if (!id2) {
520
0
            goto error;
521
0
        }
522
523
54.1k
        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
54.1k
        id = id2;
533
54.1k
    }
534
2.29M
    static const char * const forbidden[] = {
535
2.29M
        "None",
536
2.29M
        "True",
537
2.29M
        "False",
538
2.29M
        NULL
539
2.29M
    };
540
9.19M
    for (int i = 0; forbidden[i] != NULL; i++) {
541
6.89M
        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
6.89M
    }
549
2.29M
    PyInterpreterState *interp = _PyInterpreterState_GET();
550
2.29M
    _PyUnicode_InternImmortal(interp, &id);
551
2.29M
    if (_PyArena_AddPyObject(p->arena, id) < 0)
552
0
    {
553
0
        Py_DECREF(id);
554
0
        goto error;
555
0
    }
556
2.29M
    return id;
557
558
0
error:
559
0
    p->error_indicator = 1;
560
0
    return NULL;
561
2.29M
}
562
563
static expr_ty
564
_PyPegen_name_from_token(Parser *p, Token* t)
565
5.35M
{
566
5.35M
    if (t == NULL) {
567
3.05M
        return NULL;
568
3.05M
    }
569
2.29M
    const char *s = PyBytes_AsString(t->bytes);
570
2.29M
    if (!s) {
571
0
        p->error_indicator = 1;
572
0
        return NULL;
573
0
    }
574
2.29M
    PyObject *id = _PyPegen_new_identifier(p, s);
575
2.29M
    if (id == NULL) {
576
0
        p->error_indicator = 1;
577
0
        return NULL;
578
0
    }
579
2.29M
    return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
580
2.29M
                       t->end_col_offset, p->arena);
581
2.29M
}
582
583
expr_ty
584
_PyPegen_name_token(Parser *p)
585
5.34M
{
586
5.34M
    Token *t = _PyPegen_expect_token(p, NAME);
587
5.34M
    return _PyPegen_name_from_token(p, t);
588
5.34M
}
589
590
void *
591
_PyPegen_string_token(Parser *p)
592
1.32M
{
593
1.32M
    return _PyPegen_expect_token(p, STRING);
594
1.32M
}
595
596
215k
expr_ty _PyPegen_soft_keyword_token(Parser *p) {
597
215k
    Token *t = _PyPegen_expect_token(p, NAME);
598
215k
    if (t == NULL) {
599
148k
        return NULL;
600
148k
    }
601
67.3k
    char *the_token;
602
67.3k
    Py_ssize_t size;
603
67.3k
    PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
604
322k
    for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
605
258k
        if (strlen(*keyword) == (size_t)size &&
606
58.5k
            strncmp(*keyword, the_token, (size_t)size) == 0) {
607
4.37k
            return _PyPegen_name_from_token(p, t);
608
4.37k
        }
609
258k
    }
610
63.0k
    return NULL;
611
67.3k
}
612
613
static PyObject *
614
parsenumber_raw(const char *s)
615
239k
{
616
239k
    const char *end;
617
239k
    long x;
618
239k
    double dx;
619
239k
    Py_complex compl;
620
239k
    int imflag;
621
622
239k
    assert(s != NULL);
623
239k
    errno = 0;
624
239k
    end = s + strlen(s) - 1;
625
239k
    imflag = *end == 'j' || *end == 'J';
626
239k
    if (s[0] == '0') {
627
75.8k
        x = (long)PyOS_strtoul(s, (char **)&end, 0);
628
75.8k
        if (x < 0 && errno == 0) {
629
303
            return PyLong_FromString(s, (char **)0, 0);
630
303
        }
631
75.8k
    }
632
163k
    else {
633
163k
        x = PyOS_strtol(s, (char **)&end, 0);
634
163k
    }
635
239k
    if (*end == '\0') {
636
183k
        if (errno != 0) {
637
2.36k
            return PyLong_FromString(s, (char **)0, 0);
638
2.36k
        }
639
181k
        return PyLong_FromLong(x);
640
183k
    }
641
    /* XXX Huge floats may silently fail */
642
55.5k
    if (imflag) {
643
7.91k
        compl.real = 0.;
644
7.91k
        compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
645
7.91k
        if (compl.imag == -1.0 && PyErr_Occurred()) {
646
0
            return NULL;
647
0
        }
648
7.91k
        return PyComplex_FromCComplex(compl);
649
7.91k
    }
650
47.6k
    dx = PyOS_string_to_double(s, NULL, NULL);
651
47.6k
    if (dx == -1.0 && PyErr_Occurred()) {
652
7
        return NULL;
653
7
    }
654
47.6k
    return PyFloat_FromDouble(dx);
655
47.6k
}
656
657
static PyObject *
658
parsenumber(const char *s)
659
239k
{
660
239k
    char *dup;
661
239k
    char *end;
662
239k
    PyObject *res = NULL;
663
664
239k
    assert(s != NULL);
665
666
239k
    if (strchr(s, '_') == NULL) {
667
238k
        return parsenumber_raw(s);
668
238k
    }
669
    /* Create a duplicate without underscores. */
670
996
    dup = PyMem_Malloc(strlen(s) + 1);
671
996
    if (dup == NULL) {
672
0
        return PyErr_NoMemory();
673
0
    }
674
996
    end = dup;
675
16.3k
    for (; *s; s++) {
676
15.3k
        if (*s != '_') {
677
12.3k
            *end++ = *s;
678
12.3k
        }
679
15.3k
    }
680
996
    *end = '\0';
681
996
    res = parsenumber_raw(dup);
682
996
    PyMem_Free(dup);
683
996
    return res;
684
996
}
685
686
expr_ty
687
_PyPegen_number_token(Parser *p)
688
858k
{
689
858k
    Token *t = _PyPegen_expect_token(p, NUMBER);
690
858k
    if (t == NULL) {
691
619k
        return NULL;
692
619k
    }
693
694
239k
    const char *num_raw = PyBytes_AsString(t->bytes);
695
239k
    if (num_raw == NULL) {
696
0
        p->error_indicator = 1;
697
0
        return NULL;
698
0
    }
699
700
239k
    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
239k
    PyObject *c = parsenumber(num_raw);
707
708
239k
    if (c == NULL) {
709
7
        p->error_indicator = 1;
710
7
        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
7
        if (tstate->current_exception != NULL &&
714
7
            Py_TYPE(tstate->current_exception) == (PyTypeObject *)PyExc_ValueError
715
7
        ) {
716
7
            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
7
            RAISE_ERROR_KNOWN_LOCATION(
721
7
                p, PyExc_SyntaxError,
722
7
                t->lineno, -1 /* col_offset */,
723
7
                t->end_lineno, -1 /* end_col_offset */,
724
7
                "%S - Consider hexadecimal for huge integer literals "
725
7
                "to avoid decimal conversion limits.",
726
7
                exc);
727
7
            Py_DECREF(exc);
728
7
        }
729
7
        return NULL;
730
7
    }
731
732
239k
    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
239k
    return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
739
239k
                           t->end_col_offset, p->arena);
740
239k
}
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
18.6k
{
774
18.6k
    int parser_flags = 0;
775
18.6k
    if (!flags) {
776
84
        return 0;
777
84
    }
778
18.5k
    if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
779
0
        parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
780
0
    }
781
18.5k
    if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
782
100
        parser_flags |= PyPARSE_IGNORE_COOKIE;
783
100
    }
784
18.5k
    if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
785
0
        parser_flags |= PyPARSE_BARRY_AS_BDFL;
786
0
    }
787
18.5k
    if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
788
0
        parser_flags |= PyPARSE_TYPE_COMMENTS;
789
0
    }
790
18.5k
    if (flags->cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT) {
791
0
        parser_flags |= PyPARSE_ALLOW_INCOMPLETE_INPUT;
792
0
    }
793
18.5k
    return parser_flags;
794
18.6k
}
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
18.6k
{
802
18.6k
    Parser *p = PyMem_Malloc(sizeof(Parser));
803
18.6k
    if (p == NULL) {
804
0
        return (Parser *) PyErr_NoMemory();
805
0
    }
806
18.6k
    assert(tok != NULL);
807
18.6k
    tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
808
18.6k
    p->tok = tok;
809
18.6k
    p->keywords = NULL;
810
18.6k
    p->n_keyword_lists = -1;
811
18.6k
    p->soft_keywords = NULL;
812
18.6k
    p->tokens = PyMem_Malloc(sizeof(Token *));
813
18.6k
    if (!p->tokens) {
814
0
        PyMem_Free(p);
815
0
        return (Parser *) PyErr_NoMemory();
816
0
    }
817
18.6k
    p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
818
18.6k
    if (!p->tokens[0]) {
819
0
        PyMem_Free(p->tokens);
820
0
        PyMem_Free(p);
821
0
        return (Parser *) PyErr_NoMemory();
822
0
    }
823
18.6k
    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
18.6k
    p->mark = 0;
831
18.6k
    p->fill = 0;
832
18.6k
    p->size = 1;
833
834
18.6k
    p->errcode = errcode;
835
18.6k
    p->arena = arena;
836
18.6k
    p->start_rule = start_rule;
837
18.6k
    p->parsing_started = 0;
838
18.6k
    p->normalize = NULL;
839
18.6k
    p->error_indicator = 0;
840
841
18.6k
    p->starting_lineno = 0;
842
18.6k
    p->starting_col_offset = 0;
843
18.6k
    p->flags = flags;
844
18.6k
    p->feature_version = feature_version;
845
18.6k
    p->known_err_token = NULL;
846
18.6k
    p->level = 0;
847
18.6k
    p->call_invalid_rules = 0;
848
18.6k
    p->last_stmt_location.lineno = 0;
849
18.6k
    p->last_stmt_location.col_offset = 0;
850
18.6k
    p->last_stmt_location.end_lineno = 0;
851
18.6k
    p->last_stmt_location.end_col_offset = 0;
852
#ifdef Py_DEBUG
853
    p->debug = _Py_GetConfig()->parser_debug;
854
#endif
855
18.6k
    return p;
856
18.6k
}
857
858
void
859
_PyPegen_Parser_Free(Parser *p)
860
18.6k
{
861
18.6k
    Py_XDECREF(p->normalize);
862
2.54M
    for (int i = 0; i < p->size; i++) {
863
2.52M
        PyMem_Free(p->tokens[i]);
864
2.52M
    }
865
18.6k
    PyMem_Free(p->tokens);
866
18.6k
    growable_comment_array_deallocate(&p->type_ignore_comments);
867
18.6k
    PyMem_Free(p);
868
18.6k
}
869
870
static void
871
reset_parser_state_for_error_pass(Parser *p)
872
12.1k
{
873
12.1k
    p->last_stmt_location.lineno = 0;
874
12.1k
    p->last_stmt_location.col_offset = 0;
875
12.1k
    p->last_stmt_location.end_lineno = 0;
876
12.1k
    p->last_stmt_location.end_col_offset = 0;
877
474k
    for (int i = 0; i < p->fill; i++) {
878
462k
        p->tokens[i]->memo = NULL;
879
462k
    }
880
12.1k
    p->mark = 0;
881
12.1k
    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
12.1k
    p->tok->interactive_underflow = IUNDERFLOW_STOP;
885
12.1k
}
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
12.0k
_PyPegen_set_syntax_error_metadata(Parser *p) {
895
12.0k
    PyObject *exc = PyErr_GetRaisedException();
896
12.0k
    if (!exc || !PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_SyntaxError)) {
897
0
        PyErr_SetRaisedException(exc);
898
0
        return;
899
0
    }
900
12.0k
    const char *source = NULL;
901
12.0k
    if (p->tok->str != NULL) {
902
12.0k
        source = p->tok->str;
903
12.0k
    }
904
12.0k
    if (!source && p->tok->fp_interactive && p->tok->interactive_src_start) {
905
0
        source = p->tok->interactive_src_start;
906
0
    }
907
12.0k
    PyObject* the_source = NULL;
908
12.0k
    if (source) {
909
12.0k
        if (p->tok->encoding == NULL) {
910
10.6k
            the_source = PyUnicode_FromString(source);
911
10.6k
        } else {
912
1.41k
            the_source = PyUnicode_Decode(source, strlen(source), p->tok->encoding, NULL);
913
1.41k
        }
914
12.0k
    }
915
12.0k
    if (!the_source) {
916
0
        PyErr_Clear();
917
0
        the_source = Py_None;
918
0
        Py_INCREF(the_source);
919
0
    }
920
12.0k
    PyObject* metadata = Py_BuildValue(
921
12.0k
        "(iiN)",
922
12.0k
        p->last_stmt_location.lineno,
923
12.0k
        p->last_stmt_location.col_offset,
924
12.0k
        the_source // N gives ownership to metadata
925
12.0k
    );
926
12.0k
    if (!metadata) {
927
0
        Py_DECREF(the_source);
928
0
        PyErr_Clear();
929
0
        return;
930
0
    }
931
12.0k
    PySyntaxErrorObject *syntax_error = (PySyntaxErrorObject *)exc;
932
933
12.0k
    Py_XDECREF(syntax_error->metadata);
934
12.0k
    syntax_error->metadata = metadata;
935
12.0k
    PyErr_SetRaisedException(exc);
936
12.0k
}
937
938
void *
939
_PyPegen_run_parser(Parser *p)
940
18.6k
{
941
18.6k
    void *res = _PyPegen_parse(p);
942
18.6k
    assert(p->level == 0);
943
18.6k
    if (res == NULL) {
944
12.1k
        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
12.1k
        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
12.1k
        Token *last_token = p->tokens[p->fill - 1];
955
12.1k
        reset_parser_state_for_error_pass(p);
956
12.1k
        _PyPegen_parse(p);
957
958
        // Set SyntaxErrors accordingly depending on the parser/tokenizer status at the failure
959
        // point.
960
12.1k
        _Pypegen_set_syntax_error(p, last_token);
961
962
        // Set the metadata in the exception from p->last_stmt_location
963
12.1k
        if (PyErr_ExceptionMatches(PyExc_SyntaxError)) {
964
12.0k
            _PyPegen_set_syntax_error_metadata(p);
965
12.0k
        }
966
12.1k
       return NULL;
967
12.1k
    }
968
969
6.49k
    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
6.49k
    return res;
986
6.49k
}
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
21.0k
{
1045
21.0k
    int exec_input = start_rule == Py_file_input;
1046
1047
21.0k
    struct tok_state *tok;
1048
21.0k
    if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
1049
100
        tok = _PyTokenizer_FromUTF8(str, exec_input, 0);
1050
20.9k
    } else {
1051
20.9k
        tok = _PyTokenizer_FromString(str, exec_input, 0);
1052
20.9k
    }
1053
21.0k
    if (tok == NULL) {
1054
2.42k
        if (PyErr_Occurred()) {
1055
2.42k
            _PyPegen_raise_tokenizer_init_error(filename_ob);
1056
2.42k
        }
1057
2.42k
        return NULL;
1058
2.42k
    }
1059
    // This transfers the ownership to the tokenizer
1060
18.6k
    tok->filename = Py_NewRef(filename_ob);
1061
18.6k
    tok->module = Py_XNewRef(module);
1062
1063
    // We need to clear up from here on
1064
18.6k
    mod_ty result = NULL;
1065
1066
18.6k
    int parser_flags = compute_parser_flags(flags);
1067
18.6k
    int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1068
18.1k
        flags->cf_feature_version : PY_MINOR_VERSION;
1069
18.6k
    Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1070
18.6k
                                    NULL, str, arena);
1071
18.6k
    if (p == NULL) {
1072
0
        goto error;
1073
0
    }
1074
1075
18.6k
    result = _PyPegen_run_parser(p);
1076
18.6k
    _PyPegen_Parser_Free(p);
1077
1078
18.6k
error:
1079
18.6k
    _PyTokenizer_Free(tok);
1080
18.6k
    return result;
1081
18.6k
}