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.

1227 lines
38 KiB

  1. #include <stdbool.h>
  2. #include <Python.h>
  3. #include "tokenizer.h"
  4. #include "pegen.h"
  5. #include "string_parser.h"
  6. //// STRING HANDLING FUNCTIONS ////
  7. static int
  8. warn_invalid_escape_sequence(Parser *p, unsigned char first_invalid_escape_char, Token *t)
  9. {
  10. PyObject *msg =
  11. PyUnicode_FromFormat("invalid escape sequence '\\%c'", first_invalid_escape_char);
  12. if (msg == NULL) {
  13. return -1;
  14. }
  15. if (PyErr_WarnExplicitObject(PyExc_DeprecationWarning, msg, p->tok->filename,
  16. t->lineno, NULL, NULL) < 0) {
  17. if (PyErr_ExceptionMatches(PyExc_DeprecationWarning)) {
  18. /* Replace the DeprecationWarning exception with a SyntaxError
  19. to get a more accurate error report */
  20. PyErr_Clear();
  21. /* This is needed, in order for the SyntaxError to point to the token t,
  22. since _PyPegen_raise_error uses p->tokens[p->fill - 1] for the
  23. error location, if p->known_err_token is not set. */
  24. p->known_err_token = t;
  25. RAISE_SYNTAX_ERROR("invalid escape sequence '\\%c'", first_invalid_escape_char);
  26. }
  27. Py_DECREF(msg);
  28. return -1;
  29. }
  30. Py_DECREF(msg);
  31. return 0;
  32. }
  33. static PyObject *
  34. decode_utf8(const char **sPtr, const char *end)
  35. {
  36. const char *s;
  37. const char *t;
  38. t = s = *sPtr;
  39. while (s < end && (*s & 0x80)) {
  40. s++;
  41. }
  42. *sPtr = s;
  43. return PyUnicode_DecodeUTF8(t, s - t, NULL);
  44. }
  45. static PyObject *
  46. decode_unicode_with_escapes(Parser *parser, const char *s, size_t len, Token *t)
  47. {
  48. PyObject *v;
  49. PyObject *u;
  50. char *buf;
  51. char *p;
  52. const char *end;
  53. /* check for integer overflow */
  54. if (len > SIZE_MAX / 6) {
  55. return NULL;
  56. }
  57. /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
  58. "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
  59. u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
  60. if (u == NULL) {
  61. return NULL;
  62. }
  63. p = buf = PyBytes_AsString(u);
  64. if (p == NULL) {
  65. return NULL;
  66. }
  67. end = s + len;
  68. while (s < end) {
  69. if (*s == '\\') {
  70. *p++ = *s++;
  71. if (s >= end || *s & 0x80) {
  72. strcpy(p, "u005c");
  73. p += 5;
  74. if (s >= end) {
  75. break;
  76. }
  77. }
  78. }
  79. if (*s & 0x80) {
  80. PyObject *w;
  81. int kind;
  82. const void *data;
  83. Py_ssize_t w_len;
  84. Py_ssize_t i;
  85. w = decode_utf8(&s, end);
  86. if (w == NULL) {
  87. Py_DECREF(u);
  88. return NULL;
  89. }
  90. kind = PyUnicode_KIND(w);
  91. data = PyUnicode_DATA(w);
  92. w_len = PyUnicode_GET_LENGTH(w);
  93. for (i = 0; i < w_len; i++) {
  94. Py_UCS4 chr = PyUnicode_READ(kind, data, i);
  95. sprintf(p, "\\U%08x", chr);
  96. p += 10;
  97. }
  98. /* Should be impossible to overflow */
  99. assert(p - buf <= PyBytes_GET_SIZE(u));
  100. Py_DECREF(w);
  101. }
  102. else {
  103. *p++ = *s++;
  104. }
  105. }
  106. len = p - buf;
  107. s = buf;
  108. const char *first_invalid_escape;
  109. v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape);
  110. if (v != NULL && first_invalid_escape != NULL) {
  111. if (warn_invalid_escape_sequence(parser, *first_invalid_escape, t) < 0) {
  112. /* We have not decref u before because first_invalid_escape points
  113. inside u. */
  114. Py_XDECREF(u);
  115. Py_DECREF(v);
  116. return NULL;
  117. }
  118. }
  119. Py_XDECREF(u);
  120. return v;
  121. }
  122. static PyObject *
  123. decode_bytes_with_escapes(Parser *p, const char *s, Py_ssize_t len, Token *t)
  124. {
  125. const char *first_invalid_escape;
  126. PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, &first_invalid_escape);
  127. if (result == NULL) {
  128. return NULL;
  129. }
  130. if (first_invalid_escape != NULL) {
  131. if (warn_invalid_escape_sequence(p, *first_invalid_escape, t) < 0) {
  132. Py_DECREF(result);
  133. return NULL;
  134. }
  135. }
  136. return result;
  137. }
  138. /* s must include the bracketing quote characters, and r, b, u,
  139. &/or f prefixes (if any), and embedded escape sequences (if any).
  140. _PyPegen_parsestr parses it, and sets *result to decoded Python string object.
  141. If the string is an f-string, set *fstr and *fstrlen to the unparsed
  142. string object. Return 0 if no errors occurred. */
  143. int
  144. _PyPegen_parsestr(Parser *p, int *bytesmode, int *rawmode, PyObject **result,
  145. const char **fstr, Py_ssize_t *fstrlen, Token *t)
  146. {
  147. const char *s = PyBytes_AsString(t->bytes);
  148. if (s == NULL) {
  149. return -1;
  150. }
  151. size_t len;
  152. int quote = Py_CHARMASK(*s);
  153. int fmode = 0;
  154. *bytesmode = 0;
  155. *rawmode = 0;
  156. *result = NULL;
  157. *fstr = NULL;
  158. if (Py_ISALPHA(quote)) {
  159. while (!*bytesmode || !*rawmode) {
  160. if (quote == 'b' || quote == 'B') {
  161. quote =(unsigned char)*++s;
  162. *bytesmode = 1;
  163. }
  164. else if (quote == 'u' || quote == 'U') {
  165. quote = (unsigned char)*++s;
  166. }
  167. else if (quote == 'r' || quote == 'R') {
  168. quote = (unsigned char)*++s;
  169. *rawmode = 1;
  170. }
  171. else if (quote == 'f' || quote == 'F') {
  172. quote = (unsigned char)*++s;
  173. fmode = 1;
  174. }
  175. else {
  176. break;
  177. }
  178. }
  179. }
  180. /* fstrings are only allowed in Python 3.6 and greater */
  181. if (fmode && p->feature_version < 6) {
  182. p->error_indicator = 1;
  183. RAISE_SYNTAX_ERROR("Format strings are only supported in Python 3.6 and greater");
  184. return -1;
  185. }
  186. if (fmode && *bytesmode) {
  187. PyErr_BadInternalCall();
  188. return -1;
  189. }
  190. if (quote != '\'' && quote != '\"') {
  191. PyErr_BadInternalCall();
  192. return -1;
  193. }
  194. /* Skip the leading quote char. */
  195. s++;
  196. len = strlen(s);
  197. if (len > INT_MAX) {
  198. PyErr_SetString(PyExc_OverflowError, "string to parse is too long");
  199. return -1;
  200. }
  201. if (s[--len] != quote) {
  202. /* Last quote char must match the first. */
  203. PyErr_BadInternalCall();
  204. return -1;
  205. }
  206. if (len >= 4 && s[0] == quote && s[1] == quote) {
  207. /* A triple quoted string. We've already skipped one quote at
  208. the start and one at the end of the string. Now skip the
  209. two at the start. */
  210. s += 2;
  211. len -= 2;
  212. /* And check that the last two match. */
  213. if (s[--len] != quote || s[--len] != quote) {
  214. PyErr_BadInternalCall();
  215. return -1;
  216. }
  217. }
  218. if (fmode) {
  219. /* Just return the bytes. The caller will parse the resulting
  220. string. */
  221. *fstr = s;
  222. *fstrlen = len;
  223. return 0;
  224. }
  225. /* Not an f-string. */
  226. /* Avoid invoking escape decoding routines if possible. */
  227. *rawmode = *rawmode || strchr(s, '\\') == NULL;
  228. if (*bytesmode) {
  229. /* Disallow non-ASCII characters. */
  230. const char *ch;
  231. for (ch = s; *ch; ch++) {
  232. if (Py_CHARMASK(*ch) >= 0x80) {
  233. RAISE_SYNTAX_ERROR(
  234. "bytes can only contain ASCII "
  235. "literal characters");
  236. return -1;
  237. }
  238. }
  239. if (*rawmode) {
  240. *result = PyBytes_FromStringAndSize(s, len);
  241. }
  242. else {
  243. *result = decode_bytes_with_escapes(p, s, len, t);
  244. }
  245. }
  246. else {
  247. if (*rawmode) {
  248. *result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL);
  249. }
  250. else {
  251. *result = decode_unicode_with_escapes(p, s, len, t);
  252. }
  253. }
  254. return *result == NULL ? -1 : 0;
  255. }
  256. // FSTRING STUFF
  257. /* Fix locations for the given node and its children.
  258. `parent` is the enclosing node.
  259. `expr_start` is the starting position of the expression (pointing to the open brace).
  260. `n` is the node which locations are going to be fixed relative to parent.
  261. `expr_str` is the child node's string representation, including braces.
  262. */
  263. static bool
  264. fstring_find_expr_location(Token *parent, const char* expr_start, char *expr_str, int *p_lines, int *p_cols)
  265. {
  266. *p_lines = 0;
  267. *p_cols = 0;
  268. assert(expr_start != NULL && *expr_start == '{');
  269. if (parent && parent->bytes) {
  270. const char *parent_str = PyBytes_AsString(parent->bytes);
  271. if (!parent_str) {
  272. return false;
  273. }
  274. // The following is needed, in order to correctly shift the column
  275. // offset, in the case that (disregarding any whitespace) a newline
  276. // immediately follows the opening curly brace of the fstring expression.
  277. bool newline_after_brace = 1;
  278. const char *start = expr_start + 1;
  279. while (start && *start != '}' && *start != '\n') {
  280. if (*start != ' ' && *start != '\t' && *start != '\f') {
  281. newline_after_brace = 0;
  282. break;
  283. }
  284. start++;
  285. }
  286. // Account for the characters from the last newline character to our
  287. // left until the beginning of expr_start.
  288. if (!newline_after_brace) {
  289. start = expr_start;
  290. while (start > parent_str && *start != '\n') {
  291. start--;
  292. }
  293. *p_cols += (int)(expr_start - start);
  294. }
  295. /* adjust the start based on the number of newlines encountered
  296. before the f-string expression */
  297. for (const char *p = parent_str; p < expr_start; p++) {
  298. if (*p == '\n') {
  299. (*p_lines)++;
  300. }
  301. }
  302. }
  303. return true;
  304. }
  305. /* Compile this expression in to an expr_ty. Add parens around the
  306. expression, in order to allow leading spaces in the expression. */
  307. static expr_ty
  308. fstring_compile_expr(Parser *p, const char *expr_start, const char *expr_end,
  309. Token *t)
  310. {
  311. expr_ty expr = NULL;
  312. char *str;
  313. Py_ssize_t len;
  314. const char *s;
  315. expr_ty result = NULL;
  316. assert(expr_end >= expr_start);
  317. assert(*(expr_start-1) == '{');
  318. assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':' ||
  319. *expr_end == '=');
  320. /* If the substring is all whitespace, it's an error. We need to catch this
  321. here, and not when we call PyParser_SimpleParseStringFlagsFilename,
  322. because turning the expression '' in to '()' would go from being invalid
  323. to valid. */
  324. for (s = expr_start; s != expr_end; s++) {
  325. char c = *s;
  326. /* The Python parser ignores only the following whitespace
  327. characters (\r already is converted to \n). */
  328. if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) {
  329. break;
  330. }
  331. }
  332. if (s == expr_end) {
  333. RAISE_SYNTAX_ERROR("f-string: empty expression not allowed");
  334. return NULL;
  335. }
  336. len = expr_end - expr_start;
  337. /* Allocate 3 extra bytes: open paren, close paren, null byte. */
  338. str = PyMem_Calloc(len + 3, sizeof(char));
  339. if (str == NULL) {
  340. PyErr_NoMemory();
  341. return NULL;
  342. }
  343. // The call to fstring_find_expr_location is responsible for finding the column offset
  344. // the generated AST nodes need to be shifted to the right, which is equal to the number
  345. // of the f-string characters before the expression starts.
  346. memcpy(str+1, expr_start, len);
  347. int lines, cols;
  348. if (!fstring_find_expr_location(t, expr_start-1, str+1, &lines, &cols)) {
  349. PyMem_Free(str);
  350. return NULL;
  351. }
  352. // The parentheses are needed in order to allow for leading whitespace within
  353. // the f-string expression. This consequently gets parsed as a group (see the
  354. // group rule in python.gram).
  355. str[0] = '(';
  356. str[len+1] = ')';
  357. struct tok_state* tok = PyTokenizer_FromString(str, 1);
  358. if (tok == NULL) {
  359. PyMem_Free(str);
  360. return NULL;
  361. }
  362. Py_INCREF(p->tok->filename);
  363. tok->filename = p->tok->filename;
  364. Parser *p2 = _PyPegen_Parser_New(tok, Py_fstring_input, p->flags, p->feature_version,
  365. NULL, p->arena);
  366. p2->starting_lineno = t->lineno + lines - 1;
  367. p2->starting_col_offset = t->col_offset + cols;
  368. expr = _PyPegen_run_parser(p2);
  369. if (expr == NULL) {
  370. goto exit;
  371. }
  372. result = expr;
  373. exit:
  374. PyMem_Free(str);
  375. _PyPegen_Parser_Free(p2);
  376. PyTokenizer_Free(tok);
  377. return result;
  378. }
  379. /* Return -1 on error.
  380. Return 0 if we reached the end of the literal.
  381. Return 1 if we haven't reached the end of the literal, but we want
  382. the caller to process the literal up to this point. Used for
  383. doubled braces.
  384. */
  385. static int
  386. fstring_find_literal(Parser *p, const char **str, const char *end, int raw,
  387. PyObject **literal, int recurse_lvl, Token *t)
  388. {
  389. /* Get any literal string. It ends when we hit an un-doubled left
  390. brace (which isn't part of a unicode name escape such as
  391. "\N{EULER CONSTANT}"), or the end of the string. */
  392. const char *s = *str;
  393. const char *literal_start = s;
  394. int result = 0;
  395. assert(*literal == NULL);
  396. while (s < end) {
  397. char ch = *s++;
  398. if (!raw && ch == '\\' && s < end) {
  399. ch = *s++;
  400. if (ch == 'N') {
  401. if (s < end && *s++ == '{') {
  402. while (s < end && *s++ != '}') {
  403. }
  404. continue;
  405. }
  406. break;
  407. }
  408. if (ch == '{' && warn_invalid_escape_sequence(p, ch, t) < 0) {
  409. return -1;
  410. }
  411. }
  412. if (ch == '{' || ch == '}') {
  413. /* Check for doubled braces, but only at the top level. If
  414. we checked at every level, then f'{0:{3}}' would fail
  415. with the two closing braces. */
  416. if (recurse_lvl == 0) {
  417. if (s < end && *s == ch) {
  418. /* We're going to tell the caller that the literal ends
  419. here, but that they should continue scanning. But also
  420. skip over the second brace when we resume scanning. */
  421. *str = s + 1;
  422. result = 1;
  423. goto done;
  424. }
  425. /* Where a single '{' is the start of a new expression, a
  426. single '}' is not allowed. */
  427. if (ch == '}') {
  428. *str = s - 1;
  429. RAISE_SYNTAX_ERROR("f-string: single '}' is not allowed");
  430. return -1;
  431. }
  432. }
  433. /* We're either at a '{', which means we're starting another
  434. expression; or a '}', which means we're at the end of this
  435. f-string (for a nested format_spec). */
  436. s--;
  437. break;
  438. }
  439. }
  440. *str = s;
  441. assert(s <= end);
  442. assert(s == end || *s == '{' || *s == '}');
  443. done:
  444. if (literal_start != s) {
  445. if (raw) {
  446. *literal = PyUnicode_DecodeUTF8Stateful(literal_start,
  447. s - literal_start,
  448. NULL, NULL);
  449. } else {
  450. *literal = decode_unicode_with_escapes(p, literal_start,
  451. s - literal_start, t);
  452. }
  453. if (!*literal) {
  454. return -1;
  455. }
  456. }
  457. return result;
  458. }
  459. /* Forward declaration because parsing is recursive. */
  460. static expr_ty
  461. fstring_parse(Parser *p, const char **str, const char *end, int raw, int recurse_lvl,
  462. Token *first_token, Token* t, Token *last_token);
  463. /* Parse the f-string at *str, ending at end. We know *str starts an
  464. expression (so it must be a '{'). Returns the FormattedValue node, which
  465. includes the expression, conversion character, format_spec expression, and
  466. optionally the text of the expression (if = is used).
  467. Note that I don't do a perfect job here: I don't make sure that a
  468. closing brace doesn't match an opening paren, for example. It
  469. doesn't need to error on all invalid expressions, just correctly
  470. find the end of all valid ones. Any errors inside the expression
  471. will be caught when we parse it later.
  472. *expression is set to the expression. For an '=' "debug" expression,
  473. *expr_text is set to the debug text (the original text of the expression,
  474. including the '=' and any whitespace around it, as a string object). If
  475. not a debug expression, *expr_text set to NULL. */
  476. static int
  477. fstring_find_expr(Parser *p, const char **str, const char *end, int raw, int recurse_lvl,
  478. PyObject **expr_text, expr_ty *expression, Token *first_token,
  479. Token *t, Token *last_token)
  480. {
  481. /* Return -1 on error, else 0. */
  482. const char *expr_start;
  483. const char *expr_end;
  484. expr_ty simple_expression;
  485. expr_ty format_spec = NULL; /* Optional format specifier. */
  486. int conversion = -1; /* The conversion char. Use default if not
  487. specified, or !r if using = and no format
  488. spec. */
  489. /* 0 if we're not in a string, else the quote char we're trying to
  490. match (single or double quote). */
  491. char quote_char = 0;
  492. /* If we're inside a string, 1=normal, 3=triple-quoted. */
  493. int string_type = 0;
  494. /* Keep track of nesting level for braces/parens/brackets in
  495. expressions. */
  496. Py_ssize_t nested_depth = 0;
  497. char parenstack[MAXLEVEL];
  498. *expr_text = NULL;
  499. /* Can only nest one level deep. */
  500. if (recurse_lvl >= 2) {
  501. RAISE_SYNTAX_ERROR("f-string: expressions nested too deeply");
  502. goto error;
  503. }
  504. /* The first char must be a left brace, or we wouldn't have gotten
  505. here. Skip over it. */
  506. assert(**str == '{');
  507. *str += 1;
  508. expr_start = *str;
  509. for (; *str < end; (*str)++) {
  510. char ch;
  511. /* Loop invariants. */
  512. assert(nested_depth >= 0);
  513. assert(*str >= expr_start && *str < end);
  514. if (quote_char) {
  515. assert(string_type == 1 || string_type == 3);
  516. } else {
  517. assert(string_type == 0);
  518. }
  519. ch = **str;
  520. /* Nowhere inside an expression is a backslash allowed. */
  521. if (ch == '\\') {
  522. /* Error: can't include a backslash character, inside
  523. parens or strings or not. */
  524. RAISE_SYNTAX_ERROR(
  525. "f-string expression part "
  526. "cannot include a backslash");
  527. goto error;
  528. }
  529. if (quote_char) {
  530. /* We're inside a string. See if we're at the end. */
  531. /* This code needs to implement the same non-error logic
  532. as tok_get from tokenizer.c, at the letter_quote
  533. label. To actually share that code would be a
  534. nightmare. But, it's unlikely to change and is small,
  535. so duplicate it here. Note we don't need to catch all
  536. of the errors, since they'll be caught when parsing the
  537. expression. We just need to match the non-error
  538. cases. Thus we can ignore \n in single-quoted strings,
  539. for example. Or non-terminated strings. */
  540. if (ch == quote_char) {
  541. /* Does this match the string_type (single or triple
  542. quoted)? */
  543. if (string_type == 3) {
  544. if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
  545. /* We're at the end of a triple quoted string. */
  546. *str += 2;
  547. string_type = 0;
  548. quote_char = 0;
  549. continue;
  550. }
  551. } else {
  552. /* We're at the end of a normal string. */
  553. quote_char = 0;
  554. string_type = 0;
  555. continue;
  556. }
  557. }
  558. } else if (ch == '\'' || ch == '"') {
  559. /* Is this a triple quoted string? */
  560. if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
  561. string_type = 3;
  562. *str += 2;
  563. } else {
  564. /* Start of a normal string. */
  565. string_type = 1;
  566. }
  567. /* Start looking for the end of the string. */
  568. quote_char = ch;
  569. } else if (ch == '[' || ch == '{' || ch == '(') {
  570. if (nested_depth >= MAXLEVEL) {
  571. RAISE_SYNTAX_ERROR("f-string: too many nested parenthesis");
  572. goto error;
  573. }
  574. parenstack[nested_depth] = ch;
  575. nested_depth++;
  576. } else if (ch == '#') {
  577. /* Error: can't include a comment character, inside parens
  578. or not. */
  579. RAISE_SYNTAX_ERROR("f-string expression part cannot include '#'");
  580. goto error;
  581. } else if (nested_depth == 0 &&
  582. (ch == '!' || ch == ':' || ch == '}' ||
  583. ch == '=' || ch == '>' || ch == '<')) {
  584. /* See if there's a next character. */
  585. if (*str+1 < end) {
  586. char next = *(*str+1);
  587. /* For "!=". since '=' is not an allowed conversion character,
  588. nothing is lost in this test. */
  589. if ((ch == '!' && next == '=') || /* != */
  590. (ch == '=' && next == '=') || /* == */
  591. (ch == '<' && next == '=') || /* <= */
  592. (ch == '>' && next == '=') /* >= */
  593. ) {
  594. *str += 1;
  595. continue;
  596. }
  597. /* Don't get out of the loop for these, if they're single
  598. chars (not part of 2-char tokens). If by themselves, they
  599. don't end an expression (unlike say '!'). */
  600. if (ch == '>' || ch == '<') {
  601. continue;
  602. }
  603. }
  604. /* Normal way out of this loop. */
  605. break;
  606. } else if (ch == ']' || ch == '}' || ch == ')') {
  607. if (!nested_depth) {
  608. RAISE_SYNTAX_ERROR("f-string: unmatched '%c'", ch);
  609. goto error;
  610. }
  611. nested_depth--;
  612. int opening = (unsigned char)parenstack[nested_depth];
  613. if (!((opening == '(' && ch == ')') ||
  614. (opening == '[' && ch == ']') ||
  615. (opening == '{' && ch == '}')))
  616. {
  617. RAISE_SYNTAX_ERROR(
  618. "f-string: closing parenthesis '%c' "
  619. "does not match opening parenthesis '%c'",
  620. ch, opening);
  621. goto error;
  622. }
  623. } else {
  624. /* Just consume this char and loop around. */
  625. }
  626. }
  627. expr_end = *str;
  628. /* If we leave this loop in a string or with mismatched parens, we
  629. don't care. We'll get a syntax error when compiling the
  630. expression. But, we can produce a better error message, so
  631. let's just do that.*/
  632. if (quote_char) {
  633. RAISE_SYNTAX_ERROR("f-string: unterminated string");
  634. goto error;
  635. }
  636. if (nested_depth) {
  637. int opening = (unsigned char)parenstack[nested_depth - 1];
  638. RAISE_SYNTAX_ERROR("f-string: unmatched '%c'", opening);
  639. goto error;
  640. }
  641. if (*str >= end) {
  642. goto unexpected_end_of_string;
  643. }
  644. /* Compile the expression as soon as possible, so we show errors
  645. related to the expression before errors related to the
  646. conversion or format_spec. */
  647. simple_expression = fstring_compile_expr(p, expr_start, expr_end, t);
  648. if (!simple_expression) {
  649. goto error;
  650. }
  651. /* Check for =, which puts the text value of the expression in
  652. expr_text. */
  653. if (**str == '=') {
  654. if (p->feature_version < 8) {
  655. RAISE_SYNTAX_ERROR("f-string: self documenting expressions are "
  656. "only supported in Python 3.8 and greater");
  657. goto error;
  658. }
  659. *str += 1;
  660. /* Skip over ASCII whitespace. No need to test for end of string
  661. here, since we know there's at least a trailing quote somewhere
  662. ahead. */
  663. while (Py_ISSPACE(**str)) {
  664. *str += 1;
  665. }
  666. /* Set *expr_text to the text of the expression. */
  667. *expr_text = PyUnicode_FromStringAndSize(expr_start, *str-expr_start);
  668. if (!*expr_text) {
  669. goto error;
  670. }
  671. }
  672. /* Check for a conversion char, if present. */
  673. if (**str == '!') {
  674. *str += 1;
  675. if (*str >= end) {
  676. goto unexpected_end_of_string;
  677. }
  678. conversion = (unsigned char)**str;
  679. *str += 1;
  680. /* Validate the conversion. */
  681. if (!(conversion == 's' || conversion == 'r' || conversion == 'a')) {
  682. RAISE_SYNTAX_ERROR(
  683. "f-string: invalid conversion character: "
  684. "expected 's', 'r', or 'a'");
  685. goto error;
  686. }
  687. }
  688. /* Check for the format spec, if present. */
  689. if (*str >= end) {
  690. goto unexpected_end_of_string;
  691. }
  692. if (**str == ':') {
  693. *str += 1;
  694. if (*str >= end) {
  695. goto unexpected_end_of_string;
  696. }
  697. /* Parse the format spec. */
  698. format_spec = fstring_parse(p, str, end, raw, recurse_lvl+1,
  699. first_token, t, last_token);
  700. if (!format_spec) {
  701. goto error;
  702. }
  703. }
  704. if (*str >= end || **str != '}') {
  705. goto unexpected_end_of_string;
  706. }
  707. /* We're at a right brace. Consume it. */
  708. assert(*str < end);
  709. assert(**str == '}');
  710. *str += 1;
  711. /* If we're in = mode (detected by non-NULL expr_text), and have no format
  712. spec and no explicit conversion, set the conversion to 'r'. */
  713. if (*expr_text && format_spec == NULL && conversion == -1) {
  714. conversion = 'r';
  715. }
  716. /* And now create the FormattedValue node that represents this
  717. entire expression with the conversion and format spec. */
  718. //TODO: Fix this
  719. *expression = _PyAST_FormattedValue(simple_expression, conversion,
  720. format_spec, first_token->lineno,
  721. first_token->col_offset,
  722. last_token->end_lineno,
  723. last_token->end_col_offset, p->arena);
  724. if (!*expression) {
  725. goto error;
  726. }
  727. return 0;
  728. unexpected_end_of_string:
  729. RAISE_SYNTAX_ERROR("f-string: expecting '}'");
  730. /* Falls through to error. */
  731. error:
  732. Py_XDECREF(*expr_text);
  733. return -1;
  734. }
  735. /* Return -1 on error.
  736. Return 0 if we have a literal (possible zero length) and an
  737. expression (zero length if at the end of the string.
  738. Return 1 if we have a literal, but no expression, and we want the
  739. caller to call us again. This is used to deal with doubled
  740. braces.
  741. When called multiple times on the string 'a{{b{0}c', this function
  742. will return:
  743. 1. the literal 'a{' with no expression, and a return value
  744. of 1. Despite the fact that there's no expression, the return
  745. value of 1 means we're not finished yet.
  746. 2. the literal 'b' and the expression '0', with a return value of
  747. 0. The fact that there's an expression means we're not finished.
  748. 3. literal 'c' with no expression and a return value of 0. The
  749. combination of the return value of 0 with no expression means
  750. we're finished.
  751. */
  752. static int
  753. fstring_find_literal_and_expr(Parser *p, const char **str, const char *end, int raw,
  754. int recurse_lvl, PyObject **literal,
  755. PyObject **expr_text, expr_ty *expression,
  756. Token *first_token, Token *t, Token *last_token)
  757. {
  758. int result;
  759. assert(*literal == NULL && *expression == NULL);
  760. /* Get any literal string. */
  761. result = fstring_find_literal(p, str, end, raw, literal, recurse_lvl, t);
  762. if (result < 0) {
  763. goto error;
  764. }
  765. assert(result == 0 || result == 1);
  766. if (result == 1) {
  767. /* We have a literal, but don't look at the expression. */
  768. return 1;
  769. }
  770. if (*str >= end || **str == '}') {
  771. /* We're at the end of the string or the end of a nested
  772. f-string: no expression. The top-level error case where we
  773. expect to be at the end of the string but we're at a '}' is
  774. handled later. */
  775. return 0;
  776. }
  777. /* We must now be the start of an expression, on a '{'. */
  778. assert(**str == '{');
  779. if (fstring_find_expr(p, str, end, raw, recurse_lvl, expr_text,
  780. expression, first_token, t, last_token) < 0) {
  781. goto error;
  782. }
  783. return 0;
  784. error:
  785. Py_CLEAR(*literal);
  786. return -1;
  787. }
  788. #ifdef NDEBUG
  789. #define ExprList_check_invariants(l)
  790. #else
  791. static void
  792. ExprList_check_invariants(ExprList *l)
  793. {
  794. /* Check our invariants. Make sure this object is "live", and
  795. hasn't been deallocated. */
  796. assert(l->size >= 0);
  797. assert(l->p != NULL);
  798. if (l->size <= EXPRLIST_N_CACHED) {
  799. assert(l->data == l->p);
  800. }
  801. }
  802. #endif
  803. static void
  804. ExprList_Init(ExprList *l)
  805. {
  806. l->allocated = EXPRLIST_N_CACHED;
  807. l->size = 0;
  808. /* Until we start allocating dynamically, p points to data. */
  809. l->p = l->data;
  810. ExprList_check_invariants(l);
  811. }
  812. static int
  813. ExprList_Append(ExprList *l, expr_ty exp)
  814. {
  815. ExprList_check_invariants(l);
  816. if (l->size >= l->allocated) {
  817. /* We need to alloc (or realloc) the memory. */
  818. Py_ssize_t new_size = l->allocated * 2;
  819. /* See if we've ever allocated anything dynamically. */
  820. if (l->p == l->data) {
  821. Py_ssize_t i;
  822. /* We're still using the cached data. Switch to
  823. alloc-ing. */
  824. l->p = PyMem_Malloc(sizeof(expr_ty) * new_size);
  825. if (!l->p) {
  826. return -1;
  827. }
  828. /* Copy the cached data into the new buffer. */
  829. for (i = 0; i < l->size; i++) {
  830. l->p[i] = l->data[i];
  831. }
  832. } else {
  833. /* Just realloc. */
  834. expr_ty *tmp = PyMem_Realloc(l->p, sizeof(expr_ty) * new_size);
  835. if (!tmp) {
  836. PyMem_Free(l->p);
  837. l->p = NULL;
  838. return -1;
  839. }
  840. l->p = tmp;
  841. }
  842. l->allocated = new_size;
  843. assert(l->allocated == 2 * l->size);
  844. }
  845. l->p[l->size++] = exp;
  846. ExprList_check_invariants(l);
  847. return 0;
  848. }
  849. static void
  850. ExprList_Dealloc(ExprList *l)
  851. {
  852. ExprList_check_invariants(l);
  853. /* If there's been an error, or we've never dynamically allocated,
  854. do nothing. */
  855. if (!l->p || l->p == l->data) {
  856. /* Do nothing. */
  857. } else {
  858. /* We have dynamically allocated. Free the memory. */
  859. PyMem_Free(l->p);
  860. }
  861. l->p = NULL;
  862. l->size = -1;
  863. }
  864. static asdl_expr_seq *
  865. ExprList_Finish(ExprList *l, PyArena *arena)
  866. {
  867. asdl_expr_seq *seq;
  868. ExprList_check_invariants(l);
  869. /* Allocate the asdl_seq and copy the expressions in to it. */
  870. seq = _Py_asdl_expr_seq_new(l->size, arena);
  871. if (seq) {
  872. Py_ssize_t i;
  873. for (i = 0; i < l->size; i++) {
  874. asdl_seq_SET(seq, i, l->p[i]);
  875. }
  876. }
  877. ExprList_Dealloc(l);
  878. return seq;
  879. }
  880. #ifdef NDEBUG
  881. #define FstringParser_check_invariants(state)
  882. #else
  883. static void
  884. FstringParser_check_invariants(FstringParser *state)
  885. {
  886. if (state->last_str) {
  887. assert(PyUnicode_CheckExact(state->last_str));
  888. }
  889. ExprList_check_invariants(&state->expr_list);
  890. }
  891. #endif
  892. void
  893. _PyPegen_FstringParser_Init(FstringParser *state)
  894. {
  895. state->last_str = NULL;
  896. state->fmode = 0;
  897. ExprList_Init(&state->expr_list);
  898. FstringParser_check_invariants(state);
  899. }
  900. void
  901. _PyPegen_FstringParser_Dealloc(FstringParser *state)
  902. {
  903. FstringParser_check_invariants(state);
  904. Py_XDECREF(state->last_str);
  905. ExprList_Dealloc(&state->expr_list);
  906. }
  907. /* Make a Constant node, but decref the PyUnicode object being added. */
  908. static expr_ty
  909. make_str_node_and_del(Parser *p, PyObject **str, Token* first_token, Token *last_token)
  910. {
  911. PyObject *s = *str;
  912. PyObject *kind = NULL;
  913. *str = NULL;
  914. assert(PyUnicode_CheckExact(s));
  915. if (_PyArena_AddPyObject(p->arena, s) < 0) {
  916. Py_DECREF(s);
  917. return NULL;
  918. }
  919. const char* the_str = PyBytes_AsString(first_token->bytes);
  920. if (the_str && the_str[0] == 'u') {
  921. kind = _PyPegen_new_identifier(p, "u");
  922. }
  923. if (kind == NULL && PyErr_Occurred()) {
  924. return NULL;
  925. }
  926. return _PyAST_Constant(s, kind, first_token->lineno, first_token->col_offset,
  927. last_token->end_lineno, last_token->end_col_offset,
  928. p->arena);
  929. }
  930. /* Add a non-f-string (that is, a regular literal string). str is
  931. decref'd. */
  932. int
  933. _PyPegen_FstringParser_ConcatAndDel(FstringParser *state, PyObject *str)
  934. {
  935. FstringParser_check_invariants(state);
  936. assert(PyUnicode_CheckExact(str));
  937. if (PyUnicode_GET_LENGTH(str) == 0) {
  938. Py_DECREF(str);
  939. return 0;
  940. }
  941. if (!state->last_str) {
  942. /* We didn't have a string before, so just remember this one. */
  943. state->last_str = str;
  944. } else {
  945. /* Concatenate this with the previous string. */
  946. PyUnicode_AppendAndDel(&state->last_str, str);
  947. if (!state->last_str) {
  948. return -1;
  949. }
  950. }
  951. FstringParser_check_invariants(state);
  952. return 0;
  953. }
  954. /* Parse an f-string. The f-string is in *str to end, with no
  955. 'f' or quotes. */
  956. int
  957. _PyPegen_FstringParser_ConcatFstring(Parser *p, FstringParser *state, const char **str,
  958. const char *end, int raw, int recurse_lvl,
  959. Token *first_token, Token* t, Token *last_token)
  960. {
  961. FstringParser_check_invariants(state);
  962. state->fmode = 1;
  963. /* Parse the f-string. */
  964. while (1) {
  965. PyObject *literal = NULL;
  966. PyObject *expr_text = NULL;
  967. expr_ty expression = NULL;
  968. /* If there's a zero length literal in front of the
  969. expression, literal will be NULL. If we're at the end of
  970. the f-string, expression will be NULL (unless result == 1,
  971. see below). */
  972. int result = fstring_find_literal_and_expr(p, str, end, raw, recurse_lvl,
  973. &literal, &expr_text,
  974. &expression, first_token, t, last_token);
  975. if (result < 0) {
  976. return -1;
  977. }
  978. /* Add the literal, if any. */
  979. if (literal && _PyPegen_FstringParser_ConcatAndDel(state, literal) < 0) {
  980. Py_XDECREF(expr_text);
  981. return -1;
  982. }
  983. /* Add the expr_text, if any. */
  984. if (expr_text && _PyPegen_FstringParser_ConcatAndDel(state, expr_text) < 0) {
  985. return -1;
  986. }
  987. /* We've dealt with the literal and expr_text, their ownership has
  988. been transferred to the state object. Don't look at them again. */
  989. /* See if we should just loop around to get the next literal
  990. and expression, while ignoring the expression this
  991. time. This is used for un-doubling braces, as an
  992. optimization. */
  993. if (result == 1) {
  994. continue;
  995. }
  996. if (!expression) {
  997. /* We're done with this f-string. */
  998. break;
  999. }
  1000. /* We know we have an expression. Convert any existing string
  1001. to a Constant node. */
  1002. if (!state->last_str) {
  1003. /* Do nothing. No previous literal. */
  1004. } else {
  1005. /* Convert the existing last_str literal to a Constant node. */
  1006. expr_ty last_str = make_str_node_and_del(p, &state->last_str, first_token, last_token);
  1007. if (!last_str || ExprList_Append(&state->expr_list, last_str) < 0) {
  1008. return -1;
  1009. }
  1010. }
  1011. if (ExprList_Append(&state->expr_list, expression) < 0) {
  1012. return -1;
  1013. }
  1014. }
  1015. /* If recurse_lvl is zero, then we must be at the end of the
  1016. string. Otherwise, we must be at a right brace. */
  1017. if (recurse_lvl == 0 && *str < end-1) {
  1018. RAISE_SYNTAX_ERROR("f-string: unexpected end of string");
  1019. return -1;
  1020. }
  1021. if (recurse_lvl != 0 && **str != '}') {
  1022. RAISE_SYNTAX_ERROR("f-string: expecting '}'");
  1023. return -1;
  1024. }
  1025. FstringParser_check_invariants(state);
  1026. return 0;
  1027. }
  1028. /* Convert the partial state reflected in last_str and expr_list to an
  1029. expr_ty. The expr_ty can be a Constant, or a JoinedStr. */
  1030. expr_ty
  1031. _PyPegen_FstringParser_Finish(Parser *p, FstringParser *state, Token* first_token,
  1032. Token *last_token)
  1033. {
  1034. asdl_expr_seq *seq;
  1035. FstringParser_check_invariants(state);
  1036. /* If we're just a constant string with no expressions, return
  1037. that. */
  1038. if (!state->fmode) {
  1039. assert(!state->expr_list.size);
  1040. if (!state->last_str) {
  1041. /* Create a zero length string. */
  1042. state->last_str = PyUnicode_FromStringAndSize(NULL, 0);
  1043. if (!state->last_str) {
  1044. goto error;
  1045. }
  1046. }
  1047. return make_str_node_and_del(p, &state->last_str, first_token, last_token);
  1048. }
  1049. /* Create a Constant node out of last_str, if needed. It will be the
  1050. last node in our expression list. */
  1051. if (state->last_str) {
  1052. expr_ty str = make_str_node_and_del(p, &state->last_str, first_token, last_token);
  1053. if (!str || ExprList_Append(&state->expr_list, str) < 0) {
  1054. goto error;
  1055. }
  1056. }
  1057. /* This has already been freed. */
  1058. assert(state->last_str == NULL);
  1059. seq = ExprList_Finish(&state->expr_list, p->arena);
  1060. if (!seq) {
  1061. goto error;
  1062. }
  1063. return _PyAST_JoinedStr(seq, first_token->lineno, first_token->col_offset,
  1064. last_token->end_lineno, last_token->end_col_offset,
  1065. p->arena);
  1066. error:
  1067. _PyPegen_FstringParser_Dealloc(state);
  1068. return NULL;
  1069. }
  1070. /* Given an f-string (with no 'f' or quotes) that's in *str and ends
  1071. at end, parse it into an expr_ty. Return NULL on error. Adjust
  1072. str to point past the parsed portion. */
  1073. static expr_ty
  1074. fstring_parse(Parser *p, const char **str, const char *end, int raw,
  1075. int recurse_lvl, Token *first_token, Token* t, Token *last_token)
  1076. {
  1077. FstringParser state;
  1078. _PyPegen_FstringParser_Init(&state);
  1079. if (_PyPegen_FstringParser_ConcatFstring(p, &state, str, end, raw, recurse_lvl,
  1080. first_token, t, last_token) < 0) {
  1081. _PyPegen_FstringParser_Dealloc(&state);
  1082. return NULL;
  1083. }
  1084. return _PyPegen_FstringParser_Finish(p, &state, t, t);
  1085. }