use crate::arith::{self, Prim};
use crate::compare;
use crate::heap::Heap;
use crate::id::LuaFault;
use crate::index::metamethod;
use crate::opcode::{ArithOp, CmpKind};
use crate::value::Value;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Step {
Done(Value),
Call(Value),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Truth {
Done(bool),
Call(Value),
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Joined {
Bytes(Vec<u8>),
TooLong,
NoRoom(usize),
Call(Value),
}
pub(crate) fn arith(heap: &Heap, op: ArithOp, a: Value, b: Value) -> Result<Step, LuaFault> {
match arith::binary(op, a, b)? {
Prim::Value(value) => Ok(Step::Done(value)),
Prim::Meta(fault) => either(heap, a, b, op.event()).map(Step::Call).ok_or(fault),
}
}
pub(crate) fn negate(heap: &Heap, a: Value) -> Result<Step, LuaFault> {
unary(heap, arith::negate(a), a, b"__unm")
}
pub(crate) fn bnot(heap: &Heap, a: Value) -> Result<Step, LuaFault> {
unary(heap, arith::bnot(a), a, b"__bnot")
}
fn unary(heap: &Heap, primitive: Prim, a: Value, event: &[u8]) -> Result<Step, LuaFault> {
match primitive {
Prim::Value(value) => Ok(Step::Done(value)),
Prim::Meta(fault) => metamethod(heap, a, event).map(Step::Call).ok_or(fault),
}
}
pub(crate) fn concat(heap: &Heap, a: Value, b: Value) -> Result<Joined, LuaFault> {
match crate::concat::concat(heap, a, b) {
Some(Ok(bytes)) => return Ok(Joined::Bytes(bytes)),
Some(Err(crate::concat::Refused::TooLong)) => return Ok(Joined::TooLong),
Some(Err(crate::concat::Refused::NoRoom(len))) => return Ok(Joined::NoRoom(len)),
None => {}
}
either(heap, a, b, b"__concat")
.map(Joined::Call)
.ok_or(LuaFault::Concat)
}
pub(crate) fn compare(heap: &Heap, kind: CmpKind, a: Value, b: Value) -> Result<Truth, LuaFault> {
let (primitive, event) = match kind {
CmpKind::Eq | CmpKind::Ne => {
if compare::equal(heap, a, b) {
return Ok(Truth::Done(true));
}
if !matches!(
(a, b),
(Value::Table(_), Value::Table(_)) | (Value::Userdata(_), Value::Userdata(_))
) {
return Ok(Truth::Done(false));
}
return Ok(either(heap, a, b, b"__eq").map_or(Truth::Done(false), Truth::Call));
}
CmpKind::Lt => (compare::less_than(heap, a, b), b"__lt"),
CmpKind::Le => (compare::less_equal(heap, a, b), b"__le"),
};
match primitive {
Ok(bit) => Ok(Truth::Done(bit)),
Err(fault) => either(heap, a, b, event).map(Truth::Call).ok_or(fault),
}
}
fn either(heap: &Heap, a: Value, b: Value, event: &[u8]) -> Option<Value> {
metamethod(heap, a, event).or_else(|| metamethod(heap, b, event))
}