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.

938 lines
25 KiB

  1. #include <stdbool.h>
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. static PyObject *_str_open_br;
  5. static PyObject *_str_dbl_open_br;
  6. static PyObject *_str_close_br;
  7. static PyObject *_str_dbl_close_br;
  8. /* Forward declarations for recursion via helper functions. */
  9. static PyObject *
  10. expr_as_unicode(expr_ty e, int level);
  11. static int
  12. append_ast_expr(_PyUnicodeWriter *writer, expr_ty e, int level);
  13. static int
  14. append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec);
  15. static int
  16. append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e);
  17. static int
  18. append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice);
  19. static int
  20. append_charp(_PyUnicodeWriter *writer, const char *charp)
  21. {
  22. return _PyUnicodeWriter_WriteASCIIString(writer, charp, -1);
  23. }
  24. #define APPEND_STR_FINISH(str) do { \
  25. return append_charp(writer, (str)); \
  26. } while (0)
  27. #define APPEND_STR(str) do { \
  28. if (-1 == append_charp(writer, (str))) { \
  29. return -1; \
  30. } \
  31. } while (0)
  32. #define APPEND_STR_IF(cond, str) do { \
  33. if ((cond) && -1 == append_charp(writer, (str))) { \
  34. return -1; \
  35. } \
  36. } while (0)
  37. #define APPEND_STR_IF_NOT_FIRST(str) do { \
  38. APPEND_STR_IF(!first, (str)); \
  39. first = false; \
  40. } while (0)
  41. #define APPEND_EXPR(expr, pr) do { \
  42. if (-1 == append_ast_expr(writer, (expr), (pr))) { \
  43. return -1; \
  44. } \
  45. } while (0)
  46. #define APPEND(type, value) do { \
  47. if (-1 == append_ast_ ## type(writer, (value))) { \
  48. return -1; \
  49. } \
  50. } while (0)
  51. static int
  52. append_repr(_PyUnicodeWriter *writer, PyObject *obj)
  53. {
  54. int ret;
  55. PyObject *repr;
  56. repr = PyObject_Repr(obj);
  57. if (!repr) {
  58. return -1;
  59. }
  60. ret = _PyUnicodeWriter_WriteStr(writer, repr);
  61. Py_DECREF(repr);
  62. return ret;
  63. }
  64. /* Priority levels */
  65. enum {
  66. PR_TUPLE,
  67. PR_TEST, /* 'if'-'else', 'lambda' */
  68. PR_OR, /* 'or' */
  69. PR_AND, /* 'and' */
  70. PR_NOT, /* 'not' */
  71. PR_CMP, /* '<', '>', '==', '>=', '<=', '!=',
  72. 'in', 'not in', 'is', 'is not' */
  73. PR_EXPR,
  74. PR_BOR = PR_EXPR, /* '|' */
  75. PR_BXOR, /* '^' */
  76. PR_BAND, /* '&' */
  77. PR_SHIFT, /* '<<', '>>' */
  78. PR_ARITH, /* '+', '-' */
  79. PR_TERM, /* '*', '@', '/', '%', '//' */
  80. PR_FACTOR, /* unary '+', '-', '~' */
  81. PR_POWER, /* '**' */
  82. PR_AWAIT, /* 'await' */
  83. PR_ATOM,
  84. };
  85. static int
  86. append_ast_boolop(_PyUnicodeWriter *writer, expr_ty e, int level)
  87. {
  88. Py_ssize_t i, value_count;
  89. asdl_seq *values;
  90. const char *op = (e->v.BoolOp.op == And) ? " and " : " or ";
  91. int pr = (e->v.BoolOp.op == And) ? PR_AND : PR_OR;
  92. APPEND_STR_IF(level > pr, "(");
  93. values = e->v.BoolOp.values;
  94. value_count = asdl_seq_LEN(values);
  95. for (i = 0; i < value_count; ++i) {
  96. APPEND_STR_IF(i > 0, op);
  97. APPEND_EXPR((expr_ty)asdl_seq_GET(values, i), pr + 1);
  98. }
  99. APPEND_STR_IF(level > pr, ")");
  100. return 0;
  101. }
  102. static int
  103. append_ast_binop(_PyUnicodeWriter *writer, expr_ty e, int level)
  104. {
  105. const char *op;
  106. int pr;
  107. bool rassoc = false; /* is right-associative? */
  108. switch (e->v.BinOp.op) {
  109. case Add: op = " + "; pr = PR_ARITH; break;
  110. case Sub: op = " - "; pr = PR_ARITH; break;
  111. case Mult: op = " * "; pr = PR_TERM; break;
  112. case MatMult: op = " @ "; pr = PR_TERM; break;
  113. case Div: op = " / "; pr = PR_TERM; break;
  114. case Mod: op = " % "; pr = PR_TERM; break;
  115. case LShift: op = " << "; pr = PR_SHIFT; break;
  116. case RShift: op = " >> "; pr = PR_SHIFT; break;
  117. case BitOr: op = " | "; pr = PR_BOR; break;
  118. case BitXor: op = " ^ "; pr = PR_BXOR; break;
  119. case BitAnd: op = " & "; pr = PR_BAND; break;
  120. case FloorDiv: op = " // "; pr = PR_TERM; break;
  121. case Pow: op = " ** "; pr = PR_POWER; rassoc = true; break;
  122. default:
  123. PyErr_SetString(PyExc_SystemError,
  124. "unknown binary operator");
  125. return -1;
  126. }
  127. APPEND_STR_IF(level > pr, "(");
  128. APPEND_EXPR(e->v.BinOp.left, pr + rassoc);
  129. APPEND_STR(op);
  130. APPEND_EXPR(e->v.BinOp.right, pr + !rassoc);
  131. APPEND_STR_IF(level > pr, ")");
  132. return 0;
  133. }
  134. static int
  135. append_ast_unaryop(_PyUnicodeWriter *writer, expr_ty e, int level)
  136. {
  137. const char *op;
  138. int pr;
  139. switch (e->v.UnaryOp.op) {
  140. case Invert: op = "~"; pr = PR_FACTOR; break;
  141. case Not: op = "not "; pr = PR_NOT; break;
  142. case UAdd: op = "+"; pr = PR_FACTOR; break;
  143. case USub: op = "-"; pr = PR_FACTOR; break;
  144. default:
  145. PyErr_SetString(PyExc_SystemError,
  146. "unknown unary operator");
  147. return -1;
  148. }
  149. APPEND_STR_IF(level > pr, "(");
  150. APPEND_STR(op);
  151. APPEND_EXPR(e->v.UnaryOp.operand, pr);
  152. APPEND_STR_IF(level > pr, ")");
  153. return 0;
  154. }
  155. static int
  156. append_ast_arg(_PyUnicodeWriter *writer, arg_ty arg)
  157. {
  158. if (-1 == _PyUnicodeWriter_WriteStr(writer, arg->arg)) {
  159. return -1;
  160. }
  161. if (arg->annotation) {
  162. APPEND_STR(": ");
  163. APPEND_EXPR(arg->annotation, PR_TEST);
  164. }
  165. return 0;
  166. }
  167. static int
  168. append_ast_args(_PyUnicodeWriter *writer, arguments_ty args)
  169. {
  170. bool first;
  171. Py_ssize_t i, di, arg_count, posonlyarg_count, default_count;
  172. first = true;
  173. /* positional-only and positional arguments with defaults */
  174. posonlyarg_count = asdl_seq_LEN(args->posonlyargs);
  175. arg_count = asdl_seq_LEN(args->args);
  176. default_count = asdl_seq_LEN(args->defaults);
  177. for (i = 0; i < posonlyarg_count + arg_count; i++) {
  178. APPEND_STR_IF_NOT_FIRST(", ");
  179. if (i < posonlyarg_count){
  180. APPEND(arg, (arg_ty)asdl_seq_GET(args->posonlyargs, i));
  181. } else {
  182. APPEND(arg, (arg_ty)asdl_seq_GET(args->args, i-posonlyarg_count));
  183. }
  184. di = i - posonlyarg_count - arg_count + default_count;
  185. if (di >= 0) {
  186. APPEND_STR("=");
  187. APPEND_EXPR((expr_ty)asdl_seq_GET(args->defaults, di), PR_TEST);
  188. }
  189. if (posonlyarg_count && i + 1 == posonlyarg_count) {
  190. APPEND_STR(", /");
  191. }
  192. }
  193. /* vararg, or bare '*' if no varargs but keyword-only arguments present */
  194. if (args->vararg || asdl_seq_LEN(args->kwonlyargs)) {
  195. APPEND_STR_IF_NOT_FIRST(", ");
  196. APPEND_STR("*");
  197. if (args->vararg) {
  198. APPEND(arg, args->vararg);
  199. }
  200. }
  201. /* keyword-only arguments */
  202. arg_count = asdl_seq_LEN(args->kwonlyargs);
  203. default_count = asdl_seq_LEN(args->kw_defaults);
  204. for (i = 0; i < arg_count; i++) {
  205. APPEND_STR_IF_NOT_FIRST(", ");
  206. APPEND(arg, (arg_ty)asdl_seq_GET(args->kwonlyargs, i));
  207. di = i - arg_count + default_count;
  208. if (di >= 0) {
  209. expr_ty default_ = (expr_ty)asdl_seq_GET(args->kw_defaults, di);
  210. if (default_) {
  211. APPEND_STR("=");
  212. APPEND_EXPR(default_, PR_TEST);
  213. }
  214. }
  215. }
  216. /* **kwargs */
  217. if (args->kwarg) {
  218. APPEND_STR_IF_NOT_FIRST(", ");
  219. APPEND_STR("**");
  220. APPEND(arg, args->kwarg);
  221. }
  222. return 0;
  223. }
  224. static int
  225. append_ast_lambda(_PyUnicodeWriter *writer, expr_ty e, int level)
  226. {
  227. APPEND_STR_IF(level > PR_TEST, "(");
  228. Py_ssize_t n_positional = (asdl_seq_LEN(e->v.Lambda.args->args) +
  229. asdl_seq_LEN(e->v.Lambda.args->posonlyargs));
  230. APPEND_STR(n_positional ? "lambda " : "lambda");
  231. APPEND(args, e->v.Lambda.args);
  232. APPEND_STR(": ");
  233. APPEND_EXPR(e->v.Lambda.body, PR_TEST);
  234. APPEND_STR_IF(level > PR_TEST, ")");
  235. return 0;
  236. }
  237. static int
  238. append_ast_ifexp(_PyUnicodeWriter *writer, expr_ty e, int level)
  239. {
  240. APPEND_STR_IF(level > PR_TEST, "(");
  241. APPEND_EXPR(e->v.IfExp.body, PR_TEST + 1);
  242. APPEND_STR(" if ");
  243. APPEND_EXPR(e->v.IfExp.test, PR_TEST + 1);
  244. APPEND_STR(" else ");
  245. APPEND_EXPR(e->v.IfExp.orelse, PR_TEST);
  246. APPEND_STR_IF(level > PR_TEST, ")");
  247. return 0;
  248. }
  249. static int
  250. append_ast_dict(_PyUnicodeWriter *writer, expr_ty e)
  251. {
  252. Py_ssize_t i, value_count;
  253. expr_ty key_node;
  254. APPEND_STR("{");
  255. value_count = asdl_seq_LEN(e->v.Dict.values);
  256. for (i = 0; i < value_count; i++) {
  257. APPEND_STR_IF(i > 0, ", ");
  258. key_node = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i);
  259. if (key_node != NULL) {
  260. APPEND_EXPR(key_node, PR_TEST);
  261. APPEND_STR(": ");
  262. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_TEST);
  263. }
  264. else {
  265. APPEND_STR("**");
  266. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_EXPR);
  267. }
  268. }
  269. APPEND_STR_FINISH("}");
  270. }
  271. static int
  272. append_ast_set(_PyUnicodeWriter *writer, expr_ty e)
  273. {
  274. Py_ssize_t i, elem_count;
  275. APPEND_STR("{");
  276. elem_count = asdl_seq_LEN(e->v.Set.elts);
  277. for (i = 0; i < elem_count; i++) {
  278. APPEND_STR_IF(i > 0, ", ");
  279. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST);
  280. }
  281. APPEND_STR_FINISH("}");
  282. }
  283. static int
  284. append_ast_list(_PyUnicodeWriter *writer, expr_ty e)
  285. {
  286. Py_ssize_t i, elem_count;
  287. APPEND_STR("[");
  288. elem_count = asdl_seq_LEN(e->v.List.elts);
  289. for (i = 0; i < elem_count; i++) {
  290. APPEND_STR_IF(i > 0, ", ");
  291. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.List.elts, i), PR_TEST);
  292. }
  293. APPEND_STR_FINISH("]");
  294. }
  295. static int
  296. append_ast_tuple(_PyUnicodeWriter *writer, expr_ty e, int level)
  297. {
  298. Py_ssize_t i, elem_count;
  299. elem_count = asdl_seq_LEN(e->v.Tuple.elts);
  300. if (elem_count == 0) {
  301. APPEND_STR_FINISH("()");
  302. }
  303. APPEND_STR_IF(level > PR_TUPLE, "(");
  304. for (i = 0; i < elem_count; i++) {
  305. APPEND_STR_IF(i > 0, ", ");
  306. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Tuple.elts, i), PR_TEST);
  307. }
  308. APPEND_STR_IF(elem_count == 1, ",");
  309. APPEND_STR_IF(level > PR_TUPLE, ")");
  310. return 0;
  311. }
  312. static int
  313. append_ast_comprehension(_PyUnicodeWriter *writer, comprehension_ty gen)
  314. {
  315. Py_ssize_t i, if_count;
  316. APPEND_STR(gen->is_async ? " async for " : " for ");
  317. APPEND_EXPR(gen->target, PR_TUPLE);
  318. APPEND_STR(" in ");
  319. APPEND_EXPR(gen->iter, PR_TEST + 1);
  320. if_count = asdl_seq_LEN(gen->ifs);
  321. for (i = 0; i < if_count; i++) {
  322. APPEND_STR(" if ");
  323. APPEND_EXPR((expr_ty)asdl_seq_GET(gen->ifs, i), PR_TEST + 1);
  324. }
  325. return 0;
  326. }
  327. static int
  328. append_ast_comprehensions(_PyUnicodeWriter *writer, asdl_seq *comprehensions)
  329. {
  330. Py_ssize_t i, gen_count;
  331. gen_count = asdl_seq_LEN(comprehensions);
  332. for (i = 0; i < gen_count; i++) {
  333. APPEND(comprehension, (comprehension_ty)asdl_seq_GET(comprehensions, i));
  334. }
  335. return 0;
  336. }
  337. static int
  338. append_ast_genexp(_PyUnicodeWriter *writer, expr_ty e)
  339. {
  340. APPEND_STR("(");
  341. APPEND_EXPR(e->v.GeneratorExp.elt, PR_TEST);
  342. APPEND(comprehensions, e->v.GeneratorExp.generators);
  343. APPEND_STR_FINISH(")");
  344. }
  345. static int
  346. append_ast_listcomp(_PyUnicodeWriter *writer, expr_ty e)
  347. {
  348. APPEND_STR("[");
  349. APPEND_EXPR(e->v.ListComp.elt, PR_TEST);
  350. APPEND(comprehensions, e->v.ListComp.generators);
  351. APPEND_STR_FINISH("]");
  352. }
  353. static int
  354. append_ast_setcomp(_PyUnicodeWriter *writer, expr_ty e)
  355. {
  356. APPEND_STR("{");
  357. APPEND_EXPR(e->v.SetComp.elt, PR_TEST);
  358. APPEND(comprehensions, e->v.SetComp.generators);
  359. APPEND_STR_FINISH("}");
  360. }
  361. static int
  362. append_ast_dictcomp(_PyUnicodeWriter *writer, expr_ty e)
  363. {
  364. APPEND_STR("{");
  365. APPEND_EXPR(e->v.DictComp.key, PR_TEST);
  366. APPEND_STR(": ");
  367. APPEND_EXPR(e->v.DictComp.value, PR_TEST);
  368. APPEND(comprehensions, e->v.DictComp.generators);
  369. APPEND_STR_FINISH("}");
  370. }
  371. static int
  372. append_ast_compare(_PyUnicodeWriter *writer, expr_ty e, int level)
  373. {
  374. const char *op;
  375. Py_ssize_t i, comparator_count;
  376. asdl_seq *comparators;
  377. asdl_int_seq *ops;
  378. APPEND_STR_IF(level > PR_CMP, "(");
  379. comparators = e->v.Compare.comparators;
  380. ops = e->v.Compare.ops;
  381. comparator_count = asdl_seq_LEN(comparators);
  382. assert(comparator_count > 0);
  383. assert(comparator_count == asdl_seq_LEN(ops));
  384. APPEND_EXPR(e->v.Compare.left, PR_CMP + 1);
  385. for (i = 0; i < comparator_count; i++) {
  386. switch ((cmpop_ty)asdl_seq_GET(ops, i)) {
  387. case Eq:
  388. op = " == ";
  389. break;
  390. case NotEq:
  391. op = " != ";
  392. break;
  393. case Lt:
  394. op = " < ";
  395. break;
  396. case LtE:
  397. op = " <= ";
  398. break;
  399. case Gt:
  400. op = " > ";
  401. break;
  402. case GtE:
  403. op = " >= ";
  404. break;
  405. case Is:
  406. op = " is ";
  407. break;
  408. case IsNot:
  409. op = " is not ";
  410. break;
  411. case In:
  412. op = " in ";
  413. break;
  414. case NotIn:
  415. op = " not in ";
  416. break;
  417. default:
  418. PyErr_SetString(PyExc_SystemError,
  419. "unexpected comparison kind");
  420. return -1;
  421. }
  422. APPEND_STR(op);
  423. APPEND_EXPR((expr_ty)asdl_seq_GET(comparators, i), PR_CMP + 1);
  424. }
  425. APPEND_STR_IF(level > PR_CMP, ")");
  426. return 0;
  427. }
  428. static int
  429. append_ast_keyword(_PyUnicodeWriter *writer, keyword_ty kw)
  430. {
  431. if (kw->arg == NULL) {
  432. APPEND_STR("**");
  433. }
  434. else {
  435. if (-1 == _PyUnicodeWriter_WriteStr(writer, kw->arg)) {
  436. return -1;
  437. }
  438. APPEND_STR("=");
  439. }
  440. APPEND_EXPR(kw->value, PR_TEST);
  441. return 0;
  442. }
  443. static int
  444. append_ast_call(_PyUnicodeWriter *writer, expr_ty e)
  445. {
  446. bool first;
  447. Py_ssize_t i, arg_count, kw_count;
  448. expr_ty expr;
  449. APPEND_EXPR(e->v.Call.func, PR_ATOM);
  450. arg_count = asdl_seq_LEN(e->v.Call.args);
  451. kw_count = asdl_seq_LEN(e->v.Call.keywords);
  452. if (arg_count == 1 && kw_count == 0) {
  453. expr = (expr_ty)asdl_seq_GET(e->v.Call.args, 0);
  454. if (expr->kind == GeneratorExp_kind) {
  455. /* Special case: a single generator expression. */
  456. return append_ast_genexp(writer, expr);
  457. }
  458. }
  459. APPEND_STR("(");
  460. first = true;
  461. for (i = 0; i < arg_count; i++) {
  462. APPEND_STR_IF_NOT_FIRST(", ");
  463. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Call.args, i), PR_TEST);
  464. }
  465. for (i = 0; i < kw_count; i++) {
  466. APPEND_STR_IF_NOT_FIRST(", ");
  467. APPEND(keyword, (keyword_ty)asdl_seq_GET(e->v.Call.keywords, i));
  468. }
  469. APPEND_STR_FINISH(")");
  470. }
  471. static PyObject *
  472. escape_braces(PyObject *orig)
  473. {
  474. PyObject *temp;
  475. PyObject *result;
  476. temp = PyUnicode_Replace(orig, _str_open_br, _str_dbl_open_br, -1);
  477. if (!temp) {
  478. return NULL;
  479. }
  480. result = PyUnicode_Replace(temp, _str_close_br, _str_dbl_close_br, -1);
  481. Py_DECREF(temp);
  482. return result;
  483. }
  484. static int
  485. append_fstring_unicode(_PyUnicodeWriter *writer, PyObject *unicode)
  486. {
  487. PyObject *escaped;
  488. int result = -1;
  489. escaped = escape_braces(unicode);
  490. if (escaped) {
  491. result = _PyUnicodeWriter_WriteStr(writer, escaped);
  492. Py_DECREF(escaped);
  493. }
  494. return result;
  495. }
  496. static int
  497. append_fstring_element(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  498. {
  499. switch (e->kind) {
  500. case Constant_kind:
  501. return append_fstring_unicode(writer, e->v.Constant.value);
  502. case JoinedStr_kind:
  503. return append_joinedstr(writer, e, is_format_spec);
  504. case FormattedValue_kind:
  505. return append_formattedvalue(writer, e);
  506. default:
  507. PyErr_SetString(PyExc_SystemError,
  508. "unknown expression kind inside f-string");
  509. return -1;
  510. }
  511. }
  512. /* Build body separately to enable wrapping the entire stream of Strs,
  513. Constants and FormattedValues in one opening and one closing quote. */
  514. static PyObject *
  515. build_fstring_body(asdl_seq *values, bool is_format_spec)
  516. {
  517. Py_ssize_t i, value_count;
  518. _PyUnicodeWriter body_writer;
  519. _PyUnicodeWriter_Init(&body_writer);
  520. body_writer.min_length = 256;
  521. body_writer.overallocate = 1;
  522. value_count = asdl_seq_LEN(values);
  523. for (i = 0; i < value_count; ++i) {
  524. if (-1 == append_fstring_element(&body_writer,
  525. (expr_ty)asdl_seq_GET(values, i),
  526. is_format_spec
  527. )) {
  528. _PyUnicodeWriter_Dealloc(&body_writer);
  529. return NULL;
  530. }
  531. }
  532. return _PyUnicodeWriter_Finish(&body_writer);
  533. }
  534. static int
  535. append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  536. {
  537. int result = -1;
  538. PyObject *body = build_fstring_body(e->v.JoinedStr.values, is_format_spec);
  539. if (!body) {
  540. return -1;
  541. }
  542. if (!is_format_spec) {
  543. if (-1 != append_charp(writer, "f") &&
  544. -1 != append_repr(writer, body))
  545. {
  546. result = 0;
  547. }
  548. }
  549. else {
  550. result = _PyUnicodeWriter_WriteStr(writer, body);
  551. }
  552. Py_DECREF(body);
  553. return result;
  554. }
  555. static int
  556. append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e)
  557. {
  558. const char *conversion;
  559. const char *outer_brace = "{";
  560. /* Grammar allows PR_TUPLE, but use >PR_TEST for adding parenthesis
  561. around a lambda with ':' */
  562. PyObject *temp_fv_str = expr_as_unicode(e->v.FormattedValue.value, PR_TEST + 1);
  563. if (!temp_fv_str) {
  564. return -1;
  565. }
  566. if (PyUnicode_Find(temp_fv_str, _str_open_br, 0, 1, 1) == 0) {
  567. /* Expression starts with a brace, split it with a space from the outer
  568. one. */
  569. outer_brace = "{ ";
  570. }
  571. if (-1 == append_charp(writer, outer_brace)) {
  572. Py_DECREF(temp_fv_str);
  573. return -1;
  574. }
  575. if (-1 == _PyUnicodeWriter_WriteStr(writer, temp_fv_str)) {
  576. Py_DECREF(temp_fv_str);
  577. return -1;
  578. }
  579. Py_DECREF(temp_fv_str);
  580. if (e->v.FormattedValue.conversion > 0) {
  581. switch (e->v.FormattedValue.conversion) {
  582. case 'a':
  583. conversion = "!a";
  584. break;
  585. case 'r':
  586. conversion = "!r";
  587. break;
  588. case 's':
  589. conversion = "!s";
  590. break;
  591. default:
  592. PyErr_SetString(PyExc_SystemError,
  593. "unknown f-value conversion kind");
  594. return -1;
  595. }
  596. APPEND_STR(conversion);
  597. }
  598. if (e->v.FormattedValue.format_spec) {
  599. if (-1 == _PyUnicodeWriter_WriteASCIIString(writer, ":", 1) ||
  600. -1 == append_fstring_element(writer,
  601. e->v.FormattedValue.format_spec,
  602. true
  603. ))
  604. {
  605. return -1;
  606. }
  607. }
  608. APPEND_STR_FINISH("}");
  609. }
  610. static int
  611. append_ast_attribute(_PyUnicodeWriter *writer, expr_ty e)
  612. {
  613. const char *period;
  614. expr_ty v = e->v.Attribute.value;
  615. APPEND_EXPR(v, PR_ATOM);
  616. /* Special case: integers require a space for attribute access to be
  617. unambiguous. */
  618. if (v->kind == Constant_kind && PyLong_CheckExact(v->v.Constant.value)) {
  619. period = " .";
  620. }
  621. else {
  622. period = ".";
  623. }
  624. APPEND_STR(period);
  625. return _PyUnicodeWriter_WriteStr(writer, e->v.Attribute.attr);
  626. }
  627. static int
  628. append_ast_simple_slice(_PyUnicodeWriter *writer, slice_ty slice)
  629. {
  630. if (slice->v.Slice.lower) {
  631. APPEND_EXPR(slice->v.Slice.lower, PR_TEST);
  632. }
  633. APPEND_STR(":");
  634. if (slice->v.Slice.upper) {
  635. APPEND_EXPR(slice->v.Slice.upper, PR_TEST);
  636. }
  637. if (slice->v.Slice.step) {
  638. APPEND_STR(":");
  639. APPEND_EXPR(slice->v.Slice.step, PR_TEST);
  640. }
  641. return 0;
  642. }
  643. static int
  644. append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
  645. {
  646. Py_ssize_t i, dims_count;
  647. dims_count = asdl_seq_LEN(slice->v.ExtSlice.dims);
  648. for (i = 0; i < dims_count; i++) {
  649. APPEND_STR_IF(i > 0, ", ");
  650. APPEND(slice, (slice_ty)asdl_seq_GET(slice->v.ExtSlice.dims, i));
  651. }
  652. APPEND_STR_IF(dims_count == 1, ",");
  653. return 0;
  654. }
  655. static int
  656. append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
  657. {
  658. switch (slice->kind) {
  659. case Slice_kind:
  660. return append_ast_simple_slice(writer, slice);
  661. case ExtSlice_kind:
  662. return append_ast_ext_slice(writer, slice);
  663. case Index_kind:
  664. APPEND_EXPR(slice->v.Index.value, PR_TUPLE);
  665. return 0;
  666. default:
  667. PyErr_SetString(PyExc_SystemError,
  668. "unexpected slice kind");
  669. return -1;
  670. }
  671. }
  672. static int
  673. append_ast_subscript(_PyUnicodeWriter *writer, expr_ty e)
  674. {
  675. APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
  676. APPEND_STR("[");
  677. APPEND(slice, e->v.Subscript.slice);
  678. APPEND_STR_FINISH("]");
  679. }
  680. static int
  681. append_ast_starred(_PyUnicodeWriter *writer, expr_ty e)
  682. {
  683. APPEND_STR("*");
  684. APPEND_EXPR(e->v.Starred.value, PR_EXPR);
  685. return 0;
  686. }
  687. static int
  688. append_ast_yield(_PyUnicodeWriter *writer, expr_ty e)
  689. {
  690. if (!e->v.Yield.value) {
  691. APPEND_STR_FINISH("(yield)");
  692. }
  693. APPEND_STR("(yield ");
  694. APPEND_EXPR(e->v.Yield.value, PR_TEST);
  695. APPEND_STR_FINISH(")");
  696. }
  697. static int
  698. append_ast_yield_from(_PyUnicodeWriter *writer, expr_ty e)
  699. {
  700. APPEND_STR("(yield from ");
  701. APPEND_EXPR(e->v.YieldFrom.value, PR_TEST);
  702. APPEND_STR_FINISH(")");
  703. }
  704. static int
  705. append_ast_await(_PyUnicodeWriter *writer, expr_ty e, int level)
  706. {
  707. APPEND_STR_IF(level > PR_AWAIT, "(");
  708. APPEND_STR("await ");
  709. APPEND_EXPR(e->v.Await.value, PR_ATOM);
  710. APPEND_STR_IF(level > PR_AWAIT, ")");
  711. return 0;
  712. }
  713. static int
  714. append_named_expr(_PyUnicodeWriter *writer, expr_ty e, int level)
  715. {
  716. APPEND_STR_IF(level > PR_TUPLE, "(");
  717. APPEND_EXPR(e->v.NamedExpr.target, PR_ATOM);
  718. APPEND_STR(":=");
  719. APPEND_EXPR(e->v.NamedExpr.value, PR_ATOM);
  720. APPEND_STR_IF(level > PR_TUPLE, ")");
  721. return 0;
  722. }
  723. static int
  724. append_ast_expr(_PyUnicodeWriter *writer, expr_ty e, int level)
  725. {
  726. switch (e->kind) {
  727. case BoolOp_kind:
  728. return append_ast_boolop(writer, e, level);
  729. case BinOp_kind:
  730. return append_ast_binop(writer, e, level);
  731. case UnaryOp_kind:
  732. return append_ast_unaryop(writer, e, level);
  733. case Lambda_kind:
  734. return append_ast_lambda(writer, e, level);
  735. case IfExp_kind:
  736. return append_ast_ifexp(writer, e, level);
  737. case Dict_kind:
  738. return append_ast_dict(writer, e);
  739. case Set_kind:
  740. return append_ast_set(writer, e);
  741. case GeneratorExp_kind:
  742. return append_ast_genexp(writer, e);
  743. case ListComp_kind:
  744. return append_ast_listcomp(writer, e);
  745. case SetComp_kind:
  746. return append_ast_setcomp(writer, e);
  747. case DictComp_kind:
  748. return append_ast_dictcomp(writer, e);
  749. case Yield_kind:
  750. return append_ast_yield(writer, e);
  751. case YieldFrom_kind:
  752. return append_ast_yield_from(writer, e);
  753. case Await_kind:
  754. return append_ast_await(writer, e, level);
  755. case Compare_kind:
  756. return append_ast_compare(writer, e, level);
  757. case Call_kind:
  758. return append_ast_call(writer, e);
  759. case Constant_kind:
  760. if (e->v.Constant.value == Py_Ellipsis) {
  761. APPEND_STR_FINISH("...");
  762. }
  763. return append_repr(writer, e->v.Constant.value);
  764. case JoinedStr_kind:
  765. return append_joinedstr(writer, e, false);
  766. case FormattedValue_kind:
  767. return append_formattedvalue(writer, e);
  768. /* The following exprs can be assignment targets. */
  769. case Attribute_kind:
  770. return append_ast_attribute(writer, e);
  771. case Subscript_kind:
  772. return append_ast_subscript(writer, e);
  773. case Starred_kind:
  774. return append_ast_starred(writer, e);
  775. case Name_kind:
  776. return _PyUnicodeWriter_WriteStr(writer, e->v.Name.id);
  777. case List_kind:
  778. return append_ast_list(writer, e);
  779. case Tuple_kind:
  780. return append_ast_tuple(writer, e, level);
  781. case NamedExpr_kind:
  782. return append_named_expr(writer, e, level);
  783. default:
  784. PyErr_SetString(PyExc_SystemError,
  785. "unknown expression kind");
  786. return -1;
  787. }
  788. }
  789. static int
  790. maybe_init_static_strings(void)
  791. {
  792. if (!_str_open_br &&
  793. !(_str_open_br = PyUnicode_InternFromString("{"))) {
  794. return -1;
  795. }
  796. if (!_str_dbl_open_br &&
  797. !(_str_dbl_open_br = PyUnicode_InternFromString("{{"))) {
  798. return -1;
  799. }
  800. if (!_str_close_br &&
  801. !(_str_close_br = PyUnicode_InternFromString("}"))) {
  802. return -1;
  803. }
  804. if (!_str_dbl_close_br &&
  805. !(_str_dbl_close_br = PyUnicode_InternFromString("}}"))) {
  806. return -1;
  807. }
  808. return 0;
  809. }
  810. static PyObject *
  811. expr_as_unicode(expr_ty e, int level)
  812. {
  813. _PyUnicodeWriter writer;
  814. _PyUnicodeWriter_Init(&writer);
  815. writer.min_length = 256;
  816. writer.overallocate = 1;
  817. if (-1 == maybe_init_static_strings() ||
  818. -1 == append_ast_expr(&writer, e, level))
  819. {
  820. _PyUnicodeWriter_Dealloc(&writer);
  821. return NULL;
  822. }
  823. return _PyUnicodeWriter_Finish(&writer);
  824. }
  825. PyObject *
  826. _PyAST_ExprAsUnicode(expr_ty e)
  827. {
  828. return expr_as_unicode(e, PR_TEST);
  829. }