blob: f3c1d9b20ade112743ec005d9e0c6b0bf0ef8b92 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Tokenizer implementation */
3
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +02004#define PY_SSIZE_T_CLEAN
Jack Jansen7b8c7542002-04-14 20:12:41 +00005#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00006
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007#include <ctype.h>
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00008#include <assert.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "tokenizer.h"
11#include "errcode.h"
12
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000013#include "unicodeobject.h"
Christian Heimes2c9c7a52008-05-26 13:42:13 +000014#include "bytesobject.h"
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000015#include "fileobject.h"
16#include "codecs.h"
17#include "abstract.h"
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000018
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -080019/* Alternate tab spacing */
20#define ALTTABSIZE 1
21
Martin v. Löwis5b222132007-06-10 09:51:05 +000022#define is_potential_identifier_start(c) (\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 (c >= 'a' && c <= 'z')\
24 || (c >= 'A' && c <= 'Z')\
25 || c == '_'\
26 || (c >= 128))
Martin v. Löwis5b222132007-06-10 09:51:05 +000027
28#define is_potential_identifier_char(c) (\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 (c >= 'a' && c <= 'z')\
30 || (c >= 'A' && c <= 'Z')\
31 || (c >= '0' && c <= '9')\
32 || c == '_'\
33 || (c >= 128))
Martin v. Löwis5b222132007-06-10 09:51:05 +000034
Guido van Rossumf4b1a641994-08-29 12:43:07 +000035
Guido van Rossum4fe87291992-02-26 15:24:44 +000036/* Don't ever change this -- it would break the portability of Python code */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037#define TABSIZE 8
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossum3f5da241990-12-20 15:06:42 +000039/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000040static struct tok_state *tok_new(void);
41static int tok_nextc(struct tok_state *tok);
42static void tok_backup(struct tok_state *tok, int c);
Guido van Rossum3f5da241990-12-20 15:06:42 +000043
Brett Cannond5ec98c2007-10-20 02:54:14 +000044
Guido van Rossumdcfcd142019-01-31 03:40:27 -080045/* Spaces in this constant are treated as "zero or more spaces or tabs" when
46 tokenizing. */
47static const char* type_comment_prefix = "# type: ";
48
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049/* Create and initialize a new tok_state structure */
50
51static struct tok_state *
Thomas Wouters23c9e002000-07-22 19:20:54 +000052tok_new(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(
55 sizeof(struct tok_state));
56 if (tok == NULL)
57 return NULL;
Andy Lester384f3c52020-02-27 20:44:52 -060058 tok->buf = tok->cur = tok->inp = NULL;
59 tok->start = NULL;
60 tok->end = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 tok->done = E_OK;
62 tok->fp = NULL;
63 tok->input = NULL;
64 tok->tabsize = TABSIZE;
65 tok->indent = 0;
66 tok->indstack[0] = 0;
Yury Selivanov75445082015-05-11 22:57:16 -040067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 tok->atbol = 1;
69 tok->pendin = 0;
70 tok->prompt = tok->nextprompt = NULL;
71 tok->lineno = 0;
72 tok->level = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 tok->altindstack[0] = 0;
74 tok->decoding_state = STATE_INIT;
75 tok->decoding_erred = 0;
76 tok->read_coding_spec = 0;
77 tok->enc = NULL;
78 tok->encoding = NULL;
79 tok->cont_line = 0;
Victor Stinner7f2fee32011-04-05 00:39:01 +020080 tok->filename = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 tok->decoding_readline = NULL;
82 tok->decoding_buffer = NULL;
Guido van Rossumdcfcd142019-01-31 03:40:27 -080083 tok->type_comments = 0;
Yury Selivanov96ec9342015-07-23 15:01:58 +030084
Guido van Rossum495da292019-03-07 12:38:08 -080085 tok->async_hacks = 0;
86 tok->async_def = 0;
87 tok->async_def_indent = 0;
88 tok->async_def_nl = 0;
89
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 return tok;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091}
92
Benjamin Petersonaeaa5922009-11-13 00:17:59 +000093static char *
Benjamin Peterson2dbfd882013-07-15 19:15:34 -070094new_string(const char *s, Py_ssize_t len, struct tok_state *tok)
Benjamin Petersonaeaa5922009-11-13 00:17:59 +000095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 char* result = (char *)PyMem_MALLOC(len + 1);
Benjamin Peterson2dbfd882013-07-15 19:15:34 -070097 if (!result) {
98 tok->done = E_NOMEM;
99 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700101 memcpy(result, s, len);
102 result[len] = '\0';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return result;
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000104}
105
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000106static char *
107error_ret(struct tok_state *tok) /* XXX */
108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 tok->decoding_erred = 1;
110 if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */
111 PyMem_FREE(tok->buf);
Andy Lester384f3c52020-02-27 20:44:52 -0600112 tok->buf = tok->cur = tok->inp = NULL;
113 tok->start = NULL;
114 tok->end = NULL;
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200115 tok->done = E_DECODE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 return NULL; /* as if it were EOF */
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000117}
118
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000119
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200120static const char *
121get_normal_name(const char *s) /* for utf-8 and latin-1 */
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 char buf[13];
124 int i;
125 for (i = 0; i < 12; i++) {
126 int c = s[i];
127 if (c == '\0')
128 break;
129 else if (c == '_')
130 buf[i] = '-';
131 else
132 buf[i] = tolower(c);
133 }
134 buf[i] = '\0';
135 if (strcmp(buf, "utf-8") == 0 ||
136 strncmp(buf, "utf-8-", 6) == 0)
137 return "utf-8";
138 else if (strcmp(buf, "latin-1") == 0 ||
139 strcmp(buf, "iso-8859-1") == 0 ||
140 strcmp(buf, "iso-latin-1") == 0 ||
141 strncmp(buf, "latin-1-", 8) == 0 ||
142 strncmp(buf, "iso-8859-1-", 11) == 0 ||
143 strncmp(buf, "iso-latin-1-", 12) == 0)
144 return "iso-8859-1";
145 else
146 return s;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000147}
148
149/* Return the coding spec in S, or NULL if none is found. */
150
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700151static int
152get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok)
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 Py_ssize_t i;
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700155 *spec = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 /* Coding spec must be in a comment, and that comment must be
157 * the only statement on the source code line. */
158 for (i = 0; i < size - 6; i++) {
159 if (s[i] == '#')
160 break;
161 if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700162 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 for (; i < size - 6; i++) { /* XXX inefficient search */
165 const char* t = s + i;
166 if (strncmp(t, "coding", 6) == 0) {
167 const char* begin = NULL;
168 t += 6;
169 if (t[0] != ':' && t[0] != '=')
170 continue;
171 do {
172 t++;
173 } while (t[0] == '\x20' || t[0] == '\t');
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 begin = t;
176 while (Py_ISALNUM(t[0]) ||
177 t[0] == '-' || t[0] == '_' || t[0] == '.')
178 t++;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (begin < t) {
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700181 char* r = new_string(begin, t - begin, tok);
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200182 const char* q;
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700183 if (!r)
184 return 0;
Benjamin Peterson265fba42013-07-15 20:50:22 -0700185 q = get_normal_name(r);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (r != q) {
187 PyMem_FREE(r);
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700188 r = new_string(q, strlen(q), tok);
189 if (!r)
190 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700192 *spec = r;
Serhiy Storchakae431d3c2016-03-20 23:36:29 +0200193 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 }
195 }
196 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700197 return 1;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000198}
199
200/* Check whether the line contains a coding spec. If it does,
201 invoke the set_readline function for the new encoding.
202 This function receives the tok_state and the new encoding.
203 Return 1 on success, 0 on failure. */
204
205static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 int set_readline(struct tok_state *, const char *))
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000208{
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700209 char *cs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 int r = 1;
Tim Peters17db21f2002-09-03 15:39:58 +0000211
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200212 if (tok->cont_line) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* It's a continuation line, so it can't be a coding spec. */
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200214 tok->read_coding_spec = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 return 1;
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200216 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700217 if (!get_coding_spec(line, &cs, size, tok))
218 return 0;
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200219 if (!cs) {
220 Py_ssize_t i;
221 for (i = 0; i < size; i++) {
222 if (line[i] == '#' || line[i] == '\n' || line[i] == '\r')
223 break;
224 if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') {
225 /* Stop checking coding spec after a line containing
226 * anything except a comment. */
227 tok->read_coding_spec = 1;
228 break;
229 }
230 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700231 return 1;
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200232 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700233 tok->read_coding_spec = 1;
234 if (tok->encoding == NULL) {
235 assert(tok->decoding_state == STATE_RAW);
236 if (strcmp(cs, "utf-8") == 0) {
237 tok->encoding = cs;
238 } else {
239 r = set_readline(tok, cs);
240 if (r) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 tok->encoding = cs;
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700242 tok->decoding_state = STATE_NORMAL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700244 else {
Serhiy Storchaka3af14aa2013-06-09 16:51:52 +0300245 PyErr_Format(PyExc_SyntaxError,
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700246 "encoding problem: %s", cs);
247 PyMem_FREE(cs);
248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 }
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700250 } else { /* then, compare cs with BOM */
251 r = (strcmp(tok->encoding, cs) == 0);
252 if (!r)
253 PyErr_Format(PyExc_SyntaxError,
254 "encoding problem: %s with BOM", cs);
255 PyMem_FREE(cs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return r;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000258}
259
260/* See whether the file starts with a BOM. If it does,
261 invoke the set_readline function with the new encoding.
262 Return 1 on success, 0 on failure. */
263
264static int
265check_bom(int get_char(struct tok_state *),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 void unget_char(int, struct tok_state *),
267 int set_readline(struct tok_state *, const char *),
268 struct tok_state *tok)
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 int ch1, ch2, ch3;
271 ch1 = get_char(tok);
272 tok->decoding_state = STATE_RAW;
273 if (ch1 == EOF) {
274 return 1;
275 } else if (ch1 == 0xEF) {
276 ch2 = get_char(tok);
277 if (ch2 != 0xBB) {
278 unget_char(ch2, tok);
279 unget_char(ch1, tok);
280 return 1;
281 }
282 ch3 = get_char(tok);
283 if (ch3 != 0xBF) {
284 unget_char(ch3, tok);
285 unget_char(ch2, tok);
286 unget_char(ch1, tok);
287 return 1;
288 }
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000289#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Disable support for UTF-16 BOMs until a decision
291 is made whether this needs to be supported. */
292 } else if (ch1 == 0xFE) {
293 ch2 = get_char(tok);
294 if (ch2 != 0xFF) {
295 unget_char(ch2, tok);
296 unget_char(ch1, tok);
297 return 1;
298 }
299 if (!set_readline(tok, "utf-16-be"))
300 return 0;
301 tok->decoding_state = STATE_NORMAL;
302 } else if (ch1 == 0xFF) {
303 ch2 = get_char(tok);
304 if (ch2 != 0xFE) {
305 unget_char(ch2, tok);
306 unget_char(ch1, tok);
307 return 1;
308 }
309 if (!set_readline(tok, "utf-16-le"))
310 return 0;
311 tok->decoding_state = STATE_NORMAL;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000312#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 } else {
314 unget_char(ch1, tok);
315 return 1;
316 }
317 if (tok->encoding != NULL)
318 PyMem_FREE(tok->encoding);
Benjamin Peterson2dbfd882013-07-15 19:15:34 -0700319 tok->encoding = new_string("utf-8", 5, tok);
320 if (!tok->encoding)
321 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 /* No need to set_readline: input is already utf-8 */
323 return 1;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000324}
325
326/* Read a line of text from TOK into S, using the stream in TOK.
Walter Dörwaldc1f5fff2005-07-12 21:53:43 +0000327 Return NULL on failure, else S.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328
Walter Dörwaldc1f5fff2005-07-12 21:53:43 +0000329 On entry, tok->decoding_buffer will be one of:
330 1) NULL: need to call tok->decoding_readline to get a new line
331 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 stored the result in tok->decoding_buffer
Christian Heimes9c4756e2008-05-26 13:22:05 +0000333 3) PyByteArrayObject *: previous call to fp_readl did not have enough room
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 (in the s buffer) to copy entire contents of the line read
335 by tok->decoding_readline. tok->decoding_buffer has the overflow.
336 In this case, fp_readl is called in a loop (with an expanded buffer)
337 until the buffer ends with a '\n' (or until the end of the file is
338 reached): see tok_nextc and its calls to decoding_fgets.
Walter Dörwaldc1f5fff2005-07-12 21:53:43 +0000339*/
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000340
341static char *
342fp_readl(char *s, int size, struct tok_state *tok)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyObject* bufobj;
345 const char *buf;
346 Py_ssize_t buflen;
Walter Dörwaldc1f5fff2005-07-12 21:53:43 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* Ask for one less byte so we can terminate it */
349 assert(size > 0);
350 size--;
Walter Dörwaldc1f5fff2005-07-12 21:53:43 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (tok->decoding_buffer) {
353 bufobj = tok->decoding_buffer;
354 Py_INCREF(bufobj);
355 }
356 else
357 {
Victor Stinnera5ed5f02016-12-06 18:45:50 +0100358 bufobj = _PyObject_CallNoArg(tok->decoding_readline);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (bufobj == NULL)
360 goto error;
361 }
362 if (PyUnicode_CheckExact(bufobj))
363 {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200364 buf = PyUnicode_AsUTF8AndSize(bufobj, &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (buf == NULL) {
366 goto error;
367 }
368 }
369 else
370 {
371 buf = PyByteArray_AsString(bufobj);
372 if (buf == NULL) {
373 goto error;
374 }
375 buflen = PyByteArray_GET_SIZE(bufobj);
376 }
Amaury Forgeot d'Arc65f9ace2007-11-15 23:19:43 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 Py_XDECREF(tok->decoding_buffer);
379 if (buflen > size) {
380 /* Too many chars, the rest goes into tok->decoding_buffer */
381 tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size,
382 buflen-size);
383 if (tok->decoding_buffer == NULL)
384 goto error;
385 buflen = size;
386 }
387 else
388 tok->decoding_buffer = NULL;
Amaury Forgeot d'Arc65f9ace2007-11-15 23:19:43 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 memcpy(s, buf, buflen);
391 s[buflen] = '\0';
392 if (buflen == 0) /* EOF */
393 s = NULL;
394 Py_DECREF(bufobj);
395 return s;
Neal Norwitz41eaedd2007-08-12 00:03:22 +0000396
397error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_XDECREF(bufobj);
399 return error_ret(tok);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000400}
401
402/* Set the readline function for TOK to a StreamReader's
403 readline function. The StreamReader is named ENC.
404
405 This function is called from check_bom and check_coding_spec.
406
407 ENC is usually identical to the future value of tok->encoding,
408 except for the (currently unsupported) case of UTF-16.
409
410 Return 1 on success, 0 on failure. */
411
412static int
413fp_setreadl(struct tok_state *tok, const char* enc)
414{
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700415 PyObject *readline, *io, *stream;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200416 _Py_IDENTIFIER(open);
417 _Py_IDENTIFIER(readline);
Victor Stinner22a351a2010-10-14 12:04:34 +0000418 int fd;
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200419 long pos;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000420
Victor Stinner22a351a2010-10-14 12:04:34 +0000421 fd = fileno(tok->fp);
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200422 /* Due to buffering the file offset for fd can be different from the file
Martin v. Löwis815b41b2014-02-28 15:27:29 +0100423 * position of tok->fp. If tok->fp was opened in text mode on Windows,
424 * its file position counts CRLF as one char and can't be directly mapped
425 * to the file offset for fd. Instead we step back one byte and read to
426 * the end of line.*/
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200427 pos = ftell(tok->fp);
Martin v. Löwis815b41b2014-02-28 15:27:29 +0100428 if (pos == -1 ||
429 lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {
Victor Stinner22a351a2010-10-14 12:04:34 +0000430 PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700431 return 0;
Victor Stinner22a351a2010-10-14 12:04:34 +0000432 }
433
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700434 io = PyImport_ImportModuleNoBlock("io");
435 if (io == NULL)
436 return 0;
437
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200438 stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO",
Victor Stinner22a351a2010-10-14 12:04:34 +0000439 fd, "r", -1, enc, Py_None, Py_None, Py_False);
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700440 Py_DECREF(io);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (stream == NULL)
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700442 return 0;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000443
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200444 readline = _PyObject_GetAttrId(stream, &PyId_readline);
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700445 Py_DECREF(stream);
446 if (readline == NULL)
447 return 0;
Serhiy Storchaka48842712016-04-06 09:45:48 +0300448 Py_XSETREF(tok->decoding_readline, readline);
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700449
Martin v. Löwis815b41b2014-02-28 15:27:29 +0100450 if (pos > 0) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +0100451 PyObject *bufobj = _PyObject_CallNoArg(readline);
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700452 if (bufobj == NULL)
453 return 0;
454 Py_DECREF(bufobj);
Martin v. Löwis815b41b2014-02-28 15:27:29 +0100455 }
Guido van Rossum9cbfffd2007-06-07 00:54:15 +0000456
Benjamin Peterson35ee9482016-09-12 22:06:58 -0700457 return 1;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000458}
459
460/* Fetch the next byte from TOK. */
461
462static int fp_getc(struct tok_state *tok) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return getc(tok->fp);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000464}
465
466/* Unfetch the last byte back into TOK. */
467
468static void fp_ungetc(int c, struct tok_state *tok) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 ungetc(c, tok->fp);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000470}
471
Martin v. Löwis447d33e2007-07-29 18:10:01 +0000472/* Check whether the characters at s start a valid
473 UTF-8 sequence. Return the number of characters forming
474 the sequence if yes, 0 if not. */
475static int valid_utf8(const unsigned char* s)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 int expected = 0;
478 int length;
479 if (*s < 0x80)
480 /* single-byte code */
481 return 1;
482 if (*s < 0xc0)
483 /* following byte */
484 return 0;
485 if (*s < 0xE0)
486 expected = 1;
487 else if (*s < 0xF0)
488 expected = 2;
489 else if (*s < 0xF8)
490 expected = 3;
491 else
492 return 0;
493 length = expected + 1;
494 for (; expected; expected--)
495 if (s[expected] < 0x80 || s[expected] >= 0xC0)
496 return 0;
497 return length;
Martin v. Löwis447d33e2007-07-29 18:10:01 +0000498}
499
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000500/* Read a line of input from TOK. Determine encoding
501 if necessary. */
502
503static char *
504decoding_fgets(char *s, int size, struct tok_state *tok)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 char *line = NULL;
507 int badchar = 0;
508 for (;;) {
509 if (tok->decoding_state == STATE_NORMAL) {
510 /* We already have a codec associated with
511 this input. */
512 line = fp_readl(s, size, tok);
513 break;
514 } else if (tok->decoding_state == STATE_RAW) {
515 /* We want a 'raw' read. */
516 line = Py_UniversalNewlineFgets(s, size,
517 tok->fp, NULL);
518 break;
519 } else {
520 /* We have not yet determined the encoding.
521 If an encoding is found, use the file-pointer
522 reader functions from now on. */
523 if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok))
524 return error_ret(tok);
525 assert(tok->decoding_state != STATE_INIT);
526 }
527 }
528 if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) {
529 if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) {
530 return error_ret(tok);
531 }
532 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* The default encoding is UTF-8, so make sure we don't have any
534 non-UTF-8 sequences in it. */
535 if (line && !tok->encoding) {
536 unsigned char *c;
537 int length;
538 for (c = (unsigned char *)line; *c; c += length)
539 if (!(length = valid_utf8(c))) {
540 badchar = *c;
541 break;
542 }
543 }
544 if (badchar) {
545 /* Need to add 1 to the line number, since this line
546 has not been counted, yet. */
Jesus Ceac1935d22011-04-25 04:03:58 +0200547 PyErr_Format(PyExc_SyntaxError,
548 "Non-UTF-8 code starting with '\\x%.2x' "
549 "in file %U on line %i, "
550 "but no encoding declared; "
551 "see http://python.org/dev/peps/pep-0263/ for details",
552 badchar, tok->filename, tok->lineno + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return error_ret(tok);
554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return line;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000556}
557
558static int
559decoding_feof(struct tok_state *tok)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (tok->decoding_state != STATE_NORMAL) {
562 return feof(tok->fp);
563 } else {
564 PyObject* buf = tok->decoding_buffer;
565 if (buf == NULL) {
Victor Stinnera5ed5f02016-12-06 18:45:50 +0100566 buf = _PyObject_CallNoArg(tok->decoding_readline);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (buf == NULL) {
568 error_ret(tok);
569 return 1;
570 } else {
571 tok->decoding_buffer = buf;
572 }
573 }
574 return PyObject_Length(buf) == 0;
575 }
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000576}
577
578/* Fetch a byte from TOK, using the string buffer. */
579
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580static int
581buf_getc(struct tok_state *tok) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return Py_CHARMASK(*tok->str++);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000583}
584
585/* Unfetch a byte from TOK, using the string buffer. */
586
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000587static void
588buf_ungetc(int c, struct tok_state *tok) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 tok->str--;
590 assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000591}
592
593/* Set the readline function for TOK to ENC. For the string-based
594 tokenizer, this means to just record the encoding. */
595
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000596static int
597buf_setreadl(struct tok_state *tok, const char* enc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 tok->enc = enc;
599 return 1;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000600}
601
602/* Return a UTF-8 encoding Python string object from the
603 C byte string STR, which is encoded with ENC. */
604
605static PyObject *
606translate_into_utf8(const char* str, const char* enc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyObject *utf8;
608 PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
609 if (buf == NULL)
610 return NULL;
611 utf8 = PyUnicode_AsUTF8String(buf);
612 Py_DECREF(buf);
613 return utf8;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000614}
615
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000616
617static char *
618translate_newlines(const char *s, int exec_input, struct tok_state *tok) {
Victor Stinner79697732013-06-05 00:44:00 +0200619 int skip_next_lf = 0;
620 size_t needed_length = strlen(s) + 2, final_length;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 char *buf, *current;
622 char c = '\0';
623 buf = PyMem_MALLOC(needed_length);
624 if (buf == NULL) {
625 tok->done = E_NOMEM;
626 return NULL;
627 }
628 for (current = buf; *s; s++, current++) {
629 c = *s;
630 if (skip_next_lf) {
631 skip_next_lf = 0;
632 if (c == '\n') {
633 c = *++s;
634 if (!c)
635 break;
636 }
637 }
638 if (c == '\r') {
639 skip_next_lf = 1;
640 c = '\n';
641 }
642 *current = c;
643 }
644 /* If this is exec input, add a newline to the end of the string if
645 there isn't one already. */
646 if (exec_input && c != '\n') {
647 *current = '\n';
648 current++;
649 }
650 *current = '\0';
651 final_length = current - buf + 1;
Pablo Galindocb90c892019-03-19 17:17:58 +0000652 if (final_length < needed_length && final_length) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* should never fail */
Pablo Galindocb90c892019-03-19 17:17:58 +0000654 char* result = PyMem_REALLOC(buf, final_length);
655 if (result == NULL) {
656 PyMem_FREE(buf);
657 }
658 buf = result;
659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return buf;
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000661}
662
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000663/* Decode a byte string STR for use as the buffer of TOK.
664 Look for encoding declarations inside STR, and record them
665 inside TOK. */
666
Andy Lester384f3c52020-02-27 20:44:52 -0600667static char *
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000668decode_str(const char *input, int single, struct tok_state *tok)
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject* utf8 = NULL;
Andy Lester384f3c52020-02-27 20:44:52 -0600671 char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 const char *s;
673 const char *newl[2] = {NULL, NULL};
674 int lineno = 0;
675 tok->input = str = translate_newlines(input, single, tok);
676 if (str == NULL)
677 return NULL;
678 tok->enc = NULL;
679 tok->str = str;
680 if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok))
681 return error_ret(tok);
682 str = tok->str; /* string after BOM if any */
683 assert(str);
684 if (tok->enc != NULL) {
685 utf8 = translate_into_utf8(str, tok->enc);
686 if (utf8 == NULL)
687 return error_ret(tok);
688 str = PyBytes_AsString(utf8);
689 }
690 for (s = str;; s++) {
691 if (*s == '\0') break;
692 else if (*s == '\n') {
693 assert(lineno < 2);
694 newl[lineno] = s;
695 lineno++;
696 if (lineno == 2) break;
697 }
698 }
699 tok->enc = NULL;
700 /* need to check line 1 and 2 separately since check_coding_spec
701 assumes a single line as input */
702 if (newl[0]) {
703 if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl))
704 return error_ret(tok);
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200705 if (tok->enc == NULL && !tok->read_coding_spec && newl[1]) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (!check_coding_spec(newl[0]+1, newl[1] - newl[0],
707 tok, buf_setreadl))
708 return error_ret(tok);
709 }
710 }
711 if (tok->enc != NULL) {
712 assert(utf8 == NULL);
713 utf8 = translate_into_utf8(str, tok->enc);
714 if (utf8 == NULL)
715 return error_ret(tok);
716 str = PyBytes_AS_STRING(utf8);
717 }
718 assert(tok->decoding_buffer == NULL);
719 tok->decoding_buffer = utf8; /* CAUTION */
720 return str;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000721}
722
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723/* Set up tokenizer for string */
724
725struct tok_state *
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000726PyTokenizer_FromString(const char *str, int exec_input)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 struct tok_state *tok = tok_new();
Andy Lester384f3c52020-02-27 20:44:52 -0600729 char *decoded;
730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (tok == NULL)
732 return NULL;
Andy Lester384f3c52020-02-27 20:44:52 -0600733 decoded = decode_str(str, exec_input, tok);
734 if (decoded == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyTokenizer_Free(tok);
736 return NULL;
737 }
Neal Norwitzdee2fd52005-11-16 05:12:59 +0000738
Andy Lester384f3c52020-02-27 20:44:52 -0600739 tok->buf = tok->cur = tok->inp = decoded;
740 tok->end = decoded;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return tok;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742}
743
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000744struct tok_state *
Benjamin Petersonaeaa5922009-11-13 00:17:59 +0000745PyTokenizer_FromUTF8(const char *str, int exec_input)
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 struct tok_state *tok = tok_new();
Andy Lester384f3c52020-02-27 20:44:52 -0600748 char *translated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (tok == NULL)
750 return NULL;
Andy Lester384f3c52020-02-27 20:44:52 -0600751 tok->input = translated = translate_newlines(str, exec_input, tok);
752 if (translated == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyTokenizer_Free(tok);
754 return NULL;
755 }
756 tok->decoding_state = STATE_RAW;
757 tok->read_coding_spec = 1;
758 tok->enc = NULL;
Andy Lester384f3c52020-02-27 20:44:52 -0600759 tok->str = translated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 tok->encoding = (char *)PyMem_MALLOC(6);
761 if (!tok->encoding) {
762 PyTokenizer_Free(tok);
763 return NULL;
764 }
765 strcpy(tok->encoding, "utf-8");
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000766
Andy Lester384f3c52020-02-27 20:44:52 -0600767 tok->buf = tok->cur = tok->inp = translated;
768 tok->end = translated;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return tok;
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000770}
771
Guido van Rossum8c11a5c1991-07-27 21:42:56 +0000772/* Set up tokenizer for file */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773
774struct tok_state *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300775PyTokenizer_FromFile(FILE *fp, const char* enc,
776 const char *ps1, const char *ps2)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 struct tok_state *tok = tok_new();
779 if (tok == NULL)
780 return NULL;
781 if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) {
782 PyTokenizer_Free(tok);
783 return NULL;
784 }
785 tok->cur = tok->inp = tok->buf;
786 tok->end = tok->buf + BUFSIZ;
787 tok->fp = fp;
788 tok->prompt = ps1;
789 tok->nextprompt = ps2;
790 if (enc != NULL) {
791 /* Must copy encoding declaration since it
792 gets copied into the parse tree. */
793 tok->encoding = PyMem_MALLOC(strlen(enc)+1);
794 if (!tok->encoding) {
795 PyTokenizer_Free(tok);
796 return NULL;
797 }
798 strcpy(tok->encoding, enc);
799 tok->decoding_state = STATE_NORMAL;
800 }
801 return tok;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802}
803
804
805/* Free a tok_state structure */
806
807void
Thomas Wouters23c9e002000-07-22 19:20:54 +0000808PyTokenizer_Free(struct tok_state *tok)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (tok->encoding != NULL)
811 PyMem_FREE(tok->encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_XDECREF(tok->decoding_readline);
813 Py_XDECREF(tok->decoding_buffer);
Victor Stinner7f2fee32011-04-05 00:39:01 +0200814 Py_XDECREF(tok->filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (tok->fp != NULL && tok->buf != NULL)
816 PyMem_FREE(tok->buf);
817 if (tok->input)
Andy Lester384f3c52020-02-27 20:44:52 -0600818 PyMem_FREE(tok->input);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyMem_FREE(tok);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000820}
821
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000822/* Get next char, updating state; error code goes into tok->done */
823
824static int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200825tok_nextc(struct tok_state *tok)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 for (;;) {
828 if (tok->cur != tok->inp) {
829 return Py_CHARMASK(*tok->cur++); /* Fast path */
830 }
831 if (tok->done != E_OK)
832 return EOF;
833 if (tok->fp == NULL) {
834 char *end = strchr(tok->inp, '\n');
835 if (end != NULL)
836 end++;
837 else {
838 end = strchr(tok->inp, '\0');
839 if (end == tok->inp) {
840 tok->done = E_EOF;
841 return EOF;
842 }
843 }
844 if (tok->start == NULL)
845 tok->buf = tok->cur;
846 tok->line_start = tok->cur;
847 tok->lineno++;
848 tok->inp = end;
849 return Py_CHARMASK(*tok->cur++);
850 }
851 if (tok->prompt != NULL) {
852 char *newtok = PyOS_Readline(stdin, stdout, tok->prompt);
Victor Stinner89e34362011-01-07 18:47:22 +0000853 if (newtok != NULL) {
854 char *translated = translate_newlines(newtok, 0, tok);
855 PyMem_FREE(newtok);
856 if (translated == NULL)
857 return EOF;
858 newtok = translated;
859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (tok->encoding && newtok && *newtok) {
861 /* Recode to UTF-8 */
862 Py_ssize_t buflen;
863 const char* buf;
864 PyObject *u = translate_into_utf8(newtok, tok->encoding);
865 PyMem_FREE(newtok);
866 if (!u) {
867 tok->done = E_DECODE;
868 return EOF;
869 }
870 buflen = PyBytes_GET_SIZE(u);
871 buf = PyBytes_AS_STRING(u);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 newtok = PyMem_MALLOC(buflen+1);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700873 if (newtok == NULL) {
874 Py_DECREF(u);
875 tok->done = E_NOMEM;
876 return EOF;
877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 strcpy(newtok, buf);
879 Py_DECREF(u);
880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (tok->nextprompt != NULL)
882 tok->prompt = tok->nextprompt;
883 if (newtok == NULL)
884 tok->done = E_INTR;
885 else if (*newtok == '\0') {
886 PyMem_FREE(newtok);
887 tok->done = E_EOF;
888 }
889 else if (tok->start != NULL) {
890 size_t start = tok->start - tok->buf;
891 size_t oldlen = tok->cur - tok->buf;
892 size_t newlen = oldlen + strlen(newtok);
Pablo Galindo5ec91f72020-01-06 15:59:09 +0000893 Py_ssize_t cur_multi_line_start = tok->multi_line_start - tok->buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 char *buf = tok->buf;
895 buf = (char *)PyMem_REALLOC(buf, newlen+1);
896 tok->lineno++;
897 if (buf == NULL) {
898 PyMem_FREE(tok->buf);
899 tok->buf = NULL;
900 PyMem_FREE(newtok);
901 tok->done = E_NOMEM;
902 return EOF;
903 }
904 tok->buf = buf;
905 tok->cur = tok->buf + oldlen;
Pablo Galindo5ec91f72020-01-06 15:59:09 +0000906 tok->multi_line_start = tok->buf + cur_multi_line_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 tok->line_start = tok->cur;
908 strcpy(tok->buf + oldlen, newtok);
909 PyMem_FREE(newtok);
910 tok->inp = tok->buf + newlen;
911 tok->end = tok->inp + 1;
912 tok->start = tok->buf + start;
913 }
914 else {
915 tok->lineno++;
916 if (tok->buf != NULL)
917 PyMem_FREE(tok->buf);
918 tok->buf = newtok;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 tok->cur = tok->buf;
920 tok->line_start = tok->buf;
921 tok->inp = strchr(tok->buf, '\0');
922 tok->end = tok->inp + 1;
923 }
924 }
925 else {
926 int done = 0;
927 Py_ssize_t cur = 0;
928 char *pt;
929 if (tok->start == NULL) {
930 if (tok->buf == NULL) {
931 tok->buf = (char *)
932 PyMem_MALLOC(BUFSIZ);
933 if (tok->buf == NULL) {
934 tok->done = E_NOMEM;
935 return EOF;
936 }
937 tok->end = tok->buf + BUFSIZ;
938 }
939 if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf),
940 tok) == NULL) {
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200941 if (!tok->decoding_erred)
942 tok->done = E_EOF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 done = 1;
944 }
945 else {
946 tok->done = E_OK;
947 tok->inp = strchr(tok->buf, '\0');
Benjamin Peterson26d998c2016-09-18 23:41:11 -0700948 done = tok->inp == tok->buf || tok->inp[-1] == '\n';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 }
950 }
951 else {
952 cur = tok->cur - tok->buf;
953 if (decoding_feof(tok)) {
954 tok->done = E_EOF;
955 done = 1;
956 }
957 else
958 tok->done = E_OK;
959 }
960 tok->lineno++;
961 /* Read until '\n' or EOF */
962 while (!done) {
963 Py_ssize_t curstart = tok->start == NULL ? -1 :
964 tok->start - tok->buf;
Anthony Sottile5b94f352019-07-29 06:59:13 -0700965 Py_ssize_t cur_multi_line_start = tok->multi_line_start - tok->buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 Py_ssize_t curvalid = tok->inp - tok->buf;
967 Py_ssize_t newsize = curvalid + BUFSIZ;
968 char *newbuf = tok->buf;
969 newbuf = (char *)PyMem_REALLOC(newbuf,
970 newsize);
971 if (newbuf == NULL) {
972 tok->done = E_NOMEM;
973 tok->cur = tok->inp;
974 return EOF;
975 }
976 tok->buf = newbuf;
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200977 tok->cur = tok->buf + cur;
Anthony Sottile5b94f352019-07-29 06:59:13 -0700978 tok->multi_line_start = tok->buf + cur_multi_line_start;
Serhiy Storchaka0d441112015-11-14 15:10:35 +0200979 tok->line_start = tok->cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 tok->inp = tok->buf + curvalid;
981 tok->end = tok->buf + newsize;
982 tok->start = curstart < 0 ? NULL :
983 tok->buf + curstart;
984 if (decoding_fgets(tok->inp,
985 (int)(tok->end - tok->inp),
986 tok) == NULL) {
987 /* Break out early on decoding
988 errors, as tok->buf will be NULL
989 */
990 if (tok->decoding_erred)
991 return EOF;
992 /* Last line does not end in \n,
993 fake one */
Anthony Sottileabea73b2019-05-18 11:27:17 -0700994 if (tok->inp[-1] != '\n')
995 strcpy(tok->inp, "\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 tok->inp = strchr(tok->inp, '\0');
998 done = tok->inp[-1] == '\n';
999 }
1000 if (tok->buf != NULL) {
1001 tok->cur = tok->buf + cur;
1002 tok->line_start = tok->cur;
1003 /* replace "\r\n" with "\n" */
1004 /* For Mac leave the \r, giving a syntax error */
1005 pt = tok->inp - 2;
1006 if (pt >= tok->buf && *pt == '\r') {
1007 *pt++ = '\n';
1008 *pt = '\0';
1009 tok->inp = pt;
1010 }
1011 }
1012 }
1013 if (tok->done != E_OK) {
1014 if (tok->prompt != NULL)
1015 PySys_WriteStderr("\n");
1016 tok->cur = tok->inp;
1017 return EOF;
1018 }
1019 }
1020 /*NOTREACHED*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001021}
1022
1023
1024/* Back-up one character */
1025
1026static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001027tok_backup(struct tok_state *tok, int c)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (c != EOF) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001030 if (--tok->cur < tok->buf) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001031 Py_FatalError("tokenizer beginning of buffer");
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001032 }
1033 if (*tok->cur != c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 *tok->cur = c;
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001035 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001037}
1038
1039
Guido van Rossum926f13a1998-04-09 21:38:06 +00001040static int
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001041syntaxerror(struct tok_state *tok, const char *format, ...)
1042{
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +02001043 PyObject *errmsg, *errtext, *args;
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001044 va_list vargs;
1045#ifdef HAVE_STDARG_PROTOTYPES
1046 va_start(vargs, format);
1047#else
1048 va_start(vargs);
1049#endif
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +02001050 errmsg = PyUnicode_FromFormatV(format, vargs);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001051 va_end(vargs);
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +02001052 if (!errmsg) {
1053 goto error;
1054 }
1055
1056 errtext = PyUnicode_DecodeUTF8(tok->line_start, tok->cur - tok->line_start,
1057 "replace");
1058 if (!errtext) {
1059 goto error;
1060 }
1061 int offset = (int)PyUnicode_GET_LENGTH(errtext);
1062 Py_ssize_t line_len = strcspn(tok->line_start, "\n");
1063 if (line_len != tok->cur - tok->line_start) {
1064 Py_DECREF(errtext);
1065 errtext = PyUnicode_DecodeUTF8(tok->line_start, line_len,
1066 "replace");
1067 }
1068 if (!errtext) {
1069 goto error;
1070 }
1071
1072 args = Py_BuildValue("(O(OiiN))", errmsg,
1073 tok->filename, tok->lineno, offset, errtext);
1074 if (args) {
1075 PyErr_SetObject(PyExc_SyntaxError, args);
1076 Py_DECREF(args);
1077 }
1078
1079error:
1080 Py_XDECREF(errmsg);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001081 tok->done = E_ERROR;
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001082 return ERRORTOKEN;
1083}
1084
1085static int
Thomas Wouters23c9e002000-07-22 19:20:54 +00001086indenterror(struct tok_state *tok)
Guido van Rossum926f13a1998-04-09 21:38:06 +00001087{
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -08001088 tok->done = E_TABSPACE;
1089 tok->cur = tok->inp;
1090 return ERRORTOKEN;
Guido van Rossum926f13a1998-04-09 21:38:06 +00001091}
1092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001093/* Verify that the identifier follows PEP 3131.
1094 All identifier strings are guaranteed to be "ready" unicode objects.
1095 */
Martin v. Löwis47383402007-08-15 07:32:56 +00001096static int
Victor Stinner52f6dd72010-03-12 14:45:56 +00001097verify_identifier(struct tok_state *tok)
Martin v. Löwis47383402007-08-15 07:32:56 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *s;
Benjamin Petersond73aca72015-04-21 12:05:19 -04001100 if (tok->decoding_erred)
1101 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL);
Zackery Spytz5061a742018-09-10 00:27:31 -06001103 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +03001105 tok->done = E_DECODE;
1106 }
1107 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 tok->done = E_ERROR;
1109 }
1110 return 0;
1111 }
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +03001112 Py_ssize_t invalid = _PyUnicode_ScanIdentifier(s);
1113 if (invalid < 0) {
1114 Py_DECREF(s);
1115 tok->done = E_ERROR;
1116 return 0;
Victor Stinnerf3e7ea52020-02-11 14:29:33 +01001117 }
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +03001118 assert(PyUnicode_GET_LENGTH(s) > 0);
1119 if (invalid < PyUnicode_GET_LENGTH(s)) {
1120 Py_UCS4 ch = PyUnicode_READ_CHAR(s, invalid);
1121 if (invalid + 1 < PyUnicode_GET_LENGTH(s)) {
1122 /* Determine the offset in UTF-8 encoded input */
1123 Py_SETREF(s, PyUnicode_Substring(s, 0, invalid + 1));
1124 if (s != NULL) {
1125 Py_SETREF(s, PyUnicode_AsUTF8String(s));
1126 }
1127 if (s == NULL) {
1128 tok->done = E_ERROR;
1129 return 0;
1130 }
1131 tok->cur = (char *)tok->start + PyBytes_GET_SIZE(s);
1132 }
1133 Py_DECREF(s);
1134 // PyUnicode_FromFormatV() does not support %X
1135 char hex[9];
Victor Stinnere822e372020-06-15 21:59:47 +02001136 (void)PyOS_snprintf(hex, sizeof(hex), "%04X", ch);
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +03001137 if (Py_UNICODE_ISPRINTABLE(ch)) {
1138 syntaxerror(tok, "invalid character '%c' (U+%s)", ch, hex);
1139 }
1140 else {
1141 syntaxerror(tok, "invalid non-printable character U+%s", hex);
1142 }
1143 return 0;
1144 }
1145 Py_DECREF(s);
1146 return 1;
Martin v. Löwis47383402007-08-15 07:32:56 +00001147}
Guido van Rossum926f13a1998-04-09 21:38:06 +00001148
Brett Cannona721aba2016-09-09 14:57:09 -07001149static int
1150tok_decimal_tail(struct tok_state *tok)
1151{
1152 int c;
1153
1154 while (1) {
1155 do {
1156 c = tok_nextc(tok);
1157 } while (isdigit(c));
1158 if (c != '_') {
1159 break;
1160 }
1161 c = tok_nextc(tok);
1162 if (!isdigit(c)) {
Brett Cannona721aba2016-09-09 14:57:09 -07001163 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001164 syntaxerror(tok, "invalid decimal literal");
Brett Cannona721aba2016-09-09 14:57:09 -07001165 return 0;
1166 }
1167 }
1168 return c;
1169}
1170
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001171/* Get next token, after space stripping etc. */
1172
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001173static int
Andy Lester384f3c52020-02-27 20:44:52 -06001174tok_get(struct tok_state *tok, const char **p_start, const char **p_end)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001175{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001176 int c;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 int blankline, nonascii;
Guido van Rossum8c11a5c1991-07-27 21:42:56 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 *p_start = *p_end = NULL;
Guido van Rossum8c11a5c1991-07-27 21:42:56 +00001180 nextline:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 tok->start = NULL;
1182 blankline = 0;
Guido van Rossum8c11a5c1991-07-27 21:42:56 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Get indentation level */
1185 if (tok->atbol) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001186 int col = 0;
1187 int altcol = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 tok->atbol = 0;
1189 for (;;) {
1190 c = tok_nextc(tok);
Brett Cannona721aba2016-09-09 14:57:09 -07001191 if (c == ' ') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 col++, altcol++;
Brett Cannona721aba2016-09-09 14:57:09 -07001193 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 else if (c == '\t') {
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -08001195 col = (col / tok->tabsize + 1) * tok->tabsize;
1196 altcol = (altcol / ALTTABSIZE + 1) * ALTTABSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 }
Brett Cannona721aba2016-09-09 14:57:09 -07001198 else if (c == '\014') {/* Control-L (formfeed) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 col = altcol = 0; /* For Emacs users */
Brett Cannona721aba2016-09-09 14:57:09 -07001200 }
1201 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 break;
Brett Cannona721aba2016-09-09 14:57:09 -07001203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 }
1205 tok_backup(tok, c);
Lysandros Nikolaou896f4cf2020-06-11 02:56:08 +03001206 if (c == '#' || c == '\n' || c == '\\') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 /* Lines with only whitespace and/or comments
Lysandros Nikolaou896f4cf2020-06-11 02:56:08 +03001208 and/or a line continuation character
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 shouldn't affect the indentation and are
1210 not passed to the parser as NEWLINE tokens,
1211 except *totally* empty lines in interactive
1212 mode, which signal the end of a command group. */
Brett Cannona721aba2016-09-09 14:57:09 -07001213 if (col == 0 && c == '\n' && tok->prompt != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 blankline = 0; /* Let it through */
Brett Cannona721aba2016-09-09 14:57:09 -07001215 }
Batuhan Taşkaya109fc272019-12-09 07:36:27 +03001216 else if (tok->prompt != NULL && tok->lineno == 1) {
1217 /* In interactive mode, if the first line contains
1218 only spaces and/or a comment, let it through. */
1219 blankline = 0;
1220 col = altcol = 0;
1221 }
Brett Cannona721aba2016-09-09 14:57:09 -07001222 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 blankline = 1; /* Ignore completely */
Brett Cannona721aba2016-09-09 14:57:09 -07001224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* We can't jump back right here since we still
1226 may need to skip to the end of a comment */
1227 }
1228 if (!blankline && tok->level == 0) {
1229 if (col == tok->indstack[tok->indent]) {
1230 /* No change */
1231 if (altcol != tok->altindstack[tok->indent]) {
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -08001232 return indenterror(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 }
1234 }
1235 else if (col > tok->indstack[tok->indent]) {
1236 /* Indent -- always one */
1237 if (tok->indent+1 >= MAXINDENT) {
1238 tok->done = E_TOODEEP;
1239 tok->cur = tok->inp;
1240 return ERRORTOKEN;
1241 }
1242 if (altcol <= tok->altindstack[tok->indent]) {
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -08001243 return indenterror(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 }
1245 tok->pendin++;
1246 tok->indstack[++tok->indent] = col;
1247 tok->altindstack[tok->indent] = altcol;
1248 }
1249 else /* col < tok->indstack[tok->indent] */ {
1250 /* Dedent -- any number, must be consistent */
1251 while (tok->indent > 0 &&
1252 col < tok->indstack[tok->indent]) {
1253 tok->pendin--;
1254 tok->indent--;
1255 }
1256 if (col != tok->indstack[tok->indent]) {
1257 tok->done = E_DEDENT;
1258 tok->cur = tok->inp;
1259 return ERRORTOKEN;
1260 }
1261 if (altcol != tok->altindstack[tok->indent]) {
Victor Stinnerf2ddc6a2017-11-17 01:25:47 -08001262 return indenterror(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 }
1264 }
1265 }
1266 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 tok->start = tok->cur;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* Return pending indents/dedents */
1271 if (tok->pendin != 0) {
1272 if (tok->pendin < 0) {
1273 tok->pendin++;
1274 return DEDENT;
1275 }
1276 else {
1277 tok->pendin--;
1278 return INDENT;
1279 }
1280 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001281
Guido van Rossum495da292019-03-07 12:38:08 -08001282 /* Peek ahead at the next character */
1283 c = tok_nextc(tok);
1284 tok_backup(tok, c);
1285 /* Check if we are closing an async function */
1286 if (tok->async_def
1287 && !blankline
1288 /* Due to some implementation artifacts of type comments,
1289 * a TYPE_COMMENT at the start of a function won't set an
1290 * indentation level and it will produce a NEWLINE after it.
1291 * To avoid spuriously ending an async function due to this,
1292 * wait until we have some non-newline char in front of us. */
1293 && c != '\n'
1294 && tok->level == 0
1295 /* There was a NEWLINE after ASYNC DEF,
1296 so we're past the signature. */
1297 && tok->async_def_nl
1298 /* Current indentation level is less than where
1299 the async function was defined */
1300 && tok->async_def_indent >= tok->indent)
1301 {
1302 tok->async_def = 0;
1303 tok->async_def_indent = 0;
1304 tok->async_def_nl = 0;
1305 }
1306
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001307 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 tok->start = NULL;
1309 /* Skip spaces */
1310 do {
1311 c = tok_nextc(tok);
1312 } while (c == ' ' || c == '\t' || c == '\014');
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* Set start of current token */
1315 tok->start = tok->cur - 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001316
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001317 /* Skip comment, unless it's a type comment */
Brett Cannona721aba2016-09-09 14:57:09 -07001318 if (c == '#') {
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001319 const char *prefix, *p, *type_start;
1320
Brett Cannona721aba2016-09-09 14:57:09 -07001321 while (c != EOF && c != '\n') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 c = tok_nextc(tok);
Brett Cannona721aba2016-09-09 14:57:09 -07001323 }
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001324
1325 if (tok->type_comments) {
1326 p = tok->start;
1327 prefix = type_comment_prefix;
1328 while (*prefix && p < tok->cur) {
1329 if (*prefix == ' ') {
1330 while (*p == ' ' || *p == '\t') {
1331 p++;
1332 }
1333 } else if (*prefix == *p) {
1334 p++;
1335 } else {
1336 break;
1337 }
1338
1339 prefix++;
1340 }
1341
1342 /* This is a type comment if we matched all of type_comment_prefix. */
1343 if (!*prefix) {
1344 int is_type_ignore = 1;
Michael J. Sullivan933e1502019-05-22 07:54:20 -07001345 const char *ignore_end = p + 6;
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001346 tok_backup(tok, c); /* don't eat the newline or EOF */
1347
1348 type_start = p;
1349
Michael J. Sullivand8320ec2019-05-11 11:17:24 -07001350 /* A TYPE_IGNORE is "type: ignore" followed by the end of the token
Michael J. Sullivand8a82e22019-05-22 13:43:37 -07001351 * or anything ASCII and non-alphanumeric. */
Michael J. Sullivand8320ec2019-05-11 11:17:24 -07001352 is_type_ignore = (
Michael J. Sullivan933e1502019-05-22 07:54:20 -07001353 tok->cur >= ignore_end && memcmp(p, "ignore", 6) == 0
Michael J. Sullivand8a82e22019-05-22 13:43:37 -07001354 && !(tok->cur > ignore_end
1355 && ((unsigned char)ignore_end[0] >= 128 || Py_ISALNUM(ignore_end[0]))));
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001356
1357 if (is_type_ignore) {
Andy Lester384f3c52020-02-27 20:44:52 -06001358 *p_start = ignore_end;
Michael J. Sullivan933e1502019-05-22 07:54:20 -07001359 *p_end = tok->cur;
1360
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001361 /* If this type ignore is the only thing on the line, consume the newline also. */
1362 if (blankline) {
1363 tok_nextc(tok);
1364 tok->atbol = 1;
1365 }
1366 return TYPE_IGNORE;
1367 } else {
Andy Lester384f3c52020-02-27 20:44:52 -06001368 *p_start = type_start; /* after type_comment_prefix */
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001369 *p_end = tok->cur;
1370 return TYPE_COMMENT;
1371 }
1372 }
1373 }
Brett Cannona721aba2016-09-09 14:57:09 -07001374 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* Check for EOF and errors now */
1377 if (c == EOF) {
1378 return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
1379 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 /* Identifier (most frequent token!) */
1382 nonascii = 0;
1383 if (is_potential_identifier_start(c)) {
Berker Peksag6f805622017-02-05 04:32:39 +03001384 /* Process the various legal combinations of b"", r"", u"", and f"". */
Eric V. Smith235a6f02015-09-19 14:51:32 -04001385 int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0;
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01001386 while (1) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04001387 if (!(saw_b || saw_u || saw_f) && (c == 'b' || c == 'B'))
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01001388 saw_b = 1;
Armin Ronacher6ecf77b2012-03-04 12:04:06 +00001389 /* Since this is a backwards compatibility support literal we don't
1390 want to support it in arbitrary order like byte literals. */
Brett Cannona721aba2016-09-09 14:57:09 -07001391 else if (!(saw_b || saw_u || saw_r || saw_f)
1392 && (c == 'u'|| c == 'U')) {
Armin Ronacher6ecf77b2012-03-04 12:04:06 +00001393 saw_u = 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001394 }
Christian Heimes0b3847d2012-06-20 11:17:58 +02001395 /* ur"" and ru"" are not supported */
Brett Cannona721aba2016-09-09 14:57:09 -07001396 else if (!(saw_r || saw_u) && (c == 'r' || c == 'R')) {
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01001397 saw_r = 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001398 }
1399 else if (!(saw_f || saw_b || saw_u) && (c == 'f' || c == 'F')) {
Eric V. Smith235a6f02015-09-19 14:51:32 -04001400 saw_f = 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001401 }
1402 else {
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +01001403 break;
Brett Cannona721aba2016-09-09 14:57:09 -07001404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 c = tok_nextc(tok);
Brett Cannona721aba2016-09-09 14:57:09 -07001406 if (c == '"' || c == '\'') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 goto letter_quote;
Brett Cannona721aba2016-09-09 14:57:09 -07001408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
1410 while (is_potential_identifier_char(c)) {
Brett Cannona721aba2016-09-09 14:57:09 -07001411 if (c >= 128) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 nonascii = 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 c = tok_nextc(tok);
1415 }
1416 tok_backup(tok, c);
Brett Cannona721aba2016-09-09 14:57:09 -07001417 if (nonascii && !verify_identifier(tok)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 return ERRORTOKEN;
Brett Cannona721aba2016-09-09 14:57:09 -07001419 }
Pablo Galindo11a7f152020-04-21 01:53:04 +01001420
1421 *p_start = tok->start;
1422 *p_end = tok->cur;
1423
Guido van Rossum495da292019-03-07 12:38:08 -08001424 /* async/await parsing block. */
1425 if (tok->cur - tok->start == 5 && tok->start[0] == 'a') {
1426 /* May be an 'async' or 'await' token. For Python 3.7 or
1427 later we recognize them unconditionally. For Python
1428 3.5 or 3.6 we recognize 'async' in front of 'def', and
1429 either one inside of 'async def'. (Technically we
1430 shouldn't recognize these at all for 3.4 or earlier,
1431 but there's no *valid* Python 3.4 code that would be
1432 rejected, and async functions will be rejected in a
1433 later phase.) */
1434 if (!tok->async_hacks || tok->async_def) {
1435 /* Always recognize the keywords. */
1436 if (memcmp(tok->start, "async", 5) == 0) {
1437 return ASYNC;
1438 }
1439 if (memcmp(tok->start, "await", 5) == 0) {
1440 return AWAIT;
1441 }
1442 }
1443 else if (memcmp(tok->start, "async", 5) == 0) {
1444 /* The current token is 'async'.
1445 Look ahead one token to see if that is 'def'. */
1446
1447 struct tok_state ahead_tok;
Andy Lester384f3c52020-02-27 20:44:52 -06001448 const char *ahead_tok_start = NULL;
1449 const char *ahead_tok_end = NULL;
Guido van Rossum495da292019-03-07 12:38:08 -08001450 int ahead_tok_kind;
1451
1452 memcpy(&ahead_tok, tok, sizeof(ahead_tok));
1453 ahead_tok_kind = tok_get(&ahead_tok, &ahead_tok_start,
1454 &ahead_tok_end);
1455
1456 if (ahead_tok_kind == NAME
1457 && ahead_tok.cur - ahead_tok.start == 3
1458 && memcmp(ahead_tok.start, "def", 3) == 0)
1459 {
1460 /* The next token is going to be 'def', so instead of
1461 returning a plain NAME token, return ASYNC. */
1462 tok->async_def_indent = tok->indent;
1463 tok->async_def = 1;
1464 return ASYNC;
1465 }
1466 }
1467 }
1468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 return NAME;
1470 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 /* Newline */
1473 if (c == '\n') {
1474 tok->atbol = 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001475 if (blankline || tok->level > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 goto nextline;
Brett Cannona721aba2016-09-09 14:57:09 -07001477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 *p_start = tok->start;
1479 *p_end = tok->cur - 1; /* Leave '\n' out of the string */
1480 tok->cont_line = 0;
Guido van Rossum495da292019-03-07 12:38:08 -08001481 if (tok->async_def) {
1482 /* We're somewhere inside an 'async def' function, and
1483 we've encountered a NEWLINE after its signature. */
1484 tok->async_def_nl = 1;
1485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 return NEWLINE;
1487 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 /* Period or number starting with period? */
1490 if (c == '.') {
1491 c = tok_nextc(tok);
1492 if (isdigit(c)) {
1493 goto fraction;
1494 } else if (c == '.') {
1495 c = tok_nextc(tok);
1496 if (c == '.') {
1497 *p_start = tok->start;
1498 *p_end = tok->cur;
1499 return ELLIPSIS;
Brett Cannona721aba2016-09-09 14:57:09 -07001500 }
1501 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 tok_backup(tok, c);
1503 }
1504 tok_backup(tok, '.');
Brett Cannona721aba2016-09-09 14:57:09 -07001505 }
1506 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 tok_backup(tok, c);
1508 }
1509 *p_start = tok->start;
1510 *p_end = tok->cur;
1511 return DOT;
1512 }
Guido van Rossumf595fde1996-01-12 01:31:58 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* Number */
1515 if (isdigit(c)) {
1516 if (c == '0') {
1517 /* Hex, octal or binary -- maybe. */
1518 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (c == 'x' || c == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 /* Hex */
1521 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 do {
Brett Cannona721aba2016-09-09 14:57:09 -07001523 if (c == '_') {
1524 c = tok_nextc(tok);
1525 }
1526 if (!isxdigit(c)) {
Brett Cannona721aba2016-09-09 14:57:09 -07001527 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001528 return syntaxerror(tok, "invalid hexadecimal literal");
Brett Cannona721aba2016-09-09 14:57:09 -07001529 }
1530 do {
1531 c = tok_nextc(tok);
1532 } while (isxdigit(c));
1533 } while (c == '_');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 }
1535 else if (c == 'o' || c == 'O') {
1536 /* Octal */
1537 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 do {
Brett Cannona721aba2016-09-09 14:57:09 -07001539 if (c == '_') {
1540 c = tok_nextc(tok);
1541 }
1542 if (c < '0' || c >= '8') {
Brett Cannona721aba2016-09-09 14:57:09 -07001543 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001544 if (isdigit(c)) {
1545 return syntaxerror(tok,
1546 "invalid digit '%c' in octal literal", c);
1547 }
1548 else {
1549 return syntaxerror(tok, "invalid octal literal");
1550 }
Brett Cannona721aba2016-09-09 14:57:09 -07001551 }
1552 do {
1553 c = tok_nextc(tok);
1554 } while ('0' <= c && c < '8');
1555 } while (c == '_');
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001556 if (isdigit(c)) {
1557 return syntaxerror(tok,
1558 "invalid digit '%c' in octal literal", c);
1559 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 }
1561 else if (c == 'b' || c == 'B') {
1562 /* Binary */
1563 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 do {
Brett Cannona721aba2016-09-09 14:57:09 -07001565 if (c == '_') {
1566 c = tok_nextc(tok);
1567 }
1568 if (c != '0' && c != '1') {
Brett Cannona721aba2016-09-09 14:57:09 -07001569 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001570 if (isdigit(c)) {
1571 return syntaxerror(tok,
1572 "invalid digit '%c' in binary literal", c);
1573 }
1574 else {
1575 return syntaxerror(tok, "invalid binary literal");
1576 }
Brett Cannona721aba2016-09-09 14:57:09 -07001577 }
1578 do {
1579 c = tok_nextc(tok);
1580 } while (c == '0' || c == '1');
1581 } while (c == '_');
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001582 if (isdigit(c)) {
1583 return syntaxerror(tok,
1584 "invalid digit '%c' in binary literal", c);
1585 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 }
1587 else {
1588 int nonzero = 0;
1589 /* maybe old-style octal; c is first char of it */
1590 /* in any case, allow '0' as a literal */
Brett Cannona721aba2016-09-09 14:57:09 -07001591 while (1) {
1592 if (c == '_') {
1593 c = tok_nextc(tok);
1594 if (!isdigit(c)) {
Brett Cannona721aba2016-09-09 14:57:09 -07001595 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001596 return syntaxerror(tok, "invalid decimal literal");
Brett Cannona721aba2016-09-09 14:57:09 -07001597 }
1598 }
1599 if (c != '0') {
1600 break;
1601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 c = tok_nextc(tok);
1603 }
Brett Cannona721aba2016-09-09 14:57:09 -07001604 if (isdigit(c)) {
1605 nonzero = 1;
1606 c = tok_decimal_tail(tok);
1607 if (c == 0) {
1608 return ERRORTOKEN;
1609 }
1610 }
1611 if (c == '.') {
1612 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 goto fraction;
Brett Cannona721aba2016-09-09 14:57:09 -07001614 }
1615 else if (c == 'e' || c == 'E') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 goto exponent;
Brett Cannona721aba2016-09-09 14:57:09 -07001617 }
1618 else if (c == 'j' || c == 'J') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 goto imaginary;
Brett Cannona721aba2016-09-09 14:57:09 -07001620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 else if (nonzero) {
Brett Cannona721aba2016-09-09 14:57:09 -07001622 /* Old-style octal: now disallowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001624 return syntaxerror(tok,
1625 "leading zeros in decimal integer "
1626 "literals are not permitted; "
1627 "use an 0o prefix for octal integers");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 }
1629 }
1630 }
1631 else {
1632 /* Decimal */
Brett Cannona721aba2016-09-09 14:57:09 -07001633 c = tok_decimal_tail(tok);
1634 if (c == 0) {
1635 return ERRORTOKEN;
1636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 {
1638 /* Accept floating point numbers. */
1639 if (c == '.') {
Brett Cannona721aba2016-09-09 14:57:09 -07001640 c = tok_nextc(tok);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 fraction:
1642 /* Fraction */
Brett Cannona721aba2016-09-09 14:57:09 -07001643 if (isdigit(c)) {
1644 c = tok_decimal_tail(tok);
1645 if (c == 0) {
1646 return ERRORTOKEN;
1647 }
1648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 }
1650 if (c == 'e' || c == 'E') {
Benjamin Petersonc4161622014-06-07 12:36:39 -07001651 int e;
1652 exponent:
1653 e = c;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Exponent part */
1655 c = tok_nextc(tok);
Benjamin Petersonc4161622014-06-07 12:36:39 -07001656 if (c == '+' || c == '-') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 c = tok_nextc(tok);
Benjamin Petersonc4161622014-06-07 12:36:39 -07001658 if (!isdigit(c)) {
Benjamin Petersonc4161622014-06-07 12:36:39 -07001659 tok_backup(tok, c);
Serhiy Storchakacf7303e2018-07-09 15:09:35 +03001660 return syntaxerror(tok, "invalid decimal literal");
Benjamin Petersonc4161622014-06-07 12:36:39 -07001661 }
1662 } else if (!isdigit(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 tok_backup(tok, c);
Benjamin Petersonc4161622014-06-07 12:36:39 -07001664 tok_backup(tok, e);
1665 *p_start = tok->start;
1666 *p_end = tok->cur;
1667 return NUMBER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 }
Brett Cannona721aba2016-09-09 14:57:09 -07001669 c = tok_decimal_tail(tok);
1670 if (c == 0) {
1671 return ERRORTOKEN;
1672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 }
Brett Cannona721aba2016-09-09 14:57:09 -07001674 if (c == 'j' || c == 'J') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 /* Imaginary part */
1676 imaginary:
1677 c = tok_nextc(tok);
Brett Cannona721aba2016-09-09 14:57:09 -07001678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
1680 }
1681 tok_backup(tok, c);
1682 *p_start = tok->start;
1683 *p_end = tok->cur;
1684 return NUMBER;
1685 }
Guido van Rossum24dacb31997-04-06 03:46:20 +00001686
1687 letter_quote:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* String */
1689 if (c == '\'' || c == '"') {
1690 int quote = c;
1691 int quote_size = 1; /* 1 or 3 */
1692 int end_quote_size = 0;
Guido van Rossumcf171a72007-11-16 00:51:45 +00001693
Anthony Sottile995d9b92019-01-12 20:05:13 -08001694 /* Nodes of type STRING, especially multi line strings
1695 must be handled differently in order to get both
1696 the starting line number and the column offset right.
1697 (cf. issue 16806) */
1698 tok->first_lineno = tok->lineno;
1699 tok->multi_line_start = tok->line_start;
1700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* Find the quote size and start of string */
1702 c = tok_nextc(tok);
1703 if (c == quote) {
1704 c = tok_nextc(tok);
Brett Cannona721aba2016-09-09 14:57:09 -07001705 if (c == quote) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 quote_size = 3;
Brett Cannona721aba2016-09-09 14:57:09 -07001707 }
1708 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 end_quote_size = 1; /* empty string found */
Brett Cannona721aba2016-09-09 14:57:09 -07001710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 }
Brett Cannona721aba2016-09-09 14:57:09 -07001712 if (c != quote) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 tok_backup(tok, c);
Brett Cannona721aba2016-09-09 14:57:09 -07001714 }
Guido van Rossumcf171a72007-11-16 00:51:45 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* Get rest of string */
1717 while (end_quote_size != quote_size) {
1718 c = tok_nextc(tok);
1719 if (c == EOF) {
Brett Cannona721aba2016-09-09 14:57:09 -07001720 if (quote_size == 3) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 tok->done = E_EOFS;
Brett Cannona721aba2016-09-09 14:57:09 -07001722 }
1723 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 tok->done = E_EOLS;
Brett Cannona721aba2016-09-09 14:57:09 -07001725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 tok->cur = tok->inp;
1727 return ERRORTOKEN;
1728 }
1729 if (quote_size == 1 && c == '\n') {
1730 tok->done = E_EOLS;
1731 tok->cur = tok->inp;
1732 return ERRORTOKEN;
1733 }
Brett Cannona721aba2016-09-09 14:57:09 -07001734 if (c == quote) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 end_quote_size += 1;
Brett Cannona721aba2016-09-09 14:57:09 -07001736 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 else {
1738 end_quote_size = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07001739 if (c == '\\') {
Christian Heimesc6cc23d2016-09-09 00:09:45 +02001740 tok_nextc(tok); /* skip escaped char */
Brett Cannona721aba2016-09-09 14:57:09 -07001741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 }
1743 }
Guido van Rossumcf171a72007-11-16 00:51:45 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 *p_start = tok->start;
1746 *p_end = tok->cur;
1747 return STRING;
1748 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 /* Line continuation */
1751 if (c == '\\') {
1752 c = tok_nextc(tok);
1753 if (c != '\n') {
1754 tok->done = E_LINECONT;
1755 tok->cur = tok->inp;
1756 return ERRORTOKEN;
1757 }
Anthony Sottileabea73b2019-05-18 11:27:17 -07001758 c = tok_nextc(tok);
1759 if (c == EOF) {
1760 tok->done = E_EOF;
1761 tok->cur = tok->inp;
1762 return ERRORTOKEN;
1763 } else {
1764 tok_backup(tok, c);
1765 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 tok->cont_line = 1;
1767 goto again; /* Read next line */
1768 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Check for two-character token */
1771 {
1772 int c2 = tok_nextc(tok);
1773 int token = PyToken_TwoChars(c, c2);
1774 if (token != OP) {
1775 int c3 = tok_nextc(tok);
1776 int token3 = PyToken_ThreeChars(c, c2, c3);
1777 if (token3 != OP) {
1778 token = token3;
Brett Cannona721aba2016-09-09 14:57:09 -07001779 }
1780 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 tok_backup(tok, c3);
1782 }
1783 *p_start = tok->start;
1784 *p_end = tok->cur;
1785 return token;
1786 }
1787 tok_backup(tok, c2);
1788 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Keep track of parentheses nesting level */
1791 switch (c) {
1792 case '(':
1793 case '[':
1794 case '{':
Serhiy Storchaka94cf3082018-12-17 17:34:14 +02001795 if (tok->level >= MAXLEVEL) {
1796 return syntaxerror(tok, "too many nested parentheses");
1797 }
1798 tok->parenstack[tok->level] = c;
1799 tok->parenlinenostack[tok->level] = tok->lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 tok->level++;
1801 break;
1802 case ')':
1803 case ']':
1804 case '}':
Serhiy Storchaka94cf3082018-12-17 17:34:14 +02001805 if (!tok->level) {
1806 return syntaxerror(tok, "unmatched '%c'", c);
1807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 tok->level--;
Serhiy Storchaka94cf3082018-12-17 17:34:14 +02001809 int opening = tok->parenstack[tok->level];
1810 if (!((opening == '(' && c == ')') ||
1811 (opening == '[' && c == ']') ||
1812 (opening == '{' && c == '}')))
1813 {
1814 if (tok->parenlinenostack[tok->level] != tok->lineno) {
1815 return syntaxerror(tok,
1816 "closing parenthesis '%c' does not match "
1817 "opening parenthesis '%c' on line %d",
1818 c, opening, tok->parenlinenostack[tok->level]);
1819 }
1820 else {
1821 return syntaxerror(tok,
1822 "closing parenthesis '%c' does not match "
1823 "opening parenthesis '%c'",
1824 c, opening);
1825 }
1826 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 break;
1828 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 /* Punctuation character */
1831 *p_start = tok->start;
1832 *p_end = tok->cur;
1833 return PyToken_OneChar(c);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001834}
1835
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001836int
Andy Lester384f3c52020-02-27 20:44:52 -06001837PyTokenizer_Get(struct tok_state *tok, const char **p_start, const char **p_end)
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 int result = tok_get(tok, p_start, p_end);
1840 if (tok->decoding_erred) {
1841 result = ERRORTOKEN;
1842 tok->done = E_DECODE;
1843 }
1844 return result;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001845}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001847/* Get the encoding of a Python file. Check for the coding cookie and check if
1848 the file starts with a BOM.
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001849
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001850 PyTokenizer_FindEncodingFilename() returns NULL when it can't find the
1851 encoding in the first or second line of the file (in which case the encoding
1852 should be assumed to be UTF-8).
Brett Cannone4539892007-10-20 03:46:49 +00001853
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001854 The char* returned is malloc'ed via PyMem_MALLOC() and thus must be freed
1855 by the caller. */
1856
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001857char *
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001858PyTokenizer_FindEncodingFilename(int fd, PyObject *filename)
Guido van Rossum40d20bc2007-10-22 00:09:51 +00001859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 struct tok_state *tok;
1861 FILE *fp;
Andy Lester384f3c52020-02-27 20:44:52 -06001862 const char *p_start = NULL;
1863 const char *p_end = NULL;
1864 char *encoding = NULL;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001865
Victor Stinnerdaf45552013-08-28 00:53:59 +02001866 fd = _Py_dup(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (fd < 0) {
1868 return NULL;
1869 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 fp = fdopen(fd, "r");
1872 if (fp == NULL) {
1873 return NULL;
1874 }
1875 tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL);
1876 if (tok == NULL) {
1877 fclose(fp);
1878 return NULL;
1879 }
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001880 if (filename != NULL) {
1881 Py_INCREF(filename);
1882 tok->filename = filename;
1883 }
1884 else {
1885 tok->filename = PyUnicode_FromString("<string>");
1886 if (tok->filename == NULL) {
1887 fclose(fp);
1888 PyTokenizer_Free(tok);
1889 return encoding;
1890 }
1891 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 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)
Hansraj Das69f37bc2019-08-15 21:49:07 +05301899 strcpy(encoding, tok->encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 }
1901 PyTokenizer_Free(tok);
1902 return encoding;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001903}
Thomas Wouters89d996e2007-09-08 17:39:28 +00001904
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02001905char *
1906PyTokenizer_FindEncoding(int fd)
1907{
1908 return PyTokenizer_FindEncodingFilename(fd, NULL);
1909}
1910
Guido van Rossum408027e1996-12-30 16:17:54 +00001911#ifdef Py_DEBUG
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001912
1913void
Thomas Wouters23c9e002000-07-22 19:20:54 +00001914tok_dump(int type, char *start, char *end)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 printf("%s", _PyParser_TokenNames[type]);
1917 if (type == NAME || type == NUMBER || type == STRING || type == OP)
1918 printf("(%.*s)", (int)(end - start), start);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919}
1920
1921#endif