use crate::host::{Builtin, HostRegistry};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum MathFn {
Abs,
Acos,
Asin,
Atan,
Ceil,
Cos,
Deg,
Exp,
Floor,
Fmod,
Log,
Max,
Min,
Modf,
Rad,
Random,
RandomSeed,
Sin,
Sqrt,
Tan,
ToInteger,
Type,
Ult,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TableFn {
Concat,
Insert,
Move,
Pack,
Remove,
Sort,
Unpack,
}
pub(crate) const MATH_FUNCTIONS: [(&str, &str, MathFn); 23] = [
("abs", "math.abs", MathFn::Abs),
("acos", "math.acos", MathFn::Acos),
("asin", "math.asin", MathFn::Asin),
("atan", "math.atan", MathFn::Atan),
("ceil", "math.ceil", MathFn::Ceil),
("cos", "math.cos", MathFn::Cos),
("deg", "math.deg", MathFn::Deg),
("exp", "math.exp", MathFn::Exp),
("floor", "math.floor", MathFn::Floor),
("fmod", "math.fmod", MathFn::Fmod),
("log", "math.log", MathFn::Log),
("max", "math.max", MathFn::Max),
("min", "math.min", MathFn::Min),
("modf", "math.modf", MathFn::Modf),
("rad", "math.rad", MathFn::Rad),
("random", "math.random", MathFn::Random),
("randomseed", "math.randomseed", MathFn::RandomSeed),
("sin", "math.sin", MathFn::Sin),
("sqrt", "math.sqrt", MathFn::Sqrt),
("tan", "math.tan", MathFn::Tan),
("tointeger", "math.tointeger", MathFn::ToInteger),
("type", "math.type", MathFn::Type),
("ult", "math.ult", MathFn::Ult),
];
pub(crate) const TABLE_FUNCTIONS: [(&str, &str, TableFn); 7] = [
("concat", "table.concat", TableFn::Concat),
("insert", "table.insert", TableFn::Insert),
("move", "table.move", TableFn::Move),
("pack", "table.pack", TableFn::Pack),
("remove", "table.remove", TableFn::Remove),
("sort", "table.sort", TableFn::Sort),
("unpack", "table.unpack", TableFn::Unpack),
];
pub fn register_math(registry: &mut HostRegistry) {
for (_, symbol, function) in MATH_FUNCTIONS {
registry.register_builtin(symbol, Builtin::Math(function));
}
}
pub fn register_table(registry: &mut HostRegistry) {
for (_, symbol, function) in TABLE_FUNCTIONS {
registry.register_builtin(symbol, Builtin::Table(function));
}
}
pub fn register_standard(registry: &mut HostRegistry) {
crate::base::register_base(registry);
crate::oslib::register_os(registry);
register_math(registry);
register_table(registry);
crate::strlib::register_string(registry);
crate::utf8lib::register_utf8(registry);
crate::package::register_package(registry);
crate::corolib::register_coroutine(registry);
crate::iolib::register_io(registry);
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct LibraryState {
pub(crate) rng: [u64; 4],
pub(crate) entropy: u64,
}
impl LibraryState {
pub(crate) fn new(entropy: u64) -> Self {
let mut state = Self {
rng: [0; 4],
entropy,
};
state.seed(0, 0);
state
}
pub(crate) fn draw(&mut self) -> u64 {
self.entropy = self.entropy.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.entropy;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
pub(crate) fn seed(&mut self, n1: u64, n2: u64) {
self.rng = [n1, 0xff, n2, 0];
for _ in 0..16 {
self.next();
}
}
pub(crate) fn next(&mut self) -> u64 {
let [s0, s1, s2, s3] = self.rng;
let s2 = s2 ^ s0;
let s3 = s3 ^ s1;
let result = s1.wrapping_mul(5).rotate_left(7).wrapping_mul(9);
self.rng = [s0 ^ s3, s1 ^ s2, s2 ^ (s1 << 17), s3.rotate_left(45)];
result
}
pub(crate) fn project(&mut self, mut random: u64, n: u64) -> u64 {
if n & n.wrapping_add(1) == 0 {
return random & n;
}
let mut lim = n;
lim |= lim >> 1;
lim |= lim >> 2;
lim |= lim >> 4;
lim |= lim >> 8;
lim |= lim >> 16;
lim |= lim >> 32;
loop {
random &= lim;
if random <= n {
return random;
}
random = self.next();
}
}
}
pub(crate) fn unit_float(random: u64) -> f64 {
(random >> 11) as f64 * (0.5 / (1u64 << 52) as f64)
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LibTask {
pub(crate) work: Work,
pub(crate) wait: Wait,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Wait {
Nothing,
Get { into: u32 },
Set,
Len,
Truth,
Pair { into: u32 },
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Work {
Extreme {
max: bool,
best: u32,
next: u32,
},
Insert {
stage: Stage,
pos: i64,
i: i64,
},
Remove {
stage: Stage,
size: i64,
pos: i64,
},
Move {
stage: Stage,
f: i64,
t: i64,
n: i64,
i: i64,
backward: bool,
},
Concat {
stage: Stage,
i: i64,
last: i64,
text: Vec<u8>,
},
Pack {
stage: Stage,
next: u32,
},
Unpack {
stage: Stage,
first: i64,
count: u32,
got: u32,
},
Sort(Box<SortState>),
Str(Box<crate::strlib::StrWork>),
Utf8(Box<crate::utf8lib::Utf8Work>),
Os(Box<crate::oslib::OsWork>),
Package(Box<crate::package::PackageWork>),
Debug(Box<crate::debuglib::DebugWork>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stage {
Start,
Length,
First,
Read,
Write,
Last,
Equal,
Done,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SortState {
pub(crate) step: SortStep,
pub(crate) n: u32,
pub(crate) lo: u32,
pub(crate) up: u32,
pub(crate) p: u32,
pub(crate) i: u32,
pub(crate) j: u32,
pub(crate) rnd: u32,
pub(crate) pending: Vec<SortRange>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SortRange {
pub(crate) lo: u32,
pub(crate) up: u32,
pub(crate) smaller: u32,
pub(crate) rnd: u32,
}
pub(crate) fn closure_fits(
heap: &crate::heap::Heap,
builtin: crate::host::Builtin,
values: &[crate::value::Value],
state: &[i64],
) -> bool {
match builtin {
crate::host::Builtin::String(crate::strlib::StrFn::GmatchStep) => {
crate::runtime::gmatch_fits(heap, values, state)
}
crate::host::Builtin::Package(
crate::package::PkgFn::Require | crate::package::PkgFn::SearchLua,
) => matches!(values, [crate::value::Value::Table(_)]) && state.is_empty(),
crate::host::Builtin::Coroutine(crate::corolib::CoFn::WrapCall) => {
matches!(values, [crate::value::Value::Thread(_)]) && state.is_empty()
}
crate::host::Builtin::Io(crate::iolib::IoFn::LinesStep) => {
crate::runtime::io::lines_fits(heap, values, state)
}
_ => false,
}
}
pub(crate) const MAX_SORT_PENDING: usize = 40;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SortStep {
Length,
Range,
GetLo,
GetUp,
UpLessLo,
SetLoUp,
SetUpLo,
GetP,
GetLo2,
PLessLo,
SetPLo,
SetLoP,
GetUp2,
UpLessP,
SetPUp,
SetUpP,
GetPivot,
GetUpMinus1,
SetPToUpMinus1,
SetUpMinus1ToPivot,
GetI,
ILessPivot,
GetJ,
PivotLessJ,
SetIJ,
SetJI,
SetUpMinus1I,
SetIPivot,
}
impl Work {
pub(crate) fn scratch(&self) -> u32 {
match self {
Self::Extreme { .. } => 0,
Self::Insert { .. } | Self::Move { .. } | Self::Concat { .. } | Self::Pack { .. } => 1,
Self::Remove { .. } => 2,
Self::Unpack { count, .. } => *count,
Self::Str(work) => work.scratch(),
Self::Utf8(work) => work.scratch(),
Self::Os(_) => 10,
Self::Package(work) => work.scratch(),
Self::Debug(work) => work.scratch(),
Self::Sort(_) => 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xoshiro_matches_the_reference_outputs() {
let mut state = LibraryState::new(0);
state.rng = [1, 2, 3, 4];
let outputs: Vec<u64> = (0..3).map(|_| state.next()).collect();
assert_eq!(outputs, [11520, 0, 1509978240]);
}
#[test]
fn projection_stays_in_range_without_modulo() {
let mut state = LibraryState::new(7);
for n in [0u64, 1, 2, 5, 6, 7, 1000, u64::MAX / 3, u64::MAX] {
for _ in 0..200 {
let random = state.next();
assert!(state.project(random, n) <= n);
}
}
}
}