From b8cd163978161acca16ea29bdb8b49e0b2d0bc6d Mon Sep 17 00:00:00 2001 From: David Nadlinger Date: Sat, 20 Mar 2021 00:27:25 +0000 Subject: [PATCH] compiler: Fix type inference for "ternary" if expressions Previously, any type would be accepted for the test expression, leading to internal errors in the code generator if the passed value wasn't in fact a bool. --- artiq/compiler/transforms/inferencer.py | 1 + artiq/test/lit/inferencer/if_expr.py | 6 ++++++ 2 files changed, 7 insertions(+) create mode 100644 artiq/test/lit/inferencer/if_expr.py diff --git a/artiq/compiler/transforms/inferencer.py b/artiq/compiler/transforms/inferencer.py index f72f01127..7d6d065b7 100644 --- a/artiq/compiler/transforms/inferencer.py +++ b/artiq/compiler/transforms/inferencer.py @@ -305,6 +305,7 @@ class Inferencer(algorithm.Visitor): def visit_IfExpT(self, node): self.generic_visit(node) + self._unify(node.test.type, builtins.TBool(), node.test.loc, None) self._unify(node.body.type, node.orelse.type, node.body.loc, node.orelse.loc) self._unify(node.type, node.body.type, diff --git a/artiq/test/lit/inferencer/if_expr.py b/artiq/test/lit/inferencer/if_expr.py new file mode 100644 index 000000000..d955bc736 --- /dev/null +++ b/artiq/test/lit/inferencer/if_expr.py @@ -0,0 +1,6 @@ +# RUN: %python -m artiq.compiler.testbench.inferencer %s >%t +# RUN: OutputCheck %s --file-to-check=%t + +# CHECK-L: def foo(val:bool)->numpy.int?: +def foo(val): + return 1 if val else 0