You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1985 lines
54 KiB

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