Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mypyc/analysis/ircheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ def can_coerce_to(src: RType, dest: RType) -> bool:
if isinstance(src, (RInstance, RVec)):
return is_object_rprimitive(dest)
if isinstance(src, RUnion):
if is_object_rprimitive(dest):
# Unions are boxed, even if some of their items are unboxed.
return True
# IR doesn't have the ability to narrow unions based on
# control flow, so cannot be a strict all() here.
return any(can_coerce_to(s, dest) for s in src.items)
Expand Down
34 changes: 15 additions & 19 deletions mypyc/irbuild/ll_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2239,13 +2239,15 @@ def unary_not(self, value: Value, line: int, *, likely_bool: bool = False) -> Va
or is_list_rprimitive(typ)
or is_tuple_rprimitive(typ)
or is_dict_rprimitive(typ)
or isinstance(typ, RInstance)
or isinstance(typ, (RInstance, RTuple))
):
bool_val = self.bool_value(value)
return self.unary_not(bool_val, line)
if is_optional_type(typ):
value_typ = optional_value_type(typ)
assert value_typ
if isinstance(value_typ, RTuple) and value_typ.types:
return self.add(ComparisonOp(value, self.none_object(), ComparisonOp.EQ, line))
if (
is_str_rprimitive(value_typ)
or is_list_rprimitive(value_typ)
Expand Down Expand Up @@ -2490,6 +2492,8 @@ def bool_value(self, value: Value) -> Value:
elif is_fixed_width_rtype(value.type):
zero = Integer(0, value.type)
result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ))
elif isinstance(value.type, RTuple):
result = self.true() if value.type.types else self.false()
elif is_str_rprimitive(value.type):
result = self.call_c(str_check_if_true, [value], value.line)
elif (
Expand All @@ -2513,15 +2517,7 @@ def bool_value(self, value: Value) -> Value:
value_type = optional_value_type(value.type)
if value_type is not None:
not_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
always_truthy = False
if isinstance(value_type, RInstance):
# check whether X.__bool__ is always just the default (object.__bool__)
if not value_type.class_ir.has_method(
"__bool__"
) and value_type.class_ir.is_method_final("__bool__"):
always_truthy = True

if always_truthy:
if self.is_always_truthy(value_type):
result = not_none
else:
# "X | None" where X may be falsey and requires a check
Expand All @@ -2544,6 +2540,14 @@ def bool_value(self, value: Value) -> Value:
result = self.primitive_op(bool_op, [value], value.line)
return result

def is_always_truthy(self, typ: RType) -> bool:
if isinstance(typ, RInstance):
return not typ.class_ir.has_method("__bool__") and typ.class_ir.is_method_final(
"__bool__"
)
# Fixed-length tuples ignore subclass truthiness overrides, even when boxed.
return isinstance(typ, RTuple) and len(typ.types) > 0

def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
opt_value_type = optional_value_type(value.type)
if opt_value_type is None:
Expand All @@ -2554,15 +2558,7 @@ def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) ->
is_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
branch = Branch(is_none, true, false, Branch.BOOL, value.line)
self.add(branch)
always_truthy = False
if isinstance(opt_value_type, RInstance):
# check whether X.__bool__ is always just the default (object.__bool__)
if not opt_value_type.class_ir.has_method(
"__bool__"
) and opt_value_type.class_ir.is_method_final("__bool__"):
always_truthy = True

if not always_truthy:
if not self.is_always_truthy(opt_value_type):
# Optional[X] where X may be falsey and requires a check
branch.true = BasicBlock()
self.activate_block(branch.true)
Expand Down
59 changes: 59 additions & 0 deletions mypyc/test-data/irbuild-tuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -1332,3 +1332,62 @@ L3:
r19 = r20
L4:
return r19

[case testFixedLengthTupleTruthiness]
def nonempty_bool(t: tuple[int, int]) -> bool:
return bool(t)
def empty_bool(t: tuple[()]) -> bool:
return bool(t)
def nonempty_not(t: tuple[int, int]) -> bool:
return not t
def optional_if(t: tuple[int, int] | None) -> bool:
if t:
return True
return False
def optional_bool(t: tuple[int, int] | None) -> bool:
return bool(t)
def optional_not(t: tuple[int, int] | None) -> bool:
return not t
[out]
def nonempty_bool(t):
t :: tuple[int, int]
L0:
return 1
def empty_bool(t):
t :: tuple[]
L0:
return 0
def nonempty_not(t):
t :: tuple[int, int]
r0 :: bool
L0:
r0 = 1 ^ 1
return r0
def optional_if(t):
t :: union[tuple[int, int], None]
r0 :: object
r1 :: bit
L0:
r0 = load_address _Py_NoneStruct
r1 = t != r0
if r1 goto L1 else goto L2 :: bool
L1:
return 1
L2:
return 0
def optional_bool(t):
t :: union[tuple[int, int], None]
r0 :: object
r1 :: bit
L0:
r0 = load_address _Py_NoneStruct
r1 = t != r0
return r1
def optional_not(t):
t :: union[tuple[int, int], None]
r0 :: object
r1 :: bit
L0:
r0 = load_address _Py_NoneStruct
r1 = t == r0
return r1
151 changes: 151 additions & 0 deletions mypyc/test-data/run-tuples.test
Original file line number Diff line number Diff line change
Expand Up @@ -783,3 +783,154 @@ class TupleNeOverride(tuple[Any, ...]):
class NT(NamedTuple):
x: int
y: int

