Coverage Report

Created: 2025-07-11 06:24

/src/cpython/Parser/string_parser.c
Line
Count
Source (jump to first uncovered line)
1
#include <Python.h>
2
#include "pycore_bytesobject.h"   // _PyBytes_DecodeEscape()
3
#include "pycore_unicodeobject.h" // _PyUnicode_DecodeUnicodeEscapeInternal()
4
5
#include "lexer/state.h"
6
#include "pegen.h"
7
#include "string_parser.h"
8
9
#include <stdbool.h>
10
11
//// STRING HANDLING FUNCTIONS ////
12
13
static int
14
warn_invalid_escape_sequence(Parser *p, const char* buffer, const char *first_invalid_escape, Token *t)
15
4.65k
{
16
4.65k
    if (p->call_invalid_rules) {
17
        // Do not report warnings if we are in the second pass of the parser
18
        // to avoid showing the warning twice.
19
1.32k
        return 0;
20
1.32k
    }
21
3.33k
    unsigned char c = (unsigned char)*first_invalid_escape;
22
3.33k
    if ((t->type == FSTRING_MIDDLE || t->type == FSTRING_END || t->type == TSTRING_MIDDLE || t->type == TSTRING_END)
23
3.33k
            && (c == '{' || c == '}')) {
24
        // in this case the tokenizer has already emitted a warning,
25
        // see Parser/tokenizer/helpers.c:warn_invalid_escape_sequence
26
680
        return 0;
27
680
    }
28
29
2.65k
    int octal = ('4' <= c && c <= '7');
30
2.65k
    PyObject *msg =
31
2.65k
        octal
32
2.65k
        ? PyUnicode_FromFormat(
33
745
              "\"\\%.3s\" is an invalid octal escape sequence. "
34
745
              "Such sequences will not work in the future. "
35
745
              "Did you mean \"\\\\%.3s\"? A raw string is also an option.",
36
745
              first_invalid_escape, first_invalid_escape)
37
2.65k
        : PyUnicode_FromFormat(
38
1.91k
              "\"\\%c\" is an invalid escape sequence. "
39
1.91k
              "Such sequences will not work in the future. "
40
1.91k
              "Did you mean \"\\\\%c\"? A raw string is also an option.",
41
1.91k
              c, c);
42
2.65k
    if (msg == NULL) {
43
0
        return -1;
44
0
    }
45
2.65k
    PyObject *category;
46
2.65k
    if (p->feature_version >= 12) {
47
2.65k
        category = PyExc_SyntaxWarning;
48
2.65k
    }
49
0
    else {
50
0
        category = PyExc_DeprecationWarning;
51
0
    }
52
53
    // Calculate the lineno and the col_offset of the invalid escape sequence
54
2.65k
    const char *start = buffer;
55
2.65k
    const char *end = first_invalid_escape;
56
2.65k
    int lineno = t->lineno;
57
2.65k
    int col_offset = t->col_offset;
58
28.2k
    while (start < end) {
59
25.5k
        if (*start == '\n') {
60
905
            lineno++;
61
905
            col_offset = 0;
62
905
        }
63
24.6k
        else {
64
24.6k
            col_offset++;
65
24.6k
        }
66
25.5k
        start++;
67
25.5k
    }
68
69
    // Count the number of quotes in the token
70
2.65k
    char first_quote = 0;
71
2.65k
    if (lineno == t->lineno) {
72
2.44k
        int quote_count = 0;
73
2.44k
        char* tok = PyBytes_AsString(t->bytes);
74
4.66k
        for (int i = 0; i < PyBytes_Size(t->bytes); i++) {
75
3.82k
            if (tok[i] == '\'' || tok[i] == '\"') {
76
2.21k
                if (quote_count == 0) {
77
1.85k
                    first_quote = tok[i];
78
1.85k
                }
79
2.21k
                if (tok[i] == first_quote) {
80
1.94k
                    quote_count++;
81
1.94k
                }
82
2.21k
            } else {
83
1.60k
                break;
84
1.60k
            }
85
3.82k
        }
86
87
2.44k
        col_offset += quote_count;
88
2.44k
    }
89
90
2.65k
    if (PyErr_WarnExplicitObject(category, msg, p->tok->filename,
91
2.65k
                                 lineno, NULL, NULL) < 0) {
92
0
        if (PyErr_ExceptionMatches(category)) {
93
            /* Replace the Syntax/DeprecationWarning exception with a SyntaxError
94
               to get a more accurate error report */
95
0
            PyErr_Clear();
96
97
            /* This is needed, in order for the SyntaxError to point to the token t,
98
               since _PyPegen_raise_error uses p->tokens[p->fill - 1] for the
99
               error location, if p->known_err_token is not set. */
100
0
            p->known_err_token = t;
101
0
            if (octal) {
102
0
                RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, lineno, col_offset-1, lineno, col_offset+1,
103
0
                    "\"\\%.3s\" is an invalid octal escape sequence. "
104
0
                    "Did you mean \"\\\\%.3s\"? A raw string is also an option.",
105
0
                    first_invalid_escape, first_invalid_escape);
106
0
            }
107
0
            else {
108
0
                RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, lineno, col_offset-1, lineno, col_offset+1,
109
0
                    "\"\\%c\" is an invalid escape sequence. "
110
0
                    "Did you mean \"\\\\%c\"? A raw string is also an option.",
111
0
                    c, c);
112
0
            }
113
0
        }
