refactor: extract core objects into a standalone package
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m34s
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m34s
This commit is contained in:
@@ -0,0 +1,317 @@
|
||||
//! Lossless number representations. Arithmetic and numeric equivalence are
|
||||
//! deliberately separate from representation equality.
|
||||
|
||||
use std::any::Any;
|
||||
use std::fmt;
|
||||
|
||||
use crate::{CompareOp, ObjectPayload, ObjectRef, VmError};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EndorInteger {
|
||||
negative: bool,
|
||||
digits: String,
|
||||
}
|
||||
|
||||
impl EndorInteger {
|
||||
/// Decimal digits of any length, limited only by available memory.
|
||||
pub fn parse(text: &str) -> Result<Self, VmError> {
|
||||
let (negative, digits) = split_sign(text);
|
||||
if !is_digits(digits) {
|
||||
return Err(VmError::InvalidArgument("invalid integer"));
|
||||
}
|
||||
let digits = digits.trim_start_matches('0');
|
||||
Ok(Self {
|
||||
negative: negative && !digits.is_empty(),
|
||||
digits: if digits.is_empty() { "0" } else { digits }.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn digits(&self) -> &str {
|
||||
&self.digits
|
||||
}
|
||||
|
||||
pub fn is_negative(&self) -> bool {
|
||||
self.negative
|
||||
}
|
||||
|
||||
pub fn is_zero(&self) -> bool {
|
||||
self.digits == "0"
|
||||
}
|
||||
|
||||
pub fn to_i64(&self) -> Option<i64> {
|
||||
self.to_string().parse().ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EndorInteger {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.negative {
|
||||
f.write_str("-")?;
|
||||
}
|
||||
f.write_str(&self.digits)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EndorDecimal {
|
||||
literal: String,
|
||||
zero: bool,
|
||||
}
|
||||
|
||||
impl EndorDecimal {
|
||||
/// Retains all digits, trailing zeroes, sign, and an arbitrarily long
|
||||
/// decimal exponent. No intermediate binary floating-point conversion.
|
||||
pub fn parse(text: &str) -> Result<Self, VmError> {
|
||||
let (_, unsigned) = split_sign(text);
|
||||
let mut parts = unsigned.split(['e', 'E']);
|
||||
let mantissa = parts.next().unwrap_or_default();
|
||||
if let Some(exponent) = parts.next()
|
||||
&& (!is_digits(split_sign(exponent).1) || parts.next().is_some())
|
||||
{
|
||||
return Err(VmError::InvalidArgument("invalid decimal exponent"));
|
||||
}
|
||||
let mut decimal_point = false;
|
||||
let mut digits = 0_usize;
|
||||
let mut zero = true;
|
||||
for byte in mantissa.bytes() {
|
||||
match byte {
|
||||
b'.' if !decimal_point => decimal_point = true,
|
||||
b'0'..=b'9' => {
|
||||
digits += 1;
|
||||
zero &= byte == b'0';
|
||||
}
|
||||
_ => return Err(VmError::InvalidArgument("invalid decimal")),
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
return Err(VmError::InvalidArgument("decimal needs digits"));
|
||||
}
|
||||
Ok(Self {
|
||||
literal: text.into(),
|
||||
zero,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn literal(&self) -> &str {
|
||||
&self.literal
|
||||
}
|
||||
|
||||
pub fn is_zero(&self) -> bool {
|
||||
self.zero
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EndorDecimal {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.literal)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EndorRational {
|
||||
numerator: EndorInteger,
|
||||
denominator: EndorInteger,
|
||||
}
|
||||
|
||||
impl EndorRational {
|
||||
/// Normalizes denominator sign, without reducing or rounding the fraction.
|
||||
pub fn new(
|
||||
mut numerator: EndorInteger,
|
||||
mut denominator: EndorInteger,
|
||||
) -> Result<Self, VmError> {
|
||||
if denominator.is_zero() {
|
||||
return Err(VmError::InvalidArgument("zero rational denominator"));
|
||||
}
|
||||
if denominator.negative {
|
||||
denominator.negative = false;
|
||||
if !numerator.is_zero() {
|
||||
numerator.negative = !numerator.negative;
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
numerator,
|
||||
denominator,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn numerator(&self) -> &EndorInteger {
|
||||
&self.numerator
|
||||
}
|
||||
|
||||
pub fn denominator(&self) -> &EndorInteger {
|
||||
&self.denominator
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EndorRational {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}/{}", self.numerator, self.denominator)
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal storage forms within one Endor number API, not language classes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EndorReal {
|
||||
Integer(EndorInteger),
|
||||
Decimal(EndorDecimal),
|
||||
Rational(EndorRational),
|
||||
/// IEEE-754 bits preserve signed zero, infinities and NaN payloads.
|
||||
BinaryFloat(u64),
|
||||
}
|
||||
|
||||
impl EndorReal {
|
||||
pub fn is_zero(&self) -> bool {
|
||||
match self {
|
||||
Self::Integer(value) => value.is_zero(),
|
||||
Self::Decimal(value) => value.is_zero(),
|
||||
Self::Rational(value) => value.numerator.is_zero(),
|
||||
Self::BinaryFloat(bits) => f64::from_bits(*bits) == 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EndorReal {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Integer(value) => value.fmt(f),
|
||||
Self::Decimal(value) => value.fmt(f),
|
||||
Self::Rational(value) => value.fmt(f),
|
||||
Self::BinaryFloat(bits) => f64::from_bits(*bits).fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified, lossless number value. PartialEq/Eq compare representations, NOT
|
||||
/// mathematical values: decimal scale and IEEE NaN bits remain observable.
|
||||
/// Language-level comparison and hashing are not defined by these Rust traits.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum EndorNumber {
|
||||
Real(EndorReal),
|
||||
Complex {
|
||||
real: EndorReal,
|
||||
imaginary: EndorReal,
|
||||
},
|
||||
}
|
||||
|
||||
impl EndorNumber {
|
||||
pub fn integer(text: &str) -> Result<Self, VmError> {
|
||||
Ok(Self::Real(EndorReal::Integer(EndorInteger::parse(text)?)))
|
||||
}
|
||||
|
||||
pub fn decimal(text: &str) -> Result<Self, VmError> {
|
||||
Ok(Self::Real(EndorReal::Decimal(EndorDecimal::parse(text)?)))
|
||||
}
|
||||
|
||||
pub fn rational(numerator: &str, denominator: &str) -> Result<Self, VmError> {
|
||||
Ok(Self::Real(EndorReal::Rational(EndorRational::new(
|
||||
EndorInteger::parse(numerator)?,
|
||||
EndorInteger::parse(denominator)?,
|
||||
)?)))
|
||||
}
|
||||
|
||||
pub fn binary_float(value: f64) -> Self {
|
||||
Self::Real(EndorReal::BinaryFloat(value.to_bits()))
|
||||
}
|
||||
|
||||
pub fn complex(real: EndorReal, imaginary: EndorReal) -> Self {
|
||||
Self::Complex { real, imaginary }
|
||||
}
|
||||
|
||||
pub fn as_real(&self) -> Option<&EndorReal> {
|
||||
match self {
|
||||
Self::Real(value) => Some(value),
|
||||
Self::Complex { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_i64(&self) -> Option<i64> {
|
||||
match self {
|
||||
Self::Real(EndorReal::Integer(value)) => value.to_i64(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_zero(&self) -> bool {
|
||||
match self {
|
||||
Self::Real(value) => value.is_zero(),
|
||||
Self::Complex { real, imaginary } => real.is_zero() && imaginary.is_zero(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for EndorNumber {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::integer(&value.to_string()).expect("i64 always has valid decimal digits")
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for EndorNumber {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::binary_float(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EndorNumber {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Real(value) => value.fmt(f),
|
||||
Self::Complex { real, imaginary } => write!(f, "({real} + ({imaginary})i)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EndorNumberObject {
|
||||
value: EndorNumber,
|
||||
}
|
||||
|
||||
impl EndorNumberObject {
|
||||
pub fn new(value: EndorNumber) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
|
||||
pub fn value(&self) -> &EndorNumber {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectPayload for EndorNumberObject {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"number"
|
||||
}
|
||||
|
||||
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
|
||||
Ok(self.value.to_string())
|
||||
}
|
||||
|
||||
fn is_true(&self) -> Result<bool, VmError> {
|
||||
Ok(!self.value.is_zero())
|
||||
}
|
||||
|
||||
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
|
||||
Err(VmError::UnsupportedOperation("numeric hash"))
|
||||
}
|
||||
|
||||
fn compare(&self, other: &dyn ObjectPayload, _op: CompareOp) -> Result<Option<bool>, VmError> {
|
||||
if other.as_any().is::<Self>() {
|
||||
return Err(VmError::UnsupportedOperation("numeric comparison"));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn split_sign(text: &str) -> (bool, &str) {
|
||||
if let Some(rest) = text.strip_prefix('-') {
|
||||
(true, rest)
|
||||
} else {
|
||||
(false, text.strip_prefix('+').unwrap_or(text))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_digits(text: &str) -> bool {
|
||||
!text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
|
||||
}
|
||||
Reference in New Issue
Block a user