From a230b440b9589935b26b87eca2a971afe1643f83 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Thu, 24 Sep 2026 16:52:59 +0530 Subject: [PATCH] Core: Give bools C's rules: widen to 0 or 1, narrow by comparing with zero A bool is ir.IntType(1), so convert() handled it as a 1-bit integer: a bool slot's plain descriptor read as signed and True sign-extended to -1 on the way out, and an integer narrowed to a bool by truncation, so 2 became false. Both predate this branch. C widens a bool to 0 or 1 and narrows to it with != 0, and Python's truthiness agrees on the second. signedness() now answers unsigned for any 1-bit integer whatever it is wrapped in, convert() narrows to width 1 with icmp ne 0, and a bool constant's slot carries the unsigned descriptor like the comparison results already do. Co-Authored-By: Claude Fable 5.1 --- pythonbpf/allocation_pass.py | 2 +- pythonbpf/expr/type_normalization.py | 4 ++++ pythonbpf/type_deducer.py | 5 +++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/pythonbpf/allocation_pass.py b/pythonbpf/allocation_pass.py index 8118620..aaf2539 100644 --- a/pythonbpf/allocation_pass.py +++ b/pythonbpf/allocation_pass.py @@ -263,7 +263,7 @@ def _allocate_for_constant(builder, var_name, rval, local_sym_tab): """Allocate memory for variable assigned from a constant.""" if isinstance(rval.value, bool): - ir_type = ir.IntType(1) + ir_type = IntTy(1, False) # a bool widens to 0 or 1, never sign-extends var = builder.alloca(ir_type, name=var_name) var.align = 1 local_sym_tab[var_name] = LocalSymbol(var, ir_type) diff --git a/pythonbpf/expr/type_normalization.py b/pythonbpf/expr/type_normalization.py index 9687e54..e89815f 100644 --- a/pythonbpf/expr/type_normalization.py +++ b/pythonbpf/expr/type_normalization.py @@ -60,6 +60,10 @@ def convert(builder, val, from_ty, to_ty): f"integer conversion requested for a {val.type} value to {to_ty}" ) if val.type.width > to_ty.width: + if to_ty.width == 1: + # C's rule for bool: nonzero is true. Truncation would keep the + # low bit and turn 2 into false. + return builder.icmp_unsigned("!=", val, ir.Constant(val.type, 0)) return builder.trunc(val, to_ty) if val.type.width < to_ty.width: ext = builder.zext if not signedness(from_ty) else builder.sext diff --git a/pythonbpf/type_deducer.py b/pythonbpf/type_deducer.py index 0987eab..1ec4027 100644 --- a/pythonbpf/type_deducer.py +++ b/pythonbpf/type_deducer.py @@ -50,6 +50,11 @@ def int_literal_type(value: int) -> IntTy: def signedness(ty) -> bool: + """Sign of a descriptor: an IntTy says; a vmlinux Field says through its + ctype; a 1-bit integer is a bool and never negative, whatever it is + wrapped in; anything else is signed, the pre-signedness default.""" + if isinstance(ty, ir.IntType) and ty.width == 1: + return False """Sign of an integer type descriptor. IntTy carries it directly. A vmlinux Field carries a ctypes class in .type,