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.

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