Skip to content
This repository was archived by the owner on Mar 2, 2022. It is now read-only.

Commit 9851616

Browse files
committed
Tuple to constant folding
Summary: This implements an optimization that replaces [LOAD_CONST ...] BUILD_TUPLE with a simple LOAD_CONST with the actual tuple object burned in. Again we just produce a new Constant AST node whose value is the tuple object. Test Plan: ./python -m test.test_compiler
1 parent d5eec06 commit 9851616

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

compiler/optimizer.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import ast
22
import operator
33
from ast import Constant, Num, Str, Bytes, Ellipsis, NameConstant, copy_location
4+
from typing import Iterable, Optional
45
from compiler.peephole import safe_multiply, safe_power, safe_mod, safe_lshift
56
from compiler.visitor import ASTRewriter
67

@@ -95,3 +96,19 @@ def visitBinOp(self, node: ast.BinOp) -> ast.expr:
9596
pass
9697

9798
return self.update_node(node, left=l, right=r)
99+
100+
def makeConstTuple(self, elts: Iterable[ast.expr]) -> Optional[Constant]:
101+
if all(is_const(elt) for elt in elts):
102+
return Constant(tuple(get_const_value(elt) for elt in elts))
103+
104+
return None
105+
106+
def visitTuple(self, node: ast.Tuple) -> ast.expr:
107+
elts = self.walk_list(node.elts)
108+
109+
if isinstance(node.ctx, ast.Load):
110+
res = self.makeConstTuple(elts)
111+
if res is not None:
112+
return copy_location(res, node)
113+
114+
return self.update_node(node, elts=elts)

test_compiler/test_py37.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,9 @@ def test_ast_optimizer(self):
188188
("1 + None", "1 + None"),
189189
("True + None", "True + None"),
190190
("True + 1", "2"),
191+
("(1, 2)", "(1, 2)"),
192+
("(1, 2) * 2", "(1, 2, 1, 2)"),
193+
("(1, --2, abc)", "(1, 2, abc)"),
191194
]
192195
for inp, expected in cases:
193196
optimizer = AstOptimizer()

0 commit comments

Comments
 (0)