Skip to content

Commit 10c9634

Browse files
DinoVfacebook-github-bot
authored andcommitted
Do constant folding for match variables
Summary: With the removal of the constant folding pass match variables are no longer working when they're in the form `-1` or `1 + 3j`. This adds them back in so patterns work. Reviewed By: jbower-fb Differential Revision: D81961225 fbshipit-source-id: c843e571a68ad8218d61048f299363a9d59ee4fb
1 parent 4fdeb4b commit 10c9634

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

cinderx/PythonLib/cinderx/compiler/optimizer.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,28 @@ def visitBinOp(self, node: ast.BinOp) -> ast.expr:
509509

510510
return self.update_node(node, left=lhs, right=rhs)
511511

512+
def visitMatchValue(self, node: ast.MatchValue) -> ast.MatchValue:
513+
return self.update_node(node, value=self.fold_const_match_patterns(node.value))
514+
515+
def visitMatchMapping(self, node: ast.MatchMapping) -> ast.MatchMapping:
516+
keys = [self.fold_const_match_patterns(key) for key in node.keys]
517+
patterns = self.walk_list(node.patterns)
518+
return self.update_node(node, keys=keys, patterns=patterns)
519+
520+
def fold_const_match_patterns(self, node: ast.expr) -> ast.expr:
521+
if isinstance(node, ast.UnaryOp):
522+
if isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Constant):
523+
return super().visitUnaryOp(node)
524+
elif isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
525+
if isinstance(node.right, ast.Constant):
526+
node = self.update_node(
527+
node, left=self.fold_const_match_patterns(node.left)
528+
)
529+
if isinstance(node.left, ast.Constant):
530+
return super().visitBinOp(node)
531+
532+
return node
533+
512534
def visitTuple(self, node: ast.Tuple) -> ast.expr:
513535
elts = self.walk_list(node.elts)
514536

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
match x:
2+
case 0 + 0j:
3+
y = 0
4+
5+
match x:
6+
case -1:
7+
y = 0

0 commit comments

Comments
 (0)