tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

445 lignes · 15117 octetsBrut · Historique
1//! `Int`: tagged small ints, promoted to big integers outside 63 bits
2//! (ADR 0014).
3//!
4//! A big integer is a `TAG_BIGINT` block whose raw area holds an `i64`
5//! `len` (`|len|` limbs; its sign is the number's), then `|len|` 64-bit
6//! limbs of the magnitude, least significant first. It never holds a
7//! number in the 63-bit range: results are *canonical*, small whenever
8//! they fit, so two equal `Int`s are equal words or two blocks with equal
9//! limbs, and a small int never equals a big one.
10//!
11//! The inline fast paths in `louise_rt.h` (`tl_int_add`, `tl_int_sub`,
12//! `tl_int_mul`, `tl_int_div`, `tl_int_rem`, `tl_int_eq`,
13//! `tl_int_compare`) handle two small ints whose result is small;
14//! everything else (and a division by zero) comes here, to the `_slow`
15//! functions. Big arithmetic goes through `num-bigint`, as in the
16//! interpreter (`louise_interp`'s `int`), so both backends compute, print and
17//! hash alike. Like every `@extern` function these borrow their arguments.
18
19use num_bigint::{BigInt, BigUint, Sign};
20use num_traits::ToPrimitive;
21
22use louise_rt_prims::{SMALL_INT, hash_limbs, mix};
23
24use crate::abi::{Block, Ctx, TAG_BIGINT, Value, int, int_get, is_ptr};
25use crate::heap::tl_alloc;
26use crate::prims::{boolean, order, panic_with};
27
28const WORD: usize = size_of::<Value>();
29
30/// The sign-and-length word and the limbs of a big integer (borrowed).
31///
32/// # Safety
33/// `v` must be a live big integer.
34unsafe fn limbs<'a>(v: Value) -> (i64, &'a [u64]) {
35 // SAFETY: a big integer's raw area is its length word, then the limbs.
36 unsafe {
37 let raw = Block::fields_ptr(v as *mut Block).cast::<i64>();
38 let len = raw.read();
39 let limbs =
40 std::slice::from_raw_parts(raw.add(1).cast::<u64>(), len.unsigned_abs() as usize);
41 (len, limbs)
42 }
43}
44
45/// The value of an `Int` (borrowed).
46///
47/// # Safety
48/// `v` must be a live `Int`.
49pub(crate) unsafe fn to_big(v: Value) -> BigInt {
50 if !is_ptr(v) {
51 return BigInt::from(int_get(v));
52 }
53 // SAFETY: forwarded caller guarantee.
54 let (len, limbs) = unsafe { limbs(v) };
55 let digits: Vec<u32> = limbs
56 .iter()
57 .flat_map(|l| [*l as u32, (l >> 32) as u32])
58 .collect();
59 let sign = if len < 0 { Sign::Minus } else { Sign::Plus };
60 BigInt::from_biguint(sign, BigUint::new(digits))
61}
62
63/// `n` as an `Int` (owned): small if it fits in 63 bits.
64pub(crate) fn from_big(ctx: *mut Ctx, n: &BigInt) -> Value {
65 if let Some(small) = n.to_i64().filter(|v| SMALL_INT.contains(v)) {
66 return int(small);
67 }
68 let (sign, digits) = n.to_u64_digits();
69 let b = tl_alloc(ctx, TAG_BIGINT, 0, WORD * (1 + digits.len()));
70 let len = digits.len() as i64;
71 // SAFETY: the raw area holds the length word and `digits.len()` limbs.
72 unsafe {
73 let raw = Block::fields_ptr(b).cast::<i64>();
74 raw.write(if sign == Sign::Minus { -len } else { len });
75 std::ptr::copy_nonoverlapping(digits.as_ptr(), raw.add(1).cast::<u64>(), digits.len());
76 }
77 b as Value
78}
79
80/// `n` as an `Int` (owned): small if it fits in 63 bits.
81pub(crate) fn from_i128(ctx: *mut Ctx, n: i128) -> Value {
82 match i64::try_from(n) {
83 Ok(small) if SMALL_INT.contains(&small) => int(small),
84 _ => from_big(ctx, &BigInt::from(n)),
85 }
86}
87
88/// An `Int` used as an index, a count, a size or a duration: the nearest
89/// `i64` (a big integer saturates). The interpreter does the same.
90///
91/// # Safety
92/// `v` must be a live `Int`.
93pub(crate) unsafe fn saturating(v: Value) -> i64 {
94 if !is_ptr(v) {
95 return int_get(v);
96 }
97 // SAFETY: forwarded caller guarantee.
98 if unsafe { limbs(v) }.0 < 0 {
99 i64::MIN
100 } else {
101 i64::MAX
102 }
103}
104
105/// A binary operation on two `Int`s: `small` when both are small, `big`
106/// otherwise. `small` computes in 64 bits, where 63-bit operands only
107/// overflow a product (it returns `None` then). Not in 128 bits: a
108/// 128-bit division is a library call, several times slower.
109///
110/// # Safety
111/// `a` and `b` must be live `Int`s.
112unsafe fn binary(
113 ctx: *mut Ctx,
114 a: Value,
115 b: Value,
116 small: impl Fn(i64, i64) -> Option<i64>,
117 big: impl Fn(BigInt, BigInt) -> BigInt,
118) -> Value {
119 if !is_ptr(a)
120 && !is_ptr(b)
121 && let Some(r) = small(int_get(a), int_get(b))
122 {
123 return from_i128(ctx, i128::from(r));
124 }
125 // SAFETY: forwarded caller guarantee.
126 let (x, y) = unsafe { (to_big(a), to_big(b)) };
127 from_big(ctx, &big(x, y))
128}
129
130/// `a + b` when it overflows 63 bits or an argument is big (`tl_int_add`'s
131/// slow path).
132///
133/// # Safety
134/// `a` and `b` must be live `Int`s.
135#[unsafe(no_mangle)]
136pub unsafe extern "C" fn tl_int_add_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
137 // SAFETY: forwarded caller guarantee.
138 unsafe { binary(ctx, a, b, |x, y| Some(x + y), |x, y| x + y) }
139}
140
141/// # Safety
142/// `a` and `b` must be live `Int`s.
143#[unsafe(no_mangle)]
144pub unsafe extern "C" fn tl_int_sub_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
145 // SAFETY: forwarded caller guarantee.
146 unsafe { binary(ctx, a, b, |x, y| Some(x - y), |x, y| x - y) }
147}
148
149/// # Safety
150/// `a` and `b` must be live `Int`s.
151#[unsafe(no_mangle)]
152pub unsafe extern "C" fn tl_int_mul_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
153 // SAFETY: forwarded caller guarantee.
154 unsafe { binary(ctx, a, b, i64::checked_mul, |x, y| x * y) }
155}
156
157/// Truncating division; panics on division by zero.
158///
159/// # Safety
160/// `ctx` must be the running actor's context; `a` and `b` live `Int`s.
161#[unsafe(no_mangle)]
162pub unsafe extern "C" fn tl_int_div_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
163 if b == int(0) {
164 // SAFETY: caller guarantees the running actor's context.
165 return unsafe { panic_with(ctx, "division by zero") };
166 }
167 // SAFETY: forwarded caller guarantee.
168 unsafe { binary(ctx, a, b, |x, y| Some(x / y), |x, y| x / y) }
169}
170
171/// The remainder of the truncating division (the sign of `a`); panics on
172/// division by zero.
173///
174/// # Safety
175/// `ctx` must be the running actor's context; `a` and `b` live `Int`s.
176#[unsafe(no_mangle)]
177pub unsafe extern "C" fn tl_int_rem_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
178 if b == int(0) {
179 // SAFETY: caller guarantees the running actor's context.
180 return unsafe { panic_with(ctx, "division by zero") };
181 }
182 // SAFETY: forwarded caller guarantee.
183 unsafe { binary(ctx, a, b, |x, y| Some(x % y), |x, y| x % y) }
184}
185
186/// # Safety
187/// `a` and `b` must be live `Int`s.
188#[unsafe(no_mangle)]
189pub unsafe extern "C" fn tl_int_eq_slow(_ctx: *mut Ctx, a: Value, b: Value) -> Value {
190 // Canonical forms: a small int equals only the same word.
191 if a == b || !is_ptr(a) || !is_ptr(b) {
192 return boolean(a == b);
193 }
194 // SAFETY: both are live big integers.
195 boolean(unsafe { limbs(a) == limbs(b) })
196}
197
198/// # Safety
199/// `a` and `b` must be live `Int`s.
200#[unsafe(no_mangle)]
201pub unsafe extern "C" fn tl_int_compare_slow(_ctx: *mut Ctx, a: Value, b: Value) -> Value {
202 if !is_ptr(a) && !is_ptr(b) {
203 return order(int_get(a).cmp(&int_get(b)));
204 }
205 // SAFETY: forwarded caller guarantee.
206 order(unsafe { to_big(a).cmp(&to_big(b)) })
207}
208
209/// Decimal, every digit.
210///
211/// # Safety
212/// `a` must be a live `Int`.
213#[unsafe(no_mangle)]
214pub unsafe extern "C" fn tl_int_show(ctx: *mut Ctx, a: Value) -> Value {
215 let text = if is_ptr(a) {
216 // SAFETY: forwarded caller guarantee.
217 unsafe { to_big(a) }.to_string()
218 } else {
219 int_get(a).to_string()
220 };
221 // SAFETY: `text` is valid for its length.
222 unsafe { crate::values::tl_string_from(ctx, text.as_ptr().cast(), text.len()) }
223}
224
225/// Small ints: mixed. Big integers: FNV-1a over the limbs, complemented
226/// when negative, then mixed (the interpreter's formula too).
227///
228/// # Safety
229/// `a` must be a live `Int`.
230#[unsafe(no_mangle)]
231pub unsafe extern "C" fn tl_hash_int(_ctx: *mut Ctx, a: Value) -> Value {
232 if !is_ptr(a) {
233 return int(mix(int_get(a) as u64));
234 }
235 // SAFETY: forwarded caller guarantee.
236 let (len, limbs) = unsafe { limbs(a) };
237 int(mix(hash_limbs(len < 0, limbs)))
238}
239
240/// The `Int` written in `text`: an optional sign, then decimal digits (no
241/// other character), of any length.
242pub(crate) fn parse(text: &str) -> Option<BigInt> {
243 let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
244 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
245 return None;
246 }
247 let n: BigInt = digits.parse().ok()?;
248 Some(if text.starts_with('-') { -n } else { n })
249}
250
251/// The `i64` of an `Int` in C bindings: false when it does not fit.
252///
253/// # Safety
254/// `v` must be a live `Int`; `out` valid for a write.
255#[unsafe(no_mangle)]
256pub unsafe extern "C" fn tl_int_to_i64(v: Value, out: *mut i64) -> bool {
257 // SAFETY: forwarded caller guarantee.
258 match unsafe { to_big(v) }.to_i64() {
259 Some(n) => {
260 // SAFETY: forwarded caller guarantee.
261 unsafe { out.write(n) };
262 true
263 }
264 None => false,
265 }
266}
267
268/// An `Int` (owned) from C bindings: big outside 63 bits.
269#[unsafe(no_mangle)]
270pub extern "C" fn tl_int_from_i64(ctx: *mut Ctx, n: i64) -> Value {
271 from_i128(ctx, i128::from(n))
272}
273
274// ---- bitwise operations (std/int, ADR 0035) ------------------------------------------
275//
276// Two's complement with infinite sign extension, as num-bigint (and Python)
277// compute: `-1` is all ones, so a small and a big operand give the same
278// result as if both were big. The inline fast paths in `louise_rt.h` handle
279// two small operands; these are the rest.
280
281/// `int.and` when an argument is big.
282///
283/// # Safety
284/// `a` and `b` must be live `Int`s.
285#[unsafe(no_mangle)]
286pub unsafe extern "C" fn tl_int_and_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
287 // SAFETY: forwarded caller guarantee.
288 unsafe { binary(ctx, a, b, |x, y| Some(x & y), |x, y| x & y) }
289}
290
291/// `int.or` when an argument is big.
292///
293/// # Safety
294/// `a` and `b` must be live `Int`s.
295#[unsafe(no_mangle)]
296pub unsafe extern "C" fn tl_int_or_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
297 // SAFETY: forwarded caller guarantee.
298 unsafe { binary(ctx, a, b, |x, y| Some(x | y), |x, y| x | y) }
299}
300
301/// `int.xor` when an argument is big.
302///
303/// # Safety
304/// `a` and `b` must be live `Int`s.
305#[unsafe(no_mangle)]
306pub unsafe extern "C" fn tl_int_xor_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value {
307 // SAFETY: forwarded caller guarantee.
308 unsafe { binary(ctx, a, b, |x, y| Some(x ^ y), |x, y| x ^ y) }
309}
310
311/// `int.not` of a big integer: `-n - 1`.
312///
313/// # Safety
314/// `a` must be a live `Int`.
315#[unsafe(no_mangle)]
316pub unsafe extern "C" fn tl_int_not_slow(ctx: *mut Ctx, a: Value) -> Value {
317 // SAFETY: forwarded caller guarantee.
318 from_big(ctx, &!unsafe { to_big(a) })
319}
320
321/// `int.shift_left(n, k)` when the fast path can't: a big `n` or `k`, a
322/// result outside 63 bits, or a negative `k` (a panic). `k ≥ 2^32` of a
323/// non-zero `n` panics instead of exhausting memory.
324///
325/// # Safety
326/// `n` and `k` must be live `Int`s; `ctx` the running actor's.
327#[unsafe(no_mangle)]
328pub unsafe extern "C" fn tl_int_shift_left_slow(ctx: *mut Ctx, n: Value, k: Value) -> Value {
329 // SAFETY: forwarded caller guarantee.
330 let (n, k) = unsafe { (to_big(n), to_big(k)) };
331 if k.sign() == Sign::Minus {
332 // SAFETY: forwarded caller guarantee.
333 return unsafe {
334 panic_with(
335 ctx,
336 &louise_rt_prims::negative_shift("int.shift_left", &k.to_string()),
337 )
338 };
339 }
340 if n.sign() == Sign::NoSign {
341 return int(0);
342 }
343 match k.to_u64().filter(|k| *k < louise_rt_prims::MAX_SHIFT) {
344 Some(k) => from_big(ctx, &(n << k)),
345 // SAFETY: forwarded caller guarantee.
346 None => unsafe { panic_with(ctx, &louise_rt_prims::shift_too_large(&k.to_string())) },
347 }
348}
349
350/// `int.shift_right(n, k)`, arithmetic (rounds towards minus infinity),
351/// when the fast path can't: a big `n` or `k`, or a negative `k` (a panic).
352///
353/// # Safety
354/// `n` and `k` must be live `Int`s; `ctx` the running actor's.
355#[unsafe(no_mangle)]
356pub unsafe extern "C" fn tl_int_shift_right_slow(ctx: *mut Ctx, n: Value, k: Value) -> Value {
357 // SAFETY: forwarded caller guarantee.
358 let (n, k) = unsafe { (to_big(n), to_big(k)) };
359 if k.sign() == Sign::Minus {
360 // SAFETY: forwarded caller guarantee.
361 return unsafe {
362 panic_with(
363 ctx,
364 &louise_rt_prims::negative_shift("int.shift_right", &k.to_string()),
365 )
366 };
367 }
368 match k.to_u64().filter(|k| *k < louise_rt_prims::MAX_SHIFT) {
369 Some(k) => from_big(ctx, &(n >> k)),
370 // Every bit shifted out: the sign is what's left.
371 None => int(if n.sign() == Sign::Minus { -1 } else { 0 }),
372 }
373}
374
375/// `int.bit_length(n)`: the number of bits of `|n|` (0 for 0).
376///
377/// # Safety
378/// `n` must be a live `Int`.
379#[unsafe(no_mangle)]
380pub unsafe extern "C" fn tl_int_bit_length(_ctx: *mut Ctx, n: Value) -> Value {
381 if !is_ptr(n) {
382 return int(i64::from(64 - int_get(n).unsigned_abs().leading_zeros()));
383 }
384 // SAFETY: forwarded caller guarantee.
385 int(unsafe { to_big(n) }.bits() as i64)
386}
387
388/// `float.from_int(n)`: the nearest Float (ties to even); an infinity past
389/// the largest Float.
390///
391/// # Safety
392/// `n` must be a live `Int`.
393#[unsafe(no_mangle)]
394pub unsafe extern "C" fn tl_float_from_int(ctx: *mut Ctx, n: Value) -> Value {
395 let x = if is_ptr(n) {
396 // SAFETY: forwarded caller guarantee.
397 unsafe { to_big(n) }.to_f64().unwrap_or(f64::NAN)
398 } else {
399 int_get(n) as f64
400 };
401 crate::prims::tl_float_from(ctx, x)
402}
403
404/// The low 64 bits of an `Int`, two's complement (`-1` is all ones).
405///
406/// # Safety
407/// `n` must be a live `Int`.
408pub(crate) unsafe fn low_u64(n: Value) -> u64 {
409 if !is_ptr(n) {
410 return int_get(n) as u64;
411 }
412 // SAFETY: forwarded caller guarantee.
413 let big = unsafe { to_big(n) } & BigInt::from(u64::MAX);
414 big.to_u64().unwrap_or(0)
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 #[test]
422 fn parsing_decimal_ints() {
423 for (text, n) in [("0", 0), ("+7", 7), ("-12", -12), ("007", 7)] {
424 assert_eq!(parse(text), Some(BigInt::from(n)), "{text:?}");
425 }
426 let big = "-123456789012345678901234567890";
427 assert_eq!(parse(big).map(|n| n.to_string()).as_deref(), Some(big));
428 for text in [
429 "", "+", "-", "--1", "+-1", " 1", "1 ", "1_000", "0x10", "1e3", "١",
430 ] {
431 assert_eq!(parse(text), None, "{text:?}");
432 }
433 }
434
435 /// Small `Int`s need no block, so `saturating` and `to_big` read them
436 /// without a heap.
437 #[test]
438 fn small_ints_read_as_themselves() {
439 for n in [0, -1, (1 << 62) - 1, -(1 << 62)] {
440 // SAFETY: small ints are not pointers.
441 let (s, b) = unsafe { (saturating(int(n)), to_big(int(n))) };
442 assert_eq!((s, b), (n, BigInt::from(n)));
443 }
444 }
445}