From c5f7e386c23ac74ea4081945d674c90d45715a29 Mon Sep 17 00:00:00 2001 From: Rerumu Date: Thu, 16 Jun 2022 04:08:52 -0400 Subject: [PATCH] Fix signed remainder assumption --- codegen-luajit/runtime/runtime.lua | 17 +++++++++++++++++ codegen-luajit/src/analyzer/operator.rs | 4 +--- codegen-luajit/src/translator.rs | 4 +++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/codegen-luajit/runtime/runtime.lua b/codegen-luajit/runtime/runtime.lua index e04f031..f0fe2d8 100644 --- a/codegen-luajit/runtime/runtime.lua +++ b/codegen-luajit/runtime/runtime.lua @@ -24,6 +24,7 @@ do local sub = {} local mul = {} local div = {} + local rem = {} local neg = {} local copysign = {} local nearest = {} @@ -78,6 +79,21 @@ do 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 @@ -106,6 +122,7 @@ do module.sub = sub module.mul = mul module.div = div + module.rem = rem module.neg = neg module.copysign = copysign module.nearest = nearest diff --git a/codegen-luajit/src/analyzer/operator.rs b/codegen-luajit/src/analyzer/operator.rs index 2660ac6..64ce47b 100644 --- a/codegen-luajit/src/analyzer/operator.rs +++ b/codegen-luajit/src/analyzer/operator.rs @@ -6,9 +6,7 @@ pub fn bin_symbol_of(op: BinOpType) -> Option<&'static str> { BinOpType::Sub_I64 | BinOpType::Sub_FN => "-", BinOpType::Mul_I64 | BinOpType::Mul_FN => "*", BinOpType::DivS_I64 | BinOpType::Div_FN => "/", - BinOpType::RemS_I32 | BinOpType::RemU_I32 | BinOpType::RemS_I64 | BinOpType::RemU_I64 => { - "%" - } + BinOpType::RemS_I64 => "%", _ => return None, }; diff --git a/codegen-luajit/src/translator.rs b/codegen-luajit/src/translator.rs index d6a8b1a..4f9a70d 100644 --- a/codegen-luajit/src/translator.rs +++ b/codegen-luajit/src/translator.rs @@ -238,7 +238,9 @@ fn write_local_operation(head: &str, tail: &str, w: &mut dyn Write) -> Result<() ("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} "), } }