12345678910111213141516171819202122232425262728293031323334353637383940414243 | #!/usr/bin/env nomsu -V8.0.0
###
This file defines bitwise operators: ($x | $y), ($x & $y), ($x ~ $y), (~$x),
($x << $n), and ($x >> $n). They compile to the functions in bitops.lua, which use
Lua's built-in operators on Lua 5.3 and later, and the bit/bit32 libraries on
LuaJIT and Lua 5.2, so the compiled code works on any version of Lua.
### TODO: implement |, ~, and & for multiple operands?
test:
assume (~(~5) == 5)
assume ((1 | 4) == 5)
assume ((1 ~ 3) == 2)
assume ((1 & 3) == 1)
assume ((1 << 2) == 4)
assume ((4 >> 2) == 1)
### Objects can define their own bitwise operators, on either side of the operator:
test:
use "things"
(a Mask) is (a thing) with {$bits}:
($self, & $other) means "masked"
assume (((a Mask) & 1) == "masked")
assume ((1 & (a Mask)) == "masked")
public:
at compile time:
(~$) compiles to "Bit.bnot(\($ as lua expr))"
($x | $y) compiles to
"Bit.bor(\($x as lua expr), \($y as lua expr))"
($x ~ $y) compiles to
"Bit.bxor(\($x as lua expr), \($y as lua expr))"
($x & $y) compiles to
"Bit.band(\($x as lua expr), \($y as lua expr))"
($x << $shift) compiles to
"Bit.lshift(\($x as lua expr), \($shift as lua expr))"
($x >> $shift) compiles to
"Bit.rshift(\($x as lua expr), \($shift as lua expr))"
$Bit = (=lua "require('bitops')")
|