114
0
        Py_DECREF(msg);
115
0
        return -1;
116
0
    }
117
2.65k
    Py_DECREF(msg);
118
2.65k
    return 0;
119
2.65k
}
120
121
static PyObject *
122
decode_utf8(const char **sPtr, const char *end)
123
6.50k
{
124
6.50k
    const char *s;
125
6.50k
    const char *t;
126
6.50k
    t = s = *sPtr;
127
63.6k
    while (s < end && (*s & 0x80)) {
128
57.1k
        s++;
129
57.1k
    }
130
6.50k
    *sPtr = s;
131
6.50k
    return PyUnicode_DecodeUTF8(t, s - t, NULL);
132
6.50k
}
133
134
static PyObject *
135
decode_unicode_with_escapes(Parser *parser, const char *s, size_t len, Token *t)
136
31.7k
{
137
31.7k
    PyObject *v;
138
31.7k
    PyObject *u;
139
31.7k
    char *buf;
140
31.7k
    char *p;
141
31.7k
    const char *end;
142
143
    /* check for integer overflow */
144
31.7k
    if (len > (size_t)PY_SSIZE_T_MAX / 6) {
145
0
        return NULL;
146
0
    }
147
    /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
148
       "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
149
31.7k
    u = PyBytes_FromStringAndSize((char *)NULL, (Py_ssize_t)len * 6);
150
31.7k
    if (u == NULL) {
151
0
        return NULL;
152
0
    }
153
31.7k
    p = buf = PyBytes_AsString(u);
154
31.7k
    if (p == NULL) {
155
0
        return NULL;
156
0
    }
157
31.7k
    end = s + len;
158
272k
    while (s < end) {
159
241k
        if (*s == '\\') {
160
40.7k
            *p++ = *s++;
161
40.7k
            if (s >= end || *s & 0x80) {
162
1.46k
                strcpy(p, "u005c");
163
1.46k
                p += 5;
164
1.46k
                if (s >= end) {
165
312
                    break;
166
312
                }
167
1.46k
            }
168
40.7k
        }
169
240k
        if (*s & 0x80) {
170
6.50k
            PyObject *w;
171
6.50k
            int kind;
172
6.50k
            const void *data;
173
6.50k
            Py_ssize_t w_len;
174
6.50k
            Py_ssize_t i;
175
6.50k
            w = decode_utf8(&s, end);
176
6.50k
            if (w == NULL) {
177
33
                Py_DECREF(u);
178
33
                return NULL;
179
33
            }
180
6.47k
            kind = PyUnicode_KIND(w);
181
6.47k
            data = PyUnicode_DATA(w);
182
6.47k
            w_len = PyUnicode_GET_LENGTH(w);
183
27.6k
            for (i = 0; i < w_len; i++) {
184
21.1k
                Py_UCS4 chr = PyUnicode_READ(kind, data, i);
185
21.1k
                sprintf(p, "\\U%08x", chr);
186
21.1k
                p += 10;
187
21.1k
            }
188
            /* Should be impossible to overflow */
189
6.47k
            assert(p - buf <= PyBytes_GET_SIZE(u));
190
6.47k
            Py_DECREF(w);
191
6.47k
        }
192
234k
        else {
193
234k
            *p++ = *s++;
194
234k
        }
195
240k
    }
196
31.6k
    len = (size_t)(p - buf);
197
31.6k
    s = buf;
198
199
31.6k
    int first_invalid_escape_char;
200
31.6k
    const char *first_invalid_escape_ptr;
201
31.6k
    v = _PyUnicode_DecodeUnicodeEscapeInternal2(s, (Py_ssize_t)len, NULL, NULL,
202
31.6k
                                                &first_invalid_escape_char,
203
31.6k
                                                &first_invalid_escape_ptr);
204
205
    // HACK: later we can simply pass the line no, since we don't preserve the tokens
206
    // when we are decoding the string but we preserve the line numbers.
207
31.6k
    if (v != NULL && first_invalid_escape_ptr != NULL && t != NULL) {
208
4.00k
        if (warn_invalid_escape_sequence(parser, s, first_invalid_escape_ptr, t) < 0) {
209
            /* We have not decref u before because first_invalid_escape_ptr
210
               points inside u. */
211
0
            Py_XDECREF(u);
212
0
            Py_DECREF(v);
213
0
            return NULL;
214
0
        }
215
4.00k
    }
216
31.6k
    Py_XDECREF(u);
217
31.6k
    return v;
218
31.6k
}
219
220
static PyObject *
221
decode_bytes_with_escapes(Parser *p, const char *s, Py_ssize_t len, Token *t)
222
2.73k
{
223
2.73k
    int first_invalid_escape_char;
224
2.73k
    const char *first_invalid_escape_ptr;
225
2.73k
    PyObject *result = _PyBytes_DecodeEscape2(s, len, NULL,
226
2.73k
                                              &first_invalid_escape_char,
227
2.73k
                                              &first_invalid_escape_ptr);
228
2.73k
    if (result == NULL) {
229
5
        return NULL;
230
5
    }
231
232
2.72k
    if (first_invalid_escape_ptr != NULL) {
233
650
        if (warn_invalid_escape_sequence(p, s, first_invalid_escape_ptr, t) < 0) {
234
0
            Py_DECREF(result);
235
0
            return NULL;
236
0
        }
237
650
    }
238
2.72k
    return result;
239
2.72k
}
240
241
PyObject *
242
_PyPegen_decode_string(Parser *p, int raw, const char *s, size_t len, Token *t)
243
92.8k
{
244
92.8k
    if (raw) {
245
61.1k
        return PyUnicode_DecodeUTF8Stateful(s, (Py_ssize_t)len, NULL, NULL);
246
61.1k
    }
247
31.7k
    return decode_unicode_with_escapes(p, s, len, t);
248
92.8k
}
249
250
/* s must include the bracketing quote characters, and r, b &/or f prefixes
251
    (if any), and embedded escape sequences (if any). (f-strings are handled by the parser)
252
   _PyPegen_parse_string parses it, and returns the decoded Python string object. */
