Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Parser/lexer/lexer.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_token.h"
3
#include "pycore_unicodeobject.h"
4
#include "errcode.h"
5
6
#include "lexer_internal.h"
7
#include "../tokenizer/helpers.h"
8
#include "../tokenizer/reader.h"
9
10
1.58M
#define MAKE_TOKEN(token_type) _PyLexer_token_setup(tok, token, token_type, p_start, p_end)
11
12
/* Spaces in this constant are treated as "zero or more spaces or tabs" when
13
   tokenizing. */
14
static const char* type_comment_prefix = "# type: ";
15
16
int
17
_PyLexer_refill(struct tok_state *tok)
18
452k
{
19
452k
    if (tok->done != E_OK) {
20
123k
        return 0;
21
123k
    }
22
328k
    int rc = _PyTok_ReaderUnderflow(tok);
23
#if defined(Py_DEBUG)
24
    if (tok->debug) {
25
        fprintf(stderr, "line[%d] = ", tok->lineno);
26
        _PyTokenizer_print_escape(
27
            stderr, _PyTok_SourcePointer(&tok->source, tok->cur),
28
            tok->inp - tok->cur);
29
        fprintf(stderr, "  tok->done = %d\n", tok->done);
30
    }
31
#endif
32
328k
    if (!rc) {
33
62.0k
        tok->cur = tok->inp;
34
62.0k
        return 0;
35
62.0k
    }
36
266k
    tok->line_start = tok->cur;
37
266k
    _PyTok_Span line = {tok->line_start, tok->inp};
38
266k
    if (_PyTok_SourceFindByte(&tok->source, line, '\0') >= 0) {
39
99
        _PyTokenizer_syntaxerror(tok, "source code cannot contain null bytes");
40
99
        tok->cur = tok->inp;
41
99
        return 0;
42
99
    }
43
266k
    return 1;
44
266k
}
45
46
/* Back-up one character */
47
void
48
_PyLexer_backup(struct tok_state *tok, int c)
49
4.13M
{
50
4.13M
    if (c != EOF) {
51
4.00M
        if (--tok->cur < tok->buf_offset) {
52
0
            Py_FatalError("tokenizer beginning of buffer");
53
0
        }
54
4.00M
        if (_PyTok_SourceByte(&tok->source, tok->cur) != Py_CHARMASK(c)) {
55
0
            Py_FatalError("tok_backup: wrong character");
56
0
        }
57
4.00M
    }
58
4.13M
}
59
60
61
62
/* Verify that the identifier follows PEP 3131. */
63
static int
64
verify_identifier(struct tok_state *tok)
65
12.7k
{
66
12.7k
    if (tok->tok_extra_tokens) {
67
0
        return 1;
68
0
    }
69
12.7k
    PyObject *s;
70
12.7k
    if (tok_failed(tok))
71
0
        return 0;
72
12.7k
    s = PyUnicode_DecodeUTF8(_PyTok_SourcePointer(&tok->source, tok->start),
73
12.7k
                             tok->cur - tok->start, NULL);
74
12.7k
    if (s == NULL) {
75
0
        if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
76
0
            tok->done = E_DECODE;
77
0
        }
78
0
        else {
79
0
            tok->done = E_ERROR;
80
0
        }
81
0
        return 0;
82
0
    }
83
12.7k
    Py_ssize_t invalid = _PyUnicode_ScanIdentifier(s);
84
12.7k
    assert(invalid >= 0);
85
12.7k
    assert(PyUnicode_GET_LENGTH(s) > 0);
