From 3084751de01d961bff034df40caa2968be91d7c5 Mon Sep 17 00:00:00 2001 From: "Davide Gessa (dakk)" Date: Sat, 28 Oct 2023 15:27:35 +0200 Subject: [PATCH] multi-assign tuple unrolling --- qlasskit/ast2ast.py | 22 ++++++++++++++++++++++ test/test_qlassf_tuple.py | 15 +++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/qlasskit/ast2ast.py b/qlasskit/ast2ast.py index c652f5b8..96eb6288 100644 --- a/qlasskit/ast2ast.py +++ b/qlasskit/ast2ast.py @@ -67,6 +67,28 @@ def visit_FunctionDef(self, node): return super().generic_visit(node) def visit_Assign(self, node): + # Transform multi-target assign to single target assigns + if len(node.targets) == 1 and hasattr(node.targets[0], "elts"): + _temptup = self.visit( + ast.Assign(targets=[ast.Name(id="_temptup")], value=node.value) + ) + + single_assigns = [ + self.visit( + ast.Assign( + targets=[ast.Name(id=node.targets[0].elts[i].id)], + value=ast.Subscript( + value=ast.Name(id="_temptup"), + slice=ast.Index( + value=ast.Constant(value=i), ctx=ast.Load() + ), + ), + ) + ) + for i in range(len(node.targets[0].elts)) + ] + return [_temptup] + single_assigns + was_known = node.targets[0].id in self.env if isinstance(node.value, ast.Name) and node.value.id in self.env: diff --git a/test/test_qlassf_tuple.py b/test/test_qlassf_tuple.py index e1209a73..79724813 100644 --- a/test/test_qlassf_tuple.py +++ b/test/test_qlassf_tuple.py @@ -123,6 +123,21 @@ def test_tuple_assign3(self): ) compute_and_compare_results(self, qf) + def test_multi_assign(self): + f = "def test(a: bool) -> bool:\n\tc, d = a, not a\n\treturn c and d" + qf = qlassf(f, to_compile=COMPILATION_ENABLED) + compute_and_compare_results(self, qf) + + def test_multi_assign2(self): + f = "def test() -> Qint4:\n\tc, d = 1, 2\n\treturn c+d" + qf = qlassf(f, to_compile=COMPILATION_ENABLED) + compute_and_compare_results(self, qf) + + def test_multi_assign3(self): + f = "def test() -> Qint4:\n\tc, d, e = 1, 2, 0xa\n\treturn c+d+e" + qf = qlassf(f, to_compile=COMPILATION_ENABLED) + compute_and_compare_results(self, qf) + def test_tuple_result(self): f = "def test(a: bool, b: bool) -> Tuple[bool,bool]:\n\treturn a,b" qf = qlassf(f, to_compile=COMPILATION_ENABLED)