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.

914 lines
24 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, bool is_format_spec);
  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, default_count;
  172. first = true;
  173. /* positional arguments with defaults */
  174. arg_count = asdl_seq_LEN(args->args);
  175. default_count = asdl_seq_LEN(args->defaults);
  176. for (i = 0; i < arg_count; i++) {
  177. APPEND_STR_IF_NOT_FIRST(", ");
  178. APPEND(arg, (arg_ty)asdl_seq_GET(args->args, i));
  179. di = i - arg_count + default_count;
  180. if (di >= 0) {
  181. APPEND_STR("=");
  182. APPEND_EXPR((expr_ty)asdl_seq_GET(args->defaults, di), PR_TEST);
  183. }
  184. }
  185. /* vararg, or bare '*' if no varargs but keyword-only arguments present */
  186. if (args->vararg || asdl_seq_LEN(args->kwonlyargs)) {
  187. APPEND_STR_IF_NOT_FIRST(", ");
  188. APPEND_STR("*");
  189. if (args->vararg) {
  190. APPEND(arg, args->vararg);
  191. }
  192. }
  193. /* keyword-only arguments */
  194. arg_count = asdl_seq_LEN(args->kwonlyargs);
  195. default_count = asdl_seq_LEN(args->kw_defaults);
  196. for (i = 0; i < arg_count; i++) {
  197. APPEND_STR_IF_NOT_FIRST(", ");
  198. APPEND(arg, (arg_ty)asdl_seq_GET(args->kwonlyargs, i));
  199. di = i - arg_count + default_count;
  200. if (di >= 0) {
  201. expr_ty default_ = (expr_ty)asdl_seq_GET(args->kw_defaults, di);
  202. if (default_) {
  203. APPEND_STR("=");
  204. APPEND_EXPR(default_, PR_TEST);
  205. }
  206. }
  207. }
  208. /* **kwargs */
  209. if (args->kwarg) {
  210. APPEND_STR_IF_NOT_FIRST(", ");
  211. APPEND_STR("**");
  212. APPEND(arg, args->kwarg);
  213. }
  214. return 0;
  215. }
  216. static int
  217. append_ast_lambda(_PyUnicodeWriter *writer, expr_ty e, int level)
  218. {
  219. APPEND_STR_IF(level > PR_TEST, "(");
  220. APPEND_STR(asdl_seq_LEN(e->v.Lambda.args->args) ? "lambda " : "lambda");
  221. APPEND(args, e->v.Lambda.args);
  222. APPEND_STR(": ");
  223. APPEND_EXPR(e->v.Lambda.body, PR_TEST);
  224. APPEND_STR_IF(level > PR_TEST, ")");
  225. return 0;
  226. }
  227. static int
  228. append_ast_ifexp(_PyUnicodeWriter *writer, expr_ty e, int level)
  229. {
  230. APPEND_STR_IF(level > PR_TEST, "(");
  231. APPEND_EXPR(e->v.IfExp.body, PR_TEST + 1);
  232. APPEND_STR(" if ");
  233. APPEND_EXPR(e->v.IfExp.test, PR_TEST + 1);
  234. APPEND_STR(" else ");
  235. APPEND_EXPR(e->v.IfExp.orelse, PR_TEST);
  236. APPEND_STR_IF(level > PR_TEST, ")");
  237. return 0;
  238. }
  239. static int
  240. append_ast_dict(_PyUnicodeWriter *writer, expr_ty e)
  241. {
  242. Py_ssize_t i, value_count;
  243. expr_ty key_node;
  244. APPEND_STR("{");
  245. value_count = asdl_seq_LEN(e->v.Dict.values);
  246. for (i = 0; i < value_count; i++) {
  247. APPEND_STR_IF(i > 0, ", ");
  248. key_node = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i);
  249. if (key_node != NULL) {
  250. APPEND_EXPR(key_node, PR_TEST);
  251. APPEND_STR(": ");
  252. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_TEST);
  253. }
  254. else {
  255. APPEND_STR("**");
  256. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_EXPR);
  257. }
  258. }
  259. APPEND_STR_FINISH("}");
  260. }
  261. static int
  262. append_ast_set(_PyUnicodeWriter *writer, expr_ty e)
  263. {
  264. Py_ssize_t i, elem_count;
  265. APPEND_STR("{");
  266. elem_count = asdl_seq_LEN(e->v.Set.elts);
  267. for (i = 0; i < elem_count; i++) {
  268. APPEND_STR_IF(i > 0, ", ");
  269. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST);
  270. }
  271. APPEND_STR_FINISH("}");
  272. }
  273. static int
  274. append_ast_list(_PyUnicodeWriter *writer, expr_ty e)
  275. {
  276. Py_ssize_t i, elem_count;
  277. APPEND_STR("[");
  278. elem_count = asdl_seq_LEN(e->v.List.elts);
  279. for (i = 0; i < elem_count; i++) {
  280. APPEND_STR_IF(i > 0, ", ");
  281. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.List.elts, i), PR_TEST);
  282. }
  283. APPEND_STR_FINISH("]");
  284. }
  285. static int
  286. append_ast_tuple(_PyUnicodeWriter *writer, expr_ty e, int level)
  287. {
  288. Py_ssize_t i, elem_count;
  289. elem_count = asdl_seq_LEN(e->v.Tuple.elts);
  290. if (elem_count == 0) {
  291. APPEND_STR_FINISH("()");
  292. }
  293. APPEND_STR_IF(level > PR_TUPLE, "(");
  294. for (i = 0; i < elem_count; i++) {
  295. APPEND_STR_IF(i > 0, ", ");
  296. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Tuple.elts, i), PR_TEST);
  297. }
  298. APPEND_STR_IF(elem_count == 1, ",");
  299. APPEND_STR_IF(level > PR_TUPLE, ")");
  300. return 0;
  301. }
  302. static int
  303. append_ast_comprehension(_PyUnicodeWriter *writer, comprehension_ty gen)
  304. {
  305. Py_ssize_t i, if_count;
  306. APPEND_STR(gen->is_async ? " async for " : " for ");
  307. APPEND_EXPR(gen->target, PR_TUPLE);
  308. APPEND_STR(" in ");
  309. APPEND_EXPR(gen->iter, PR_TEST + 1);
  310. if_count = asdl_seq_LEN(gen->ifs);
  311. for (i = 0; i < if_count; i++) {
  312. APPEND_STR(" if ");
  313. APPEND_EXPR((expr_ty)asdl_seq_GET(gen->ifs, i), PR_TEST + 1);
  314. }
  315. return 0;
  316. }
  317. static int
  318. append_ast_comprehensions(_PyUnicodeWriter *writer, asdl_seq *comprehensions)
  319. {
  320. Py_ssize_t i, gen_count;
  321. gen_count = asdl_seq_LEN(comprehensions);
  322. for (i = 0; i < gen_count; i++) {
  323. APPEND(comprehension, (comprehension_ty)asdl_seq_GET(comprehensions, i));
  324. }
  325. return 0;
  326. }
  327. static int
  328. append_ast_genexp(_PyUnicodeWriter *writer, expr_ty e)
  329. {
  330. APPEND_STR("(");
  331. APPEND_EXPR(e->v.GeneratorExp.elt, PR_TEST);
  332. APPEND(comprehensions, e->v.GeneratorExp.generators);
  333. APPEND_STR_FINISH(")");
  334. }
  335. static int
  336. append_ast_listcomp(_PyUnicodeWriter *writer, expr_ty e)
  337. {
  338. APPEND_STR("[");
  339. APPEND_EXPR(e->v.ListComp.elt, PR_TEST);
  340. APPEND(comprehensions, e->v.ListComp.generators);
  341. APPEND_STR_FINISH("]");
  342. }
  343. static int
  344. append_ast_setcomp(_PyUnicodeWriter *writer, expr_ty e)
  345. {
  346. APPEND_STR("{");
  347. APPEND_EXPR(e->v.SetComp.elt, PR_TEST);
  348. APPEND(comprehensions, e->v.SetComp.generators);
  349. APPEND_STR_FINISH("}");
  350. }
  351. static int
  352. append_ast_dictcomp(_PyUnicodeWriter *writer, expr_ty e)
  353. {
  354. APPEND_STR("{");
  355. APPEND_EXPR(e->v.DictComp.key, PR_TEST);
  356. APPEND_STR(": ");
  357. APPEND_EXPR(e->v.DictComp.value, PR_TEST);
  358. APPEND(comprehensions, e->v.DictComp.generators);
  359. APPEND_STR_FINISH("}");
  360. }
  361. static int
  362. append_ast_compare(_PyUnicodeWriter *writer, expr_ty e, int level)
  363. {
  364. const char *op;
  365. Py_ssize_t i, comparator_count;
  366. asdl_seq *comparators;
  367. asdl_int_seq *ops;
  368. APPEND_STR_IF(level > PR_CMP, "(");
  369. comparators = e->v.Compare.comparators;
  370. ops = e->v.Compare.ops;
  371. comparator_count = asdl_seq_LEN(comparators);
  372. assert(comparator_count > 0);
  373. assert(comparator_count == asdl_seq_LEN(ops));
  374. APPEND_EXPR(e->v.Compare.left, PR_CMP + 1);
  375. for (i = 0; i < comparator_count; i++) {
  376. switch ((cmpop_ty)asdl_seq_GET(ops, i)) {
  377. case Eq:
  378. op = " == ";
  379. break;
  380. case NotEq:
  381. op = " != ";
  382. break;
  383. case Lt:
  384. op = " < ";
  385. break;
  386. case LtE:
  387. op = " <= ";
  388. break;
  389. case Gt:
  390. op = " > ";
  391. break;
  392. case GtE:
  393. op = " >= ";
  394. break;
  395. case Is:
  396. op = " is ";
  397. break;
  398. case IsNot:
  399. op = " is not ";
  400. break;
  401. case In:
  402. op = " in ";
  403. break;
  404. case NotIn:
  405. op = " not in ";
  406. break;
  407. default:
  408. PyErr_SetString(PyExc_SystemError,
  409. "unexpected comparison kind");
  410. return -1;
  411. }
  412. APPEND_STR(op);
  413. APPEND_EXPR((expr_ty)asdl_seq_GET(comparators, i), PR_CMP + 1);
  414. }
  415. APPEND_STR_IF(level > PR_CMP, ")");
  416. return 0;
  417. }
  418. static int
  419. append_ast_keyword(_PyUnicodeWriter *writer, keyword_ty kw)
  420. {
  421. if (kw->arg == NULL) {
  422. APPEND_STR("**");
  423. }
  424. else {
  425. if (-1 == _PyUnicodeWriter_WriteStr(writer, kw->arg)) {
  426. return -1;
  427. }
  428. APPEND_STR("=");
  429. }
  430. APPEND_EXPR(kw->value, PR_TEST);
  431. return 0;
  432. }
  433. static int
  434. append_ast_call(_PyUnicodeWriter *writer, expr_ty e)
  435. {
  436. bool first;
  437. Py_ssize_t i, arg_count, kw_count;
  438. expr_ty expr;
  439. APPEND_EXPR(e->v.Call.func, PR_ATOM);
  440. arg_count = asdl_seq_LEN(e->v.Call.args);
  441. kw_count = asdl_seq_LEN(e->v.Call.keywords);
  442. if (arg_count == 1 && kw_count == 0) {
  443. expr = (expr_ty)asdl_seq_GET(e->v.Call.args, 0);
  444. if (expr->kind == GeneratorExp_kind) {
  445. /* Special case: a single generator expression. */
  446. return append_ast_genexp(writer, expr);
  447. }
  448. }
  449. APPEND_STR("(");
  450. first = true;
  451. for (i = 0; i < arg_count; i++) {
  452. APPEND_STR_IF_NOT_FIRST(", ");
  453. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Call.args, i), PR_TEST);
  454. }
  455. for (i = 0; i < kw_count; i++) {
  456. APPEND_STR_IF_NOT_FIRST(", ");
  457. APPEND(keyword, (keyword_ty)asdl_seq_GET(e->v.Call.keywords, i));
  458. }
  459. APPEND_STR_FINISH(")");
  460. }
  461. static PyObject *
  462. escape_braces(PyObject *orig)
  463. {
  464. PyObject *temp;
  465. PyObject *result;
  466. temp = PyUnicode_Replace(orig, _str_open_br, _str_dbl_open_br, -1);
  467. if (!temp) {
  468. return NULL;
  469. }
  470. result = PyUnicode_Replace(temp, _str_close_br, _str_dbl_close_br, -1);
  471. Py_DECREF(temp);
  472. return result;
  473. }
  474. static int
  475. append_fstring_unicode(_PyUnicodeWriter *writer, PyObject *unicode)
  476. {
  477. PyObject *escaped;
  478. int result = -1;
  479. escaped = escape_braces(unicode);
  480. if (escaped) {
  481. result = _PyUnicodeWriter_WriteStr(writer, escaped);
  482. Py_DECREF(escaped);
  483. }
  484. return result;
  485. }
  486. static int
  487. append_fstring_element(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  488. {
  489. switch (e->kind) {
  490. case Constant_kind:
  491. return append_fstring_unicode(writer, e->v.Constant.value);
  492. case JoinedStr_kind:
  493. return append_joinedstr(writer, e, is_format_spec);
  494. case FormattedValue_kind:
  495. return append_formattedvalue(writer, e, is_format_spec);
  496. default:
  497. PyErr_SetString(PyExc_SystemError,
  498. "unknown expression kind inside f-string");
  499. return -1;
  500. }
  501. }
  502. /* Build body separately to enable wrapping the entire stream of Strs,
  503. Constants and FormattedValues in one opening and one closing quote. */
  504. static PyObject *
  505. build_fstring_body(asdl_seq *values, bool is_format_spec)
  506. {
  507. Py_ssize_t i, value_count;
  508. _PyUnicodeWriter body_writer;
  509. _PyUnicodeWriter_Init(&body_writer);
  510. body_writer.min_length = 256;
  511. body_writer.overallocate = 1;
  512. value_count = asdl_seq_LEN(values);
  513. for (i = 0; i < value_count; ++i) {
  514. if (-1 == append_fstring_element(&body_writer,
  515. (expr_ty)asdl_seq_GET(values, i),
  516. is_format_spec
  517. )) {
  518. _PyUnicodeWriter_Dealloc(&body_writer);
  519. return NULL;
  520. }
  521. }
  522. return _PyUnicodeWriter_Finish(&body_writer);
  523. }
  524. static int
  525. append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  526. {
  527. int result = -1;
  528. PyObject *body = build_fstring_body(e->v.JoinedStr.values, is_format_spec);
  529. if (!body) {
  530. return -1;
  531. }
  532. if (!is_format_spec) {
  533. if (-1 != append_charp(writer, "f") &&
  534. -1 != append_repr(writer, body))
  535. {
  536. result = 0;
  537. }
  538. }
  539. else {
  540. result = _PyUnicodeWriter_WriteStr(writer, body);
  541. }
  542. Py_DECREF(body);
  543. return result;
  544. }
  545. static int
  546. append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  547. {
  548. const char *conversion;
  549. const char *outer_brace = "{";
  550. /* Grammar allows PR_TUPLE, but use >PR_TEST for adding parenthesis
  551. around a lambda with ':' */
  552. PyObject *temp_fv_str = expr_as_unicode(e->v.FormattedValue.value, PR_TEST + 1);
  553. if (!temp_fv_str) {
  554. return -1;
  555. }
  556. if (PyUnicode_Find(temp_fv_str, _str_open_br, 0, 1, 1) == 0) {
  557. /* Expression starts with a brace, split it with a space from the outer
  558. one. */
  559. outer_brace = "{ ";
  560. }
  561. if (-1 == append_charp(writer, outer_brace)) {
  562. Py_DECREF(temp_fv_str);
  563. return -1;
  564. }
  565. if (-1 == _PyUnicodeWriter_WriteStr(writer, temp_fv_str)) {
  566. Py_DECREF(temp_fv_str);
  567. return -1;
  568. }
  569. Py_DECREF(temp_fv_str);
  570. if (e->v.FormattedValue.conversion > 0) {
  571. switch (e->v.FormattedValue.conversion) {
  572. case 'a':
  573. conversion = "!a";
  574. break;
  575. case 'r':
  576. conversion = "!r";
  577. break;
  578. case 's':
  579. conversion = "!s";
  580. break;
  581. default:
  582. PyErr_SetString(PyExc_SystemError,
  583. "unknown f-value conversion kind");
  584. return -1;
  585. }
  586. APPEND_STR(conversion);
  587. }
  588. if (e->v.FormattedValue.format_spec) {
  589. if (-1 == _PyUnicodeWriter_WriteASCIIString(writer, ":", 1) ||
  590. -1 == append_fstring_element(writer,
  591. e->v.FormattedValue.format_spec,
  592. true
  593. ))
  594. {
  595. return -1;
  596. }
  597. }
  598. APPEND_STR_FINISH("}");
  599. }
  600. static int
  601. append_ast_attribute(_PyUnicodeWriter *writer, expr_ty e)
  602. {
  603. const char *period;
  604. expr_ty v = e->v.Attribute.value;
  605. APPEND_EXPR(v, PR_ATOM);
  606. /* Special case: integers require a space for attribute access to be
  607. unambiguous. */
  608. if (v->kind == Constant_kind && PyLong_CheckExact(v->v.Constant.value)) {
  609. period = " .";
  610. }
  611. else {
  612. period = ".";
  613. }
  614. APPEND_STR(period);
  615. return _PyUnicodeWriter_WriteStr(writer, e->v.Attribute.attr);
  616. }
  617. static int
  618. append_ast_simple_slice(_PyUnicodeWriter *writer, slice_ty slice)
  619. {
  620. if (slice->v.Slice.lower) {
  621. APPEND_EXPR(slice->v.Slice.lower, PR_TEST);
  622. }
  623. APPEND_STR(":");
  624. if (slice->v.Slice.upper) {
  625. APPEND_EXPR(slice->v.Slice.upper, PR_TEST);
  626. }
  627. if (slice->v.Slice.step) {
  628. APPEND_STR(":");
  629. APPEND_EXPR(slice->v.Slice.step, PR_TEST);
  630. }
  631. return 0;
  632. }
  633. static int
  634. append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
  635. {
  636. Py_ssize_t i, dims_count;
  637. dims_count = asdl_seq_LEN(slice->v.ExtSlice.dims);
  638. for (i = 0; i < dims_count; i++) {
  639. APPEND_STR_IF(i > 0, ", ");
  640. APPEND(slice, (slice_ty)asdl_seq_GET(slice->v.ExtSlice.dims, i));
  641. }
  642. return 0;
  643. }
  644. static int
  645. append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
  646. {
  647. switch (slice->kind) {
  648. case Slice_kind:
  649. return append_ast_simple_slice(writer, slice);
  650. case ExtSlice_kind:
  651. return append_ast_ext_slice(writer, slice);
  652. case Index_kind:
  653. APPEND_EXPR(slice->v.Index.value, PR_TUPLE);
  654. return 0;
  655. default:
  656. PyErr_SetString(PyExc_SystemError,
  657. "unexpected slice kind");
  658. return -1;
  659. }
  660. }
  661. static int
  662. append_ast_subscript(_PyUnicodeWriter *writer, expr_ty e)
  663. {
  664. APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
  665. APPEND_STR("[");
  666. APPEND(slice, e->v.Subscript.slice);
  667. APPEND_STR_FINISH("]");
  668. }
  669. static int
  670. append_ast_starred(_PyUnicodeWriter *writer, expr_ty e)
  671. {
  672. APPEND_STR("*");
  673. APPEND_EXPR(e->v.Starred.value, PR_EXPR);
  674. return 0;
  675. }
  676. static int
  677. append_ast_yield(_PyUnicodeWriter *writer, expr_ty e)
  678. {
  679. if (!e->v.Yield.value) {
  680. APPEND_STR_FINISH("(yield)");
  681. }
  682. APPEND_STR("(yield ");
  683. APPEND_EXPR(e->v.Yield.value, PR_TEST);
  684. APPEND_STR_FINISH(")");
  685. }
  686. static int
  687. append_ast_yield_from(_PyUnicodeWriter *writer, expr_ty e)
  688. {
  689. APPEND_STR("(yield from ");
  690. APPEND_EXPR(e->v.YieldFrom.value, PR_TEST);
  691. APPEND_STR_FINISH(")");
  692. }
  693. static int
  694. append_ast_await(_PyUnicodeWriter *writer, expr_ty e, int level)
  695. {
  696. APPEND_STR_IF(level > PR_AWAIT, "(");
  697. APPEND_STR("await ");
  698. APPEND_EXPR(e->v.Await.value, PR_ATOM);
  699. APPEND_STR_IF(level > PR_AWAIT, ")");
  700. return 0;
  701. }
  702. static int
  703. append_ast_expr(_PyUnicodeWriter *writer, expr_ty e, int level)
  704. {
  705. switch (e->kind) {
  706. case BoolOp_kind:
  707. return append_ast_boolop(writer, e, level);
  708. case BinOp_kind:
  709. return append_ast_binop(writer, e, level);
  710. case UnaryOp_kind:
  711. return append_ast_unaryop(writer, e, level);
  712. case Lambda_kind:
  713. return append_ast_lambda(writer, e, level);
  714. case IfExp_kind:
  715. return append_ast_ifexp(writer, e, level);
  716. case Dict_kind:
  717. return append_ast_dict(writer, e);
  718. case Set_kind:
  719. return append_ast_set(writer, e);
  720. case GeneratorExp_kind:
  721. return append_ast_genexp(writer, e);
  722. case ListComp_kind:
  723. return append_ast_listcomp(writer, e);
  724. case SetComp_kind:
  725. return append_ast_setcomp(writer, e);
  726. case DictComp_kind:
  727. return append_ast_dictcomp(writer, e);
  728. case Yield_kind:
  729. return append_ast_yield(writer, e);
  730. case YieldFrom_kind:
  731. return append_ast_yield_from(writer, e);
  732. case Await_kind:
  733. return append_ast_await(writer, e, level);
  734. case Compare_kind:
  735. return append_ast_compare(writer, e, level);
  736. case Call_kind:
  737. return append_ast_call(writer, e);
  738. case Constant_kind:
  739. if (e->v.Constant.value == Py_Ellipsis) {
  740. APPEND_STR_FINISH("...");
  741. }
  742. return append_repr(writer, e->v.Constant.value);
  743. case JoinedStr_kind:
  744. return append_joinedstr(writer, e, false);
  745. case FormattedValue_kind:
  746. return append_formattedvalue(writer, e, false);
  747. /* The following exprs can be assignment targets. */
  748. case Attribute_kind:
  749. return append_ast_attribute(writer, e);
  750. case Subscript_kind:
  751. return append_ast_subscript(writer, e);
  752. case Starred_kind:
  753. return append_ast_starred(writer, e);
  754. case Name_kind:
  755. return _PyUnicodeWriter_WriteStr(writer, e->v.Name.id);
  756. case List_kind:
  757. return append_ast_list(writer, e);
  758. case Tuple_kind:
  759. return append_ast_tuple(writer, e, level);
  760. default:
  761. PyErr_SetString(PyExc_SystemError,
  762. "unknown expression kind");
  763. return -1;
  764. }
  765. }
  766. static int
  767. maybe_init_static_strings(void)
  768. {
  769. if (!_str_open_br &&
  770. !(_str_open_br = PyUnicode_InternFromString("{"))) {
  771. return -1;
  772. }
  773. if (!_str_dbl_open_br &&
  774. !(_str_dbl_open_br = PyUnicode_InternFromString("{{"))) {
  775. return -1;
  776. }
  777. if (!_str_close_br &&
  778. !(_str_close_br = PyUnicode_InternFromString("}"))) {
  779. return -1;
  780. }
  781. if (!_str_dbl_close_br &&
  782. !(_str_dbl_close_br = PyUnicode_InternFromString("}}"))) {
  783. return -1;
  784. }
  785. return 0;
  786. }
  787. static PyObject *
  788. expr_as_unicode(expr_ty e, int level)
  789. {
  790. _PyUnicodeWriter writer;
  791. _PyUnicodeWriter_Init(&writer);
  792. writer.min_length = 256;
  793. writer.overallocate = 1;
  794. if (-1 == maybe_init_static_strings() ||
  795. -1 == append_ast_expr(&writer, e, level))
  796. {
  797. _PyUnicodeWriter_Dealloc(&writer);
  798. return NULL;
  799. }
  800. return _PyUnicodeWriter_Finish(&writer);
  801. }
  802. PyObject *
  803. _PyAST_ExprAsUnicode(expr_ty e)
  804. {
  805. return expr_as_unicode(e, PR_TEST);
  806. }