86
12.7k
    if (invalid < PyUnicode_GET_LENGTH(s)) {
87
595
        Py_UCS4 ch = PyUnicode_READ_CHAR(s, invalid);
88
595
        _PyTok_Off error_cursor = tok->cur;
89
595
        if (invalid + 1 < PyUnicode_GET_LENGTH(s)) {
90
            /* Determine the offset in UTF-8 encoded input */
91
397
            Py_SETREF(s, PyUnicode_Substring(s, 0, invalid + 1));
92
397
            if (s != NULL) {
93
397
                Py_SETREF(s, PyUnicode_AsUTF8String(s));
94
397
            }
95
397
            if (s == NULL) {
96
0
                tok->done = E_ERROR;
97
0
                return 0;
98
0
            }
99
397
            error_cursor = tok->start + PyBytes_GET_SIZE(s);
100
397
        }
101
595
        Py_DECREF(s);
102
595
        if (Py_UNICODE_ISPRINTABLE(ch)) {
103
353
            _PyTokenizer_syntaxerror_at(
104
353
                tok, _PyTok_SourcePointer(&tok->source, tok->line_start),
105
353
                error_cursor - tok->line_start, tok->lineno, -1, -1,
106
353
                "invalid character '%c' (U+%04X)", ch, ch);
107
353
        }
108
242
        else {
109
242
            _PyTokenizer_syntaxerror_at(
110
242
                tok, _PyTok_SourcePointer(&tok->source, tok->line_start),
111
242
                error_cursor - tok->line_start, tok->lineno, -1, -1,
112
242
                "invalid non-printable character U+%04X", ch);
113
242
        }
114
595
        return 0;
115
595
    }
116
12.1k
    Py_DECREF(s);
117
12.1k
    return 1;
