Re-structure and decouple AST from generator

This commit is contained in:
Rerumu
2022-02-08 17:39:14 -05:00
parent 9d2d8aa69b
commit 22ea8910ad
32 changed files with 753 additions and 481 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "codegen-luau"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies.wasm-ast]
path = "../wasm-ast"
[dependencies.parity-wasm]
git = "https://github.com/paritytech/parity-wasm.git"
features = ["multi_value", "sign_ext"]
+430
View File
@@ -0,0 +1,430 @@
local Numeric = {}
Numeric.__index = Numeric
local bit_band = bit32.band
local bit_bnot = bit32.bnot
local bit_bor = bit32.bor
local bit_xor = bit32.bxor
local bit_lshift = bit32.lshift
local bit_rshift = bit32.rshift
local bit_arshift = bit32.arshift
local math_floor = math.floor
local N_2_TO_31 = 0x80000000
local N_2_TO_32 = 0x100000000
local VAL_ZERO
local VAL_ONE
local VAL_2_TO_24
local op_is_equal
local op_is_greater_unsigned
local op_is_less_unsigned
local op_is_negative
local op_is_zero
local op_bnot
local op_negate
-- TODO: Eventually support Vector3
local function from_u32(low, high)
return setmetatable({ low, high }, Numeric)
end
local function to_u32(value)
return value[1], value[2]
end
local function from_f64(value)
if value < 0 then
return op_negate(from_f64(-value))
else
return from_u32(value % N_2_TO_32, math_floor(value / N_2_TO_32))
end
end
local function to_f64(value)
local low, high = to_u32(value)
return low + high * N_2_TO_32
end
local function op_add(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
local low = low_a + low_b
local high = high_a + high_b
if low >= N_2_TO_32 then
low = low - N_2_TO_32
high = high + 1
end
if high >= N_2_TO_32 then
high = high - N_2_TO_32
end
return from_u32(low, high)
end
local function op_subtract(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
local low = low_a - low_b
local high = high_a - high_b
if low < 0 then
low = low + N_2_TO_32
high = high - 1
end
if high < 0 then
high = high + N_2_TO_32
end
return from_u32(low, high)
end
local function set_absolute(lhs, rhs)
local has_negative = false
if op_is_negative(lhs) then
lhs = op_negate(lhs)
has_negative = not has_negative
end
if op_is_negative(rhs) then
rhs = op_negate(rhs)
has_negative = not has_negative
end
return has_negative, lhs, rhs
end
local function op_multiply(lhs, rhs)
if op_is_zero(lhs) or op_is_zero(rhs) then
return VAL_ZERO
end
local has_negative
has_negative, lhs, rhs = set_absolute(lhs, rhs)
-- If both longs are small, use float multiplication
if op_is_less_unsigned(lhs, VAL_2_TO_24) and op_is_less_unsigned(rhs, VAL_2_TO_24) then
local low_a = to_u32(lhs)
local low_b = to_u32(rhs)
local result = from_f64(low_a * low_b)
if has_negative then
result = op_negate(result)
end
return result
end
-- Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
-- We can skip products that would overflow.
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
local a48 = bit_rshift(high_a, 16)
local a32 = bit_band(high_a, 0xFFFF)
local a16 = bit_rshift(low_a, 16)
local a00 = bit_band(low_a, 0xFFFF)
local b48 = bit_rshift(high_b, 16)
local b32 = bit_band(high_b, 0xFFFF)
local b16 = bit_rshift(low_b, 16)
local b00 = bit_band(low_b, 0xFFFF)
local c48, c32, c16, c00 = 0, 0, 0, 0
c00 = c00 + a00 * b00
c16 = c16 + bit_rshift(c00, 16)
c00 = bit_band(c00, 0xFFFF)
c16 = c16 + a16 * b00
c32 = c32 + bit_rshift(c16, 16)
c16 = bit_band(c16, 0xFFFF)
c16 = c16 + a00 * b16
c32 = c32 + bit_rshift(c16, 16)
c16 = bit_band(c16, 0xFFFF)
c32 = c32 + a32 * b00
c48 = c48 + bit_rshift(c32, 16)
c32 = bit_band(c32, 0xFFFF)
c32 = c32 + a16 * b16
c48 = c48 + bit_rshift(c32, 16)
c32 = bit_band(c32, 0xFFFF)
c32 = c32 + a00 * b32
c48 = c48 + bit_rshift(c32, 16)
c32 = bit_band(c32, 0xFFFF)
c48 = c48 + a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48
c48 = bit_band(c48, 0xFFFF)
local low_v = bit_bor(bit_lshift(c16, 16), c00)
local high_v = bit_bor(bit_lshift(c48, 16), c32)
local result = from_u32(low_v, high_v)
if has_negative then
result = op_negate(result)
end
return result
end
local math_ceil = math.ceil
local math_log = math.log
local math_max = math.max
local math_pow = math.pow
local function get_approx_delta(rem, rhs)
local approx = math_max(1, math_floor(rem / rhs))
local log = math_ceil(math_log(approx, 2))
local delta = log <= 48 and 1 or math_pow(2, log - 48)
return approx, delta
end
local function op_divide_unsigned(lhs, rhs)
if op_is_zero(rhs) then
error("division by zero")
elseif op_is_zero(lhs) then
return 0
end
local rhs_number = to_f64(rhs)
local rem = lhs
local res = VAL_ZERO
while op_is_greater_unsigned(rem, rhs) or op_is_equal(rem, rhs) do
local res_approx, delta = get_approx_delta(to_f64(rem), rhs_number)
local res_temp = from_f64(res_approx)
local rem_temp = op_multiply(res_temp, rhs)
while op_is_negative(rem_temp) or op_is_greater_unsigned(rem_temp, rem) do
res_approx = res_approx - delta
res_temp = from_f64(res_approx)
rem_temp = op_multiply(res_temp, rhs)
end
if op_is_zero(res_temp) then
res_temp = VAL_ONE
end
res = op_add(res, res_temp)
rem = op_subtract(rem, rem_temp)
end
return res
end
local function op_divide_signed(lhs, rhs)
local has_negative
has_negative, lhs, rhs = set_absolute(lhs, rhs)
local result = op_divide_unsigned(lhs, rhs)
if has_negative then
result = op_negate(result)
end
return result
end
function op_negate(value)
return op_add(op_bnot(value), VAL_ONE)
end
local function op_band(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return from_u32(bit_band(low_a, low_b), bit_band(high_a, high_b))
end
function op_bnot(value)
local low, high = to_u32(value)
return from_u32(bit_bnot(low), bit_bnot(high))
end
local function op_bor(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return from_u32(bit_bor(low_a, low_b), bit_bor(high_a, high_b))
end
local function op_bxor(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return from_u32(bit_xor(low_a, low_b), bit_xor(high_a, high_b))
end
local function op_shift_left(lhs, rhs)
local count = to_f64(rhs)
if count < 32 then
local low_a, high_a = to_u32(lhs)
local low_v = bit_lshift(low_a, count)
local high_v = bit_bor(bit_lshift(high_a, count), bit_rshift(low_a, 32 - count))
return from_u32(low_v, high_v)
else
local _, high_a = to_u32(lhs)
local high_v = bit_lshift(high_a, count - 32)
return from_u32(0, high_v)
end
end
local function op_shift_right_unsigned(lhs, rhs)
local count = to_f64(rhs)
if count < 32 then
local low_a, high_a = to_u32(lhs)
local low_v = bit_bor(bit_rshift(low_a, count), bit_lshift(high_a, 32 - count))
local high_v = bit_rshift(high_a, count)
return from_u32(low_v, high_v)
elseif numBits == 32 then
local _, high_a = to_u32(lhs)
return from_u32(high_a, 0)
else
local _, high_a = to_u32(lhs)
return from_u32(bit_rshift(high_a, count - 32), 0)
end
end
local function op_shift_right_signed(lhs, rhs)
local count = to_f64(rhs)
if count < 32 then
local low_a, high_a = to_u32(lhs)
local low_v = bit_bor(bit_rshift(low_a, count), bit_lshift(high_a, 32 - count))
local high_v = bit_arshift(high_a, count)
return from_u32(low_v, high_v)
else
local low_a, high_a = to_u32(lhs)
local low_v = bit_arshift(high_a, count - 32)
local high_v = high_a > N_2_TO_31 and N_2_TO_32 - 1 or 0
return from_u32(low_v, high_v)
end
end
function op_is_negative(value)
local _, high = to_u32(value)
return high > N_2_TO_31
end
function op_is_zero(value)
local low, high = to_u32(value)
return low == 0 and high == 0
end
function op_is_equal(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return low_a == low_b and high_a == high_b
end
function op_is_less_unsigned(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return high_a < high_b or (high_a == high_b and low_a < low_b)
end
function op_is_greater_unsigned(lhs, rhs)
local low_a, high_a = to_u32(lhs)
local low_b, high_b = to_u32(rhs)
return high_a > high_b or (high_a == high_b and low_a > low_b)
end
local function op_is_less_signed(lhs, rhs)
local neg_a = op_is_negative(lhs)
local neg_b = op_is_negative(rhs)
if neg_a and not neg_b then
return true
elseif not neg_a and neg_b then
return false
else
return op_is_negative(op_subtract(lhs, rhs))
end
end
local function op_is_greater_signed(lhs, rhs)
local neg_a = op_is_negative(lhs)
local neg_b = op_is_negative(rhs)
if neg_a and not neg_b then
return false
elseif not neg_a and neg_b then
return true
else
return op_is_negative(op_subtract(rhs, lhs))
end
end
local function to_bytes_le(value)
local low, high = to_u32(value)
return {
bit_band(low, 0xFF),
bit_band(bit_rshift(low, 8), 0xFF),
bit_band(bit_rshift(low, 16), 0xFF),
bit_band(bit_rshift(low, 24), 0xFF),
bit_band(high, 0xFF),
bit_band(bit_rshift(high, 8), 0xFF),
bit_band(bit_rshift(high, 16), 0xFF),
bit_band(bit_rshift(high, 24), 0xFF),
}
end
VAL_ZERO = from_f64(0)
VAL_ONE = from_f64(1)
VAL_2_TO_24 = from_f64(0x1000000)
Numeric.from_f64 = from_f64
Numeric.from_u32 = from_u32
Numeric.__add = op_add
Numeric.__sub = op_subtract
Numeric.__mul = op_multiply
Numeric.__div = op_divide_unsigned
Numeric.__unm = op_negate
Numeric.__eq = op_is_equal
Numeric.__lt = op_is_less_unsigned
function Numeric.__le(lhs, rhs)
return op_is_less_unsigned(lhs, rhs) or op_is_equal(lhs, rhs)
end
function Numeric.__tostring(value)
return tostring(to_f64(value))
end
return Numeric
+376
View File
@@ -0,0 +1,376 @@
local module = {}
local math_floor = math.floor
local math_ceil = math.ceil
local bit32 = bit32
local bit_band = bit32.band
local function no_op(x)
return x
end
local function to_u32(x)
return bit_band(x, 0xFFFFFFFF)
end
local function to_i32(x)
if x > 0x7FFFFFFF then
x = x - 0x100000000
end
return x
end
local function wrap_i32(x)
return to_i32(to_u32(x))
end
local function truncate(num)
if num >= 0 then
return math_floor(num)
else
return math_ceil(num)
end
end
do
local add = {}
local sub = {}
local mul = {}
local div = {}
function add.i32(a, b)
return wrap_i32(a + b)
end
function sub.i32(a, b)
return wrap_i32(a - b)
end
function mul.i32(a, b)
return wrap_i32(a * b)
end
function div.i32(lhs, rhs)
assert(rhs ~= 0, "division by zero")
return truncate(lhs / rhs)
end
function div.u32(lhs, rhs)
assert(rhs ~= 0, "division by zero")
lhs = to_u32(lhs)
rhs = to_u32(rhs)
return to_i32(math.floor(lhs / rhs))
end
module.add = add
module.sub = sub
module.mul = mul
module.div = div
end
do
local clz = {}
local ctz = {}
local popcnt = {}
clz.i32 = bit32.countlz
ctz.i32 = bit32.countrz
function popcnt.i32(num)
local count = 0
while num ~= 0 do
num = bit32.band(num, num - 1)
count = count + 1
end
return count
end
module.clz = clz
module.ctz = ctz
module.popcnt = popcnt
end
do
local eqz = {}
local eq = {}
local ne = {}
local le = {}
local lt = {}
local ge = {}
local gt = {}
local function to_boolean(cond)
if cond then
return 1
else
return 0
end
end
function eq.i32(lhs, rhs)
return to_boolean(lhs == rhs)
end
function eq.num(lhs, rhs)
return to_boolean(lhs == rhs)
end
function eqz.i32(lhs)
return to_boolean(lhs == 0)
end
function ne.i32(lhs, rhs)
return to_boolean(lhs ~= rhs)
end
function ne.num(lhs, rhs)
return to_boolean(lhs ~= rhs)
end
function ge.i32(lhs, rhs)
return to_boolean(lhs >= rhs)
end
function ge.u32(lhs, rhs)
return to_boolean(to_u32(lhs) >= to_u32(rhs))
end
function gt.i32(lhs, rhs)
return to_boolean(lhs > rhs)
end
function gt.u32(lhs, rhs)
return to_boolean(to_u32(lhs) > to_u32(rhs))
end
function le.i32(lhs, rhs)
return to_boolean(lhs <= rhs)
end
function le.u32(lhs, rhs)
return to_boolean(to_u32(lhs) <= to_u32(rhs))
end
function lt.i32(lhs, rhs)
return to_boolean(lhs < rhs)
end
function lt.u32(lhs, rhs)
return to_boolean(to_u32(lhs) < to_u32(rhs))
end
module.eqz = eqz
module.eq = eq
module.ne = ne
module.le = le
module.lt = lt
module.ge = ge
module.gt = gt
end
do
local band = {}
local bor = {}
local bxor = {}
local bnot = {}
band.i32 = bit32.band
bnot.i32 = bit32.bnot
bor.i32 = bit32.bor
bxor.i32 = bit32.bxor
module.band = band
module.bor = bor
module.bxor = bxor
module.bnot = bnot
end
do
local shl = {}
local shr = {}
local rotl = {}
local rotr = {}
rotl.i32 = bit32.lrotate
rotr.i32 = bit32.rrotate
shl.i32 = bit32.lshift
shl.u32 = bit32.lshift
shr.i32 = bit32.arshift
shr.u32 = bit32.rshift
module.shl = shl
module.shr = shr
module.rotl = rotl
module.rotr = rotr
end
do
local wrap = {}
local trunc = {}
local extend = {}
local convert = {}
local reinterpret = {}
trunc.i32_f32 = truncate
trunc.i32_f64 = truncate
trunc.u32_f32 = truncate
trunc.u32_f64 = truncate
extend.i64_i32 = no_op
function convert.f32_i32(num)
return num
end
function convert.f64_i32(num)
return num
end
module.wrap = wrap
module.trunc = trunc
module.extend = extend
module.convert = convert
module.reinterpret = reinterpret
end
do
local load = {}
local store = {}
local allocator = {}
local function rip_u64(x)
return math.floor(x / 0x100000000), x % 0x100000000
end
local function merge_u64(hi, lo)
return hi * 0x100000000 + lo
end
local function black_mask_byte(value, offset)
local mask = bit32.lshift(0xFF, offset * 8)
return bit32.band(value, bit32.bnot(mask))
end
local function load_byte(memory, addr)
local offset = addr % 4
local value = memory.data[(addr - offset) / 4] or 0
return bit32.band(bit32.rshift(value, offset * 8), 0xFF)
end
local function store_byte(memory, addr, value)
local offset = addr % 4
local adjust = (addr - offset) / 4
local lhs = bit32.lshift(bit32.band(value, 0xFF), offset * 8)
local rhs = black_mask_byte(memory.data[adjust] or 0, offset)
memory.data[adjust] = bit32.bor(lhs, rhs)
end
function load.i32_i8(memory, addr)
local b = load_byte(memory, addr)
if b > 0x7F then
b = b - 0x100
end
return b
end
load.i32_u8 = load_byte
function load.i32(memory, addr)
if addr % 4 == 0 then
-- aligned read
return memory.data[addr / 4] or 0
else
-- unaligned read
local b1 = load_byte(memory, addr)
local b2 = bit32.lshift(load_byte(memory, addr + 1), 8)
local b3 = bit32.lshift(load_byte(memory, addr + 2), 16)
local b4 = bit32.lshift(load_byte(memory, addr + 3), 24)
return bit32.bor(b1, b2, b3, b4)
end
end
function load.i64(memory, addr)
local hi = load.i32(memory, addr + 4)
local lo = load.i32(memory, addr)
return merge_u64(hi, lo)
end
store.i32_n8 = store_byte
function store.i32(memory, addr, value)
if addr % 4 == 0 then
-- aligned write
memory.data[addr / 4] = value
else
-- unaligned write
store_byte(memory, addr, value)
store_byte(memory, addr + 1, bit32.rshift(value, 8))
store_byte(memory, addr + 2, bit32.rshift(value, 16))
store_byte(memory, addr + 3, bit32.rshift(value, 24))
end
end
function store.i64(memory, addr, value)
local hi, lo = rip_u64(value)
store.i32(memory, addr, lo)
store.i32(memory, addr + 4, hi)
end
function allocator.new(min, max)
return { min = min, max = max, data = {} }
end
function allocator.init(memory, offset, data)
local store_i8 = module.store.i32_n8
local store_i32 = module.store.i32
local len = #data
local rem = len % 4
for i = 1, len - rem, 4 do
local v = string.unpack("<I4", data, i)
store_i32(memory, offset + i - 1, v)
end
for i = len - rem + 1, len do
local v = string.byte(data, i)
store_i8(memory, offset + i - 1, v)
end
end
function allocator.grow(memory, num)
local old = memory.min
local new = old + num
if new > memory.max then
return -1
else
memory.min = new
return old
end
end
module.load = load
module.store = store
module.allocator = allocator
end
return module
+60
View File
@@ -0,0 +1,60 @@
use std::collections::BTreeSet;
use wasm_ast::{
node::{AnyBinOp, AnyCmpOp, AnyLoad, AnyStore, AnyUnOp, Function},
visit::{Driver, Visitor},
};
struct Visit {
result: BTreeSet<(&'static str, &'static str)>,
}
impl Visitor for Visit {
fn visit_any_load(&mut self, v: &AnyLoad) {
let name = v.op.as_name();
self.result.insert(("load", name));
}
fn visit_any_store(&mut self, v: &AnyStore) {
let name = v.op.as_name();
self.result.insert(("store", name));
}
fn visit_any_unop(&mut self, v: &AnyUnOp) {
let name = v.op.as_name();
self.result.insert(name);
}
fn visit_any_binop(&mut self, v: &AnyBinOp) {
if v.op.as_operator().is_some() {
return;
}
let name = v.op.as_name();
self.result.insert(name);
}
fn visit_any_cmpop(&mut self, v: &AnyCmpOp) {
if v.op.as_operator().is_some() {
return;
}
let name = v.op.as_name();
self.result.insert(name);
}
}
pub fn visit(func: &Function) -> BTreeSet<(&'static str, &'static str)> {
let mut visit = Visit {
result: BTreeSet::new(),
};
func.accept(&mut visit);
visit.result
}
+38
View File
@@ -0,0 +1,38 @@
use std::collections::BTreeSet;
use wasm_ast::{
node::{AnyLoad, AnyStore, Function, MemoryGrow, MemorySize},
visit::{Driver, Visitor},
};
struct Visit {
result: BTreeSet<u8>,
}
impl Visitor for Visit {
fn visit_any_store(&mut self, _: &AnyStore) {
self.result.insert(0);
}
fn visit_any_load(&mut self, _: &AnyLoad) {
self.result.insert(0);
}
fn visit_memory_size(&mut self, m: &MemorySize) {
self.result.insert(m.memory);
}
fn visit_memory_grow(&mut self, m: &MemoryGrow) {
self.result.insert(m.memory);
}
}
pub fn visit(func: &Function) -> BTreeSet<u8> {
let mut visit = Visit {
result: BTreeSet::new(),
};
func.accept(&mut visit);
visit.result
}
+2
View File
@@ -0,0 +1,2 @@
pub mod localize;
pub mod memory;
+862
View File
@@ -0,0 +1,862 @@
use std::{collections::BTreeSet, io::Result, ops::Range};
use parity_wasm::elements::{
External, ImportCountType, Instruction, Internal, Module, NameSection, ResizableLimits,
};
use wasm_ast::{
builder::{Arities, Builder},
node::{
AnyBinOp, AnyCmpOp, AnyLoad, AnyStore, AnyUnOp, Backward, Br, BrIf, BrTable, Call,
CallIndirect, Else, Expression, Forward, Function, GetGlobal, GetLocal, If, Memorize,
MemoryGrow, MemorySize, Recall, Return, Select, SetGlobal, SetLocal, Statement, Value,
},
writer::{Transpiler, Writer},
};
use super::analyzer::{localize, memory};
fn aux_internal_index(internal: Internal) -> u32 {
match internal {
Internal::Function(v) | Internal::Table(v) | Internal::Memory(v) | Internal::Global(v) => v,
}
}
fn new_limit_max(limits: &ResizableLimits) -> String {
match limits.maximum() {
Some(v) => v.to_string(),
None => "0xFFFF".to_string(),
}
}
fn write_table_init(limit: &ResizableLimits, w: Writer) -> Result<()> {
let a = limit.initial();
let b = new_limit_max(limit);
write!(w, "{{ min = {}, max = {}, data = {{}} }}", a, b)
}
fn write_memory_init(limit: &ResizableLimits, w: Writer) -> Result<()> {
let a = limit.initial();
let b = new_limit_max(limit);
write!(w, "rt.allocator.new({}, {})", a, b)
}
fn write_func_name(wasm: &Module, index: u32, offset: u32, w: Writer) -> Result<()> {
let opt = wasm
.names_section()
.and_then(NameSection::functions)
.and_then(|v| v.names().get(index));
write!(w, "FUNC_LIST")?;
if let Some(name) = opt {
write!(w, "--[[{}]]", name)?;
}
write!(w, "[{}] =", index + offset)
}
fn write_in_order(prefix: &str, len: u32, w: Writer) -> Result<()> {
if len == 0 {
return Ok(());
}
write!(w, "{}_{}", prefix, 0)?;
(1..len).try_for_each(|i| write!(w, ", {}_{}", prefix, i))
}
fn write_f32(f: f32, w: Writer) -> Result<()> {
let sign = if f.is_sign_negative() { "-" } else { "" };
if f.is_infinite() {
write!(w, "{}math.huge ", sign)
} else if f.is_nan() {
write!(w, "{}0/0 ", sign)
} else {
write!(w, "{:e} ", f)
}
}
fn write_f64(f: f64, w: Writer) -> Result<()> {
let sign = if f.is_sign_negative() { "-" } else { "" };
if f.is_infinite() {
write!(w, "{}math.huge ", sign)
} else if f.is_nan() {
write!(w, "{}0/0 ", sign)
} else {
write!(w, "{:e} ", f)
}
}
fn write_list(name: &str, len: usize, w: Writer) -> Result<()> {
let len = len.saturating_sub(1);
write!(w, "local {} = table.create({})", name, len)
}
fn write_parameter_list(func: &Function, w: Writer) -> Result<()> {
write!(w, "function(")?;
write_in_order("param", func.num_param, w)?;
write!(w, ")")
}
fn write_result_list(range: Range<u32>, w: Writer) -> Result<()> {
if range.is_empty() {
return Ok(());
}
range.clone().try_for_each(|i| {
if i != range.start {
write!(w, ", ")?;
}
write!(w, "reg_{}", i)
})?;
write!(w, " = ")
}
fn write_variable_list(func: &Function, w: Writer) -> Result<()> {
if !func.local_list.is_empty() {
let num_local = func.local_list.len().try_into().unwrap();
write!(w, "local ")?;
write_in_order("loc", num_local, w)?;
write!(w, " = ")?;
for (i, t) in func.local_list.iter().enumerate() {
if i != 0 {
write!(w, ", ")?;
}
write!(w, "ZERO_{} ", t)?;
}
}
if func.num_stack != 0 {
write!(w, "local ")?;
write_in_order("reg", func.num_stack, w)?;
write!(w, " ")?;
}
Ok(())
}
fn write_expression(code: &[Instruction], w: Writer) -> Result<()> {
// FIXME: Badly generated WASM will produce the wrong constant.
for inst in code {
let result = match *inst {
Instruction::I32Const(v) => write!(w, "{} ", v),
Instruction::I64Const(v) => write!(w, "{} ", v),
Instruction::F32Const(v) => write_f32(f32::from_bits(v), w),
Instruction::F64Const(v) => write_f64(f64::from_bits(v), w),
Instruction::GetGlobal(i) => write!(w, "GLOBAL_LIST[{}].value ", i),
_ => {
continue;
}
};
return result;
}
write!(w, "error(\"mundane expression\")")
}
fn br_target(level: usize, in_loop: bool, w: Writer) -> Result<()> {
write!(w, "if desired then ")?;
write!(w, "if desired == {} then ", level)?;
write!(w, "desired = nil ")?;
if in_loop {
write!(w, "continue ")?;
}
write!(w, "end ")?;
write!(w, "break ")?;
write!(w, "end ")
}
#[derive(PartialEq, Eq)]
enum Label {
Forward,
Backward,
If,
}
#[derive(Default)]
struct Visitor {
label_list: Vec<Label>,
num_param: u32,
}
impl Visitor {
fn write_br_gadget(&self, rem: usize, w: Writer) -> Result<()> {
match self.label_list.last() {
Some(Label::Forward | Label::If) => br_target(rem, false, w),
Some(Label::Backward) => br_target(rem, true, w),
None => Ok(()),
}
}
}
trait Driver {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()>;
}
impl Driver for Recall {
fn visit(&self, _: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "reg_{} ", self.var)
}
}
impl Driver for Select {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "(")?;
self.cond.visit(v, w)?;
write!(w, "~= 0 and ")?;
self.a.visit(v, w)?;
write!(w, "or ")?;
self.b.visit(v, w)?;
write!(w, ")")
}
}
fn write_variable(var: u32, v: &Visitor, w: Writer) -> Result<()> {
if let Some(rem) = var.checked_sub(v.num_param) {
write!(w, "loc_{} ", rem)
} else {
write!(w, "param_{} ", var)
}
}
impl Driver for GetLocal {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_variable(self.var, v, w)
}
}
impl Driver for GetGlobal {
fn visit(&self, _: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value ", self.var)
}
}
impl Driver for AnyLoad {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "load_{}(memory_at_0, ", self.op.as_name())?;
self.pointer.visit(v, w)?;
write!(w, "+ {})", self.offset)
}
}
impl Driver for MemorySize {
fn visit(&self, _: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "memory_at_{}.min ", self.memory)
}
}
impl Driver for MemoryGrow {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "rt.allocator.grow(memory_at_{}, ", self.memory)?;
self.value.visit(v, w)?;
write!(w, ")")
}
}
impl Driver for Value {
fn visit(&self, _: &mut Visitor, w: Writer) -> Result<()> {
match self {
Self::I32(i) => write!(w, "{} ", i),
Self::I64(i) => write!(w, "{} ", i),
Self::F32(f) => write_f32(*f, w),
Self::F64(f) => write_f64(*f, w),
}
}
}
impl Driver for AnyUnOp {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
let (a, b) = self.op.as_name();
write!(w, "{}_{}(", a, b)?;
self.rhs.visit(v, w)?;
write!(w, ")")
}
}
fn write_bin_op(bin_op: &AnyBinOp, v: &mut Visitor, w: Writer) -> Result<()> {
let op = bin_op.op.as_operator().unwrap();
write!(w, "(")?;
bin_op.lhs.visit(v, w)?;
write!(w, "{} ", op)?;
bin_op.rhs.visit(v, w)?;
write!(w, ")")
}
fn write_bin_op_call(bin_op: &AnyBinOp, v: &mut Visitor, w: Writer) -> Result<()> {
let (a, b) = bin_op.op.as_name();
write!(w, "{}_{}(", a, b)?;
bin_op.lhs.visit(v, w)?;
write!(w, ", ")?;
bin_op.rhs.visit(v, w)?;
write!(w, ")")
}
impl Driver for AnyBinOp {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
if self.op.as_operator().is_some() {
write_bin_op(self, v, w)
} else {
write_bin_op_call(self, v, w)
}
}
}
impl Driver for AnyCmpOp {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
let (a, b) = self.op.as_name();
write!(w, "{}_{}(", a, b)?;
self.lhs.visit(v, w)?;
write!(w, ", ")?;
self.rhs.visit(v, w)?;
write!(w, ")")
}
}
fn write_expr_list(list: &[Expression], v: &mut Visitor, w: Writer) -> Result<()> {
list.iter().enumerate().try_for_each(|(i, e)| {
if i != 0 {
write!(w, ", ")?;
}
e.visit(v, w)
})
}
impl Driver for Expression {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
match self {
Self::Recall(e) => e.visit(v, w),
Self::Select(e) => e.visit(v, w),
Self::GetLocal(e) => e.visit(v, w),
Self::GetGlobal(e) => e.visit(v, w),
Self::AnyLoad(e) => e.visit(v, w),
Self::MemorySize(e) => e.visit(v, w),
Self::MemoryGrow(e) => e.visit(v, w),
Self::Value(e) => e.visit(v, w),
Self::AnyUnOp(e) => e.visit(v, w),
Self::AnyBinOp(e) => e.visit(v, w),
Self::AnyCmpOp(e) => e.visit(v, w),
}
}
}
impl Driver for Memorize {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "reg_{} = ", self.var)?;
self.value.visit(v, w)
}
}
impl Driver for Forward {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
let rem = v.label_list.len();
v.label_list.push(Label::Forward);
write!(w, "while true do ")?;
self.body.iter().try_for_each(|s| s.visit(v, w))?;
write!(w, "break ")?;
write!(w, "end ")?;
v.label_list.pop().unwrap();
v.write_br_gadget(rem, w)
}
}
impl Driver for Backward {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
let rem = v.label_list.len();
v.label_list.push(Label::Backward);
write!(w, "while true do ")?;
self.body.iter().try_for_each(|s| s.visit(v, w))?;
write!(w, "break ")?;
write!(w, "end ")?;
v.label_list.pop().unwrap();
v.write_br_gadget(rem, w)
}
}
impl Driver for Else {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "else ")?;
self.body.iter().try_for_each(|s| s.visit(v, w))
}
}
impl Driver for If {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
let rem = v.label_list.len();
v.label_list.push(Label::If);
write!(w, "while true do ")?;
write!(w, "if ")?;
self.cond.visit(v, w)?;
write!(w, "~= 0 then ")?;
self.truthy.iter().try_for_each(|s| s.visit(v, w))?;
if let Some(s) = &self.falsey {
s.visit(v, w)?;
}
write!(w, "end ")?;
write!(w, "break ")?;
write!(w, "end ")?;
v.label_list.pop().unwrap();
v.write_br_gadget(rem, w)
}
}
fn write_br_at(up: u32, v: &Visitor, w: Writer) -> Result<()> {
let up = up as usize;
let level = v.label_list.len() - 1;
write!(w, "do ")?;
if up == 0 {
let is_loop = v.label_list[level - up] == Label::Backward;
if is_loop {
write!(w, "continue ")?;
} else {
write!(w, "break ")?;
}
} else {
write!(w, "desired = {} ", level - up)?;
write!(w, "break ")?;
}
write!(w, "end ")
}
impl Driver for Br {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_br_at(self.target, v, w)
}
}
impl Driver for BrIf {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "if ")?;
self.cond.visit(v, w)?;
write!(w, "~= 0 then ")?;
write_br_at(self.target, v, w)?;
write!(w, "end ")
}
}
impl Driver for BrTable {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "do ")?;
write!(w, "local temp = {{")?;
if !self.data.table.is_empty() {
write!(w, "[0] =")?;
for d in self.data.table.iter() {
write!(w, "{}, ", d)?;
}
}
write!(w, "}} ")?;
write!(w, "desired = temp[")?;
self.cond.visit(v, w)?;
write!(w, "] or {} ", self.data.default)?;
write!(w, "break ")?;
write!(w, "end ")
}
}
impl Driver for Return {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "do return ")?;
write_expr_list(&self.list, v, w)?;
write!(w, "end ")
}
}
impl Driver for Call {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_result_list(self.result.clone(), w)?;
write!(w, "FUNC_LIST[{}](", self.func)?;
write_expr_list(&self.param_list, v, w)?;
write!(w, ")")
}
}
impl Driver for CallIndirect {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_result_list(self.result.clone(), w)?;
write!(w, "TABLE_LIST[{}].data[", self.table)?;
self.index.visit(v, w)?;
write!(w, "](")?;
write_expr_list(&self.param_list, v, w)?;
write!(w, ")")
}
}
impl Driver for SetLocal {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_variable(self.var, v, w)?;
write!(w, "= ")?;
self.value.visit(v, w)
}
}
impl Driver for SetGlobal {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value = ", self.var)?;
self.value.visit(v, w)
}
}
impl Driver for AnyStore {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write!(w, "store_{}(memory_at_0, ", self.op.as_name())?;
self.pointer.visit(v, w)?;
write!(w, "+ {}, ", self.offset)?;
self.value.visit(v, w)?;
write!(w, ")")
}
}
impl Driver for Statement {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
match self {
Statement::Unreachable => write!(w, "error(\"out of code bounds\")"),
Statement::Memorize(s) => s.visit(v, w),
Statement::Forward(s) => s.visit(v, w),
Statement::Backward(s) => s.visit(v, w),
Statement::If(s) => s.visit(v, w),
Statement::Br(s) => s.visit(v, w),
Statement::BrIf(s) => s.visit(v, w),
Statement::BrTable(s) => s.visit(v, w),
Statement::Return(s) => s.visit(v, w),
Statement::Call(s) => s.visit(v, w),
Statement::CallIndirect(s) => s.visit(v, w),
Statement::SetLocal(s) => s.visit(v, w),
Statement::SetGlobal(s) => s.visit(v, w),
Statement::AnyStore(s) => s.visit(v, w),
}
}
}
impl Driver for Function {
fn visit(&self, v: &mut Visitor, w: Writer) -> Result<()> {
write_parameter_list(self, w)?;
for v in memory::visit(self) {
write!(w, "local memory_at_{0} = MEMORY_LIST[{0}]", v)?;
}
write_variable_list(self, w)?;
v.num_param = self.num_param;
self.body.visit(v, w)?;
write!(w, "end ")
}
}
pub struct Generator<'a> {
wasm: &'a Module,
arity: Arities,
}
static RUNTIME: &str = include_str!("../runtime/runtime.lua");
impl<'a> Transpiler<'a> for Generator<'a> {
fn new(wasm: &'a Module) -> Self {
let arity = Arities::new(wasm);
Self { wasm, arity }
}
fn runtime(w: Writer) -> Result<()> {
write!(w, "{}", RUNTIME)
}
fn transpile(&self, w: Writer) -> Result<()> {
write!(w, "local rt = require(script.Runtime)")?;
let func_list = self.build_func_list();
Self::gen_localize(&func_list, w)?;
write!(w, "local ZERO_i32 = 0 ")?;
write!(w, "local ZERO_i64 = 0 ")?;
write!(w, "local ZERO_f32 = 0.0 ")?;
write!(w, "local ZERO_f64 = 0.0 ")?;
write_list("FUNC_LIST", self.wasm.functions_space(), w)?;
write_list("TABLE_LIST", self.wasm.table_space(), w)?;
write_list("MEMORY_LIST", self.wasm.memory_space(), w)?;
write_list("GLOBAL_LIST", self.wasm.globals_space(), w)?;
self.gen_func_list(&func_list, w)?;
self.gen_start_point(w)
}
}
impl<'a> Generator<'a> {
fn gen_import_of<T>(&self, w: Writer, lower: &str, cond: T) -> Result<()>
where
T: Fn(&External) -> bool,
{
let import = match self.wasm.import_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let upper = lower.to_uppercase();
for (i, v) in import.iter().filter(|v| cond(v.external())).enumerate() {
let field = v.field();
let module = v.module();
write!(w, "{}[{}] = wasm.{}.{}.{} ", upper, i, module, lower, field)?;
}
Ok(())
}
fn gen_export_of<T>(&self, w: Writer, lower: &str, cond: T) -> Result<()>
where
T: Fn(&Internal) -> bool,
{
let export = match self.wasm.export_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let upper = lower.to_uppercase();
write!(w, "{} = {{", lower)?;
for v in export.iter().filter(|v| cond(v.internal())) {
let field = v.field();
let index = aux_internal_index(*v.internal());
write!(w, "{} = {}[{}],", field, upper, index)?;
}
write!(w, "}},")
}
fn gen_import_list(&self, w: Writer) -> Result<()> {
self.gen_import_of(w, "func_list", |v| matches!(v, External::Function(_)))?;
self.gen_import_of(w, "table_list", |v| matches!(v, External::Table(_)))?;
self.gen_import_of(w, "memory_list", |v| matches!(v, External::Memory(_)))?;
self.gen_import_of(w, "global_list", |v| matches!(v, External::Global(_)))
}
fn gen_export_list(&self, w: Writer) -> Result<()> {
self.gen_export_of(w, "func_list", |v| matches!(v, Internal::Function(_)))?;
self.gen_export_of(w, "table_list", |v| matches!(v, Internal::Table(_)))?;
self.gen_export_of(w, "memory_list", |v| matches!(v, Internal::Memory(_)))?;
self.gen_export_of(w, "global_list", |v| matches!(v, Internal::Global(_)))
}
fn gen_table_list(&self, w: Writer) -> Result<()> {
let table = match self.wasm.table_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = self.wasm.import_count(ImportCountType::Table);
for (i, v) in table.iter().enumerate() {
let index = i + offset;
write!(w, "TABLE_LIST[{}] =", index)?;
write_table_init(v.limits(), w)?;
}
Ok(())
}
fn gen_memory_list(&self, w: Writer) -> Result<()> {
let memory = match self.wasm.memory_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = self.wasm.import_count(ImportCountType::Memory);
for (i, v) in memory.iter().enumerate() {
let index = i + offset;
write!(w, "MEMORY_LIST[{}] =", index)?;
write_memory_init(v.limits(), w)?;
}
Ok(())
}
fn gen_global_list(&self, w: Writer) -> Result<()> {
let global = match self.wasm.global_section() {
Some(v) => v,
None => return Ok(()),
};
let offset = self.wasm.import_count(ImportCountType::Global);
for (i, v) in global.entries().iter().enumerate() {
let index = i + offset;
write!(w, "GLOBAL_LIST[{}] = {{ value =", index)?;
write_expression(v.init_expr().code(), w)?;
write!(w, "}}")?;
}
Ok(())
}
fn gen_element_list(&self, w: Writer) -> Result<()> {
let element = match self.wasm.elements_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in element {
write!(w, "do ")?;
write!(w, "local target = TABLE_LIST[{}].data ", v.index())?;
write!(w, "local offset =")?;
write_expression(v.offset().as_ref().unwrap().code(), w)?;
write!(w, "local data = {{")?;
v.members()
.iter()
.try_for_each(|v| write!(w, "FUNC_LIST[{}],", v))?;
write!(w, "}}")?;
write!(w, "table.move(data, 1, #data, offset, target)")?;
write!(w, "end ")?;
}
Ok(())
}
fn gen_data_list(&self, w: Writer) -> Result<()> {
let data = match self.wasm.data_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in data {
write!(w, "do ")?;
write!(w, "local target = MEMORY_LIST[{}]", v.index())?;
write!(w, "local offset =")?;
write_expression(v.offset().as_ref().unwrap().code(), w)?;
write!(w, "local data = \"")?;
v.value()
.iter()
.try_for_each(|v| write!(w, "\\x{:02X}", v))?;
write!(w, "\"")?;
write!(w, "rt.allocator.init(target, offset, data)")?;
write!(w, "end ")?;
}
Ok(())
}
fn gen_start_point(&self, w: Writer) -> Result<()> {
write!(w, "local function run_init_code()")?;
self.gen_table_list(w)?;
self.gen_memory_list(w)?;
self.gen_global_list(w)?;
self.gen_element_list(w)?;
self.gen_data_list(w)?;
write!(w, "end ")?;
write!(w, "return function(wasm)")?;
self.gen_import_list(w)?;
write!(w, "run_init_code()")?;
if let Some(start) = self.wasm.start_section() {
write!(w, "FUNC_LIST[{}]()", start)?;
}
write!(w, "return {{")?;
self.gen_export_list(w)?;
write!(w, "}} end ")
}
fn gen_localize(func_list: &[Function], w: Writer) -> Result<()> {
let mut loc_set = BTreeSet::new();
for func in func_list {
loc_set.extend(localize::visit(func));
}
loc_set
.into_iter()
.try_for_each(|(a, b)| write!(w, "local {0}_{1} = rt.{0}.{1} ", a, b))
}
fn build_func_list(&self) -> Vec<Function> {
let range = 0..self.arity.len_in();
range
.map(|i| Builder::new(self.wasm, &self.arity).consume(i))
.collect()
}
fn gen_func_list(&self, func_list: &[Function], w: Writer) -> Result<()> {
let o = self.arity.len_ex();
func_list.iter().enumerate().try_for_each(|(i, v)| {
write_func_name(self.wasm, i.try_into().unwrap(), o.try_into().unwrap(), w)?;
v.visit(&mut Visitor::default(), w)
})
}
}
+2
View File
@@ -0,0 +1,2 @@
mod analyzer;
pub mod gen;