Skip to main content

inlean_runtime/
int.rs

1//! Lean's `Int`: an integer of any size.
2//!
3//! An integer that fits 32 bits is stored in the pointer bits; anything else is the same
4//! heap object a large `Nat` uses, with a sign. As in `lean.h`, arguments are borrowed and
5//! results are owned unless noted.
6
7use crate::bignum;
8use crate::nat::{alloc_big, big_parts};
9use crate::object::{box_, dec, inc, is_scalar, unbox, Obj};
10use std::cmp::Ordering;
11
12/// An integer as a sign and a magnitude. Zero is not negative.
13struct Signed {
14    negative: bool,
15    magnitude: Vec<u64>,
16}
17
18unsafe fn read(o: Obj) -> Signed {
19    if is_scalar(o) {
20        let value = unbox(o) as u32 as i32 as i64;
21        let magnitude = if value == 0 { Vec::new() } else { vec![value.unsigned_abs()] };
22        Signed { negative: value < 0, magnitude }
23    } else {
24        let (negative, limbs) = big_parts(o);
25        Signed { negative, magnitude: limbs.to_vec() }
26    }
27}
28
29fn write(mut value: Signed) -> Obj {
30    while value.magnitude.last() == Some(&0) {
31        value.magnitude.pop();
32    }
33    let negative = value.negative && !value.magnitude.is_empty();
34    if let [] | [_] = value.magnitude.as_slice() {
35        let magnitude = value.magnitude.first().copied().unwrap_or(0) as i128;
36        let signed = if negative { -magnitude } else { magnitude };
37        if let Ok(small) = i32::try_from(signed) {
38            return box_(small as u32 as usize);
39        }
40    }
41    alloc_big(value.magnitude, negative)
42}
43
44fn from_i64(value: i64) -> Obj {
45    write(Signed { negative: value < 0, magnitude: if value == 0 { Vec::new() } else { vec![value.unsigned_abs()] } })
46}
47
48/// The value of an integer stored in the pointer bits.
49unsafe fn small(o: Obj) -> Option<i64> {
50    is_scalar(o).then(|| unbox(o) as u32 as i32 as i64)
51}
52
53fn add_signed(a: Signed, b: Signed) -> Signed {
54    if a.negative == b.negative {
55        return Signed { negative: a.negative, magnitude: bignum::add(&a.magnitude, &b.magnitude) };
56    }
57    match bignum::compare(&a.magnitude, &b.magnitude) {
58        Ordering::Less => Signed { negative: b.negative, magnitude: bignum::sub(&b.magnitude, &a.magnitude) },
59        _ => Signed { negative: a.negative, magnitude: bignum::sub(&a.magnitude, &b.magnitude) },
60    }
61}
62
63fn negate(a: Signed) -> Signed {
64    Signed { negative: !a.negative, magnitude: a.magnitude }
65}
66
67/// A `Nat` as an `Int`. Consumes `a`.
68pub unsafe fn nat_to_int(a: Obj) -> Obj {
69    if is_scalar(a) && unbox(a) > i32::MAX as usize {
70        return alloc_big(vec![unbox(a) as u64], false);
71    }
72    a
73}
74
75/// A non-negative `Int` as a `Nat`. Consumes `a`.
76pub unsafe fn int_to_nat(a: Obj) -> Obj {
77    if is_scalar(a) {
78        return a;
79    }
80    let result = crate::nat::of_limbs(big_parts(a).1.to_vec());
81    dec(a);
82    result
83}
84
85/// The absolute value, as a `Nat`.
86pub unsafe fn nat_abs(a: Obj) -> Obj {
87    crate::nat::of_limbs(read(a).magnitude)
88}
89
90pub unsafe fn int_neg(a: Obj) -> Obj {
91    write(negate(read(a)))
92}
93
94/// `-(n + 1)` for a `Nat` `n`. Consumes `n`.
95pub unsafe fn int_neg_succ_of_nat(n: Obj) -> Obj {
96    let successor = crate::nat::nat_succ(n);
97    dec(n);
98    let as_int = nat_to_int(successor);
99    let result = int_neg(as_int);
100    dec(as_int);
101    result
102}
103
104pub unsafe fn int_add(a: Obj, b: Obj) -> Obj {
105    match (small(a), small(b)) {
106        (Some(x), Some(y)) => from_i64(x + y),
107        _ => write(add_signed(read(a), read(b))),
108    }
109}
110
111pub unsafe fn int_sub(a: Obj, b: Obj) -> Obj {
112    match (small(a), small(b)) {
113        (Some(x), Some(y)) => from_i64(x - y),
114        _ => write(add_signed(read(a), negate(read(b)))),
115    }
116}
117
118pub unsafe fn int_mul(a: Obj, b: Obj) -> Obj {
119    match (small(a), small(b)) {
120        (Some(x), Some(y)) => from_i64(x * y),
121        _ => {
122            let (a, b) = (read(a), read(b));
123            write(Signed { negative: a.negative != b.negative, magnitude: bignum::mul(&a.magnitude, &b.magnitude) })
124        }
125    }
126}
127
128/// Quotient and remainder rounding toward zero, for a nonzero divisor.
129fn divrem(a: &Signed, b: &Signed) -> (Signed, Signed) {
130    let (quotient, remainder) = bignum::divrem(&a.magnitude, &b.magnitude);
131    (Signed { negative: a.negative != b.negative, magnitude: quotient }, Signed { negative: a.negative, magnitude: remainder })
132}
133
134fn one() -> Signed {
135    Signed { negative: false, magnitude: vec![1] }
136}
137
138/// Division rounding toward zero; zero when the divisor is zero.
139pub unsafe fn int_div(a: Obj, b: Obj) -> Obj {
140    let (a, b) = (read(a), read(b));
141    if b.magnitude.is_empty() {
142        return box_(0);
143    }
144    write(divrem(&a, &b).0)
145}
146
147pub unsafe fn int_div_exact(a: Obj, b: Obj) -> Obj {
148    int_div(a, b)
149}
150
151/// Remainder with the sign of the dividend; the dividend when the divisor is zero.
152pub unsafe fn int_mod(a: Obj, b: Obj) -> Obj {
153    let (x, y) = (read(a), read(b));
154    if y.magnitude.is_empty() {
155        inc(a);
156        return a;
157    }
158    write(divrem(&x, &y).1)
159}
160
161/// Euclidean division: the remainder is never negative. Zero when the divisor is zero.
162pub unsafe fn int_ediv(a: Obj, b: Obj) -> Obj {
163    let (x, y) = (read(a), read(b));
164    if y.magnitude.is_empty() {
165        return box_(0);
166    }
167    let (quotient, remainder) = divrem(&x, &y);
168    if remainder.negative && !remainder.magnitude.is_empty() {
169        let step = if y.negative { one() } else { negate(one()) };
170        return write(add_signed(quotient, step));
171    }
172    write(quotient)
173}
174
175/// The remainder of Euclidean division; the dividend when the divisor is zero.
176pub unsafe fn int_emod(a: Obj, b: Obj) -> Obj {
177    let (x, y) = (read(a), read(b));
178    if y.magnitude.is_empty() {
179        inc(a);
180        return a;
181    }
182    let remainder = divrem(&x, &y).1;
183    if remainder.negative && !remainder.magnitude.is_empty() {
184        return write(add_signed(remainder, Signed { negative: false, magnitude: y.magnitude }));
185    }
186    write(remainder)
187}
188
189unsafe fn compare(a: Obj, b: Obj) -> Ordering {
190    if let (Some(x), Some(y)) = (small(a), small(b)) {
191        return x.cmp(&y);
192    }
193    let (a, b) = (read(a), read(b));
194    match (a.negative, b.negative) {
195        (false, true) => Ordering::Greater,
196        (true, false) => Ordering::Less,
197        (false, false) => bignum::compare(&a.magnitude, &b.magnitude),
198        (true, true) => bignum::compare(&b.magnitude, &a.magnitude),
199    }
200}
201
202pub unsafe fn int_dec_eq(a: Obj, b: Obj) -> u8 {
203    (compare(a, b) == Ordering::Equal) as u8
204}
205
206pub unsafe fn int_dec_lt(a: Obj, b: Obj) -> u8 {
207    (compare(a, b) == Ordering::Less) as u8
208}
209
210pub unsafe fn int_dec_le(a: Obj, b: Obj) -> u8 {
211    (compare(a, b) != Ordering::Greater) as u8
212}
213
214pub unsafe fn int_dec_nonneg(a: Obj) -> u8 {
215    !read(a).negative as u8
216}
217
218/// `a * 2^b`.
219pub unsafe fn float_scaleb(a: f64, b: Obj) -> f64 {
220    let exponent = match small(b) {
221        Some(exponent) => exponent as i32,
222        None if read(b).negative => i32::MIN,
223        None => i32::MAX,
224    };
225    // Scale in steps: one multiplication by 2^exponent would overflow or lose a subnormal
226    // result for exponents that the product itself can represent.
227    let mut value = a;
228    let mut left = exponent.clamp(-2200, 2200);
229    while left != 0 {
230        let step = left.clamp(-1000, 1000);
231        value *= 2f64.powi(step);
232        left -= step;
233    }
234    value
235}
236
237
238
239fn of_i64(value: i64) -> Obj {
240    from_i64(value)
241}
242
243/// A fixed-width signed integer, given as its bits, as an `Int`.
244pub fn int8_to_int(a: u8) -> Obj {
245    of_i64(a as i8 as i64)
246}
247
248pub fn int16_to_int(a: u16) -> Obj {
249    of_i64(a as i16 as i64)
250}
251
252pub fn int32_to_int(a: u32) -> Obj {
253    of_i64(a as i32 as i64)
254}
255
256pub fn int64_to_int_sint(a: u64) -> Obj {
257    of_i64(a as i64)
258}
259
260pub fn isize_to_int(a: usize) -> Obj {
261    of_i64(a as isize as i64)
262}
263
264/// The lowest 64 bits of an integer in two's complement.
265unsafe fn low_bits(a: Obj) -> u64 {
266    let value = read(a);
267    let low = value.magnitude.first().copied().unwrap_or(0);
268    if value.negative {
269        low.wrapping_neg()
270    } else {
271        low
272    }
273}
274
275/// An `Int` reduced to a fixed width, as its bits.
276pub unsafe fn int8_of_int(a: Obj) -> u8 {
277    low_bits(a) as u8
278}
279
280pub unsafe fn int16_of_int(a: Obj) -> u16 {
281    low_bits(a) as u16
282}
283
284pub unsafe fn int32_of_int(a: Obj) -> u32 {
285    low_bits(a) as u32
286}
287
288pub unsafe fn int64_of_int(a: Obj) -> u64 {
289    low_bits(a)
290}
291
292pub unsafe fn isize_of_int(a: Obj) -> usize {
293    low_bits(a) as usize
294}
295
296/// The functions of this module that generated code may call, named as in `lean.h` without
297/// the `lean_` prefix.
298pub(crate) const OPS: &[&str] = &[
299    "nat_to_int", "int_to_nat", "nat_abs", "int_neg", "int_neg_succ_of_nat", "int_add", "int_sub", "int_mul",
300    "int_div", "int_div_exact", "int_mod", "int_ediv", "int_emod", "int_dec_eq", "int_dec_lt", "int_dec_le",
301    "int_dec_nonneg", "float_scaleb", "int8_to_int", "int16_to_int", "int32_to_int", "int64_to_int_sint",
302    "isize_to_int", "int8_of_int", "int16_of_int", "int32_of_int", "int64_of_int", "isize_of_int",
303];
304
305/// An `Int` from a sign and the decimal digits of its magnitude.
306pub(crate) fn from_decimal(negative: bool, digits: &str) -> Option<Obj> {
307    Some(write(Signed { negative, magnitude: bignum::from_decimal(digits)? }))
308}
309
310pub(crate) unsafe fn to_decimal(a: Obj) -> String {
311    let value = read(a);
312    let digits = bignum::to_decimal(&value.magnitude);
313    if value.negative {
314        format!("-{digits}")
315    } else {
316        digits
317    }
318}
319
320pub(crate) fn of_i128(value: i128) -> Obj {
321    let magnitude = value.unsigned_abs();
322    write(Signed { negative: value < 0, magnitude: vec![magnitude as u64, (magnitude >> 64) as u64] })
323}
324
325pub(crate) unsafe fn to_i128(a: Obj) -> Option<i128> {
326    let value = read(a);
327    let magnitude = match value.magnitude.as_slice() {
328        [] => 0u128,
329        [low] => *low as u128,
330        [low, high] => (*high as u128) << 64 | *low as u128,
331        _ => return None,
332    };
333    if value.negative {
334        0i128.checked_sub_unsigned(magnitude)
335    } else {
336        i128::try_from(magnitude).ok()
337    }
338}
339
340pub(crate) unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
341    compare(a, b)
342}