Add Endor builtin objects and lossless unified number representations
Verify databases and deploy Aster VM / verify-and-deploy (push) Waiting to run

This commit is contained in:
2026-10-18 19:54:17 +08:00
parent 534c2a3b2c
commit 891defb34c
14 changed files with 1461 additions and 34 deletions
+393
View File
@@ -0,0 +1,393 @@
use std::any::Any;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use crate::{CompareOp, ObjectPayload, ObjectRef, Value, VmError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndorStringObject {
text: String,
}
impl EndorStringObject {
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into() }
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn char_count(&self) -> usize {
self.text.chars().count()
}
pub fn char_at(&self, index: usize) -> Option<char> {
self.text.chars().nth(index)
}
}
impl ObjectPayload for EndorStringObject {
fn as_any(&self) -> &dyn Any {
self
}
fn kind_name(&self) -> &'static str {
"string"
}
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(format!("{:?}", self.text))
}
fn str(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(self.text.clone())
}
fn is_true(&self) -> Result<bool, VmError> {
Ok(!self.text.is_empty())
}
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
let mut hasher = DefaultHasher::new();
self.text.hash(&mut hasher);
Ok(hasher.finish())
}
fn compare(&self, other: &dyn ObjectPayload, op: CompareOp) -> Result<Option<bool>, VmError> {
let Some(other) = other.as_any().downcast_ref::<Self>() else {
return Ok(None);
};
Ok(Some(match op {
CompareOp::Eq => self.text == other.text,
CompareOp::Ne => self.text != other.text,
CompareOp::Lt => self.text < other.text,
CompareOp::Le => self.text <= other.text,
CompareOp::Gt => self.text > other.text,
CompareOp::Ge => self.text >= other.text,
}))
}
}
/// Insertion-ordered entries. Mutation is only exposed through Vm so every
/// key/value reference is validated, retained, traced, and released correctly.
/// Linear lookup is intentional for the initial representation layer.
#[derive(Debug, Clone, Default)]
pub struct EndorDictObject {
pub(crate) entries: Vec<(Value, Value)>,
}
impl EndorDictObject {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn entries(&self) -> &[(Value, Value)] {
&self.entries
}
}
impl ObjectPayload for EndorDictObject {
fn as_any(&self) -> &dyn Any {
self
}
fn kind_name(&self) -> &'static str {
"dict"
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for (key, value) in &self.entries {
trace_value(key, visit);
trace_value(value, visit);
}
}
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(format!("<dict len={}>", self.len()))
}
fn is_true(&self) -> Result<bool, VmError> {
Ok(!self.is_empty())
}
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
Err(VmError::UnsupportedOperation("dict hash"))
}
}
/// An empty cell differs from a cell containing Value::Nil.
#[derive(Debug, Clone, Default)]
pub struct EndorCellObject {
pub(crate) value: Option<Value>,
}
impl EndorCellObject {
pub fn new(value: Option<Value>) -> Self {
Self { value }
}
pub fn value(&self) -> Option<&Value> {
self.value.as_ref()
}
}
impl ObjectPayload for EndorCellObject {
fn as_any(&self) -> &dyn Any {
self
}
fn kind_name(&self) -> &'static str {
"cell"
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
if let Some(value) = &self.value {
trace_value(value, visit);
}
}
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(if self.value.is_some() {
"<cell occupied>"
} else {
"<cell empty>"
}
.into())
}
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
Err(VmError::UnsupportedOperation("cell hash"))
}
}
/// Code data only: bytecode is opaque until an instruction format/executor
/// is defined. Constants may own managed objects through the enclosing function.
#[derive(Debug, Clone)]
pub struct EndorCode {
bytecode: Vec<u8>,
constants: Vec<Value>,
parameters: Vec<String>,
free_variables: Vec<String>,
}
impl EndorCode {
pub fn new(
bytecode: Vec<u8>,
constants: Vec<Value>,
parameters: Vec<String>,
free_variables: Vec<String>,
) -> Result<Self, VmError> {
for names in [&parameters, &free_variables] {
let mut seen = std::collections::BTreeSet::new();
for name in names {
if name.is_empty() || !seen.insert(name) {
return Err(VmError::InvalidArgument(
"empty or duplicate code variable name",
));
}
}
}
Ok(Self {
bytecode,
constants,
parameters,
free_variables,
})
}
pub fn bytecode(&self) -> &[u8] {
&self.bytecode
}
pub fn constants(&self) -> &[Value] {
&self.constants
}
pub fn parameters(&self) -> &[String] {
&self.parameters
}
pub fn free_variables(&self) -> &[String] {
&self.free_variables
}
}
#[derive(Debug, Clone)]
pub struct EndorFunctionObject {
name: String,
code: EndorCode,
globals: ObjectRef,
defaults: Vec<Value>,
closure: Vec<ObjectRef>,
}
impl EndorFunctionObject {
pub fn new(
name: impl Into<String>,
code: EndorCode,
globals: ObjectRef,
defaults: Vec<Value>,
closure: Vec<ObjectRef>,
) -> Result<Self, VmError> {
if defaults.len() > code.parameters.len() || closure.len() != code.free_variables.len() {
return Err(VmError::InvalidArgument(
"function defaults or closure do not match code",
));
}
Ok(Self {
name: name.into(),
code,
globals,
defaults,
closure,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn code(&self) -> &EndorCode {
&self.code
}
pub fn globals(&self) -> ObjectRef {
self.globals
}
pub fn defaults(&self) -> &[Value] {
&self.defaults
}
pub fn closure(&self) -> &[ObjectRef] {
&self.closure
}
}
impl ObjectPayload for EndorFunctionObject {
fn as_any(&self) -> &dyn Any {
self
}
fn kind_name(&self) -> &'static str {
"function"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.globals);
for reference in &self.closure {
visit(*reference);
}
for value in self.defaults.iter().chain(&self.code.constants) {
trace_value(value, visit);
}
}
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(format!("<function {}>", self.name))
}
fn call(&self, _arguments: &[Value]) -> Result<Value, VmError> {
Err(VmError::UnsupportedOperation("language function execution"))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndorTracebackEntry {
pub function: String,
pub file: String,
pub line: usize,
}
/// Common exception instance data, not an exception class or inheritance tree.
#[derive(Debug, Clone)]
pub struct EndorBaseExceptionObject {
name: String,
args: Vec<Value>,
cause: Option<ObjectRef>,
context: Option<ObjectRef>,
suppress_context: bool,
notes: Vec<String>,
traceback: Vec<EndorTracebackEntry>,
}
impl EndorBaseExceptionObject {
pub fn new(name: impl Into<String>, args: Vec<Value>) -> Self {
Self {
name: name.into(),
args,
cause: None,
context: None,
suppress_context: false,
notes: Vec::new(),
traceback: Vec::new(),
}
}
pub fn with_cause(mut self, cause: ObjectRef) -> Self {
self.cause = Some(cause);
self.suppress_context = true;
self
}
pub fn with_context(mut self, context: ObjectRef) -> Self {
self.context = Some(context);
self
}
pub fn suppress_context(mut self, suppress: bool) -> Self {
self.suppress_context = suppress;
self
}
pub fn with_note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
pub fn with_traceback(mut self, entry: EndorTracebackEntry) -> Self {
self.traceback.push(entry);
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn args(&self) -> &[Value] {
&self.args
}
pub fn cause(&self) -> Option<ObjectRef> {
self.cause
}
pub fn context(&self) -> Option<ObjectRef> {
self.context
}
pub fn context_suppressed(&self) -> bool {
self.suppress_context
}
pub fn notes(&self) -> &[String] {
&self.notes
}
pub fn traceback(&self) -> &[EndorTracebackEntry] {
&self.traceback
}
}
impl ObjectPayload for EndorBaseExceptionObject {
fn as_any(&self) -> &dyn Any {
self
}
fn kind_name(&self) -> &'static str {
"exception"
}
fn allows_attributes(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for value in &self.args {
trace_value(value, visit);
}
for reference in [self.cause, self.context].into_iter().flatten() {
visit(reference);
}
}
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(format!(
"{}({})",
self.name,
self.args
.iter()
.map(|arg| format!("{arg:?}"))
.collect::<Vec<_>>()
.join(", ")
))
}
fn str(&self, _identity: ObjectRef) -> Result<String, VmError> {
Ok(match self.args.as_slice() {
[] => String::new(),
[Value::Text(text)] => text.clone(),
[Value::Number(number)] => number.to_string(),
args => format!("{args:?}"),
})
}
}
pub(crate) fn trace_value(value: &Value, visit: &mut dyn FnMut(ObjectRef)) {
if let Value::Object(reference) = value {
visit(*reference);
}
}
+21
View File
@@ -92,6 +92,27 @@ impl Heap {
.ok_or(VmError::InvalidHandle)
}
/// Transactional copy-on-update for built-in containers. The EndorObject
/// box and identity stay stable; only its payload and edge snapshot change.
/// All new edges are validated/retained before any old edge is released.
pub(crate) fn replace_payload(
&mut self,
reference: ObjectRef,
payload: impl ObjectPayload,
) -> Result<(), VmError> {
self.get(reference)?;
let mut edges = Vec::new();
payload.trace(&mut |target| edges.push(target));
let increments = self.prepare_increments(&edges)?;
self.apply_increments(increments);
let object = self.get_mut(reference)?;
let old_edges = std::mem::replace(&mut object.payload_edges, edges);
let old_payload = std::mem::replace(&mut object.payload, Box::new(payload));
self.release_edges(old_edges);
drop(old_payload);
Ok(())
}
fn get_mut(&mut self, reference: ObjectRef) -> Result<&mut EndorObject, VmError> {
self.get(reference)?;
Ok(self.slots[reference.index].object.as_deref_mut().unwrap())
+14 -3
View File
@@ -4,8 +4,8 @@
//! use aster_core::{Value, Vm};
//! let mut vm = Vm::new()?;
//! let object = vm.new_object()?; // One owned external reference.
//! vm.set_attr(object, "x", Value::Integer(42))?;
//! assert_eq!(vm.get_attr(object, "x")?, Value::Integer(42));
//! vm.set_attr(object, "x", Value::Number(42_i64.into()))?;
//! assert_eq!(vm.get_attr(object, "x")?, Value::Number(42_i64.into()));
//! vm.retain(object)?; // Own an additional reference.
//! vm.release(object)?;
//! assert_eq!(vm.ref_count(object)?, 1);
@@ -14,12 +14,23 @@
//! # Ok::<(), aster_core::VmError>(())
//! ```
mod builtins;
mod heap;
mod number;
mod object;
mod vm;
mod vm_builtins;
pub use builtins::{
EndorBaseExceptionObject, EndorCellObject, EndorCode, EndorDictObject, EndorFunctionObject,
EndorStringObject, EndorTracebackEntry,
};
pub use heap::ObjectRef;
pub use number::{
EndorDecimal, EndorInteger, EndorNumber, EndorNumberObject, EndorRational, EndorReal,
};
pub use object::{
CompareOp, EndorObject, NativeCall, NativeFunction, ObjectHeader, ObjectPayload, Record, Value,
CompareOp, EndorNativeCall, EndorNativeFunctionObject, EndorObject, NativeCall, NativeFunction,
ObjectHeader, ObjectPayload, Record, Value,
};
pub use vm::{Vm, VmError};
+317
View File
@@ -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())
}
+19 -9
View File
@@ -4,7 +4,7 @@ use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
use crate::{ObjectRef, VmError};
use crate::{EndorNumber, ObjectRef, VmError};
/// Immediate values stay outside the object heap. Object values are borrowed
/// handles: copying or cloning one does not retain an external strong reference.
@@ -12,8 +12,8 @@ use crate::{ObjectRef, VmError};
pub enum Value {
Nil,
Bool(bool),
Integer(i64),
Float(f64),
/// Rust equality preserves representation; it is not numeric equivalence.
Number(EndorNumber),
Text(String),
Object(ObjectRef),
}
@@ -45,7 +45,8 @@ impl CompareOp {
///
/// Implementations must report every payload-owned object reference in trace(),
/// including duplicates. Those edges must stay immutable after allocation;
/// mutable object references belong in VM-managed attributes instead.
/// mutable object references belong in VM-managed attributes or built-in
/// containers updated transactionally by the VM instead.
/// Rust Drop releases host resources when the payload is destroyed.
/// Equal payloads must provide compatible hashes, or reject hashing explicitly.
pub trait ObjectPayload: Any + fmt::Debug + Send + Sync {
@@ -112,24 +113,32 @@ impl ObjectPayload for Record {
}
}
pub type NativeCall = fn(&[Value]) -> Result<Value, VmError>;
pub type EndorNativeCall = fn(&[Value]) -> Result<Value, VmError>;
pub type NativeCall = EndorNativeCall;
#[derive(Debug)]
pub struct NativeFunction {
pub struct EndorNativeFunctionObject {
name: String,
function: NativeCall,
}
impl NativeFunction {
impl EndorNativeFunctionObject {
pub fn new(name: impl Into<String>, function: NativeCall) -> Self {
Self {
name: name.into(),
function,
}
}
pub fn name(&self) -> &str {
&self.name
}
}
impl ObjectPayload for NativeFunction {
/// Compatibility name for existing embedders.
pub type NativeFunction = EndorNativeFunctionObject;
impl ObjectPayload for EndorNativeFunctionObject {
fn as_any(&self) -> &dyn Any {
self
}
@@ -190,7 +199,8 @@ impl EndorObject {
}
/// Visits owned edges, not external roots. Payload edges are snapshotted at
/// allocation; attributes are maintained by the VM's reference accounting.
/// allocation and refreshed on VM-managed payload replacement; attributes
/// are maintained by the VM's reference accounting.
pub fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
for reference in &self.payload_edges {
visit(*reference);
+7 -2
View File
@@ -13,6 +13,8 @@ pub enum VmError {
AttributeNotFound(String),
UnsupportedOperation(&'static str),
InvalidArgument(&'static str),
ObjectKindMismatch(&'static str),
EmptyCell,
}
impl fmt::Display for VmError {
@@ -28,6 +30,8 @@ impl fmt::Display for VmError {
write!(f, "object does not support {operation}")
}
Self::InvalidArgument(message) => f.write_str(message),
Self::ObjectKindMismatch(expected) => write!(f, "expected {expected} object"),
Self::EmptyCell => f.write_str("cell is empty"),
}
}
}
@@ -38,7 +42,7 @@ impl std::error::Error for VmError {}
/// metaclasses or a Python type system. Dropping it releases all host resources.
#[derive(Debug)]
pub struct Vm {
heap: Heap,
pub(crate) heap: Heap,
}
impl Vm {
@@ -53,6 +57,7 @@ impl Vm {
/// Returns one external strong reference. Copies of the returned handle
/// are borrowed; use retain/release to manage additional owned references.
pub fn allocate(&mut self, payload: impl ObjectPayload) -> Result<ObjectRef, VmError> {
self.validate_builtin(&payload)?;
self.heap.allocate(Box::new(payload))
}
@@ -151,7 +156,7 @@ impl Vm {
Ok(result)
}
fn validate_value(&self, value: &Value) -> Result<(), VmError> {
pub(crate) fn validate_value(&self, value: &Value) -> Result<(), VmError> {
if let Value::Object(reference) = value {
self.heap.get(*reference)?;
}
+171
View File
@@ -0,0 +1,171 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use crate::{
CompareOp, EndorBaseExceptionObject, EndorCellObject, EndorDictObject, EndorFunctionObject,
EndorNumber, EndorNumberObject, EndorStringObject, ObjectPayload, ObjectRef, Value, Vm,
VmError,
};
impl Vm {
pub(crate) fn validate_builtin(&self, payload: &dyn ObjectPayload) -> Result<(), VmError> {
if let Some(function) = payload.as_any().downcast_ref::<EndorFunctionObject>() {
self.payload::<EndorDictObject>(function.globals(), "dict")?;
for cell in function.closure() {
self.payload::<EndorCellObject>(*cell, "cell")?;
}
}
if let Some(exception) = payload.as_any().downcast_ref::<EndorBaseExceptionObject>() {
for reference in [exception.cause(), exception.context()]
.into_iter()
.flatten()
{
self.payload::<EndorBaseExceptionObject>(reference, "exception")?;
}
}
Ok(())
}
pub fn payload<T: ObjectPayload>(
&self,
reference: ObjectRef,
expected: &'static str,
) -> Result<&T, VmError> {
self.object(reference)?
.payload()
.as_any()
.downcast_ref()
.ok_or(VmError::ObjectKindMismatch(expected))
}
pub fn new_string(&mut self, text: impl Into<String>) -> Result<ObjectRef, VmError> {
self.allocate(EndorStringObject::new(text))
}
pub fn new_number(&mut self, number: EndorNumber) -> Result<ObjectRef, VmError> {
self.allocate(EndorNumberObject::new(number))
}
pub fn new_dict(&mut self) -> Result<ObjectRef, VmError> {
self.allocate(EndorDictObject::new())
}
/// Returns borrowed keys and values in insertion order.
pub fn dict_items(&self, dictionary: ObjectRef) -> Result<&[(Value, Value)], VmError> {
Ok(self
.payload::<EndorDictObject>(dictionary, "dict")?
.entries())
}
pub fn dict_get(&self, dictionary: ObjectRef, key: &Value) -> Result<Option<Value>, VmError> {
let dict = self.payload::<EndorDictObject>(dictionary, "dict")?;
self.key_hash(key)?;
Ok(self
.dict_position(dict, key)?
.map(|index| dict.entries[index].1.clone()))
}
pub fn dict_set(
&mut self,
dictionary: ObjectRef,
key: Value,
value: Value,
) -> Result<(), VmError> {
let mut dict = self.payload::<EndorDictObject>(dictionary, "dict")?.clone();
self.key_hash(&key)?;
self.validate_value(&value)?;
if let Some(index) = self.dict_position(&dict, &key)? {
// Preserve the first key object and insertion position.
dict.entries[index].1 = value;
} else {
dict.entries.push((key, value));
}
self.heap.replace_payload(dictionary, dict)
}
pub fn dict_delete(&mut self, dictionary: ObjectRef, key: &Value) -> Result<bool, VmError> {
let mut dict = self.payload::<EndorDictObject>(dictionary, "dict")?.clone();
self.key_hash(key)?;
let Some(index) = self.dict_position(&dict, key)? else {
return Ok(false);
};
dict.entries.remove(index);
self.heap.replace_payload(dictionary, dict)?;
Ok(true)
}
pub fn dict_clear(&mut self, dictionary: ObjectRef) -> Result<(), VmError> {
self.payload::<EndorDictObject>(dictionary, "dict")?;
self.heap
.replace_payload(dictionary, EndorDictObject::new())
}
fn dict_position(&self, dict: &EndorDictObject, key: &Value) -> Result<Option<usize>, VmError> {
for (index, (existing, _)) in dict.entries.iter().enumerate() {
if self.key_equal(existing, key)? {
return Ok(Some(index));
}
}
Ok(None)
}
fn key_hash(&self, value: &Value) -> Result<u64, VmError> {
self.validate_value(value)?;
let mut hasher = DefaultHasher::new();
match value {
Value::Nil => "nil".hash(&mut hasher),
Value::Bool(value) => value.hash(&mut hasher),
Value::Text(value) => value.hash(&mut hasher),
Value::Number(_) => return Err(VmError::UnsupportedOperation("numeric hash")),
Value::Object(reference) => return self.hash(*reference),
}
Ok(hasher.finish())
}
fn key_equal(&self, left: &Value, right: &Value) -> Result<bool, VmError> {
let text = |value: &Value| -> Result<Option<String>, VmError> {
Ok(match value {
Value::Text(text) => Some(text.clone()),
Value::Object(reference) => self
.object(*reference)?
.payload()
.as_any()
.downcast_ref::<EndorStringObject>()
.map(|string| string.as_str().to_owned()),
_ => None,
})
};
if let (Some(left), Some(right)) = (text(left)?, text(right)?) {
return Ok(left == right);
}
match (left, right) {
(Value::Object(left), Value::Object(right)) => {
self.compare(*left, *right, CompareOp::Eq)
}
_ => Ok(left == right),
}
}
pub fn new_cell(&mut self, value: Option<Value>) -> Result<ObjectRef, VmError> {
self.allocate(EndorCellObject::new(value))
}
/// Reads a borrowed value; an empty cell is not Value::Nil.
pub fn cell_get(&self, cell: ObjectRef) -> Result<Value, VmError> {
self.payload::<EndorCellObject>(cell, "cell")?
.value()
.cloned()
.ok_or(VmError::EmptyCell)
}
pub fn cell_set(&mut self, cell: ObjectRef, value: Value) -> Result<(), VmError> {
self.payload::<EndorCellObject>(cell, "cell")?;
self.heap
.replace_payload(cell, EndorCellObject::new(Some(value)))
}
pub fn cell_clear(&mut self, cell: ObjectRef) -> Result<(), VmError> {
self.payload::<EndorCellObject>(cell, "cell")?;
self.heap.replace_payload(cell, EndorCellObject::default())
}
}
+343
View File
@@ -0,0 +1,343 @@
use aster_core::{
CompareOp, EndorBaseExceptionObject, EndorCode, EndorDictObject, EndorFunctionObject,
EndorInteger, EndorNativeFunctionObject, EndorNumber, EndorNumberObject, EndorReal,
EndorStringObject, EndorTracebackEntry, Value, Vm, VmError,
};
fn text(value: &str) -> Value {
Value::Text(value.into())
}
#[test]
fn numbers_preserve_large_digits_decimal_scale_exponents_and_fraction_parts() {
let huge = "123456789012345678901234567890123456789012345678901234567890";
assert_eq!(EndorNumber::integer(huge).unwrap().to_string(), huge);
assert_eq!(EndorNumber::integer("-000").unwrap().to_string(), "0");
assert_eq!(EndorNumber::integer("+0012").unwrap().as_i64(), Some(12));
assert_eq!(EndorNumber::integer(huge).unwrap().as_i64(), None);
for literal in [
"-0.0000",
"1.2300000000000000000001",
".5",
"1.",
"2e+999999999999999999999999999999",
] {
assert_eq!(EndorNumber::decimal(literal).unwrap().to_string(), literal);
}
assert_ne!(
EndorNumber::decimal("1.00").unwrap(),
EndorNumber::decimal("1.0").unwrap()
);
assert_eq!(
EndorNumber::rational("2", "-6").unwrap().to_string(),
"-2/6"
);
assert_eq!(EndorNumber::rational("0", "-6").unwrap().to_string(), "0/6");
assert!(EndorNumber::rational("1", "0").is_err());
for invalid in ["", "+", " 1", "1 ", "1_000", "12", "1.0"] {
assert!(EndorNumber::integer(invalid).is_err(), "{invalid}");
}
for invalid in ["", ".", "1.2.3", "1e", "1e+", "1e2e3", "nan", " 0.1", "--1"] {
assert!(EndorNumber::decimal(invalid).is_err(), "{invalid}");
}
}
#[test]
fn number_objects_preserve_ieee_bits_and_reject_undefined_numeric_operations() {
let mut vm = Vm::new().unwrap();
let bits = 0x7ff8_0000_0000_0042;
let nan = EndorNumber::binary_float(f64::from_bits(bits));
assert_eq!(nan.as_real(), Some(&EndorReal::BinaryFloat(bits)));
assert_ne!(
EndorNumber::binary_float(-0.0),
EndorNumber::binary_float(0.0)
);
assert!(!EndorNumber::binary_float(f64::INFINITY).is_zero());
let zero = vm
.new_number(EndorNumber::decimal("-0.000e99999999999").unwrap())
.unwrap();
assert!(!vm.is_true(zero).unwrap());
let complex = EndorNumber::complex(
EndorReal::Integer(EndorInteger::parse("3").unwrap()),
EndorNumber::rational("1", "3")
.unwrap()
.as_real()
.unwrap()
.clone(),
);
let object = vm.new_number(complex).unwrap();
assert_eq!(vm.str(object).unwrap(), "(3 + (1/3)i)");
assert_eq!(
vm.hash(object),
Err(VmError::UnsupportedOperation("numeric hash"))
);
assert_eq!(
vm.compare(object, zero, CompareOp::Eq),
Err(VmError::UnsupportedOperation("numeric comparison"))
);
assert!(
vm.payload::<EndorNumberObject>(object, "number")
.unwrap()
.value()
.as_real()
.is_none()
);
}
#[test]
fn strings_use_unicode_characters_and_content_equality() {
let mut vm = Vm::new().unwrap();
let a = vm.new_string("Endor中文🦀").unwrap();
let b = vm.new_string("Endor中文🦀").unwrap();
let empty = vm.new_string("").unwrap();
let string = vm.payload::<EndorStringObject>(a, "string").unwrap();
assert_eq!(string.char_count(), 8);
assert_eq!(string.char_at(7), Some('🦀'));
assert_eq!(string.char_at(8), None);
assert!(vm.compare(a, b, CompareOp::Eq).unwrap());
assert_eq!(vm.hash(a).unwrap(), vm.hash(b).unwrap());
assert_eq!(vm.str(a).unwrap(), "Endor中文🦀");
assert!(!vm.is_true(empty).unwrap());
}
#[test]
fn dictionaries_keep_order_and_first_key_and_own_keys_and_values() {
let mut vm = Vm::new().unwrap();
let dict = vm.new_dict().unwrap();
let key = vm.new_string("answer").unwrap();
let old = vm.new_object().unwrap();
vm.dict_set(dict, Value::Object(key), Value::Object(old))
.unwrap();
vm.release(key).unwrap();
vm.release(old).unwrap();
vm.dict_set(dict, text("second"), Value::Nil).unwrap();
vm.dict_set(dict, text("answer"), text("replacement"))
.unwrap();
assert_eq!(
vm.dict_get(dict, &text("answer")).unwrap(),
Some(text("replacement"))
);
assert_eq!(vm.dict_items(dict).unwrap()[0].0, Value::Object(key));
assert_eq!(vm.dict_items(dict).unwrap().len(), 2);
assert!(matches!(vm.object(old), Err(VmError::InvalidHandle)));
assert!(vm.dict_delete(dict, &text("answer")).unwrap());
assert!(matches!(vm.object(key), Err(VmError::InvalidHandle)));
assert!(!vm.dict_delete(dict, &text("missing")).unwrap());
vm.dict_clear(dict).unwrap();
assert!(!vm.is_true(dict).unwrap());
}
#[test]
fn failed_container_writes_leave_values_and_counts_unchanged() {
let mut vm = Vm::new().unwrap();
let mut other = Vm::new().unwrap();
let foreign = other.new_object().unwrap();
let dict = vm.new_dict().unwrap();
let child = vm.new_object().unwrap();
vm.dict_set(dict, text("x"), Value::Object(child)).unwrap();
assert_eq!(
vm.dict_set(dict, text("x"), Value::Object(foreign)),
Err(VmError::ForeignHandle)
);
assert_eq!(
vm.dict_get(dict, &text("x")).unwrap(),
Some(Value::Object(child))
);
assert_eq!(vm.ref_count(child).unwrap(), 2);
assert_eq!(
vm.dict_set(dict, Value::Number(1_i64.into()), Value::Nil),
Err(VmError::UnsupportedOperation("numeric hash"))
);
assert_eq!(
vm.dict_set(dict, Value::Object(dict), Value::Nil),
Err(VmError::UnsupportedOperation("dict hash"))
);
let cell = vm.new_cell(Some(Value::Object(child))).unwrap();
assert_eq!(
vm.cell_set(cell, Value::Object(foreign)),
Err(VmError::ForeignHandle)
);
assert_eq!(vm.cell_get(cell).unwrap(), Value::Object(child));
let dead = vm.new_object().unwrap();
vm.release(dead).unwrap();
assert_eq!(
vm.cell_set(cell, Value::Object(dead)),
Err(VmError::InvalidHandle)
);
assert_eq!(vm.ref_count(child).unwrap(), 3);
assert_eq!(
vm.dict_clear(child),
Err(VmError::ObjectKindMismatch("dict"))
);
}
#[test]
fn cells_share_rebinding_distinguish_empty_and_none_and_keep_stable_objects() {
let mut vm = Vm::new().unwrap();
let cell = vm.new_cell(None).unwrap();
assert_eq!(vm.cell_get(cell), Err(VmError::EmptyCell));
vm.cell_set(cell, Value::Nil).unwrap();
assert_eq!(vm.cell_get(cell).unwrap(), Value::Nil);
let child = vm.new_object().unwrap();
vm.cell_set(cell, Value::Object(child)).unwrap();
vm.release(child).unwrap();
vm.cell_set(cell, Value::Object(child)).unwrap();
assert_eq!(vm.ref_count(child).unwrap(), 1);
vm.cell_clear(cell).unwrap();
assert!(matches!(vm.object(child), Err(VmError::InvalidHandle)));
assert_eq!(vm.cell_get(cell), Err(VmError::EmptyCell));
}
#[test]
fn container_cycles_and_duplicate_edges_are_collected() {
let mut vm = Vm::new().unwrap();
let dict = vm.new_dict().unwrap();
let cell = vm.new_cell(Some(Value::Object(dict))).unwrap();
vm.dict_set(dict, text("a"), Value::Object(cell)).unwrap();
vm.dict_set(dict, text("b"), Value::Object(cell)).unwrap();
assert_eq!(vm.ref_count(cell).unwrap(), 3);
vm.release(dict).unwrap();
vm.release(cell).unwrap();
assert_eq!(vm.collect_cycles(), 2);
assert_eq!(vm.object_count(), 0);
}
#[test]
fn functions_retain_globals_constants_defaults_and_shared_closure_cells() {
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
let constant = vm.new_string("constant").unwrap();
let cell = vm.new_cell(Some(text("first"))).unwrap();
let code = EndorCode::new(
vec![0],
vec![Value::Object(constant)],
vec!["argument".into()],
vec!["captured".into()],
)
.unwrap();
let function = vm
.allocate(
EndorFunctionObject::new(
"read",
code.clone(),
globals,
vec![Value::Object(constant)],
vec![cell],
)
.unwrap(),
)
.unwrap();
let second = vm
.allocate(
EndorFunctionObject::new("read_again", code, globals, vec![], vec![cell]).unwrap(),
)
.unwrap();
assert_eq!(vm.ref_count(constant).unwrap(), 4);
vm.release(constant).unwrap();
vm.release(cell).unwrap();
vm.cell_set(cell, text("updated")).unwrap();
for reference in [function, second] {
let f = vm
.payload::<EndorFunctionObject>(reference, "function")
.unwrap();
assert_eq!(vm.cell_get(f.closure()[0]).unwrap(), text("updated"));
}
assert_eq!(
vm.call(function, &[]),
Err(VmError::UnsupportedOperation("language function execution"))
);
vm.dict_set(globals, text("read"), Value::Object(function))
.unwrap();
vm.release(globals).unwrap();
vm.release(function).unwrap();
vm.release(second).unwrap();
assert_eq!(vm.collect_cycles(), 4);
}
#[test]
fn malformed_function_environments_are_rejected_without_retaining_any_edges() {
let mut vm = Vm::new().unwrap();
let globals = vm.new_object().unwrap();
let code = EndorCode::new(vec![], vec![], vec![], vec![]).unwrap();
let function = EndorFunctionObject::new("bad", code, globals, vec![], vec![]).unwrap();
assert_eq!(
vm.allocate(function),
Err(VmError::ObjectKindMismatch("dict"))
);
assert_eq!(vm.ref_count(globals).unwrap(), 1);
assert!(EndorCode::new(vec![], vec![], vec!["x".into(), "x".into()], vec![]).is_err());
let code = EndorCode::new(vec![], vec![], vec![], vec!["x".into()]).unwrap();
assert!(EndorFunctionObject::new("bad", code, globals, vec![], vec![]).is_err());
}
#[test]
fn exceptions_preserve_arguments_chains_notes_and_traceback_without_type_classes() {
let mut vm = Vm::new().unwrap();
let argument = vm.new_string("detail").unwrap();
let cause = vm
.allocate(EndorBaseExceptionObject::new(
"ValueError",
vec![Value::Object(argument)],
))
.unwrap();
let exception = vm
.allocate(
EndorBaseExceptionObject::new("RuntimeError", vec![text("failed")])
.with_cause(cause)
.with_context(cause)
.with_note("while loading")
.with_traceback(EndorTracebackEntry {
function: "load".into(),
file: "demo.endor".into(),
line: 12,
}),
)
.unwrap();
assert_eq!(vm.ref_count(cause).unwrap(), 3);
vm.release(argument).unwrap();
vm.release(cause).unwrap();
let data = vm
.payload::<EndorBaseExceptionObject>(exception, "exception")
.unwrap();
assert!(data.context_suppressed());
assert_eq!(data.notes(), &["while loading"]);
assert_eq!(data.traceback()[0].line, 12);
assert_eq!(vm.str(exception).unwrap(), "failed");
vm.release(exception).unwrap();
assert_eq!(vm.object_count(), 0);
let wrong = vm.new_dict().unwrap();
assert_eq!(
vm.allocate(EndorBaseExceptionObject::new("Error", vec![]).with_cause(wrong)),
Err(VmError::ObjectKindMismatch("exception"))
);
}
fn echo(arguments: &[Value]) -> Result<Value, VmError> {
match arguments {
[value] => Ok(value.clone()),
_ => Err(VmError::InvalidArgument("expected one value")),
}
}
#[test]
fn native_functions_pass_lossless_numbers_and_borrowed_objects() {
let mut vm = Vm::new().unwrap();
let function = vm
.allocate(EndorNativeFunctionObject::new("echo", echo))
.unwrap();
let number = Value::Number(EndorNumber::decimal("12345678901234567890.000100").unwrap());
assert_eq!(
vm.call(function, std::slice::from_ref(&number)).unwrap(),
number
);
let dict = vm.new_dict().unwrap();
assert_eq!(
vm.call(function, &[Value::Object(dict)]).unwrap(),
Value::Object(dict)
);
assert_eq!(vm.ref_count(dict).unwrap(), 1);
assert_eq!(
vm.payload::<EndorDictObject>(dict, "dict").unwrap().len(),
0
);
}
+31 -12
View File
@@ -164,9 +164,13 @@ fn replacing_the_same_edge_does_not_destroy_the_target() {
vm.release(target).unwrap();
vm.set_attr(owner, "child", Value::Object(target)).unwrap();
assert_eq!(vm.ref_count(target).unwrap(), 1);
vm.set_attr(owner, "child", Value::Integer(7)).unwrap();
vm.set_attr(owner, "child", Value::Number(7_i64.into()))
.unwrap();
assert!(matches!(vm.object(target), Err(VmError::InvalidHandle)));
assert_eq!(vm.get_attr(owner, "child").unwrap(), Value::Integer(7));
assert_eq!(
vm.get_attr(owner, "child").unwrap(),
Value::Number(7_i64.into())
);
}
#[test]
@@ -194,7 +198,8 @@ fn failed_foreign_and_stale_writes_preserve_the_old_attribute() {
let foreign = other.new_object().unwrap();
let stale = vm.new_object().unwrap();
vm.release(stale).unwrap();
vm.set_attr(owner, "value", Value::Integer(1)).unwrap();
vm.set_attr(owner, "value", Value::Number(1_i64.into()))
.unwrap();
assert_eq!(
vm.set_attr(owner, "value", Value::Object(foreign)),
Err(VmError::ForeignHandle)
@@ -203,7 +208,10 @@ fn failed_foreign_and_stale_writes_preserve_the_old_attribute() {
vm.set_attr(owner, "value", Value::Object(stale)),
Err(VmError::InvalidHandle)
);
assert_eq!(vm.get_attr(owner, "value").unwrap(), Value::Integer(1));
assert_eq!(
vm.get_attr(owner, "value").unwrap(),
Value::Number(1_i64.into())
);
assert_eq!(vm.retain(foreign), Err(VmError::ForeignHandle));
assert_eq!(vm.release(foreign), Err(VmError::ForeignHandle));
assert_eq!(vm.is_same(owner, foreign), Err(VmError::ForeignHandle));
@@ -378,10 +386,15 @@ fn reflected_operations_and_explicitly_unsupported_hashing_are_respected() {
fn add(arguments: &[Value]) -> Result<Value, VmError> {
match arguments {
[Value::Integer(left), Value::Integer(right)] => left
.checked_add(*right)
.map(Value::Integer)
.ok_or(VmError::InvalidArgument("integer overflow")),
[Value::Number(left), Value::Number(right)] => {
let (left, right) = left
.as_i64()
.zip(right.as_i64())
.ok_or(VmError::InvalidArgument("expected two integers"))?;
left.checked_add(right)
.map(|value| Value::Number(value.into()))
.ok_or(VmError::InvalidArgument("integer overflow"))
}
_ => Err(VmError::InvalidArgument("expected two integers")),
}
}
@@ -392,16 +405,22 @@ fn native_calls_dispatch_validate_arguments_and_propagate_errors() {
let function = vm.allocate(NativeFunction::new("add", add)).unwrap();
assert_eq!(vm.repr(function).unwrap(), "<native-function add>");
assert_eq!(
vm.call(function, &[Value::Integer(2), Value::Integer(3)])
.unwrap(),
Value::Integer(5)
vm.call(
function,
&[Value::Number(2_i64.into()), Value::Number(3_i64.into())]
)
.unwrap(),
Value::Number(5_i64.into())
);
assert_eq!(
vm.call(function, &[]),
Err(VmError::InvalidArgument("expected two integers"))
);
assert_eq!(
vm.call(function, &[Value::Integer(i64::MAX), Value::Integer(1)]),
vm.call(
function,
&[Value::Number(i64::MAX.into()), Value::Number(1_i64.into())]
),
Err(VmError::InvalidArgument("integer overflow"))
);
assert_eq!(