diff --git a/core/operators.nom b/core/operators.nom index a44f06b..fbb8325 100644 --- a/core/operators.nom +++ b/core/operators.nom @@ -240,26 +240,54 @@ test: compile [%x and %y] to (Lua value "(\(%x as lua expr) and \(%y as lua expr))") compile [%x or %y] to (Lua value "(\(%x as lua expr) or \(%y as lua expr))") +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # Bitwise Operators -# TODO: support bit.???() for luajit and bit32.??? for lua 5.2 +# TODO: implement OR, XOR, AND for multiple operands? +test: + assume ((1 | 4) == 5) + assume ((1 ~ 3) == 2) + assume ((1 & 3) == 1) + assume ((1 << 2) == 4) + assume ((4 >> 2) == 1) + +# Lua 5.3 introduced bit operators like | and &. Use them when possible, otherwise + fall back to bit.bor(), bit.band(), etc. +%use_bitops = ((is jit) or ((Lua version) == "Lua 5.2")) +compile [NOT %, ~ %] to (..) + Lua value (..) + (%use_bitops and "bit.bnot(\(% as lua expr))") or "~(\(% as lua expr))" + compile [%a OR %b, %a | %b] to (..) - Lua value "(\(%a as lua expr) | \(%b as lua expr))" + Lua value (..) + (%use_bitops and "bit.bor(\(%a as lua expr), \(%b as lua expr))") or ".." + (\(%a as lua expr) | \(%b as lua expr)) + +compile [%a XOR %b, %a ~ %b] to (..) + Lua value (..) + (%use_bitops and "bit.bxor(\(%a as lua expr), \(%b as lua expr))") or ".." + (\(%a as lua expr) ~ \(%b as lua expr)) -compile [%a XOR %b] to (Lua value "(\(%a as lua expr) ^ \(%b as lua expr))") compile [%a AND %b, %a & %b] to (..) - Lua value "(\(%a as lua expr) & \(%b as lua expr))" + Lua value (..) + (%use_bitops and "bit.band(\(%a as lua expr), \(%b as lua expr))") or ".." + (\(%a as lua expr) & \(%b as lua expr)) -compile [NOT %, ~ %] to (Lua value "~(\(% as lua expr))") compile [%x LSHIFT %shift, %x << %shift] to (..) - Lua value "(\(%x as lua expr) << \(%shift as lua expr))" + Lua value (..) + (%use_bitops and "bit.lshift(\(%x as lua expr), \(%shift as lua expr))") or ".." + (\(%x as lua expr) << \(%shift as lua expr)) compile [%x RSHIFT %shift, %x >>> %shift] to (..) - Lua value "(\(%x as lua expr) >>> \(%shift as lua expr))" + Lua value (..) + (%use_bitops and "bit.rshift(\(%x as lua expr), \(%shift as lua expr))") or ".." + (\(%x as lua expr) >>> \(%shift as lua expr)) compile [%x ARSHIFT %shift, %x >> %shift] to (..) - Lua value "(\(%x as lua expr) >> \(%shift as lua expr))" + Lua value (..) + (%use_bitops and "bit.arshift(\(%x as lua expr), \(%shift as lua expr))") or ".." + (\(%x as lua expr) >> \(%shift as lua expr)) -# TODO: implement OR, XOR, AND for multiple operands? # Unary operators test: assume ((- 5) == -5)