[case testFixedLengthTupleTruthiness]
calls: list[int] = []

def make_tuple(n: int) -> tuple[int, int]:
calls.append(n)
return n, n + 1

def mark(n: int) -> int:
calls.append(n)
return n

def nonempty_bool(t: tuple[int, int]) -> bool:
return bool(t)

def nonempty_if(t: tuple[int, int]) -> int:
if t:
return 1
return 2

def nonempty_not(t: tuple[int, int]) -> bool:
return not t

def empty_bool(t: tuple[()]) -> bool:
return bool(t)

def empty_if(t: tuple[()]) -> int:
if t:
return 1
return 2

def empty_not(t: tuple[()]) -> bool:
return not t

def empty_or(t: tuple[()]) -> tuple[int, int]:
return t or make_tuple(7)

def optional_bool(t: tuple[int, int] | None) -> bool:
return bool(t)

def optional_if(t: tuple[int, int] | None) -> int:
if t:
return t[0]
return -1

def optional_not(t: tuple[int, int] | None) -> bool:
return not t

def optional_or(t: tuple[int, int] | None) -> tuple[int, int]:
return t or make_tuple(7)

def optional_and(t: tuple[int, int] | None, x: int) -> tuple[int, int] | int | None:
return t and mark(x)

def optional_empty_bool(t: tuple[()] | None) -> bool:
return bool(t)

def optional_empty_not(t: tuple[()] | None) -> bool:
return not t

def union_bool(t: tuple[int] | list[int]) -> bool:
return bool(t)

def union_not(t: tuple[int] | list[int]) -> bool:
return not t

def side_effects() -> tuple[bool, bool]:
a = bool(make_tuple(1))
b = not make_tuple(2)
if make_tuple(3):
pass
return a, b

def test_nonempty() -> None:
assert nonempty_bool((0, 0)) is True
assert nonempty_if((0, 0)) == 1
assert nonempty_not((0, 0)) is False

def test_empty() -> None:
assert empty_bool(()) is False
assert empty_if(()) == 2
assert empty_not(()) is True

def test_optional() -> None:
assert optional_bool(None) is False
assert optional_bool((0, 0)) is True
assert optional_if(None) == -1
assert optional_if((5, 6)) == 5
assert optional_not(None) is True
assert optional_not((0, 0)) is False
assert optional_empty_bool(None) is False
assert optional_empty_bool(()) is False
assert optional_empty_not(None) is True
assert optional_empty_not(()) is True

def test_short_circuiting() -> None:
calls.clear()
assert empty_or(()) == (7, 8)
assert optional_or(None) == (7, 8)
assert optional_or((1, 2)) == (1, 2)
assert optional_and(None, 3) is None
assert optional_and((1, 2), 3) == 3
assert calls == [7, 7, 3]

def test_union_with_list() -> None:
assert union_bool((0,)) is True
assert union_bool([]) is False
assert union_bool([0]) is True
assert union_not([]) is True
assert union_not([0]) is False
assert union_not((1,)) is False

def test_side_effects() -> None:
calls.clear()
assert side_effects() == (True, False)
assert calls == [1, 2, 3]

[case testFixedLengthTupleSubclassTruthiness]
def plain(t: tuple[int, int]) -> tuple[bool, bool, bool]:
if t:
branch = True
else:
branch = False
return bool(t), branch, not t

def optional(t: tuple[int, int] | None) -> tuple[bool, bool, bool]:
if t:
branch = True
else:
branch = False
return bool(t), branch, not t

[file driver.py]
from native import plain, optional

class FalsyTuple(tuple):
def __bool__(self):
return False

class LenZeroTuple(tuple):
def __len__(self):
return 0

# Fixed-length tuple value semantics ignore subclass truthiness overrides.
for cls in (FalsyTuple, LenZeroTuple):
value = cls((0, 0))
assert bool(value) is False
assert plain(value) == (True, True, False)
assert optional(value) == (True, True, False)

assert optional(None) == (False, False, True)
4 changes: 4 additions & 0 deletions mypyc/test/test_ircheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from mypyc.ir.pprint import format_func
from mypyc.ir.rtypes import (
RInstance,
RTuple,
RType,
RUnion,
bytes_rprimitive,
Expand Down Expand Up @@ -143,12 +144,15 @@ def test_can_coerce_to(self) -> None:
(RUnion([bytes_rprimitive, str_rprimitive]), str_rprimitive),
(str_rprimitive, RUnion([bytes_rprimitive, str_rprimitive])),
(RInstance(cls), object_rprimitive),
(RUnion([RTuple([str_rprimitive]), none_rprimitive]), object_rprimitive),
(RUnion([RTuple([]), RTuple([str_rprimitive])]), object_rprimitive),
]

invalid_cases = [
(int64_rprimitive, int32_rprimitive),
(RInstance(cls), str_rprimitive),
(str_rprimitive, bytes_rprimitive),
(RTuple([str_rprimitive]), object_rprimitive),
]

for src, dest in valid_cases:
Expand Down
Loading