Move conditional logic to eval_expr, add _conver_to_bool, add passing bool test

This commit is contained in:
Pragyansh Chaturvedi
2025-10-07 03:11:23 +05:30
parent 4f433d00cc
commit fb63dbd698
3 changed files with 63 additions and 3 deletions

View File

@ -131,9 +131,35 @@ def _handle_ctypes_call(
return val
def _handle_comparator(builder, op, lhs, rhs):
"""Handle comparison operations."""
# NOTE: For now assume same types
comparison_ops = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
}
if type(op) not in comparison_ops:
logger.error(f"Unsupported comparison operator: {type(op)}")
return None
predicate = comparison_ops[type(op)]
result = builder.icmp_signed(predicate, lhs, rhs)
logger.debug(f"Comparison result: {result}")
return result, ir.IntType(1)
def _handle_compare(
func, module, builder, cond, local_sym_tab, map_sym_tab, structs_sym_tab=None
):
"""Handle ast.Compare expressions."""
if len(cond.ops) != 1 or len(cond.comparators) != 1:
logger.error("Only single comparisons are supported")
return None
@ -162,7 +188,7 @@ def _handle_compare(
lhs, _ = lhs
rhs, _ = rhs
return None
return _handle_comparator(builder, cond.ops[0], lhs, rhs)
def eval_expr(

View File

@ -240,12 +240,25 @@ def handle_assign(
logger.info("Unsupported assignment value type")
def _convert_to_bool(builder, val):
if val.type == ir.IntType(1):
return val
if isinstance(val.type, ir.PointerType):
zero = ir.Constant(val.type, None)
else:
zero = ir.Constant(val.type, 0)
return builder.icmp_signed("!=", val, zero)
def handle_cond(func, module, builder, cond, local_sym_tab, map_sym_tab):
if True:
val = eval_expr(func, module, builder, cond, local_sym_tab, map_sym_tab)[0]
return _convert_to_bool(builder, val)
if isinstance(cond, ast.Constant):
if isinstance(cond.value, bool) or isinstance(cond.value, int):
return ir.Constant(ir.IntType(1), int(bool(cond.value)))
return ir.Constant(ir.IntType(1), int(cond.value))
else:
logger.info("Unsupported constant type in condition")
raise ValueError("Unsupported constant type in condition")
return None
elif isinstance(cond, ast.Name):
if cond.id in local_sym_tab: