inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Lean values as Rust values: the types that appear in the signatures of generated
//! functions.

use crate::nat;
use crate::object::{box_, dec, Obj};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;

/// A natural number of any size: Lean's `Nat`.
///
/// Converts from every unsigned integer type, and back with `TryFrom` when the value fits.
/// It prints and parses as decimal digits.
///
/// ```
/// use inlean_runtime::Nat;
/// let n: Nat = "340282366920938463463374607431768211456".parse().unwrap(); // 2^128
/// assert!(u128::try_from(&n).is_err());
/// assert_eq!(Nat::from(7u8).to_string(), "7");
/// ```
///
/// A `Nat` is `Send` and `Sync`, like an integer: it holds a number of its own. A clone of
/// a number too large for a machine word copies its digits.
pub struct Nat(Obj);

// Lean counts references without synchronization, so what a `Nat` holds is never an object
// that something else counts: it is a number in the pointer bits, the only reference to an
// object, or an object that is never counted. Nothing is written through a `&Nat`, and a
// `Nat` that is dropped frees an object no one else refers to.
unsafe impl Send for Nat {}
unsafe impl Sync for Nat {}

impl Nat {
    /// Wraps a Lean object that is a `Nat`, taking over the reference to it.
    ///
    /// # Safety
    /// `raw` must be a `Nat` produced by this runtime that nothing else counts on: a number
    /// in the pointer bits, an object the caller owns the only reference to, or one that is
    /// never counted. A value that only stands in for a number Lean holds, and is not
    /// dropped, may wrap any `Nat` for as long as nothing else changes its count.
    #[doc(hidden)]
    pub unsafe fn from_raw(raw: Obj) -> Nat {
        Nat(raw)
    }

    /// The number a Lean object is, giving up the caller's reference to the object. An
    /// object that something else still holds is copied.
    ///
    /// # Safety
    /// `raw` must be a `Nat` produced by this runtime, and the caller must own a reference.
    #[doc(hidden)]
    #[inline]
    pub unsafe fn owning(raw: Obj) -> Nat {
        Nat(nat::owned(raw))
    }

    /// The Lean object, still owned by `self`.
    #[doc(hidden)]
    pub fn as_raw(&self) -> Obj {
        self.0
    }

    /// The Lean object, with the reference `self` owned.
    #[doc(hidden)]
    pub fn into_raw(self) -> Obj {
        let raw = self.0;
        std::mem::forget(self);
        raw
    }
}

impl Clone for Nat {
    #[inline]
    fn clone(&self) -> Nat {
        Nat(unsafe { nat::unshared(self.0) })
    }
}

impl Drop for Nat {
    #[inline]
    fn drop(&mut self) {
        unsafe { dec(self.0) };
    }
}

impl Default for Nat {
    fn default() -> Nat {
        Nat(box_(0))
    }
}

impl From<&Nat> for Nat {
    fn from(value: &Nat) -> Nat {
        value.clone()
    }
}

impl From<u128> for Nat {
    fn from(value: u128) -> Nat {
        Nat(nat::of_u128(value))
    }
}

macro_rules! conversions {
    ($($ty:ty),*) => {$(
        impl From<$ty> for Nat {
            fn from(value: $ty) -> Nat {
                Nat(nat::uint64_to_nat(value as u64))
            }
        }

        impl TryFrom<&Nat> for $ty {
            type Error = TooLarge;

            fn try_from(value: &Nat) -> Result<$ty, TooLarge> {
                u128::try_from(value)?.try_into().map_err(|_| TooLarge)
            }
        }

        impl TryFrom<Nat> for $ty {
            type Error = TooLarge;

            fn try_from(value: Nat) -> Result<$ty, TooLarge> {
                <$ty>::try_from(&value)
            }
        }
    )*};
}

conversions!(u8, u16, u32, u64, usize);

impl TryFrom<&Nat> for u128 {
    type Error = TooLarge;

    fn try_from(value: &Nat) -> Result<u128, TooLarge> {
        unsafe { nat::to_u128(value.0) }.ok_or(TooLarge)
    }
}

impl TryFrom<Nat> for u128 {
    type Error = TooLarge;

    fn try_from(value: Nat) -> Result<u128, TooLarge> {
        u128::try_from(&value)
    }
}

impl Nat {
    /// The number with these 64-bit limbs, least significant first: the form in which
    /// fixed-width integer libraries hold their words.
    ///
    /// ```
    /// use inlean_runtime::Nat;
    /// assert_eq!(Nat::from_limbs(&[0, 1]), Nat::from(1u128 << 64));
    /// ```
    pub fn from_limbs(limbs: &[u64]) -> Nat {
        Nat(nat::of_limbs(limbs))
    }

