Restructure and compartmentalize the project

This commit is contained in:
Rerumu
2022-06-23 20:14:04 -04:00
parent 59a5a3219f
commit 223895e617
34 changed files with 105 additions and 93 deletions
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "codegen-luajit"
version = "0.8.0"
edition = "2021"
[dependencies.wasm-ast]
path = "../../wasm-ast"
[dependencies.parity-wasm]
git = "https://github.com/paritytech/parity-wasm.git"
features = ["multi_value", "sign_ext"]
[[bin]]
name = "wasm2luajit"
+649
View File
@@ -0,0 +1,649 @@
local module = {}
local bit = require("bit")
local ffi = require("ffi")
local u32 = ffi.typeof("uint32_t")
local u64 = ffi.typeof("uint64_t")
local i64 = ffi.typeof("int64_t")
local math_ceil = math.ceil
local math_floor = math.floor
local to_number = tonumber
local ID_ZERO = i64(0)
local ID_ONE = i64(1)
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 = {}
local rem = {}
local neg = {}
local copysign = {}
local nearest = {}
local to_signed = bit.tobit
local math_abs = math.abs
local RE_INSTANCE = ffi.new([[union {
double f64;
struct { int32_t a32, b32; };
}]])
local function round(num)
if num >= 0 then
return (math_floor(num + 0.5))
else
return (math_ceil(num - 0.5))
end
end
function add.i32(a, b)
return (to_signed(a + b))
end
function sub.i32(a, b)
return (to_signed(a - b))
end
function mul.i32(a, b)
return (to_signed(ID_ONE * 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_number(u32(lhs))
rhs = to_number(u32(rhs))
return (to_signed(math_floor(lhs / rhs)))
end
function div.u64(lhs, rhs)
assert(rhs ~= 0, "division by zero")
return (i64(u64(lhs) / u64(rhs)))
end
function rem.u32(lhs, rhs)
assert(rhs ~= 0, "division by zero")
lhs = to_number(u32(lhs))
rhs = to_number(u32(rhs))
return (to_signed(lhs % rhs))
end
function rem.u64(lhs, rhs)
assert(rhs ~= 0, "division by zero")
return (i64(u64(lhs) % u64(rhs)))
end
function neg.num(num)
return -num
end
function copysign.num(lhs, rhs)
RE_INSTANCE.f64 = rhs
if RE_INSTANCE.b32 >= 0 then
return (math_abs(lhs))
else
return -math_abs(lhs)
end
end
function nearest.num(num)
local result = round(num)
if math_abs(num) % 1 == 0.5 and temp_2 % 2 == 1 then
result = result - 1
end
return result
end
module.add = add
module.sub = sub
module.mul = mul
module.div = div
module.rem = rem
module.neg = neg
module.copysign = copysign
module.nearest = nearest
end
do
local clz = {}
local ctz = {}
local popcnt = {}
local lj_band = bit.band
local lj_lshift = bit.lshift
function clz.i32(num)
for i = 0, 31 do
local mask = lj_lshift(1, 31 - i)
if lj_band(num, mask) ~= 0 then
return i
end
end
return 32
end
function ctz.i32(num)
for i = 0, 31 do
local mask = lj_lshift(1, i)
if lj_band(num, mask) ~= 0 then
return i
end
end
return 32
end
function popcnt.i32(num)
local count = 0
while num ~= 0 do
num = lj_band(num, num - 1)
count = count + 1
end
return count
end
function clz.i64(num)
for i = 0, 63 do
local mask = lj_lshift(ID_ONE, 63 - i)
if lj_band(num, mask) ~= ID_ZERO then
return i * ID_ONE
end
end
return 64 * ID_ONE
end
function ctz.i64(num)
for i = 0, 63 do
local mask = lj_lshift(ID_ONE, i)
if lj_band(num, mask) ~= ID_ZERO then
return i * ID_ONE
end
end
return 64 * ID_ONE
end
function popcnt.i64(num)
local count = ID_ZERO
while num ~= ID_ZERO do
num = lj_band(num, num - 1)
count = count + ID_ONE
end
return count
end
module.clz = clz
module.ctz = ctz
module.popcnt = popcnt
end
do
local le = {}
local lt = {}
local ge = {}
local gt = {}
function ge.u32(lhs, rhs)
return u32(lhs) >= u32(rhs)
end
function ge.u64(lhs, rhs)
return u64(lhs) >= u64(rhs)
end
function gt.u32(lhs, rhs)
return u32(lhs) > u32(rhs)
end
function gt.u64(lhs, rhs)
return u64(lhs) > u64(rhs)
end
function le.u32(lhs, rhs)
return u32(lhs) <= u32(rhs)
end
function le.u64(lhs, rhs)
return u64(lhs) <= u64(rhs)
end
function lt.u32(lhs, rhs)
return u32(lhs) < u32(rhs)
end
function lt.u64(lhs, rhs)
return u64(lhs) < u64(rhs)
end
module.le = le
module.lt = lt
module.ge = ge
module.gt = gt
end
do
local bnot = {}
bnot.i32 = bit.bnot
bnot.i64 = bit.bnot
module.bnot = bnot
end
do
local shl = {}
local shr = {}
local rotl = {}
local rotr = {}
rotl.i32 = bit.rol
rotl.i64 = bit.rol
rotr.i32 = bit.ror
rotr.i64 = bit.ror
shl.i32 = bit.lshift
shl.i64 = bit.lshift
shl.u32 = bit.lshift
shl.u64 = bit.lshift
shr.i32 = bit.arshift
shr.i64 = bit.arshift
shr.u32 = bit.rshift
shr.u64 = bit.rshift
module.shl = shl
module.shr = shr
module.rotl = rotl
module.rotr = rotr
end
do
local wrap = {}
local trunc = {}
local extend = {}
local convert = {}
local promote = {}
local demote = {}
local reinterpret = {}
local bit_band = bit.band
-- This would surely be an issue in a multi-thread environment...
-- ... thankfully this isn't one.
local RE_INSTANCE = ffi.new([[union {
int32_t i32;
int64_t i64;
float f32;
double f64;
}]])
function wrap.i32_i64(num)
RE_INSTANCE.i64 = num
return RE_INSTANCE.i32
end
trunc.i32_f32 = truncate
trunc.i32_f64 = truncate
trunc.u32_f32 = math_floor
trunc.u32_f64 = math_floor
trunc.i64_f32 = i64
trunc.i64_f64 = i64
trunc.u64_f32 = i64
trunc.u64_f64 = i64
function extend.i32_i8(num)
num = bit_band(num, 0xFF)
if num >= 0x80 then
return num - 0x100
else
return num
end
end
function extend.i32_i16(num)
num = bit_band(num, 0xFFFF)
if num >= 0x8000 then
return num - 0x10000
else
return num
end
end
function extend.i64_i8(num)
num = bit_band(num, 0xFF)
if num >= 0x80 then
return num - 0x100
else
return num
end
end
function extend.i64_i16(num)
num = bit_band(num, 0xFFFF)
if num >= 0x8000 then
return num - 0x10000
else
return num
end
end
function extend.i64_i32(num)
num = bit_band(num, 0xFFFFFFFF)
if num >= 0x80000000 then
return num - 0x100000000
else
return num
end
end
function extend.u64_i32(num)
RE_INSTANCE.i64 = ID_ZERO
RE_INSTANCE.i32 = num
return RE_INSTANCE.i64
end
function convert.f32_i32(num)
return num
end
function convert.f32_u32(num)
return (to_number(u32(num)))
end
function convert.f32_i64(num)
return (to_number(num))
end
function convert.f32_u64(num)
return (to_number(u64(num)))
end
function convert.f64_i32(num)
return num
end
function convert.f64_u32(num)
return (to_number(u32(num)))
end
function convert.f64_i64(num)
return (to_number(num))
end
function convert.f64_u64(num)
return (to_number(u64(num)))
end
function demote.f32_f64(num)
return num
end
function promote.f64_f32(num)
return num
end
function reinterpret.i32_f32(num)
RE_INSTANCE.f32 = num
return RE_INSTANCE.i32
end
function reinterpret.i64_f64(num)
RE_INSTANCE.f64 = num
return RE_INSTANCE.i64
end
function reinterpret.f32_i32(num)
RE_INSTANCE.i32 = num
return RE_INSTANCE.f32
end
function reinterpret.f64_i64(num)
RE_INSTANCE.i64 = num
return RE_INSTANCE.f64
end
module.wrap = wrap
module.trunc = trunc
module.extend = extend
module.convert = convert
module.demote = demote
module.promote = promote
module.reinterpret = reinterpret
end
do
local load = {}
local store = {}
local allocator = {}
ffi.cdef([[
union Any {
int8_t i8;
int16_t i16;
int32_t i32;
int64_t i64;
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
float f32;
double f64;
};
struct Memory {
uint32_t min;
uint32_t max;
union Any *data;
};
void *calloc(size_t num, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
]])
local alias_t = ffi.typeof("uint8_t *")
local any_t = ffi.typeof("union Any *")
local cast = ffi.cast
local function by_offset(pointer, offset)
local aliased = cast(alias_t, pointer)
return cast(any_t, aliased + offset)
end
function load.i32_i8(memory, addr)
return by_offset(memory.data, addr).i8
end
function load.i32_u8(memory, addr)
return by_offset(memory.data, addr).u8
end
function load.i32_i16(memory, addr)
return by_offset(memory.data, addr).i16
end
function load.i32_u16(memory, addr)
return by_offset(memory.data, addr).u16
end
function load.i32(memory, addr)
return by_offset(memory.data, addr).i32
end
function load.i64_i8(memory, addr)
return (i64(by_offset(memory.data, addr).i8))
end
function load.i64_u8(memory, addr)
return (i64(by_offset(memory.data, addr).u8))
end
function load.i64_i16(memory, addr)
return (i64(by_offset(memory.data, addr).i16))
end
function load.i64_u16(memory, addr)
return (i64(by_offset(memory.data, addr).u16))
end
function load.i64_i32(memory, addr)
return (i64(by_offset(memory.data, addr).i32))
end
function load.i64_u32(memory, addr)
return (i64(by_offset(memory.data, addr).u32))
end
function load.i64(memory, addr)
return by_offset(memory.data, addr).i64
end
function load.f32(memory, addr)
return by_offset(memory.data, addr).f32
end
function load.f64(memory, addr)
return by_offset(memory.data, addr).f64
end
function store.i32_n8(memory, addr, value)
by_offset(memory.data, addr).i8 = value
end
function store.i32_n16(memory, addr, value)
by_offset(memory.data, addr).i16 = value
end
function store.i32(memory, addr, value)
by_offset(memory.data, addr).i32 = value
end
function store.i64_n8(memory, addr, value)
by_offset(memory.data, addr).i8 = value
end
function store.i64_n16(memory, addr, value)
by_offset(memory.data, addr).i16 = value
end
function store.i64_n32(memory, addr, value)
by_offset(memory.data, addr).i32 = value
end
function store.i64(memory, addr, value)
by_offset(memory.data, addr).i64 = value
end
function store.f32(memory, addr, value)
by_offset(memory.data, addr).f32 = value
end
function store.f64(memory, addr, value)
by_offset(memory.data, addr).f64 = value
end
function store.string(memory, addr, data, len)
local start = by_offset(memory.data, addr)
ffi.copy(start, data, len or #data)
end
local WASM_PAGE_SIZE = 65536
local function finalizer(memory)
ffi.C.free(memory.data)
end
local function grow_unchecked(memory, old, new)
memory.data = ffi.C.realloc(memory.data, new)
assert(memory.data ~= nil, "failed to reallocate")
ffi.fill(by_offset(memory.data, old), new - old, 0)
end
function allocator.new(min, max)
local data = ffi.C.calloc(max, WASM_PAGE_SIZE)
assert(data ~= nil, "failed to allocate")
local memory = ffi.new("struct Memory", min, max, data)
return ffi.gc(memory, finalizer)
end
function allocator.grow(memory, num)
if num == 0 then
return memory.min
end
local old = memory.min
local new = old + num
if new > memory.max then
return -1
else
grow_unchecked(memory, old * WASM_PAGE_SIZE, new * WASM_PAGE_SIZE)
memory.min = new
return old
end
end
module.load = load
module.store = store
module.allocator = allocator
end
return module
+36
View File
@@ -0,0 +1,36 @@
use wasm_ast::node::{BinOpType, CmpOpType};
pub trait AsSymbol {
fn as_symbol(&self) -> Option<&'static str>;
}
impl AsSymbol for BinOpType {
fn as_symbol(&self) -> Option<&'static str> {
let result = match self {
Self::Add_I64 | Self::Add_FN => "+",
Self::Sub_I64 | Self::Sub_FN => "-",
Self::Mul_I64 | Self::Mul_FN => "*",
Self::DivS_I64 | Self::Div_FN => "/",
Self::RemS_I64 => "%",
_ => return None,
};
Some(result)
}
}
impl AsSymbol for CmpOpType {
fn as_symbol(&self) -> Option<&'static str> {
let result = match self {
Self::Eq_I32 | Self::Eq_I64 | Self::Eq_FN => "==",
Self::Ne_I32 | Self::Ne_I64 | Self::Ne_FN => "~=",
Self::LtS_I32 | Self::LtS_I64 | Self::Lt_FN => "<",
Self::GtS_I32 | Self::GtS_I64 | Self::Gt_FN => ">",
Self::LeS_I32 | Self::LeS_I64 | Self::Le_FN => "<=",
Self::GeS_I32 | Self::GeS_I64 | Self::Ge_FN => ">=",
_ => return None,
};
Some(result)
}
}
+29
View File
@@ -0,0 +1,29 @@
use std::collections::HashMap;
use wasm_ast::{
node::{BrTable, FuncData},
visit::{Driver, Visitor},
};
struct Visit {
id_map: HashMap<usize, usize>,
}
impl Visitor for Visit {
fn visit_br_table(&mut self, table: &BrTable) {
let id = table as *const _ as usize;
let len = self.id_map.len() + 1;
self.id_map.insert(id, len);
}
}
pub fn visit(ast: &FuncData) -> HashMap<usize, usize> {
let mut visit = Visit {
id_map: HashMap::new(),
};
ast.accept(&mut visit);
visit.id_map
}
+74
View File
@@ -0,0 +1,74 @@
use std::collections::BTreeSet;
use wasm_ast::{
node::{BinOp, CmpOp, FuncData, LoadAt, MemoryGrow, MemorySize, StoreAt, UnOp},
visit::{Driver, Visitor},
};
use super::as_symbol::AsSymbol;
struct Visit {
local_set: BTreeSet<(&'static str, &'static str)>,
memory_set: BTreeSet<usize>,
}
impl Visitor for Visit {
fn visit_load_at(&mut self, v: &LoadAt) {
let name = v.load_type().as_name();
self.memory_set.insert(0);
self.local_set.insert(("load", name));
}
fn visit_store_at(&mut self, v: &StoreAt) {
let name = v.store_type().as_name();
self.memory_set.insert(0);
self.local_set.insert(("store", name));
}
fn visit_un_op(&mut self, v: &UnOp) {
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_bin_op(&mut self, v: &BinOp) {
if v.op_type().as_symbol().is_some() {
return;
}
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_cmp_op(&mut self, v: &CmpOp) {
if v.op_type().as_symbol().is_some() {
return;
}
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_memory_size(&mut self, m: &MemorySize) {
self.memory_set.insert(m.memory());
}
fn visit_memory_grow(&mut self, m: &MemoryGrow) {
self.memory_set.insert(m.memory());
}
}
pub fn visit(ast: &FuncData) -> (BTreeSet<(&'static str, &'static str)>, BTreeSet<usize>) {
let mut visit = Visit {
local_set: BTreeSet::new(),
memory_set: BTreeSet::new(),
};
ast.accept(&mut visit);
(visit.local_set, visit.memory_set)
}
+3
View File
@@ -0,0 +1,3 @@
pub mod as_symbol;
pub mod br_table;
pub mod localize;
+153
View File
@@ -0,0 +1,153 @@
use std::{
io::{Result, Write},
num::FpCategory,
};
use wasm_ast::node::{
BinOp, CmpOp, Expression, GetGlobal, GetLocal, GetTemporary, LoadAt, MemorySize, Select, UnOp,
Value,
};
use crate::analyzer::as_symbol::AsSymbol;
use super::manager::{
write_cmp_op, write_condition, write_separated, write_variable, Driver, Manager,
};
macro_rules! impl_write_number {
($name:tt, $numeric:ty) => {
fn $name(number: $numeric, w: &mut dyn Write) -> Result<()> {
match (number.classify(), number.is_sign_negative()) {
(FpCategory::Nan, true) => write!(w, "(0.0 / 0.0) "),
(FpCategory::Nan, false) => write!(w, "-(0.0 / 0.0) "),
(FpCategory::Infinite, true) => write!(w, "-math.huge "),
(FpCategory::Infinite, false) => write!(w, "math.huge "),
_ => write!(w, "{number:e} "),
}
}
};
}
impl Driver for Select {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "(")?;
write_condition(self.condition(), mng, w)?;
write!(w, "and ")?;
self.on_true().write(mng, w)?;
write!(w, "or ")?;
self.on_false().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for GetTemporary {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "reg_{} ", self.var())
}
}
impl Driver for GetLocal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_variable(self.var(), mng, w)
}
}
impl Driver for GetGlobal {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value ", self.var())
}
}
impl Driver for LoadAt {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "load_{}(memory_at_0, ", self.load_type().as_name())?;
self.pointer().write(mng, w)?;
if self.offset() != 0 {
write!(w, "+ {}", self.offset())?;
}
write!(w, ")")
}
}
impl Driver for MemorySize {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "memory_at_{}.min ", self.memory())
}
}
impl_write_number!(write_f32, f32);
impl_write_number!(write_f64, f64);
impl Driver for Value {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::I32(i) => write!(w, "{i} "),
Self::I64(i) => write!(w, "{i}LL "),
Self::F32(f) => write_f32(*f, w),
Self::F64(f) => write_f64(*f, w),
}
}
}
impl Driver for UnOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let (a, b) = self.op_type().as_name();
write!(w, "{a}_{b}(")?;
self.rhs().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for BinOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Some(symbol) = self.op_type().as_symbol() {
write!(w, "(")?;
self.lhs().write(mng, w)?;
write!(w, "{symbol} ")?;
self.rhs().write(mng, w)?;
write!(w, ")")
} else {
let (head, tail) = self.op_type().as_name();
write!(w, "{head}_{tail}(")?;
self.lhs().write(mng, w)?;
write!(w, ", ")?;
self.rhs().write(mng, w)?;
write!(w, ")")
}
}
}
impl Driver for CmpOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "(")?;
write_cmp_op(self, mng, w)?;
write!(w, "and 1 or 0)")
}
}
impl Driver for Expression {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Select(e) => e.write(mng, w),
Self::GetTemporary(e) => e.write(mng, w),
Self::GetLocal(e) => e.write(mng, w),
Self::GetGlobal(e) => e.write(mng, w),
Self::LoadAt(e) => e.write(mng, w),
Self::MemorySize(e) => e.write(mng, w),
Self::Value(e) => e.write(mng, w),
Self::UnOp(e) => e.write(mng, w),
Self::BinOp(e) => e.write(mng, w),
Self::CmpOp(e) => e.write(mng, w),
}
}
}
impl Driver for &[Expression] {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_separated(self.iter(), |e, w| e.write(mng, w), w)
}
}
+105
View File
@@ -0,0 +1,105 @@
use std::{
collections::HashMap,
io::{Result, Write},
ops::Range,
};
use wasm_ast::node::{BrTable, CmpOp, Expression};
use crate::analyzer::as_symbol::AsSymbol;
#[derive(Default)]
pub struct Manager {
table_map: HashMap<usize, usize>,
label_list: Vec<usize>,
num_label: usize,
num_param: usize,
}
impl Manager {
pub fn get_table_index(&self, table: &BrTable) -> usize {
let id = table as *const _ as usize;
self.table_map[&id]
}
pub fn set_table_map(&mut self, map: HashMap<usize, usize>) {
self.table_map = map;
}
pub fn set_num_param(&mut self, num: usize) {
self.num_param = num;
}
pub fn label_list(&self) -> &[usize] {
&self.label_list
}
pub fn push_label(&mut self) -> usize {
self.label_list.push(self.num_label);
self.num_label += 1;
self.num_label - 1
}
pub fn pop_label(&mut self) {
self.label_list.pop().unwrap();
}
}
pub trait Driver {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()>;
}
pub fn write_separated<I, T, M>(mut iter: I, mut func: M, w: &mut dyn Write) -> Result<()>
where
M: FnMut(T, &mut dyn Write) -> Result<()>,
I: Iterator<Item = T>,
{
match iter.next() {
Some(first) => func(first, w)?,
None => return Ok(()),
}
iter.try_for_each(|v| {
write!(w, ", ")?;
func(v, w)
})
}
pub fn write_ascending(prefix: &str, range: Range<usize>, w: &mut dyn Write) -> Result<()> {
write_separated(range, |i, w| write!(w, "{prefix}_{i}"), w)
}
pub fn write_variable(var: usize, mng: &Manager, w: &mut dyn Write) -> Result<()> {
if let Some(rem) = var.checked_sub(mng.num_param) {
write!(w, "loc_{rem} ")
} else {
write!(w, "param_{var} ")
}
}
pub fn write_cmp_op(cmp: &CmpOp, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Some(symbol) = cmp.op_type().as_symbol() {
cmp.lhs().write(mng, w)?;
write!(w, "{symbol} ")?;
cmp.rhs().write(mng, w)
} else {
let (head, tail) = cmp.op_type().as_name();
write!(w, "{head}_{tail}(")?;
cmp.lhs().write(mng, w)?;
write!(w, ", ")?;
cmp.rhs().write(mng, w)?;
write!(w, ")")
}
}
pub fn write_condition(data: &Expression, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Expression::CmpOp(node) = data {
write_cmp_op(node, mng, w)
} else {
data.write(mng, w)?;
write!(w, "~= 0 ")
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod manager;
mod expression;
mod statement;
+345
View File
@@ -0,0 +1,345 @@
use std::{
io::{Result, Write},
ops::Range,
};
use parity_wasm::elements::ValueType;
use wasm_ast::node::{
Backward, Br, BrIf, BrTable, Call, CallIndirect, Forward, FuncData, If, MemoryGrow, SetGlobal,
SetLocal, SetTemporary, Statement, StoreAt, Terminator,
};
use crate::analyzer::br_table;
use super::manager::{
write_ascending, write_condition, write_separated, write_variable, Driver, Manager,
};
impl Driver for Br {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let level = *mng.label_list().iter().nth_back(self.target()).unwrap();
if !self.align().is_aligned() {
write_ascending("reg", self.align().new_range(), w)?;
write!(w, " = ")?;
write_ascending("reg", self.align().old_range(), w)?;
write!(w, " ")?;
}
write!(w, "goto continue_at_{level} ")
}
}
fn to_ordered_table<'a>(list: &'a [Br], default: &'a Br) -> Vec<&'a Br> {
let mut data: Vec<_> = list.iter().chain(std::iter::once(default)).collect();
data.sort_by_key(|v| v.target());
data.dedup_by_key(|v| v.target());
data
}
fn write_search_layer(
range: Range<usize>,
list: &[&Br],
mng: &mut Manager,
w: &mut dyn Write,
) -> Result<()> {
if range.len() == 1 {
return list[range.start].write(mng, w);
}
let center = range.start + range.len() / 2;
let br = list[center];
if range.start != center {
write!(w, "if temp < {} then ", br.target())?;
write_search_layer(range.start..center, list, mng, w)?;
write!(w, "else")?;
}
if range.end != center + 1 {
write!(w, "if temp > {} then ", br.target())?;
write_search_layer(center + 1..range.end, list, mng, w)?;
write!(w, "else")?;
}
write!(w, " ")?;
br.write(mng, w)?;
write!(w, "end ")
}
fn write_table_setup(table: &BrTable, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let id = mng.get_table_index(table);
write!(w, "if not br_map[{id}] then ")?;
write!(w, "br_map[{id}] = (function() return {{[0] =")?;
table
.data()
.iter()
.try_for_each(|v| write!(w, "{},", v.target()))?;
write!(w, "}} end)()")?;
write!(w, "end ")?;
write!(w, "temp = br_map[{id}][")?;
table.condition().write(mng, w)?;
write!(w, "] or {} ", table.default().target())
}
impl Driver for BrTable {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if self.data().is_empty() {
// Our condition should be pure so we probably don't need
// to emit it in this case.
return self.default().write(mng, w);
}
// `BrTable` is optimized by first mapping all indices to targets through
// a Lua table; this reduces the size of the code generated as duplicate entries
// don't need checking. Then, for speed, a binary search is done for the target
// and the appropriate jump is performed.
let list = to_ordered_table(self.data(), self.default());
write_table_setup(self, mng, w)?;
write_search_layer(0..list.len(), &list, mng, w)
}
}
impl Driver for Terminator {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Unreachable => write!(w, "error(\"out of code bounds\")"),
Self::Br(s) => s.write(mng, w),
Self::BrTable(s) => s.write(mng, w),
}
}
}
impl Driver for Forward {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let label = mng.push_label();
self.code().iter().try_for_each(|s| s.write(mng, w))?;
if let Some(v) = self.last() {
v.write(mng, w)?;
}
write!(w, "::continue_at_{label}::")?;
mng.pop_label();
Ok(())
}
}
impl Driver for Backward {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let label = mng.push_label();
write!(w, "::continue_at_{label}::")?;
write!(w, "while true do ")?;
self.code().iter().try_for_each(|s| s.write(mng, w))?;
if let Some(v) = self.last() {
v.write(mng, w)?;
} else {
write!(w, "break ")?;
}
write!(w, "end ")?;
mng.pop_label();
Ok(())
}
}
impl Driver for BrIf {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "if ")?;
write_condition(self.condition(), mng, w)?;
write!(w, "then ")?;
self.target().write(mng, w)?;
write!(w, "end ")
}
}
impl Driver for If {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "if ")?;
write_condition(self.condition(), mng, w)?;
write!(w, "then ")?;
self.on_true().write(mng, w)?;
if let Some(v) = self.on_false() {
write!(w, "else ")?;
v.write(mng, w)?;
}
write!(w, "end ")
}
}
fn write_call_store(result: Range<usize>, w: &mut dyn Write) -> Result<()> {
if result.is_empty() {
return Ok(());
}
write_ascending("reg", result, w)?;
write!(w, " = ")
}
impl Driver for Call {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_call_store(self.result(), w)?;
write!(w, "FUNC_LIST[{}](", self.function())?;
self.param_list().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for CallIndirect {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_call_store(self.result(), w)?;
write!(w, "TABLE_LIST[{}].data[", self.table())?;
self.index().write(mng, w)?;
write!(w, "](")?;
self.param_list().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for SetTemporary {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "reg_{} = ", self.var())?;
self.value().write(mng, w)
}
}
impl Driver for SetLocal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_variable(self.var(), mng, w)?;
write!(w, "= ")?;
self.value().write(mng, w)
}
}
impl Driver for SetGlobal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value = ", self.var())?;
self.value().write(mng, w)
}
}
impl Driver for StoreAt {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "store_{}(memory_at_0, ", self.store_type().as_name())?;
self.pointer().write(mng, w)?;
if self.offset() != 0 {
write!(w, "+ {}", self.offset())?;
}
write!(w, ", ")?;
self.value().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for MemoryGrow {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let result = self.result();
let memory = self.memory();
write!(w, "reg_{result} = rt.allocator.grow(memory_at_{memory}, ")?;
self.size().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for Statement {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Forward(s) => s.write(mng, w),
Self::Backward(s) => s.write(mng, w),
Self::BrIf(s) => s.write(mng, w),
Self::If(s) => s.write(mng, w),
Self::Call(s) => s.write(mng, w),
Self::CallIndirect(s) => s.write(mng, w),
Self::SetTemporary(s) => s.write(mng, w),
Self::SetLocal(s) => s.write(mng, w),
Self::SetGlobal(s) => s.write(mng, w),
Self::StoreAt(s) => s.write(mng, w),
Self::MemoryGrow(s) => s.write(mng, w),
}
}
}
fn write_parameter_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
write!(w, "function(")?;
write_ascending("param", 0..ast.num_param(), w)?;
write!(w, ")")
}
fn write_variable_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
let mut total = 0;
for data in ast.local_data().iter().filter(|v| v.count() != 0) {
let range = total..total + usize::try_from(data.count()).unwrap();
let typed = if data.value_type() == ValueType::I64 {
"0LL"
} else {
"0"
}
.as_bytes();
total = range.end;
write!(w, "local ")?;
write_ascending("loc", range.clone(), w)?;
write!(w, " = ")?;
write_separated(range, |_, w| w.write_all(typed), w)?;
write!(w, " ")?;
}
if ast.num_stack() != 0 {
write!(w, "local ")?;
write_ascending("reg", 0..ast.num_stack(), w)?;
write!(w, " ")?;
}
Ok(())
}
impl Driver for FuncData {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let br_map = br_table::visit(self);
write_parameter_list(self, w)?;
write_variable_list(self, w)?;
if !br_map.is_empty() {
write!(w, "local br_map, temp = {{}}, nil ")?;
}
mng.set_table_map(br_map);
mng.set_num_param(self.num_param());
self.code().write(mng, w)?;
if self.num_result() != 0 {
write!(w, "return ")?;
write_ascending("reg", 0..self.num_result(), w)?;
write!(w, " ")?;
}
write!(w, "end ")
}
}
+34
View File
@@ -0,0 +1,34 @@
use std::io::{Result, Write};
use parity_wasm::{deserialize_file, elements::Module};
fn load_module(name: &str) -> Module {
deserialize_file(name)
.expect("Failed to parse WebAssembly file")
.parse_names()
.unwrap_or_else(|v| v.1)
}
fn do_runtime(lock: &mut dyn Write) -> Result<()> {
let runtime = codegen_luajit::RUNTIME;
writeln!(lock, "local rt = (function()")?;
writeln!(lock, "{runtime}")?;
writeln!(lock, "end)()")
}
fn main() -> Result<()> {
let wasm = match std::env::args().nth(1) {
Some(name) => load_module(&name),
None => {
eprintln!("usage: wasm2luajit <file>");
return Ok(());
}
};
let lock = &mut std::io::stdout().lock();
do_runtime(lock)?;
codegen_luajit::from_module_untyped(&wasm, lock)
}
+7
View File
@@ -0,0 +1,7 @@
pub static RUNTIME: &str = include_str!("../runtime/runtime.lua");
pub use translator::{from_inst_list, from_module_typed, from_module_untyped};
mod analyzer;
mod backend;
mod translator;
+355
View File
@@ -0,0 +1,355 @@
use std::{
collections::BTreeSet,
io::{Result, Write},
};
use parity_wasm::elements::{
External, ImportCountType, Instruction, Internal, Module, NameSection, ResizableLimits,
};
use wasm_ast::{
builder::{Builder, TypeInfo},
node::{FuncData, Statement},
};
use crate::{
analyzer::localize,
backend::manager::{Driver, Manager},
};
fn to_internal_index(internal: Internal) -> u32 {
match internal {
Internal::Function(v) | Internal::Table(v) | Internal::Memory(v) | Internal::Global(v) => v,
}
}
fn limit_data_of(limits: &ResizableLimits) -> (u32, u32) {
let max = limits.maximum().unwrap_or(0xFFFF);
(limits.initial(), max)
}
fn write_table_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
let (a, b) = limit_data_of(limit);
write!(w, "{{ min = {a}, max = {b}, data = {{}} }}")
}
fn write_memory_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
let (a, b) = limit_data_of(limit);
write!(w, "rt.allocator.new({a}, {b})")
}
fn write_named_array(name: &str, len: usize, w: &mut dyn Write) -> Result<()> {
let hash = len.min(1);
let len = len.saturating_sub(1);
write!(w, "local {name} = table_new({len}, {hash})")
}
fn write_constant(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let func = Builder::from_type_info(type_info).build_anonymous(code);
if let Some(Statement::SetTemporary(stat)) = func.code().code().last() {
stat.value().write(&mut Manager::default(), w)?;
} else {
panic!("Not a valid constant");
}
Ok(())
}
fn write_import_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
where
T: Fn(&External) -> bool,
{
let import = match 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, r#"{upper}[{i}] = wasm["{module}"].{lower}["{field}"]"#)?;
}
Ok(())
}
fn write_export_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
where
T: Fn(&Internal) -> bool,
{
let export = match 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 = to_internal_index(*v.internal());
write!(w, r#"["{field}"] = {upper}[{index}],"#)?;
}
write!(w, "}},")
}
fn write_import_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
write_import_of(wasm, "func_list", |v| matches!(v, External::Function(_)), w)?;
write_import_of(wasm, "table_list", |v| matches!(v, External::Table(_)), w)?;
write_import_of(wasm, "memory_list", |v| matches!(v, External::Memory(_)), w)?;
write_import_of(wasm, "global_list", |v| matches!(v, External::Global(_)), w)
}
fn write_export_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
write_export_of(wasm, "func_list", |v| matches!(v, Internal::Function(_)), w)?;
write_export_of(wasm, "table_list", |v| matches!(v, Internal::Table(_)), w)?;
write_export_of(wasm, "memory_list", |v| matches!(v, Internal::Memory(_)), w)?;
write_export_of(wasm, "global_list", |v| matches!(v, Internal::Global(_)), w)
}
fn write_table_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let table = match wasm.table_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Table);
for (i, v) in table.iter().enumerate() {
write!(w, "TABLE_LIST[{}] =", i + offset)?;
write_table_init(v.limits(), w)?;
}
Ok(())
}
fn write_memory_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let memory = match wasm.memory_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Memory);
for (i, v) in memory.iter().enumerate() {
write!(w, "MEMORY_LIST[{}] =", i + offset)?;
write_memory_init(v.limits(), w)?;
}
Ok(())
}
fn write_global_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let global = match wasm.global_section() {
Some(v) => v,
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Global);
for (i, v) in global.entries().iter().enumerate() {
write!(w, "GLOBAL_LIST[{}] = {{ value =", i + offset)?;
write_constant(v.init_expr().code(), type_info, w)?;
write!(w, "}}")?;
}
Ok(())
}
fn write_element_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let element = match wasm.elements_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in element {
let code = v.offset().as_ref().unwrap().code();
write!(w, "do ")?;
write!(w, "local target = TABLE_LIST[{}].data ", v.index())?;
write!(w, "local offset =")?;
write_constant(code, type_info, 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 write_data_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let data = match wasm.data_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in data {
let code = v.offset().as_ref().unwrap().code();
let index = v.index();
write!(w, "rt.store.string(")?;
write!(w, "MEMORY_LIST[{index}],")?;
write_constant(code, type_info, w)?;
write!(w, r#","{}")"#, v.value().escape_ascii())?;
}
Ok(())
}
fn build_func_list(wasm: &Module, type_info: &TypeInfo) -> Vec<FuncData> {
let list = match wasm.code_section() {
Some(v) => v.bodies(),
None => return Vec::new(),
};
let mut builder = Builder::from_type_info(type_info);
list.iter()
.enumerate()
.map(|f| builder.build_indexed(f.0, f.1))
.collect()
}
fn write_local_operation(head: &str, tail: &str, w: &mut dyn Write) -> Result<()> {
match (head, tail) {
("band" | "bor" | "bxor", _) => {
write!(w, "local {head}_{tail} = bit.{head} ")
}
("abs" | "ceil" | "floor" | "sqrt" | "min" | "max", _) => {
write!(w, "local {head}_{tail} = math.{head} ")
}
("rem", "i32") => {
write!(w, "local {head}_{tail} = math.fmod ")
}
_ => write!(w, "local {head}_{tail} = rt.{head}.{tail} "),
}
}
fn write_localize_used(func_list: &[FuncData], w: &mut dyn Write) -> Result<BTreeSet<usize>> {
let mut loc_set = BTreeSet::new();
let mut mem_set = BTreeSet::new();
for (loc, mem) in func_list.iter().map(localize::visit) {
loc_set.extend(loc);
mem_set.extend(mem);
}
for loc in loc_set {
write_local_operation(loc.0, loc.1, w)?;
}
for mem in &mem_set {
write!(w, "local memory_at_{mem} ")?;
}
Ok(mem_set)
}
fn write_func_start(wasm: &Module, index: u32, w: &mut dyn Write) -> 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}] =")
}
fn write_func_list(
wasm: &Module,
type_info: &TypeInfo,
func_list: &[FuncData],
w: &mut dyn Write,
) -> Result<()> {
func_list.iter().enumerate().try_for_each(|(i, v)| {
let index = (type_info.len_ex() + i).try_into().unwrap();
write_func_start(wasm, index, w)?;
v.write(&mut Manager::default(), w)
})
}
fn write_module_start(
wasm: &Module,
type_info: &TypeInfo,
mem_set: &BTreeSet<usize>,
w: &mut dyn Write,
) -> Result<()> {
write!(w, "local function run_init_code()")?;
write_table_list(wasm, w)?;
write_memory_list(wasm, w)?;
write_global_list(wasm, type_info, w)?;
write_element_list(wasm, type_info, w)?;
write_data_list(wasm, type_info, w)?;
write!(w, "end ")?;
write!(w, "return function(wasm)")?;
write_import_list(wasm, w)?;
write!(w, "run_init_code()")?;
for mem in mem_set {
write!(w, "memory_at_{mem} = MEMORY_LIST[{mem}]")?;
}
if let Some(start) = wasm.start_section() {
write!(w, "FUNC_LIST[{start}]()")?;
}
write!(w, "return {{")?;
write_export_list(wasm, w)?;
write!(w, "}} end ")
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_inst_list(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
Builder::from_type_info(type_info)
.build_anonymous(code)
.write(&mut Manager::default(), w)
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_module_typed(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let func_list = build_func_list(wasm, type_info);
let mem_set = write_localize_used(&func_list, w)?;
write!(w, "local table_new = require(\"table.new\")")?;
write_named_array("FUNC_LIST", wasm.functions_space(), w)?;
write_named_array("TABLE_LIST", wasm.table_space(), w)?;
write_named_array("MEMORY_LIST", wasm.memory_space(), w)?;
write_named_array("GLOBAL_LIST", wasm.globals_space(), w)?;
write_func_list(wasm, type_info, &func_list, w)?;
write_module_start(wasm, type_info, &mem_set, w)
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_module_untyped(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let type_info = TypeInfo::from_module(wasm);
from_module_typed(wasm, &type_info, w)
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "codegen-luau"
version = "0.5.0"
edition = "2021"
[dependencies.wasm-ast]
path = "../../wasm-ast"
[dependencies.parity-wasm]
git = "https://github.com/paritytech/parity-wasm.git"
features = ["multi_value", "sign_ext"]
[[bin]]
name = "wasm2luau"
+411
View File
@@ -0,0 +1,411 @@
local Numeric = {}
local BIT_SET_31 = 0x80000000
local BIT_SET_32 = 0x100000000
local K_ZERO, K_ONE, K_BIT_SET_26
local bit_lshift = bit32.lshift
local bit_rshift = bit32.rshift
local bit_arshift = bit32.arshift
local bit_and = bit32.band
local bit_or = bit32.bor
local bit_xor = bit32.bxor
local bit_not = bit32.bnot
local bit_replace = bit32.replace
local math_ceil = math.ceil
local math_floor = math.floor
local math_log = math.log
local math_max = math.max
local math_pow = math.pow
local table_freeze = table.freeze
local from_u32, into_u32, from_u64, into_u64
local num_add, num_subtract, num_multiply, num_divide_unsigned, num_negate, num_bit_not
local num_is_negative, num_is_zero, num_is_equal, num_is_less_unsigned, num_is_greater_unsigned
-- TODO: Eventually support Vector3
function Numeric.from_u32(data_1, data_2)
return table_freeze({ data_1, data_2 })
end
function Numeric.into_u32(data)
return data[1], data[2]
end
function Numeric.from_u64(value)
return from_u32(bit_and(value), math_floor(value / BIT_SET_32))
end
function Numeric.into_u64(value)
local data_1, data_2 = into_u32(value)
return data_1 + data_2 * BIT_SET_32
end
function Numeric.add(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
local data_1 = data_l_1 + data_r_1
local data_2 = data_l_2 + data_r_2
if data_1 >= BIT_SET_32 then
data_1 = data_1 - BIT_SET_32
data_2 = data_2 + 1
end
if data_2 >= BIT_SET_32 then
data_2 = data_2 - BIT_SET_32
end
return from_u32(data_1, data_2)
end
function Numeric.subtract(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
local data_1 = data_l_1 - data_r_1
local data_2 = data_l_2 - data_r_2
if data_1 < 0 then
data_1 = data_1 + BIT_SET_32
data_2 = data_2 - 1
end
if data_2 < 0 then
data_2 = data_2 + BIT_SET_32
end
return from_u32(data_1, data_2)
end
local function set_absolute(lhs, rhs)
local has_negative = false
if num_is_negative(lhs) then
lhs = num_negate(lhs)
has_negative = not has_negative
end
if num_is_negative(rhs) then
rhs = num_negate(rhs)
has_negative = not has_negative
end
return has_negative, lhs, rhs
end
function Numeric.multiply(lhs, rhs)
if num_is_zero(lhs) or num_is_zero(rhs) then
return K_ZERO
end
local has_negative
has_negative, lhs, rhs = set_absolute(lhs, rhs)
-- If both longs are small, use float multiplication
if num_is_less_unsigned(lhs, K_BIT_SET_26) and num_is_less_unsigned(rhs, K_BIT_SET_26) then
local data_l_1, _ = into_u32(lhs)
local data_r_1, _ = into_u32(rhs)
local result = from_u64(data_l_1 * data_r_1)
if has_negative then
result = num_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 data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
local a48 = bit_rshift(data_l_2, 16)
local a32 = bit_and(data_l_2, 0xFFFF)
local a16 = bit_rshift(data_l_1, 16)
local a00 = bit_and(data_l_1, 0xFFFF)
local b48 = bit_rshift(data_r_2, 16)
local b32 = bit_and(data_r_2, 0xFFFF)
local b16 = bit_rshift(data_r_1, 16)
local b00 = bit_and(data_r_1, 0xFFFF)
local c00 = a00 * b00
local c16 = bit_rshift(c00, 16)
c00 = bit_and(c00, 0xFFFF)
c16 = c16 + a16 * b00
local c32 = bit_rshift(c16, 16)
c16 = bit_and(c16, 0xFFFF)
c16 = c16 + a00 * b16
c32 = c32 + bit_rshift(c16, 16)
c16 = bit_and(c16, 0xFFFF)
c32 = c32 + a32 * b00
local c48 = bit_rshift(c32, 16)
c32 = bit_and(c32, 0xFFFF)
c32 = c32 + a16 * b16
c48 = c48 + bit_rshift(c32, 16)
c32 = bit_and(c32, 0xFFFF)
c32 = c32 + a00 * b32
c48 = c48 + bit_rshift(c32, 16)
c32 = bit_and(c32, 0xFFFF)
c48 = c48 + a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48
c48 = bit_and(c48, 0xFFFF)
local data_1 = bit_replace(c00, c16, 16, 16)
local data_2 = bit_replace(c32, c48, 16, 16)
local result = from_u32(data_1, data_2)
if has_negative then
result = num_negate(result)
end
return result
end
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
function Numeric.divide_unsigned(lhs, rhs)
if num_is_zero(rhs) then
error("division by zero")
elseif num_is_zero(lhs) then
return 0
end
local rhs_number = into_u64(rhs)
local rem = lhs
local res = K_ZERO
while num_is_greater_unsigned(rem, rhs) or num_is_equal(rem, rhs) do
local res_approx, delta = get_approx_delta(into_u64(rem), rhs_number)
local res_temp = from_u64(res_approx)
local rem_temp = num_multiply(res_temp, rhs)
while num_is_negative(rem_temp) or num_is_greater_unsigned(rem_temp, rem) do
res_approx = res_approx - delta
res_temp = from_u64(res_approx)
rem_temp = num_multiply(res_temp, rhs)
end
if num_is_zero(res_temp) then
res_temp = K_ONE
end
res = num_add(res, res_temp)
rem = num_subtract(rem, rem_temp)
end
return res
end
function Numeric.divide_signed(lhs, rhs)
local has_negative
has_negative, lhs, rhs = set_absolute(lhs, rhs)
local result = num_divide_unsigned(lhs, rhs)
if has_negative then
result = num_negate(result)
end
return result
end
function Numeric.negate(value)
return num_add(num_bit_not(value), K_ONE)
end
function Numeric.bit_and(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return from_u32(bit_and(data_l_1, data_r_1), bit_and(data_l_2, data_r_2))
end
function Numeric.bit_not(value)
local data_1, data_2 = into_u32(value)
return from_u32(bit_not(data_1), bit_not(data_2))
end
function Numeric.bit_or(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return from_u32(bit_or(data_l_1, data_r_1), bit_or(data_l_2, data_r_2))
end
function Numeric.bit_xor(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return from_u32(bit_xor(data_l_1, data_r_1), bit_xor(data_l_2, data_r_2))
end
function Numeric.shift_left(lhs, rhs)
local count = into_u64(rhs)
if count < 32 then
local pad = 32 - count
local data_l_1, data_l_2 = into_u32(lhs)
local data_1 = bit_lshift(data_l_1, count)
local data_2 = bit_replace(bit_rshift(data_l_1, pad), data_l_2, count, pad)
return from_u32(data_1, data_2)
elseif count == 32 then
local data_l_1, _ = into_u32(lhs)
return from_u32(0, data_l_1)
else
local data_l_1, _ = into_u32(lhs)
return from_u32(0, bit_lshift(data_l_1, count - 32))
end
end
function Numeric.shift_right_unsigned(lhs, rhs)
local count = into_u64(rhs)
if count < 32 then
local data_l_1, data_l_2 = into_u32(lhs)
local data_1 = bit_replace(bit_rshift(data_l_1, count), data_l_2, 32 - count, count)
local data_2 = bit_rshift(data_l_2, count)
return from_u32(data_1, data_2)
elseif count == 32 then
local _, data_l_2 = into_u32(lhs)
return from_u32(data_l_2, 0)
else
local _, data_l_2 = into_u32(lhs)
return from_u32(bit_rshift(data_l_2, count - 32), 0)
end
end
function Numeric.shift_right_signed(lhs, rhs)
local count = into_u64(rhs)
if count < 32 then
local data_l_1, data_l_2 = into_u32(lhs)
local data_1 = bit_replace(bit_rshift(data_l_1, count), data_l_2, 32 - count, count)
local data_2 = bit_arshift(data_l_2, count)
return from_u32(data_1, data_2)
else
local _, data_l_2 = into_u32(lhs)
local data_1 = bit_arshift(data_l_2, count - 32)
local data_2 = data_l_2 > BIT_SET_31 and BIT_SET_32 - 1 or 0
return from_u32(data_1, data_2)
end
end
function Numeric.is_negative(value)
local _, data_2 = into_u32(value)
return data_2 > BIT_SET_31
end
function Numeric.is_zero(value)
local data_1, data_2 = into_u32(value)
return data_1 == 0 and data_2 == 0
end
function Numeric.is_equal(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return data_l_1 == data_r_1 and data_l_2 == data_r_2
end
function Numeric.is_less_unsigned(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return data_l_2 < data_r_2 or (data_l_2 == data_r_2 and data_l_1 < data_r_1)
end
function Numeric.is_greater_unsigned(lhs, rhs)
local data_l_1, data_l_2 = into_u32(lhs)
local data_r_1, data_r_2 = into_u32(rhs)
return data_l_2 > data_r_2 or (data_l_2 == data_r_2 and data_l_1 > data_r_1)
end
function Numeric.is_less_signed(lhs, rhs)
local neg_a = num_is_negative(lhs)
local neg_b = num_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 num_is_negative(num_subtract(lhs, rhs))
end
end
function Numeric.is_greater_signed(lhs, rhs)
local neg_a = num_is_negative(lhs)
local neg_b = num_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 num_is_negative(num_subtract(rhs, lhs))
end
end
from_u32 = Numeric.from_u32
into_u32 = Numeric.into_u32
from_u64 = Numeric.from_u64
into_u64 = Numeric.into_u64
num_add = Numeric.add
num_subtract = Numeric.subtract
num_multiply = Numeric.multiply
num_divide_unsigned = Numeric.divide_unsigned
num_negate = Numeric.negate
num_bit_not = Numeric.bit_not
num_is_negative = Numeric.is_negative
num_is_zero = Numeric.is_zero
num_is_equal = Numeric.is_equal
num_is_less_unsigned = Numeric.is_less_unsigned
num_is_greater_unsigned = Numeric.is_greater_unsigned
K_ZERO = from_u64(0)
K_ONE = from_u64(1)
K_BIT_SET_26 = from_u64(0x4000000)
Numeric.K_ZERO = K_ZERO
Numeric.K_ONE = K_ONE
return table_freeze(Numeric)
+637
View File
@@ -0,0 +1,637 @@
local module = {}
local MAX_SIGNED = 0x7fffffff
local BIT_SET_32 = 0x100000000
local to_u32 = bit32.band
local num_from_u32 = I64.from_u32
local num_into_u32 = I64.into_u32
local function to_i32(num)
if num > MAX_SIGNED then
num = num - BIT_SET_32
end
return num
end
local function no_op(num)
return num
end
do
local temp = {}
temp.K_ZERO = I64.K_ZERO
temp.K_ONE = I64.K_ONE
temp.from_u32 = num_from_u32
module.i64 = temp
end
do
local add = {}
local sub = {}
local mul = {}
local div = {}
local neg = {}
local min = {}
local max = {}
local copysign = {}
local nearest = {}
local assert = assert
local math_abs = math.abs
local math_round = math.round
local math_floor = math.floor
local math_sign = math.sign
local math_min = math.min
local math_max = math.max
function add.i32(a, b)
return to_u32(a + b)
end
add.i64 = I64.add
function sub.i32(a, b)
return to_u32(a - b)
end
sub.i64 = I64.subtract
function mul.i32(a, b)
return to_u32(a * b)
end
mul.i64 = I64.multiply
function div.i32(lhs, rhs)
assert(rhs ~= 0, "division by zero")
lhs = to_i32(lhs)
rhs = to_i32(rhs)
return to_u32(lhs / rhs)
end
div.i64 = I64.divide_signed
function div.u32(lhs, rhs)
assert(rhs ~= 0, "division by zero")
return to_u32(lhs / rhs)
end
div.u64 = I64.divide_unsigned
function neg.num(num)
return -num
end
function min.num(a, b)
if b ~= b then
return b
end
return math_min(a, b)
end
function max.num(a, b)
if b ~= b then
return b
end
return math_max(a, b)
end
function copysign.num(lhs, rhs)
if rhs >= 0 then
return (math_abs(lhs))
else
return -math_abs(lhs)
end
end
function nearest.num(num)
local result = math_round(num)
if math_abs(num) % 1 == 0.5 and math_floor(math_abs(num) % 2) == 0 then
result -= math_sign(result)
end
return result
end
module.add = add
module.sub = sub
module.mul = mul
module.div = div
module.neg = neg
module.min = min
module.max = max
module.copysign = copysign
module.nearest = nearest
end
do
local clz = {}
local ctz = {}
local popcnt = {}
local bit_and = bit32.band
clz.i32 = bit32.countlz
ctz.i32 = bit32.countrz
function popcnt.i32(num)
local count = 0
while num ~= 0 do
num = bit_and(num, num - 1)
count = count + 1
end
return count
end
module.clz = clz
module.ctz = ctz
module.popcnt = popcnt
end
do
local eq = {}
local ne = {}
local le = {}
local lt = {}
local ge = {}
local gt = {}
local num_is_equal = I64.is_equal
local num_is_greater_signed = I64.is_greater_signed
local num_is_greater_unsigned = I64.is_greater_unsigned
local num_is_less_signed = I64.is_less_signed
local num_is_less_unsigned = I64.is_less_unsigned
eq.i64 = num_is_equal
function ne.i64(lhs, rhs)
return not num_is_equal(lhs, rhs)
end
function ge.i32(lhs, rhs)
return to_i32(lhs) >= to_i32(rhs)
end
function ge.i64(lhs, rhs)
return num_is_greater_signed(lhs, rhs) or num_is_equal(lhs, rhs)
end
function ge.u64(lhs, rhs)
return num_is_greater_unsigned(lhs, rhs) or num_is_equal(lhs, rhs)
end
function gt.i32(lhs, rhs)
return to_i32(lhs) > to_i32(rhs)
end
gt.i64 = num_is_greater_signed
gt.u64 = num_is_greater_unsigned
function le.i32(lhs, rhs)
return to_i32(lhs) <= to_i32(rhs)
end
function le.i64(lhs, rhs)
return num_is_less_signed(lhs, rhs) or num_is_equal(lhs, rhs)
end
function le.u64(lhs, rhs)
return num_is_less_unsigned(lhs, rhs) or num_is_equal(lhs, rhs)
end
function lt.i32(lhs, rhs)
return to_i32(lhs) < to_i32(rhs)
end
lt.i64 = num_is_less_signed
lt.u64 = num_is_less_unsigned
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.i64 = I64.bit_and
bnot.i32 = bit32.bnot
bnot.i64 = I64.bit_not
bor.i64 = I64.bit_or
bxor.i64 = I64.bit_xor
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
rotl.i64 = bit32.lrotate
rotr.i32 = bit32.rrotate
rotr.i64 = bit32.rrotate
shl.i32 = bit32.lshift
shl.i64 = bit32.lshift
shl.u32 = bit32.lshift
shl.u64 = bit32.lshift
shr.i32 = bit32.arshift
shr.i64 = bit32.arshift
shr.u32 = bit32.rshift
shr.u64 = 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 demote = {}
local promote = {}
local reinterpret = {}
local math_ceil = math.ceil
local math_floor = math.floor
local string_pack = string.pack
local string_unpack = string.unpack
local num_from_u64 = I64.from_u64
local num_into_u64 = I64.into_u64
local num_negate = I64.negate
local num_is_negative = I64.is_negative
function wrap.i32_i64(num)
local data_1, _ = num_into_u32(num)
return data_1
end
trunc.i32_f32 = to_u32
trunc.i32_f64 = to_u32
trunc.u32_f32 = no_op
trunc.u32_f64 = no_op
function trunc.i64_f32(num)
if num < 0 then
local temp = num_from_u64(-math_ceil(num))
return num_negate(temp)
else
local temp = math_floor(num)
return num_from_u64(temp)
end
end
function trunc.i64_f64(num)
if num < 0 then
local temp = num_from_u64(-math_ceil(num))
return num_negate(temp)
else
local temp = math_floor(num)
return num_from_u64(temp)
end
end
function trunc.num(num)
return if num >= 0 then math.floor(num) else math.ceil(num)
end
trunc.u64_f32 = num_from_u64
trunc.u64_f64 = num_from_u64
function extend.i64_i32(num)
if num > MAX_SIGNED then
local temp = num_from_u32(-num + BIT_SET_32, 0)
return num_negate(temp)
else
return num_from_u32(num, 0)
end
end
function extend.u64_i32(num)
return num_from_u32(num, 0)
end
convert.f32_i32 = no_op
convert.f32_u32 = no_op
function convert.f32_i64(num)
if num_is_negative(num) then
local temp = num_negate(num)
return -num_into_u64(temp)
else
return num_into_u64(num)
end
end
convert.f32_u64 = num_into_u64
convert.f64_i32 = to_i32
convert.f64_u32 = no_op
function convert.f64_i64(num)
if num_is_negative(num) then
local temp = num_negate(num)
return -num_into_u64(temp)
else
return num_into_u64(num)
end
end
convert.f64_u64 = num_into_u64
demote.f32_f64 = no_op
promote.f64_f32 = no_op
function reinterpret.i32_f32(num)
local packed = string_pack("f", num)
return string_unpack("<I4", packed)
end
function reinterpret.i64_f64(num)
local packed = string_pack("d", num)
local data_1, data_2 = string_unpack("<I4I4", packed)
return num_from_u32(data_1, data_2)
end
function reinterpret.f32_i32(num)
local packed = string_pack("<I4", num)
return string_unpack("f", packed)
end
function reinterpret.f64_i64(num)
local data_1, data_2 = num_into_u32(num)
local packed = string_pack("<I4I4", data_1, data_2)
return string_unpack("d", packed)
end
module.wrap = wrap
module.trunc = trunc
module.extend = extend
module.convert = convert
module.demote = demote
module.promote = promote
module.reinterpret = reinterpret
end
do
local load = {}
local store = {}
local allocator = {}
local bit_extract = bit32.extract
local bit_replace = bit32.replace
local bit_bor = bit32.bor
local bit_band = bit32.band
local bit_lshift = bit32.lshift
local bit_rshift = bit32.rshift
local math_floor = math.floor
local string_byte = string.byte
local string_unpack = string.unpack
local reinterpret_f32_i32 = module.reinterpret.f32_i32
local reinterpret_f64_i64 = module.reinterpret.f64_i64
local reinterpret_i32_f32 = module.reinterpret.i32_f32
local reinterpret_i64_f64 = module.reinterpret.i64_f64
local function load_byte(data, addr)
local value = data[math_floor(addr / 4)] or 0
return bit_extract(value, addr % 4 * 8, 8)
end
local function store_byte(data, addr, value)
local adjust = math_floor(addr / 4)
data[adjust] = bit_replace(data[adjust] or 0, value, addr % 4 * 8, 8)
end
function load.i32_i8(memory, addr)
local b = load_byte(memory.data, addr)
if b >= 0x80 then
return to_u32(b - 0x100)
else
return b
end
end
function load.i32_u8(memory, addr)
return load_byte(memory.data, addr)
end
function load.i32_i16(memory, addr)
local data = memory.data
local num
if addr % 4 == 0 then
num = bit_band(data[addr / 4] or 0, 0xFFFF)
else
local b1 = load_byte(data, addr)
local b2 = bit_lshift(load_byte(data, addr + 1), 8)
num = bit_bor(b1, b2)
end
if num >= 0x8000 then
return to_u32(num - 0x10000)
else
return num
end
end
function load.i32(memory, addr)
local data = memory.data
if addr % 4 == 0 then
-- aligned read
return data[addr / 4] or 0
else
-- unaligned read
local b1 = load_byte(data, addr)
local b2 = bit_lshift(load_byte(data, addr + 1), 8)
local b3 = bit_lshift(load_byte(data, addr + 2), 16)
local b4 = bit_lshift(load_byte(data, addr + 3), 24)
return bit_bor(b1, b2, b3, b4)
end
end
local load_i32 = load.i32
function load.i64(memory, addr)
local data_1 = load_i32(memory, addr)
local data_2 = load_i32(memory, addr + 4)
return num_from_u32(data_1, data_2)
end
local load_i64 = load.i64
function load.f32(memory, addr)
local raw = load_i32(memory, addr)
return reinterpret_f32_i32(raw)
end
function load.f64(memory, addr)
local raw = load_i64(memory, addr)
return reinterpret_f64_i64(raw)
end
function store.i32_n8(memory, addr, value)
store_byte(memory.data, addr, value)
end
local store_i8 = store.i32_n8
function store.i32_n16(memory, addr, value)
store_byte(memory.data, addr, value)
store_byte(memory.data, addr + 1, bit_rshift(value, 8))
end
function store.i32(memory, addr, value)
local data = memory.data
if addr % 4 == 0 then
-- aligned write
data[addr / 4] = value
else
-- unaligned write
store_byte(data, addr, value)
store_byte(data, addr + 1, bit_rshift(value, 8))
store_byte(data, addr + 2, bit_rshift(value, 16))
store_byte(data, addr + 3, bit_rshift(value, 24))
end
end
local store_i32 = store.i32
local store_i32_n8 = store.i32_n8
local store_i32_n16 = store.i32_n16
function store.i64_n8(memory, addr, value)
local data_1, _ = num_into_u32(value)
store_i32_n8(memory, addr, data_1)
end
function store.i64_n16(memory, addr, value)
local data_1, _ = num_into_u32(value)
store_i32_n16(memory, addr, data_1)
end
function store.i64_n32(memory, addr, value)
local data_1, _ = num_into_u32(value)
store_i32(memory, addr, data_1)
end
function store.i64(memory, addr, value)
local data_1, data_2 = num_into_u32(value)
store_i32(memory, addr, data_1)
store_i32(memory, addr + 4, data_2)
end
local store_i64 = store.i64
function store.f32(memory, addr, value)
store_i32(memory, addr, reinterpret_i32_f32(value))
end
function store.f64(memory, addr, value)
store_i64(memory, addr, reinterpret_i64_f64(value))
end
function store.string(memory, offset, data, len)
len = len or #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.new(min, max)
return { min = min, max = max, data = {} }
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
+36
View File
@@ -0,0 +1,36 @@
use wasm_ast::node::{BinOpType, CmpOpType};
pub trait AsSymbol {
fn as_symbol(&self) -> Option<&'static str>;
}
impl AsSymbol for BinOpType {
fn as_symbol(&self) -> Option<&'static str> {
let result = match self {
Self::Add_FN => "+",
Self::Sub_FN => "-",
Self::Mul_FN => "*",
Self::Div_FN => "/",
Self::RemS_I32 | Self::RemU_I32 => "%",
_ => return None,
};
Some(result)
}
}
impl AsSymbol for CmpOpType {
fn as_symbol(&self) -> Option<&'static str> {
let result = match self {
Self::Eq_I32 | Self::Eq_FN => "==",
Self::Ne_I32 | Self::Ne_FN => "~=",
Self::LtU_I32 | Self::Lt_FN => "<",
Self::GtU_I32 | Self::Gt_FN => ">",
Self::LeU_I32 | Self::Le_FN => "<=",
Self::GeU_I32 | Self::Ge_FN => ">=",
_ => return None,
};
Some(result)
}
}
+29
View File
@@ -0,0 +1,29 @@
use std::collections::HashMap;
use wasm_ast::{
node::{BrTable, FuncData},
visit::{Driver, Visitor},
};
struct Visit {
id_map: HashMap<usize, usize>,
}
impl Visitor for Visit {
fn visit_br_table(&mut self, table: &BrTable) {
let id = table as *const _ as usize;
let len = self.id_map.len() + 1;
self.id_map.insert(id, len);
}
}
pub fn visit(ast: &FuncData) -> HashMap<usize, usize> {
let mut visit = Visit {
id_map: HashMap::new(),
};
ast.accept(&mut visit);
visit.id_map
}
+94
View File
@@ -0,0 +1,94 @@
use std::collections::BTreeSet;
use parity_wasm::elements::ValueType;
use wasm_ast::{
node::{BinOp, CmpOp, FuncData, LoadAt, MemoryGrow, MemorySize, StoreAt, UnOp, Value},
visit::{Driver, Visitor},
};
use super::as_symbol::AsSymbol;
struct Visit {
local_set: BTreeSet<(&'static str, &'static str)>,
memory_set: BTreeSet<usize>,
}
impl Visitor for Visit {
fn visit_load_at(&mut self, v: &LoadAt) {
let name = v.load_type().as_name();
self.memory_set.insert(0);
self.local_set.insert(("load", name));
}
fn visit_store_at(&mut self, v: &StoreAt) {
let name = v.store_type().as_name();
self.memory_set.insert(0);
self.local_set.insert(("store", name));
}
fn visit_value(&mut self, v: &Value) {
let name = match v {
Value::I64(0) => "K_ZERO",
Value::I64(1) => "K_ONE",
Value::I64(_) => "from_u32",
_ => return,
};
self.local_set.insert(("i64", name));
}
fn visit_un_op(&mut self, v: &UnOp) {
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_bin_op(&mut self, v: &BinOp) {
if v.op_type().as_symbol().is_some() {
return;
}
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_cmp_op(&mut self, v: &CmpOp) {
if v.op_type().as_symbol().is_some() {
return;
}
let name = v.op_type().as_name();
self.local_set.insert(name);
}
fn visit_memory_size(&mut self, m: &MemorySize) {
self.memory_set.insert(m.memory());
}
fn visit_memory_grow(&mut self, m: &MemoryGrow) {
self.memory_set.insert(m.memory());
}
}
pub fn visit(ast: &FuncData) -> (BTreeSet<(&'static str, &'static str)>, BTreeSet<usize>) {
let mut visit = Visit {
local_set: BTreeSet::new(),
memory_set: BTreeSet::new(),
};
if ast
.local_data()
.iter()
.any(|v| v.value_type() == ValueType::I64)
{
visit.local_set.insert(("i64", "K_ZERO"));
}
ast.accept(&mut visit);
(visit.local_set, visit.memory_set)
}
+3
View File
@@ -0,0 +1,3 @@
pub mod as_symbol;
pub mod br_table;
pub mod localize;
+173
View File
@@ -0,0 +1,173 @@
use std::{
io::{Result, Write},
num::FpCategory,
};
use wasm_ast::node::{
BinOp, CmpOp, Expression, GetGlobal, GetLocal, GetTemporary, LoadAt, MemorySize, Select, UnOp,
Value,
};
use crate::analyzer::as_symbol::AsSymbol;
use super::manager::{
write_cmp_op, write_condition, write_separated, write_variable, Driver, Manager,
};
macro_rules! impl_write_number {
($name:tt, $numeric:ty) => {
fn $name(number: $numeric, w: &mut dyn Write) -> Result<()> {
match (number.classify(), number.is_sign_negative()) {
(FpCategory::Nan, true) => write!(w, "(0.0 / 0.0) "),
(FpCategory::Nan, false) => write!(w, "-(0.0 / 0.0) "),
(FpCategory::Infinite, true) => write!(w, "-math.huge "),
(FpCategory::Infinite, false) => write!(w, "math.huge "),
_ => write!(w, "{number:e} "),
}
}
};
}
impl Driver for Select {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "(")?;
write_condition(self.condition(), mng, w)?;
write!(w, "and ")?;
self.on_true().write(mng, w)?;
write!(w, "or ")?;
self.on_false().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for GetTemporary {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "reg_{} ", self.var())
}
}
impl Driver for GetLocal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_variable(self.var(), mng, w)
}
}
impl Driver for GetGlobal {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value ", self.var())
}
}
impl Driver for LoadAt {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "load_{}(memory_at_0, ", self.load_type().as_name())?;
self.pointer().write(mng, w)?;
if self.offset() != 0 {
write!(w, "+ {}", self.offset())?;
}
write!(w, ")")
}
}
impl Driver for MemorySize {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "memory_at_{}.min ", self.memory())
}
}
pub fn write_i32(number: i32, w: &mut dyn Write) -> Result<()> {
let list = number.to_ne_bytes();
write!(w, "{} ", u32::from_ne_bytes(list))
}
fn write_i64(number: i64, w: &mut dyn Write) -> Result<()> {
match number {
0 => write!(w, "i64_K_ZERO "),
1 => write!(w, "i64_K_ONE "),
_ => {
let list = number.to_ne_bytes();
let a = u32::from_ne_bytes(list[0..4].try_into().unwrap());
let b = u32::from_ne_bytes(list[4..8].try_into().unwrap());
write!(w, "i64_from_u32({a}, {b}) ")
}
}
}
impl_write_number!(write_f32, f32);
impl_write_number!(write_f64, f64);
impl Driver for Value {
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::I32(i) => write_i32(*i, w),
Self::I64(i) => write_i64(*i, w),
Self::F32(f) => write_f32(*f, w),
Self::F64(f) => write_f64(*f, w),
}
}
}
impl Driver for UnOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let (a, b) = self.op_type().as_name();
write!(w, "{a}_{b}(")?;
self.rhs().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for BinOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Some(symbol) = self.op_type().as_symbol() {
write!(w, "(")?;
self.lhs().write(mng, w)?;
write!(w, "{symbol} ")?;
self.rhs().write(mng, w)?;
write!(w, ")")
} else {
let (head, tail) = self.op_type().as_name();
write!(w, "{head}_{tail}(")?;
self.lhs().write(mng, w)?;
write!(w, ", ")?;
self.rhs().write(mng, w)?;
write!(w, ")")
}
}
}
impl Driver for CmpOp {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "(")?;
write_cmp_op(self, mng, w)?;
write!(w, "and 1 or 0)")
}
}
impl Driver for Expression {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Select(e) => e.write(mng, w),
Self::GetTemporary(e) => e.write(mng, w),
Self::GetLocal(e) => e.write(mng, w),
Self::GetGlobal(e) => e.write(mng, w),
Self::LoadAt(e) => e.write(mng, w),
Self::MemorySize(e) => e.write(mng, w),
Self::Value(e) => e.write(mng, w),
Self::UnOp(e) => e.write(mng, w),
Self::BinOp(e) => e.write(mng, w),
Self::CmpOp(e) => e.write(mng, w),
}
}
}
impl Driver for &[Expression] {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_separated(self.iter(), |e, w| e.write(mng, w), w)
}
}
+109
View File
@@ -0,0 +1,109 @@
use std::{
collections::HashMap,
io::{Result, Write},
ops::Range,
};
use wasm_ast::node::{BrTable, CmpOp, Expression};
use crate::analyzer::as_symbol::AsSymbol;
#[derive(PartialEq, Eq)]
pub enum Label {
Forward,
Backward,
}
#[derive(Default)]
pub struct Manager {
table_map: HashMap<usize, usize>,
label_list: Vec<Label>,
num_param: usize,
}
impl Manager {
pub fn get_table_index(&self, table: &BrTable) -> usize {
let id = table as *const _ as usize;
self.table_map[&id]
}
pub fn set_table_map(&mut self, map: HashMap<usize, usize>) {
self.table_map = map;
}
pub fn set_num_param(&mut self, num_param: usize) {
self.num_param = num_param;
}
pub fn label_list(&self) -> &[Label] {
&self.label_list
}
pub fn push_label(&mut self, label: Label) -> usize {
self.label_list.push(label);
self.label_list.len() - 1
}
pub fn pop_label(&mut self) {
self.label_list.pop().unwrap();
}
}
pub trait Driver {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()>;
}
pub fn write_separated<I, T, M>(mut iter: I, mut func: M, w: &mut dyn Write) -> Result<()>
where
M: FnMut(T, &mut dyn Write) -> Result<()>,
I: Iterator<Item = T>,
{
match iter.next() {
Some(first) => func(first, w)?,
None => return Ok(()),
}
iter.try_for_each(|v| {
write!(w, ", ")?;
func(v, w)
})
}
pub fn write_ascending(prefix: &str, range: Range<usize>, w: &mut dyn Write) -> Result<()> {
write_separated(range, |i, w| write!(w, "{prefix}_{i}"), w)
}
pub fn write_variable(var: usize, mng: &Manager, w: &mut dyn Write) -> Result<()> {
if let Some(rem) = var.checked_sub(mng.num_param) {
write!(w, "loc_{rem} ")
} else {
write!(w, "param_{var} ")
}
}
pub fn write_cmp_op(cmp: &CmpOp, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Some(symbol) = cmp.op_type().as_symbol() {
cmp.lhs().write(mng, w)?;
write!(w, "{symbol} ")?;
cmp.rhs().write(mng, w)
} else {
let (head, tail) = cmp.op_type().as_name();
write!(w, "{head}_{tail}(")?;
cmp.lhs().write(mng, w)?;
write!(w, ", ")?;
cmp.rhs().write(mng, w)?;
write!(w, ")")
}
}
pub fn write_condition(data: &Expression, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if let Expression::CmpOp(node) = data {
write_cmp_op(node, mng, w)
} else {
data.write(mng, w)?;
write!(w, "~= 0 ")
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod manager;
mod expression;
mod statement;
+380
View File
@@ -0,0 +1,380 @@
use std::{
io::{Result, Write},
ops::Range,
};
use parity_wasm::elements::ValueType;
use wasm_ast::node::{
Backward, Br, BrIf, BrTable, Call, CallIndirect, Forward, FuncData, If, MemoryGrow, SetGlobal,
SetLocal, SetTemporary, Statement, StoreAt, Terminator,
};
use crate::analyzer::br_table;
use super::manager::{
write_ascending, write_condition, write_separated, write_variable, Driver, Label, Manager,
};
impl Driver for Br {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if !self.align().is_aligned() {
write_ascending("reg", self.align().new_range(), w)?;
write!(w, " = ")?;
write_ascending("reg", self.align().old_range(), w)?;
write!(w, " ")?;
}
if self.target() == 0 {
if let Some(&Label::Backward) = mng.label_list().last() {
write!(w, "continue ")?;
} else {
write!(w, "break ")?;
}
} else {
let level = mng.label_list().len() - 1 - self.target();
write!(w, "desired = {level} ")?;
write!(w, "break ")?;
}
Ok(())
}
}
fn to_ordered_table<'a>(list: &'a [Br], default: &'a Br) -> Vec<&'a Br> {
let mut data: Vec<_> = list.iter().chain(std::iter::once(default)).collect();
data.sort_by_key(|v| v.target());
data.dedup_by_key(|v| v.target());
data
}
fn write_search_layer(
range: Range<usize>,
list: &[&Br],
mng: &mut Manager,
w: &mut dyn Write,
) -> Result<()> {
if range.len() == 1 {
return list[range.start].write(mng, w);
}
let center = range.start + range.len() / 2;
let br = list[center];
if range.start != center {
write!(w, "if temp < {} then ", br.target())?;
write_search_layer(range.start..center, list, mng, w)?;
write!(w, "else")?;
}
if range.end != center + 1 {
write!(w, "if temp > {} then ", br.target())?;
write_search_layer(center + 1..range.end, list, mng, w)?;
write!(w, "else")?;
}
write!(w, " ")?;
br.write(mng, w)?;
write!(w, "end ")
}
fn write_table_setup(table: &BrTable, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let id = mng.get_table_index(table);
write!(w, "if not br_map[{id}] then ")?;
write!(w, "br_map[{id}] = (function() return {{[0] =")?;
table
.data()
.iter()
.try_for_each(|v| write!(w, "{},", v.target()))?;
write!(w, "}} end)()")?;
write!(w, "end ")?;
write!(w, "local temp = br_map[{id}][")?;
table.condition().write(mng, w)?;
write!(w, "] or {} ", table.default().target())
}
impl Driver for BrTable {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
if self.data().is_empty() {
// Our condition should be pure so we probably don't need
// to emit it in this case.
return self.default().write(mng, w);
}
// `BrTable` is optimized by first mapping all indices to targets through
// a Lua table; this reduces the size of the code generated as duplicate entries
// don't need checking. Then, for speed, a binary search is done for the target
// and the appropriate jump is performed.
let list = to_ordered_table(self.data(), self.default());
write_table_setup(self, mng, w)?;
write_search_layer(0..list.len(), &list, mng, w)
}
}
impl Driver for Terminator {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Unreachable => write!(w, "error(\"out of code bounds\")"),
Self::Br(s) => s.write(mng, w),
Self::BrTable(s) => s.write(mng, w),
}
}
}
fn br_target(level: usize, in_loop: bool, w: &mut dyn Write) -> Result<()> {
write!(w, "if desired then ")?;
write!(w, "if desired == {level} then ")?;
write!(w, "desired = nil ")?;
if in_loop {
write!(w, "continue ")?;
}
write!(w, "else ")?;
write!(w, "break ")?;
write!(w, "end ")?;
write!(w, "end ")
}
fn write_br_gadget(label_list: &[Label], rem: usize, w: &mut dyn Write) -> Result<()> {
match label_list.last() {
Some(Label::Forward) => br_target(rem, false, w),
Some(Label::Backward) => br_target(rem, true, w),
None => Ok(()),
}
}
impl Driver for Forward {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let rem = mng.push_label(Label::Forward);
write!(w, "while true do ")?;
self.code().iter().try_for_each(|s| s.write(mng, w))?;
if let Some(v) = self.last() {
v.write(mng, w)?;
} else {
write!(w, "break ")?;
}
write!(w, "end ")?;
mng.pop_label();
write_br_gadget(mng.label_list(), rem, w)
}
}
impl Driver for Backward {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let rem = mng.push_label(Label::Backward);
write!(w, "while true do ")?;
self.code().iter().try_for_each(|s| s.write(mng, w))?;
if let Some(v) = self.last() {
v.write(mng, w)?;
} else {
write!(w, "break ")?;
}
write!(w, "end ")?;
mng.pop_label();
write_br_gadget(mng.label_list(), rem, w)
}
}
impl Driver for BrIf {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "if ")?;
write_condition(self.condition(), mng, w)?;
write!(w, "then ")?;
self.target().write(mng, w)?;
write!(w, "end ")
}
}
impl Driver for If {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "if ")?;
write_condition(self.condition(), mng, w)?;
write!(w, "then ")?;
self.on_true().write(mng, w)?;
if let Some(v) = self.on_false() {
write!(w, "else ")?;
v.write(mng, w)?;
}
write!(w, "end ")
}
}
fn write_call_store(result: Range<usize>, w: &mut dyn Write) -> Result<()> {
if result.is_empty() {
return Ok(());
}
write_ascending("reg", result, w)?;
write!(w, " = ")
}
impl Driver for Call {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_call_store(self.result(), w)?;
write!(w, "FUNC_LIST[{}](", self.function())?;
self.param_list().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for CallIndirect {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_call_store(self.result(), w)?;
write!(w, "TABLE_LIST[{}].data[", self.table())?;
self.index().write(mng, w)?;
write!(w, "](")?;
self.param_list().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for SetTemporary {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "reg_{} = ", self.var())?;
self.value().write(mng, w)
}
}
impl Driver for SetLocal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write_variable(self.var(), mng, w)?;
write!(w, "= ")?;
self.value().write(mng, w)
}
}
impl Driver for SetGlobal {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "GLOBAL_LIST[{}].value = ", self.var())?;
self.value().write(mng, w)
}
}
impl Driver for StoreAt {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
write!(w, "store_{}(memory_at_0, ", self.store_type().as_name())?;
self.pointer().write(mng, w)?;
if self.offset() != 0 {
write!(w, "+ {}", self.offset())?;
}
write!(w, ", ")?;
self.value().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for MemoryGrow {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let result = self.result();
let memory = self.memory();
write!(w, "reg_{result} = rt.allocator.grow(memory_at_{memory}, ")?;
self.size().write(mng, w)?;
write!(w, ")")
}
}
impl Driver for Statement {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
match self {
Self::Forward(s) => s.write(mng, w),
Self::Backward(s) => s.write(mng, w),
Self::BrIf(s) => s.write(mng, w),
Self::If(s) => s.write(mng, w),
Self::Call(s) => s.write(mng, w),
Self::CallIndirect(s) => s.write(mng, w),
Self::SetTemporary(s) => s.write(mng, w),
Self::SetLocal(s) => s.write(mng, w),
Self::SetGlobal(s) => s.write(mng, w),
Self::StoreAt(s) => s.write(mng, w),
Self::MemoryGrow(s) => s.write(mng, w),
}
}
}
fn write_parameter_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
write!(w, "function(")?;
write_ascending("param", 0..ast.num_param(), w)?;
write!(w, ")")
}
fn write_variable_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
let mut total = 0;
for data in ast.local_data().iter().filter(|v| v.count() != 0) {
let range = total..total + usize::try_from(data.count()).unwrap();
let zero = if data.value_type() == ValueType::I64 {
"i64_K_ZERO "
} else {
"0 "
};
total = range.end;
write!(w, "local ")?;
write_ascending("loc", range.clone(), w)?;
write!(w, " = ")?;
write_separated(range, |_, w| w.write_all(zero.as_bytes()), w)?;
write!(w, " ")?;
}
if ast.num_stack() != 0 {
write!(w, "local ")?;
write_ascending("reg", 0..ast.num_stack(), w)?;
write!(w, " ")?;
}
Ok(())
}
impl Driver for FuncData {
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
let br_map = br_table::visit(self);
write_parameter_list(self, w)?;
write_variable_list(self, w)?;
write!(w, "local desired ")?;
if !br_map.is_empty() {
write!(w, "local br_map = {{}} ")?;
}
mng.set_table_map(br_map);
mng.set_num_param(self.num_param());
self.code().write(mng, w)?;
if self.num_result() != 0 {
write!(w, "return ")?;
write_ascending("reg", 0..self.num_result(), w)?;
write!(w, " ")?;
}
write!(w, "end ")
}
}
+38
View File
@@ -0,0 +1,38 @@
use std::io::{Result, Write};
use parity_wasm::{deserialize_file, elements::Module};
fn load_module(name: &str) -> Module {
deserialize_file(name)
.expect("Failed to parse WebAssembly file")
.parse_names()
.unwrap_or_else(|v| v.1)
}
fn do_runtime(lock: &mut dyn Write) -> Result<()> {
let runtime = codegen_luau::RUNTIME;
let numeric = codegen_luau::NUMERIC;
writeln!(lock, "local rt = (function()")?;
writeln!(lock, "local I64 = (function()")?;
writeln!(lock, "{numeric}")?;
writeln!(lock, "end)()")?;
writeln!(lock, "{runtime}")?;
writeln!(lock, "end)()")
}
fn main() -> Result<()> {
let wasm = match std::env::args().nth(1) {
Some(name) => load_module(&name),
None => {
eprintln!("usage: wasm2luau <file>");
return Ok(());
}
};
let lock = &mut std::io::stdout().lock();
do_runtime(lock)?;
codegen_luau::from_module_untyped(&wasm, lock)
}
+8
View File
@@ -0,0 +1,8 @@
pub static RUNTIME: &str = include_str!("../runtime/runtime.lua");
pub static NUMERIC: &str = include_str!("../runtime/numeric.lua");
pub use translator::{from_inst_list, from_module_typed, from_module_untyped};
mod analyzer;
mod backend;
mod translator;
+350
View File
@@ -0,0 +1,350 @@
use std::{
collections::BTreeSet,
io::{Result, Write},
};
use parity_wasm::elements::{
External, ImportCountType, Instruction, Internal, Module, NameSection, ResizableLimits,
};
use wasm_ast::{
builder::{Builder, TypeInfo},
node::{FuncData, Statement},
};
use crate::{
analyzer::localize,
backend::manager::{Driver, Manager},
};
fn to_internal_index(internal: Internal) -> u32 {
match internal {
Internal::Function(v) | Internal::Table(v) | Internal::Memory(v) | Internal::Global(v) => v,
}
}
fn limit_data_of(limits: &ResizableLimits) -> (u32, u32) {
let max = limits.maximum().unwrap_or(0xFFFF);
(limits.initial(), max)
}
fn write_table_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
let (a, b) = limit_data_of(limit);
write!(w, "{{ min = {a}, max = {b}, data = {{}} }}")
}
fn write_memory_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
let (a, b) = limit_data_of(limit);
write!(w, "rt.allocator.new({a}, {b})")
}
fn write_named_array(name: &str, len: usize, w: &mut dyn Write) -> Result<()> {
let len = len.saturating_sub(1);
write!(w, "local {name} = table.create({len})")
}
fn write_constant(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let func = Builder::from_type_info(type_info).build_anonymous(code);
if let Some(Statement::SetTemporary(stat)) = func.code().code().last() {
stat.value().write(&mut Manager::default(), w)?;
} else {
panic!("Not a valid constant");
}
Ok(())
}
fn write_import_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
where
T: Fn(&External) -> bool,
{
let import = match 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, r#"{upper}[{i}] = wasm["{module}"].{lower}["{field}"]"#)?;
}
Ok(())
}
fn write_export_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
where
T: Fn(&Internal) -> bool,
{
let export = match 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 = to_internal_index(*v.internal());
write!(w, r#"["{field}"] = {upper}[{index}],"#)?;
}
write!(w, "}},")
}
fn write_import_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
write_import_of(wasm, "func_list", |v| matches!(v, External::Function(_)), w)?;
write_import_of(wasm, "table_list", |v| matches!(v, External::Table(_)), w)?;
write_import_of(wasm, "memory_list", |v| matches!(v, External::Memory(_)), w)?;
write_import_of(wasm, "global_list", |v| matches!(v, External::Global(_)), w)
}
fn write_export_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
write_export_of(wasm, "func_list", |v| matches!(v, Internal::Function(_)), w)?;
write_export_of(wasm, "table_list", |v| matches!(v, Internal::Table(_)), w)?;
write_export_of(wasm, "memory_list", |v| matches!(v, Internal::Memory(_)), w)?;
write_export_of(wasm, "global_list", |v| matches!(v, Internal::Global(_)), w)
}
fn write_table_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let table = match wasm.table_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Table);
for (i, v) in table.iter().enumerate() {
write!(w, "TABLE_LIST[{}] =", i + offset)?;
write_table_init(v.limits(), w)?;
}
Ok(())
}
fn write_memory_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let memory = match wasm.memory_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Memory);
for (i, v) in memory.iter().enumerate() {
write!(w, "MEMORY_LIST[{}] =", i + offset)?;
write_memory_init(v.limits(), w)?;
}
Ok(())
}
fn write_global_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let global = match wasm.global_section() {
Some(v) => v,
None => return Ok(()),
};
let offset = wasm.import_count(ImportCountType::Global);
for (i, v) in global.entries().iter().enumerate() {
write!(w, "GLOBAL_LIST[{}] = {{ value =", i + offset)?;
write_constant(v.init_expr().code(), type_info, w)?;
write!(w, "}}")?;
}
Ok(())
}
fn write_element_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let element = match wasm.elements_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in element {
let code = v.offset().as_ref().unwrap().code();
write!(w, "do ")?;
write!(w, "local target = TABLE_LIST[{}].data ", v.index())?;
write!(w, "local offset =")?;
write_constant(code, type_info, 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 write_data_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let data = match wasm.data_section() {
Some(v) => v.entries(),
None => return Ok(()),
};
for v in data {
let code = v.offset().as_ref().unwrap().code();
let index = v.index();
write!(w, "rt.store.string(")?;
write!(w, "MEMORY_LIST[{index}],")?;
write_constant(code, type_info, w)?;
write!(w, r#","{}")"#, v.value().escape_ascii())?;
}
Ok(())
}
fn build_func_list(wasm: &Module, type_info: &TypeInfo) -> Vec<FuncData> {
let list = match wasm.code_section() {
Some(v) => v.bodies(),
None => return Vec::new(),
};
let mut builder = Builder::from_type_info(type_info);
list.iter()
.enumerate()
.map(|f| builder.build_indexed(f.0, f.1))
.collect()
}
fn write_local_operation(head: &str, tail: &str, w: &mut dyn Write) -> Result<()> {
match (head, tail) {
("band" | "bor" | "bxor", "i32") => {
write!(w, "local {head}_{tail} = bit32.{head} ")
}
("abs" | "ceil" | "floor" | "sqrt", _) => {
write!(w, "local {head}_{tail} = math.{head} ")
}
_ => write!(w, "local {head}_{tail} = rt.{head}.{tail} "),
}
}
fn write_localize_used(func_list: &[FuncData], w: &mut dyn Write) -> Result<BTreeSet<usize>> {
let mut loc_set = BTreeSet::new();
let mut mem_set = BTreeSet::new();
for (loc, mem) in func_list.iter().map(localize::visit) {
loc_set.extend(loc);
mem_set.extend(mem);
}
for loc in loc_set {
write_local_operation(loc.0, loc.1, w)?;
}
for mem in &mem_set {
write!(w, "local memory_at_{mem} ")?;
}
Ok(mem_set)
}
fn write_func_start(wasm: &Module, index: u32, w: &mut dyn Write) -> 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}] =")
}
fn write_func_list(
wasm: &Module,
type_info: &TypeInfo,
func_list: &[FuncData],
w: &mut dyn Write,
) -> Result<()> {
func_list.iter().enumerate().try_for_each(|(i, v)| {
let index = (type_info.len_ex() + i).try_into().unwrap();
write_func_start(wasm, index, w)?;
v.write(&mut Manager::default(), w)
})
}
fn write_module_start(
wasm: &Module,
type_info: &TypeInfo,
mem_set: &BTreeSet<usize>,
w: &mut dyn Write,
) -> Result<()> {
write!(w, "local function run_init_code()")?;
write_table_list(wasm, w)?;
write_memory_list(wasm, w)?;
write_global_list(wasm, type_info, w)?;
write_element_list(wasm, type_info, w)?;
write_data_list(wasm, type_info, w)?;
write!(w, "end ")?;
write!(w, "return function(wasm)")?;
write_import_list(wasm, w)?;
write!(w, "run_init_code()")?;
for mem in mem_set {
write!(w, "memory_at_{mem} = MEMORY_LIST[{mem}]")?;
}
if let Some(start) = wasm.start_section() {
write!(w, "FUNC_LIST[{start}]()")?;
}
write!(w, "return {{")?;
write_export_list(wasm, w)?;
write!(w, "}} end ")
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_inst_list(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
Builder::from_type_info(type_info)
.build_anonymous(code)
.write(&mut Manager::default(), w)
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_module_typed(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
let func_list = build_func_list(wasm, type_info);
let mem_set = write_localize_used(&func_list, w)?;
write_named_array("FUNC_LIST", wasm.functions_space(), w)?;
write_named_array("TABLE_LIST", wasm.table_space(), w)?;
write_named_array("MEMORY_LIST", wasm.memory_space(), w)?;
write_named_array("GLOBAL_LIST", wasm.globals_space(), w)?;
write_func_list(wasm, type_info, &func_list, w)?;
write_module_start(wasm, type_info, &mem_set, w)
}
/// # Errors
/// Returns `Err` if writing to `Write` failed.
pub fn from_module_untyped(wasm: &Module, w: &mut dyn Write) -> Result<()> {
let type_info = TypeInfo::from_module(wasm);
from_module_typed(wasm, &type_info, w)
}