Skip to main content

lua_stdlib/
math_lib.rs

1//! Standard mathematical library — `math.*`
2//!
3//! Translated from `src/lmathlib.c` (Lua 5.4.7, 782 lines, 28 functions).
4//!
5//! The PRNG is xoshiro256** operating on four 64-bit words. In C the
6//! implementation has two code paths (64-bit integers vs two 32-bit halves);
7//! Rust always has `u64`, so only the 64-bit path is kept.
8//!
9//! Deprecated compat functions guarded by `LUA_COMPAT_MATHLIB` (cosh, sinh,
10//! tanh, pow, frexp, ldexp, log10, atan2) are omitted; we target Lua 5.4
11//! semantics only. See PORTING.md §13.
12
13// PORT NOTE: All imports below will be unresolved until Phase B lands the
14// lua-types crate. Expected Phase-A errors: E0432, E0412, E0433, E0425.
15use lua_types::{LuaError, LuaType, LuaValue};
16use crate::state_stub::{LuaState, LuaStateStubExt as _, lua_CFunction as LuaCFn, upvalue_index, CompareOp, LuaDebug};
17
18// ── Constants ──────────────────────────────────────────────────────────────
19
20///
21/// Higher precision than `std::f64::consts::PI`; matches the C source literal.
22const PI: f64 = 3.141592653589793238462643383279502884_f64;
23
24/// Number of binary digits in the mantissa of `lua_Number` (f64).
25const FIGS: u32 = 53; // DBL_MANT_DIG for f64
26
27/// Bits to discard from the 64-bit random word before float conversion.
28const SHIFT64_FIG: u32 = 64 - FIGS; // = 11
29
30// ── Type aliases for library registration ─────────────────────────────────
31
32/// A Lua C-style function: takes the Lua state, returns count of pushed values.
33/// PORT NOTE: Phase B will unify with `lua_types::LuaCFunction`.
34type LuaCFunction = fn(&mut LuaState) -> Result<usize, LuaError>;
35
36/// An entry in the library registration table (name, optional function).
37/// `None` is used for placeholder entries whose values are set manually
38/// (e.g. `pi`, `huge`, `maxinteger`, `mininteger`, `random`, `randomseed`).
39/// PORT NOTE: Phase B will unify with `lua_types::LibReg`.
40struct LibReg {
41    name: &'static [u8],
42    func: Option<LuaCFunction>,
43}
44
45// ── PRNG state ────────────────────────────────────────────────────────────
46
47/// State for the xoshiro256** PRNG.
48///
49/// In C this is stored as raw `lua_newuserdatauv` memory and accessed by
50/// casting the userdata pointer. Until typed-userdata closure upvalues land
51/// in Phase B, we keep the PRNG state in a thread-local cell so that
52/// `math.random` and `math.randomseed` are callable from Lua. This collapses
53/// per-lua_State PRNG isolation to per-thread, which is sufficient for the
54/// 5.4 test corpus.
55struct RanState {
56    s: [u64; 4],
57}
58
59thread_local! {
60    static RAN_STATE: std::cell::RefCell<RanState> =
61        std::cell::RefCell::new(RanState { s: [0xff, 0xff, 0xff, 0xff] });
62}
63
64// ── Pure PRNG algorithms ──────────────────────────────────────────────────
65
66/// Advance the xoshiro256** state by one step and return the next raw 64-bit
67/// pseudo-random value.
68///
69fn next_rand(s: &mut [u64; 4]) -> u64 {
70    let s0 = s[0];
71    let s1 = s[1];
72    let s2 = s[2] ^ s0;
73    let s3 = s[3] ^ s1;
74    let res = s1.wrapping_mul(5).rotate_left(7).wrapping_mul(9);
75    s[0] = s0 ^ s3;
76    s[1] = s1 ^ s2;
77    s[2] = s2 ^ (s1 << 17);
78    s[3] = s3.rotate_left(45);
79    res
80}
81
82/// Convert a raw 64-bit PRNG output to a float in [0.0, 1.0).
83///
84/// Takes the top FIGS=53 bits, interprets them as a signed integer, scales
85/// by `scaleFIG = 0.5 / 2^52`, then corrects the two's-complement sign.
86fn rand_to_float(x: u64) -> f64 {
87    let sx = (x >> SHIFT64_FIG) as i64;
88    //            = 0.5 / 2^52
89    let scale_fig: f64 = 0.5 / ((1u64 << (FIGS - 1)) as f64);
90    let mut res = (sx as f64) * scale_fig;
91    if sx < 0 {
92        res += 1.0;
93    }
94    debug_assert!(0.0 <= res && res < 1.0);
95    res
96}
97
98/// Initialise the four PRNG words from two seed values.
99///
100///
101/// PORT NOTE: The Lua pushes (n1, n2) are done at the call site in Rust so
102/// that this function does not need `&mut LuaState`, avoiding a borrow
103/// conflict with the upvalue `RanState`.
104fn set_seed_words(s: &mut [u64; 4], n1: u64, n2: u64) {
105    s[0] = n1;
106    s[1] = 0xff; // avoid a zero state
107    s[2] = n2;
108    s[3] = 0;
109    for _ in 0..16 {
110        next_rand(s); // discard initial values to "spread" seed
111    }
112}
113
114/// Project `ran` uniformly into [0, n].
115///
116///
117/// Uses rejection sampling with the smallest Mersenne number ≥ n as a mask.
118/// Takes `&mut [u64; 4]` rather than `&mut RanState` to avoid nested borrows
119/// at call sites.
120fn project(mut ran: u64, n: u64, s: &mut [u64; 4]) -> u64 {
121    if (n & n.wrapping_add(1)) == 0 {
122        return ran & n;
123    }
124    // Compute the smallest (2^b - 1) not smaller than n.
125    let mut lim = n;
126    lim |= lim >> 1;
127    lim |= lim >> 2;
128    lim |= lim >> 4;
129    lim |= lim >> 8;
130    lim |= lim >> 16;
131    lim |= lim >> 32; // u64 always has 64 bits; C guards this with #if
132    debug_assert!((lim & lim.wrapping_add(1)) == 0); // lim+1 is a power of 2
133    debug_assert!(lim >= n);
134    debug_assert!((lim >> 1) < n);
135    loop {
136        ran &= lim;
137        if ran <= n {
138            break;
139        }
140        ran = next_rand(s);
141    }
142    ran
143}
144
145// ── Helpers ───────────────────────────────────────────────────────────────
146
147/// Convert `d` to integer and push it; push the float unchanged if it doesn't
148/// fit exactly in an i64.
149///
150fn push_num_int(state: &mut LuaState, d: f64) {
151    //    else lua_pushnumber(L, d);
152    //
153    // lua_numbertointeger: d >= LUA_MININTEGER as float &&
154    //                      d <  -(LUA_MININTEGER as float)
155    let min_f = i64::MIN as f64; // -2^63
156    let max_plus1_f = -(i64::MIN as f64); // 2^63 (one past i64::MAX as float)
157    if d >= min_f && d < max_plus1_f {
158        state.push(LuaValue::Int(d as i64));
159    } else {
160        state.push(LuaValue::Float(d));
161    }
162}
163
164// ── Basic math functions ──────────────────────────────────────────────────
165
166/// `math.abs(x)` — absolute value, preserving integer type when possible.
167///
168fn math_abs(state: &mut LuaState) -> Result<usize, LuaError> {
169    if matches!(state.value_at(1), LuaValue::Int(_)) {
170        let n = state.to_integer(1).unwrap_or(0);
171        let n = if n < 0 {
172            (0u64.wrapping_sub(n as u64)) as i64
173        } else {
174            n
175        };
176        state.push(LuaValue::Int(n));
177    } else {
178        let x = state.check_number(1)?;
179        state.push(LuaValue::Float(x.abs()));
180    }
181    Ok(1)
182}
183
184/// `math.sin(x)` — sine (radians).
185///
186fn math_sin(state: &mut LuaState) -> Result<usize, LuaError> {
187    let x = state.check_number(1)?;
188    state.push(LuaValue::Float(x.sin()));
189    Ok(1)
190}
191
192/// `math.cos(x)` — cosine (radians).
193///
194fn math_cos(state: &mut LuaState) -> Result<usize, LuaError> {
195    let x = state.check_number(1)?;
196    state.push(LuaValue::Float(x.cos()));
197    Ok(1)
198}
199
200/// `math.tan(x)` — tangent (radians).
201///
202fn math_tan(state: &mut LuaState) -> Result<usize, LuaError> {
203    let x = state.check_number(1)?;
204    state.push(LuaValue::Float(x.tan()));
205    Ok(1)
206}
207
208/// `math.asin(x)` — arc-sine, result in radians.
209///
210fn math_asin(state: &mut LuaState) -> Result<usize, LuaError> {
211    let x = state.check_number(1)?;
212    state.push(LuaValue::Float(x.asin()));
213    Ok(1)
214}
215
216/// `math.acos(x)` — arc-cosine, result in radians.
217///
218fn math_acos(state: &mut LuaState) -> Result<usize, LuaError> {
219    let x = state.check_number(1)?;
220    state.push(LuaValue::Float(x.acos()));
221    Ok(1)
222}
223
224/// `math.atan(y [, x])` — arc-tangent of y/x (defaults x=1), result in
225/// radians. Subsumes C's `atan2` when x is provided.
226///
227fn math_atan(state: &mut LuaState) -> Result<usize, LuaError> {
228    let y = state.check_number(1)?;
229    let x = state.opt_number(2, 1.0)?;
230    state.push(LuaValue::Float(y.atan2(x)));
231    Ok(1)
232}
233
234/// `math.tointeger(x)` — convert x to an integer or return false.
235///
236fn math_toint(state: &mut LuaState) -> Result<usize, LuaError> {
237    // TODO(port): state.to_integer_opt(1) should return Option<i64>;
238    // the method name/signature will be confirmed in Phase B.
239    let maybe_n: Option<i64> = state.to_integer_opt(1);
240    if let Some(n) = maybe_n {
241        state.push(LuaValue::Int(n));
242    } else {
243        state.check_any(1)?;
244        // PORT NOTE: luaL_pushfail in Lua 5.4 pushes false (not nil).
245        state.push(LuaValue::Bool(false));
246    }
247    Ok(1)
248}
249
250/// `math.floor(x)` — largest integer ≤ x.
251///
252fn math_floor(state: &mut LuaState) -> Result<usize, LuaError> {
253    if matches!(state.value_at(1), LuaValue::Int(_)) {
254        // Must go through the public C-API set_top (relative to the call
255        // frame); the inherent LuaState::set_top treats its argument as an
256        // absolute StackIdx.
257        lua_vm::api::set_top(state, 1)?;
258    } else {
259        let d = state.check_number(1)?.floor();
260        push_num_int(state, d);
261    }
262    Ok(1)
263}
264
265/// `math.ceil(x)` — smallest integer ≥ x.
266///
267fn math_ceil(state: &mut LuaState) -> Result<usize, LuaError> {
268    if matches!(state.value_at(1), LuaValue::Int(_)) {
269        // Public C-API set_top (relative); inherent LuaState::set_top is absolute.
270        lua_vm::api::set_top(state, 1)?;
271    } else {
272        let d = state.check_number(1)?.ceil();
273        push_num_int(state, d);
274    }
275    Ok(1)
276}
277
278/// `math.fmod(x, y)` — floating-point remainder (same sign as x).
279///
280fn math_fmod(state: &mut LuaState) -> Result<usize, LuaError> {
281    if matches!(state.value_at(1), LuaValue::Int(_))
282        && matches!(state.value_at(2), LuaValue::Int(_))
283    {
284        let a = state.to_integer(1).unwrap_or(0);
285        let d = state.to_integer(2).unwrap_or(0);
286        if (d as u64).wrapping_add(1) <= 1 {
287            if d == 0 {
288                return Err(LuaError::arg_error(2, "zero"));
289            }
290            state.push(LuaValue::Int(0));
291        } else {
292            state.push(LuaValue::Int(a % d));
293        }
294    } else {
295        let x = state.check_number(1)?;
296        let y = state.check_number(2)?;
297        state.push(LuaValue::Float(x % y));
298    }
299    Ok(1)
300}
301
302/// `math.modf(x)` — split into integer and fractional parts; returns 2 values.
303///
304///
305/// PORT NOTE: Does not use `modf` (avoids `double *` / `float *` ABI mismatch
306/// for non-double `lua_Number`). Instead, uses ceil/floor + subtraction.
307fn math_modf(state: &mut LuaState) -> Result<usize, LuaError> {
308    if matches!(state.value_at(1), LuaValue::Int(_)) {
309        // Public C-API set_top (relative); inherent LuaState::set_top is absolute.
310        lua_vm::api::set_top(state, 1)?; // integer part is the integer itself
311        state.push(LuaValue::Float(0.0)); // no fractional part
312    } else {
313        let n = state.check_number(1)?;
314        let ip = if n < 0.0 { n.ceil() } else { n.floor() };
315        push_num_int(state, ip);
316        let frac = if n == ip { 0.0 } else { n - ip };
317        state.push(LuaValue::Float(frac));
318    }
319    Ok(2)
320}
321
322/// `math.sqrt(x)` — square root.
323///
324fn math_sqrt(state: &mut LuaState) -> Result<usize, LuaError> {
325    let x = state.check_number(1)?;
326    state.push(LuaValue::Float(x.sqrt()));
327    Ok(1)
328}
329
330/// `math.ult(m, n)` — unsigned less-than on integers.
331///
332fn math_ult(state: &mut LuaState) -> Result<usize, LuaError> {
333    let a = state.check_integer(1)?;
334    let b = state.check_integer(2)?;
335    state.push(LuaValue::Bool((a as u64) < (b as u64)));
336    Ok(1)
337}
338
339/// `math.log(x [, base])` — logarithm; natural if base omitted.
340///
341fn math_log(state: &mut LuaState) -> Result<usize, LuaError> {
342    let x = state.check_number(1)?;
343    let res = if matches!(state.type_at(2), LuaType::None | LuaType::Nil) {
344        x.ln()
345    } else {
346        let base = state.check_number(2)?;
347        if base == 2.0 {
348            x.log2()
349        } else if base == 10.0 {
350            x.log10()
351        } else {
352            x.ln() / base.ln()
353        }
354    };
355    state.push(LuaValue::Float(res));
356    Ok(1)
357}
358
359/// `math.exp(x)` — e raised to the power x.
360///
361fn math_exp(state: &mut LuaState) -> Result<usize, LuaError> {
362    let x = state.check_number(1)?;
363    state.push(LuaValue::Float(x.exp()));
364    Ok(1)
365}
366
367/// `math.deg(x)` — convert radians to degrees.
368///
369fn math_deg(state: &mut LuaState) -> Result<usize, LuaError> {
370    let x = state.check_number(1)?;
371    state.push(LuaValue::Float(x * (180.0 / PI)));
372    Ok(1)
373}
374
375/// `math.rad(x)` — convert degrees to radians.
376///
377fn math_rad(state: &mut LuaState) -> Result<usize, LuaError> {
378    let x = state.check_number(1)?;
379    state.push(LuaValue::Float(x * (PI / 180.0)));
380    Ok(1)
381}
382
383/// `math.min(x, ...)` — minimum of all arguments (uses Lua `<` comparison).
384///
385fn math_min(state: &mut LuaState) -> Result<usize, LuaError> {
386    let n = state.get_top();
387    let mut imin: i32 = 1;
388    if n < 1 {
389        return Err(LuaError::arg_error(1, "value expected"));
390    }
391    for i in 2..=n {
392        if state.compare_lt(i, imin)? {
393            imin = i;
394        }
395    }
396    state.push_value(imin)?;
397    Ok(1)
398}
399
400/// `math.max(x, ...)` — maximum of all arguments (uses Lua `<` comparison).
401///
402fn math_max(state: &mut LuaState) -> Result<usize, LuaError> {
403    let n = state.get_top();
404    let mut imax: i32 = 1;
405    if n < 1 {
406        return Err(LuaError::arg_error(1, "value expected"));
407    }
408    for i in 2..=n {
409        if state.compare_lt(imax, i)? {
410            imax = i;
411        }
412    }
413    state.push_value(imax)?;
414    Ok(1)
415}
416
417/// `math.type(x)` — return `"integer"`, `"float"`, or false for non-numbers.
418///
419fn math_type(state: &mut LuaState) -> Result<usize, LuaError> {
420    if matches!(state.type_at(1), LuaType::Number) {
421        if matches!(state.value_at(1), LuaValue::Int(_)) {
422            state.push_string(b"integer");
423        } else {
424            state.push_string(b"float");
425        }
426    } else {
427        state.check_any(1)?;
428        // PORT NOTE: luaL_pushfail pushes false in Lua 5.4.4+.
429        state.push(LuaValue::Bool(false));
430    }
431    Ok(1)
432}
433
434// ── PRNG-backed Lua functions ─────────────────────────────────────────────
435
436/// `math.random([m [, n]])` — pseudo-random number generation.
437///
438///
439/// With no arguments: float in [0, 1).
440/// With one argument n: integer in [1, n] (or full random u64 if n == 0).
441/// With two arguments m, n: integer in [m, n].
442fn math_random(state: &mut LuaState) -> Result<usize, LuaError> {
443    // TODO(port): RanState is stored as typed userdata in closure upvalue 1.
444    // Phase B must implement `state.upvalue_userdata_mut::<RanState>(1)` using
445    // interior mutability (e.g. GcRef<RefCell<RanState>>) to avoid the borrow
446    // conflict between &mut RanState and subsequent &mut LuaState push calls.
447    //
448    // For Phase A: advance PRNG and get args via separate borrows.
449    let rv = advance_prng(state)?;
450    let n_args = state.get_top();
451
452    if n_args == 0 {
453        state.push(LuaValue::Float(rand_to_float(rv)));
454        return Ok(1);
455    }
456
457    let (low, up) = match n_args {
458        1 => {
459            let up = state.check_integer(1)?;
460            if up == 0 {
461                // I2UInt(rv) = rv (trivial for u64)
462                state.push(LuaValue::Int(rv as i64));
463                return Ok(1);
464            }
465            (1i64, up)
466        }
467        2 => {
468            let low = state.check_integer(1)?;
469            let up = state.check_integer(2)?;
470            (low, up)
471        }
472        _ => {
473            return Err(LuaError::runtime(format_args!(
474                "wrong number of arguments"
475            )));
476        }
477    };
478
479    if low > up {
480        return Err(LuaError::arg_error(1, "interval is empty"));
481    }
482
483    let range = (up as u64).wrapping_sub(low as u64);
484    let p = project_from_upvalue(state, rv, range)?;
485    state.push(LuaValue::Int((p as u64).wrapping_add(low as u64) as i64));
486    Ok(1)
487}
488
489/// `math.randomseed([x [, y]])` — seed the PRNG; returns two seed values.
490///
491fn math_randomseed(state: &mut LuaState) -> Result<usize, LuaError> {
492    // TODO(port): same upvalue userdata access issue as math_random.
493    if matches!(state.type_at(1), LuaType::None) {
494        // randseed uses time(NULL) and address of L for entropy.
495        apply_random_seed(state)?;
496    } else {
497        //    lua_Integer n2 = luaL_optinteger(L, 2, 0);
498        let n1 = state.check_integer(1)? as u64;
499        let n2 = state.opt_integer(2, 0)? as u64;
500        apply_set_seed(state, n1, n2)?;
501    }
502    Ok(2)
503}
504
505/// Advance the PRNG stored in the thread-local `RAN_STATE` and return the
506/// raw 64-bit output.
507///
508/// PORT NOTE: In C this draws from the userdata in closure upvalue 1. The
509/// Rust port stores the PRNG state in a thread-local until typed-userdata
510/// closure upvalues are wired up. Storage location is the only difference;
511/// the algorithm is unchanged.
512fn advance_prng(_state: &mut LuaState) -> Result<u64, LuaError> {
513    Ok(RAN_STATE.with(|r| next_rand(&mut r.borrow_mut().s)))
514}
515
516/// Apply rejection sampling for `math.random` using the thread-local PRNG.
517///
518/// PORT NOTE: see `advance_prng` for the thread-local rationale.
519fn project_from_upvalue(
520    _state: &mut LuaState,
521    ran: u64,
522    n: u64,
523) -> Result<u64, LuaError> {
524    Ok(RAN_STATE.with(|r| project(ran, n, &mut r.borrow_mut().s)))
525}
526
527/// Seed the PRNG from wall-clock time (entropy source).
528///
529///
530/// TODO(port): must write n1 and n2 back to the upvalue RanState.
531fn apply_random_seed(state: &mut LuaState) -> Result<(), LuaError> {
532    // PORT NOTE: std::time is not in the banned list (only std::fs/net/process).
533    let seed1 = std::time::SystemTime::now()
534        .duration_since(std::time::UNIX_EPOCH)
535        .map(|d| d.as_secs())
536        .unwrap_or(0);
537    // TODO(port): C uses address of L for ASLR entropy; no safe equivalent.
538    // Phase B can use a thread-local counter or OS entropy instead.
539    let seed2: u64 = 0;
540    apply_set_seed(state, seed1, seed2)
541}
542
543/// Apply explicit seeds to the PRNG and push them onto the stack.
544///
545///
546/// PORT NOTE: writes seeds into the thread-local RanState (see `advance_prng`).
547fn apply_set_seed(state: &mut LuaState, n1: u64, n2: u64) -> Result<(), LuaError> {
548    RAN_STATE.with(|r| set_seed_words(&mut r.borrow_mut().s, n1, n2));
549    state.push(LuaValue::Int(n1 as i64));
550    state.push(LuaValue::Int(n2 as i64));
551    Ok(())
552}
553
554/// Register `math.random` and `math.randomseed` on the math library table at
555/// stack top, after seeding the thread-local PRNG.
556///
557///
558/// PORT NOTE: C stores the PRNG inside a userdata bound as upvalue 1 of both
559/// closures. Until typed userdata closure upvalues are available, the Rust
560/// port keeps the PRNG in a thread-local (see `RAN_STATE`) and registers the
561/// functions as plain non-closure entries on the library table.
562fn set_rand_func(state: &mut LuaState) -> Result<(), LuaError> {
563    apply_random_seed(state)?;
564    state.pop_n(2);
565
566    state.push_c_function(math_random)?;
567    state.set_field(-2, b"random")?;
568    state.push_c_function(math_randomseed)?;
569    state.set_field(-2, b"randomseed")?;
570    Ok(())
571}
572
573// ── Library registration table ────────────────────────────────────────────
574
575/// The `math` library function table.
576///
577///
578/// Placeholder entries (`None`) are filled in manually by `luaopen_math`
579/// (`pi`, `huge`, `maxinteger`, `mininteger`) or by `set_rand_func`
580/// (`random`, `randomseed`).
581static MATHLIB: &[LibReg] = &[
582    LibReg { name: b"abs",        func: Some(math_abs)    },
583    LibReg { name: b"acos",       func: Some(math_acos)   },
584    LibReg { name: b"asin",       func: Some(math_asin)   },
585    LibReg { name: b"atan",       func: Some(math_atan)   },
586    LibReg { name: b"ceil",       func: Some(math_ceil)   },
587    LibReg { name: b"cos",        func: Some(math_cos)    },
588    LibReg { name: b"deg",        func: Some(math_deg)    },
589    LibReg { name: b"exp",        func: Some(math_exp)    },
590    LibReg { name: b"tointeger",  func: Some(math_toint)  },
591    LibReg { name: b"floor",      func: Some(math_floor)  },
592    LibReg { name: b"fmod",       func: Some(math_fmod)   },
593    LibReg { name: b"ult",        func: Some(math_ult)    },
594    LibReg { name: b"log",        func: Some(math_log)    },
595    LibReg { name: b"max",        func: Some(math_max)    },
596    LibReg { name: b"min",        func: Some(math_min)    },
597    LibReg { name: b"modf",       func: Some(math_modf)   },
598    LibReg { name: b"rad",        func: Some(math_rad)    },
599    LibReg { name: b"sin",        func: Some(math_sin)    },
600    LibReg { name: b"sqrt",       func: Some(math_sqrt)   },
601    LibReg { name: b"tan",        func: Some(math_tan)    },
602    LibReg { name: b"type",       func: Some(math_type)   },
603    // Placeholders; values are set manually in luaopen_math / set_rand_func.
604    LibReg { name: b"random",     func: None },
605    LibReg { name: b"randomseed", func: None },
606    LibReg { name: b"pi",         func: None },
607    LibReg { name: b"huge",       func: None },
608    LibReg { name: b"maxinteger", func: None },
609    LibReg { name: b"mininteger", func: None },
610];
611
612static MATHLIB_FUNCS: &[(&[u8], LuaCFunction)] = &[
613    (b"abs",        math_abs),
614    (b"acos",       math_acos),
615    (b"asin",       math_asin),
616    (b"atan",       math_atan),
617    (b"ceil",       math_ceil),
618    (b"cos",        math_cos),
619    (b"deg",        math_deg),
620    (b"exp",        math_exp),
621    (b"tointeger",  math_toint),
622    (b"floor",      math_floor),
623    (b"fmod",       math_fmod),
624    (b"ult",        math_ult),
625    (b"log",        math_log),
626    (b"max",        math_max),
627    (b"min",        math_min),
628    (b"modf",       math_modf),
629    (b"rad",        math_rad),
630    (b"sin",        math_sin),
631    (b"sqrt",       math_sqrt),
632    (b"tan",        math_tan),
633    (b"type",       math_type),
634];
635
636// ── Module entry point ────────────────────────────────────────────────────
637
638/// Open the `math` library: create the table, populate constants, register
639/// the PRNG functions with their shared `RanState` upvalue.
640///
641///
642/// `LUAMOD_API` → `pub` (see macros.tsv).
643pub fn luaopen_math(state: &mut LuaState) -> Result<usize, LuaError> {
644    // Creates a new table and registers all non-None entries from MATHLIB.
645    state.new_lib(MATHLIB_FUNCS)?;
646
647    state.push(LuaValue::Float(PI));
648    state.set_field(-2, b"pi")?;
649
650    state.push(LuaValue::Float(f64::INFINITY));
651    state.set_field(-2, b"huge")?;
652
653    // LUA_MAXINTEGER = i64::MAX (lua_Integer is int64_t in default config).
654    state.push(LuaValue::Int(i64::MAX));
655    state.set_field(-2, b"maxinteger")?;
656
657    state.push(LuaValue::Int(i64::MIN));
658    state.set_field(-2, b"mininteger")?;
659
660    // Registers math.random and math.randomseed as upvalue-bearing closures.
661    set_rand_func(state)?;
662
663    Ok(1)
664}
665
666// ──────────────────────────────────────────────────────────────────────────
667// PORT STATUS
668//   source:        src/lmathlib.c  (782 lines, 28 functions)
669//   target_crate:  lua-stdlib
670//   confidence:    medium
671//   todos:         16
672//   port_notes:    8
673//   unsafe_blocks: 0
674//   notes:         All basic math functions are mechanically faithful. The
675//                  PRNG xoshiro256** algorithm is correctly translated using
676//                  native u64 (only the 64-bit code path; the 32-bit fallback
677//                  is dropped). The main Phase-B work is wiring up the upvalue
678//                  RanState userdata: advance_prng, project_from_upvalue,
679//                  apply_random_seed, apply_set_seed, and set_rand_func all
680//                  carry TODO(port) stubs where typed userdata + interior
681//                  mutability (RefCell) is required to avoid borrow conflicts.
682//                  Deprecated LUA_COMPAT_MATHLIB functions are omitted per
683//                  PORTING.md §13. state.new_lib, state.set_field,
684//                  state.compare_lt, state.push_value, state.opt_number,
685//                  state.opt_integer, state.check_integer, state.check_number,
686//                  state.check_any, state.to_integer_opt, state.get_top,
687//                  state.set_top, state.pop_n API names assumed; Phase B
688//                  will reconcile with the actual LuaState impl.
689// ──────────────────────────────────────────────────────────────────────────