Skip to main content

rhue_bytecode/
arith.rs

1//! Arithmetic, all in one place.
2//!
3//! The constant folder and the VM both go through [`arith`], so a folded
4//! expression and a run one come out bit-for-bit the same.
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub enum ArithOp {
8    Add,
9    Sub,
10    Mul,
11    Div,
12    IDiv,
13    Mod,
14    Pow,
15}
16
17impl ArithOp {
18    /// The name Luau puts in "attempt to perform arithmetic (add) on ..."
19    /// errors.
20    pub fn name(self) -> &'static str {
21        match self {
22            ArithOp::Add => "add",
23            ArithOp::Sub => "sub",
24            ArithOp::Mul => "mul",
25            ArithOp::Div => "div",
26            ArithOp::IDiv => "idiv",
27            ArithOp::Mod => "mod",
28            ArithOp::Pow => "pow",
29        }
30    }
31}
32
33/// Luau's number semantics, IEEE-754 doubles all the way.
34///
35/// - `a // b` is `floor(a / b)`.
36/// - `a % b` is `a - floor(a / b) * b`, so the result takes the divisor's sign.
37/// - Dividing by zero gives ±inf or NaN, it's not an error.
38#[inline]
39pub fn arith(op: ArithOp, a: f64, b: f64) -> f64 {
40    match op {
41        ArithOp::Add => a + b,
42        ArithOp::Sub => a - b,
43        ArithOp::Mul => a * b,
44        ArithOp::Div => a / b,
45        ArithOp::IDiv => floor(a / b),
46        ArithOp::Mod => a - floor(a / b) * b,
47        ArithOp::Pow => a.powf(b),
48    }
49}
50
51/// `x.floor()` without the libm call baseline x86-64 (no SSE4.1) turns
52/// `f64::floor` into. Matches `f64::floor` exactly for every input, signed
53/// zeros, infinities and NaN included.
54#[inline]
55pub fn floor(x: f64) -> f64 {
56    // from 2^52 up every double is already an integer (and the cast below would
57    // saturate), so only smaller ones need work
58    if x.abs() < 4_503_599_627_370_496.0 {
59        #[expect(
60            clippy::cast_possible_truncation,
61            reason = "under 2^52, checked just above"
62        )]
63        let t = x as i64 as f64;
64        // truncation rounds toward zero, so negative non-integers need one
65        // less. the only zero result from a negative input is floor(-0.0) =
66        // -0.0, and `copysign` puts back the sign the cast lost
67        (if t > x { t - 1.0 } else { t }).copysign(x)
68    } else {
69        x
70    }
71}
72
73/// Formats a number like Luau's `tostring`: whole numbers print without a
74/// fraction (`3`), others use the shortest form that round-trips (`0.1`), and
75/// really big or small ones get an exponent (`1e+20`).
76pub fn format_number(n: f64) -> String {
77    if n.is_nan() {
78        return if n.is_sign_negative() {
79            "-nan".into()
80        } else {
81            "nan".into()
82        };
83    }
84    if n.is_infinite() {
85        return if n > 0.0 { "inf".into() } else { "-inf".into() };
86    }
87    if n == 0.0 {
88        return if n.is_sign_negative() {
89            "-0".into()
90        } else {
91            "0".into()
92        };
93    }
94    let abs = n.abs();
95    if (1e-5..1e16).contains(&abs) {
96        return format!("{n}");
97    }
98    // `{:e}` gives "1e20" / "1.5e-7", Luau writes "1e+20" / "1.5e-07"
99    let s = format!("{n:e}");
100    let (mantissa, exp) = s.split_once('e').expect("`{:e}` always has an exponent");
101    let (sign, digits) = match exp.strip_prefix('-') {
102        Some(d) => ('-', d),
103        None => ('+', exp),
104    };
105    format!("{mantissa}e{sign}{digits:0>2}")
106}
107
108#[cfg(test)]
109mod tests {
110
111    #[test]
112    fn floor_matches_f64_floor_bit_for_bit() {
113        let mut xs = vec![
114            0.0,
115            -0.0,
116            0.5,
117            -0.5,
118            1.0,
119            -1.0,
120            1.5,
121            -1.5,
122            2.0f64.powi(52),
123            -(2.0f64.powi(52)),
124            2.0f64.powi(52) - 0.5,
125            -(2.0f64.powi(52)) + 0.5,
126            1e300,
127            -1e300,
128            f64::MIN_POSITIVE,
129            -f64::MIN_POSITIVE,
130            f64::INFINITY,
131            f64::NEG_INFINITY,
132            f64::NAN,
133            f64::MAX,
134            f64::MIN,
135            9.007199254740993e15,
136            -9.007199254740993e15,
137            0.9999999999999999,
138            -0.9999999999999999,
139        ];
140        // a deterministic spread over lots of magnitudes
141        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
142        for _ in 0..200_000 {
143            seed ^= seed << 13;
144            seed ^= seed >> 7;
145            seed ^= seed << 17;
146            xs.push(f64::from_bits(seed));
147            xs.push((seed % 2_000_001) as f64 / 1000.0 - 1000.0);
148        }
149        for x in xs {
150            let (want, got) = (x.floor(), floor(x));
151            assert!(
152                want.to_bits() == got.to_bits() || (want.is_nan() && got.is_nan()),
153                "floor({x:e}) = {got:e}, want {want:e}"
154            );
155        }
156    }
157    use super::*;
158    use ArithOp::*;
159
160    #[test]
161    fn floor_division_and_modulo_follow_luau() {
162        assert_eq!(arith(IDiv, 7.0, 2.0), 3.0);
163        assert_eq!(arith(IDiv, -7.0, 2.0), -4.0);
164        assert_eq!(arith(Mod, 7.0, 3.0), 1.0);
165        assert_eq!(arith(Mod, -7.0, 3.0), 2.0);
166        assert_eq!(arith(Mod, 7.0, -3.0), -2.0);
167        assert_eq!(arith(Mod, 5.5, 2.0), 1.5);
168    }
169
170    #[test]
171    fn division_by_zero_is_not_an_error() {
172        assert_eq!(arith(Div, 1.0, 0.0), f64::INFINITY);
173        assert_eq!(arith(Div, -1.0, 0.0), f64::NEG_INFINITY);
174        assert!(arith(Div, 0.0, 0.0).is_nan());
175        assert!(arith(Mod, 1.0, 0.0).is_nan());
176    }
177
178    #[test]
179    fn pow() {
180        assert_eq!(arith(Pow, 2.0, 10.0), 1024.0);
181        assert_eq!(arith(Pow, 2.0, -1.0), 0.5);
182    }
183
184    #[test]
185    fn number_formatting() {
186        let cases = [
187            (3.0, "3"),
188            (-3.0, "-3"),
189            (0.1, "0.1"),
190            (3.5, "3.5"),
191            (0.0, "0"),
192            (-0.0, "-0"),
193            (1e15, "1000000000000000"),
194            (1e16, "1e+16"),
195            (1e20, "1e+20"),
196            (1.5e-7, "1.5e-07"),
197            (0.00001, "0.00001"),
198            (123456.789, "123456.789"),
199            (f64::INFINITY, "inf"),
200            (f64::NEG_INFINITY, "-inf"),
201            (1e300, "1e+300"),
202            (2f64.powi(53), "9007199254740992"),
203        ];
204        for (n, want) in cases {
205            assert_eq!(format_number(n), want, "formatting {n:?}");
206        }
207        assert_eq!(format_number(f64::NAN), "nan");
208    }
209}