253
PyObject *
254
_PyPegen_parse_string(Parser *p, Token *t)
255
64.9k
{
256
64.9k
    const char *s = PyBytes_AsString(t->bytes);
257
64.9k
    if (s == NULL) {
258
0
        return NULL;
259
0
    }
260
261
64.9k
    size_t len;
262
64.9k
    int quote = Py_CHARMASK(*s);
263
64.9k
    int bytesmode = 0;
264
64.9k
    int rawmode = 0;
265
266
64.9k
    if (Py_ISALPHA(quote)) {
267
15.1k
        while (!bytesmode || !rawmode) {
268
14.7k
            if (quote == 'b' || quote == 'B') {
269
5.93k
                quote =(unsigned char)*++s;
270
5.93k
                bytesmode = 1;
271
5.93k
            }
272
8.80k
            else if (quote == 'u' || quote == 'U') {
273
629
                quote = (unsigned char)*++s;
274
629
            }
275
8.17k
            else if (quote == 'r' || quote == 'R') {
276
1.18k
                quote = (unsigned char)*++s;
277
1.18k
                rawmode = 1;
278
1.18k
            }
279
6.99k
            else {
280
6.99k
                break;
281
6.99k
            }
282
14.7k
        }
283
7.37k
    }
284
285
64.9k
    if (quote != '\'' && quote != '\"') {
286
1
        PyErr_BadInternalCall();
287
1
        return NULL;
288
1
    }
289
290
    /* Skip the leading quote char. */
291
64.9k
    s++;
292
64.9k
    len = strlen(s);
293
    // gh-120155: 's' contains at least the trailing quote,
294
    // so the code '--len' below is safe.
295
64.9k
    assert(len >= 1);
296
297
64.9k
    if (len > INT_MAX) {
298
0
        PyErr_SetString(PyExc_OverflowError, "string to parse is too long");
299
0
        return NULL;
300
0
    }
301
64.9k
    if (s[--len] != quote) {
302
        /* Last quote char must match the first. */
303
0
        PyErr_BadInternalCall();
304
0
        return NULL;
305
0
    }
306
64.9k
    if (len >= 4 && s[0] == quote && s[1] == quote) {
307
        /* A triple quoted string. We've already skipped one quote at
308
           the start and one at the end of the string. Now skip the
309
           two at the start. */
310
2.52k
        s += 2;
311
2.52k
        len -= 2;
312
        /* And check that the last two match. */
313
2.52k
        if (s[--len] != quote || s[--len] != quote) {
314
0
            PyErr_BadInternalCall();
315
0
            return NULL;
316
0
        }
317
2.52k
    }
318
319
    /* Avoid invoking escape decoding routines if possible. */
320
64.9k
    rawmode = rawmode || strchr(s, '\\') == NULL;
321
64.9k
    if (bytesmode) {
322
        /* Disallow non-ASCII characters. */
323
5.93k
        const char *ch;
324
73.9k
        for (ch = s; *ch; ch++) {
325
68.0k
            if (Py_CHARMASK(*ch) >= 0x80) {
326
8
                RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
327
8
                                   t,
328
8
                                   "bytes can only contain ASCII "
329
8
                                   "literal characters");
330
8
                return NULL;
331
8
            }
332
68.0k
        }
333
5.93k
        if (rawmode) {
334
3.19k
            return PyBytes_FromStringAndSize(s, (Py_ssize_t)len);
335
3.19k
        }
336
2.73k
        return decode_bytes_with_escapes(p, s, (Py_ssize_t)len, t);
337
5.93k
    }
338
58.9k
    return _PyPegen_decode_string(p, rawmode, s, len, t);
339
64.9k
}