    /// The 64-bit limbs of the number, least significant first, without leading zeros.
    pub fn to_limbs(&self) -> Vec<u64> {
        unsafe { nat::with_limbs(self.0, <[u64]>::to_vec) }
    }
}

impl<const N: usize> From<[u64; N]> for Nat {
    /// The number with these limbs, least significant first.
    fn from(limbs: [u64; N]) -> Nat {
        Nat::from_limbs(&limbs)
    }
}

impl<const N: usize> TryFrom<&Nat> for [u64; N] {
    type Error = TooLarge;

    /// The limbs of the number, least significant first, when it is below 2^(64·N).
    fn try_from(value: &Nat) -> Result<[u64; N], TooLarge> {
        unsafe { nat::with_limbs(value.0, crate::codec::fixed_limbs) }.ok_or(TooLarge)
    }
}

impl<const N: usize> TryFrom<Nat> for [u64; N] {
    type Error = TooLarge;

    fn try_from(value: Nat) -> Result<[u64; N], TooLarge> {
        <[u64; N]>::try_from(&value)
    }
}

/// A [`Nat`] does not fit the integer type it was converted to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TooLarge;

impl fmt::Display for TooLarge {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the natural number does not fit the integer type")
    }
}

impl std::error::Error for TooLarge {}

/// A string is not a natural number in decimal digits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseNatError;

impl fmt::Display for ParseNatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("expected a natural number in decimal digits")
    }
}

impl std::error::Error for ParseNatError {}

impl FromStr for Nat {
    type Err = ParseNatError;

    fn from_str(text: &str) -> Result<Nat, ParseNatError> {
        if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
            return Err(ParseNatError);
        }
        Ok(Nat(nat::cstr_to_nat(text)))
    }
}

impl fmt::Display for Nat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad_integral(true, "", &unsafe { nat::to_decimal(self.0) })
    }
}

impl fmt::Debug for Nat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl PartialEq for Nat {
    fn eq(&self, other: &Nat) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Nat {}

impl PartialOrd for Nat {
    fn partial_cmp(&self, other: &Nat) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Nat {
    fn cmp(&self, other: &Nat) -> Ordering {
        unsafe { nat::ordering(self.0, other.0) }
    }
}

impl std::hash::Hash for Nat {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // The limbs without leading zeros: one sequence for each number.
        unsafe { nat::with_limbs(self.0, |limbs| limbs.hash(state)) }
    }
}

/// An integer of any size: Lean's `Int`.
///
/// Converts from every signed integer type, and back with `TryFrom` when the value fits. It
/// prints and parses as decimal digits with an optional minus sign.
///
/// ```
/// use inlean_runtime::Int;
/// let n: Int = "-170141183460469231731687303715884105729".parse().unwrap(); // -2^127 - 1
/// assert!(i128::try_from(&n).is_err());
/// assert_eq!(Int::from(-7i8).to_string(), "-7");
/// ```
///
/// Like [`Nat`], an `Int` is `Send` and `Sync`, and a clone of a large one copies its digits.
pub struct Int(Obj);

// As for `Nat`: what an `Int` holds is never an object that something else counts.
unsafe impl Send for Int {}
unsafe impl Sync for Int {}

impl Int {
    /// Wraps a Lean object that is an `Int`, taking over the reference to it.
    ///
    /// # Safety
    /// As for [`Nat::from_raw`], for an `Int`.
    #[doc(hidden)]
    pub unsafe fn from_raw(raw: Obj) -> Int {
        Int(raw)
    }

    /// The number a Lean object is, giving up the caller's reference to the object. An
    /// object that something else still holds is copied.
    ///
    /// # Safety
    /// `raw` must be an `Int` produced by this runtime, and the caller must own a reference.
    #[doc(hidden)]
    #[inline]
    pub unsafe fn owning(raw: Obj) -> Int {
        Int(nat::owned(raw))
    }

    /// The Lean object, still owned by `self`.
    #[doc(hidden)]
    pub fn as_raw(&self) -> Obj {
        self.0
    }

