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 PyErr_NoMemory();
197 return NULL;
198 }
199 memcpy(result, s, len);
200 result[len] = '\0';
201 return result;
202 }
203
204 PyObject *
205 _PyTokenizer_translate_into_utf8(const char* str, const char* enc) {
206 PyObject *utf8;
207 PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
208 if (buf == NULL)
209 return NULL;
210 utf8 = PyUnicode_AsUTF8String(buf);
211 Py_DECREF(buf);
212 return utf8;
213 }
214
215 char *
216 _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf,
217 struct tok_state *tok) {
218 int skip_next_lf = 0;
219 size_t needed_length = strlen(s) + 2, final_length;
220 char *buf, *current;
221 char c = '\0';
222 buf = PyMem_Malloc(needed_length);
223 if (buf == NULL) {
224 tok->done = E_NOMEM;
225 PyErr_NoMemory();
226 return NULL;
227 }
228 for (current = buf; *s; s++, current++) {
229 c = *s;
230 if (skip_next_lf) {
231 skip_next_lf = 0;
232 if (c == '\n') {
233 c = *++s;
234 if (!c)
235 break;
236 }
237 }
238 if (!preserve_crlf && c == '\r') {
239 skip_next_lf = 1;
240 c = '\n';
241 }
242 *current = c;
243 }
244 /* If this is exec input, add a newline to the end of the string if
245 there isn't one already. */
246 if (exec_input && c != '\n' && c != '\0') {
247 *current = '\n';
248 current++;
249 }
250 *current = '\0';
251 final_length = current - buf + 1;
252 if (final_length < needed_length && final_length) {
253 /* should never fail */
254 char* result = PyMem_Realloc(buf, final_length);
255 if (result == NULL) {
256 PyMem_Free(buf);
257 }
258 buf = result;
259 }
260 return buf;
261 }
262
263 /* ############## ENCODING STUFF ############## */
264
265
266 /* See whether the file starts with a BOM. If it does,
267 invoke the set_readline function with the new encoding.
268 Return 1 on success, 0 on failure. */
269 int
270 _PyTokenizer_check_bom(int get_char(struct tok_state *),
271 void unget_char(int, struct tok_state *),
272 int set_readline(struct tok_state *, const char *),
273 struct tok_state *tok)
274 {
275 int ch1, ch2, ch3;
276 ch1 = get_char(tok);
277 tok->decoding_state = STATE_SEEK_CODING;
278 if (ch1 == EOF) {
279 return 1;
280 } else if (ch1 == 0xEF) {
281 ch2 = get_char(tok);
282 if (ch2 != 0xBB) {
283 unget_char(ch2, tok);
284 unget_char(ch1, tok);
285 return 1;
286 }
287 ch3 = get_char(tok);
288 if (ch3 != 0xBF) {
289 unget_char(ch3, tok);
290 unget_char(ch2, tok);
291 unget_char(ch1, tok);
292 return 1;
293 }
294 } else {
295 unget_char(ch1, tok);
296 return 1;
297 }
298 if (tok->encoding != NULL)
299 PyMem_Free(tok->encoding);
300 tok->encoding = _PyTokenizer_new_string("utf-8", 5, tok);
301 if (!tok->encoding)
302 return 0;
303 /* No need to set_readline: input is already utf-8 */
304 return 1;
305 }
306
307 static const char *
308 get_normal_name(const char *s) /* for utf-8 and latin-1 */
309 {
310 char buf[13];
311 int i;
312 for (i = 0; i < 12; i++) {
313 int c = s[i];
314 if (c == '\0')
315 break;
316 else if (c == '_')
317 buf[i] = '-';
318 else
319 buf[i] = Py_TOLOWER(c);
320 }
321 buf[i] = '\0';
322 if (strcmp(buf, "utf-8") == 0 ||
323 strncmp(buf, "utf-8-", 6) == 0)
324 return "utf-8";
325 else if (strcmp(buf, "latin-1") == 0 ||
326 strcmp(buf, "iso-8859-1") == 0 ||
327 strcmp(buf, "iso-latin-1") == 0 ||
328 strncmp(buf, "latin-1-", 8) == 0 ||
329 strncmp(buf, "iso-8859-1-", 11) == 0 ||
330 strncmp(buf, "iso-latin-1-", 12) == 0)
331 return "iso-8859-1";
332 else
333 return s;
334 }
335
336 /* Return the coding spec in S, or NULL if none is found. */
337 static int
338 get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok)
339 {
340 Py_ssize_t i;
341 *spec = NULL;
342 /* Coding spec must be in a comment, and that comment must be
343 * the only statement on the source code line. */
344 for (i = 0; i < size - 6; i++) {
345 if (s[i] == '#')
346 break;
347 if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
348 return 1;
349 }
350 for (; i < size - 6; i++) { /* XXX inefficient search */
351 const char* t = s + i;
352 if (memcmp(t, "coding", 6) == 0) {
353 const char* begin = NULL;
354 t += 6;
355 if (t[0] != ':' && t[0] != '=')
356 continue;
357 do {
358 t++;
359 } while (t[0] == ' ' || t[0] == '\t');
360
361 begin = t;
362 while (Py_ISALNUM(t[0]) ||
363 t[0] == '-' || t[0] == '_' || t[0] == '.')
364 t++;
365
366 if (begin < t) {
367 char* r = _PyTokenizer_new_string(begin, t - begin, tok);
368 const char* q;
369 if (!r)
370 return 0;
371 q = get_normal_name(r);
372 if (r != q) {
373 PyMem_Free(r);
374 r = _PyTokenizer_new_string(q, strlen(q), tok);
375 if (!r)
376 return 0;
377 }
378 *spec = r;
379 break;
380 }
381 }
382 }
383 return 1;
384 }
385
386 /* Check whether the line contains a coding spec. If it does,
387 invoke the set_readline function for the new encoding.
388 This function receives the tok_state and the new encoding.
389 Return 1 on success, 0 on failure. */
390 int
391 _PyTokenizer_check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
392 int set_readline(struct tok_state *, const char *))
393 {
394 char *cs;
395 if (tok->cont_line) {
396 /* It's a continuation line, so it can't be a coding spec. */
397 tok->decoding_state = STATE_NORMAL;
398 return 1;
399 }
400 if (!get_coding_spec(line, &cs, size, tok)) {
401 return 0;
402 }
403 if (!cs) {
404 Py_ssize_t i;
405 for (i = 0; i < size; i++) {
406 if (line[i] == '#' || line[i] == '\n' || line[i] == '\r')
407 break;
408 if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') {
409 /* Stop checking coding spec after a line containing
410 * anything except a comment. */
411 tok->decoding_state = STATE_NORMAL;
412 break;
413 }
414 }
415 return 1;
416 }
417 tok->decoding_state = STATE_NORMAL;
418 if (tok->encoding == NULL) {
419 assert(tok->decoding_readline == NULL);
420 if (strcmp(cs, "utf-8") != 0 && !set_readline(tok, cs)) {
421 _PyTokenizer_error_ret(tok);
422 PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs);
423 PyMem_Free(cs);
424 return 0;
425 }
426 tok->encoding = cs;
427 } else { /* then, compare cs with BOM */
428 if (strcmp(tok->encoding, cs) != 0) {
429 tok->line_start = line;
430 tok->cur = (char *)line;
431 assert(size <= INT_MAX);
432 _PyTokenizer_syntaxerror_known_range(tok, 0, (int)size,
433 "encoding problem: %s with BOM", cs);
434 PyMem_Free(cs);
435 _PyTokenizer_error_ret(tok);
436 return 0;
437 }
438 PyMem_Free(cs);
439 }
440 return 1;
441 }
442
443 /* Check whether the characters at s start a valid
444 UTF-8 sequence. Return the number of characters forming
445 the sequence if yes, 0 if not. The special cases match
446 those in stringlib/codecs.h:utf8_decode.
447 */
448 static int
449 valid_utf8(const unsigned char* s)
450 {
451 int expected = 0;
452 int length;
453 if (*s < 0x80) {
454 /* single-byte code */
455 return 1;
456 }
457 else if (*s < 0xE0) {
458 /* \xC2\x80-\xDF\xBF -- 0080-07FF */
459 if (*s < 0xC2) {
460 /* invalid sequence
461 \x80-\xBF -- continuation byte
462 \xC0-\xC1 -- fake 0000-007F */
463 return 0;
464 }
465 expected = 1;
466 }
467 else if (*s < 0xF0) {
468 /* \xE0\xA0\x80-\xEF\xBF\xBF -- 0800-FFFF */
469 if (*s == 0xE0 && *(s + 1) < 0xA0) {
470 /* invalid sequence
471 \xE0\x80\x80-\xE0\x9F\xBF -- fake 0000-0800 */
472 return 0;
473 }
474 else if (*s == 0xED && *(s + 1) >= 0xA0) {
475 /* Decoding UTF-8 sequences in range \xED\xA0\x80-\xED\xBF\xBF
476 will result in surrogates in range D800-DFFF. Surrogates are
477 not valid UTF-8 so they are rejected.
478 See https://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
479 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
480 return 0;
481 }
482 expected = 2;
483 }
484 else if (*s < 0xF5) {
485 /* \xF0\x90\x80\x80-\xF4\x8F\xBF\xBF -- 10000-10FFFF */
486 if (*(s + 1) < 0x90 ? *s == 0xF0 : *s == 0xF4) {
487 /* invalid sequence -- one of:
488 \xF0\x80\x80\x80-\xF0\x8F\xBF\xBF -- fake 0000-FFFF
489 \xF4\x90\x80\x80- -- 110000- overflow */
490 return 0;
491 }
492 expected = 3;
493 }
494 else {
495 /* invalid start byte */
496 return 0;
497 }
498 length = expected + 1;
499 for (int i = 1; i <= expected; i++) {
500 if (s[i] < 0x80 || s[i] >= 0xC0) {
501 return 0;
502 }
503 }
504 return length;
505 }
506
507 int
508 _PyTokenizer_ensure_utf8(const char *line, struct tok_state *tok, int lineno)
509 {
510 const char *badchar = NULL;
511 const char *c;
512 int length;
513 int col_offset = 0;
514 const char *line_start = line;
515 for (c = line; *c; c += length) {
516 if (!(length = valid_utf8((const unsigned char *)c))) {
517 badchar = c;
518 break;
519 }
520 col_offset++;
521 if (*c == '\n') {
522 lineno++;
523 col_offset = 0;
524 line_start = c + 1;
525 }
526 }
527 if (badchar) {
528 tok->lineno = lineno;
529 tok->line_start = line_start;
530 tok->cur = (char *)badchar;
531 _PyTokenizer_syntaxerror_known_range(tok,
532 col_offset + 1, col_offset + 1,
533 "Non-UTF-8 code starting with '\\x%.2x'"
534 "%s%V on line %i, "
535 "but no encoding declared; "
536 "see https://peps.python.org/pep-0263/ for details",
537 (unsigned char)*badchar,
538 tok->filename ? " in file " : "", tok->filename, "",
539 lineno);
540 return 0;
541 }
542 return 1;
543 }
544
545
546 /* ############## DEBUGGING STUFF ############## */
547
548 #ifdef Py_DEBUG
549 void
550 _PyTokenizer_print_escape(FILE *f, const char *s, Py_ssize_t size)
551 {
552 if (s == NULL) {
553 fputs("NULL", f);
554 return;
555 }
556 putc('"', f);
557 while (size-- > 0) {
558 unsigned char c = *s++;
559 switch (c) {
560 case '\n': fputs("\\n", f); break;
561 case '\r': fputs("\\r", f); break;
562 case '\t': fputs("\\t", f); break;
563 case '\f': fputs("\\f", f); break;
564 case '\'': fputs("\\'", f); break;
565 case '"': fputs("\\\"", f); break;
566 default:
567 if (0x20 <= c && c <= 0x7f)
568 putc(c, f);
569 else
570 fprintf(f, "\\x%02x", c);
571 }
572 }
573 putc('"', f);
574 }
575
576 void
577 _PyTokenizer_tok_dump(int type, char *start, char *end)
578 {
579 fprintf(stderr, "%s", _PyParser_TokenNames[type]);
580 if (type == NAME || type == NUMBER || type == STRING || type == OP)
581 fprintf(stderr, "(%.*s)", (int)(end - start), start);
582 }
583 #endif