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        let t = x as i64 as f64;
60        // truncation rounds toward zero, so negative non-integers need one
61        // less. the only zero result from a negative input is floor(-0.0) =
62        // -0.0, and `copysign` puts back the sign the cast lost
63        (if t > x { t - 1.0 } else { t }).copysign(x)
64    } else {
65        x
66    }
67}
68
69/// Formats a number like Luau's `tostring`: whole numbers print without a
70/// fraction (`3`), others use the shortest form that round-trips (`0.1`), and
71/// really big or small ones get an exponent (`1e+20`).
72pub fn format_number(n: f64) -> String {
73    if n.is_nan() {
74        return if n.is_sign_negative() {
75            "-nan".into()
76        } else {
77            "nan".into()
78        };
79    }
80    if n.is_infinite() {
81        return if n > 0.0 { "inf".into() } else { "-inf".into() };
82    }
83    if n == 0.0 {
84        return if n.is_sign_negative() {
85            "-0".into()
86        } else {
87            "0".into()
88        };
89    }
90    let abs = n.abs();
91    if (1e-5..1e16).contains(&abs) {
92        return format!("{n}");
93    }
94    // `{:e}` gives "1e20" / "1.5e-7", Luau writes "1e+20" / "1.5e-07"
95    let s = format!("{n:e}");
96    let (mantissa, exp) = s.split_once('e').expect("`{:e}` always has an exponent");
97    let (sign, digits) = match exp.strip_prefix('-') {
98        Some(d) => ('-', d),
99        None => ('+', exp),
100    };
101    format!("{mantissa}e{sign}{digits:0>2}")
102}
103
104#[cfg(test)]
105mod tests {
106
107    #[test]
108    fn floor_matches_f64_floor_bit_for_bit() {
109        let mut xs = vec![
110            0.0,
111            -0.0,
112            0.5,
113            -0.5,
114            1.0,
115            -1.0,
116            1.5,
117            -1.5,
118            2.0f64.powi(52),
119            -(2.0f64.powi(52)),
120            2.0f64.powi(52) - 0.5,
121            -(2.0f64.powi(52)) + 0.5,
122            1e300,
123            -1e300,
124            f64::MIN_POSITIVE,
125            -f64::MIN_POSITIVE,
126            f64::INFINITY,
127            f64::NEG_INFINITY,
128            f64::NAN,
129            f64::MAX,
130            f64::MIN,
131            9.007199254740993e15,
132            -9.007199254740993e15,
133            0.9999999999999999,
134            -0.9999999999999999,
135        ];
136        // a deterministic spread over lots of magnitudes
137        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
138        for _ in 0..200_000 {
139            seed ^= seed << 13;
140            seed ^= seed >> 7;
141            seed ^= seed << 17;
142            xs.push(f64::from_bits(seed));
143            xs.push((seed % 2_000_001) as f64 / 1000.0 - 1000.0);
144        }
145        for x in xs {
146            let (want, got) = (x.floor(), floor(x));
147            assert!(
148                want.to_bits() == got.to_bits() || (want.is_nan() && got.is_nan()),
149                "floor({x:e}) = {got:e}, want {want:e}"
150            );
151        }
152    }
153    use super::*;
154    use ArithOp::*;
155
156    #[test]
157    fn floor_division_and_modulo_follow_luau() {
158        assert_eq!(arith(IDiv, 7.0, 2.0), 3.0);
159        assert_eq!(arith(IDiv, -7.0, 2.0), -4.0);
160        assert_eq!(arith(Mod, 7.0, 3.0), 1.0);
161        assert_eq!(arith(Mod, -7.0, 3.0), 2.0);
162        assert_eq!(arith(Mod, 7.0, -3.0), -2.0);
163        assert_eq!(arith(Mod, 5.5, 2.0), 1.5);
164    }
165
166    #[test]
167    fn division_by_zero_is_not_an_error() {
168        assert_eq!(arith(Div, 1.0, 0.0), f64::INFINITY);
169        assert_eq!(arith(Div, -1.0, 0.0), f64::NEG_INFINITY);
170        assert!(arith(Div, 0.0, 0.0).is_nan());
171        assert!(arith(Mod, 1.0, 0.0).is_nan());
172    }
173
174    #[test]
175    fn pow() {
176        assert_eq!(arith(Pow, 2.0, 10.0), 1024.0);
177        assert_eq!(arith(Pow, 2.0, -1.0), 0.5);
178    }
179
180    #[test]
181    fn number_formatting() {
182        let cases = [
183            (3.0, "3"),
184            (-3.0, "-3"),
185            (0.1, "0.1"),
186            (3.5, "3.5"),
187            (0.0, "0"),
188            (-0.0, "-0"),
189            (1e15, "1000000000000000"),
190            (1e16, "1e+16"),
191            (1e20, "1e+20"),
192            (1.5e-7, "1.5e-07"),
193            (0.00001, "0.00001"),
194            (123456.789, "123456.789"),
195            (f64::INFINITY, "inf"),
196            (f64::NEG_INFINITY, "-inf"),
197            (1e300, "1e+300"),
198            (2f64.powi(53), "9007199254740992"),
199        ];
200        for (n, want) in cases {
201            assert_eq!(format_number(n), want, "formatting {n:?}");
202        }
203        assert_eq!(format_number(f64::NAN), "nan");
204    }
205}