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.

921 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 || 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. APPEND_STR("=");
  202. APPEND_EXPR((expr_ty)asdl_seq_GET(args->kw_defaults, di), PR_TEST);
  203. }
  204. }
  205. /* **kwargs */
  206. if (args->kwarg) {
  207. APPEND_STR_IF_NOT_FIRST(", ");
  208. APPEND_STR("**");
  209. APPEND(arg, args->kwarg);
  210. }
  211. return 0;
  212. }
  213. static int
  214. append_ast_lambda(_PyUnicodeWriter *writer, expr_ty e, int level)
  215. {
  216. APPEND_STR_IF(level > PR_TEST, "(");
  217. APPEND_STR("lambda ");
  218. APPEND(args, e->v.Lambda.args);
  219. APPEND_STR(": ");
  220. APPEND_EXPR(e->v.Lambda.body, PR_TEST);
  221. APPEND_STR_IF(level > PR_TEST, ")");
  222. return 0;
  223. }
  224. static int
  225. append_ast_ifexp(_PyUnicodeWriter *writer, expr_ty e, int level)
  226. {
  227. APPEND_STR_IF(level > PR_TEST, "(");
  228. APPEND_EXPR(e->v.IfExp.body, PR_TEST + 1);
  229. APPEND_STR(" if ");
  230. APPEND_EXPR(e->v.IfExp.test, PR_TEST + 1);
  231. APPEND_STR(" else ");
  232. APPEND_EXPR(e->v.IfExp.orelse, PR_TEST);
  233. APPEND_STR_IF(level > PR_TEST, ")");
  234. return 0;
  235. }
  236. static int
  237. append_ast_dict(_PyUnicodeWriter *writer, expr_ty e)
  238. {
  239. Py_ssize_t i, value_count;
  240. expr_ty key_node;
  241. APPEND_STR("{");
  242. value_count = asdl_seq_LEN(e->v.Dict.values);
  243. for (i = 0; i < value_count; i++) {
  244. APPEND_STR_IF(i > 0, ", ");
  245. key_node = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i);
  246. if (key_node != NULL) {
  247. APPEND_EXPR(key_node, PR_TEST);
  248. APPEND_STR(": ");
  249. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_TEST);
  250. }
  251. else {
  252. APPEND_STR("**");
  253. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_EXPR);
  254. }
  255. }
  256. APPEND_STR_FINISH("}");
  257. }
  258. static int
  259. append_ast_set(_PyUnicodeWriter *writer, expr_ty e)
  260. {
  261. Py_ssize_t i, elem_count;
  262. APPEND_STR("{");
  263. elem_count = asdl_seq_LEN(e->v.Set.elts);
  264. for (i = 0; i < elem_count; i++) {
  265. APPEND_STR_IF(i > 0, ", ");
  266. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST);
  267. }
  268. APPEND_STR_FINISH("}");
  269. }
  270. static int
  271. append_ast_list(_PyUnicodeWriter *writer, expr_ty e)
  272. {
  273. Py_ssize_t i, elem_count;
  274. APPEND_STR("[");
  275. elem_count = asdl_seq_LEN(e->v.List.elts);
  276. for (i = 0; i < elem_count; i++) {
  277. APPEND_STR_IF(i > 0, ", ");
  278. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.List.elts, i), PR_TEST);
  279. }
  280. APPEND_STR_FINISH("]");
  281. }
  282. static int
  283. append_ast_tuple(_PyUnicodeWriter *writer, expr_ty e, int level)
  284. {
  285. Py_ssize_t i, elem_count;
  286. elem_count = asdl_seq_LEN(e->v.Tuple.elts);
  287. if (elem_count == 0) {
  288. APPEND_STR_FINISH("()");
  289. }
  290. APPEND_STR_IF(level > PR_TUPLE, "(");
  291. for (i = 0; i < elem_count; i++) {
  292. APPEND_STR_IF(i > 0, ", ");
  293. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Tuple.elts, i), PR_TEST);
  294. }
  295. APPEND_STR_IF(elem_count == 1, ",");
  296. APPEND_STR_IF(level > PR_TUPLE, ")");
  297. return 0;
  298. }
  299. static int
  300. append_ast_comprehension(_PyUnicodeWriter *writer, comprehension_ty gen)
  301. {
  302. Py_ssize_t i, if_count;
  303. APPEND_STR(gen->is_async ? " async for " : " for ");
  304. APPEND_EXPR(gen->target, PR_TUPLE);
  305. APPEND_STR(" in ");
  306. APPEND_EXPR(gen->iter, PR_TEST + 1);
  307. if_count = asdl_seq_LEN(gen->ifs);
  308. for (i = 0; i < if_count; i++) {
  309. APPEND_STR(" if ");
  310. APPEND_EXPR((expr_ty)asdl_seq_GET(gen->ifs, i), PR_TEST + 1);
  311. }
  312. return 0;
  313. }
  314. static int
  315. append_ast_comprehensions(_PyUnicodeWriter *writer, asdl_seq *comprehensions)
  316. {
  317. Py_ssize_t i, gen_count;
  318. gen_count = asdl_seq_LEN(comprehensions);
  319. for (i = 0; i < gen_count; i++) {
  320. APPEND(comprehension, (comprehension_ty)asdl_seq_GET(comprehensions, i));
  321. }
  322. return 0;
  323. }
  324. static int
  325. append_ast_genexp(_PyUnicodeWriter *writer, expr_ty e)
  326. {
  327. APPEND_STR("(");
  328. APPEND_EXPR(e->v.GeneratorExp.elt, PR_TEST);
  329. APPEND(comprehensions, e->v.GeneratorExp.generators);
  330. APPEND_STR_FINISH(")");
  331. }
  332. static int
  333. append_ast_listcomp(_PyUnicodeWriter *writer, expr_ty e)
  334. {
  335. APPEND_STR("[");
  336. APPEND_EXPR(e->v.ListComp.elt, PR_TEST);
  337. APPEND(comprehensions, e->v.ListComp.generators);
  338. APPEND_STR_FINISH("]");
  339. }
  340. static int
  341. append_ast_setcomp(_PyUnicodeWriter *writer, expr_ty e)
  342. {
  343. APPEND_STR("{");
  344. APPEND_EXPR(e->v.SetComp.elt, PR_TEST);
  345. APPEND(comprehensions, e->v.SetComp.generators);
  346. APPEND_STR_FINISH("}");
  347. }
  348. static int
  349. append_ast_dictcomp(_PyUnicodeWriter *writer, expr_ty e)
  350. {
  351. APPEND_STR("{");
  352. APPEND_EXPR(e->v.DictComp.key, PR_TEST);
  353. APPEND_STR(": ");
  354. APPEND_EXPR(e->v.DictComp.value, PR_TEST);
  355. APPEND(comprehensions, e->v.DictComp.generators);
  356. APPEND_STR_FINISH("}");
  357. }
  358. static int
  359. append_ast_compare(_PyUnicodeWriter *writer, expr_ty e, int level)
  360. {
  361. const char *op;
  362. Py_ssize_t i, comparator_count;
  363. asdl_seq *comparators;
  364. asdl_int_seq *ops;
  365. APPEND_STR_IF(level > PR_CMP, "(");
  366. comparators = e->v.Compare.comparators;
  367. ops = e->v.Compare.ops;
  368. comparator_count = asdl_seq_LEN(comparators);
  369. assert(comparator_count > 0);
  370. assert(comparator_count == asdl_seq_LEN(ops));
  371. APPEND_EXPR(e->v.Compare.left, PR_CMP + 1);
  372. for (i = 0; i < comparator_count; i++) {
  373. switch ((cmpop_ty)asdl_seq_GET(ops, i)) {
  374. case Eq:
  375. op = " == ";
  376. break;
  377. case NotEq:
  378. op = " != ";
  379. break;
  380. case Lt:
  381. op = " < ";
  382. break;
  383. case LtE:
  384. op = " <= ";
  385. break;
  386. case Gt:
  387. op = " > ";
  388. break;
  389. case GtE:
  390. op = " >= ";
  391. break;
  392. case Is:
  393. op = " is ";
  394. break;
  395. case IsNot:
  396. op = " is not ";
  397. break;
  398. case In:
  399. op = " in ";
  400. break;
  401. case NotIn:
  402. op = " not in ";
  403. break;
  404. default:
  405. PyErr_SetString(PyExc_SystemError,
  406. "unexpected comparison kind");
  407. return -1;
  408. }
  409. APPEND_STR(op);
  410. APPEND_EXPR((expr_ty)asdl_seq_GET(comparators, i), PR_CMP + 1);
  411. }
  412. APPEND_STR_IF(level > PR_CMP, ")");
  413. return 0;
  414. }
  415. static int
  416. append_ast_keyword(_PyUnicodeWriter *writer, keyword_ty kw)
  417. {
  418. if (kw->arg == NULL) {
  419. APPEND_STR("**");
  420. }
  421. else {
  422. if (-1 == _PyUnicodeWriter_WriteStr(writer, kw->arg)) {
  423. return -1;
  424. }
  425. APPEND_STR("=");
  426. }
  427. APPEND_EXPR(kw->value, PR_TEST);
  428. return 0;
  429. }
  430. static int
  431. append_ast_call(_PyUnicodeWriter *writer, expr_ty e)
  432. {
  433. bool first;
  434. Py_ssize_t i, arg_count, kw_count;
  435. expr_ty expr;
  436. APPEND_EXPR(e->v.Call.func, PR_ATOM);
  437. arg_count = asdl_seq_LEN(e->v.Call.args);
  438. kw_count = asdl_seq_LEN(e->v.Call.keywords);
  439. if (arg_count == 1 && kw_count == 0) {
  440. expr = (expr_ty)asdl_seq_GET(e->v.Call.args, 0);
  441. if (expr->kind == GeneratorExp_kind) {
  442. /* Special case: a single generator expression. */
  443. return append_ast_genexp(writer, expr);
  444. }
  445. }
  446. APPEND_STR("(");
  447. first = true;
  448. for (i = 0; i < arg_count; i++) {
  449. APPEND_STR_IF_NOT_FIRST(", ");
  450. APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Call.args, i), PR_TEST);
  451. }
  452. for (i = 0; i < kw_count; i++) {
  453. APPEND_STR_IF_NOT_FIRST(", ");
  454. APPEND(keyword, (keyword_ty)asdl_seq_GET(e->v.Call.keywords, i));
  455. }
  456. APPEND_STR_FINISH(")");
  457. }
  458. static PyObject *
  459. escape_braces(PyObject *orig)
  460. {
  461. PyObject *temp;
  462. PyObject *result;
  463. temp = PyUnicode_Replace(orig, _str_open_br, _str_dbl_open_br, -1);
  464. if (!temp) {
  465. return NULL;
  466. }
  467. result = PyUnicode_Replace(temp, _str_close_br, _str_dbl_close_br, -1);
  468. Py_DECREF(temp);
  469. return result;
  470. }
  471. static int
  472. append_fstring_unicode(_PyUnicodeWriter *writer, PyObject *unicode)
  473. {
  474. PyObject *escaped;
  475. int result = -1;
  476. escaped = escape_braces(unicode);
  477. if (escaped) {
  478. result = _PyUnicodeWriter_WriteStr(writer, escaped);
  479. Py_DECREF(escaped);
  480. }
  481. return result;
  482. }
  483. static int
  484. append_fstring_element(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  485. {
  486. switch (e->kind) {
  487. case Constant_kind:
  488. return append_fstring_unicode(writer, e->v.Constant.value);
  489. case Str_kind:
  490. return append_fstring_unicode(writer, e->v.Str.s);
  491. case JoinedStr_kind:
  492. return append_joinedstr(writer, e, is_format_spec);
  493. case FormattedValue_kind:
  494. return append_formattedvalue(writer, e, is_format_spec);
  495. default:
  496. PyErr_SetString(PyExc_SystemError,
  497. "unknown expression kind inside f-string");
  498. return -1;
  499. }
  500. }
  501. /* Build body separately to enable wrapping the entire stream of Strs,
  502. Constants and FormattedValues in one opening and one closing quote. */
  503. static PyObject *
  504. build_fstring_body(asdl_seq *values, bool is_format_spec)
  505. {
  506. Py_ssize_t i, value_count;
  507. _PyUnicodeWriter body_writer;
  508. _PyUnicodeWriter_Init(&body_writer);
  509. body_writer.min_length = 256;
  510. body_writer.overallocate = 1;
  511. value_count = asdl_seq_LEN(values);
  512. for (i = 0; i < value_count; ++i) {
  513. if (-1 == append_fstring_element(&body_writer,
  514. (expr_ty)asdl_seq_GET(values, i),
  515. is_format_spec
  516. )) {
  517. _PyUnicodeWriter_Dealloc(&body_writer);
  518. return NULL;
  519. }
  520. }
  521. return _PyUnicodeWriter_Finish(&body_writer);
  522. }
  523. static int
  524. append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  525. {
  526. int result = -1;
  527. PyObject *body = build_fstring_body(e->v.JoinedStr.values, is_format_spec);
  528. if (!body) {
  529. return -1;
  530. }
  531. if (!is_format_spec) {
  532. if (-1 != append_charp(writer, "f") &&
  533. -1 != append_repr(writer, body))
  534. {
  535. result = 0;
  536. }
  537. }
  538. else {
  539. result = _PyUnicodeWriter_WriteStr(writer, body);
  540. }
  541. Py_DECREF(body);
  542. return result;
  543. }
  544. static int
  545. append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
  546. {
  547. const char *conversion;
  548. const char *outer_brace = "{";
  549. /* Grammar allows PR_TUPLE, but use >PR_TEST for adding parenthesis
  550. around a lambda with ':' */
  551. PyObject *temp_fv_str = expr_as_unicode(e->v.FormattedValue.value, PR_TEST + 1);
  552. if (!temp_fv_str) {
  553. return -1;
  554. }
  555. if (PyUnicode_Find(temp_fv_str, _str_open_br, 0, 1, 1) == 0) {
  556. /* Expression starts with a brace, split it with a space from the outer
  557. one. */
  558. outer_brace = "{ ";
  559. }
  560. if (-1 == append_charp(writer, outer_brace)) {
  561. Py_DECREF(temp_fv_str);
  562. return -1;
  563. }
  564. if (-1 == _PyUnicodeWriter_WriteStr(writer, temp_fv_str)) {
  565. Py_DECREF(temp_fv_str);
  566. return -1;
  567. }
  568. Py_DECREF(temp_fv_str);
  569. if (e->v.FormattedValue.conversion > 0) {
  570. switch (e->v.FormattedValue.conversion) {
  571. case 'a':
  572. conversion = "!a";
  573. break;
  574. case 'r':
  575. conversion = "!r";
  576. break;
  577. case 's':
  578. conversion = "!s";
  579. break;
  580. default:
  581. PyErr_SetString(PyExc_SystemError,
  582. "unknown f-value conversion kind");
  583. return -1;
  584. }
  585. APPEND_STR(conversion);
  586. }
  587. if (e->v.FormattedValue.format_spec) {
  588. if (-1 == _PyUnicodeWriter_WriteASCIIString(writer, ":", 1) ||
  589. -1 == append_fstring_element(writer,
  590. e->v.FormattedValue.format_spec,
  591. true
  592. ))
  593. {
  594. return -1;
  595. }
  596. }
  597. APPEND_STR_FINISH("}");
  598. }
  599. static int
  600. append_ast_attribute(_PyUnicodeWriter *writer, expr_ty e)
  601. {
  602. const char *period;
  603. APPEND_EXPR(e->v.Attribute.value, PR_ATOM);
  604. /* Special case: integers require a space for attribute access to be
  605. unambiguous. Floats and complex numbers don't but work with it, too. */
  606. if (e->v.Attribute.value->kind == Num_kind ||
  607. e->v.Attribute.value->kind == Constant_kind)
  608. {
  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. return append_repr(writer, e->v.Constant.value);
  740. case Num_kind:
  741. return append_repr(writer, e->v.Num.n);
  742. case Str_kind:
  743. return append_repr(writer, e->v.Str.s);
  744. case JoinedStr_kind:
  745. return append_joinedstr(writer, e, false);
  746. case FormattedValue_kind:
  747. return append_formattedvalue(writer, e, false);
  748. case Bytes_kind:
  749. return append_repr(writer, e->v.Bytes.s);
  750. case Ellipsis_kind:
  751. APPEND_STR_FINISH("...");
  752. case NameConstant_kind:
  753. return append_repr(writer, e->v.NameConstant.value);
  754. /* The following exprs can be assignment targets. */
  755. case Attribute_kind:
  756. return append_ast_attribute(writer, e);
  757. case Subscript_kind:
  758. return append_ast_subscript(writer, e);
  759. case Starred_kind:
  760. return append_ast_starred(writer, e);
  761. case Name_kind:
  762. return _PyUnicodeWriter_WriteStr(writer, e->v.Name.id);
  763. case List_kind:
  764. return append_ast_list(writer, e);
  765. case Tuple_kind:
  766. return append_ast_tuple(writer, e, level);
  767. default:
  768. PyErr_SetString(PyExc_SystemError,
  769. "unknown expression kind");
  770. return -1;
  771. }
  772. }
  773. static int
  774. maybe_init_static_strings(void)
  775. {
  776. if (!_str_open_br &&
  777. !(_str_open_br = PyUnicode_InternFromString("{"))) {
  778. return -1;
  779. }
  780. if (!_str_dbl_open_br &&
  781. !(_str_dbl_open_br = PyUnicode_InternFromString("{{"))) {
  782. return -1;
  783. }
  784. if (!_str_close_br &&
  785. !(_str_close_br = PyUnicode_InternFromString("}"))) {
  786. return -1;
  787. }
  788. if (!_str_dbl_close_br &&
  789. !(_str_dbl_close_br = PyUnicode_InternFromString("}}"))) {
  790. return -1;
  791. }
  792. return 0;
  793. }
  794. static PyObject *
  795. expr_as_unicode(expr_ty e, int level)
  796. {
  797. _PyUnicodeWriter writer;
  798. _PyUnicodeWriter_Init(&writer);
  799. writer.min_length = 256;
  800. writer.overallocate = 1;
  801. if (-1 == maybe_init_static_strings() ||
  802. -1 == append_ast_expr(&writer, e, level))
  803. {
  804. _PyUnicodeWriter_Dealloc(&writer);
  805. return NULL;
  806. }
  807. return _PyUnicodeWriter_Finish(&writer);
  808. }
  809. PyObject *
  810. _PyAST_ExprAsUnicode(expr_ty e)
  811. {
  812. return expr_as_unicode(e, PR_TEST);
  813. }