    /// The Lean object, with the reference `self` owned.
    #[doc(hidden)]
    pub fn into_raw(self) -> Obj {
        let raw = self.0;
        std::mem::forget(self);
        raw
    }
}

impl Clone for Int {
    #[inline]
    fn clone(&self) -> Int {
        Int(unsafe { nat::unshared(self.0) })
    }
}

impl Drop for Int {
    #[inline]
    fn drop(&mut self) {
        unsafe { dec(self.0) };
    }
}

impl Default for Int {
    fn default() -> Int {
        Int(box_(0))
    }
}

impl From<&Int> for Int {
    fn from(value: &Int) -> Int {
        value.clone()
    }
}

impl From<i128> for Int {
    fn from(value: i128) -> Int {
        Int(crate::int::of_i128(value))
    }
}

impl From<Nat> for Int {
    fn from(value: Nat) -> Int {
        Int(unsafe { crate::int::nat_to_int(value.into_raw()) })
    }
}

macro_rules! int_conversions {
    ($($ty:ty),*) => {$(
        impl From<$ty> for Int {
            fn from(value: $ty) -> Int {
                Int(crate::int::of_i128(value as i128))
            }
        }

        impl TryFrom<&Int> for $ty {
            type Error = TooLarge;

            fn try_from(value: &Int) -> Result<$ty, TooLarge> {
                i128::try_from(value)?.try_into().map_err(|_| TooLarge)
            }
        }

        impl TryFrom<Int> for $ty {
            type Error = TooLarge;

            fn try_from(value: Int) -> Result<$ty, TooLarge> {
                <$ty>::try_from(&value)
            }
        }
    )*};
}

int_conversions!(i8, i16, i32, i64, isize);

impl TryFrom<&Int> for i128 {
    type Error = TooLarge;

    fn try_from(value: &Int) -> Result<i128, TooLarge> {
        unsafe { crate::int::to_i128(value.0) }.ok_or(TooLarge)
    }
}

impl TryFrom<Int> for i128 {
    type Error = TooLarge;

    fn try_from(value: Int) -> Result<i128, TooLarge> {
        i128::try_from(&value)
    }
}

/// A string is not an integer in decimal digits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseIntError;

impl fmt::Display for ParseIntError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("expected an integer in decimal digits")
    }
}

impl std::error::Error for ParseIntError {}

impl FromStr for Int {
    type Err = ParseIntError;

    fn from_str(text: &str) -> Result<Int, ParseIntError> {
        let (negative, digits) = match text.strip_prefix('-') {
            Some(digits) => (true, digits),
            None => (false, text),
        };
        crate::int::from_decimal(negative, digits).map(Int).ok_or(ParseIntError)
    }
}

impl fmt::Display for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = unsafe { crate::int::to_decimal(self.0) };
        match text.strip_prefix('-') {
            Some(digits) => f.pad_integral(false, "", digits),
            None => f.pad_integral(true, "", &text),
        }
    }
}

impl fmt::Debug for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl PartialEq for Int {
    fn eq(&self, other: &Int) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Int {}

impl PartialOrd for Int {
    fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Int {
    fn cmp(&self, other: &Int) -> Ordering {
        unsafe { crate::int::ordering(self.0, other.0) }
    }
}

impl std::hash::Hash for Int {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        unsafe { crate::int::hash(self.0, state) }
    }
}

/// A Lean value of a type that a declaration bound to Rust is generic in.
///
/// The Rust function behind such a declaration is generic in the type as well, and this is
/// what the type is when Lean calls it. So the function can pass the value on, hold it for
/// the length of the call, clone it and give it back, and cannot look inside: all that a
/// value of an unknown type allows, in Rust as in Lean. It is a Lean object, so it stays on
/// the thread it is on.
///
/// Each type a declaration is generic in is a type of its own in Rust: `N` is the type's
/// place among the declaration's type parameters. A Rust function therefore has to be
/// generic in each of them apart. One that takes two values as one type, where they have
/// two types in Lean, could give Lean a value of one type as a value of the other, and
/// does not compile.
///
/// The lifetime closes the other way to do that. It is the call's own, so the type is not
/// `'static`, and a value cannot be kept in a place that outlives the call or be told apart
/// at run time.
pub struct Generic<'a, const N: usize>(Obj, std::marker::PhantomData<&'a ()>);

impl<const N: usize> Generic<'_, N> {
    /// # Safety
    /// `raw` is an object of this runtime, and the caller owns a reference to it.
    #[doc(hidden)]
    #[inline(always)]
    pub unsafe fn from_raw(raw: Obj) -> Self {
        Generic(raw, std::marker::PhantomData)
    }

    /// The Lean object, with the reference `self` owned.
    #[doc(hidden)]
    #[inline(always)]
    pub fn into_raw(self) -> Obj {
        let raw = self.0;
        std::mem::forget(self);
        raw
    }
}

impl<const N: usize> Clone for Generic<'_, N> {
    #[inline]
    fn clone(&self) -> Self {
        unsafe { crate::object::inc(self.0) };
        Generic(self.0, std::marker::PhantomData)
    }
}

impl<const N: usize> Drop for Generic<'_, N> {
    #[inline]
    fn drop(&mut self) {
        unsafe { dec(self.0) };
    }
}