mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 01:48:35 +00:00
Core: Reject a struct value as a condition with a clear error
`if dat:` on a local struct built Constant(struct_type, 0) in convert_to_bool, and llvmlite failed later, while printing the module, with "'int' object is not iterable". A struct has no truth value (C rejects `if (s)`; Python would call any object true), so it is now a TypeError that says to test a field. A pointer to a struct is unaffected. The xfail was named struct_ptr but tests a struct value; it is renamed to struct_value.py and becomes a negative test. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@ -113,6 +113,14 @@ def convert_to_bool(builder, val):
|
||||
"""Convert a value to boolean."""
|
||||
if val.type == ir.IntType(1):
|
||||
return val
|
||||
if not isinstance(val.type, (ir.IntType, ir.PointerType)):
|
||||
# C rejects `if (s)` on a struct, and Python would call any object
|
||||
# true; either way it is never what was meant.
|
||||
kind = "struct" if isinstance(val.type, ir.BaseStructType) else "value"
|
||||
raise TypeError(
|
||||
f"a {kind} of type {val.type} has no truth value: test one of its "
|
||||
"fields instead"
|
||||
)
|
||||
if isinstance(val.type, ir.PointerType):
|
||||
zero = ir.Constant(val.type, None)
|
||||
else:
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
from pythonbpf import bpf, struct, section, bpfglobal, compile
|
||||
from ctypes import c_void_p, c_int64, c_uint64
|
||||
|
||||
# NOTE: Decided against fixing this
|
||||
# as one workaround is to just check any field of the struct
|
||||
# in the if statement. Ugly but works.
|
||||
# Might fix in future.
|
||||
# Negative test: `dat` is a struct value, and a struct has no truth value
|
||||
# (C rejects `if (s)`; Python would call any object true). It is a compile
|
||||
# error that says to test one of the struct's fields instead. A *pointer* to
|
||||
# a struct, such as a map lookup result, is a valid condition (non-null).
|
||||
|
||||
|
||||
@bpf
|
||||
@ -15,7 +15,7 @@
|
||||
|
||||
[xfail]
|
||||
|
||||
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
|
||||
"failing_tests/conditionals/struct_value.py" = {reason = "A struct value has no truth value (C rejects `if (s)`): a compile error naming the struct", level = "ir"}
|
||||
|
||||
"failing_tests/return_struct.py" = {reason = "Returning a struct value from an integer function is a type error (nothing to dereference to an integer)", level = "ir"}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user