use crate::nat;
use crate::object::{box_, dec, inc, Obj};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;
pub struct Nat(Obj);
impl Nat {
#[doc(hidden)]
pub unsafe fn from_raw(raw: Obj) -> Nat {
Nat(raw)
}
#[doc(hidden)]
pub fn as_raw(&self) -> Obj {
self.0
}
#[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)
}
}
#[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 {}
#[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);
}
}
pub trait ToLean {
#[doc(hidden)]
fn to_lean(&self) -> Obj;
}
pub trait FromLean: Sized {
#[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;
#[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))
}
}
pub struct Int(Obj);
impl Int {
#[doc(hidden)]
pub fn as_raw(&self) -> Obj {
self.0
}
#[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)
}
}
#[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)
}
}