118
12.7k
}
119
120
int
121
_PyLexer_get_normal(struct tok_state *tok, ftstring_state *current, struct token *token)
122
1.90M
{
123
1.90M
    assert(current == NULL ||
124
1.90M
           (current->mode == FTSTRING_MODE_EXPRESSION &&
125
1.90M
            current->replacement_depth > 0));
126
1.90M
    int c;
127
1.90M
    int blankline, nonascii;
128
129
1.90M
    _PyTok_Off p_start = -1;
130
1.90M
    _PyTok_Off p_end = -1;
131
2.02M
  nextline:
132
2.02M
    tok->start = -1;
133
2.02M
    tok->start_loc = (_PyTok_Loc){tok->lineno, -1};
134
2.02M
    blankline = 0;
135
136
137
2.02M
    if (tok->layout.at_bol) {
138
316k
        blankline = _PyLexer_BeginLine(tok);
139
316k
        if (blankline < 0) {
140
139
            return MAKE_TOKEN(ERRORTOKEN);
141
139
        }
142
316k
    }
143
144
2.02M
    tok->start = tok->cur;
145
2.02M
    tok->start_loc = (_PyTok_Loc){
146
2.02M
        tok->lineno, tok->line_start >= 0 ? _PyLexer_ByteColumn(tok) : -1};
147
148
2.02M
    if (tok->layout.pending != 0) {
149
18.8k
        return _PyLexer_IndentationToken(tok, token);
150
18.8k
    }
151
152
    /* Peek ahead at the next character */
153
2.00M
    c = tok_nextc(tok);
154
2.00M
    tok_backup(tok, c);
155
156
2.00M
 again:
157
2.00M
    tok->start = -1;
158
    /* Skip spaces */
159
2.36M
    do {
160
2.36M
        c = tok_nextc(tok);
161
2.36M
    } while (c == ' ' || c == '\t' || c == '\014');
162
163
    /* Set start of current token */
164
2.00M
    tok->start = tok->cur - 1;
165
2.00M
    tok->start_loc = (_PyTok_Loc){
166
2.00M
        tok->lineno, tok->line_start >= 0 ? _PyLexer_ByteColumn(tok) - 1 : -1};
167
168
    /* Skip comment, unless it's a type comment */
169
2.00M
    if (c == '#') {
170
171
1.15M
        while (c != EOF && c != '\n' && c != '\r') {
172
1.12M
            c = tok_nextc(tok);
173
1.12M
        }
174
175
36.0k
        if (current != NULL) {
176
2.41k
            _PyTok_Off comment_end = tok->cur;
177
2.41k
            if (c == '\n' || c == '\r') {
178
2.41k
                comment_end--;
179
2.41k
            }
180
2.41k
            if (_PyLexer_record_ftstring_comment(
181
2.41k
                    tok, current, tok->start, comment_end) < 0) {
182
0
                tok->done = E_NOMEM;
183
0
                return MAKE_TOKEN(ERRORTOKEN);
184
0
            }
185
2.41k
        }
186
187
36.0k
        _PyTok_Off comment = tok->start;
188
36.0k
        if (tok->type_comments) {
189
0
            const char *prefix = type_comment_prefix;
190
0
            while (*prefix && comment < tok->cur) {
191
0
                if (*prefix == ' ') {
192
0
                    while (comment < tok->cur) {
193
0
                        int ch = _PyTok_SourceByte(&tok->source, comment);
194
0
                        if (ch != ' ' && ch != '\t') {
195
0
                            break;
196
0
                        }
197
0
                        comment++;
198
0
                    }
199
0
                } else if (*prefix == _PyTok_SourceByte(&tok->source, comment)) {
200
0
                    comment++;
201
0
                } else {
202
0
                    break;
203
0
                }
204
205
0
                prefix++;
206
0
            }
207
208
            /* This is a type comment if we matched all of type_comment_prefix. */
209
0
            if (!*prefix) {
210
0
                tok_backup(tok, c);  /* don't eat the newline or EOF */
211
                /* A TYPE_IGNORE is "type: ignore" followed by the end of the token
212
                 * or anything ASCII and non-alphanumeric. */
213
0
                int is_type_ignore = tok->cur - comment >= 6 &&
214
0
                    memcmp(_PyTok_SourcePointer(&tok->source, comment),
215
0
                           "ignore", 6) == 0;
216
0
                if (is_type_ignore && comment + 6 < tok->cur) {
217
0
                    int ch = _PyTok_SourceByte(&tok->source, comment + 6);
218
0
                    is_type_ignore = ch < 128 && !Py_ISALNUM(ch);
219
0
                }
220
221
0
                int type = is_type_ignore ? TYPE_IGNORE : TYPE_COMMENT;
222
0
                p_start = comment + (is_type_ignore ? 6 : 0);
223
0
                p_end = tok->cur;
224
0
                int start_col_offset = tok->start_loc.byte_col +
225
0
                    (int)(p_start - tok->start);
226
                /* Consume the newline after a standalone type ignore. */
227
0
                if (is_type_ignore && blankline) {
228
0
                    tok_nextc(tok);
229
0
                    tok->layout.at_bol = 1;
230
0
                }
231
0
                _PyLexer_token_setup(tok, token, type, p_start, p_end);
232
0
                token->start_loc = (_PyTok_Loc){tok->lineno, start_col_offset};
233
0
                token->end_loc = (_PyTok_Loc){tok->lineno,
234
0
                                              _PyLexer_ByteColumn(tok)};
235
0
                return type;
236
0
            }
237
0
        }
238
36.0k
        if (tok->implicit_newline == _PyTokenizer_IMPLY_NEWLINE &&
239
1.90k
            tok->layout.depth > 0) {
240
            // Ending this comment lets the next line dedent the suite.
241
46
            tok->needs_newline |= _PyTokenizer_NEWLINE_STATEMENT;
242
46
        }
243
36.0k
        if (tok->tok_extra_tokens) {
244
44
            tok_backup(tok, c);  /* don't eat the newline or EOF */
245
44
            p_start = comment;
246
44
            p_end = tok->cur;
247
44
            tok->layout.comment_newline = blankline;
248
44
            return MAKE_TOKEN(COMMENT);
249
44
        }
250
36.0k
    }
251
252
2.00M
    if (tok->done == E_INTERACT_STOP) {
253
0
        return MAKE_TOKEN(ENDMARKER);
254
0
    }
255
256
    /* Check for EOF and errors now */
257
2.00M
    if (c == EOF) {
258
61.9k
        if (tok->level) {
259
4.46k
            return MAKE_TOKEN(ERRORTOKEN);
260
4.46k
        }
261
57.5k
        return MAKE_TOKEN(tok->done == E_EOF ? ENDMARKER : ERRORTOKEN);
262
61.9k
    }
263
264
    /* Identifier (most frequent token!) */
265
1.94M
    nonascii = 0;
266
1.94M
    if (is_potential_identifier_start(c)) {
267
        /* Process the various legal combinations of b"", r"", u"", and f"". */
268
634k
        int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0, saw_t = 0;
269
783k
        while (1) {
270
783k
            if (!saw_b && (c == 'b' || c == 'B')) {
271
20.6k
                saw_b = 1;
272
20.6k
            }
273
            /* Since this is a backwards compatibility support literal we don't
274
               want to support it in arbitrary order like byte literals. */
275
763k
            else if (!saw_u && (c == 'u'|| c == 'U')) {
276
48.5k
                saw_u = 1;
277
48.5k
            }
278
            /* ur"" and ru"" are not supported */
279
714k
            else if (!saw_r && (c == 'r' || c == 'R')) {
280
26.2k
                saw_r = 1;
281
26.2k
            }
282
688k
            else if (!saw_f && (c == 'f' || c == 'F')) {
283
47.2k
                saw_f = 1;
284
47.2k
            }
285
641k
            else if (!saw_t && (c == 't' || c == 'T')) {
286
34.9k
                saw_t = 1;
287
34.9k
            }
288
606k
            else {
289
606k
                break;
290
606k
            }
291
177k
            c = tok_nextc(tok);
292
177k
            if (c == '"' || c == '\'') {
293
                // Raise error on incompatible string prefixes:
294
28.0k
                int status = _PyLexer_check_string_prefixes(
295
28.0k
                    tok, saw_b, saw_r, saw_u, saw_f, saw_t);
296
28.0k
                if (status < 0) {
297
8
                    return MAKE_TOKEN(ERRORTOKEN);
298
8
                }
299
300
                // Handle valid f or t string creation:
301
28.0k
                if (saw_f || saw_t) {
302
22.9k
                    ftstring_kind kind = saw_t
303
22.9k
                        ? (saw_r ? RAW_TSTRING : TSTRING)
304
22.9k
                        : (saw_r ? RAW_FSTRING : FSTRING);
305
22.9k
                    return _PyLexer_scan_fstring_start(tok, token, c, kind);
306
22.9k
                }
307
5.11k
                return _PyLexer_scan_string(tok, token, c);
308
28.0k
            }
309
177k
        }
310
2.62M
        while (is_potential_identifier_char(c)) {
311
2.02M
            if (c >= 128) {
312
257k
                nonascii = 1;
313
257k
            }
314
2.02M
            c = tok_nextc(tok);
315
2.02M
        }
316
606k
        tok_backup(tok, c);
317
606k
        if (nonascii && !verify_identifier(tok)) {
318
595
            return MAKE_TOKEN(ERRORTOKEN);
319
595
        }
320
321
605k
        p_start = tok->start;
322
605k
        p_end = tok->cur;
323
324
605k
        return MAKE_TOKEN(NAME);
325
606k
    }
326
327
1.30M
    if (c == '\r') {
328
0
        c = tok_nextc(tok);
329
0
    }
330
331
1.30M
    if (c == '\n') {
332
251k
        int type = _PyLexer_Newline(tok, token, blankline);
333
251k
        if (type == 0) {
334
121k
            goto nextline;
335
121k
        }
336
129k
        return type;
337
251k
    }
338
339
    /* Period or number starting with period? */
340
1.05M
    if (c == '.') {
341
41.1k
        c = tok_nextc(tok);
342
41.1k
        if (Py_ISDIGIT(c)) {
343
4.38k
            return _PyLexer_scan_number(tok, token, c, 1);
344
36.7k
        } else if (c == '.') {
345
5.01k
            c = tok_nextc(tok);
346
5.01k
            if (c == '.') {
347
3.24k
                p_start = tok->start;
348
3.24k
                p_end = tok->cur;
349
3.24k
                return MAKE_TOKEN(ELLIPSIS);
350
3.24k
            }
351
1.77k
            else {
352
1.77k
                tok_backup(tok, c);
353
1.77k
            }
354
1.77k
            tok_backup(tok, '.');
355
1.77k
        }
356
31.7k
        else {
357
31.7k
            tok_backup(tok, c);
358
31.7k
        }
359
33.5k
        p_start = tok->start;
360
33.5k
        p_end = tok->cur;
361
33.5k
        return MAKE_TOKEN(DOT);
362
41.1k
    }
363
364
365
    /* Number */
366
1.01M
    if (Py_ISDIGIT(c)) {
367
101k
        return _PyLexer_scan_number(tok, token, c, 0);
368
101k
    }
369
370
    /* String */
371
914k
    if (c == '\'' || c == '"') {
372
33.6k
        return _PyLexer_scan_string(tok, token, c);
373
33.6k
    }
374
375
    /* Line continuation */
376
880k
    if (c == '\\') {
377
337
        if ((c = _PyLexer_ContinueLine(tok)) == -1) {
378
74
            return MAKE_TOKEN(ERRORTOKEN);
379
74
        }
380
263
        goto again; /* Read next line */
381
337
    }
382
383
    /* Punctuation character */
384
880k
    int is_punctuation = (c == ':' || c == '}' || c == '!');
385
880k
    if (is_punctuation && current != NULL) {
386
35.3k
        int type = _PyLexer_ftstring_punctuation(tok, current, token, c);
387
35.3k
        if (type < 0) {
388
0
            return MAKE_TOKEN(ERRORTOKEN);
389
0
        }
390
35.3k
        if (type != 0) {
391
5.39k
            p_start = tok->start;
392
5.39k
            p_end = tok->cur;
393
5.39k
            return MAKE_TOKEN(type);
394
5.39k
        }
395
35.3k
    }
396
397
    /* Check for two-character token */
398
875k
    {
399
875k
        int c2 = tok_nextc(tok);
400
875k
        int current_token = _PyToken_TwoChars(c, c2, tok->barry_as_bdfl);
401
875k
        if (current_token != OP) {
402
27.8k
            int c3 = tok_nextc(tok);
403
27.8k
            int current_token3 = _PyToken_ThreeChars(c, c2, c3);
404
27.8k
            if (current_token3 != OP) {
405
1.23k
                current_token = current_token3;
406
1.23k
            }
407
26.6k
            else {
408
26.6k
                tok_backup(tok, c3);
409
26.6k
            }
410
27.8k
            p_start = tok->start;
411
27.8k
            p_end = tok->cur;
412
27.8k
            return MAKE_TOKEN(current_token);
413
27.8k
        }
414
847k
        tok_backup(tok, c2);
415
847k
    }
416
417
    /* Keep track of parentheses nesting level */
418
0
    switch (c) {
419
73.9k
    case '(':
420
110k
    case '[':
421
165k
    case '{':
422
165k
        if (tok->level >= MAXLEVEL) {
423
7
            return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok, "too many nested parentheses"));
424
7
        }
