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.

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