inlean-runtime 0.1.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Lean values as Rust values: the types that appear in the signatures of generated
//! functions.

use crate::nat;
use crate::object::{box_, dec, inc, 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` cannot be sent to another thread: Lean counts references without synchronization.
pub struct Nat(Obj);

impl Nat {
    /// Wraps a Lean object that is a `Nat`, taking over one reference to it.
    ///
    /// # Safety
    /// `raw` must be a `Nat` produced by this runtime, and the caller must own a reference.
    #[doc(hidden)]
    pub unsafe fn from_raw(raw: Obj) -> Nat {
        Nat(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 {
    fn clone(&self) -> Nat {
        unsafe { inc(self.0) };
        Nat(self.0)
    }
}

impl Drop for Nat {
    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)
    }
}

/// 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) {
        unsafe { nat::to_decimal(self.0) }.hash(state);
    }
}

/// A Rust value that has a Lean counterpart: the conversion into the Lean object.
///
/// Implemented for the types that can appear in the signature of a generated function. The
/// Lean type is determined by the Rust type: `u32` is `UInt32`, `&str` and `String` are
/// `String`, slices and `Vec<T>` are `Array`, `Option<T>` is `Option`, pairs are `Prod`.
pub trait ToLean {
    /// A new Lean object with the value of `self`, owned by the caller.
    #[doc(hidden)]
    fn to_lean(&self) -> Obj;
}

/// The conversion from a Lean object back to the Rust value.
pub trait FromLean: Sized {
    /// Reads the value out of `object` and gives up one reference to it.
    ///
    /// # Safety
    /// `object` must be a value of the Lean type that corresponds to `Self`, produced by this
    /// runtime, and the caller must own a reference to it.
    #[doc(hidden)]
    unsafe fn from_lean(object: Obj) -> Self;
}

impl<T: ToLean + ?Sized> ToLean for &T {
    fn to_lean(&self) -> Obj {
        (**self).to_lean()
    }
}

macro_rules! boxed_scalars {
    ($($ty:ty: |$value:ident| $to:expr, |$object:ident| $from:expr;)*) => {$(
        impl ToLean for $ty {
            fn to_lean(&self) -> Obj {
                let $value = *self;
                // Allocation aside, boxing has no precondition.
                #[allow(unused_unsafe)]
                unsafe {
                    $to
                }
            }
        }

        impl FromLean for $ty {
            unsafe fn from_lean($object: Obj) -> $ty {
                let value = $from;
                dec($object);
                value
            }
        }
    )*};
}

use crate::object as o;

boxed_scalars! {
    u8: |v| box_(v as usize), |x| o::unbox(x) as u8;
    u16: |v| box_(v as usize), |x| o::unbox(x) as u16;
    u32: |v| o::box_uint32(v), |x| o::unbox_uint32(x);
    u64: |v| o::box_uint64(v), |x| o::unbox_uint64(x);
    usize: |v| o::box_usize(v), |x| o::unbox_usize(x);
    i8: |v| box_(v as u8 as usize), |x| o::unbox(x) as u8 as i8;
    i16: |v| box_(v as u16 as usize), |x| o::unbox(x) as u16 as i16;
    i32: |v| o::box_uint32(v as u32), |x| o::unbox_uint32(x) as i32;
    i64: |v| o::box_uint64(v as u64), |x| o::unbox_uint64(x) as i64;
    isize: |v| o::box_usize(v as usize), |x| o::unbox_usize(x) as isize;
    bool: |v| box_(v as usize), |x| o::unbox(x) != 0;
    char: |v| o::box_uint32(v as u32), |x| crate::char_of_u32(o::unbox_uint32(x));
    f64: |v| o::box_float(v), |x| o::unbox_float(x);
    f32: |v| o::box_float32(v), |x| o::unbox_float32(x);
}

impl ToLean for () {
    fn to_lean(&self) -> Obj {
        box_(0)
    }
}

impl FromLean for () {
    unsafe fn from_lean(_object: Obj) {}
}

impl ToLean for Nat {
    fn to_lean(&self) -> Obj {
        self.clone().into_raw()
    }
}

impl FromLean for Nat {
    unsafe fn from_lean(object: Obj) -> Nat {
        Nat(object)
    }
}

impl ToLean for str {
    fn to_lean(&self) -> Obj {
        crate::string::mk_string(self)
    }
}

impl ToLean for String {
    fn to_lean(&self) -> Obj {
        crate::string::mk_string(self)
    }
}

impl FromLean for String {
    unsafe fn from_lean(object: Obj) -> String {
        crate::string::into_string(object)
    }
}

impl<T: ToLean> ToLean for [T] {
    fn to_lean(&self) -> Obj {
        crate::array::from_vec(self.iter().map(ToLean::to_lean).collect())
    }
}

impl<T: ToLean> ToLean for Vec<T> {
    fn to_lean(&self) -> Obj {
        self.as_slice().to_lean()
    }
}

impl<T: FromLean> FromLean for Vec<T> {
    unsafe fn from_lean(object: Obj) -> Vec<T> {
        let items = crate::array::elements(object)
            .iter()
            .map(|&item| {
                inc(item);
                T::from_lean(item)
            })
            .collect();
        dec(object);
        items
    }
}

impl<T: ToLean> ToLean for Option<T> {
    fn to_lean(&self) -> Obj {
        match self {
            None => box_(0),
            Some(value) => unsafe {
                let some = o::alloc_ctor(1, 1, 0, 0);
                o::ctor_set(some, 0, value.to_lean());
                some
            },
        }
    }
}

impl<T: FromLean> FromLean for Option<T> {
    unsafe fn from_lean(object: Obj) -> Option<T> {
        if o::is_scalar(object) {
            return None;
        }
        let value = o::ctor_get(object, 0);
        inc(value);
        dec(object);
        Some(T::from_lean(value))
    }
}

impl<A: ToLean, B: ToLean> ToLean for (A, B) {
    fn to_lean(&self) -> Obj {
        unsafe {
            let pair = o::alloc_ctor(0, 2, 0, 0);
            o::ctor_set(pair, 0, self.0.to_lean());
            o::ctor_set(pair, 1, self.1.to_lean());
            pair
        }
    }
}

impl<A: FromLean, B: FromLean> FromLean for (A, B) {
    unsafe fn from_lean(object: Obj) -> (A, B) {
        let (first, second) = (o::ctor_get(object, 0), o::ctor_get(object, 1));
        inc(first);
        inc(second);
        dec(object);
        (A::from_lean(first), B::from_lean(second))
    }
}

impl<T: ToLean> ToLean for Box<T> {
    fn to_lean(&self) -> Obj {
        (**self).to_lean()
    }
}

impl<T: FromLean> FromLean for Box<T> {
    unsafe fn from_lean(object: Obj) -> Box<T> {
        Box::new(T::from_lean(object))
    }
}

/// 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` cannot be sent to another thread.
pub struct Int(Obj);

impl Int {
    /// 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 {
    fn clone(&self) -> Int {
        unsafe { inc(self.0) };
        Int(self.0)
    }
}

impl Drop for Int {
    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::to_decimal(self.0) }.hash(state);
    }
}

impl ToLean for Int {
    fn to_lean(&self) -> Obj {
        self.clone().into_raw()
    }
}

impl FromLean for Int {
    unsafe fn from_lean(object: Obj) -> Int {
        Int(object)
    }
}