Skip to main content

inlean_runtime/
types.rs

1//! Lean values as Rust values: the types that appear in the signatures of generated
2//! functions.
3
4use crate::nat;
5use crate::object::{box_, dec, Obj};
6use std::cmp::Ordering;
7use std::fmt;
8use std::str::FromStr;
9
10/// A natural number of any size: Lean's `Nat`.
11///
12/// Converts from every unsigned integer type, and back with `TryFrom` when the value fits.
13/// It prints and parses as decimal digits.
14///
15/// ```
16/// use inlean_runtime::Nat;
17/// let n: Nat = "340282366920938463463374607431768211456".parse().unwrap(); // 2^128
18/// assert!(u128::try_from(&n).is_err());
19/// assert_eq!(Nat::from(7u8).to_string(), "7");
20/// ```
21///
22/// A `Nat` is `Send` and `Sync`, like an integer: it holds a number of its own. A clone of
23/// a number too large for a machine word copies its digits.
24pub struct Nat(Obj);
25
26// Lean counts references without synchronization, so what a `Nat` holds is never an object
27// that something else counts: it is a number in the pointer bits, the only reference to an
28// object, or an object that is never counted. Nothing is written through a `&Nat`, and a
29// `Nat` that is dropped frees an object no one else refers to.
30unsafe impl Send for Nat {}
31unsafe impl Sync for Nat {}
32
33impl Nat {
34    /// Wraps a Lean object that is a `Nat`, taking over the reference to it.
35    ///
36    /// # Safety
37    /// `raw` must be a `Nat` produced by this runtime that nothing else counts on: a number
38    /// in the pointer bits, an object the caller owns the only reference to, or one that is
39    /// never counted. A value that only stands in for a number Lean holds, and is not
40    /// dropped, may wrap any `Nat` for as long as nothing else changes its count.
41    #[doc(hidden)]
42    pub unsafe fn from_raw(raw: Obj) -> Nat {
43        Nat(raw)
44    }
45
46    /// The number a Lean object is, giving up the caller's reference to the object. An
47    /// object that something else still holds is copied.
48    ///
49    /// # Safety
50    /// `raw` must be a `Nat` produced by this runtime, and the caller must own a reference.
51    #[doc(hidden)]
52    #[inline]
53    pub unsafe fn owning(raw: Obj) -> Nat {
54        Nat(nat::owned(raw))
55    }
56
57    /// The Lean object, still owned by `self`.
58    #[doc(hidden)]
59    pub fn as_raw(&self) -> Obj {
60        self.0
61    }
62
63    /// The Lean object, with the reference `self` owned.
64    #[doc(hidden)]
65    pub fn into_raw(self) -> Obj {
66        let raw = self.0;
67        std::mem::forget(self);
68        raw
69    }
70}
71
72impl Clone for Nat {
73    #[inline]
74    fn clone(&self) -> Nat {
75        Nat(unsafe { nat::unshared(self.0) })
76    }
77}
78
79impl Drop for Nat {
80    #[inline]
81    fn drop(&mut self) {
82        unsafe { dec(self.0) };
83    }
84}
85
86impl Default for Nat {
87    fn default() -> Nat {
88        Nat(box_(0))
89    }
90}
91
92impl From<&Nat> for Nat {
93    fn from(value: &Nat) -> Nat {
94        value.clone()
95    }
96}
97
98impl From<u128> for Nat {
99    fn from(value: u128) -> Nat {
100        Nat(nat::of_u128(value))
101    }
102}
103
104macro_rules! conversions {
105    ($($ty:ty),*) => {$(
106        impl From<$ty> for Nat {
107            fn from(value: $ty) -> Nat {
108                Nat(nat::uint64_to_nat(value as u64))
109            }
110        }
111
112        impl TryFrom<&Nat> for $ty {
113            type Error = TooLarge;
114
115            fn try_from(value: &Nat) -> Result<$ty, TooLarge> {
116                u128::try_from(value)?.try_into().map_err(|_| TooLarge)
117            }
118        }
119
120        impl TryFrom<Nat> for $ty {
121            type Error = TooLarge;
122
123            fn try_from(value: Nat) -> Result<$ty, TooLarge> {
124                <$ty>::try_from(&value)
125            }
126        }
127    )*};
128}
129
130conversions!(u8, u16, u32, u64, usize);
131
132impl TryFrom<&Nat> for u128 {
133    type Error = TooLarge;
134
135    fn try_from(value: &Nat) -> Result<u128, TooLarge> {
136        unsafe { nat::to_u128(value.0) }.ok_or(TooLarge)
137    }
138}
139
140impl TryFrom<Nat> for u128 {
141    type Error = TooLarge;
142
143    fn try_from(value: Nat) -> Result<u128, TooLarge> {
144        u128::try_from(&value)
145    }
146}
147
148impl Nat {
149    /// The number with these 64-bit limbs, least significant first: the form in which
150    /// fixed-width integer libraries hold their words.
151    ///
152    /// ```
153    /// use inlean_runtime::Nat;
154    /// assert_eq!(Nat::from_limbs(&[0, 1]), Nat::from(1u128 << 64));
155    /// ```
156    pub fn from_limbs(limbs: &[u64]) -> Nat {
157        Nat(nat::of_limbs(limbs))
158    }
159
160    /// The 64-bit limbs of the number, least significant first, without leading zeros.
161    pub fn to_limbs(&self) -> Vec<u64> {
162        unsafe { nat::with_limbs(self.0, <[u64]>::to_vec) }
163    }
164}
165
166impl<const N: usize> From<[u64; N]> for Nat {
167    /// The number with these limbs, least significant first.
168    fn from(limbs: [u64; N]) -> Nat {
169        Nat::from_limbs(&limbs)
170    }
171}
172
173impl<const N: usize> TryFrom<&Nat> for [u64; N] {
174    type Error = TooLarge;
175
176    /// The limbs of the number, least significant first, when it is below 2^(64·N).
177    fn try_from(value: &Nat) -> Result<[u64; N], TooLarge> {
178        unsafe { nat::with_limbs(value.0, crate::codec::fixed_limbs) }.ok_or(TooLarge)
179    }
180}
181
182impl<const N: usize> TryFrom<Nat> for [u64; N] {
183    type Error = TooLarge;
184
185    fn try_from(value: Nat) -> Result<[u64; N], TooLarge> {
186        <[u64; N]>::try_from(&value)
187    }
188}
189
190/// A [`Nat`] does not fit the integer type it was converted to.
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub struct TooLarge;
193
194impl fmt::Display for TooLarge {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        f.write_str("the natural number does not fit the integer type")
197    }
198}
199
200impl std::error::Error for TooLarge {}
201
202/// A string is not a natural number in decimal digits.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub struct ParseNatError;
205
206impl fmt::Display for ParseNatError {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.write_str("expected a natural number in decimal digits")
209    }
210}
211
212impl std::error::Error for ParseNatError {}
213
214impl FromStr for Nat {
215    type Err = ParseNatError;
216
217    fn from_str(text: &str) -> Result<Nat, ParseNatError> {
218        if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
219            return Err(ParseNatError);
220        }
221        Ok(Nat(nat::cstr_to_nat(text)))
222    }
223}
224
225impl fmt::Display for Nat {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        f.pad_integral(true, "", &unsafe { nat::to_decimal(self.0) })
228    }
229}
230
231impl fmt::Debug for Nat {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        fmt::Display::fmt(self, f)
234    }
235}
236
237impl PartialEq for Nat {
238    fn eq(&self, other: &Nat) -> bool {
239        self.cmp(other) == Ordering::Equal
240    }
241}
242
243impl Eq for Nat {}
244
245impl PartialOrd for Nat {
246    fn partial_cmp(&self, other: &Nat) -> Option<Ordering> {
247        Some(self.cmp(other))
248    }
249}
250
251impl Ord for Nat {
252    fn cmp(&self, other: &Nat) -> Ordering {
253        unsafe { nat::ordering(self.0, other.0) }
254    }
255}
256
257impl std::hash::Hash for Nat {
258    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
259        // The limbs without leading zeros: one sequence for each number.
260        unsafe { nat::with_limbs(self.0, |limbs| limbs.hash(state)) }
261    }
262}
263
264/// An integer of any size: Lean's `Int`.
265///
266/// Converts from every signed integer type, and back with `TryFrom` when the value fits. It
267/// prints and parses as decimal digits with an optional minus sign.
268///
269/// ```
270/// use inlean_runtime::Int;
271/// let n: Int = "-170141183460469231731687303715884105729".parse().unwrap(); // -2^127 - 1
272/// assert!(i128::try_from(&n).is_err());
273/// assert_eq!(Int::from(-7i8).to_string(), "-7");
274/// ```
275///
276/// Like [`Nat`], an `Int` is `Send` and `Sync`, and a clone of a large one copies its digits.
277pub struct Int(Obj);
278
279// As for `Nat`: what an `Int` holds is never an object that something else counts.
280unsafe impl Send for Int {}
281unsafe impl Sync for Int {}
282
283impl Int {
284    /// Wraps a Lean object that is an `Int`, taking over the reference to it.
285    ///
286    /// # Safety
287    /// As for [`Nat::from_raw`], for an `Int`.
288    #[doc(hidden)]
289    pub unsafe fn from_raw(raw: Obj) -> Int {
290        Int(raw)
291    }
292
293    /// The number a Lean object is, giving up the caller's reference to the object. An
294    /// object that something else still holds is copied.
295    ///
296    /// # Safety
297    /// `raw` must be an `Int` produced by this runtime, and the caller must own a reference.
298    #[doc(hidden)]
299    #[inline]
300    pub unsafe fn owning(raw: Obj) -> Int {
301        Int(nat::owned(raw))
302    }
303
304    /// The Lean object, still owned by `self`.
305    #[doc(hidden)]
306    pub fn as_raw(&self) -> Obj {
307        self.0
308    }
309
310    /// The Lean object, with the reference `self` owned.
311    #[doc(hidden)]
312    pub fn into_raw(self) -> Obj {
313        let raw = self.0;
314        std::mem::forget(self);
315        raw
316    }
317}
318
319impl Clone for Int {
320    #[inline]
321    fn clone(&self) -> Int {
322        Int(unsafe { nat::unshared(self.0) })
323    }
324}
325
326impl Drop for Int {
327    #[inline]
328    fn drop(&mut self) {
329        unsafe { dec(self.0) };
330    }
331}
332
333impl Default for Int {
334    fn default() -> Int {
335        Int(box_(0))
336    }
337}
338
339impl From<&Int> for Int {
340    fn from(value: &Int) -> Int {
341        value.clone()
342    }
343}
344
345impl From<i128> for Int {
346    fn from(value: i128) -> Int {
347        Int(crate::int::of_i128(value))
348    }
349}
350
351impl From<Nat> for Int {
352    fn from(value: Nat) -> Int {
353        Int(unsafe { crate::int::nat_to_int(value.into_raw()) })
354    }
355}
356
357macro_rules! int_conversions {
358    ($($ty:ty),*) => {$(
359        impl From<$ty> for Int {
360            fn from(value: $ty) -> Int {
361                Int(crate::int::of_i128(value as i128))
362            }
363        }
364
365        impl TryFrom<&Int> for $ty {
366            type Error = TooLarge;
367
368            fn try_from(value: &Int) -> Result<$ty, TooLarge> {
369                i128::try_from(value)?.try_into().map_err(|_| TooLarge)
370            }
371        }
372
373        impl TryFrom<Int> for $ty {
374            type Error = TooLarge;
375
376            fn try_from(value: Int) -> Result<$ty, TooLarge> {
377                <$ty>::try_from(&value)
378            }
379        }
380    )*};
381}
382
383int_conversions!(i8, i16, i32, i64, isize);
384
385impl TryFrom<&Int> for i128 {
386    type Error = TooLarge;
387
388    fn try_from(value: &Int) -> Result<i128, TooLarge> {
389        unsafe { crate::int::to_i128(value.0) }.ok_or(TooLarge)
390    }
391}
392
393impl TryFrom<Int> for i128 {
394    type Error = TooLarge;
395
396    fn try_from(value: Int) -> Result<i128, TooLarge> {
397        i128::try_from(&value)
398    }
399}
400
401/// A string is not an integer in decimal digits.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub struct ParseIntError;
404
405impl fmt::Display for ParseIntError {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        f.write_str("expected an integer in decimal digits")
408    }
409}
410
411impl std::error::Error for ParseIntError {}
412
413impl FromStr for Int {
414    type Err = ParseIntError;
415
416    fn from_str(text: &str) -> Result<Int, ParseIntError> {
417        let (negative, digits) = match text.strip_prefix('-') {
418            Some(digits) => (true, digits),
419            None => (false, text),
420        };
421        crate::int::from_decimal(negative, digits).map(Int).ok_or(ParseIntError)
422    }
423}
424
425impl fmt::Display for Int {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        let text = unsafe { crate::int::to_decimal(self.0) };
428        match text.strip_prefix('-') {
429            Some(digits) => f.pad_integral(false, "", digits),
430            None => f.pad_integral(true, "", &text),
431        }
432    }
433}
434
435impl fmt::Debug for Int {
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        fmt::Display::fmt(self, f)
438    }
439}
440
441impl PartialEq for Int {
442    fn eq(&self, other: &Int) -> bool {
443        self.cmp(other) == Ordering::Equal
444    }
445}
446
447impl Eq for Int {}
448
449impl PartialOrd for Int {
450    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
451        Some(self.cmp(other))
452    }
453}
454
455impl Ord for Int {
456    fn cmp(&self, other: &Int) -> Ordering {
457        unsafe { crate::int::ordering(self.0, other.0) }
458    }
459}
460
461impl std::hash::Hash for Int {
462    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
463        unsafe { crate::int::hash(self.0, state) }
464    }
465}
466
467/// A Lean value of a type that a declaration bound to Rust is generic in.
468///
469/// The Rust function behind such a declaration is generic in the type as well, and this is
470/// what the type is when Lean calls it. So the function can pass the value on, hold it for
471/// the length of the call, clone it and give it back, and cannot look inside: all that a
472/// value of an unknown type allows, in Rust as in Lean. It is a Lean object, so it stays on
473/// the thread it is on.
474///
475/// Each type a declaration is generic in is a type of its own in Rust: `N` is the type's
476/// place among the declaration's type parameters. A Rust function therefore has to be
477/// generic in each of them apart. One that takes two values as one type, where they have
478/// two types in Lean, could give Lean a value of one type as a value of the other, and
479/// does not compile.
480///
481/// The lifetime closes the other way to do that. It is the call's own, so the type is not
482/// `'static`, and a value cannot be kept in a place that outlives the call or be told apart
483/// at run time.
484pub struct Generic<'a, const N: usize>(Obj, std::marker::PhantomData<&'a ()>);
485
486impl<const N: usize> Generic<'_, N> {
487    /// # Safety
488    /// `raw` is an object of this runtime, and the caller owns a reference to it.
489    #[doc(hidden)]
490    #[inline(always)]
491    pub unsafe fn from_raw(raw: Obj) -> Self {
492        Generic(raw, std::marker::PhantomData)
493    }
494
495    /// The Lean object, with the reference `self` owned.
496    #[doc(hidden)]
497    #[inline(always)]
498    pub fn into_raw(self) -> Obj {
499        let raw = self.0;
500        std::mem::forget(self);
501        raw
502    }
503}
504
505impl<const N: usize> Clone for Generic<'_, N> {
506    #[inline]
507    fn clone(&self) -> Self {
508        unsafe { crate::object::inc(self.0) };
509        Generic(self.0, std::marker::PhantomData)
510    }
511}
512
513impl<const N: usize> Drop for Generic<'_, N> {
514    #[inline]
515    fn drop(&mut self) {
516        unsafe { dec(self.0) };
517    }
518}