Debian Codegraph @

Parser/tokenizer/helpers.c

raw
1 #include "Python.h"
2 #include "errcode.h"
3 #include "pycore_token.h"
4
5 #include "../lexer/state.h"
6
7
8 /* ############## ERRORS ############## */
9
10 static int
11 _syntaxerror_range(struct tok_state *tok, const char *format,
12 int col_offset, int end_col_offset,
13 va_list vargs)
14 {
15 // In release builds, we don't want to overwrite a previous error, but in debug builds we
16 // want to fail if we are not doing it so we can fix it.
17 assert(tok->done != E_ERROR);
18 if (tok->done == E_ERROR) {
19 return ERRORTOKEN;
20 }
21 PyObject *errmsg, *errtext, *args;
22 errmsg = PyUnicode_FromFormatV(format, vargs);
23 if (!errmsg) {
24 goto error;
25 }
26
27 errtext = PyUnicode_DecodeUTF8(tok->line_start, tok->cur - tok->line_start,
28 "replace");
29 if (!errtext) {
30 goto error;
31 }
32
33 if (col_offset == -1) {
34 col_offset = (int)PyUnicode_GET_LENGTH(errtext);
35 }
36 if (end_col_offset == -1) {
37 end_col_offset = col_offset;
38 }
39
40 Py_ssize_t line_len = strcspn(tok->line_start, "\n");
41 if (line_len != tok->cur - tok->line_start) {
42 Py_DECREF(errtext);
43 errtext = PyUnicode_DecodeUTF8(tok->line_start, line_len,
44 "replace");
45 }
46 if (!errtext) {
47 goto error;
48 }
49
50 args = Py_BuildValue("(O(OiiNii))", errmsg,
51 tok->filename ? tok->filename : Py_None,
52 tok->lineno, col_offset, errtext,
53 tok->lineno, end_col_offset);
54 if (args) {
55 PyErr_SetObject(PyExc_SyntaxError, args);
56 Py_DECREF(args);
57 }
58
59 error:
60 Py_XDECREF(errmsg);
61 tok->done = E_ERROR;
62 return ERRORTOKEN;
63 }
64
65 int
66 _PyTokenizer_syntaxerror(struct tok_state *tok, const char *format, ...)
67 {
68 // This errors are cleaned on startup. Todo: Fix it.
69 va_list vargs;
70 va_start(vargs, format);
71 int ret = _syntaxerror_range(tok, format, -1, -1, vargs);
72 va_end(vargs);
73 return ret;
74 }
75
76 int
77 _PyTokenizer_syntaxerror_known_range(struct tok_state *tok,
78 int col_offset, int end_col_offset,
79 const char *format, ...)
80 {
81 va_list vargs;
82 va_start(vargs, format);
83 int ret = _syntaxerror_range(tok, format, col_offset, end_col_offset, vargs);
84 va_end(vargs);
85 return ret;
86 }
87
88 int
89 _PyTokenizer_indenterror(struct tok_state *tok)
90 {
91 tok->done = E_TABSPACE;
92 tok->cur = tok->inp;
93 return ERRORTOKEN;
94 }
95
96 char *
97 _PyTokenizer_error_ret(struct tok_state *tok) /* XXX */
98 {
99 tok->decoding_erred = 1;
100 if ((tok->fp != NULL || tok->readline != NULL) && tok->buf != NULL) {/* see _PyTokenizer_Free */
101 PyMem_Free(tok->buf);
102 }
103 tok->buf = tok->cur = tok->inp = NULL;
104 tok->start = NULL;
105 tok->end = NULL;
106 tok->done = E_DECODE;
107 return NULL; /* as if it were EOF */
108 }
109
110 int
111 _PyTokenizer_warn_invalid_escape_sequence(struct tok_state *tok, int first_invalid_escape_char)
112 {
113 if (!tok->report_warnings) {
114 return 0;
115 }
116
117 PyObject *msg = PyUnicode_FromFormat(
118 "\"\\%c\" is an invalid escape sequence. "
119 "Such sequences will not work in the future. "
120 "Did you mean \"\\\\%c\"? A raw string is also an option.",
121 (char) first_invalid_escape_char,
122 (char) first_invalid_escape_char
123 );
124
125 if (msg == NULL) {
126 return -1;
127 }
128
129 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, tok->filename,
130 tok->lineno, NULL, NULL) < 0) {
131 Py_DECREF(msg);
132
133 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
134 /* Replace the SyntaxWarning exception with a SyntaxError
135 to get a more accurate error report */
136 PyErr_Clear();
137
138 return _PyTokenizer_syntaxerror(tok,
139 "\"\\%c\" is an invalid escape sequence. "
140 "Did you mean \"\\\\%c\"? A raw string is also an option.",
141 (char) first_invalid_escape_char,
142 (char) first_invalid_escape_char);
143 }
144
145 return -1;
146 }
147
148 Py_DECREF(msg);
149 return 0;
150 }
151
152 int
153 _PyTokenizer_parser_warn(struct tok_state *tok, PyObject *category, const char *format, ...)
154 {
155 if (!tok->report_warnings) {
156 return 0;
157 }
158
159 PyObject *errmsg;
160 va_list vargs;
161 va_start(vargs, format);
162 errmsg = PyUnicode_FromFormatV(format, vargs);
163 va_end(vargs);
164 if (!errmsg) {
165 goto error;
166 }
167
168 if (PyErr_WarnExplicitObject(category, errmsg, tok->filename,
169 tok->lineno, NULL, NULL) < 0) {
170 if (PyErr_ExceptionMatches(category)) {
171 /* Replace the DeprecationWarning exception with a SyntaxError
172 to get a more accurate error report */
173 PyErr_Clear();
174 _PyTokenizer_syntaxerror(tok, "%U", errmsg);
175 }
176 goto error;
177 }
178 Py_DECREF(errmsg);
179 return 0;
180
181 error:
182 Py_XDECREF(errmsg);
183 tok->done = E_ERROR;
184 return -1;
185 }
186
187
188 /* ############## STRING MANIPULATION ############## */
189
190 char *
191 _PyTokenizer_new_string(const char *s, Py_ssize_t len, struct tok_state *tok)
192 {
193 char* result = (char *)PyMem_Malloc(len + 1);
194 if (!result) {
195 tok->done = E_NOMEM;
196 return NULL;
197 }
198 memcpy(result, s, len);
199 result[len] = '\0';
200 return result;
201 }
202
203 PyObject *
204 _PyTokenizer_translate_into_utf8(const char* str, const char* enc) {
205 PyObject *utf8;
206 PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
207 if (buf == NULL)
208 return NULL;
209 utf8 = PyUnicode_AsUTF8String(buf);
210 Py_DECREF(buf);
211 return utf8;
212 }
213
214 char *
215 _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf,
216 struct tok_state *tok) {
217 int skip_next_lf = 0;
218 size_t needed_length = strlen(s) + 2, final_length;
219 char *buf, *current;
220 char c = '\0';
221 buf = PyMem_Malloc(needed_length);
222 if (buf == NULL) {
223 tok->done = E_NOMEM;
224 return NULL;
225 }
226 for (current = buf; *s; s++, current++) {
227 c = *s;
228 if (skip_next_lf) {
229 skip_next_lf = 0;
230 if (c == '\n') {
231 c = *++s;
232 if (!c)
233 break;
234 }
235 }
236 if (!preserve_crlf && c == '\r') {
237 skip_next_lf = 1;
238 c = '\n';
239 }
240 *current = c;
241 }
242 /* If this is exec input, add a newline to the end of the string if
243 there isn't one already. */
244 if (exec_input && c != '\n' && c != '\0') {
245 *current = '\n';
246 current++;
247 }
248 *current = '\0';
249 final_length = current - buf + 1;
250 if (final_length < needed_length && final_length) {
251 /* should never fail */
252 char* result = PyMem_Realloc(buf, final_length);
253 if (result == NULL) {
254 PyMem_Free(buf);
255 }
256 buf = result;
257 }
258 return buf;
259 }
260
261 /* ############## ENCODING STUFF ############## */
262
263
264 /* See whether the file starts with a BOM. If it does,
265 invoke the set_readline function with the new encoding.
266 Return 1 on success, 0 on failure. */
267 int
268 _PyTokenizer_check_bom(int get_char(struct tok_state *),
269 void unget_char(int, struct tok_state *),
270 int set_readline(struct tok_state *, const char *),
271 struct tok_state *tok)
272 {
273 int ch1, ch2, ch3;
274 ch1 = get_char(tok);
275 tok->decoding_state = STATE_SEEK_CODING;
276 if (ch1 == EOF) {
277 return 1;
278 } else if (ch1 == 0xEF) {
279 ch2 = get_char(tok);
280 if (ch2 != 0xBB) {
281 unget_char(ch2, tok);
282 unget_char(ch1, tok);
283 return 1;
284 }
285 ch3 = get_char(tok);
286 if (ch3 != 0xBF) {
287 unget_char(ch3, tok);
288 unget_char(ch2, tok);
289 unget_char(ch1, tok);
290 return 1;
291 }
292 } else {
293 unget_char(ch1, tok);
294 return 1;
295 }
296 if (tok->encoding != NULL)
297 PyMem_Free(tok->encoding);
298 tok->encoding = _PyTokenizer_new_string("utf-8", 5, tok);
299 if (!tok->encoding)
300 return 0;
301 /* No need to set_readline: input is already utf-8 */
302 return 1;
303 }
304
305 static const char *
306 get_normal_name(const char *s) /* for utf-8 and latin-1 */
307 {
308 char buf[13];
309 int i;
310 for (i = 0; i < 12; i++) {
311 int c = s[i];
312 if (c == '\0')
313 break;
314 else if (c == '_')
315 buf[i] = '-';
316 else
317 buf[i] = Py_TOLOWER(c);
318 }
319 buf[i] = '\0';
320 if (strcmp(buf, "utf-8") == 0 ||
321 strncmp(buf, "utf-8-", 6) == 0)
322 return "utf-8";
323 else if (strcmp(buf, "latin-1") == 0 ||
324 strcmp(buf, "iso-8859-1") == 0 ||
325 strcmp(buf, "iso-latin-1") == 0 ||
326 strncmp(buf, "latin-1-", 8) == 0 ||
327 strncmp(buf, "iso-8859-1-", 11) == 0 ||
328 strncmp(buf, "iso-latin-1-", 12) == 0)
329 return "iso-8859-1";
330 else
331 return s;
332 }
333
334 /* Return the coding spec in S, or NULL if none is found. */
335 static int
336 get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok)
337 {
338 Py_ssize_t i;
339 *spec = NULL;
340 /* Coding spec must be in a comment, and that comment must be
341 * the only statement on the source code line. */
342 for (i = 0; i < size - 6; i++) {
343 if (s[i] == '#')
344 break;
345 if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
346 return 1;
347 }
348 for (; i < size - 6; i++) { /* XXX inefficient search */
349 const char* t = s + i;
350 if (memcmp(t, "coding", 6) == 0) {
351 const char* begin = NULL;
352 t += 6;
353 if (t[0] != ':' && t[0] != '=')
354 continue;
355 do {
356 t++;
357 } while (t[0] == ' ' || t[0] == '\t');
358
359 begin = t;
360 while (Py_ISALNUM(t[0]) ||
361 t[0] == '-' || t[0] == '_' || t[0] == '.')
362 t++;
363
364 if (begin < t) {
365 char* r = _PyTokenizer_new_string(begin, t - begin, tok);
366 const char* q;
367 if (!r)
368 return 0;
369 q = get_normal_name(r);
370 if (r != q) {
371 PyMem_Free(r);
372 r = _PyTokenizer_new_string(q, strlen(q), tok);
373 if (!r)
374 return 0;
375 }
376 *spec = r;
377 break;
378 }
379 }
380 }
381 return 1;
382 }
383
384 /* Check whether the line contains a coding spec. If it does,
385 invoke the set_readline function for the new encoding.
386 This function receives the tok_state and the new encoding.
387 Return 1 on success, 0 on failure. */
388 int
389 _PyTokenizer_check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
390 int set_readline(struct tok_state *, const char *))
391 {
392 char *cs;
393 if (tok->cont_line) {
394 /* It's a continuation line, so it can't be a coding spec. */
395 tok->decoding_state = STATE_NORMAL;
396 return 1;
397 }
398 if (!get_coding_spec(line, &cs, size, tok)) {
399 return 0;
400 }
401 if (!cs) {
402 Py_ssize_t i;
403 for (i = 0; i < size; i++) {
404 if (line[i] == '#' || line[i] == '\n' || line[i] == '\r')
405 break;
406 if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') {
407 /* Stop checking coding spec after a line containing
408 * anything except a comment. */
409 tok->decoding_state = STATE_NORMAL;
410 break;
411 }
412 }
413 return 1;
414 }
415 tok->decoding_state = STATE_NORMAL;
416 if (tok->encoding == NULL) {
417 assert(tok->decoding_readline == NULL);
418 if (strcmp(cs, "utf-8") != 0 && !set_readline(tok, cs)) {
419 _PyTokenizer_error_ret(tok);
420 PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs);
421 PyMem_Free(cs);
422 return 0;
423 }
424 tok->encoding = cs;
425 } else { /* then, compare cs with BOM */
426 if (strcmp(tok->encoding, cs) != 0) {
427 tok->line_start = line;
428 tok->cur = (char *)line;
429 assert(size <= INT_MAX);
430 _PyTokenizer_syntaxerror_known_range(tok, 0, (int)size,
431 "encoding problem: %s with BOM", cs);
432 PyMem_Free(cs);
433 _PyTokenizer_error_ret(tok);
434 return 0;
435 }
436 PyMem_Free(cs);
437 }
438 return 1;
439 }
440
441 /* Check whether the characters at s start a valid
442 UTF-8 sequence. Return the number of characters forming
443 the sequence if yes, 0 if not. The special cases match
444 those in stringlib/codecs.h:utf8_decode.
445 */
446 static int
447 valid_utf8(const unsigned char* s)
448 {
449 int expected = 0;
450 int length;
451 if (*s < 0x80) {
452 /* single-byte code */
453 return 1;
454 }
455 else if (*s < 0xE0) {
456 /* \xC2\x80-\xDF\xBF -- 0080-07FF */
457 if (*s < 0xC2) {
458 /* invalid sequence
459 \x80-\xBF -- continuation byte
460 \xC0-\xC1 -- fake 0000-007F */
461 return 0;
462 }
463 expected = 1;
464 }
465 else if (*s < 0xF0) {
466 /* \xE0\xA0\x80-\xEF\xBF\xBF -- 0800-FFFF */
467 if (*s == 0xE0 && *(s + 1) < 0xA0) {
468 /* invalid sequence
469 \xE0\x80\x80-\xE0\x9F\xBF -- fake 0000-0800 */
470 return 0;
471 }
472 else if (*s == 0xED && *(s + 1) >= 0xA0) {
473 /* Decoding UTF-8 sequences in range \xED\xA0\x80-\xED\xBF\xBF
474 will result in surrogates in range D800-DFFF. Surrogates are
475 not valid UTF-8 so they are rejected.
476 See https://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
477 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
478 return 0;
479 }
480 expected = 2;
481 }
482 else if (*s < 0xF5) {
483 /* \xF0\x90\x80\x80-\xF4\x8F\xBF\xBF -- 10000-10FFFF */
484 if (*(s + 1) < 0x90 ? *s == 0xF0 : *s == 0xF4) {
485 /* invalid sequence -- one of:
486 \xF0\x80\x80\x80-\xF0\x8F\xBF\xBF -- fake 0000-FFFF
487 \xF4\x90\x80\x80- -- 110000- overflow */
488 return 0;
489 }
490 expected = 3;
491 }
492 else {
493 /* invalid start byte */
494 return 0;
495 }
496 length = expected + 1;
497 for (int i = 1; i <= expected; i++) {
498 if (s[i] < 0x80 || s[i] >= 0xC0) {
499 return 0;
500 }
501 }
502 return length;
503 }
504
505 int
506 _PyTokenizer_ensure_utf8(const char *line, struct tok_state *tok, int lineno)
507 {
508 const char *badchar = NULL;
509 const char *c;
510 int length;
511 int col_offset = 0;
512 const char *line_start = line;
513 for (c = line; *c; c += length) {
514 if (!(length = valid_utf8((const unsigned char *)c))) {
515 badchar = c;
516 break;
517 }
518 col_offset++;
519 if (*c == '\n') {
520 lineno++;
521 col_offset = 0;
522 line_start = c + 1;
523 }
524 }
525 if (badchar) {
526 tok->lineno = lineno;
527 tok->line_start = line_start;
528 tok->cur = (char *)badchar;
529 _PyTokenizer_syntaxerror_known_range(tok,
530 col_offset + 1, col_offset + 1,
531 "Non-UTF-8 code starting with '\\x%.2x'"
532 "%s%V on line %i, "
533 "but no encoding declared; "
534 "see https://peps.python.org/pep-0263/ for details",
535 (unsigned char)*badchar,
536 tok->filename ? " in file " : "", tok->filename, "",
537 lineno);
538 return 0;
539 }
540 return 1;
541 }
542
543
544 /* ############## DEBUGGING STUFF ############## */
545
546 #ifdef Py_DEBUG
547 void
548 _PyTokenizer_print_escape(FILE *f, const char *s, Py_ssize_t size)
549 {
550 if (s == NULL) {
551 fputs("NULL", f);
552 return;
553 }
554 putc('"', f);
555 while (size-- > 0) {
556 unsigned char c = *s++;
557 switch (c) {
558 case '\n': fputs("\\n", f); break;
559 case '\r': fputs("\\r", f); break;
560 case '\t': fputs("\\t", f); break;
561 case '\f': fputs("\\f", f); break;
562 case '\'': fputs("\\'", f); break;
563 case '"': fputs("\\\"", f); break;
564 default:
565 if (0x20 <= c && c <= 0x7f)
566 putc(c, f);
567 else
568 fprintf(f, "\\x%02x", c);
569 }
570 }
571 putc('"', f);
572 }
573
574 void
575 _PyTokenizer_tok_dump(int type, char *start, char *end)
576 {
577 fprintf(stderr, "%s", _PyParser_TokenNames[type]);
578 if (type == NAME || type == NUMBER || type == STRING || type == OP)
579 fprintf(stderr, "(%.*s)", (int)(end - start), start);
580 }
581 #endif