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.

891 lines
28 KiB

  1. /* AST Optimizer */
  2. #include "Python.h"
  3. #include "pycore_ast.h" // _PyAST_GetDocString()
  4. #include "pycore_compile.h" // _PyASTOptimizeState
  5. static int
  6. make_const(expr_ty node, PyObject *val, PyArena *arena)
  7. {
  8. // Even if no new value was calculated, make_const may still
  9. // need to clear an error (e.g. for division by zero)
  10. if (val == NULL) {
  11. if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
  12. return 0;
  13. }
  14. PyErr_Clear();
  15. return 1;
  16. }
  17. if (_PyArena_AddPyObject(arena, val) < 0) {
  18. Py_DECREF(val);
  19. return 0;
  20. }
  21. node->kind = Constant_kind;
  22. node->v.Constant.kind = NULL;
  23. node->v.Constant.value = val;
  24. return 1;
  25. }
  26. #define COPY_NODE(TO, FROM) (memcpy((TO), (FROM), sizeof(struct _expr)))
  27. static PyObject*
  28. unary_not(PyObject *v)
  29. {
  30. int r = PyObject_IsTrue(v);
  31. if (r < 0)
  32. return NULL;
  33. return PyBool_FromLong(!r);
  34. }
  35. static int
  36. fold_unaryop(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
  37. {
  38. expr_ty arg = node->v.UnaryOp.operand;
  39. if (arg->kind != Constant_kind) {
  40. /* Fold not into comparison */
  41. if (node->v.UnaryOp.op == Not && arg->kind == Compare_kind &&
  42. asdl_seq_LEN(arg->v.Compare.ops) == 1) {
  43. /* Eq and NotEq are often implemented in terms of one another, so
  44. folding not (self == other) into self != other breaks implementation
  45. of !=. Detecting such cases doesn't seem worthwhile.
  46. Python uses </> for 'is subset'/'is superset' operations on sets.
  47. They don't satisfy not folding laws. */
  48. cmpop_ty op = asdl_seq_GET(arg->v.Compare.ops, 0);
  49. switch (op) {
  50. case Is:
  51. op = IsNot;
  52. break;
  53. case IsNot:
  54. op = Is;
  55. break;
  56. case In:
  57. op = NotIn;
  58. break;
  59. case NotIn:
  60. op = In;
  61. break;
  62. // The remaining comparison operators can't be safely inverted
  63. case Eq:
  64. case NotEq:
  65. case Lt:
  66. case LtE:
  67. case Gt:
  68. case GtE:
  69. op = 0; // The AST enums leave "0" free as an "unused" marker
  70. break;
  71. // No default case, so the compiler will emit a warning if new
  72. // comparison operators are added without being handled here
  73. }
  74. if (op) {
  75. asdl_seq_SET(arg->v.Compare.ops, 0, op);
  76. COPY_NODE(node, arg);
  77. return 1;
  78. }
  79. }
  80. return 1;
  81. }
  82. typedef PyObject *(*unary_op)(PyObject*);
  83. static const unary_op ops[] = {
  84. [Invert] = PyNumber_Invert,
  85. [Not] = unary_not,
  86. [UAdd] = PyNumber_Positive,
  87. [USub] = PyNumber_Negative,
  88. };
  89. PyObject *newval = ops[node->v.UnaryOp.op](arg->v.Constant.value);
  90. return make_const(node, newval, arena);
  91. }
  92. /* Check whether a collection doesn't containing too much items (including
  93. subcollections). This protects from creating a constant that needs
  94. too much time for calculating a hash.
  95. "limit" is the maximal number of items.
  96. Returns the negative number if the total number of items exceeds the
  97. limit. Otherwise returns the limit minus the total number of items.
  98. */
  99. static Py_ssize_t
  100. check_complexity(PyObject *obj, Py_ssize_t limit)
  101. {
  102. if (PyTuple_Check(obj)) {
  103. Py_ssize_t i;
  104. limit -= PyTuple_GET_SIZE(obj);
  105. for (i = 0; limit >= 0 && i < PyTuple_GET_SIZE(obj); i++) {
  106. limit = check_complexity(PyTuple_GET_ITEM(obj, i), limit);
  107. }
  108. return limit;
  109. }
  110. else if (PyFrozenSet_Check(obj)) {
  111. Py_ssize_t i = 0;
  112. PyObject *item;
  113. Py_hash_t hash;
  114. limit -= PySet_GET_SIZE(obj);
  115. while (limit >= 0 && _PySet_NextEntry(obj, &i, &item, &hash)) {
  116. limit = check_complexity(item, limit);
  117. }
  118. }
  119. return limit;
  120. }
  121. #define MAX_INT_SIZE 128 /* bits */
  122. #define MAX_COLLECTION_SIZE 256 /* items */
  123. #define MAX_STR_SIZE 4096 /* characters */
  124. #define MAX_TOTAL_ITEMS 1024 /* including nested collections */
  125. static PyObject *
  126. safe_multiply(PyObject *v, PyObject *w)
  127. {
  128. if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w)) {
  129. size_t vbits = _PyLong_NumBits(v);
  130. size_t wbits = _PyLong_NumBits(w);
  131. if (vbits == (size_t)-1 || wbits == (size_t)-1) {
  132. return NULL;
  133. }
  134. if (vbits + wbits > MAX_INT_SIZE) {
  135. return NULL;
  136. }
  137. }
  138. else if (PyLong_Check(v) && (PyTuple_Check(w) || PyFrozenSet_Check(w))) {
  139. Py_ssize_t size = PyTuple_Check(w) ? PyTuple_GET_SIZE(w) :
  140. PySet_GET_SIZE(w);
  141. if (size) {
  142. long n = PyLong_AsLong(v);
  143. if (n < 0 || n > MAX_COLLECTION_SIZE / size) {
  144. return NULL;
  145. }
  146. if (n && check_complexity(w, MAX_TOTAL_ITEMS / n) < 0) {
  147. return NULL;
  148. }
  149. }
  150. }
  151. else if (PyLong_Check(v) && (PyUnicode_Check(w) || PyBytes_Check(w))) {
  152. Py_ssize_t size = PyUnicode_Check(w) ? PyUnicode_GET_LENGTH(w) :
  153. PyBytes_GET_SIZE(w);
  154. if (size) {
  155. long n = PyLong_AsLong(v);
  156. if (n < 0 || n > MAX_STR_SIZE / size) {
  157. return NULL;
  158. }
  159. }
  160. }
  161. else if (PyLong_Check(w) &&
  162. (PyTuple_Check(v) || PyFrozenSet_Check(v) ||
  163. PyUnicode_Check(v) || PyBytes_Check(v)))
  164. {
  165. return safe_multiply(w, v);
  166. }
  167. return PyNumber_Multiply(v, w);
  168. }
  169. static PyObject *
  170. safe_power(PyObject *v, PyObject *w)
  171. {
  172. if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w) > 0) {
  173. size_t vbits = _PyLong_NumBits(v);
  174. size_t wbits = PyLong_AsSize_t(w);
  175. if (vbits == (size_t)-1 || wbits == (size_t)-1) {
  176. return NULL;
  177. }
  178. if (vbits > MAX_INT_SIZE / wbits) {
  179. return NULL;
  180. }
  181. }
  182. return PyNumber_Power(v, w, Py_None);
  183. }
  184. static PyObject *
  185. safe_lshift(PyObject *v, PyObject *w)
  186. {
  187. if (PyLong_Check(v) && PyLong_Check(w) && Py_SIZE(v) && Py_SIZE(w)) {
  188. size_t vbits = _PyLong_NumBits(v);
  189. size_t wbits = PyLong_AsSize_t(w);
  190. if (vbits == (size_t)-1 || wbits == (size_t)-1) {
  191. return NULL;
  192. }
  193. if (wbits > MAX_INT_SIZE || vbits > MAX_INT_SIZE - wbits) {
  194. return NULL;
  195. }
  196. }
  197. return PyNumber_Lshift(v, w);
  198. }
  199. static PyObject *
  200. safe_mod(PyObject *v, PyObject *w)
  201. {
  202. if (PyUnicode_Check(v) || PyBytes_Check(v)) {
  203. return NULL;
  204. }
  205. return PyNumber_Remainder(v, w);
  206. }
  207. static int
  208. fold_binop(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
  209. {
  210. expr_ty lhs, rhs;
  211. lhs = node->v.BinOp.left;
  212. rhs = node->v.BinOp.right;
  213. if (lhs->kind != Constant_kind || rhs->kind != Constant_kind) {
  214. return 1;
  215. }
  216. PyObject *lv = lhs->v.Constant.value;
  217. PyObject *rv = rhs->v.Constant.value;
  218. PyObject *newval = NULL;
  219. switch (node->v.BinOp.op) {
  220. case Add:
  221. newval = PyNumber_Add(lv, rv);
  222. break;
  223. case Sub:
  224. newval = PyNumber_Subtract(lv, rv);
  225. break;
  226. case Mult:
  227. newval = safe_multiply(lv, rv);
  228. break;
  229. case Div:
  230. newval = PyNumber_TrueDivide(lv, rv);
  231. break;
  232. case FloorDiv:
  233. newval = PyNumber_FloorDivide(lv, rv);
  234. break;
  235. case Mod:
  236. newval = safe_mod(lv, rv);
  237. break;
  238. case Pow:
  239. newval = safe_power(lv, rv);
  240. break;
  241. case LShift:
  242. newval = safe_lshift(lv, rv);
  243. break;
  244. case RShift:
  245. newval = PyNumber_Rshift(lv, rv);
  246. break;
  247. case BitOr:
  248. newval = PyNumber_Or(lv, rv);
  249. break;
  250. case BitXor:
  251. newval = PyNumber_Xor(lv, rv);
  252. break;
  253. case BitAnd:
  254. newval = PyNumber_And(lv, rv);
  255. break;
  256. // No builtin constants implement the following operators
  257. case MatMult:
  258. return 1;
  259. // No default case, so the compiler will emit a warning if new binary
  260. // operators are added without being handled here
  261. }
  262. return make_const(node, newval, arena);
  263. }
  264. static PyObject*
  265. make_const_tuple(asdl_expr_seq *elts)
  266. {
  267. for (int i = 0; i < asdl_seq_LEN(elts); i++) {
  268. expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
  269. if (e->kind != Constant_kind) {
  270. return NULL;
  271. }
  272. }
  273. PyObject *newval = PyTuple_New(asdl_seq_LEN(elts));
  274. if (newval == NULL) {
  275. return NULL;
  276. }
  277. for (int i = 0; i < asdl_seq_LEN(elts); i++) {
  278. expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
  279. PyObject *v = e->v.Constant.value;
  280. Py_INCREF(v);
  281. PyTuple_SET_ITEM(newval, i, v);
  282. }
  283. return newval;
  284. }
  285. static int
  286. fold_tuple(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
  287. {
  288. PyObject *newval;
  289. if (node->v.Tuple.ctx != Load)
  290. return 1;
  291. newval = make_const_tuple(node->v.Tuple.elts);
  292. return make_const(node, newval, arena);
  293. }
  294. static int
  295. fold_subscr(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
  296. {
  297. PyObject *newval;
  298. expr_ty arg, idx;
  299. arg = node->v.Subscript.value;
  300. idx = node->v.Subscript.slice;
  301. if (node->v.Subscript.ctx != Load ||
  302. arg->kind != Constant_kind ||
  303. idx->kind != Constant_kind)
  304. {
  305. return 1;
  306. }
  307. newval = PyObject_GetItem(arg->v.Constant.value, idx->v.Constant.value);
  308. return make_const(node, newval, arena);
  309. }
  310. /* Change literal list or set of constants into constant
  311. tuple or frozenset respectively. Change literal list of
  312. non-constants into tuple.
  313. Used for right operand of "in" and "not in" tests and for iterable
  314. in "for" loop and comprehensions.
  315. */
  316. static int
  317. fold_iter(expr_ty arg, PyArena *arena, _PyASTOptimizeState *state)
  318. {
  319. PyObject *newval;
  320. if (arg->kind == List_kind) {
  321. /* First change a list into tuple. */
  322. asdl_expr_seq *elts = arg->v.List.elts;
  323. Py_ssize_t n = asdl_seq_LEN(elts);
  324. for (Py_ssize_t i = 0; i < n; i++) {
  325. expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
  326. if (e->kind == Starred_kind) {
  327. return 1;
  328. }
  329. }
  330. expr_context_ty ctx = arg->v.List.ctx;
  331. arg->kind = Tuple_kind;
  332. arg->v.Tuple.elts = elts;
  333. arg->v.Tuple.ctx = ctx;
  334. /* Try to create a constant tuple. */
  335. newval = make_const_tuple(elts);
  336. }
  337. else if (arg->kind == Set_kind) {
  338. newval = make_const_tuple(arg->v.Set.elts);
  339. if (newval) {
  340. Py_SETREF(newval, PyFrozenSet_New(newval));
  341. }
  342. }
  343. else {
  344. return 1;
  345. }
  346. return make_const(arg, newval, arena);
  347. }
  348. static int
  349. fold_compare(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
  350. {
  351. asdl_int_seq *ops;
  352. asdl_expr_seq *args;
  353. Py_ssize_t i;
  354. ops = node->v.Compare.ops;
  355. args = node->v.Compare.comparators;
  356. /* TODO: optimize cases with literal arguments. */
  357. /* Change literal list or set in 'in' or 'not in' into
  358. tuple or frozenset respectively. */
  359. i = asdl_seq_LEN(ops) - 1;
  360. int op = asdl_seq_GET(ops, i);
  361. if (op == In || op == NotIn) {
  362. if (!fold_iter((expr_ty)asdl_seq_GET(args, i), arena, state)) {
  363. return 0;
  364. }
  365. }
  366. return 1;
  367. }
  368. static int astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  369. static int astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  370. static int astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  371. static int astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  372. static int astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  373. static int astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  374. static int astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  375. static int astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  376. static int astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  377. static int astfold_pattern(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
  378. #define CALL(FUNC, TYPE, ARG) \
  379. if (!FUNC((ARG), ctx_, state)) \
  380. return 0;
  381. #define CALL_OPT(FUNC, TYPE, ARG) \
  382. if ((ARG) != NULL && !FUNC((ARG), ctx_, state)) \
  383. return 0;
  384. #define CALL_SEQ(FUNC, TYPE, ARG) { \
  385. int i; \
  386. asdl_ ## TYPE ## _seq *seq = (ARG); /* avoid variable capture */ \
  387. for (i = 0; i < asdl_seq_LEN(seq); i++) { \
  388. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
  389. if (elt != NULL && !FUNC(elt, ctx_, state)) \
  390. return 0; \
  391. } \
  392. }
  393. #define CALL_INT_SEQ(FUNC, TYPE, ARG) { \
  394. int i; \
  395. asdl_int_seq *seq = (ARG); /* avoid variable capture */ \
  396. for (i = 0; i < asdl_seq_LEN(seq); i++) { \
  397. TYPE elt = (TYPE)asdl_seq_GET(seq, i); \
  398. if (!FUNC(elt, ctx_, state)) \
  399. return 0; \
  400. } \
  401. }
  402. static int
  403. astfold_body(asdl_stmt_seq *stmts, PyArena *ctx_, _PyASTOptimizeState *state)
  404. {
  405. int docstring = _PyAST_GetDocString(stmts) != NULL;
  406. CALL_SEQ(astfold_stmt, stmt, stmts);
  407. if (!docstring && _PyAST_GetDocString(stmts) != NULL) {
  408. stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
  409. asdl_expr_seq *values = _Py_asdl_expr_seq_new(1, ctx_);
  410. if (!values) {
  411. return 0;
  412. }
  413. asdl_seq_SET(values, 0, st->v.Expr.value);
  414. expr_ty expr = _PyAST_JoinedStr(values, st->lineno, st->col_offset,
  415. st->end_lineno, st->end_col_offset,
  416. ctx_);
  417. if (!expr) {
  418. return 0;
  419. }
  420. st->v.Expr.value = expr;
  421. }
  422. return 1;
  423. }
  424. static int
  425. astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  426. {
  427. switch (node_->kind) {
  428. case Module_kind:
  429. CALL(astfold_body, asdl_seq, node_->v.Module.body);
  430. break;
  431. case Interactive_kind:
  432. CALL_SEQ(astfold_stmt, stmt, node_->v.Interactive.body);
  433. break;
  434. case Expression_kind:
  435. CALL(astfold_expr, expr_ty, node_->v.Expression.body);
  436. break;
  437. // The following top level nodes don't participate in constant folding
  438. case FunctionType_kind:
  439. break;
  440. // No default case, so the compiler will emit a warning if new top level
  441. // compilation nodes are added without being handled here
  442. }
  443. return 1;
  444. }
  445. static int
  446. astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  447. {
  448. switch (node_->kind) {
  449. case BoolOp_kind:
  450. CALL_SEQ(astfold_expr, expr, node_->v.BoolOp.values);
  451. break;
  452. case BinOp_kind:
  453. CALL(astfold_expr, expr_ty, node_->v.BinOp.left);
  454. CALL(astfold_expr, expr_ty, node_->v.BinOp.right);
  455. CALL(fold_binop, expr_ty, node_);
  456. break;
  457. case UnaryOp_kind:
  458. CALL(astfold_expr, expr_ty, node_->v.UnaryOp.operand);
  459. CALL(fold_unaryop, expr_ty, node_);
  460. break;
  461. case Lambda_kind:
  462. CALL(astfold_arguments, arguments_ty, node_->v.Lambda.args);
  463. CALL(astfold_expr, expr_ty, node_->v.Lambda.body);
  464. break;
  465. case IfExp_kind:
  466. CALL(astfold_expr, expr_ty, node_->v.IfExp.test);
  467. CALL(astfold_expr, expr_ty, node_->v.IfExp.body);
  468. CALL(astfold_expr, expr_ty, node_->v.IfExp.orelse);
  469. break;
  470. case Dict_kind:
  471. CALL_SEQ(astfold_expr, expr, node_->v.Dict.keys);
  472. CALL_SEQ(astfold_expr, expr, node_->v.Dict.values);
  473. break;
  474. case Set_kind:
  475. CALL_SEQ(astfold_expr, expr, node_->v.Set.elts);
  476. break;
  477. case ListComp_kind:
  478. CALL(astfold_expr, expr_ty, node_->v.ListComp.elt);
  479. CALL_SEQ(astfold_comprehension, comprehension, node_->v.ListComp.generators);
  480. break;
  481. case SetComp_kind:
  482. CALL(astfold_expr, expr_ty, node_->v.SetComp.elt);
  483. CALL_SEQ(astfold_comprehension, comprehension, node_->v.SetComp.generators);
  484. break;
  485. case DictComp_kind:
  486. CALL(astfold_expr, expr_ty, node_->v.DictComp.key);
  487. CALL(astfold_expr, expr_ty, node_->v.DictComp.value);
  488. CALL_SEQ(astfold_comprehension, comprehension, node_->v.DictComp.generators);
  489. break;
  490. case GeneratorExp_kind:
  491. CALL(astfold_expr, expr_ty, node_->v.GeneratorExp.elt);
  492. CALL_SEQ(astfold_comprehension, comprehension, node_->v.GeneratorExp.generators);
  493. break;
  494. case Await_kind:
  495. CALL(astfold_expr, expr_ty, node_->v.Await.value);
  496. break;
  497. case Yield_kind:
  498. CALL_OPT(astfold_expr, expr_ty, node_->v.Yield.value);
  499. break;
  500. case YieldFrom_kind:
  501. CALL(astfold_expr, expr_ty, node_->v.YieldFrom.value);
  502. break;
  503. case Compare_kind:
  504. CALL(astfold_expr, expr_ty, node_->v.Compare.left);
  505. CALL_SEQ(astfold_expr, expr, node_->v.Compare.comparators);
  506. CALL(fold_compare, expr_ty, node_);
  507. break;
  508. case Call_kind:
  509. CALL(astfold_expr, expr_ty, node_->v.Call.func);
  510. CALL_SEQ(astfold_expr, expr, node_->v.Call.args);
  511. CALL_SEQ(astfold_keyword, keyword, node_->v.Call.keywords);
  512. break;
  513. case FormattedValue_kind:
  514. CALL(astfold_expr, expr_ty, node_->v.FormattedValue.value);
  515. CALL_OPT(astfold_expr, expr_ty, node_->v.FormattedValue.format_spec);
  516. break;
  517. case JoinedStr_kind:
  518. CALL_SEQ(astfold_expr, expr, node_->v.JoinedStr.values);
  519. break;
  520. case Attribute_kind:
  521. CALL(astfold_expr, expr_ty, node_->v.Attribute.value);
  522. break;
  523. case Subscript_kind:
  524. CALL(astfold_expr, expr_ty, node_->v.Subscript.value);
  525. CALL(astfold_expr, expr_ty, node_->v.Subscript.slice);
  526. CALL(fold_subscr, expr_ty, node_);
  527. break;
  528. case Starred_kind:
  529. CALL(astfold_expr, expr_ty, node_->v.Starred.value);
  530. break;
  531. case Slice_kind:
  532. CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.lower);
  533. CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.upper);
  534. CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.step);
  535. break;
  536. case List_kind:
  537. CALL_SEQ(astfold_expr, expr, node_->v.List.elts);
  538. break;
  539. case Tuple_kind:
  540. CALL_SEQ(astfold_expr, expr, node_->v.Tuple.elts);
  541. CALL(fold_tuple, expr_ty, node_);
  542. break;
  543. case Name_kind:
  544. if (node_->v.Name.ctx == Load &&
  545. _PyUnicode_EqualToASCIIString(node_->v.Name.id, "__debug__")) {
  546. return make_const(node_, PyBool_FromLong(!state->optimize), ctx_);
  547. }
  548. break;
  549. case NamedExpr_kind:
  550. CALL(astfold_expr, expr_ty, node_->v.NamedExpr.value);
  551. break;
  552. case Constant_kind:
  553. // Already a constant, nothing further to do
  554. break;
  555. case MatchAs_kind:
  556. case MatchOr_kind:
  557. // These can't occur outside of patterns.
  558. Py_UNREACHABLE();
  559. // No default case, so the compiler will emit a warning if new expression
  560. // kinds are added without being handled here
  561. }
  562. return 1;
  563. }
  564. static int
  565. astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  566. {
  567. CALL(astfold_expr, expr_ty, node_->value);
  568. return 1;
  569. }
  570. static int
  571. astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  572. {
  573. CALL(astfold_expr, expr_ty, node_->target);
  574. CALL(astfold_expr, expr_ty, node_->iter);
  575. CALL_SEQ(astfold_expr, expr, node_->ifs);
  576. CALL(fold_iter, expr_ty, node_->iter);
  577. return 1;
  578. }
  579. static int
  580. astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  581. {
  582. CALL_SEQ(astfold_expr, expr, node_->kw_defaults);
  583. CALL_SEQ(astfold_expr, expr, node_->defaults);
  584. return 1;
  585. }
  586. static int
  587. astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  588. {
  589. switch (node_->kind) {
  590. case FunctionDef_kind:
  591. CALL(astfold_arguments, arguments_ty, node_->v.FunctionDef.args);
  592. CALL(astfold_body, asdl_seq, node_->v.FunctionDef.body);
  593. CALL_SEQ(astfold_expr, expr, node_->v.FunctionDef.decorator_list);
  594. break;
  595. case AsyncFunctionDef_kind:
  596. CALL(astfold_arguments, arguments_ty, node_->v.AsyncFunctionDef.args);
  597. CALL(astfold_body, asdl_seq, node_->v.AsyncFunctionDef.body);
  598. CALL_SEQ(astfold_expr, expr, node_->v.AsyncFunctionDef.decorator_list);
  599. break;
  600. case ClassDef_kind:
  601. CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.bases);
  602. CALL_SEQ(astfold_keyword, keyword, node_->v.ClassDef.keywords);
  603. CALL(astfold_body, asdl_seq, node_->v.ClassDef.body);
  604. CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.decorator_list);
  605. break;
  606. case Return_kind:
  607. CALL_OPT(astfold_expr, expr_ty, node_->v.Return.value);
  608. break;
  609. case Delete_kind:
  610. CALL_SEQ(astfold_expr, expr, node_->v.Delete.targets);
  611. break;
  612. case Assign_kind:
  613. CALL_SEQ(astfold_expr, expr, node_->v.Assign.targets);
  614. CALL(astfold_expr, expr_ty, node_->v.Assign.value);
  615. break;
  616. case AugAssign_kind:
  617. CALL(astfold_expr, expr_ty, node_->v.AugAssign.target);
  618. CALL(astfold_expr, expr_ty, node_->v.AugAssign.value);
  619. break;
  620. case AnnAssign_kind:
  621. CALL(astfold_expr, expr_ty, node_->v.AnnAssign.target);
  622. CALL_OPT(astfold_expr, expr_ty, node_->v.AnnAssign.value);
  623. break;
  624. case For_kind:
  625. CALL(astfold_expr, expr_ty, node_->v.For.target);
  626. CALL(astfold_expr, expr_ty, node_->v.For.iter);
  627. CALL_SEQ(astfold_stmt, stmt, node_->v.For.body);
  628. CALL_SEQ(astfold_stmt, stmt, node_->v.For.orelse);
  629. CALL(fold_iter, expr_ty, node_->v.For.iter);
  630. break;
  631. case AsyncFor_kind:
  632. CALL(astfold_expr, expr_ty, node_->v.AsyncFor.target);
  633. CALL(astfold_expr, expr_ty, node_->v.AsyncFor.iter);
  634. CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.body);
  635. CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.orelse);
  636. break;
  637. case While_kind:
  638. CALL(astfold_expr, expr_ty, node_->v.While.test);
  639. CALL_SEQ(astfold_stmt, stmt, node_->v.While.body);
  640. CALL_SEQ(astfold_stmt, stmt, node_->v.While.orelse);
  641. break;
  642. case If_kind:
  643. CALL(astfold_expr, expr_ty, node_->v.If.test);
  644. CALL_SEQ(astfold_stmt, stmt, node_->v.If.body);
  645. CALL_SEQ(astfold_stmt, stmt, node_->v.If.orelse);
  646. break;
  647. case With_kind:
  648. CALL_SEQ(astfold_withitem, withitem, node_->v.With.items);
  649. CALL_SEQ(astfold_stmt, stmt, node_->v.With.body);
  650. break;
  651. case AsyncWith_kind:
  652. CALL_SEQ(astfold_withitem, withitem, node_->v.AsyncWith.items);
  653. CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncWith.body);
  654. break;
  655. case Raise_kind:
  656. CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.exc);
  657. CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.cause);
  658. break;
  659. case Try_kind:
  660. CALL_SEQ(astfold_stmt, stmt, node_->v.Try.body);
  661. CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.Try.handlers);
  662. CALL_SEQ(astfold_stmt, stmt, node_->v.Try.orelse);
  663. CALL_SEQ(astfold_stmt, stmt, node_->v.Try.finalbody);
  664. break;
  665. case Assert_kind:
  666. CALL(astfold_expr, expr_ty, node_->v.Assert.test);
  667. CALL_OPT(astfold_expr, expr_ty, node_->v.Assert.msg);
  668. break;
  669. case Expr_kind:
  670. CALL(astfold_expr, expr_ty, node_->v.Expr.value);
  671. break;
  672. case Match_kind:
  673. CALL(astfold_expr, expr_ty, node_->v.Match.subject);
  674. CALL_SEQ(astfold_match_case, match_case, node_->v.Match.cases);
  675. break;
  676. // The following statements don't contain any subexpressions to be folded
  677. case Import_kind:
  678. case ImportFrom_kind:
  679. case Global_kind:
  680. case Nonlocal_kind:
  681. case Pass_kind:
  682. case Break_kind:
  683. case Continue_kind:
  684. break;
  685. // No default case, so the compiler will emit a warning if new statement
  686. // kinds are added without being handled here
  687. }
  688. return 1;
  689. }
  690. static int
  691. astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  692. {
  693. switch (node_->kind) {
  694. case ExceptHandler_kind:
  695. CALL_OPT(astfold_expr, expr_ty, node_->v.ExceptHandler.type);
  696. CALL_SEQ(astfold_stmt, stmt, node_->v.ExceptHandler.body);
  697. break;
  698. // No default case, so the compiler will emit a warning if new handler
  699. // kinds are added without being handled here
  700. }
  701. return 1;
  702. }
  703. static int
  704. astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  705. {
  706. CALL(astfold_expr, expr_ty, node_->context_expr);
  707. CALL_OPT(astfold_expr, expr_ty, node_->optional_vars);
  708. return 1;
  709. }
  710. static int
  711. astfold_pattern_negative(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  712. {
  713. assert(node_->kind == UnaryOp_kind);
  714. assert(node_->v.UnaryOp.op == USub);
  715. assert(node_->v.UnaryOp.operand->kind == Constant_kind);
  716. PyObject *value = node_->v.UnaryOp.operand->v.Constant.value;
  717. assert(PyComplex_CheckExact(value) ||
  718. PyFloat_CheckExact(value) ||
  719. PyLong_CheckExact(value));
  720. PyObject *negated = PyNumber_Negative(value);
  721. if (negated == NULL) {
  722. return 0;
  723. }
  724. assert(PyComplex_CheckExact(negated) ||
  725. PyFloat_CheckExact(negated) ||
  726. PyLong_CheckExact(negated));
  727. return make_const(node_, negated, ctx_);
  728. }
  729. static int
  730. astfold_pattern_complex(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  731. {
  732. expr_ty left = node_->v.BinOp.left;
  733. expr_ty right = node_->v.BinOp.right;
  734. if (left->kind == UnaryOp_kind) {
  735. CALL(astfold_pattern_negative, expr_ty, left);
  736. }
  737. assert(left->kind = Constant_kind);
  738. assert(right->kind = Constant_kind);
  739. // LHS must be real, RHS must be imaginary:
  740. if (!(PyFloat_CheckExact(left->v.Constant.value) ||
  741. PyLong_CheckExact(left->v.Constant.value)) ||
  742. !PyComplex_CheckExact(right->v.Constant.value))
  743. {
  744. // Not actually valid, but it's the compiler's job to complain:
  745. return 1;
  746. }
  747. PyObject *new;
  748. if (node_->v.BinOp.op == Add) {
  749. new = PyNumber_Add(left->v.Constant.value, right->v.Constant.value);
  750. }
  751. else {
  752. assert(node_->v.BinOp.op == Sub);
  753. new = PyNumber_Subtract(left->v.Constant.value, right->v.Constant.value);
  754. }
  755. if (new == NULL) {
  756. return 0;
  757. }
  758. assert(PyComplex_CheckExact(new));
  759. return make_const(node_, new, ctx_);
  760. }
  761. static int
  762. astfold_pattern_keyword(keyword_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  763. {
  764. CALL(astfold_pattern, expr_ty, node_->value);
  765. return 1;
  766. }
  767. static int
  768. astfold_pattern(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  769. {
  770. // Don't blindly optimize the pattern as an expr; it plays by its own rules!
  771. // Currently, this is only used to form complex/negative numeric constants.
  772. switch (node_->kind) {
  773. case Attribute_kind:
  774. break;
  775. case BinOp_kind:
  776. CALL(astfold_pattern_complex, expr_ty, node_);
  777. break;
  778. case Call_kind:
  779. CALL_SEQ(astfold_pattern, expr, node_->v.Call.args);
  780. CALL_SEQ(astfold_pattern_keyword, keyword, node_->v.Call.keywords);
  781. break;
  782. case Constant_kind:
  783. break;
  784. case Dict_kind:
  785. CALL_SEQ(astfold_pattern, expr, node_->v.Dict.keys);
  786. CALL_SEQ(astfold_pattern, expr, node_->v.Dict.values);
  787. break;
  788. // Not actually valid, but it's the compiler's job to complain:
  789. case JoinedStr_kind:
  790. break;
  791. case List_kind:
  792. CALL_SEQ(astfold_pattern, expr, node_->v.List.elts);
  793. break;
  794. case MatchAs_kind:
  795. CALL(astfold_pattern, expr_ty, node_->v.MatchAs.pattern);
  796. break;
  797. case MatchOr_kind:
  798. CALL_SEQ(astfold_pattern, expr, node_->v.MatchOr.patterns);
  799. break;
  800. case Name_kind:
  801. break;
  802. case Starred_kind:
  803. CALL(astfold_pattern, expr_ty, node_->v.Starred.value);
  804. break;
  805. case Tuple_kind:
  806. CALL_SEQ(astfold_pattern, expr, node_->v.Tuple.elts);
  807. break;
  808. case UnaryOp_kind:
  809. CALL(astfold_pattern_negative, expr_ty, node_);
  810. break;
  811. default:
  812. Py_UNREACHABLE();
  813. }
  814. return 1;
  815. }
  816. static int
  817. astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTOptimizeState *state)
  818. {
  819. CALL(astfold_pattern, expr_ty, node_->pattern);
  820. CALL_OPT(astfold_expr, expr_ty, node_->guard);
  821. CALL_SEQ(astfold_stmt, stmt, node_->body);
  822. return 1;
  823. }
  824. #undef CALL
  825. #undef CALL_OPT
  826. #undef CALL_SEQ
  827. #undef CALL_INT_SEQ
  828. int
  829. _PyAST_Optimize(mod_ty mod, PyArena *arena, _PyASTOptimizeState *state)
  830. {
  831. int ret = astfold_mod(mod, arena, state);
  832. assert(ret || PyErr_Occurred());
  833. return ret;
  834. }