1
2 /* Tokenizer implementation */
3
4 #include "Python.h"
5 #include "pgenheaders.h"
6
7 #include <ctype.h>
8 #include <assert.h>
9
10 #include "tokenizer.h"
11 #include "errcode.h"
12
13 #ifndef PGEN
14 #include "unicodeobject.h"
15 #include "bytesobject.h"
16 #include "fileobject.h"
17 #include "codecs.h"
18 #include "abstract.h"
19 #endif /* PGEN */
20
21 /* Alternate tab spacing */
22 #define ALTTABSIZE 1
23
24 #define is_potential_identifier_start(c) (\
25 (c >= 'a' && c <= 'z')\
26 || (c >= 'A' && c <= 'Z')\
27 || c == '_'\
28 || (c >= 128))
29
30 #define is_potential_identifier_char(c) (\
31 (c >= 'a' && c <= 'z')\
32 || (c >= 'A' && c <= 'Z')\
33 || (c >= '0' && c <= '9')\
34 || c == '_'\
35 || (c >= 128))
36
37 extern char *PyOS_Readline(FILE *, FILE *, const char *);
38 /* Return malloc'ed string including trailing \n;
39 empty malloc'ed string for EOF;
40 NULL if interrupted */
41
42 /* Don't ever change this -- it would break the portability of Python code */
43 #define TABSIZE 8
44
45 /* Forward */
46 static struct tok_state *tok_new(void);
47 static int tok_nextc(struct tok_state *tok);
48 static void tok_backup(struct tok_state *tok, int c);
49
50
51 /* Token names */
52
53 const char *_PyParser_TokenNames[] = {
54 "ENDMARKER",
55 "NAME",
56 "NUMBER",
57 "STRING",
58 "NEWLINE",
59 "INDENT",
60 "DEDENT",
61 "LPAR",
62 "RPAR",
63 "LSQB",
64 "RSQB",
65 "COLON",
66 "COMMA",
67 "SEMI",
68 "PLUS",
69 "MINUS",
70 "STAR",
71 "SLASH",
72 "VBAR",
73 "AMPER",
74 "LESS",
75 "GREATER",
76 "EQUAL",
77 "DOT",
78 "PERCENT",
79 "LBRACE",
80 "RBRACE",
81 "EQEQUAL",
82 "NOTEQUAL",
83 "LESSEQUAL",
84 "GREATEREQUAL",
85 "TILDE",
86 "CIRCUMFLEX",
87 "LEFTSHIFT",
88 "RIGHTSHIFT",
89 "DOUBLESTAR",
90 "PLUSEQUAL",
91 "MINEQUAL",
92 "STAREQUAL",
93 "SLASHEQUAL",
94 "PERCENTEQUAL",
95 "AMPEREQUAL",
96 "VBAREQUAL",
97 "CIRCUMFLEXEQUAL",
98 "LEFTSHIFTEQUAL",
99 "RIGHTSHIFTEQUAL",
100 "DOUBLESTAREQUAL",
101 "DOUBLESLASH",
102 "DOUBLESLASHEQUAL",
103 "AT",
104 "ATEQUAL",
105 "RARROW",
106 "ELLIPSIS",
107 /* This table must match the #defines in token.h! */
108 "OP",
109 "<ERRORTOKEN>",
110 "COMMENT",
111 "NL",
112 "ENCODING",
113 "<N_TOKENS>"
114 };
115
116
117 /* Create and initialize a new tok_state structure */
118
119 static struct tok_state *
tok_new(void)120 tok_new(void)
121 {
122 struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(
123 sizeof(struct tok_state));
124 if (tok == NULL)
125 return NULL;
126 tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
127 tok->done = E_OK;
128 tok->fp = NULL;
129 tok->input = NULL;
130 tok->tabsize = TABSIZE;
131 tok->indent = 0;
132 tok->indstack[0] = 0;
133
134 tok->atbol = 1;
135 tok->pendin = 0;
136 tok->prompt = tok->nextprompt = NULL;
137 tok->lineno = 0;
138 tok->level = 0;
139 tok->altindstack[0] = 0;
140 tok->decoding_state = STATE_INIT;
141 tok->decoding_erred = 0;
142 tok->read_coding_spec = 0;
143 tok->enc = NULL;
144 tok->encoding = NULL;
145 tok->cont_line = 0;
146 #ifndef PGEN
147 tok->filename = NULL;
148 tok->decoding_readline = NULL;
149 tok->decoding_buffer = NULL;
150 #endif
151
152 return tok;
153 }
154
155 static char *
new_string(const char * s,Py_ssize_t len,struct tok_state * tok)156 new_string(const char *s, Py_ssize_t len, struct tok_state *tok)
157 {
158 char* result = (char *)PyMem_MALLOC(len + 1);
159 if (!result) {
160 tok->done = E_NOMEM;
161 return NULL;
162 }
163 memcpy(result, s, len);
164 result[len] = '\0';
165 return result;
166 }
167
168 #ifdef PGEN
169
170 static char *
decoding_fgets(char * s,int size,struct tok_state * tok)171 decoding_fgets(char *s, int size, struct tok_state *tok)
172 {
173 return fgets(s, size, tok->fp);
174 }
175
176 static int
decoding_feof(struct tok_state * tok)177 decoding_feof(struct tok_state *tok)
178 {
179 return feof(tok->fp);
180 }
181
182 static char *
decode_str(const char * str,int exec_input,struct tok_state * tok)183 decode_str(const char *str, int exec_input, struct tok_state *tok)
184 {
185 return new_string(str, strlen(str), tok);
186 }
187
188 #else /* PGEN */
189
190 static char *
error_ret(struct tok_state * tok)191 error_ret(struct tok_state *tok) /* XXX */
192 {
193 tok->decoding_erred = 1;
194 if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */
195 PyMem_FREE(tok->buf);
196 tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
197 tok->done = E_DECODE;
198 return NULL; /* as if it were EOF */
199 }
200
201
202 static const char *
get_normal_name(const char * s)203 get_normal_name(const char *s) /* for utf-8 and latin-1 */
204 {
205 char buf[13];
206 int i;
207 for (i = 0; i < 12; i++) {
208 int c = s[i];
209 if (c == '\0')
210 break;
211 else if (c == '_')
212 buf[i] = '-';
213 else
214 buf[i] = tolower(c);
215 }
216 buf[i] = '\0';
217 if (strcmp(buf, "utf-8") == 0 ||
218 strncmp(buf, "utf-8-", 6) == 0)
219 return "utf-8";
220 else if (strcmp(buf, "latin-1") == 0 ||
221 strcmp(buf, "iso-8859-1") == 0 ||
222 strcmp(buf, "iso-latin-1") == 0 ||
223 strncmp(buf, "latin-1-", 8) == 0 ||
224 strncmp(buf, "iso-8859-1-", 11) == 0 ||
225 strncmp(buf, "iso-latin-1-", 12) == 0)
226 return "iso-8859-1";
227 else
228 return s;
229 }
230
231 /* Return the coding spec in S, or NULL if none is found. */
232
233 static int
get_coding_spec(const char * s,char ** spec,Py_ssize_t size,struct tok_state * tok)234 get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok)
235 {
236 Py_ssize_t i;
237 *spec = NULL;
238 /* Coding spec must be in a comment, and that comment must be
239 * the only statement on the source code line. */
240 for (i = 0; i < size - 6; i++) {
241 if (s[i] == '#')
242 break;
243 if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
244 return 1;
245 }
246 for (; i < size - 6; i++) { /* XXX inefficient search */
247 const char* t = s + i;
248 if (strncmp(t, "coding", 6) == 0) {
249 const char* begin = NULL;
250 t += 6;
251 if (t[0] != ':' && t[0] != '=')
252 continue;
253 do {
254 t++;
255 } while (t[0] == '\x20' || t[0] == '\t');
256
257 begin = t;
258 while (Py_ISALNUM(t[0]) ||
259 t[0] == '-' || t[0] == '_' || t[0] == '.')
260 t++;
261
262 if (begin < t) {
263 char* r = new_string(begin, t - begin, tok);
264 const char* q;
265 if (!r)
266 return 0;
267 q = get_normal_name(r);
268 if (r != q) {
269 PyMem_FREE(r);
270 r = new_string(q, strlen(q), tok);
271 if (!r)
272 return 0;
273 }
274 *spec = r;
275 break;
276 }
277 }
278 }
279 return 1;
280 }
281
282 /* Check whether the line contains a coding spec. If it does,
283 invoke the set_readline function for the new encoding.
284 This function receives the tok_state and the new encoding.
285 Return 1 on success, 0 on failure. */
286
287 static int
check_coding_spec(const char * line,Py_ssize_t size,struct tok_state * tok,int set_readline (struct tok_state *,const char *))288 check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
289 int set_readline(struct tok_state *, const char *))
290 {
291 char *cs;
292 int r = 1;
293
294 if (tok->cont_line) {
295 /* It's a continuation line, so it can't be a coding spec. */
296 tok->read_coding_spec = 1;
297 return 1;
298 }
299 if (!get_coding_spec(line, &cs, size, tok))
300 return 0;
301 if (!cs) {
302 Py_ssize_t i;
303 for (i = 0; i < size; i++) {
304 if (line[i] == '#' || line[i] == '\n' || line[i] == '\r')
305 break;
306 if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') {
307 /* Stop checking coding spec after a line containing
308 * anything except a comment. */
309 tok->read_coding_spec = 1;
310 break;
311 }
312 }
313 return 1;
314 }
315 tok->read_coding_spec = 1;
316 if (tok->encoding == NULL) {
317 assert(tok->decoding_state == STATE_RAW);
318 if (strcmp(cs, "utf-8") == 0) {
319 tok->encoding = cs;
320 } else {
321 r = set_readline(tok, cs);
322 if (r) {
323 tok->encoding = cs;
324 tok->decoding_state = STATE_NORMAL;
325 }
326 else {
327 PyErr_Format(PyExc_SyntaxError,
328 "encoding problem: %s", cs);
329 PyMem_FREE(cs);
330 }
331 }
332 } else { /* then, compare cs with BOM */
333 r = (strcmp(tok->encoding, cs) == 0);
334 if (!r)
335 PyErr_Format(PyExc_SyntaxError,
336 "encoding problem: %s with BOM", cs);
337 PyMem_FREE(cs);
338 }
339 return r;
340 }
341
342 /* See whether the file starts with a BOM. If it does,
343 invoke the set_readline function with the new encoding.
344 Return 1 on success, 0 on failure. */
345
346 static int
check_bom(int get_char (struct tok_state *),void unget_char (int,struct tok_state *),int set_readline (struct tok_state *,const char *),struct tok_state * tok)347 check_bom(int get_char(struct tok_state *),
348 void unget_char(int, struct tok_state *),
349 int set_readline(struct tok_state *, const char *),
350 struct tok_state *tok)
351 {
352 int ch1, ch2, ch3;
353 ch1 = get_char(tok);
354 tok->decoding_state = STATE_RAW;
355 if (ch1 == EOF) {
356 return 1;
357 } else if (ch1 == 0xEF) {
358 ch2 = get_char(tok);
359 if (ch2 != 0xBB) {
360 unget_char(ch2, tok);
361 unget_char(ch1, tok);
362 return 1;
363 }
364 ch3 = get_char(tok);
365 if (ch3 != 0xBF) {
366 unget_char(ch3, tok);
367 unget_char(ch2, tok);
368 unget_char(ch1, tok);
369 return 1;
370 }
371 #if 0
372 /* Disable support for UTF-16 BOMs until a decision
373 is made whether this needs to be supported. */
374 } else if (ch1 == 0xFE) {
375 ch2 = get_char(tok);
376 if (ch2 != 0xFF) {
377 unget_char(ch2, tok);
378 unget_char(ch1, tok);
379 return 1;
380 }
381 if (!set_readline(tok, "utf-16-be"))
382 return 0;
383 tok->decoding_state = STATE_NORMAL;
384 } else if (ch1 == 0xFF) {
385 ch2 = get_char(tok);
386 if (ch2 != 0xFE) {
387 unget_char(ch2, tok);
388 unget_char(ch1, tok);
389 return 1;
390 }
391 if (!set_readline(tok, "utf-16-le"))
392 return 0;
393 tok->decoding_state = STATE_NORMAL;
394 #endif
395 } else {
396 unget_char(ch1, tok);
397 return 1;
398 }
399 if (tok->encoding != NULL)
400 PyMem_FREE(tok->encoding);
401 tok->encoding = new_string("utf-8", 5, tok);
402 if (!tok->encoding)
403 return 0;
404 /* No need to set_readline: input is already utf-8 */
405 return 1;
406 }
407
408 /* Read a line of text from TOK into S, using the stream in TOK.
409 Return NULL on failure, else S.
410
411 On entry, tok->decoding_buffer will be one of:
412 1) NULL: need to call tok->decoding_readline to get a new line
413 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and
414 stored the result in tok->decoding_buffer
415 3) PyByteArrayObject *: previous call to fp_readl did not have enough room
416 (in the s buffer) to copy entire contents of the line read
417 by tok->decoding_readline. tok->decoding_buffer has the overflow.
418 In this case, fp_readl is called in a loop (with an expanded buffer)
419 until the buffer ends with a '\n' (or until the end of the file is
420 reached): see tok_nextc and its calls to decoding_fgets.
421 */
422
423 static char *
fp_readl(char * s,int size,struct tok_state * tok)424 fp_readl(char *s, int size, struct tok_state *tok)
425 {
426 PyObject* bufobj;
427 const char *buf;
428 Py_ssize_t buflen;
429
430 /* Ask for one less byte so we can terminate it */
431 assert(size > 0);
432 size--;
433
434 if (tok->decoding_buffer) {
435 bufobj = tok->decoding_buffer;
436 Py_INCREF(bufobj);
437 }
438 else
439 {
440 bufobj = _PyObject_CallNoArg(tok->decoding_readline);
441 if (bufobj == NULL)
442 goto error;
443 }
444 if (PyUnicode_CheckExact(bufobj))
445 {
446 buf = PyUnicode_AsUTF8AndSize(bufobj, &buflen);
447 if (buf == NULL) {
448 goto error;
449 }
450 }
451 else
452 {
453 buf = PyByteArray_AsString(bufobj);
454 if (buf == NULL) {
455 goto error;
456 }
457 buflen = PyByteArray_GET_SIZE(bufobj);
458 }
459
460 Py_XDECREF(tok->decoding_buffer);
461 if (buflen > size) {
462 /* Too many chars, the rest goes into tok->decoding_buffer */
463 tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size,
464 buflen-size);
465 if (tok->decoding_buffer == NULL)
466 goto error;
467 buflen = size;
468 }
469 else
470 tok->decoding_buffer = NULL;
471
472 memcpy(s, buf, buflen);
473 s[buflen] = '\0';
474 if (buflen == 0) /* EOF */
475 s = NULL;
476 Py_DECREF(bufobj);
477 return s;
478
479 error:
480 Py_XDECREF(bufobj);
481 return error_ret(tok);
482 }
483
484 /* Set the readline function for TOK to a StreamReader's
485 readline function. The StreamReader is named ENC.
486
487 This function is called from check_bom and check_coding_spec.
488
489 ENC is usually identical to the future value of tok->encoding,
490 except for the (currently unsupported) case of UTF-16.
491
492 Return 1 on success, 0 on failure. */
493
494 static int
fp_setreadl(struct tok_state * tok,const char * enc)495 fp_setreadl(struct tok_state *tok, const char* enc)
496 {
497 PyObject *readline, *io, *stream;
498 _Py_IDENTIFIER(open);
499 _Py_IDENTIFIER(readline);
500 int fd;
501 long pos;
502
503 fd = fileno(tok->fp);
504 /* Due to buffering the file offset for fd can be different from the file
505 * position of tok->fp. If tok->fp was opened in text mode on Windows,
506 * its file position counts CRLF as one char and can't be directly mapped
507 * to the file offset for fd. Instead we step back one byte and read to
508 * the end of line.*/
509 pos = ftell(tok->fp);
510 if (pos == -1 ||
511 lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {
512 PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);
513 return 0;
514 }
515
516 io = PyImport_ImportModuleNoBlock("io");
517 if (io == NULL)
518 return 0;
519
520 stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO",
521 fd, "r", -1, enc, Py_None, Py_None, Py_False);
522 Py_DECREF(io);
523 if (stream == NULL)
524 return 0;
525
526 readline = _PyObject_GetAttrId(stream, &PyId_readline);
527 Py_DECREF(stream);
528 if (readline == NULL)
529 return 0;
530 Py_XSETREF(tok->decoding_readline, readline);
531
532 if (pos > 0) {
533 PyObject *bufobj = _PyObject_CallNoArg(readline);
534 if (bufobj == NULL)
535 return 0;
536 Py_DECREF(bufobj);
537 }
538
539 return 1;
540 }
541
542 /* Fetch the next byte from TOK. */
543
fp_getc(struct tok_state * tok)544 static int fp_getc(struct tok_state *tok) {
545 return getc(tok->fp);
546 }
547
548 /* Unfetch the last byte back into TOK. */
549
fp_ungetc(int c,struct tok_state * tok)550 static void fp_ungetc(int c, struct tok_state *tok) {
551 ungetc(c, tok->fp);
552 }
553
554 /* Check whether the characters at s start a valid
555 UTF-8 sequence. Return the number of characters forming
556 the sequence if yes, 0 if not. */
valid_utf8(const unsigned char * s)557 static int valid_utf8(const unsigned char* s)
558 {
559 int expected = 0;
560 int length;
561 if (*s < 0x80)
562 /* single-byte code */
563 return 1;
564 if (*s < 0xc0)
565 /* following byte */
566 return 0;
567 if (*s < 0xE0)
568 expected = 1;
569 else if (*s < 0xF0)
570 expected = 2;
571 else if (*s < 0xF8)
572 expected = 3;
573 else
574 return 0;
575 length = expected + 1;
576 for (; expected; expected--)
577 if (s[expected] < 0x80 || s[expected] >= 0xC0)
578 return 0;
579 return length;
580 }
581
582 /* Read a line of input from TOK. Determine encoding
583 if necessary. */
584
585 static char *
decoding_fgets(char * s,int size,struct tok_state * tok)586 decoding_fgets(char *s, int size, struct tok_state *tok)
587 {
588 char *line = NULL;
589 int badchar = 0;
590 for (;;) {
591 if (tok->decoding_state == STATE_NORMAL) {
592 /* We already have a codec associated with
593 this input. */
594 line = fp_readl(s, size, tok);
595 break;
596 } else if (tok->decoding_state == STATE_RAW) {
597 /* We want a 'raw' read. */
598 line = Py_UniversalNewlineFgets(s, size,
599 tok->fp, NULL);
600 break;
601 } else {
602 /* We have not yet determined the encoding.
603 If an encoding is found, use the file-pointer
604 reader functions from now on. */
605 if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok))
606 return error_ret(tok);
607 assert(tok->decoding_state != STATE_INIT);
608 }
609 }
610 if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) {
611 if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) {
612 return error_ret(tok);
613 }
614 }
615 #ifndef PGEN
616 /* The default encoding is UTF-8, so make sure we don't have any
617 non-UTF-8 sequences in it. */
618 if (line && !tok->encoding) {
619 unsigned char *c;
620 int length;
621 for (c = (unsigned char *)line; *c; c += length)
622 if (!(length = valid_utf8(c))) {
623 badchar = *c;
624 break;
625 }
626 }
627 if (badchar) {
628 /* Need to add 1 to the line number, since this line
629 has not been counted, yet. */
630 PyErr_Format(PyExc_SyntaxError,
631 "Non-UTF-8 code starting with '\\x%.2x' "
632 "in file %U on line %i, "
633 "but no encoding declared; "
634 "see http://python.org/dev/peps/pep-0263/ for details",
635 badchar, tok->filename, tok->lineno + 1);
636 return error_ret(tok);
637 }
638 #endif
639 return line;
640 }
641
642 static int
decoding_feof(struct tok_state * tok)643 decoding_feof(struct tok_state *tok)
644 {
645 if (tok->decoding_state != STATE_NORMAL) {
646 return feof(tok->fp);
647 } else {
648 PyObject* buf = tok->decoding_buffer;
649 if (buf == NULL) {
650 buf = _PyObject_CallNoArg(tok->decoding_readline);
651 if (buf == NULL) {
652 error_ret(tok);
653 return 1;
654 } else {
655 tok->decoding_buffer = buf;
656 }
657 }
658 return PyObject_Length(buf) == 0;
659 }
660 }
661
662 /* Fetch a byte from TOK, using the string buffer. */
663
664 static int
buf_getc(struct tok_state * tok)665 buf_getc(struct tok_state *tok) {
666 return Py_CHARMASK(*tok->str++);
667 }
668
669 /* Unfetch a byte from TOK, using the string buffer. */
670
671 static void
buf_ungetc(int c,struct tok_state * tok)672 buf_ungetc(int c, struct tok_state *tok) {
673 tok->str--;
674 assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */
675 }
676
677 /* Set the readline function for TOK to ENC. For the string-based
678 tokenizer, this means to just record the encoding. */
679
680 static int
buf_setreadl(struct tok_state * tok,const char * enc)681 buf_setreadl(struct tok_state *tok, const char* enc) {
682 tok->enc = enc;
683 return 1;
684 }
685
686 /* Return a UTF-8 encoding Python string object from the
687 C byte string STR, which is encoded with ENC. */
688
689 static PyObject *
translate_into_utf8(const char * str,const char * enc)690 translate_into_utf8(const char* str, const char* enc) {
691 PyObject *utf8;
692 PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
693 if (buf == NULL)
694 return NULL;
695 utf8 = PyUnicode_AsUTF8String(buf);
696 Py_DECREF(buf);
697 return utf8;
698 }
699
700
701 static char *
translate_newlines(const char * s,int exec_input,struct tok_state * tok)702 translate_newlines(const char *s, int exec_input, struct tok_state *tok) {
703 int skip_next_lf = 0;
704 size_t needed_length = strlen(s) + 2, final_length;
705 char *buf, *current;
706 char c = '\0';
707 buf = PyMem_MALLOC(needed_length);
708 if (buf == NULL) {
709 tok->done = E_NOMEM;
710 return NULL;
711 }
712 for (current = buf; *s; s++, current++) {
713 c = *s;
714 if (skip_next_lf) {
715 skip_next_lf = 0;
716 if (c == '\n') {
717 c = *++s;
718 if (!c)
719 break;
720 }
721 }
722 if (c == '\r') {
723 skip_next_lf = 1;
724 c = '\n';
725 }
726 *current = c;
727 }
728 /* If this is exec input, add a newline to the end of the string if
729 there isn't one already. */
730 if (exec_input && c != '\n') {
731 *current = '\n';
732 current++;
733 }
734 *current = '\0';
735 final_length = current - buf + 1;
736 if (final_length < needed_length && final_length) {
737 /* should never fail */
738 char* result = PyMem_REALLOC(buf, final_length);
739 if (result == NULL) {
740 PyMem_FREE(buf);
741 }
742 buf = result;
743 }
744 return buf;
745 }
746
747 /* Decode a byte string STR for use as the buffer of TOK.
748 Look for encoding declarations inside STR, and record them
749 inside TOK. */
750
751 static const char *
decode_str(const char * input,int single,struct tok_state * tok)752 decode_str(const char *input, int single, struct tok_state *tok)
753 {
754 PyObject* utf8 = NULL;
755 const char *str;
756 const char *s;
757 const char *newl[2] = {NULL, NULL};
758 int lineno = 0;
759 tok->input = str = translate_newlines(input, single, tok);
760 if (str == NULL)
761 return NULL;
762 tok->enc = NULL;
763 tok->str = str;
764 if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok))
765 return error_ret(tok);
766 str = tok->str; /* string after BOM if any */
767 assert(str);
768 if (tok->enc != NULL) {
769 utf8 = translate_into_utf8(str, tok->enc);
770 if (utf8 == NULL)
771 return error_ret(tok);
772 str = PyBytes_AsString(utf8);
773 }
774 for (s = str;; s++) {
775 if (*s == '\0') break;
776 else if (*s == '\n') {
777 assert(lineno < 2);
778 newl[lineno] = s;
779 lineno++;
780 if (lineno == 2) break;
781 }
782 }
783 tok->enc = NULL;
784 /* need to check line 1 and 2 separately since check_coding_spec
785 assumes a single line as input */
786 if (newl[0]) {
787 if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl))
788 return error_ret(tok);
789 if (tok->enc == NULL && !tok->read_coding_spec && newl[1]) {
790 if (!check_coding_spec(newl[0]+1, newl[1] - newl[0],
791 tok, buf_setreadl))
792 return error_ret(tok);
793 }
794 }
795 if (tok->enc != NULL) {
796 assert(utf8 == NULL);
797 utf8 = translate_into_utf8(str, tok->enc);
798 if (utf8 == NULL)
799 return error_ret(tok);
800 str = PyBytes_AS_STRING(utf8);
801 }
802 assert(tok->decoding_buffer == NULL);
803 tok->decoding_buffer = utf8; /* CAUTION */
804 return str;
805 }
806
807 #endif /* PGEN */
808
809 /* Set up tokenizer for string */
810
811 struct tok_state *
PyTokenizer_FromString(const char * str,int exec_input)812 PyTokenizer_FromString(const char *str, int exec_input)
813 {
814 struct tok_state *tok = tok_new();
815 if (tok == NULL)
816 return NULL;
817 str = decode_str(str, exec_input, tok);
818 if (str == NULL) {
819 PyTokenizer_Free(tok);
820 return NULL;
821 }
822
823 /* XXX: constify members. */
824 tok->buf = tok->cur = tok->end = tok->inp = (char*)str;
825 return tok;
826 }
827
828 struct tok_state *
PyTokenizer_FromUTF8(const char * str,int exec_input)829 PyTokenizer_FromUTF8(const char *str, int exec_input)
830 {
831 struct tok_state *tok = tok_new();
832 if (tok == NULL)
833 return NULL;
834 #ifndef PGEN
835 tok->input = str = translate_newlines(str, exec_input, tok);
836 #endif
837 if (str == NULL) {
838 PyTokenizer_Free(tok);
839 return NULL;
840 }
841 tok->decoding_state = STATE_RAW;
842 tok->read_coding_spec = 1;
843 tok->enc = NULL;
844 tok->str = str;
845 tok->encoding = (char *)PyMem_MALLOC(6);
846 if (!tok->encoding) {
847 PyTokenizer_Free(tok);
848 return NULL;
849 }
850 strcpy(tok->encoding, "utf-8");
851
852 /* XXX: constify members. */
853 tok->buf = tok->cur = tok->end = tok->inp = (char*)str;
854 return tok;
855 }
856
857 /* Set up tokenizer for file */
858
859 struct tok_state *
PyTokenizer_FromFile(FILE * fp,const char * enc,const char * ps1,const char * ps2)860 PyTokenizer_FromFile(FILE *fp, const char* enc,
861 const char *ps1, const char *ps2)
862 {
863 struct tok_state *tok = tok_new();
864 if (tok == NULL)
865 return NULL;
866 if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) {
867 PyTokenizer_Free(tok);
868 return NULL;
869 }
870 tok->cur = tok->inp = tok->buf;
871 tok->end = tok->buf + BUFSIZ;
872 tok->fp = fp;
873 tok->prompt = ps1;
874 tok->nextprompt = ps2;
875 if (enc != NULL) {
876 /* Must copy encoding declaration since it
877 gets copied into the parse tree. */
878 tok->encoding = PyMem_MALLOC(strlen(enc)+1);
879 if (!tok->encoding) {
880 PyTokenizer_Free(tok);
881 return NULL;
882 }
883 strcpy(tok->encoding, enc);
884 tok->decoding_state = STATE_NORMAL;
885 }
886 return tok;
887 }
888
889
890 /* Free a tok_state structure */
891
892 void
PyTokenizer_Free(struct tok_state * tok)893 PyTokenizer_Free(struct tok_state *tok)
894 {
895 if (tok->encoding != NULL)
896 PyMem_FREE(tok->encoding);
897 #ifndef PGEN
898 Py_XDECREF(tok->decoding_readline);
899 Py_XDECREF(tok->decoding_buffer);
900 Py_XDECREF(tok->filename);
901 #endif
902 if (tok->fp != NULL && tok->buf != NULL)
903 PyMem_FREE(tok->buf);
904 if (tok->input)
905 PyMem_FREE((char *)tok->input);
906 PyMem_FREE(tok);
907 }
908
909 /* Get next char, updating state; error code goes into tok->done */
910
911 static int
tok_nextc(struct tok_state * tok)912 tok_nextc(struct tok_state *tok)
913 {
914 for (;;) {
915 if (tok->cur != tok->inp) {
916 return Py_CHARMASK(*tok->cur++); /* Fast path */
917 }
918 if (tok->done != E_OK)
919 return EOF;
920 if (tok->fp == NULL) {
921 char *end = strchr(tok->inp, '\n');
922 if (end != NULL)
923 end++;
924 else {
925 end = strchr(tok->inp, '\0');
926 if (end == tok->inp) {
927 tok->done = E_EOF;
928 return EOF;
929 }
930 }
931 if (tok->start == NULL)
932 tok->buf = tok->cur;
933 tok->line_start = tok->cur;
934 tok->lineno++;
935 tok->inp = end;
936 return Py_CHARMASK(*tok->cur++);
937 }
938 if (tok->prompt != NULL) {
939 char *newtok = PyOS_Readline(stdin, stdout, tok->prompt);
940 #ifndef PGEN
941 if (newtok != NULL) {
942 char *translated = translate_newlines(newtok, 0, tok);
943 PyMem_FREE(newtok);
944 if (translated == NULL)
945 return EOF;
946 newtok = translated;
947 }
948 if (tok->encoding && newtok && *newtok) {
949 /* Recode to UTF-8 */
950 Py_ssize_t buflen;
951 const char* buf;
952 PyObject *u = translate_into_utf8(newtok, tok->encoding);
953 PyMem_FREE(newtok);
954 if (!u) {
955 tok->done = E_DECODE;
956 return EOF;
957 }
958 buflen = PyBytes_GET_SIZE(u);
959 buf = PyBytes_AS_STRING(u);
960 newtok = PyMem_MALLOC(buflen+1);
961 if (newtok == NULL) {
962 Py_DECREF(u);
963 tok->done = E_NOMEM;
964 return EOF;
965 }
966 strcpy(newtok, buf);
967 Py_DECREF(u);
968 }
969 #endif
970 if (tok->nextprompt != NULL)
971 tok->prompt = tok->nextprompt;
972 if (newtok == NULL)
973 tok->done = E_INTR;
974 else if (*newtok == '\0') {
975 PyMem_FREE(newtok);
976 tok->done = E_EOF;
977 }
978 else if (tok->start != NULL) {
979 size_t start = tok->start - tok->buf;
980 size_t oldlen = tok->cur - tok->buf;
981 size_t newlen = oldlen + strlen(newtok);
982 char *buf = tok->buf;
983 buf = (char *)PyMem_REALLOC(buf, newlen+1);
984 tok->lineno++;
985 if (buf == NULL) {
986 PyMem_FREE(tok->buf);
987 tok->buf = NULL;
988 PyMem_FREE(newtok);
989 tok->done = E_NOMEM;
990 return EOF;
991 }
992 tok->buf = buf;
993 tok->cur = tok->buf + oldlen;
994 tok->line_start = tok->cur;
995 strcpy(tok->buf + oldlen, newtok);
996 PyMem_FREE(newtok);
997 tok->inp = tok->buf + newlen;
998 tok->end = tok->inp + 1;
999 tok->start = tok->buf + start;
1000 }
1001 else {
1002 tok->lineno++;
1003 if (tok->buf != NULL)
1004 PyMem_FREE(tok->buf);
1005 tok->buf = newtok;
1006 tok->cur = tok->buf;
1007 tok->line_start = tok->buf;
1008 tok->inp = strchr(tok->buf, '\0');
1009 tok->end = tok->inp + 1;
1010 }
1011 }
1012 else {
1013 int done = 0;
1014 Py_ssize_t cur = 0;
1015 char *pt;
1016 if (tok->start == NULL) {
1017 if (tok->buf == NULL) {
1018 tok->buf = (char *)
1019 PyMem_MALLOC(BUFSIZ);
1020 if (tok->buf == NULL) {
1021 tok->done = E_NOMEM;
1022 return EOF;
1023 }
1024 tok->end = tok->buf + BUFSIZ;
1025 }
1026 if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf),
1027 tok) == NULL) {
1028 if (!tok->decoding_erred)
1029 tok->done = E_EOF;
1030 done = 1;
1031 }
1032 else {
1033 tok->done = E_OK;
1034 tok->inp = strchr(tok->buf, '\0');
1035 done = tok->inp == tok->buf || tok->inp[-1] == '\n';
1036 }
1037 }
1038 else {
1039 cur = tok->cur - tok->buf;
1040 if (decoding_feof(tok)) {
1041 tok->done = E_EOF;
1042 done = 1;
1043 }
1044 else
1045 tok->done = E_OK;
1046 }
1047 tok->lineno++;
1048 /* Read until '\n' or EOF */
1049 while (!done) {
1050 Py_ssize_t curstart = tok->start == NULL ? -1 :
1051 tok->start - tok->buf;
1052 Py_ssize_t curvalid = tok->inp - tok->buf;
1053 Py_ssize_t newsize = curvalid + BUFSIZ;
1054 char *newbuf = tok->buf;
1055 newbuf = (char *)PyMem_REALLOC(newbuf,
1056 newsize);
1057 if (newbuf == NULL) {
1058 tok->done = E_NOMEM;
1059 tok->cur = tok->inp;
1060 return EOF;
1061 }
1062 tok->buf = newbuf;
1063 tok->cur = tok->buf + cur;
1064 tok->line_start = tok->cur;
1065 tok->inp = tok->buf + curvalid;
1066 tok->end = tok->buf + newsize;
1067 tok->start = curstart < 0 ? NULL :
1068 tok->buf + curstart;
1069 if (decoding_fgets(tok->inp,
1070 (int)(tok->end - tok->inp),
1071 tok) == NULL) {
1072 /* Break out early on decoding
1073 errors, as tok->buf will be NULL
1074 */
1075 if (tok->decoding_erred)
1076 return EOF;
1077 /* Last line does not end in \n,
1078 fake one */
1079 strcpy(tok->inp, "\n");
1080 }
1081 tok->inp = strchr(tok->inp, '\0');
1082 done = tok->inp[-1] == '\n';
1083 }
1084 if (tok->buf != NULL) {
1085 tok->cur = tok->buf + cur;
1086 tok->line_start = tok->cur;
1087 /* replace "\r\n" with "\n" */
1088 /* For Mac leave the \r, giving a syntax error */
1089 pt = tok->inp - 2;
1090 if (pt >= tok->buf && *pt == '\r') {
1091 *pt++ = '\n';
1092 *pt = '\0';
1093 tok->inp = pt;
1094 }
1095 }
1096 }
1097 if (tok->done != E_OK) {
1098 if (tok->prompt != NULL)
1099 PySys_WriteStderr("\n");
1100 tok->cur = tok->inp;
1101 return EOF;
1102 }
1103 }
1104 /*NOTREACHED*/
1105 }
1106
1107
1108 /* Back-up one character */
1109
1110 static void
tok_backup(struct tok_state * tok,int c)1111 tok_backup(struct tok_state *tok, int c)
1112 {
1113 if (c != EOF) {
1114 if (--tok->cur < tok->buf)
1115 Py_FatalError("tok_backup: beginning of buffer");
1116 if (*tok->cur != c)
1117 *tok->cur = c;
1118 }
1119 }
1120
1121
1122 /* Return the token corresponding to a single character */
1123
1124 int
PyToken_OneChar(int c)1125 PyToken_OneChar(int c)
1126 {
1127 switch (c) {
1128 case '(': return LPAR;
1129 case ')': return RPAR;
1130 case '[': return LSQB;
1131 case ']': return RSQB;
1132 case ':': return COLON;
1133 case ',': return COMMA;
1134 case ';': return SEMI;
1135 case '+': return PLUS;
1136 case '-': return MINUS;
1137 case '*': return STAR;
1138 case '/': return SLASH;
1139 case '|': return VBAR;
1140 case '&': return AMPER;
1141 case '<': return LESS;
1142 case '>': return GREATER;
1143 case '=': return EQUAL;
1144 case '.': return DOT;
1145 case '%': return PERCENT;
1146 case '{': return LBRACE;
1147 case '}': return RBRACE;
1148 case '^': return CIRCUMFLEX;
1149 case '~': return TILDE;
1150 case '@': return AT;
1151 default: return OP;
1152 }
1153 }
1154
1155
1156 int
PyToken_TwoChars(int c1,int c2)1157 PyToken_TwoChars(int c1, int c2)
1158 {
1159 switch (c1) {
1160 case '=':
1161 switch (c2) {
1162 case '=': return EQEQUAL;
1163 }
1164 break;
1165 case '!':
1166 switch (c2) {
1167 case '=': return NOTEQUAL;
1168 }
1169 break;
1170 case '<':
1171 switch (c2) {
1172 case '>': return NOTEQUAL;
1173 case '=': return LESSEQUAL;
1174 case '<': return LEFTSHIFT;
1175 }
1176 break;
1177 case '>':
1178 switch (c2) {
1179 case '=': return GREATEREQUAL;
1180 case '>': return RIGHTSHIFT;
1181 }
1182 break;
1183 case '+':
1184 switch (c2) {
1185 case '=': return PLUSEQUAL;
1186 }
1187 break;
1188 case '-':
1189 switch (c2) {
1190 case '=': return MINEQUAL;
1191 case '>': return RARROW;
1192 }
1193 break;
1194 case '*':
1195 switch (c2) {
1196 case '*': return DOUBLESTAR;
1197 case '=': return STAREQUAL;
1198 }
1199 break;
1200 case '/':
1201 switch (c2) {
1202 case '/': return DOUBLESLASH;
1203 case '=': return SLASHEQUAL;
1204 }
1205 break;
1206 case '|':
1207 switch (c2) {
1208 case '=': return VBAREQUAL;
1209 }
1210 break;
1211 case '%':
1212 switch (c2) {
1213 case '=': return PERCENTEQUAL;
1214 }
1215 break;
1216 case '&':
1217 switch (c2) {
1218 case '=': return AMPEREQUAL;
1219 }
1220 break;
1221 case '^':
1222 switch (c2) {
1223 case '=': return CIRCUMFLEXEQUAL;
1224 }
1225 break;
1226 case '@':
1227 switch (c2) {
1228 case '=': return ATEQUAL;
1229 }
1230 break;
1231 }
1232 return OP;
1233 }
1234
1235 int
PyToken_ThreeChars(int c1,int c2,int c3)1236 PyToken_ThreeChars(int c1, int c2, int c3)
1237 {
1238 switch (c1) {
1239 case '<':
1240 switch (c2) {
1241 case '<':
1242 switch (c3) {
1243 case '=':
1244 return LEFTSHIFTEQUAL;
1245 }
1246 break;
1247 }
1248 break;
1249 case '>':
1250 switch (c2) {
1251 case '>':
1252 switch (c3) {
1253 case '=':
1254 return RIGHTSHIFTEQUAL;
1255 }
1256 break;
1257 }
1258 break;
1259 case '*':
1260 switch (c2) {
1261 case '*':
1262 switch (c3) {
1263 case '=':
1264 return DOUBLESTAREQUAL;
1265 }
1266 break;
1267 }
1268 break;
1269 case '/':
1270 switch (c2) {
1271 case '/':
1272 switch (c3) {
1273 case '=':
1274 return DOUBLESLASHEQUAL;
1275 }
1276 break;
1277 }
1278 break;
1279 case '.':
1280 switch (c2) {
1281 case '.':
1282 switch (c3) {
1283 case '.':
1284 return ELLIPSIS;
1285 }
1286 break;
1287 }
1288 break;
1289 }
1290 return OP;
1291 }
1292
1293 static int
indenterror(struct tok_state * tok)1294 indenterror(struct tok_state *tok)
1295 {
1296 tok->done = E_TABSPACE;
1297 tok->cur = tok->inp;
1298 return ERRORTOKEN;
1299 }
1300
1301 #ifdef PGEN
1302 #define verify_identifier(tok) 1
1303 #else
1304 /* Verify that the identifier follows PEP 3131.
1305 All identifier strings are guaranteed to be "ready" unicode objects.
1306 */
1307 static int
verify_identifier(struct tok_state * tok)1308 verify_identifier(struct tok_state *tok)
1309 {
1310 PyObject *s;
1311 int result;
1312 if (tok->decoding_erred)
1313 return 0;
1314 s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL);
1315 if (s == NULL || PyUnicode_READY(s) == -1) {
1316 if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
1317 PyErr_Clear();
1318 tok->done = E_IDENTIFIER;
1319 } else {
1320 tok->done = E_ERROR;
1321 }
1322 return 0;
1323 }
1324 result = PyUnicode_IsIdentifier(s);
1325 Py_DECREF(s);
1326 if (result == 0)
1327 tok->done = E_IDENTIFIER;
1328 return result;
1329 }
1330 #endif
1331
1332 static int
tok_decimal_tail(struct tok_state * tok)1333 tok_decimal_tail(struct tok_state *tok)
1334 {
1335 int c;
1336
1337 while (1) {
1338 do {
1339 c = tok_nextc(tok);
1340 } while (isdigit(c));
1341 if (c != '_') {
1342 break;
1343 }
1344 c = tok_nextc(tok);
1345 if (!isdigit(c)) {
1346 tok->done = E_TOKEN;
1347 tok_backup(tok, c);
1348 return 0;
1349 }
1350 }
1351 return c;
1352 }
1353
1354 /* Get next token, after space stripping etc. */
1355
1356 static int
tok_get(struct tok_state * tok,char ** p_start,char ** p_end)1357 tok_get(struct tok_state *tok, char **p_start, char **p_end)
1358 {
1359 int c;
1360 int blankline, nonascii;
1361
1362 *p_start = *p_end = NULL;
1363 nextline:
1364 tok->start = NULL;
1365 blankline = 0;
1366
1367 /* Get indentation level */
1368 if (tok->atbol) {
1369 int col = 0;
1370 int altcol = 0;
1371 tok->atbol = 0;
1372 for (;;) {
1373 c = tok_nextc(tok);
1374 if (c == ' ') {
1375 col++, altcol++;
1376 }
1377 else if (c == '\t') {
1378 col = (col / tok->tabsize + 1) * tok->tabsize;
1379 altcol = (altcol / ALTTABSIZE + 1) * ALTTABSIZE;
1380 }
1381 else if (c == '\014') {/* Control-L (formfeed) */
1382 col = altcol = 0; /* For Emacs users */
1383 }
1384 else {
1385 break;
1386 }
1387 }
1388 tok_backup(tok, c);
1389 if (c == '#' || c == '\n') {
1390 /* Lines with only whitespace and/or comments
1391 shouldn't affect the indentation and are
1392 not passed to the parser as NEWLINE tokens,
1393 except *totally* empty lines in interactive
1394 mode, which signal the end of a command group. */
1395 if (col == 0 && c == '\n' && tok->prompt != NULL) {
1396 blankline = 0; /* Let it through */
1397 }
1398 else if (tok->prompt != NULL && tok->lineno == 1) {
1399 /* In interactive mode, if the first line contains
1400 only spaces and/or a comment, let it through. */
1401 blankline = 0;
1402 col = altcol = 0;
1403 }
1404 else {
1405 blankline = 1; /* Ignore completely */
1406 }
1407 /* We can't jump back right here since we still
1408 may need to skip to the end of a comment */
1409 }
1410 if (!blankline && tok->level == 0) {
1411 if (col == tok->indstack[tok->indent]) {
1412 /* No change */
1413 if (altcol != tok->altindstack[tok->indent]) {
1414 return indenterror(tok);
1415 }
1416 }
1417 else if (col > tok->indstack[tok->indent]) {
1418 /* Indent -- always one */
1419 if (tok->indent+1 >= MAXINDENT) {
1420 tok->done = E_TOODEEP;
1421 tok->cur = tok->inp;
1422 return ERRORTOKEN;
1423 }
1424 if (altcol <= tok->altindstack[tok->indent]) {
1425 return indenterror(tok);
1426 }
1427 tok->pendin++;
1428 tok->indstack[++tok->indent] = col;
1429 tok->altindstack[tok->indent] = altcol;
1430 }
1431 else /* col < tok->indstack[tok->indent] */ {
1432 /* Dedent -- any number, must be consistent */
1433 while (tok->indent > 0 &&
1434 col < tok->indstack[tok->indent]) {
1435 tok->pendin--;
1436 tok->indent--;
1437 }
1438 if (col != tok->indstack[tok->indent]) {
1439 tok->done = E_DEDENT;
1440 tok->cur = tok->inp;
1441 return ERRORTOKEN;
1442 }
1443 if (altcol != tok->altindstack[tok->indent]) {
1444 return indenterror(tok);
1445 }
1446 }
1447 }
1448 }
1449
1450 tok->start = tok->cur;
1451
1452 /* Return pending indents/dedents */
1453 if (tok->pendin != 0) {
1454 if (tok->pendin < 0) {
1455 tok->pendin++;
1456 return DEDENT;
1457 }
1458 else {
1459 tok->pendin--;
1460 return INDENT;
1461 }
1462 }
1463
1464 again:
1465 tok->start = NULL;
1466 /* Skip spaces */
1467 do {
1468 c = tok_nextc(tok);
1469 } while (c == ' ' || c == '\t' || c == '\014');
1470
1471 /* Set start of current token */
1472 tok->start = tok->cur - 1;
1473
1474 /* Skip comment */
1475 if (c == '#') {
1476 while (c != EOF && c != '\n') {
1477 c = tok_nextc(tok);
1478 }
1479 }
1480
1481 /* Check for EOF and errors now */
1482 if (c == EOF) {
1483 return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
1484 }
1485
1486 /* Identifier (most frequent token!) */
1487 nonascii = 0;
1488 if (is_potential_identifier_start(c)) {
1489 /* Process the various legal combinations of b"", r"", u"", and f"". */
1490 int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0;
1491 while (1) {
1492 if (!(saw_b || saw_u || saw_f) && (c == 'b' || c == 'B'))
1493 saw_b = 1;
1494 /* Since this is a backwards compatibility support literal we don't
1495 want to support it in arbitrary order like byte literals. */
1496 else if (!(saw_b || saw_u || saw_r || saw_f)
1497 && (c == 'u'|| c == 'U')) {
1498 saw_u = 1;
1499 }
1500 /* ur"" and ru"" are not supported */
1501 else if (!(saw_r || saw_u) && (c == 'r' || c == 'R')) {
1502 saw_r = 1;
1503 }
1504 else if (!(saw_f || saw_b || saw_u) && (c == 'f' || c == 'F')) {
1505 saw_f = 1;
1506 }
1507 else {
1508 break;
1509 }
1510 c = tok_nextc(tok);
1511 if (c == '"' || c == '\'') {
1512 goto letter_quote;
1513 }
1514 }
1515 while (is_potential_identifier_char(c)) {
1516 if (c >= 128) {
1517 nonascii = 1;
1518 }
1519 c = tok_nextc(tok);
1520 }
1521 tok_backup(tok, c);
1522 if (nonascii && !verify_identifier(tok)) {
1523 return ERRORTOKEN;
1524 }
1525 *p_start = tok->start;
1526 *p_end = tok->cur;
1527
1528 return NAME;
1529 }
1530
1531 /* Newline */
1532 if (c == '\n') {
1533 tok->atbol = 1;
1534 if (blankline || tok->level > 0) {
1535 goto nextline;
1536 }
1537 *p_start = tok->start;
1538 *p_end = tok->cur - 1; /* Leave '\n' out of the string */
1539 tok->cont_line = 0;
1540 return NEWLINE;
1541 }
1542
1543 /* Period or number starting with period? */
1544 if (c == '.') {
1545 c = tok_nextc(tok);
1546 if (isdigit(c)) {
1547 goto fraction;
1548 } else if (c == '.') {
1549 c = tok_nextc(tok);
1550 if (c == '.') {
1551 *p_start = tok->start;
1552 *p_end = tok->cur;
1553 return ELLIPSIS;
1554 }
1555 else {
1556 tok_backup(tok, c);
1557 }
1558 tok_backup(tok, '.');
1559 }
1560 else {
1561 tok_backup(tok, c);
1562 }
1563 *p_start = tok->start;
1564 *p_end = tok->cur;
1565 return DOT;
1566 }
1567
1568 /* Number */
1569 if (isdigit(c)) {
1570 if (c == '0') {
1571 /* Hex, octal or binary -- maybe. */
1572 c = tok_nextc(tok);
1573 if (c == 'x' || c == 'X') {
1574 /* Hex */
1575 c = tok_nextc(tok);
1576 do {
1577 if (c == '_') {
1578 c = tok_nextc(tok);
1579 }
1580 if (!isxdigit(c)) {
1581 tok->done = E_TOKEN;
1582 tok_backup(tok, c);
1583 return ERRORTOKEN;
1584 }
1585 do {
1586 c = tok_nextc(tok);
1587 } while (isxdigit(c));
1588 } while (c == '_');
1589 }
1590 else if (c == 'o' || c == 'O') {
1591 /* Octal */
1592 c = tok_nextc(tok);
1593 do {
1594 if (c == '_') {
1595 c = tok_nextc(tok);
1596 }
1597 if (c < '0' || c >= '8') {
1598 tok->done = E_TOKEN;
1599 tok_backup(tok, c);
1600 return ERRORTOKEN;
1601 }
1602 do {
1603 c = tok_nextc(tok);
1604 } while ('0' <= c && c < '8');
1605 } while (c == '_');
1606 }
1607 else if (c == 'b' || c == 'B') {
1608 /* Binary */
1609 c = tok_nextc(tok);
1610 do {
1611 if (c == '_') {
1612 c = tok_nextc(tok);
1613 }
1614 if (c != '0' && c != '1') {
1615 tok->done = E_TOKEN;
1616 tok_backup(tok, c);
1617 return ERRORTOKEN;
1618 }
1619 do {
1620 c = tok_nextc(tok);
1621 } while (c == '0' || c == '1');
1622 } while (c == '_');
1623 }
1624 else {
1625 int nonzero = 0;
1626 /* maybe old-style octal; c is first char of it */
1627 /* in any case, allow '0' as a literal */
1628 while (1) {
1629 if (c == '_') {
1630 c = tok_nextc(tok);
1631 if (!isdigit(c)) {
1632 tok->done = E_TOKEN;
1633 tok_backup(tok, c);
1634 return ERRORTOKEN;
1635 }
1636 }
1637 if (c != '0') {
1638 break;
1639 }
1640 c = tok_nextc(tok);
1641 }
1642 if (isdigit(c)) {
1643 nonzero = 1;
1644 c = tok_decimal_tail(tok);
1645 if (c == 0) {
1646 return ERRORTOKEN;
1647 }
1648 }
1649 if (c == '.') {
1650 c = tok_nextc(tok);
1651 goto fraction;
1652 }
1653 else if (c == 'e' || c == 'E') {
1654 goto exponent;
1655 }
1656 else if (c == 'j' || c == 'J') {
1657 goto imaginary;
1658 }
1659 else if (nonzero) {
1660 /* Old-style octal: now disallowed. */
1661 tok->done = E_TOKEN;
1662 tok_backup(tok, c);
1663 return ERRORTOKEN;
1664 }
1665 }
1666 }
1667 else {
1668 /* Decimal */
1669 c = tok_decimal_tail(tok);
1670 if (c == 0) {
1671 return ERRORTOKEN;
1672 }
1673 {
1674 /* Accept floating point numbers. */
1675 if (c == '.') {
1676 c = tok_nextc(tok);
1677 fraction:
1678 /* Fraction */
1679 if (isdigit(c)) {
1680 c = tok_decimal_tail(tok);
1681 if (c == 0) {
1682 return ERRORTOKEN;
1683 }
1684 }
1685 }
1686 if (c == 'e' || c == 'E') {
1687 int e;
1688 exponent:
1689 e = c;
1690 /* Exponent part */
1691 c = tok_nextc(tok);
1692 if (c == '+' || c == '-') {
1693 c = tok_nextc(tok);
1694 if (!isdigit(c)) {
1695 tok->done = E_TOKEN;
1696 tok_backup(tok, c);
1697 return ERRORTOKEN;
1698 }
1699 } else if (!isdigit(c)) {
1700 tok_backup(tok, c);
1701 tok_backup(tok, e);
1702 *p_start = tok->start;
1703 *p_end = tok->cur;
1704 return NUMBER;
1705 }
1706 c = tok_decimal_tail(tok);
1707 if (c == 0) {
1708 return ERRORTOKEN;
1709 }
1710 }
1711 if (c == 'j' || c == 'J') {
1712 /* Imaginary part */
1713 imaginary:
1714 c = tok_nextc(tok);
1715 }
1716 }
1717 }
1718 tok_backup(tok, c);
1719 *p_start = tok->start;
1720 *p_end = tok->cur;
1721 return NUMBER;
1722 }
1723
1724 letter_quote:
1725 /* String */
1726 if (c == '\'' || c == '"') {
1727 int quote = c;
1728 int quote_size = 1; /* 1 or 3 */
1729 int end_quote_size = 0;
1730
1731 /* Find the quote size and start of string */
1732 c = tok_nextc(tok);
1733 if (c == quote) {
1734 c = tok_nextc(tok);
1735 if (c == quote) {
1736 quote_size = 3;
1737 }
1738 else {
1739 end_quote_size = 1; /* empty string found */
1740 }
1741 }
1742 if (c != quote) {
1743 tok_backup(tok, c);
1744 }
1745
1746 /* Get rest of string */
1747 while (end_quote_size != quote_size) {
1748 c = tok_nextc(tok);
1749 if (c == EOF) {
1750 if (quote_size == 3) {
1751 tok->done = E_EOFS;
1752 }
1753 else {
1754 tok->done = E_EOLS;
1755 }
1756 tok->cur = tok->inp;
1757 return ERRORTOKEN;
1758 }
1759 if (quote_size == 1 && c == '\n') {
1760 tok->done = E_EOLS;
1761 tok->cur = tok->inp;
1762 return ERRORTOKEN;
1763 }
1764 if (c == quote) {
1765 end_quote_size += 1;
1766 }
1767 else {
1768 end_quote_size = 0;
1769 if (c == '\\') {
1770 tok_nextc(tok); /* skip escaped char */
1771 }
1772 }
1773 }
1774
1775 *p_start = tok->start;
1776 *p_end = tok->cur;
1777 return STRING;
1778 }
1779
1780 /* Line continuation */
1781 if (c == '\\') {
1782 c = tok_nextc(tok);
1783 if (c != '\n') {
1784 tok->done = E_LINECONT;
1785 tok->cur = tok->inp;
1786 return ERRORTOKEN;
1787 }
1788 tok->cont_line = 1;
1789 goto again; /* Read next line */
1790 }
1791
1792 /* Check for two-character token */
1793 {
1794 int c2 = tok_nextc(tok);
1795 int token = PyToken_TwoChars(c, c2);
1796 if (token != OP) {
1797 int c3 = tok_nextc(tok);
1798 int token3 = PyToken_ThreeChars(c, c2, c3);
1799 if (token3 != OP) {
1800 token = token3;
1801 }
1802 else {
1803 tok_backup(tok, c3);
1804 }
1805 *p_start = tok->start;
1806 *p_end = tok->cur;
1807 return token;
1808 }
1809 tok_backup(tok, c2);
1810 }
1811
1812 /* Keep track of parentheses nesting level */
1813 switch (c) {
1814 case '(':
1815 case '[':
1816 case '{':
1817 tok->level++;
1818 break;
1819 case ')':
1820 case ']':
1821 case '}':
1822 tok->level--;
1823 break;
1824 }
1825
1826 /* Punctuation character */
1827 *p_start = tok->start;
1828 *p_end = tok->cur;
1829 return PyToken_OneChar(c);
1830 }
1831
1832 int
PyTokenizer_Get(struct tok_state * tok,char ** p_start,char ** p_end)1833 PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end)
1834 {
1835 int result = tok_get(tok, p_start, p_end);
1836 if (tok->decoding_erred) {
1837 result = ERRORTOKEN;
1838 tok->done = E_DECODE;
1839 }
1840 return result;
1841 }
1842
1843 /* Get the encoding of a Python file. Check for the coding cookie and check if
1844 the file starts with a BOM.
1845
1846 PyTokenizer_FindEncodingFilename() returns NULL when it can't find the
1847 encoding in the first or second line of the file (in which case the encoding
1848 should be assumed to be UTF-8).
1849
1850 The char* returned is malloc'ed via PyMem_MALLOC() and thus must be freed
1851 by the caller. */
1852
1853 char *
PyTokenizer_FindEncodingFilename(int fd,PyObject * filename)1854 PyTokenizer_FindEncodingFilename(int fd, PyObject *filename)
1855 {
1856 struct tok_state *tok;
1857 FILE *fp;
1858 char *p_start =NULL , *p_end =NULL , *encoding = NULL;
1859
1860 #ifndef PGEN
1861 fd = _Py_dup(fd);
1862 #else
1863 fd = dup(fd);
1864 #endif
1865 if (fd < 0) {
1866 return NULL;
1867 }
1868
1869 fp = fdopen(fd, "r");
1870 if (fp == NULL) {
1871 return NULL;
1872 }
1873 tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL);
1874 if (tok == NULL) {
1875 fclose(fp);
1876 return NULL;
1877 }
1878 #ifndef PGEN
1879 if (filename != NULL) {
1880 Py_INCREF(filename);
1881 tok->filename = filename;
1882 }
1883 else {
1884 tok->filename = PyUnicode_FromString("<string>");
1885 if (tok->filename == NULL) {
1886 fclose(fp);
1887 PyTokenizer_Free(tok);
1888 return encoding;
1889 }
1890 }
1891 #endif
1892 while (tok->lineno < 2 && tok->done == E_OK) {
1893 PyTokenizer_Get(tok, &p_start, &p_end);
1894 }
1895 fclose(fp);
1896 if (tok->encoding) {
1897 encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1);
1898 if (encoding)
1899 strcpy(encoding, tok->encoding);
1900 }
1901 PyTokenizer_Free(tok);
1902 return encoding;
1903 }
1904
1905 char *
PyTokenizer_FindEncoding(int fd)1906 PyTokenizer_FindEncoding(int fd)
1907 {
1908 return PyTokenizer_FindEncodingFilename(fd, NULL);
1909 }
1910
1911 #ifdef Py_DEBUG
1912
1913 void
tok_dump(int type,char * start,char * end)1914 tok_dump(int type, char *start, char *end)
1915 {
1916 printf("%s", _PyParser_TokenNames[type]);
1917 if (type == NAME || type == NUMBER || type == STRING || type == OP)
1918 printf("(%.*s)", (int)(end - start), start);
1919 }
1920
1921 #endif
1922