Skip to content

Commit d39aa82

Browse files
add to mypyc constant folding
1 parent 606930b commit d39aa82

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

mypyc/irbuild/constant_fold.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,26 @@ def constant_fold_expr(builder: IRBuilder, expr: Expression) -> ConstantValue |
7272
value = constant_fold_expr(builder, expr.expr)
7373
if value is not None and not isinstance(value, bytes):
7474
return constant_fold_unary_op(expr.op, value)
75+
# we can also constant fold some common methods of builtin types
76+
elif isinstance(expr, CallExpr) and isinstance(callee := expr.callee, MemberExpr):
77+
folded_callee = constant_fold_expr(builder, callee.expr)
78+
79+
# builtins.str methods
80+
if isinstance(folded_callee, str):
81+
` # str.join
82+
if (
83+
callee.name == "join"
84+
and len(args := expr.args) == 1
85+
# TODO extend this to work with rtuples comprised of known literal values
86+
and isinstance(arg := args[0], (ListExpr, TupleExpr))
87+
):
88+
folded_items = []
89+
for item in arg.items:
90+
val = constant_fold_expr(builder, item)
91+
if not isinstance(val, str):
92+
return None
93+
folded_items.append(val)
94+
return folded_callee.join(folded_items)
7595
return None
7696

7797

0 commit comments

Comments
 (0)