425
165k
        tok->parenstack[tok->level] = c;
426
165k
        tok->parenlinenostack[tok->level] = tok->lineno;
427
165k
        tok->parencolstack[tok->level] = (int)(tok->start - tok->line_start);
428
165k
        tok->level++;
429
165k
        break;
430
44.2k
    case ')':
431
50.3k
    case ']':
432
81.9k
    case '}':
433
81.9k
        if (current != NULL &&
434
27.6k
                _PyLexer_FTStringBracketDepth(tok, current) == 0) {
435
0
            if (c == '}') {
436
0
                return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok,
437
0
                    "%c-string: single '}' is not allowed",
438
0
                    _PyLexer_StringPrefix(current->kind)));
439
0
            }
440
0
            return MAKE_TOKEN(_PyTokenizer_syntaxerror(
441
0
                tok, "%c-string: unmatched '%c'",
442
0
                _PyLexer_StringPrefix(current->kind), c));
443
0
        }
444
81.9k
        if (!tok->tok_extra_tokens && !tok->level) {
445
222
            return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok, "unmatched '%c'", c));
446
222
        }
447
81.7k
        if (tok->level > 0) {
448
81.7k
            tok->level--;
449
81.7k
            int opening = tok->parenstack[tok->level];
450
81.7k
            if (!((opening == '(' && c == ')') ||
451
37.6k
                  (opening == '[' && c == ']') ||
452
31.5k
                  (opening == '{' && c == '}'))) {
453
                /* Do not match a closer against the brace that opened the
454
                 * current replacement field.  The f-string state relies on
455
                 * that brace, so this is checked even with extra tokens. */
456
59
                if (current != NULL && opening == '{') {
457
7
                    int bracket_depth =
458
7
                        _PyLexer_FTStringBracketDepth(tok, current);
459
7
                    if (bracket_depth == current->replacement_depth - 1) {
460
5
                        return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok,
461
5
                            "%c-string: unmatched '%c'",
462
5
                            _PyLexer_StringPrefix(current->kind), c));
463
5
                    }
464
7
                }
