1use crate::array::*;
9use crate::int::{int_value, mk_int};
10use crate::nat::{mk_nat, nat_to_usize, nat_value};
11use crate::object::*;
12use crate::string::*;
13use core::fmt;
14use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
15use core::str::FromStr;
16use num_bigint::{BigInt, BigUint, Sign};
17use num_traits::Zero;
18
19pub trait ToLean {
21 unsafe fn to_lean(self) -> Obj;
27}
28
29pub trait FromLean: Sized {
31 unsafe fn from_lean(o: Obj) -> Self;
37}
38
39#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct Nat(BigUint);
45
46impl Nat {
47 pub fn new(v: BigUint) -> Self {
48 Nat(v)
49 }
50
51 pub fn as_biguint(&self) -> &BigUint {
52 &self.0
53 }
54
55 pub fn into_biguint(self) -> BigUint {
56 self.0
57 }
58}
59
60#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct Int(BigInt);
63
64impl Int {
65 pub fn new(v: BigInt) -> Self {
66 Int(v)
67 }
68
69 pub fn as_bigint(&self) -> &BigInt {
70 &self.0
71 }
72
73 pub fn into_bigint(self) -> BigInt {
74 self.0
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct OutOfRange;
81
82impl fmt::Display for OutOfRange {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str("the number does not fit in the target type")
85 }
86}
87
88impl std::error::Error for OutOfRange {}
89
90macro_rules! nat_from {
91 ($($t:ty),*) => {$(
92 impl From<$t> for Nat {
93 fn from(v: $t) -> Self {
94 Nat(BigUint::from(v))
95 }
96 }
97 impl TryFrom<Nat> for $t {
98 type Error = OutOfRange;
99 fn try_from(v: Nat) -> Result<Self, OutOfRange> {
100 <$t>::try_from(&v)
101 }
102 }
103 impl TryFrom<&Nat> for $t {
104 type Error = OutOfRange;
105 fn try_from(v: &Nat) -> Result<Self, OutOfRange> {
106 <$t>::try_from(&v.0).map_err(|_| OutOfRange)
107 }
108 }
109 )*};
110}
111
112nat_from!(u8, u16, u32, u64, u128, usize);
113
114macro_rules! int_from {
115 ($($t:ty),*) => {$(
116 impl From<$t> for Int {
117 fn from(v: $t) -> Self {
118 Int(BigInt::from(v))
119 }
120 }
121 impl TryFrom<Int> for $t {
122 type Error = OutOfRange;
123 fn try_from(v: Int) -> Result<Self, OutOfRange> {
124 <$t>::try_from(&v)
125 }
126 }
127 impl TryFrom<&Int> for $t {
128 type Error = OutOfRange;
129 fn try_from(v: &Int) -> Result<Self, OutOfRange> {
130 <$t>::try_from(&v.0).map_err(|_| OutOfRange)
131 }
132 }
133 )*};
134}
135
136int_from!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
137
138impl From<BigUint> for Nat {
139 fn from(v: BigUint) -> Self {
140 Nat(v)
141 }
142}
143
144impl From<BigInt> for Int {
145 fn from(v: BigInt) -> Self {
146 Int(v)
147 }
148}
149
150impl From<Nat> for Int {
151 fn from(v: Nat) -> Self {
152 Int(BigInt::from(v.0))
153 }
154}
155
156impl TryFrom<Int> for Nat {
157 type Error = OutOfRange;
158 fn try_from(v: Int) -> Result<Self, OutOfRange> {
159 v.0.to_biguint().map(Nat).ok_or(OutOfRange)
160 }
161}
162
163impl fmt::Display for Nat {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 fmt::Display::fmt(&self.0, f)
166 }
167}
168
169impl fmt::Debug for Nat {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 fmt::Display::fmt(&self.0, f)
172 }
173}
174
175impl fmt::Display for Int {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 fmt::Display::fmt(&self.0, f)
178 }
179}
180
181impl fmt::Debug for Int {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 fmt::Display::fmt(&self.0, f)
184 }
185}
186
187impl FromStr for Nat {
188 type Err = num_bigint::ParseBigIntError;
189 fn from_str(s: &str) -> Result<Self, Self::Err> {
190 s.parse().map(Nat)
191 }
192}
193
194impl FromStr for Int {
195 type Err = num_bigint::ParseBigIntError;
196 fn from_str(s: &str) -> Result<Self, Self::Err> {
197 s.parse().map(Int)
198 }
199}
200
201impl Add for Nat {
202 type Output = Nat;
203 fn add(self, rhs: Nat) -> Nat {
204 Nat(self.0 + rhs.0)
205 }
206}
207
208impl Sub for Nat {
209 type Output = Nat;
210 fn sub(self, rhs: Nat) -> Nat {
211 if self.0 <= rhs.0 {
212 Nat::default()
213 } else {
214 Nat(self.0 - rhs.0)
215 }
216 }
217}
218
219impl Mul for Nat {
220 type Output = Nat;
221 fn mul(self, rhs: Nat) -> Nat {
222 Nat(self.0 * rhs.0)
223 }
224}
225
226impl Div for Nat {
227 type Output = Nat;
228 fn div(self, rhs: Nat) -> Nat {
229 if rhs.0.is_zero() {
230 Nat::default()
231 } else {
232 Nat(self.0 / rhs.0)
233 }
234 }
235}
236
237impl Rem for Nat {
238 type Output = Nat;
239 fn rem(self, rhs: Nat) -> Nat {
240 if rhs.0.is_zero() {
241 self
242 } else {
243 Nat(self.0 % rhs.0)
244 }
245 }
246}
247
248impl Add for Int {
249 type Output = Int;
250 fn add(self, rhs: Int) -> Int {
251 Int(self.0 + rhs.0)
252 }
253}
254
255impl Sub for Int {
256 type Output = Int;
257 fn sub(self, rhs: Int) -> Int {
258 Int(self.0 - rhs.0)
259 }
260}
261
262impl Mul for Int {
263 type Output = Int;
264 fn mul(self, rhs: Int) -> Int {
265 Int(self.0 * rhs.0)
266 }
267}
268
269impl Neg for Int {
270 type Output = Int;
271 fn neg(self) -> Int {
272 Int(-self.0)
273 }
274}
275
276impl ToLean for Nat {
279 unsafe fn to_lean(self) -> Obj {
280 mk_nat(BigInt::from_biguint(Sign::Plus, self.0))
281 }
282}
283
284impl FromLean for Nat {
285 unsafe fn from_lean(o: Obj) -> Self {
286 Nat(nat_value(o).to_biguint().unwrap_or_default())
287 }
288}
289
290impl ToLean for Int {
291 unsafe fn to_lean(self) -> Obj {
292 mk_int(self.0)
293 }
294}
295
296impl FromLean for Int {
297 unsafe fn from_lean(o: Obj) -> Self {
298 Int(int_value(o))
299 }
300}
301
302impl ToLean for bool {
303 unsafe fn to_lean(self) -> Obj {
304 lean_box(self as usize)
305 }
306}
307
308impl FromLean for bool {
309 unsafe fn from_lean(o: Obj) -> Self {
310 lean_unbox(o) != 0
311 }
312}
313
314macro_rules! small_scalar {
315 ($($t:ty => $u:ty),*) => {$(
316 impl ToLean for $t {
317 unsafe fn to_lean(self) -> Obj {
318 lean_box(self as $u as usize)
319 }
320 }
321 impl FromLean for $t {
322 unsafe fn from_lean(o: Obj) -> Self {
323 lean_unbox(o) as $u as $t
324 }
325 }
326 )*};
327}
328
329small_scalar!(u8 => u8, u16 => u16, i8 => u8, i16 => u16);
330
331macro_rules! boxed_scalar {
332 ($($t:ty => $u:ty, $box:ident, $unbox:ident);*) => {$(
333 impl ToLean for $t {
334 unsafe fn to_lean(self) -> Obj {
335 $box(self as $u)
336 }
337 }
338 impl FromLean for $t {
339 unsafe fn from_lean(o: Obj) -> Self {
340 $unbox(o) as $t
341 }
342 }
343 )*};
344}
345
346boxed_scalar!(
347 u32 => u32, lean_box_uint32, lean_unbox_uint32;
348 i32 => u32, lean_box_uint32, lean_unbox_uint32;
349 u64 => u64, lean_box_uint64, lean_unbox_uint64;
350 i64 => u64, lean_box_uint64, lean_unbox_uint64;
351 usize => usize, lean_box_usize, lean_unbox_usize;
352 isize => usize, lean_box_usize, lean_unbox_usize;
353 f64 => f64, lean_box_float, lean_unbox_float;
354 f32 => f32, lean_box_float32, lean_unbox_float32
355);
356
357impl ToLean for char {
358 unsafe fn to_lean(self) -> Obj {
359 lean_box_uint32(self as u32)
360 }
361}
362
363impl FromLean for char {
364 unsafe fn from_lean(o: Obj) -> Self {
365 char_of_u32(lean_unbox_uint32(o))
366 }
367}
368
369impl ToLean for () {
370 unsafe fn to_lean(self) -> Obj {
371 lean_box(0)
372 }
373}
374
375impl FromLean for () {
376 unsafe fn from_lean(_o: Obj) -> Self {}
377}
378
379impl ToLean for &str {
380 unsafe fn to_lean(self) -> Obj {
381 lean_mk_string(self)
382 }
383}
384
385impl ToLean for String {
386 unsafe fn to_lean(self) -> Obj {
387 lean_mk_string(&self)
388 }
389}
390
391impl FromLean for String {
392 unsafe fn from_lean(o: Obj) -> Self {
393 lean_string_to_str(o).to_owned()
394 }
395}
396
397pub fn char_of_u32(c: u32) -> char {
399 char::from_u32(c).expect("a Lean Char is a Unicode scalar value")
400}
401
402pub unsafe fn list_to_lean<T>(v: Vec<T>, mut f: impl FnMut(T) -> Obj) -> Obj {
406 let elems: Vec<Obj> = v.into_iter().map(&mut f).collect();
407 let mut r = lean_box(0);
408 for e in elems.into_iter().rev() {
409 let c = lean_alloc_ctor(1, 2, 0);
410 lean_ctor_set(c, 0, e);
411 lean_ctor_set(c, 1, r);
412 r = c;
413 }
414 r
415}
416
417pub unsafe fn list_from_lean<T>(mut o: Obj, mut f: impl FnMut(Obj) -> T) -> Vec<T> {
419 let mut out = Vec::new();
420 while !lean_is_scalar(o) {
421 out.push(f(lean_ctor_get(o, 0)));
422 o = lean_ctor_get(o, 1);
423 }
424 out
425}
426
427pub unsafe fn array_to_lean<T>(v: Vec<T>, mut f: impl FnMut(T) -> Obj) -> Obj {
429 let a = lean_alloc_array(0, v.len());
430 for (i, x) in v.into_iter().enumerate() {
431 lean_array_set_core(a, i, f(x));
432 lean_array_set_size(a, i + 1);
433 }
434 a
435}
436
437pub unsafe fn array_from_lean<T>(o: Obj, mut f: impl FnMut(Obj) -> T) -> Vec<T> {
439 (0..lean_array_size(o))
440 .map(|i| f(lean_array_get_core(o, i)))
441 .collect()
442}
443
444pub unsafe fn option_to_lean<T>(v: Option<T>, f: impl FnOnce(T) -> Obj) -> Obj {
446 match v {
447 None => lean_box(0),
448 Some(x) => {
449 let c = lean_alloc_ctor(1, 1, 0);
450 lean_ctor_set(c, 0, f(x));
451 c
452 }
453 }
454}
455
456pub unsafe fn option_from_lean<T>(o: Obj, f: impl FnOnce(Obj) -> T) -> Option<T> {
458 if lean_is_scalar(o) {
459 None
460 } else {
461 Some(f(lean_ctor_get(o, 0)))
462 }
463}
464
465pub unsafe fn except_to_lean<T, E>(
467 v: Result<T, E>,
468 fe: impl FnOnce(E) -> Obj,
469 fa: impl FnOnce(T) -> Obj,
470) -> Obj {
471 let (tag, x) = match v {
472 Err(e) => (0, fe(e)),
473 Ok(a) => (1, fa(a)),
474 };
475 let c = lean_alloc_ctor(tag, 1, 0);
476 lean_ctor_set(c, 0, x);
477 c
478}
479
480pub unsafe fn except_from_lean<T, E>(
482 o: Obj,
483 fe: impl FnOnce(Obj) -> E,
484 fa: impl FnOnce(Obj) -> T,
485) -> Result<T, E> {
486 if lean_obj_tag(o) == 0 {
487 Err(fe(lean_ctor_get(o, 0)))
488 } else {
489 Ok(fa(lean_ctor_get(o, 0)))
490 }
491}
492
493pub unsafe fn prod_to_lean<A, B>(
495 v: (A, B),
496 fa: impl FnOnce(A) -> Obj,
497 fb: impl FnOnce(B) -> Obj,
498) -> Obj {
499 let c = lean_alloc_ctor(0, 2, 0);
500 lean_ctor_set(c, 0, fa(v.0));
501 lean_ctor_set(c, 1, fb(v.1));
502 c
503}
504
505pub unsafe fn prod_from_lean<A, B>(
507 o: Obj,
508 fa: impl FnOnce(Obj) -> A,
509 fb: impl FnOnce(Obj) -> B,
510) -> (A, B) {
511 (fa(lean_ctor_get(o, 0)), fb(lean_ctor_get(o, 1)))
512}
513
514pub unsafe fn fin_to_lean(i: usize, n: usize) -> Obj {
516 assert!(i < n, "Fin {n}: index {i} is out of range");
517 crate::nat::lean_usize_to_nat(i)
518}
519
520pub unsafe fn fin_from_lean(o: Obj) -> usize {
522 nat_to_usize(o).expect("a Fin value fits in usize")
523}
524
525pub unsafe fn io_error_to_std(e: Obj, msg: Obj) -> std::io::Error {
530 use std::io::ErrorKind;
531 let text = lean_string_to_str(msg).to_owned();
532 crate::object::lean_dec(msg);
533 let kind = match lean_obj_tag(e) {
534 0 => ErrorKind::AlreadyExists,
535 2 => ErrorKind::ResourceBusy,
536 4 => ErrorKind::Unsupported,
537 9 => ErrorKind::TimedOut,
538 10 => ErrorKind::Interrupted,
539 11 => ErrorKind::NotFound,
540 12 => ErrorKind::InvalidInput,
541 13 => ErrorKind::PermissionDenied,
542 14 => ErrorKind::OutOfMemory,
543 17 => ErrorKind::UnexpectedEof,
544 _ => ErrorKind::Other,
545 };
546 std::io::Error::new(kind, text)
547}