Skip to main content

logicaffeine_data/
ops.rs

1//! Exact numeric comparison for GENERATED code.
2//!
3//! Mixed Int/Float comparison in LOGOS is EXACT — mathematical values, never
4//! a lossy cast (`i as f64` rounds above 2^53, so a cast-based `==` would
5//! call `9007199254740993` equal to the float `9007199254740992.0`). The AOT
6//! backend emits these helpers for statically-mixed compares; same-type
7//! compares are untouched, so hot loops pay nothing.
8
9pub use logicaffeine_base::numeric::cmp_i64_f64_exact as logos_cmp_i64_f64;
10
11/// `i == f`, exactly (NaN is equal to nothing).
12#[inline]
13pub fn logos_i64_eq_f64(i: i64, f: f64) -> bool {
14    logos_cmp_i64_f64(i, f) == Some(core::cmp::Ordering::Equal)
15}
16
17/// `a is approximately b` — the TOLERANT float comparison (`==` is IEEE
18/// bit-exact). Python's `math.isclose` semantics: relative tolerance 1e-9
19/// (nine significant digits agree) with absolute floor 1e-12 (so values near
20/// zero compare sanely), plus an exact fast path so `inf is approximately
21/// inf` holds. NaN is approximately nothing. ONE definition — the
22/// tree-walker, VM, JIT deopt path, AOT, and WASM lowering all share it.
23#[inline]
24pub fn logos_approx_eq(a: f64, b: f64) -> bool {
25    if a == b {
26        return true;
27    }
28    let diff = (a - b).abs();
29    diff <= f64::max(1e-9 * f64::max(a.abs(), b.abs()), 1e-12)
30}
31
32/// Truthiness for GENERATED code — ONE definition shared with the
33/// interpreter's `RuntimeValue::is_truthy` and the VM's `Value::is_truthy`.
34/// Falsy: `false`, numeric zero (`-0.0` is zero; NaN is nonzero and truthy),
35/// `nothing` (`None`), and empty Text/Seq/Map/Set. Everything else is truthy.
36pub trait Truthy {
37    fn truthy(&self) -> bool;
38}
39
40impl Truthy for bool {
41    #[inline]
42    fn truthy(&self) -> bool {
43        *self
44    }
45}
46
47impl Truthy for i64 {
48    #[inline]
49    fn truthy(&self) -> bool {
50        *self != 0
51    }
52}
53
54impl Truthy for f64 {
55    #[inline]
56    fn truthy(&self) -> bool {
57        *self != 0.0
58    }
59}
60
61impl Truthy for char {
62    #[inline]
63    fn truthy(&self) -> bool {
64        true
65    }
66}
67
68impl Truthy for String {
69    #[inline]
70    fn truthy(&self) -> bool {
71        !self.is_empty()
72    }
73}
74
75impl Truthy for &str {
76    #[inline]
77    fn truthy(&self) -> bool {
78        !self.is_empty()
79    }
80}
81
82impl<T> Truthy for crate::types::LogosSeq<T> {
83    #[inline]
84    fn truthy(&self) -> bool {
85        !self.is_empty()
86    }
87}
88
89impl<K: Eq + core::hash::Hash, V> Truthy for crate::types::LogosMap<K, V> {
90    #[inline]
91    fn truthy(&self) -> bool {
92        !self.is_empty()
93    }
94}
95
96impl<T> Truthy for crate::types::FxIndexSet<T> {
97    #[inline]
98    fn truthy(&self) -> bool {
99        !self.is_empty()
100    }
101}
102
103/// `nothing` is falsy; a present value keeps its own truthiness (the
104/// interpreter never sees the `Some` wrapper — `Some(0)` at runtime IS `0`).
105impl<T: Truthy> Truthy for Option<T> {
106    #[inline]
107    fn truthy(&self) -> bool {
108        match self {
109            Some(v) => v.truthy(),
110            None => false,
111        }
112    }
113}
114
115impl Truthy for crate::types::LogosRational {
116    #[inline]
117    fn truthy(&self) -> bool {
118        !self.0.is_zero()
119    }
120}
121
122impl Truthy for crate::types::LogosDecimal {
123    #[inline]
124    fn truthy(&self) -> bool {
125        !self.0.is_zero()
126    }
127}
128
129impl Truthy for crate::types::LogosComplex {
130    #[inline]
131    fn truthy(&self) -> bool {
132        !self.0.is_zero()
133    }
134}
135
136/// The truthiness entry point the AOT backend emits (`logos_truthy(&x)`).
137#[inline]
138pub fn logos_truthy<T: Truthy>(v: &T) -> bool {
139    v.truthy()
140}
141
142/// Exact Int arithmetic for GENERATED code (overflow ruling v2, stage 2):
143/// the i64 fast path is a single checked op; overflow spills to the
144/// promoting [`crate::types::LogosInt`] — the AOT's mirror of the
145/// interpreter's Int→BigInt promotion. `impl Into<LogosInt>` lets an
146/// already-promoted operand chain through the same helper unchanged.
147#[inline(always)]
148pub fn logos_add_exact(
149    a: impl Into<crate::types::LogosInt>,
150    b: impl Into<crate::types::LogosInt>,
151) -> crate::types::LogosInt {
152    a.into().add(&b.into())
153}
154
155#[inline(always)]
156pub fn logos_sub_exact(
157    a: impl Into<crate::types::LogosInt>,
158    b: impl Into<crate::types::LogosInt>,
159) -> crate::types::LogosInt {
160    a.into().sub(&b.into())
161}
162
163#[inline(always)]
164pub fn logos_mul_exact(
165    a: impl Into<crate::types::LogosInt>,
166    b: impl Into<crate::types::LogosInt>,
167) -> crate::types::LogosInt {
168    a.into().mul(&b.into())
169}
170
171/// Truncating division — loud canonical panic on a zero divisor (the same
172/// failure the interpreter raises); `i64::MIN / -1` promotes exactly.
173#[inline(always)]
174pub fn logos_div_exact(
175    a: impl Into<crate::types::LogosInt>,
176    b: impl Into<crate::types::LogosInt>,
177) -> crate::types::LogosInt {
178    match a.into().div(&b.into()) {
179        Ok(v) => v,
180        Err(e) => panic!("{e}"),
181    }
182}
183
184/// Floor division — the quotient rounded toward NEGATIVE INFINITY (`-7 // 2 → -4`),
185/// the `//` operator. Loud canonical panic on a zero divisor; exact (promotes to
186/// `BigInt`). Distinct from [`logos_div_exact`], which truncates toward zero.
187#[inline(always)]
188pub fn logos_floordiv_exact(
189    a: impl Into<crate::types::LogosInt>,
190    b: impl Into<crate::types::LogosInt>,
191) -> crate::types::LogosInt {
192    match a.into().div_floor(&b.into()) {
193        Ok(v) => v,
194        Err(e) => panic!("{e}"),
195    }
196}
197
198/// Fused NARROWED exact ops (overflow ruling v2, stage 2): emitted when a
199/// single exact op's result narrows straight back to i64 — the dominant
200/// hot-loop shape. The fast path is one checked op on machine integers (no
201/// `LogosInt` materialization, so the value lives in a register and LLVM's
202/// induction reasoning survives); overflow raises the same loud canonical
203/// error the `logos_*_exact(..).expect_i64("Int")` chain raises, byte for
204/// byte (the printed value is the exact result).
205#[inline(always)]
206pub fn logos_add_i64(a: i64, b: i64) -> i64 {
207    match a.checked_add(b) {
208        Some(v) => v,
209        None => narrowed_overflow(logos_add_exact(a, b)),
210    }
211}
212
213#[inline(always)]
214pub fn logos_sub_i64(a: i64, b: i64) -> i64 {
215    match a.checked_sub(b) {
216        Some(v) => v,
217        None => narrowed_overflow(logos_sub_exact(a, b)),
218    }
219}
220
221#[inline(always)]
222pub fn logos_mul_i64(a: i64, b: i64) -> i64 {
223    match a.checked_mul(b) {
224        Some(v) => v,
225        None => narrowed_overflow(logos_mul_exact(a, b)),
226    }
227}
228
229/// `checked_div` is `None` on exactly the two slow cases (zero divisor,
230/// `i64::MIN / -1`); both re-route through the exact helper for the canonical
231/// error / exact-promotion narrow.
232#[inline(always)]
233pub fn logos_div_i64(a: i64, b: i64) -> i64 {
234    match a.checked_div(b) {
235        Some(v) => v,
236        None => logos_div_exact(a, b).expect_i64("Int"),
237    }
238}
239
240/// `checked_rem` is `None` on a zero divisor (canonical panic via the exact
241/// helper) and on `i64::MIN % -1` (which the helper resolves to 0 — cold but
242/// correct).
243#[inline(always)]
244pub fn logos_rem_i64(a: i64, b: i64) -> i64 {
245    match a.checked_rem(b) {
246        Some(v) => v,
247        None => logos_rem_exact(a, b).expect_i64("Int"),
248    }
249}
250
251#[cold]
252#[inline(never)]
253fn narrowed_overflow(v: crate::types::LogosInt) -> ! {
254    panic!("Integer overflow: {v} does not fit a 64-bit Int")
255}
256
257/// Narrow a width-bounded i128 chain result back to i64 (overflow ruling v2,
258/// stage 2): the codegen lowers an exact chain whose worst-case bit-width
259/// provably fits i128 as native i128 arithmetic (every intermediate exact by
260/// construction) and narrows ONCE at the root. Same canonical error text as
261/// `expect_i64` — an i128 prints the same digits `LogosInt` would.
262#[inline(always)]
263pub fn logos_narrow_i128(v: i128) -> i64 {
264    match i64::try_from(v) {
265        Ok(x) => x,
266        Err(_) => narrowed_overflow_i128(v),
267    }
268}
269
270#[cold]
271#[inline(never)]
272fn narrowed_overflow_i128(v: i128) -> ! {
273    panic!("Integer overflow: {v} does not fit a 64-bit Int")
274}
275
276/// Truncating i128 division inside a width-bounded exact chain. The zero
277/// divisor raises the canonical error; `i128::MIN / -1` cannot occur (chain
278/// operands are width-bounded far below `i128::MIN`).
279#[inline(always)]
280pub fn logos_div_i128(a: i128, b: i128) -> i128 {
281    if b == 0 {
282        panic!("{}", crate::failure::DIVISION_BY_ZERO);
283    }
284    a / b
285}
286
287/// Truncating i128 remainder inside a width-bounded exact chain — the
288/// canonical zero-divisor error, sign of the dividend.
289#[inline(always)]
290pub fn logos_rem_i128(a: i128, b: i128) -> i128 {
291    if b == 0 {
292        panic!("{}", crate::failure::MODULO_BY_ZERO);
293    }
294    a % b
295}
296
297/// Truncating remainder — loud canonical panic on a zero divisor;
298/// `i64::MIN % -1` is 0 (no overflow, no panic).
299#[inline(always)]
300pub fn logos_rem_exact(
301    a: impl Into<crate::types::LogosInt>,
302    b: impl Into<crate::types::LogosInt>,
303) -> crate::types::LogosInt {
304    match a.into().rem(&b.into()) {
305        Ok(v) => v,
306        Err(e) => panic!("{e}"),
307    }
308}
309
310/// `a & b` on exact integers, as every tier computes it: two machine words AND bit by bit, and a big integer that
311/// is not negative, beside a low mask `2^k - 1`, leaves its low `k` bits. Any other big operand is refused in
312/// [`crate::failure::BITAND_OPERANDS`]'s words.
313#[inline(always)]
314pub fn logos_band_exact(
315    a: impl Into<crate::types::LogosInt>,
316    b: impl Into<crate::types::LogosInt>,
317) -> i64 {
318    use crate::types::LogosInt;
319    let (a, b) = (a.into(), b.into());
320    match (a.to_i64(), b.to_i64()) {
321        (Some(x), Some(y)) => x & y,
322        (None, Some(mask)) | (Some(mask), None) => {
323            let big = match (&a, &b) {
324                (LogosInt::Big(big), _) | (_, LogosInt::Big(big)) => big,
325                _ => unreachable!("an operand past i64 is a big integer"),
326            };
327            if mask >= 0 && (mask as u64).wrapping_add(1).is_power_of_two() && !big.is_negative() {
328                (big.wrapping_u64() & mask as u64) as i64
329            } else {
330                banded_refusal()
331            }
332        }
333        (None, None) => banded_refusal(),
334    }
335}
336
337#[cold]
338#[inline(never)]
339fn banded_refusal() -> ! {
340    panic!("{}", crate::failure::BITAND_OPERANDS)
341}
342
343/// The branch a guard sends a computation to when its machine-word form may not hold: run out of line, so the exact
344/// arithmetic it inlines (big-integer cases and all) never sits in the hot function beside the word form it guards.
345#[cold]
346#[inline(never)]
347pub fn logos_cold_path<T>(exact: impl FnOnce() -> T) -> T {
348    exact()
349}
350
351/// An exact operand of `|`, `^`, `<<` or `>>`, which act on machine words alone: its value, or the refusal `why`
352/// when it is a big integer.
353#[inline(always)]
354pub fn logos_word_operand(a: impl Into<crate::types::LogosInt>, why: &str) -> i64 {
355    match a.into().to_i64() {
356        Some(x) => x,
357        None => word_operand_refusal(why),
358    }
359}
360
361#[cold]
362#[inline(never)]
363fn word_operand_refusal(why: &str) -> ! {
364    panic!("{why}")
365}
366
367/// Exact integer exponentiation — the i64 fast path promotes to `BigInt` on
368/// overflow (`2 ** 100`). Loud canonical panic on a negative exponent (an Int
369/// can't hold the fractional result), mirroring the interpreter.
370#[inline(always)]
371pub fn logos_pow_exact(
372    a: impl Into<crate::types::LogosInt>,
373    b: impl Into<crate::types::LogosInt>,
374) -> crate::types::LogosInt {
375    match a.into().pow(&b.into()) {
376        Ok(v) => v,
377        Err(e) => panic!("{e}"),
378    }
379}
380
381/// Numeric-unified map key: a `Float` used to index an `Int`-keyed map matches
382/// the Int key `i` iff the float is exactly `i` (integral and in i64 range) —
383/// the compiled mirror of the interpreter's `1 == 1.0` key coercion. A
384/// non-integral float (`1.5`) matches no Int key.
385#[inline(always)]
386pub fn logos_i64_key_of_f64(f: f64) -> Option<i64> {
387    if f.fract() == 0.0 && f >= i64::MIN as f64 && f <= i64::MAX as f64 {
388        Some(f as i64)
389    } else {
390        None
391    }
392}
393
394/// Fast decimal append of an `i64` to a `String`. The `write!(s, "{}", i)` the
395/// string-builder used to emit routes every integer through the `fmt::Display`
396/// vtable + formatter machinery; this writes the digits straight into a stack
397/// buffer and `push_str`s once — ~1.5× faster on integer-heavy string building
398/// (measured: 20.7ms → 13.6ms on a 2M-int build loop), byte-identical output.
399///
400/// Exposed as a method so codegen can emit `s.push_i64(x)` and get the same
401/// auto-ref/deref behavior as the existing `s.push_str(&x)` fast path.
402pub trait LogosStrPushInt {
403    fn push_i64(&mut self, v: i64);
404}
405
406/// The two digits of every number below 100, `00` to `99`: one division by 100 writes two digits.
407const DIGIT_PAIRS: &[u8; 200] = b"\
4080001020304050607080910111213141516171819\
4092021222324252627282930313233343536373839\
4104041424344454647484950515253545556575859\
4116061626364656667686970717273747576777879\
4128081828384858687888990919293949596979899";
413
414impl LogosStrPushInt for String {
415    /// The decimal digits of `v`, written straight into the string's spare capacity from the last digit back, two
416    /// digits a division: no buffer to copy from and no copy call per number.
417    #[inline]
418    fn push_i64(&mut self, v: i64) {
419        // `unsigned_abs` gives |v| as u64, correct even for i64::MIN.
420        let mut n = v.unsigned_abs();
421        let len = n.checked_ilog10().map_or(1, |l| l as usize + 1) + (v < 0) as usize;
422        self.reserve(len);
423        // SAFETY: `len` bytes of spare capacity are reserved, and every one of them is written below with ASCII `-` or
424        // a digit before the length grows over them, so the string stays UTF-8.
425        unsafe {
426            let bytes = self.as_mut_vec();
427            let at = bytes.len();
428            let out = bytes.as_mut_ptr().add(at);
429            let mut end = len;
430            while n >= 100 {
431                let pair = (n % 100) as usize * 2;
432                n /= 100;
433                end -= 2;
434                *out.add(end) = DIGIT_PAIRS[pair];
435                *out.add(end + 1) = DIGIT_PAIRS[pair + 1];
436            }
437            if n >= 10 {
438                let pair = n as usize * 2;
439                end -= 2;
440                *out.add(end) = DIGIT_PAIRS[pair];
441                *out.add(end + 1) = DIGIT_PAIRS[pair + 1];
442            } else {
443                end -= 1;
444                *out.add(end) = b'0' + n as u8;
445            }
446            if v < 0 {
447                *out = b'-';
448            }
449            bytes.set_len(at + len);
450        }
451    }
452}
453
454#[cfg(test)]
455#[path = "../../logicaffeine_tests/unit/logicaffeine_data/ops/itoa_tests.rs"]
456mod itoa_tests;