465
54
                if (tok->tok_extra_tokens) {
466
                    /* Allow other mismatched brackets. */
467
0
                }
468
54
                else if (tok->parenlinenostack[tok->level] != tok->lineno) {
469
3
                    return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok,
470
3
                            "closing parenthesis '%c' does not match "
471
3
                            "opening parenthesis '%c' on line %d",
472
3
                            c, opening, tok->parenlinenostack[tok->level]));
473
3
                }
474
51
                else {
475
51
                    return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok,
476
51
                            "closing parenthesis '%c' does not match "
477
51
                            "opening parenthesis '%c'",
478
51
                            c, opening));
479
51
                }
480
54
            }
481
81.7k
        }
482
81.6k
        if (current != NULL &&
483
27.6k
                _PyLexer_close_ftstring_expr(tok, current, c) < 0) {
484
0
            return MAKE_TOKEN(ERRORTOKEN);
485
0
        }
486
81.6k
        break;
487
600k
    default:
488
600k
        break;
489
847k
    }
490
491
847k
    if (!Py_UNICODE_ISPRINTABLE(c)) {
492
402
        return MAKE_TOKEN(_PyTokenizer_syntaxerror(tok, "invalid non-printable character U+%04X", c));
493
402
    }
494
495
846k
    if (c == '=' && current != NULL) {
496
9.58k
        _PyLexer_mark_ftstring_debug(tok, current);
497
9.58k
    }
