pegen.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. #include <Python.h>
  2. #include "pycore_ast.h" // _PyAST_Validate(),
  3. #include "pycore_pystate.h" // _PyThreadState_GET()
  4. #include <errcode.h>
  5. #include "tokenizer.h"
  6. #include "pegen.h"
  7. // Internal parser functions
  8. asdl_stmt_seq*
  9. _PyPegen_interactive_exit(Parser *p)
  10. {
  11. if (p->errcode) {
  12. *(p->errcode) = E_EOF;
  13. }
  14. return NULL;
  15. }
  16. Py_ssize_t
  17. _PyPegen_byte_offset_to_character_offset_line(PyObject *line, Py_ssize_t col_offset, Py_ssize_t end_col_offset)
  18. {
  19. const char *data = PyUnicode_AsUTF8(line);
  20. Py_ssize_t len = 0;
  21. while (col_offset < end_col_offset) {
  22. Py_UCS4 ch = data[col_offset];
  23. if (ch < 0x80) {
  24. col_offset += 1;
  25. } else if ((ch & 0xe0) == 0xc0) {
  26. col_offset += 2;
  27. } else if ((ch & 0xf0) == 0xe0) {
  28. col_offset += 3;
  29. } else if ((ch & 0xf8) == 0xf0) {
  30. col_offset += 4;
  31. } else {
  32. PyErr_SetString(PyExc_ValueError, "Invalid UTF-8 sequence");
  33. return -1;
  34. }
  35. len++;
  36. }
  37. return len;
  38. }
  39. Py_ssize_t
  40. _PyPegen_byte_offset_to_character_offset_raw(const char* str, Py_ssize_t col_offset)
  41. {
  42. Py_ssize_t len = strlen(str);
  43. if (col_offset > len + 1) {
  44. col_offset = len + 1;
  45. }
  46. assert(col_offset >= 0);
  47. PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
  48. if (!text) {
  49. return -1;
  50. }
  51. Py_ssize_t size = PyUnicode_GET_LENGTH(text);
  52. Py_DECREF(text);
  53. return size;
  54. }
  55. // Calculate the extra amount of width space the given source
  56. // code segment might take if it were to be displayed on a fixed
  57. // width output device. Supports wide unicode characters and emojis.
  58. Py_ssize_t
  59. _PyPegen_calculate_display_width(PyObject *line, Py_ssize_t character_offset)
  60. {
  61. PyObject *segment = PyUnicode_Substring(line, 0, character_offset);
  62. if (!segment) {
  63. return -1;
  64. }
  65. // Fast track for ascii strings
  66. if (PyUnicode_IS_ASCII(segment)) {
  67. Py_DECREF(segment);
  68. return character_offset;
  69. }
  70. PyObject *width_fn = _PyImport_GetModuleAttrString("unicodedata", "east_asian_width");
  71. if (!width_fn) {
  72. return -1;
  73. }
  74. Py_ssize_t width = 0;
  75. Py_ssize_t len = PyUnicode_GET_LENGTH(segment);
  76. for (Py_ssize_t i = 0; i < len; i++) {
  77. PyObject *chr = PyUnicode_Substring(segment, i, i + 1);
  78. if (!chr) {
  79. Py_DECREF(segment);
  80. Py_DECREF(width_fn);
  81. return -1;
  82. }
  83. PyObject *width_specifier = PyObject_CallOneArg(width_fn, chr);
  84. Py_DECREF(chr);
  85. if (!width_specifier) {
  86. Py_DECREF(segment);
  87. Py_DECREF(width_fn);
  88. return -1;
  89. }
  90. if (_PyUnicode_EqualToASCIIString(width_specifier, "W") ||
  91. _PyUnicode_EqualToASCIIString(width_specifier, "F")) {
  92. width += 2;
  93. }
  94. else {
  95. width += 1;
  96. }
  97. Py_DECREF(width_specifier);
  98. }
  99. Py_DECREF(segment);
  100. Py_DECREF(width_fn);
  101. return width;
  102. }
  103. Py_ssize_t
  104. _PyPegen_byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
  105. {
  106. const char *str = PyUnicode_AsUTF8(line);
  107. if (!str) {
  108. return -1;
  109. }
  110. return _PyPegen_byte_offset_to_character_offset_raw(str, col_offset);
  111. }
  112. // Here, mark is the start of the node, while p->mark is the end.
  113. // If node==NULL, they should be the same.
  114. int
  115. _PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
  116. {
  117. // Insert in front
  118. Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
  119. if (m == NULL) {
  120. return -1;
  121. }
  122. m->type = type;
  123. m->node = node;
  124. m->mark = p->mark;
  125. m->next = p->tokens[mark]->memo;
  126. p->tokens[mark]->memo = m;
  127. return 0;
  128. }
  129. // Like _PyPegen_insert_memo(), but updates an existing node if found.
  130. int
  131. _PyPegen_update_memo(Parser *p, int mark, int type, void *node)
  132. {
  133. for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
  134. if (m->type == type) {
  135. // Update existing node.
  136. m->node = node;
  137. m->mark = p->mark;
  138. return 0;
  139. }
  140. }
  141. // Insert new node.
  142. return _PyPegen_insert_memo(p, mark, type, node);
  143. }
  144. static int
  145. init_normalization(Parser *p)
  146. {
  147. if (p->normalize) {
  148. return 1;
  149. }
  150. p->normalize = _PyImport_GetModuleAttrString("unicodedata", "normalize");
  151. if (!p->normalize)
  152. {
  153. return 0;
  154. }
  155. return 1;
  156. }
  157. static int
  158. growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
  159. assert(initial_size > 0);
  160. arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
  161. arr->size = initial_size;
  162. arr->num_items = 0;
  163. return arr->items != NULL;
  164. }
  165. static int
  166. growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
  167. if (arr->num_items >= arr->size) {
  168. size_t new_size = arr->size * 2;
  169. void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
  170. if (!new_items_array) {
  171. return 0;
  172. }
  173. arr->items = new_items_array;
  174. arr->size = new_size;
  175. }
  176. arr->items[arr->num_items].lineno = lineno;
  177. arr->items[arr->num_items].comment = comment; // Take ownership
  178. arr->num_items++;
  179. return 1;
  180. }
  181. static void
  182. growable_comment_array_deallocate(growable_comment_array *arr) {
  183. for (unsigned i = 0; i < arr->num_items; i++) {
  184. PyMem_Free(arr->items[i].comment);
  185. }
  186. PyMem_Free(arr->items);
  187. }
  188. static int
  189. _get_keyword_or_name_type(Parser *p, struct token *new_token)
  190. {
  191. int name_len = new_token->end_col_offset - new_token->col_offset;
  192. assert(name_len > 0);
  193. if (name_len >= p->n_keyword_lists ||
  194. p->keywords[name_len] == NULL ||
  195. p->keywords[name_len]->type == -1) {
  196. return NAME;
  197. }
  198. for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
  199. if (strncmp(k->str, new_token->start, name_len) == 0) {
  200. return k->type;
  201. }
  202. }
  203. return NAME;
  204. }
  205. static int
  206. initialize_token(Parser *p, Token *parser_token, struct token *new_token, int token_type) {
  207. assert(parser_token != NULL);
  208. parser_token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, new_token) : token_type;
  209. parser_token->bytes = PyBytes_FromStringAndSize(new_token->start, new_token->end - new_token->start);
  210. if (parser_token->bytes == NULL) {
  211. return -1;
  212. }
  213. if (_PyArena_AddPyObject(p->arena, parser_token->bytes) < 0) {
  214. Py_DECREF(parser_token->bytes);
  215. return -1;
  216. }
  217. parser_token->metadata = NULL;
  218. if (new_token->metadata != NULL) {
  219. if (_PyArena_AddPyObject(p->arena, new_token->metadata) < 0) {
  220. Py_DECREF(parser_token->metadata);
  221. return -1;
  222. }
  223. parser_token->metadata = new_token->metadata;
  224. new_token->metadata = NULL;
  225. }
  226. parser_token->level = new_token->level;
  227. parser_token->lineno = new_token->lineno;
  228. parser_token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->col_offset
  229. : new_token->col_offset;
  230. parser_token->end_lineno = new_token->end_lineno;
  231. parser_token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->end_col_offset
  232. : new_token->end_col_offset;
  233. p->fill += 1;
  234. if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
  235. return _Pypegen_raise_decode_error(p);
  236. }
  237. return (token_type == ERRORTOKEN ? _Pypegen_tokenizer_error(p) : 0);
  238. }
  239. static int
  240. _resize_tokens_array(Parser *p) {
  241. int newsize = p->size * 2;
  242. Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
  243. if (new_tokens == NULL) {
  244. PyErr_NoMemory();
  245. return -1;
  246. }
  247. p->tokens = new_tokens;
  248. for (int i = p->size; i < newsize; i++) {
  249. p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
  250. if (p->tokens[i] == NULL) {
  251. p->size = i; // Needed, in order to cleanup correctly after parser fails
  252. PyErr_NoMemory();
  253. return -1;
  254. }
  255. }
  256. p->size = newsize;
  257. return 0;
  258. }
  259. int
  260. _PyPegen_fill_token(Parser *p)
  261. {
  262. struct token new_token;
  263. _PyToken_Init(&new_token);
  264. int type = _PyTokenizer_Get(p->tok, &new_token);
  265. // Record and skip '# type: ignore' comments
  266. while (type == TYPE_IGNORE) {
  267. Py_ssize_t len = new_token.end_col_offset - new_token.col_offset;
  268. char *tag = PyMem_Malloc(len + 1);
  269. if (tag == NULL) {
  270. PyErr_NoMemory();
  271. goto error;
  272. }
  273. strncpy(tag, new_token.start, len);
  274. tag[len] = '\0';
  275. // Ownership of tag passes to the growable array
  276. if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
  277. PyErr_NoMemory();
  278. goto error;
  279. }
  280. type = _PyTokenizer_Get(p->tok, &new_token);
  281. }
  282. // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
  283. if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
  284. type = NEWLINE; /* Add an extra newline */
  285. p->parsing_started = 0;
  286. if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
  287. p->tok->pendin = -p->tok->indent;
  288. p->tok->indent = 0;
  289. }
  290. }
  291. else {
  292. p->parsing_started = 1;
  293. }
  294. // Check if we are at the limit of the token array capacity and resize if needed
  295. if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
  296. goto error;
  297. }
  298. Token *t = p->tokens[p->fill];
  299. return initialize_token(p, t, &new_token, type);
  300. error:
  301. _PyToken_Free(&new_token);
  302. return -1;
  303. }
  304. #if defined(Py_DEBUG)
  305. // Instrumentation to count the effectiveness of memoization.
  306. // The array counts the number of tokens skipped by memoization,
  307. // indexed by type.
  308. #define NSTATISTICS _PYPEGEN_NSTATISTICS
  309. #define memo_statistics _PyRuntime.parser.memo_statistics
  310. void
  311. _PyPegen_clear_memo_statistics(void)
  312. {
  313. for (int i = 0; i < NSTATISTICS; i++) {
  314. memo_statistics[i] = 0;
  315. }
  316. }
  317. PyObject *
  318. _PyPegen_get_memo_statistics(void)
  319. {
  320. PyObject *ret = PyList_New(NSTATISTICS);
  321. if (ret == NULL) {
  322. return NULL;
  323. }
  324. for (int i = 0; i < NSTATISTICS; i++) {
  325. PyObject *value = PyLong_FromLong(memo_statistics[i]);
  326. if (value == NULL) {
  327. Py_DECREF(ret);
  328. return NULL;
  329. }
  330. // PyList_SetItem borrows a reference to value.
  331. if (PyList_SetItem(ret, i, value) < 0) {
  332. Py_DECREF(ret);
  333. return NULL;
  334. }
  335. }
  336. return ret;
  337. }
  338. #endif
  339. int // bool
  340. _PyPegen_is_memoized(Parser *p, int type, void *pres)
  341. {
  342. if (p->mark == p->fill) {
  343. if (_PyPegen_fill_token(p) < 0) {
  344. p->error_indicator = 1;
  345. return -1;
  346. }
  347. }
  348. Token *t = p->tokens[p->mark];
  349. for (Memo *m = t->memo; m != NULL; m = m->next) {
  350. if (m->type == type) {
  351. #if defined(Py_DEBUG)
  352. if (0 <= type && type < NSTATISTICS) {
  353. long count = m->mark - p->mark;
  354. // A memoized negative result counts for one.
  355. if (count <= 0) {
  356. count = 1;
  357. }
  358. memo_statistics[type] += count;
  359. }
  360. #endif
  361. p->mark = m->mark;
  362. *(void **)(pres) = m->node;
  363. return 1;
  364. }
  365. }
  366. return 0;
  367. }
  368. int
  369. _PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
  370. {
  371. int mark = p->mark;
  372. void *res = func(p);
  373. p->mark = mark;
  374. return (res != NULL) == positive;
  375. }
  376. int
  377. _PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
  378. {
  379. int mark = p->mark;
  380. void *res = func(p, arg);
  381. p->mark = mark;
  382. return (res != NULL) == positive;
  383. }
  384. int
  385. _PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
  386. {
  387. int mark = p->mark;
  388. void *res = func(p, arg);
  389. p->mark = mark;
  390. return (res != NULL) == positive;
  391. }
  392. int
  393. _PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
  394. {
  395. int mark = p->mark;
  396. void *res = (void*)func(p);
  397. p->mark = mark;
  398. return (res != NULL) == positive;
  399. }
  400. Token *
  401. _PyPegen_expect_token(Parser *p, int type)
  402. {
  403. if (p->mark == p->fill) {
  404. if (_PyPegen_fill_token(p) < 0) {
  405. p->error_indicator = 1;
  406. return NULL;
  407. }
  408. }
  409. Token *t = p->tokens[p->mark];
  410. if (t->type != type) {
  411. return NULL;
  412. }
  413. p->mark += 1;
  414. return t;
  415. }
  416. void*
  417. _PyPegen_expect_forced_result(Parser *p, void* result, const char* expected) {
  418. if (p->error_indicator == 1) {
  419. return NULL;
  420. }
  421. if (result == NULL) {
  422. RAISE_SYNTAX_ERROR("expected (%s)", expected);
  423. return NULL;
  424. }
  425. return result;
  426. }
  427. Token *
  428. _PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
  429. if (p->error_indicator == 1) {
  430. return NULL;
  431. }
  432. if (p->mark == p->fill) {
  433. if (_PyPegen_fill_token(p) < 0) {
  434. p->error_indicator = 1;
  435. return NULL;
  436. }
  437. }
  438. Token *t = p->tokens[p->mark];
  439. if (t->type != type) {
  440. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
  441. return NULL;
  442. }
  443. p->mark += 1;
  444. return t;
  445. }
  446. expr_ty
  447. _PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
  448. {
  449. if (p->mark == p->fill) {
  450. if (_PyPegen_fill_token(p) < 0) {
  451. p->error_indicator = 1;
  452. return NULL;
  453. }
  454. }
  455. Token *t = p->tokens[p->mark];
  456. if (t->type != NAME) {
  457. return NULL;
  458. }
  459. const char *s = PyBytes_AsString(t->bytes);
  460. if (!s) {
  461. p->error_indicator = 1;
  462. return NULL;
  463. }
  464. if (strcmp(s, keyword) != 0) {
  465. return NULL;
  466. }
  467. return _PyPegen_name_token(p);
  468. }
  469. Token *
  470. _PyPegen_get_last_nonnwhitespace_token(Parser *p)
  471. {
  472. assert(p->mark >= 0);
  473. Token *token = NULL;
  474. for (int m = p->mark - 1; m >= 0; m--) {
  475. token = p->tokens[m];
  476. if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
  477. break;
  478. }
  479. }
  480. return token;
  481. }
  482. PyObject *
  483. _PyPegen_new_identifier(Parser *p, const char *n)
  484. {
  485. PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
  486. if (!id) {
  487. goto error;
  488. }
  489. /* PyUnicode_DecodeUTF8 should always return a ready string. */
  490. assert(PyUnicode_IS_READY(id));
  491. /* Check whether there are non-ASCII characters in the
  492. identifier; if so, normalize to NFKC. */
  493. if (!PyUnicode_IS_ASCII(id))
  494. {
  495. PyObject *id2;
  496. if (!init_normalization(p))
  497. {
  498. Py_DECREF(id);
  499. goto error;
  500. }
  501. PyObject *form = PyUnicode_InternFromString("NFKC");
  502. if (form == NULL)
  503. {
  504. Py_DECREF(id);
  505. goto error;
  506. }
  507. PyObject *args[2] = {form, id};
  508. id2 = _PyObject_FastCall(p->normalize, args, 2);
  509. Py_DECREF(id);
  510. Py_DECREF(form);
  511. if (!id2) {
  512. goto error;
  513. }
  514. if (!PyUnicode_Check(id2))
  515. {
  516. PyErr_Format(PyExc_TypeError,
  517. "unicodedata.normalize() must return a string, not "
  518. "%.200s",
  519. _PyType_Name(Py_TYPE(id2)));
  520. Py_DECREF(id2);
  521. goto error;
  522. }
  523. id = id2;
  524. }
  525. PyInterpreterState *interp = _PyInterpreterState_GET();
  526. _PyUnicode_InternImmortal(interp, &id);
  527. if (_PyArena_AddPyObject(p->arena, id) < 0)
  528. {
  529. Py_DECREF(id);
  530. goto error;
  531. }
  532. return id;
  533. error:
  534. p->error_indicator = 1;
  535. return NULL;
  536. }
  537. static expr_ty
  538. _PyPegen_name_from_token(Parser *p, Token* t)
  539. {
  540. if (t == NULL) {
  541. return NULL;
  542. }
  543. const char *s = PyBytes_AsString(t->bytes);
  544. if (!s) {
  545. p->error_indicator = 1;
  546. return NULL;
  547. }
  548. PyObject *id = _PyPegen_new_identifier(p, s);
  549. if (id == NULL) {
  550. p->error_indicator = 1;
  551. return NULL;
  552. }
  553. return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
  554. t->end_col_offset, p->arena);
  555. }
  556. expr_ty
  557. _PyPegen_name_token(Parser *p)
  558. {
  559. Token *t = _PyPegen_expect_token(p, NAME);
  560. return _PyPegen_name_from_token(p, t);
  561. }
  562. void *
  563. _PyPegen_string_token(Parser *p)
  564. {
  565. return _PyPegen_expect_token(p, STRING);
  566. }
  567. expr_ty _PyPegen_soft_keyword_token(Parser *p) {
  568. Token *t = _PyPegen_expect_token(p, NAME);
  569. if (t == NULL) {
  570. return NULL;
  571. }
  572. char *the_token;
  573. Py_ssize_t size;
  574. PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
  575. for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
  576. if (strncmp(*keyword, the_token, size) == 0) {
  577. return _PyPegen_name_from_token(p, t);
  578. }
  579. }
  580. return NULL;
  581. }
  582. static PyObject *
  583. parsenumber_raw(const char *s)
  584. {
  585. const char *end;
  586. long x;
  587. double dx;
  588. Py_complex compl;
  589. int imflag;
  590. assert(s != NULL);
  591. errno = 0;
  592. end = s + strlen(s) - 1;
  593. imflag = *end == 'j' || *end == 'J';
  594. if (s[0] == '0') {
  595. x = (long)PyOS_strtoul(s, (char **)&end, 0);
  596. if (x < 0 && errno == 0) {
  597. return PyLong_FromString(s, (char **)0, 0);
  598. }
  599. }
  600. else {
  601. x = PyOS_strtol(s, (char **)&end, 0);
  602. }
  603. if (*end == '\0') {
  604. if (errno != 0) {
  605. return PyLong_FromString(s, (char **)0, 0);
  606. }
  607. return PyLong_FromLong(x);
  608. }
  609. /* XXX Huge floats may silently fail */
  610. if (imflag) {
  611. compl.real = 0.;
  612. compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
  613. if (compl.imag == -1.0 && PyErr_Occurred()) {
  614. return NULL;
  615. }
  616. return PyComplex_FromCComplex(compl);
  617. }
  618. dx = PyOS_string_to_double(s, NULL, NULL);
  619. if (dx == -1.0 && PyErr_Occurred()) {
  620. return NULL;
  621. }
  622. return PyFloat_FromDouble(dx);
  623. }
  624. static PyObject *
  625. parsenumber(const char *s)
  626. {
  627. char *dup;
  628. char *end;
  629. PyObject *res = NULL;
  630. assert(s != NULL);
  631. if (strchr(s, '_') == NULL) {
  632. return parsenumber_raw(s);
  633. }
  634. /* Create a duplicate without underscores. */
  635. dup = PyMem_Malloc(strlen(s) + 1);
  636. if (dup == NULL) {
  637. return PyErr_NoMemory();
  638. }
  639. end = dup;
  640. for (; *s; s++) {
  641. if (*s != '_') {
  642. *end++ = *s;
  643. }
  644. }
  645. *end = '\0';
  646. res = parsenumber_raw(dup);
  647. PyMem_Free(dup);
  648. return res;
  649. }
  650. expr_ty
  651. _PyPegen_number_token(Parser *p)
  652. {
  653. Token *t = _PyPegen_expect_token(p, NUMBER);
  654. if (t == NULL) {
  655. return NULL;
  656. }
  657. const char *num_raw = PyBytes_AsString(t->bytes);
  658. if (num_raw == NULL) {
  659. p->error_indicator = 1;
  660. return NULL;
  661. }
  662. if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
  663. p->error_indicator = 1;
  664. return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
  665. "in Python 3.6 and greater");
  666. }
  667. PyObject *c = parsenumber(num_raw);
  668. if (c == NULL) {
  669. p->error_indicator = 1;
  670. PyThreadState *tstate = _PyThreadState_GET();
  671. // The only way a ValueError should happen in _this_ code is via
  672. // PyLong_FromString hitting a length limit.
  673. if (tstate->current_exception != NULL &&
  674. Py_TYPE(tstate->current_exception) == (PyTypeObject *)PyExc_ValueError
  675. ) {
  676. PyObject *exc = PyErr_GetRaisedException();
  677. /* Intentionally omitting columns to avoid a wall of 1000s of '^'s
  678. * on the error message. Nobody is going to overlook their huge
  679. * numeric literal once given the line. */
  680. RAISE_ERROR_KNOWN_LOCATION(
  681. p, PyExc_SyntaxError,
  682. t->lineno, -1 /* col_offset */,
  683. t->end_lineno, -1 /* end_col_offset */,
  684. "%S - Consider hexadecimal for huge integer literals "
  685. "to avoid decimal conversion limits.",
  686. exc);
  687. Py_DECREF(exc);
  688. }
  689. return NULL;
  690. }
  691. if (_PyArena_AddPyObject(p->arena, c) < 0) {
  692. Py_DECREF(c);
  693. p->error_indicator = 1;
  694. return NULL;
  695. }
  696. return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
  697. t->end_col_offset, p->arena);
  698. }
  699. /* Check that the source for a single input statement really is a single
  700. statement by looking at what is left in the buffer after parsing.
  701. Trailing whitespace and comments are OK. */
  702. static int // bool
  703. bad_single_statement(Parser *p)
  704. {
  705. char *cur = p->tok->cur;
  706. char c = *cur;
  707. for (;;) {
  708. while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
  709. c = *++cur;
  710. }
  711. if (!c) {
  712. return 0;
  713. }
  714. if (c != '#') {
  715. return 1;
  716. }
  717. /* Suck up comment. */
  718. while (c && c != '\n') {
  719. c = *++cur;
  720. }
  721. }
  722. }
  723. static int
  724. compute_parser_flags(PyCompilerFlags *flags)
  725. {
  726. int parser_flags = 0;
  727. if (!flags) {
  728. return 0;
  729. }
  730. if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
  731. parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
  732. }
  733. if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
  734. parser_flags |= PyPARSE_IGNORE_COOKIE;
  735. }
  736. if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
  737. parser_flags |= PyPARSE_BARRY_AS_BDFL;
  738. }
  739. if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
  740. parser_flags |= PyPARSE_TYPE_COMMENTS;
  741. }
  742. if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
  743. parser_flags |= PyPARSE_ASYNC_HACKS;
  744. }
  745. if (flags->cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT) {
  746. parser_flags |= PyPARSE_ALLOW_INCOMPLETE_INPUT;
  747. }
  748. return parser_flags;
  749. }
  750. // Parser API
  751. Parser *
  752. _PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
  753. int feature_version, int *errcode, PyArena *arena)
  754. {
  755. Parser *p = PyMem_Malloc(sizeof(Parser));
  756. if (p == NULL) {
  757. return (Parser *) PyErr_NoMemory();
  758. }
  759. assert(tok != NULL);
  760. tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
  761. tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
  762. p->tok = tok;
  763. p->keywords = NULL;
  764. p->n_keyword_lists = -1;
  765. p->soft_keywords = NULL;
  766. p->tokens = PyMem_Malloc(sizeof(Token *));
  767. if (!p->tokens) {
  768. PyMem_Free(p);
  769. return (Parser *) PyErr_NoMemory();
  770. }
  771. p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
  772. if (!p->tokens[0]) {
  773. PyMem_Free(p->tokens);
  774. PyMem_Free(p);
  775. return (Parser *) PyErr_NoMemory();
  776. }
  777. if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
  778. PyMem_Free(p->tokens[0]);
  779. PyMem_Free(p->tokens);
  780. PyMem_Free(p);
  781. return (Parser *) PyErr_NoMemory();
  782. }
  783. p->mark = 0;
  784. p->fill = 0;
  785. p->size = 1;
  786. p->errcode = errcode;
  787. p->arena = arena;
  788. p->start_rule = start_rule;
  789. p->parsing_started = 0;
  790. p->normalize = NULL;
  791. p->error_indicator = 0;
  792. p->starting_lineno = 0;
  793. p->starting_col_offset = 0;
  794. p->flags = flags;
  795. p->feature_version = feature_version;
  796. p->known_err_token = NULL;
  797. p->level = 0;
  798. p->call_invalid_rules = 0;
  799. #ifdef Py_DEBUG
  800. p->debug = _Py_GetConfig()->parser_debug;
  801. #endif
  802. return p;
  803. }
  804. void
  805. _PyPegen_Parser_Free(Parser *p)
  806. {
  807. Py_XDECREF(p->normalize);
  808. for (int i = 0; i < p->size; i++) {
  809. PyMem_Free(p->tokens[i]);
  810. }
  811. PyMem_Free(p->tokens);
  812. growable_comment_array_deallocate(&p->type_ignore_comments);
  813. PyMem_Free(p);
  814. }
  815. static void
  816. reset_parser_state_for_error_pass(Parser *p)
  817. {
  818. for (int i = 0; i < p->fill; i++) {
  819. p->tokens[i]->memo = NULL;
  820. }
  821. p->mark = 0;
  822. p->call_invalid_rules = 1;
  823. // Don't try to get extra tokens in interactive mode when trying to
  824. // raise specialized errors in the second pass.
  825. p->tok->interactive_underflow = IUNDERFLOW_STOP;
  826. }
  827. static inline int
  828. _is_end_of_source(Parser *p) {
  829. int err = p->tok->done;
  830. return err == E_EOF || err == E_EOFS || err == E_EOLS;
  831. }
  832. void *
  833. _PyPegen_run_parser(Parser *p)
  834. {
  835. void *res = _PyPegen_parse(p);
  836. assert(p->level == 0);
  837. if (res == NULL) {
  838. if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) && _is_end_of_source(p)) {
  839. PyErr_Clear();
  840. return RAISE_SYNTAX_ERROR("incomplete input");
  841. }
  842. if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
  843. return NULL;
  844. }
  845. // Make a second parser pass. In this pass we activate heavier and slower checks
  846. // to produce better error messages and more complete diagnostics. Extra "invalid_*"
  847. // rules will be active during parsing.
  848. Token *last_token = p->tokens[p->fill - 1];
  849. reset_parser_state_for_error_pass(p);
  850. _PyPegen_parse(p);
  851. // Set SyntaxErrors accordingly depending on the parser/tokenizer status at the failure
  852. // point.
  853. _Pypegen_set_syntax_error(p, last_token);
  854. return NULL;
  855. }
  856. if (p->start_rule == Py_single_input && bad_single_statement(p)) {
  857. p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
  858. return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
  859. }
  860. // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
  861. #if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
  862. if (p->start_rule == Py_single_input ||
  863. p->start_rule == Py_file_input ||
  864. p->start_rule == Py_eval_input)
  865. {
  866. if (!_PyAST_Validate(res)) {
  867. return NULL;
  868. }
  869. }
  870. #endif
  871. return res;
  872. }
  873. mod_ty
  874. _PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
  875. const char *enc, const char *ps1, const char *ps2,
  876. PyCompilerFlags *flags, int *errcode, PyArena *arena)
  877. {
  878. struct tok_state *tok = _PyTokenizer_FromFile(fp, enc, ps1, ps2);
  879. if (tok == NULL) {
  880. if (PyErr_Occurred()) {
  881. _PyPegen_raise_tokenizer_init_error(filename_ob);
  882. return NULL;
  883. }
  884. return NULL;
  885. }
  886. if (!tok->fp || ps1 != NULL || ps2 != NULL ||
  887. PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
  888. tok->fp_interactive = 1;
  889. }
  890. // This transfers the ownership to the tokenizer
  891. tok->filename = Py_NewRef(filename_ob);
  892. // From here on we need to clean up even if there's an error
  893. mod_ty result = NULL;
  894. int parser_flags = compute_parser_flags(flags);
  895. Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
  896. errcode, arena);
  897. if (p == NULL) {
  898. goto error;
  899. }
  900. result = _PyPegen_run_parser(p);
  901. _PyPegen_Parser_Free(p);
  902. error:
  903. _PyTokenizer_Free(tok);
  904. return result;
  905. }
  906. mod_ty
  907. _PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
  908. PyCompilerFlags *flags, PyArena *arena)
  909. {
  910. int exec_input = start_rule == Py_file_input;
  911. struct tok_state *tok;
  912. if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
  913. tok = _PyTokenizer_FromUTF8(str, exec_input, 0);
  914. } else {
  915. tok = _PyTokenizer_FromString(str, exec_input, 0);
  916. }
  917. if (tok == NULL) {
  918. if (PyErr_Occurred()) {
  919. _PyPegen_raise_tokenizer_init_error(filename_ob);
  920. }
  921. return NULL;
  922. }
  923. // This transfers the ownership to the tokenizer
  924. tok->filename = Py_NewRef(filename_ob);
  925. // We need to clear up from here on
  926. mod_ty result = NULL;
  927. int parser_flags = compute_parser_flags(flags);
  928. int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
  929. flags->cf_feature_version : PY_MINOR_VERSION;
  930. Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
  931. NULL, arena);
  932. if (p == NULL) {
  933. goto error;
  934. }
  935. result = _PyPegen_run_parser(p);
  936. _PyPegen_Parser_Free(p);
  937. error:
  938. _PyTokenizer_Free(tok);
  939. return result;
  940. }