A constant-folding rewrite engine is only correct if it computes exactly what the generated C code would. Implement evaluate(expr, params=()) for elementwise programs with the course's exact value semantics.
Expressions are nested tuples:
("const", value, dtype) and ("param", slot), where params[slot] is a pair (value, dtype).("add" | "mul" | "max" | "xor" | "cmplt" | "shl" | "div" | "mod", a, b).("where", c, a, b), ("cast", x, dtype), ("recip", x) and ("trunc", x).int, float or bool literal. A literal next to a typed operand takes that operand's dtype (dtype broadcasting); on its own an int is i32, a float is f32 and a bool is bool.Dtypes are "i32", "f32" and "bool". Return a pair (value, dtype) with an int in for i32, a Python float exactly representable in binary32 for f32, and True or False for bool.
Semantics
i32: add, mul and shl wrap modulo (two's complement). shl needs a shift in , otherwise raise ValueError.div and mod are i32 only and use floor division and floor modulo, so mod has the sign of the divisor. The quotient wraps too. Division by zero raises ZeroDivisionError.f32: every operation rounds to the nearest binary32 value; a param or literal is rounded to binary32 when it is read. recip is and trunc rounds toward zero; both are f32 only. max with a NaN operand is NaN.xor is bitwise on i32 and logical on bool; max on bool is logical or. cmplt returns bool, and where needs a bool condition.cast: i32 to f32 rounds to nearest. f32 to i32 truncates toward zero (NaN or out of range raises ValueError). bool to a number gives 0 or 1, and a number to bool is value != 0.TypeError, as do shl/div/mod on non-i32 operands and recip/trunc on non-f32 ones.