498
499
    /* Punctuation character */
500
846k
    p_start = tok->start;
501
846k
    p_end = tok->cur;
502
846k
    return MAKE_TOKEN(_PyToken_OneChar(c));
503
847k
}
504
505
506
void
507
_PyTokenizer_Get(struct tok_state *tok, struct token *token)
508
1.94M
{
509
1.94M
    _PyToken_Free(token);
510
1.94M
    ftstring_state *current = _PyLexer_CurrentFTString(tok);
511
1.94M
    int result;
512
1.94M
    if (current == NULL) {
513
1.74M
        result = _PyLexer_get_normal(tok, NULL, token);
514
1.74M
    }
515
203k
    else {
516
203k
        switch (current->mode) {
517
137k
        case FTSTRING_MODE_EXPRESSION:
518
137k
            result = _PyLexer_get_normal(tok, current, token);
519
137k
            break;
520
60.3k
        case FTSTRING_MODE_MIDDLE:
521
65.7k
        case FTSTRING_MODE_FORMAT_SPEC:
522
65.7k
            result = _PyLexer_get_ftstring(tok, current, token);
523
65.7k
            break;
524
0
        default:
525
0
            Py_UNREACHABLE();
526
203k
        }
527
203k
    }
528
1.94M
    if (tok_failed(tok) && tok->done != E_INCOMPLETE) {
529
2.65k
        result = ERRORTOKEN;
530
2.65k
    }
531
1.94M
    token->type = result;
532
1.94M
}