1use crate::nat;
5use crate::object::{box_, dec, inc, Obj};
6use std::cmp::Ordering;
7use std::fmt;
8use std::str::FromStr;
9
10pub struct Nat(Obj);
24
25impl Nat {
26 #[doc(hidden)]
31 pub unsafe fn from_raw(raw: Obj) -> Nat {
32 Nat(raw)
33 }
34
35 #[doc(hidden)]
37 pub fn as_raw(&self) -> Obj {
38 self.0
39 }
40
41 #[doc(hidden)]
43 pub fn into_raw(self) -> Obj {
44 let raw = self.0;
45 std::mem::forget(self);
46 raw
47 }
48}
49
50impl Clone for Nat {
51 fn clone(&self) -> Nat {
52 unsafe { inc(self.0) };
53 Nat(self.0)
54 }
55}
56
57impl Drop for Nat {
58 fn drop(&mut self) {
59 unsafe { dec(self.0) };
60 }
61}
62
63impl Default for Nat {
64 fn default() -> Nat {
65 Nat(box_(0))
66 }
67}
68
69impl From<&Nat> for Nat {
70 fn from(value: &Nat) -> Nat {
71 value.clone()
72 }
73}
74
75impl From<u128> for Nat {
76 fn from(value: u128) -> Nat {
77 Nat(nat::of_u128(value))
78 }
79}
80
81macro_rules! conversions {
82 ($($ty:ty),*) => {$(
83 impl From<$ty> for Nat {
84 fn from(value: $ty) -> Nat {
85 Nat(nat::uint64_to_nat(value as u64))
86 }
87 }
88
89 impl TryFrom<&Nat> for $ty {
90 type Error = TooLarge;
91
92 fn try_from(value: &Nat) -> Result<$ty, TooLarge> {
93 u128::try_from(value)?.try_into().map_err(|_| TooLarge)
94 }
95 }
96
97 impl TryFrom<Nat> for $ty {
98 type Error = TooLarge;
99
100 fn try_from(value: Nat) -> Result<$ty, TooLarge> {
101 <$ty>::try_from(&value)
102 }
103 }
104 )*};
105}
106
107conversions!(u8, u16, u32, u64, usize);
108
109impl TryFrom<&Nat> for u128 {
110 type Error = TooLarge;
111
112 fn try_from(value: &Nat) -> Result<u128, TooLarge> {
113 unsafe { nat::to_u128(value.0) }.ok_or(TooLarge)
114 }
115}
116
117impl TryFrom<Nat> for u128 {
118 type Error = TooLarge;
119
120 fn try_from(value: Nat) -> Result<u128, TooLarge> {
121 u128::try_from(&value)
122 }
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub struct TooLarge;
128
129impl fmt::Display for TooLarge {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.write_str("the natural number does not fit the integer type")
132 }
133}
134
135impl std::error::Error for TooLarge {}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct ParseNatError;
140
141impl fmt::Display for ParseNatError {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str("expected a natural number in decimal digits")
144 }
145}
146
147impl std::error::Error for ParseNatError {}
148
149impl FromStr for Nat {
150 type Err = ParseNatError;
151
152 fn from_str(text: &str) -> Result<Nat, ParseNatError> {
153 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
154 return Err(ParseNatError);
155 }
156 Ok(Nat(nat::cstr_to_nat(text)))
157 }
158}
159
160impl fmt::Display for Nat {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.pad_integral(true, "", &unsafe { nat::to_decimal(self.0) })
163 }
164}
165
166impl fmt::Debug for Nat {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 fmt::Display::fmt(self, f)
169 }
170}
171
172impl PartialEq for Nat {
173 fn eq(&self, other: &Nat) -> bool {
174 self.cmp(other) == Ordering::Equal
175 }
176}
177
178impl Eq for Nat {}
179
180impl PartialOrd for Nat {
181 fn partial_cmp(&self, other: &Nat) -> Option<Ordering> {
182 Some(self.cmp(other))
183 }
184}
185
186impl Ord for Nat {
187 fn cmp(&self, other: &Nat) -> Ordering {
188 unsafe { nat::ordering(self.0, other.0) }
189 }
190}
191
192impl std::hash::Hash for Nat {
193 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
194 unsafe { nat::to_decimal(self.0) }.hash(state);
195 }
196}
197
198pub trait ToLean {
204 #[doc(hidden)]
206 fn to_lean(&self) -> Obj;
207}
208
209pub trait FromLean: Sized {
211 #[doc(hidden)]
217 unsafe fn from_lean(object: Obj) -> Self;
218}
219
220impl<T: ToLean + ?Sized> ToLean for &T {
221 fn to_lean(&self) -> Obj {
222 (**self).to_lean()
223 }
224}
225
226macro_rules! boxed_scalars {
227 ($($ty:ty: |$value:ident| $to:expr, |$object:ident| $from:expr;)*) => {$(
228 impl ToLean for $ty {
229 fn to_lean(&self) -> Obj {
230 let $value = *self;
231 #[allow(unused_unsafe)]
233 unsafe {
234 $to
235 }
236 }
237 }
238
239 impl FromLean for $ty {
240 unsafe fn from_lean($object: Obj) -> $ty {
241 let value = $from;
242 dec($object);
243 value
244 }
245 }
246 )*};
247}
248
249use crate::object as o;
250
251boxed_scalars! {
252 u8: |v| box_(v as usize), |x| o::unbox(x) as u8;
253 u16: |v| box_(v as usize), |x| o::unbox(x) as u16;
254 u32: |v| o::box_uint32(v), |x| o::unbox_uint32(x);
255 u64: |v| o::box_uint64(v), |x| o::unbox_uint64(x);
256 usize: |v| o::box_usize(v), |x| o::unbox_usize(x);
257 i8: |v| box_(v as u8 as usize), |x| o::unbox(x) as u8 as i8;
258 i16: |v| box_(v as u16 as usize), |x| o::unbox(x) as u16 as i16;
259 i32: |v| o::box_uint32(v as u32), |x| o::unbox_uint32(x) as i32;
260 i64: |v| o::box_uint64(v as u64), |x| o::unbox_uint64(x) as i64;
261 isize: |v| o::box_usize(v as usize), |x| o::unbox_usize(x) as isize;
262 bool: |v| box_(v as usize), |x| o::unbox(x) != 0;
263 char: |v| o::box_uint32(v as u32), |x| crate::char_of_u32(o::unbox_uint32(x));
264 f64: |v| o::box_float(v), |x| o::unbox_float(x);
265 f32: |v| o::box_float32(v), |x| o::unbox_float32(x);
266}
267
268impl ToLean for () {
269 fn to_lean(&self) -> Obj {
270 box_(0)
271 }
272}
273
274impl FromLean for () {
275 unsafe fn from_lean(_object: Obj) {}
276}
277
278impl ToLean for Nat {
279 fn to_lean(&self) -> Obj {
280 self.clone().into_raw()
281 }
282}
283
284impl FromLean for Nat {
285 unsafe fn from_lean(object: Obj) -> Nat {
286 Nat(object)
287 }
288}
289
290impl ToLean for str {
291 fn to_lean(&self) -> Obj {
292 crate::string::mk_string(self)
293 }
294}
295
296impl ToLean for String {
297 fn to_lean(&self) -> Obj {
298 crate::string::mk_string(self)
299 }
300}
301
302impl FromLean for String {
303 unsafe fn from_lean(object: Obj) -> String {
304 crate::string::into_string(object)
305 }
306}
307
308impl<T: ToLean> ToLean for [T] {
309 fn to_lean(&self) -> Obj {
310 crate::array::from_vec(self.iter().map(ToLean::to_lean).collect())
311 }
312}
313
314impl<T: ToLean> ToLean for Vec<T> {
315 fn to_lean(&self) -> Obj {
316 self.as_slice().to_lean()
317 }
318}
319
320impl<T: FromLean> FromLean for Vec<T> {
321 unsafe fn from_lean(object: Obj) -> Vec<T> {
322 let items = crate::array::elements(object)
323 .iter()
324 .map(|&item| {
325 inc(item);
326 T::from_lean(item)
327 })
328 .collect();
329 dec(object);
330 items
331 }
332}
333
334impl<T: ToLean> ToLean for Option<T> {
335 fn to_lean(&self) -> Obj {
336 match self {
337 None => box_(0),
338 Some(value) => unsafe {
339 let some = o::alloc_ctor(1, 1, 0, 0);
340 o::ctor_set(some, 0, value.to_lean());
341 some
342 },
343 }
344 }
345}
346
347impl<T: FromLean> FromLean for Option<T> {
348 unsafe fn from_lean(object: Obj) -> Option<T> {
349 if o::is_scalar(object) {
350 return None;
351 }
352 let value = o::ctor_get(object, 0);
353 inc(value);
354 dec(object);
355 Some(T::from_lean(value))
356 }
357}
358
359impl<A: ToLean, B: ToLean> ToLean for (A, B) {
360 fn to_lean(&self) -> Obj {
361 unsafe {
362 let pair = o::alloc_ctor(0, 2, 0, 0);
363 o::ctor_set(pair, 0, self.0.to_lean());
364 o::ctor_set(pair, 1, self.1.to_lean());
365 pair
366 }
367 }
368}
369
370impl<A: FromLean, B: FromLean> FromLean for (A, B) {
371 unsafe fn from_lean(object: Obj) -> (A, B) {
372 let (first, second) = (o::ctor_get(object, 0), o::ctor_get(object, 1));
373 inc(first);
374 inc(second);
375 dec(object);
376 (A::from_lean(first), B::from_lean(second))
377 }
378}
379
380impl<T: ToLean> ToLean for Box<T> {
381 fn to_lean(&self) -> Obj {
382 (**self).to_lean()
383 }
384}
385
386impl<T: FromLean> FromLean for Box<T> {
387 unsafe fn from_lean(object: Obj) -> Box<T> {
388 Box::new(T::from_lean(object))
389 }
390}
391
392pub struct Int(Obj);
406
407impl Int {
408 #[doc(hidden)]
410 pub fn as_raw(&self) -> Obj {
411 self.0
412 }
413
414 #[doc(hidden)]
416 pub fn into_raw(self) -> Obj {
417 let raw = self.0;
418 std::mem::forget(self);
419 raw
420 }
421}
422
423impl Clone for Int {
424 fn clone(&self) -> Int {
425 unsafe { inc(self.0) };
426 Int(self.0)
427 }
428}
429
430impl Drop for Int {
431 fn drop(&mut self) {
432 unsafe { dec(self.0) };
433 }
434}
435
436impl Default for Int {
437 fn default() -> Int {
438 Int(box_(0))
439 }
440}
441
442impl From<&Int> for Int {
443 fn from(value: &Int) -> Int {
444 value.clone()
445 }
446}
447
448impl From<i128> for Int {
449 fn from(value: i128) -> Int {
450 Int(crate::int::of_i128(value))
451 }
452}
453
454impl From<Nat> for Int {
455 fn from(value: Nat) -> Int {
456 Int(unsafe { crate::int::nat_to_int(value.into_raw()) })
457 }
458}
459
460macro_rules! int_conversions {
461 ($($ty:ty),*) => {$(
462 impl From<$ty> for Int {
463 fn from(value: $ty) -> Int {
464 Int(crate::int::of_i128(value as i128))
465 }
466 }
467
468 impl TryFrom<&Int> for $ty {
469 type Error = TooLarge;
470
471 fn try_from(value: &Int) -> Result<$ty, TooLarge> {
472 i128::try_from(value)?.try_into().map_err(|_| TooLarge)
473 }
474 }
475
476 impl TryFrom<Int> for $ty {
477 type Error = TooLarge;
478
479 fn try_from(value: Int) -> Result<$ty, TooLarge> {
480 <$ty>::try_from(&value)
481 }
482 }
483 )*};
484}
485
486int_conversions!(i8, i16, i32, i64, isize);
487
488impl TryFrom<&Int> for i128 {
489 type Error = TooLarge;
490
491 fn try_from(value: &Int) -> Result<i128, TooLarge> {
492 unsafe { crate::int::to_i128(value.0) }.ok_or(TooLarge)
493 }
494}
495
496impl TryFrom<Int> for i128 {
497 type Error = TooLarge;
498
499 fn try_from(value: Int) -> Result<i128, TooLarge> {
500 i128::try_from(&value)
501 }
502}
503
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506pub struct ParseIntError;
507
508impl fmt::Display for ParseIntError {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 f.write_str("expected an integer in decimal digits")
511 }
512}
513
514impl std::error::Error for ParseIntError {}
515
516impl FromStr for Int {
517 type Err = ParseIntError;
518
519 fn from_str(text: &str) -> Result<Int, ParseIntError> {
520 let (negative, digits) = match text.strip_prefix('-') {
521 Some(digits) => (true, digits),
522 None => (false, text),
523 };
524 crate::int::from_decimal(negative, digits).map(Int).ok_or(ParseIntError)
525 }
526}
527
528impl fmt::Display for Int {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530 let text = unsafe { crate::int::to_decimal(self.0) };
531 match text.strip_prefix('-') {
532 Some(digits) => f.pad_integral(false, "", digits),
533 None => f.pad_integral(true, "", &text),
534 }
535 }
536}
537
538impl fmt::Debug for Int {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 fmt::Display::fmt(self, f)
541 }
542}
543
544impl PartialEq for Int {
545 fn eq(&self, other: &Int) -> bool {
546 self.cmp(other) == Ordering::Equal
547 }
548}
549
550impl Eq for Int {}
551
552impl PartialOrd for Int {
553 fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
554 Some(self.cmp(other))
555 }
556}
557
558impl Ord for Int {
559 fn cmp(&self, other: &Int) -> Ordering {
560 unsafe { crate::int::ordering(self.0, other.0) }
561 }
562}
563
564impl std::hash::Hash for Int {
565 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
566 unsafe { crate::int::to_decimal(self.0) }.hash(state);
567 }
568}
569
570impl ToLean for Int {
571 fn to_lean(&self) -> Obj {
572 self.clone().into_raw()
573 }
574}
575
576impl FromLean for Int {
577 unsafe fn from_lean(object: Obj) -> Int {
578 Int(object)
579 }
580}