Implement EndorObject runtime operations and managed lifetimes without language types
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 14m4s
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 14m4s
This commit is contained in:
+284
-183
@@ -1,188 +1,100 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::VmError;
|
||||
use crate::{EndorObject, ObjectHeader, ObjectPayload, Value, VmError};
|
||||
|
||||
static NEXT_HEAP_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Opaque process-local identity. Cannot be constructed or deserialized by callers.
|
||||
/// Handles do not keep the VM alive; every dereference goes through its owner VM.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
/// Checked, process-local reference. Copying it never retains an object.
|
||||
/// The generation prevents a released handle from aliasing a reused slot.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ObjectRef {
|
||||
heap_id: u64,
|
||||
index: usize,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ClassRef(pub(crate) ObjectRef);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct InstanceRef(pub(crate) ObjectRef);
|
||||
|
||||
impl From<ClassRef> for ObjectRef {
|
||||
fn from(value: ClassRef) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InstanceRef> for ObjectRef {
|
||||
fn from(value: InstanceRef) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Primitive values are immediate; only classes and instances live on the heap.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
Nil,
|
||||
Bool(bool),
|
||||
Integer(i64),
|
||||
Float(f64),
|
||||
Text(String),
|
||||
Object(ObjectRef),
|
||||
}
|
||||
|
||||
/// Immutable class metadata, stored in a language object's payload.
|
||||
/// This Rust structure is not a language object on its own.
|
||||
#[derive(Debug)]
|
||||
pub struct Class {
|
||||
pub(crate) name: String,
|
||||
pub(crate) parent: Option<ClassRef>,
|
||||
}
|
||||
|
||||
impl Class {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn parent(&self) -> Option<ClassRef> {
|
||||
self.parent
|
||||
impl fmt::Display for ObjectRef {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}:{}:{}", self.heap_id, self.index, self.generation)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Instance {
|
||||
pub(crate) fields: BTreeMap<String, Value>,
|
||||
struct Slot {
|
||||
generation: u64,
|
||||
object: Option<Box<EndorObject>>,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
pub fn field(&self, name: &str) -> Option<&Value> {
|
||||
self.fields.get(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Common header for every heap object, including class objects.
|
||||
/// The class handle is immutable and is always local to the owning VM.
|
||||
#[derive(Debug)]
|
||||
pub struct ObjectHeader {
|
||||
class: ClassRef,
|
||||
}
|
||||
|
||||
impl ObjectHeader {
|
||||
pub fn class(&self) -> ClassRef {
|
||||
self.class
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ObjectData {
|
||||
Class(Class),
|
||||
Instance(Instance),
|
||||
}
|
||||
|
||||
/// A language object consists of a common header and a kind-specific payload.
|
||||
/// Object links use checked handles rather than addresses into the arena.
|
||||
#[derive(Debug)]
|
||||
pub struct Object {
|
||||
header: ObjectHeader,
|
||||
pub(crate) data: ObjectData,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
pub(crate) fn new(class: ClassRef, data: ObjectData) -> Self {
|
||||
Self {
|
||||
header: ObjectHeader { class },
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn header(&self) -> &ObjectHeader {
|
||||
&self.header
|
||||
}
|
||||
|
||||
pub fn data(&self) -> &ObjectData {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocation-only arena. No deletion or slot reuse until a GC model is chosen.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Heap {
|
||||
id: u64,
|
||||
objects: Vec<Object>,
|
||||
slots: Vec<Slot>,
|
||||
free: Vec<usize>,
|
||||
live: usize,
|
||||
}
|
||||
|
||||
impl Heap {
|
||||
/// Builds both foundational classes before exposing the heap. The two
|
||||
/// private handles permit Type's self-reference without null placeholders.
|
||||
pub(crate) fn bootstrap() -> Result<(Self, ClassRef, ClassRef), VmError> {
|
||||
let mut heap = Self::new()?;
|
||||
let root = ClassRef(ObjectRef {
|
||||
heap_id: heap.id,
|
||||
index: 0,
|
||||
});
|
||||
let type_class = ClassRef(ObjectRef {
|
||||
heap_id: heap.id,
|
||||
index: 1,
|
||||
});
|
||||
heap.allocate(Object::new(
|
||||
type_class,
|
||||
ObjectData::Class(Class {
|
||||
name: "Object".into(),
|
||||
parent: None,
|
||||
}),
|
||||
));
|
||||
heap.allocate(Object::new(
|
||||
type_class,
|
||||
ObjectData::Class(Class {
|
||||
name: "Type".into(),
|
||||
parent: Some(root),
|
||||
}),
|
||||
));
|
||||
Ok((heap, root, type_class))
|
||||
}
|
||||
|
||||
pub(crate) fn new() -> Result<Self, VmError> {
|
||||
let id = NEXT_HEAP_ID
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
|
||||
.map_err(|_| VmError::IdentityExhausted)?;
|
||||
Ok(Self {
|
||||
id,
|
||||
objects: Vec::new(),
|
||||
slots: Vec::new(),
|
||||
free: Vec::new(),
|
||||
live: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn allocate(&mut self, object: Object) -> ObjectRef {
|
||||
pub(crate) fn allocate(
|
||||
&mut self,
|
||||
payload: Box<dyn ObjectPayload>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let mut edges = Vec::new();
|
||||
payload.trace(&mut |reference| edges.push(reference));
|
||||
let increments = self.prepare_increments(&edges)?;
|
||||
let index = self.free.pop().unwrap_or(self.slots.len());
|
||||
if index == self.slots.len() {
|
||||
self.slots.push(Slot {
|
||||
generation: 0,
|
||||
object: None,
|
||||
});
|
||||
}
|
||||
let reference = ObjectRef {
|
||||
heap_id: self.id,
|
||||
index: self.objects.len(),
|
||||
index,
|
||||
generation: self.slots[index].generation,
|
||||
};
|
||||
self.objects.push(object);
|
||||
reference
|
||||
let object = Box::new(EndorObject {
|
||||
header: ObjectHeader {
|
||||
identity: reference,
|
||||
strong_refs: 1,
|
||||
external_refs: 1,
|
||||
},
|
||||
payload,
|
||||
attributes: BTreeMap::new(),
|
||||
payload_edges: edges,
|
||||
});
|
||||
self.apply_increments(increments);
|
||||
self.slots[index].object = Some(object);
|
||||
self.live += 1;
|
||||
Ok(reference)
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, reference: ObjectRef) -> Result<&Object, VmError> {
|
||||
pub(crate) fn get(&self, reference: ObjectRef) -> Result<&EndorObject, VmError> {
|
||||
self.validate_owner(reference)?;
|
||||
self.objects
|
||||
self.slots
|
||||
.get(reference.index)
|
||||
.filter(|slot| slot.generation == reference.generation)
|
||||
.and_then(|slot| slot.object.as_deref())
|
||||
.ok_or(VmError::InvalidHandle)
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self, reference: ObjectRef) -> Result<&mut Object, VmError> {
|
||||
self.validate_owner(reference)?;
|
||||
self.objects
|
||||
.get_mut(reference.index)
|
||||
.ok_or(VmError::InvalidHandle)
|
||||
fn get_mut(&mut self, reference: ObjectRef) -> Result<&mut EndorObject, VmError> {
|
||||
self.get(reference)?;
|
||||
Ok(self.slots[reference.index].object.as_deref_mut().unwrap())
|
||||
}
|
||||
|
||||
fn validate_owner(&self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
@@ -192,68 +104,257 @@ impl Heap {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_increments(
|
||||
&self,
|
||||
references: &[ObjectRef],
|
||||
) -> Result<BTreeMap<ObjectRef, usize>, VmError> {
|
||||
let mut counts = BTreeMap::<ObjectRef, usize>::new();
|
||||
for reference in references {
|
||||
self.get(*reference)?;
|
||||
let count = counts.entry(*reference).or_default();
|
||||
*count = count.checked_add(1).ok_or(VmError::RefCountOverflow)?;
|
||||
}
|
||||
for (reference, count) in &counts {
|
||||
self.get(*reference)?
|
||||
.header
|
||||
.strong_refs
|
||||
.checked_add(*count)
|
||||
.ok_or(VmError::RefCountOverflow)?;
|
||||
}
|
||||
Ok(counts)
|
||||
}
|
||||
|
||||
fn apply_increments(&mut self, increments: BTreeMap<ObjectRef, usize>) {
|
||||
for (reference, count) in increments {
|
||||
self.get_mut(reference).unwrap().header.strong_refs += count;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn retain(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
let header = &mut self.get_mut(reference)?.header;
|
||||
let strong = header
|
||||
.strong_refs
|
||||
.checked_add(1)
|
||||
.ok_or(VmError::RefCountOverflow)?;
|
||||
let external = header
|
||||
.external_refs
|
||||
.checked_add(1)
|
||||
.ok_or(VmError::RefCountOverflow)?;
|
||||
header.strong_refs = strong;
|
||||
header.external_refs = external;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn release(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
let header = &mut self.get_mut(reference)?.header;
|
||||
if header.external_refs == 0 {
|
||||
return Err(VmError::NoOwnedReference);
|
||||
}
|
||||
header.external_refs -= 1;
|
||||
header.strong_refs -= 1;
|
||||
let pending = if header.strong_refs == 0 {
|
||||
vec![reference]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
self.drain_zero_counts(pending);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_attr(
|
||||
&mut self,
|
||||
reference: ObjectRef,
|
||||
name: String,
|
||||
value: Value,
|
||||
) -> Result<(), VmError> {
|
||||
self.check_attributes(reference)?;
|
||||
let edges: Vec<_> = match &value {
|
||||
Value::Object(target) => vec![*target],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let increments = self.prepare_increments(&edges)?;
|
||||
self.apply_increments(increments);
|
||||
let old = self.get_mut(reference)?.attributes.insert(name, value);
|
||||
if let Some(Value::Object(target)) = old {
|
||||
self.release_edges(vec![target]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn get_attr(&self, reference: ObjectRef, name: &str) -> Result<Value, VmError> {
|
||||
self.check_attributes(reference)?;
|
||||
self.get(reference)?
|
||||
.attributes
|
||||
.get(name)
|
||||
.cloned()
|
||||
.ok_or_else(|| VmError::AttributeNotFound(name.into()))
|
||||
}
|
||||
|
||||
pub(crate) fn del_attr(&mut self, reference: ObjectRef, name: &str) -> Result<(), VmError> {
|
||||
self.check_attributes(reference)?;
|
||||
let old = self
|
||||
.get_mut(reference)?
|
||||
.attributes
|
||||
.remove(name)
|
||||
.ok_or_else(|| VmError::AttributeNotFound(name.into()))?;
|
||||
if let Value::Object(target) = old {
|
||||
self.release_edges(vec![target]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_attributes(&self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
if !self.get(reference)?.payload.allows_attributes() {
|
||||
return Err(VmError::UnsupportedOperation("attributes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn release_edges(&mut self, edges: Vec<ObjectRef>) {
|
||||
let mut pending = Vec::new();
|
||||
for target in edges {
|
||||
let header = &mut self.get_mut(target).unwrap().header;
|
||||
header.strong_refs -= 1;
|
||||
if header.strong_refs == 0 {
|
||||
pending.push(target);
|
||||
}
|
||||
}
|
||||
self.drain_zero_counts(pending);
|
||||
}
|
||||
|
||||
/// Removes the object before running Drop. Reuse increments its generation;
|
||||
/// an exhausted generation permanently retires that slot.
|
||||
fn take(&mut self, reference: ObjectRef) -> Box<EndorObject> {
|
||||
let slot = &mut self.slots[reference.index];
|
||||
let object = slot.object.take().unwrap();
|
||||
if let Some(next) = slot.generation.checked_add(1) {
|
||||
slot.generation = next;
|
||||
self.free.push(reference.index);
|
||||
}
|
||||
self.live -= 1;
|
||||
object
|
||||
}
|
||||
|
||||
fn drain_zero_counts(&mut self, mut pending: Vec<ObjectRef>) {
|
||||
while let Some(reference) = pending.pop() {
|
||||
let object = self.take(reference);
|
||||
for target in object.edges() {
|
||||
let header = &mut self.get_mut(target).unwrap().header;
|
||||
header.strong_refs -= 1;
|
||||
if header.strong_refs == 0 {
|
||||
pending.push(target);
|
||||
}
|
||||
}
|
||||
drop(object);
|
||||
}
|
||||
}
|
||||
|
||||
/// Full, explicit cycle collection. External references are roots; every
|
||||
/// managed attribute and declared payload edge participates in tracing.
|
||||
pub(crate) fn collect_cycles(&mut self) -> usize {
|
||||
let mut marked = vec![false; self.slots.len()];
|
||||
let mut pending = Vec::new();
|
||||
for slot in &self.slots {
|
||||
if let Some(object) = &slot.object
|
||||
&& object.header.external_refs > 0
|
||||
{
|
||||
pending.push(object.header.identity);
|
||||
}
|
||||
}
|
||||
while let Some(reference) = pending.pop() {
|
||||
if marked[reference.index] {
|
||||
continue;
|
||||
}
|
||||
marked[reference.index] = true;
|
||||
pending.extend(self.get(reference).unwrap().edges());
|
||||
}
|
||||
let garbage: Vec<_> = self
|
||||
.slots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !marked[*index])
|
||||
.filter_map(|(_, slot)| slot.object.as_ref().map(|object| object.header.identity))
|
||||
.collect();
|
||||
let objects: Vec<_> = garbage
|
||||
.iter()
|
||||
.map(|reference| self.take(*reference))
|
||||
.collect();
|
||||
// All garbage slots are detached before touching edges or running Drop.
|
||||
for object in &objects {
|
||||
for target in object.edges() {
|
||||
if let Ok(survivor) = self.get_mut(target) {
|
||||
survivor.header.strong_refs -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let collected = objects.len();
|
||||
drop(objects);
|
||||
collected
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.objects.len()
|
||||
self.live
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Record;
|
||||
|
||||
#[test]
|
||||
fn invalid_index_is_an_error_for_both_access_paths() {
|
||||
fn invalid_slots_and_generations_are_rejected() {
|
||||
let mut heap = Heap::new().unwrap();
|
||||
let reference = heap.allocate(Box::new(Record)).unwrap();
|
||||
let invalid = ObjectRef {
|
||||
heap_id: heap.id,
|
||||
index: usize::MAX,
|
||||
..reference
|
||||
};
|
||||
let stale = ObjectRef {
|
||||
generation: 1,
|
||||
..reference
|
||||
};
|
||||
assert!(matches!(heap.get(invalid), Err(VmError::InvalidHandle)));
|
||||
assert!(matches!(heap.get_mut(invalid), Err(VmError::InvalidHandle)));
|
||||
assert!(matches!(heap.get_mut(stale), Err(VmError::InvalidHandle)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_handles_are_checked_at_runtime_too() {
|
||||
let mut vm = crate::Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
let instance = vm.create_instance(root).unwrap();
|
||||
assert!(matches!(
|
||||
vm.class(ClassRef(instance.0)),
|
||||
Err(VmError::ExpectedClass)
|
||||
));
|
||||
assert!(matches!(
|
||||
vm.instance(InstanceRef(root.0)),
|
||||
Err(VmError::ExpectedInstance)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_lookup_rejects_an_invalid_slot() {
|
||||
let vm = crate::Vm::new().unwrap();
|
||||
let invalid = ObjectRef {
|
||||
heap_id: vm.root_class().0.heap_id,
|
||||
index: usize::MAX,
|
||||
fn reused_slots_never_alias_and_exhausted_generations_retire() {
|
||||
let mut heap = Heap::new().unwrap();
|
||||
let first = heap.allocate(Box::new(Record)).unwrap();
|
||||
heap.release(first).unwrap();
|
||||
let second = heap.allocate(Box::new(Record)).unwrap();
|
||||
assert_eq!(first.index, second.index);
|
||||
assert_ne!(first.generation, second.generation);
|
||||
assert!(matches!(heap.get(first), Err(VmError::InvalidHandle)));
|
||||
heap.slots[second.index].generation = u64::MAX;
|
||||
let last = ObjectRef {
|
||||
generation: u64::MAX,
|
||||
..second
|
||||
};
|
||||
assert_eq!(vm.type_of(invalid), Err(VmError::InvalidHandle));
|
||||
heap.slots[last.index]
|
||||
.object
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.header
|
||||
.identity = last;
|
||||
heap.release(last).unwrap();
|
||||
let next = heap.allocate(Box::new(Record)).unwrap();
|
||||
assert_ne!(next.index, last.index);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_value_reference_cannot_replace_a_field() {
|
||||
let mut vm = crate::Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
let instance = vm.create_instance(root).unwrap();
|
||||
vm.set_field(instance, "field", Value::Integer(1)).unwrap();
|
||||
let invalid = ObjectRef {
|
||||
heap_id: root.0.heap_id,
|
||||
index: usize::MAX,
|
||||
};
|
||||
fn failed_reference_increments_leave_counts_and_attributes_unchanged() {
|
||||
let mut heap = Heap::new().unwrap();
|
||||
let owner = heap.allocate(Box::new(Record)).unwrap();
|
||||
let target = heap.allocate(Box::new(Record)).unwrap();
|
||||
heap.get_mut(target).unwrap().header.strong_refs = usize::MAX;
|
||||
assert_eq!(heap.retain(target), Err(VmError::RefCountOverflow));
|
||||
assert_eq!(heap.get(target).unwrap().header.external_refs, 1);
|
||||
assert_eq!(
|
||||
vm.set_field(instance, "field", Value::Object(invalid)),
|
||||
Err(VmError::InvalidHandle)
|
||||
);
|
||||
assert_eq!(
|
||||
vm.instance(instance).unwrap().field("field"),
|
||||
Some(&Value::Integer(1))
|
||||
heap.set_attr(owner, "edge".into(), Value::Object(target)),
|
||||
Err(VmError::RefCountOverflow)
|
||||
);
|
||||
assert!(heap.get(owner).unwrap().attributes.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
//! Embeddable object runtime. No database, network, parser or executor dependencies.
|
||||
//! Embeddable object runtime. No language type system, parser or executor.
|
||||
//!
|
||||
//! ```
|
||||
//! use aster_core::{Value, Vm};
|
||||
//! let mut vm = Vm::new()?;
|
||||
//! let point = vm.create_class("Point", vm.root_class())?;
|
||||
//! let instance = vm.create_instance(point)?;
|
||||
//! vm.set_field(instance, "x", Value::Integer(42))?;
|
||||
//! assert_eq!(vm.type_of(instance.into())?, point);
|
||||
//! assert_eq!(vm.type_of(point.into())?, vm.type_class());
|
||||
//! 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.retain(object)?; // Own an additional reference.
|
||||
//! vm.release(object)?;
|
||||
//! assert_eq!(vm.ref_count(object)?, 1);
|
||||
//! vm.release(object)?; // The object is destroyed.
|
||||
//! assert_eq!(vm.object_count(), 0);
|
||||
//! # Ok::<(), aster_core::VmError>(())
|
||||
//! ```
|
||||
|
||||
mod heap;
|
||||
mod object;
|
||||
mod vm;
|
||||
|
||||
pub use heap::{
|
||||
Class, ClassRef, Instance, InstanceRef, Object, ObjectData, ObjectHeader, ObjectRef, Value,
|
||||
pub use heap::ObjectRef;
|
||||
pub use object::{
|
||||
CompareOp, EndorObject, NativeCall, NativeFunction, ObjectHeader, ObjectPayload, Record, Value,
|
||||
};
|
||||
pub use vm::{Vm, VmError};
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
use std::any::Any;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::fmt;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use crate::{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.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
Nil,
|
||||
Bool(bool),
|
||||
Integer(i64),
|
||||
Float(f64),
|
||||
Text(String),
|
||||
Object(ObjectRef),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompareOp {
|
||||
Eq,
|
||||
Ne,
|
||||
Lt,
|
||||
Le,
|
||||
Gt,
|
||||
Ge,
|
||||
}
|
||||
|
||||
impl CompareOp {
|
||||
pub(crate) fn reflected(self) -> Self {
|
||||
match self {
|
||||
Self::Eq => Self::Eq,
|
||||
Self::Ne => Self::Ne,
|
||||
Self::Lt => Self::Gt,
|
||||
Self::Le => Self::Ge,
|
||||
Self::Gt => Self::Lt,
|
||||
Self::Ge => Self::Le,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rust-side operation interface, not a language type or metaclass.
|
||||
///
|
||||
/// 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.
|
||||
/// 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 {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
|
||||
/// A diagnostic label only, with no language type or inheritance semantics.
|
||||
fn kind_name(&self) -> &'static str;
|
||||
|
||||
fn trace(&self, _visit: &mut dyn FnMut(ObjectRef)) {}
|
||||
|
||||
fn allows_attributes(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn repr(&self, identity: ObjectRef) -> Result<String, VmError> {
|
||||
Ok(format!("<{} {identity}>", self.kind_name()))
|
||||
}
|
||||
|
||||
fn str(&self, identity: ObjectRef) -> Result<String, VmError> {
|
||||
self.repr(identity)
|
||||
}
|
||||
|
||||
fn is_true(&self) -> Result<bool, VmError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn hash(&self, identity: ObjectRef) -> Result<u64, VmError> {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
identity.hash(&mut hasher);
|
||||
Ok(hasher.finish())
|
||||
}
|
||||
|
||||
/// None means "not implemented"; the VM tries the reflected operation,
|
||||
/// then falls back to identity for Eq/Ne or rejects ordering.
|
||||
fn compare(
|
||||
&self,
|
||||
_other: &dyn ObjectPayload,
|
||||
_operation: CompareOp,
|
||||
) -> Result<Option<bool>, VmError> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Object arguments and object results are borrowed handles. Native calls
|
||||
/// compute values without mutating the VM; this is not a language executor.
|
||||
fn call(&self, _arguments: &[Value]) -> Result<Value, VmError> {
|
||||
Err(VmError::UnsupportedOperation("call"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Record;
|
||||
|
||||
impl ObjectPayload for Record {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"record"
|
||||
}
|
||||
|
||||
fn allows_attributes(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub type NativeCall = fn(&[Value]) -> Result<Value, VmError>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NativeFunction {
|
||||
name: String,
|
||||
function: NativeCall,
|
||||
}
|
||||
|
||||
impl NativeFunction {
|
||||
pub fn new(name: impl Into<String>, function: NativeCall) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
function,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectPayload for NativeFunction {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"native-function"
|
||||
}
|
||||
|
||||
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
|
||||
Ok(format!("<native-function {}>", self.name))
|
||||
}
|
||||
|
||||
fn call(&self, arguments: &[Value]) -> Result<Value, VmError> {
|
||||
(self.function)(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Common runtime state. There is deliberately no language type pointer.
|
||||
#[derive(Debug)]
|
||||
pub struct ObjectHeader {
|
||||
pub(crate) identity: ObjectRef,
|
||||
pub(crate) strong_refs: usize,
|
||||
pub(crate) external_refs: usize,
|
||||
}
|
||||
|
||||
impl ObjectHeader {
|
||||
pub fn identity(&self) -> ObjectRef {
|
||||
self.identity
|
||||
}
|
||||
|
||||
pub fn ref_count(&self) -> usize {
|
||||
self.strong_refs
|
||||
}
|
||||
|
||||
pub fn external_ref_count(&self) -> usize {
|
||||
self.external_refs
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime object foundation, analogous in role to CPython's common object
|
||||
/// structure, without its type system or binary layout. The heap boxes this
|
||||
/// structure so its address remains stable throughout its lifetime.
|
||||
#[derive(Debug)]
|
||||
pub struct EndorObject {
|
||||
pub(crate) header: ObjectHeader,
|
||||
pub(crate) payload: Box<dyn ObjectPayload>,
|
||||
pub(crate) attributes: BTreeMap<String, Value>,
|
||||
pub(crate) payload_edges: Vec<ObjectRef>,
|
||||
}
|
||||
|
||||
impl EndorObject {
|
||||
pub fn header(&self) -> &ObjectHeader {
|
||||
&self.header
|
||||
}
|
||||
|
||||
pub fn payload(&self) -> &dyn ObjectPayload {
|
||||
self.payload.as_ref()
|
||||
}
|
||||
|
||||
/// Visits owned edges, not external roots. Payload edges are snapshotted at
|
||||
/// allocation; 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);
|
||||
}
|
||||
for value in self.attributes.values() {
|
||||
if let Value::Object(reference) = value {
|
||||
visit(*reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn edges(&self) -> Vec<ObjectRef> {
|
||||
let mut edges = Vec::new();
|
||||
self.trace(&mut |reference| edges.push(reference));
|
||||
edges
|
||||
}
|
||||
}
|
||||
+114
-116
@@ -1,168 +1,166 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use crate::heap::Heap;
|
||||
use crate::{Class, ClassRef, Instance, InstanceRef, Object, ObjectData, ObjectRef, Value};
|
||||
use crate::{CompareOp, EndorObject, ObjectPayload, ObjectRef, Record, Value};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VmError {
|
||||
ForeignHandle,
|
||||
InvalidHandle,
|
||||
ExpectedClass,
|
||||
ExpectedInstance,
|
||||
EmptyClassName,
|
||||
ReservedClassName,
|
||||
UnsupportedMetaclass,
|
||||
IdentityExhausted,
|
||||
RefCountOverflow,
|
||||
NoOwnedReference,
|
||||
AttributeNotFound(String),
|
||||
UnsupportedOperation(&'static str),
|
||||
InvalidArgument(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for VmError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::ForeignHandle => "handle belongs to another VM",
|
||||
Self::InvalidHandle => "handle does not identify a live object",
|
||||
Self::ExpectedClass => "object is not a class",
|
||||
Self::ExpectedInstance => "object is not an instance",
|
||||
Self::EmptyClassName => "class name cannot be blank",
|
||||
Self::ReservedClassName => "Object and Type are reserved for the bootstrap classes",
|
||||
Self::UnsupportedMetaclass => "Type only supports class creation through create_class",
|
||||
Self::IdentityExhausted => "process-local VM identities exhausted",
|
||||
})
|
||||
match self {
|
||||
Self::ForeignHandle => f.write_str("handle belongs to another VM"),
|
||||
Self::InvalidHandle => f.write_str("handle does not identify a live object"),
|
||||
Self::IdentityExhausted => f.write_str("process-local VM identities exhausted"),
|
||||
Self::RefCountOverflow => f.write_str("object reference count exhausted"),
|
||||
Self::NoOwnedReference => f.write_str("no external strong reference to release"),
|
||||
Self::AttributeNotFound(name) => write!(f, "attribute not found: {name}"),
|
||||
Self::UnsupportedOperation(operation) => {
|
||||
write!(f, "object does not support {operation}")
|
||||
}
|
||||
Self::InvalidArgument(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VmError {}
|
||||
|
||||
/// Owns its heap, the root Object class and its Type metaclass.
|
||||
/// Not Clone: handles have one owner.
|
||||
/// Runtime owner. Construction creates an empty heap, without language classes,
|
||||
/// metaclasses or a Python type system. Dropping it releases all host resources.
|
||||
#[derive(Debug)]
|
||||
pub struct Vm {
|
||||
heap: Heap,
|
||||
root: ClassRef,
|
||||
type_class: ClassRef,
|
||||
}
|
||||
|
||||
impl Vm {
|
||||
/// Bootstraps Object and Type before returning. Does not perform host I/O.
|
||||
pub fn new() -> Result<Self, VmError> {
|
||||
let (heap, root, type_class) = Heap::bootstrap()?;
|
||||
Ok(Self {
|
||||
heap,
|
||||
root,
|
||||
type_class,
|
||||
})
|
||||
}
|
||||
|
||||
/// Idempotent: construction has already performed bootstrap exactly once.
|
||||
pub fn bootstrap(&mut self) -> ClassRef {
|
||||
self.root
|
||||
}
|
||||
|
||||
pub fn root_class(&self) -> ClassRef {
|
||||
self.root
|
||||
}
|
||||
|
||||
pub fn type_class(&self) -> ClassRef {
|
||||
self.type_class
|
||||
Ok(Self { heap: Heap::new()? })
|
||||
}
|
||||
|
||||
pub fn object_count(&self) -> usize {
|
||||
self.heap.len()
|
||||
}
|
||||
|
||||
/// All user classes have an existing parent. Class names are labels rather
|
||||
/// than a global registry; duplicate non-reserved names are permitted.
|
||||
pub fn create_class(
|
||||
&mut self,
|
||||
name: impl Into<String>,
|
||||
parent: ClassRef,
|
||||
) -> Result<ClassRef, VmError> {
|
||||
self.class(parent)?;
|
||||
if parent == self.type_class {
|
||||
return Err(VmError::UnsupportedMetaclass);
|
||||
}
|
||||
let name = name.into();
|
||||
if name.trim().is_empty() {
|
||||
return Err(VmError::EmptyClassName);
|
||||
}
|
||||
if name == "Object" || name == "Type" {
|
||||
return Err(VmError::ReservedClassName);
|
||||
}
|
||||
Ok(ClassRef(self.heap.allocate(Object::new(
|
||||
self.type_class,
|
||||
ObjectData::Class(Class {
|
||||
name,
|
||||
parent: Some(parent),
|
||||
}),
|
||||
))))
|
||||
/// 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.heap.allocate(Box::new(payload))
|
||||
}
|
||||
|
||||
pub fn create_instance(&mut self, class: ClassRef) -> Result<InstanceRef, VmError> {
|
||||
self.class(class)?;
|
||||
if class == self.type_class {
|
||||
return Err(VmError::UnsupportedMetaclass);
|
||||
}
|
||||
Ok(InstanceRef(self.heap.allocate(Object::new(
|
||||
class,
|
||||
ObjectData::Instance(Instance {
|
||||
fields: BTreeMap::new(),
|
||||
}),
|
||||
))))
|
||||
pub fn new_object(&mut self) -> Result<ObjectRef, VmError> {
|
||||
self.allocate(Record)
|
||||
}
|
||||
|
||||
pub fn object(&self, reference: ObjectRef) -> Result<&Object, VmError> {
|
||||
pub fn object(&self, reference: ObjectRef) -> Result<&EndorObject, VmError> {
|
||||
self.heap.get(reference)
|
||||
}
|
||||
|
||||
/// Reads the same common header for class objects and ordinary instances.
|
||||
pub fn type_of(&self, reference: ObjectRef) -> Result<ClassRef, VmError> {
|
||||
Ok(self.heap.get(reference)?.header().class())
|
||||
pub fn retain(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
self.heap.retain(reference)
|
||||
}
|
||||
|
||||
pub fn class(&self, reference: ClassRef) -> Result<&Class, VmError> {
|
||||
match self.heap.get(reference.0)?.data() {
|
||||
ObjectData::Class(class) => Ok(class),
|
||||
ObjectData::Instance(_) => Err(VmError::ExpectedClass),
|
||||
pub fn release(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
self.heap.release(reference)
|
||||
}
|
||||
|
||||
pub fn ref_count(&self, reference: ObjectRef) -> Result<usize, VmError> {
|
||||
Ok(self.heap.get(reference)?.header().ref_count())
|
||||
}
|
||||
|
||||
pub fn is_same(&self, left: ObjectRef, right: ObjectRef) -> Result<bool, VmError> {
|
||||
self.heap.get(left)?;
|
||||
self.heap.get(right)?;
|
||||
Ok(left == right)
|
||||
}
|
||||
|
||||
pub fn repr(&self, reference: ObjectRef) -> Result<String, VmError> {
|
||||
self.heap.get(reference)?.payload().repr(reference)
|
||||
}
|
||||
|
||||
pub fn str(&self, reference: ObjectRef) -> Result<String, VmError> {
|
||||
self.heap.get(reference)?.payload().str(reference)
|
||||
}
|
||||
|
||||
pub fn is_true(&self, reference: ObjectRef) -> Result<bool, VmError> {
|
||||
self.heap.get(reference)?.payload().is_true()
|
||||
}
|
||||
|
||||
pub fn hash(&self, reference: ObjectRef) -> Result<u64, VmError> {
|
||||
self.heap.get(reference)?.payload().hash(reference)
|
||||
}
|
||||
|
||||
pub fn compare(
|
||||
&self,
|
||||
left: ObjectRef,
|
||||
right: ObjectRef,
|
||||
operation: CompareOp,
|
||||
) -> Result<bool, VmError> {
|
||||
let left_payload = self.heap.get(left)?.payload();
|
||||
let right_payload = self.heap.get(right)?.payload();
|
||||
if let Some(result) = left_payload.compare(right_payload, operation)? {
|
||||
return Ok(result);
|
||||
}
|
||||
if let Some(result) = right_payload.compare(left_payload, operation.reflected())? {
|
||||
return Ok(result);
|
||||
}
|
||||
match operation {
|
||||
CompareOp::Eq => Ok(left == right),
|
||||
CompareOp::Ne => Ok(left != right),
|
||||
_ => Err(VmError::UnsupportedOperation("ordering")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instance(&self, reference: InstanceRef) -> Result<&Instance, VmError> {
|
||||
match self.heap.get(reference.0)?.data() {
|
||||
ObjectData::Instance(instance) => Ok(instance),
|
||||
ObjectData::Class(_) => Err(VmError::ExpectedInstance),
|
||||
}
|
||||
/// Reads a borrowed value. An Object result needs retain() if the host
|
||||
/// wants it to survive removal of the attribute that currently owns it.
|
||||
pub fn get_attr(&self, reference: ObjectRef, name: &str) -> Result<Value, VmError> {
|
||||
self.heap.get_attr(reference, name)
|
||||
}
|
||||
|
||||
/// Converts a generic reference only after validating ownership and kind.
|
||||
pub fn as_class(&self, reference: ObjectRef) -> Result<ClassRef, VmError> {
|
||||
let typed = ClassRef(reference);
|
||||
self.class(typed)?;
|
||||
Ok(typed)
|
||||
}
|
||||
|
||||
pub fn as_instance(&self, reference: ObjectRef) -> Result<InstanceRef, VmError> {
|
||||
let typed = InstanceRef(reference);
|
||||
self.instance(typed)?;
|
||||
Ok(typed)
|
||||
}
|
||||
|
||||
/// Checks both destination and referenced value before changing any field.
|
||||
pub fn set_field(
|
||||
/// Object-valued attributes own internal strong references independently
|
||||
/// of the caller's external references. Failure leaves the field unchanged.
|
||||
pub fn set_attr(
|
||||
&mut self,
|
||||
instance: InstanceRef,
|
||||
reference: ObjectRef,
|
||||
name: impl Into<String>,
|
||||
value: Value,
|
||||
) -> Result<(), VmError> {
|
||||
self.instance(instance)?;
|
||||
if let Value::Object(reference) = &value {
|
||||
self.heap.set_attr(reference, name.into(), value)
|
||||
}
|
||||
|
||||
pub fn del_attr(&mut self, reference: ObjectRef, name: &str) -> Result<(), VmError> {
|
||||
self.heap.del_attr(reference, name)
|
||||
}
|
||||
|
||||
/// Results are borrowed values; native operations cannot mutate this VM.
|
||||
pub fn call(&self, reference: ObjectRef, arguments: &[Value]) -> Result<Value, VmError> {
|
||||
let payload = self.heap.get(reference)?.payload();
|
||||
for argument in arguments {
|
||||
self.validate_value(argument)?;
|
||||
}
|
||||
let result = payload.call(arguments)?;
|
||||
self.validate_value(&result)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn validate_value(&self, value: &Value) -> Result<(), VmError> {
|
||||
if let Value::Object(reference) = value {
|
||||
self.heap.get(*reference)?;
|
||||
}
|
||||
match &mut self.heap.get_mut(instance.0)?.data {
|
||||
ObjectData::Instance(instance) => {
|
||||
instance.fields.insert(name.into(), value);
|
||||
Ok(())
|
||||
}
|
||||
ObjectData::Class(_) => Err(VmError::ExpectedInstance),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Explicit full collection of unreachable cycles, using external strong
|
||||
/// references as roots. A tracing execution stack can be added later.
|
||||
pub fn collect_cycles(&mut self) -> usize {
|
||||
self.heap.collect_cycles()
|
||||
}
|
||||
}
|
||||
|
||||
+434
-145
@@ -1,172 +1,461 @@
|
||||
use aster_core::{ObjectData, Value, Vm, VmError};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn bootstrap_is_unique_and_root_has_no_parent() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
assert_eq!(vm.bootstrap(), root);
|
||||
assert_eq!(vm.bootstrap(), root);
|
||||
assert_eq!(vm.object_count(), 2);
|
||||
assert_eq!(vm.class(root).unwrap().name(), "Object");
|
||||
assert_eq!(vm.class(root).unwrap().parent(), None);
|
||||
use aster_core::{CompareOp, NativeFunction, ObjectPayload, ObjectRef, Record, Value, Vm, VmError};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Resource {
|
||||
drops: Arc<AtomicUsize>,
|
||||
edges: Vec<ObjectRef>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_types_have_headers_and_distinct_inheritance_links() {
|
||||
let vm = Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
let type_class = vm.type_class();
|
||||
assert_ne!(root, type_class);
|
||||
assert_eq!(vm.class(type_class).unwrap().name(), "Type");
|
||||
assert_eq!(vm.class(type_class).unwrap().parent(), Some(root));
|
||||
assert_eq!(vm.type_of(root.into()).unwrap(), type_class);
|
||||
assert_eq!(vm.type_of(type_class.into()).unwrap(), type_class);
|
||||
for class in [root, type_class] {
|
||||
let object = vm.object(class.into()).unwrap();
|
||||
assert_eq!(object.header().class(), type_class);
|
||||
assert!(matches!(object.data(), ObjectData::Class(_)));
|
||||
assert_eq!(vm.as_class(class.into()).unwrap(), class);
|
||||
assert_eq!(vm.as_instance(class.into()), Err(VmError::ExpectedInstance));
|
||||
impl Drop for Resource {
|
||||
fn drop(&mut self) {
|
||||
self.drops.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factories_preserve_class_links_and_distinct_identity() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
let class = vm.create_class("Point", root).unwrap();
|
||||
let child = vm.create_class("ColoredPoint", class).unwrap();
|
||||
let first = vm.create_instance(class).unwrap();
|
||||
let second = vm.create_instance(class).unwrap();
|
||||
let plain = vm.create_instance(root).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(vm.class(child).unwrap().parent(), Some(class));
|
||||
assert_eq!(vm.type_of(class.into()).unwrap(), vm.type_class());
|
||||
assert_eq!(vm.type_of(child.into()).unwrap(), vm.type_class());
|
||||
assert_eq!(vm.type_of(first.into()).unwrap(), class);
|
||||
assert_eq!(vm.type_of(plain.into()).unwrap(), root);
|
||||
let object = vm.object(first.into()).unwrap();
|
||||
assert_eq!(object.header().class(), class);
|
||||
assert!(matches!(object.data(), ObjectData::Instance(_)));
|
||||
vm.set_field(first, "x", Value::Integer(1)).unwrap();
|
||||
vm.set_field(first, "next", Value::Object(second.into()))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vm.instance(first).unwrap().field("x"),
|
||||
Some(&Value::Integer(1))
|
||||
);
|
||||
assert_eq!(vm.instance(second).unwrap().field("x"), None);
|
||||
assert_eq!(vm.as_class(class.into()).unwrap(), class);
|
||||
assert_eq!(vm.as_instance(first.into()).unwrap(), first);
|
||||
assert_eq!(vm.as_instance(class.into()), Err(VmError::ExpectedInstance));
|
||||
assert_eq!(vm.as_class(first.into()), Err(VmError::ExpectedClass));
|
||||
impl ObjectPayload for Resource {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"resource"
|
||||
}
|
||||
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
for reference in &self.edges {
|
||||
visit(*reference);
|
||||
}
|
||||
}
|
||||
|
||||
fn allows_attributes(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Number(i64);
|
||||
|
||||
impl ObjectPayload for Number {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"number"
|
||||
}
|
||||
|
||||
fn repr(&self, _identity: ObjectRef) -> Result<String, VmError> {
|
||||
Ok(self.0.to_string())
|
||||
}
|
||||
|
||||
fn is_true(&self) -> Result<bool, VmError> {
|
||||
Ok(self.0 != 0)
|
||||
}
|
||||
|
||||
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
|
||||
Ok(self.0 as u64)
|
||||
}
|
||||
|
||||
fn compare(
|
||||
&self,
|
||||
other: &dyn ObjectPayload,
|
||||
operation: CompareOp,
|
||||
) -> Result<Option<bool>, VmError> {
|
||||
let Some(other) = other.as_any().downcast_ref::<Self>() else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(match operation {
|
||||
CompareOp::Eq => self.0 == other.0,
|
||||
CompareOp::Ne => self.0 != other.0,
|
||||
CompareOp::Lt => self.0 < other.0,
|
||||
CompareOp::Le => self.0 <= other.0,
|
||||
CompareOp::Gt => self.0 > other.0,
|
||||
CompareOp::Ge => self.0 >= other.0,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn resource(vm: &mut Vm, drops: &Arc<AtomicUsize>, edges: Vec<ObjectRef>) -> ObjectRef {
|
||||
vm.allocate(Resource {
|
||||
drops: drops.clone(),
|
||||
edges,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_handles_are_rejected_without_mutation() {
|
||||
fn starts_empty_without_language_classes_or_a_type_system() {
|
||||
let vm = Vm::new().unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_provide_identity_representation_hash_and_truth() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let first = vm.new_object().unwrap();
|
||||
let second = vm.new_object().unwrap();
|
||||
assert_eq!(vm.object(first).unwrap().header().identity(), first);
|
||||
assert!(vm.is_same(first, first).unwrap());
|
||||
assert!(!vm.is_same(first, second).unwrap());
|
||||
assert!(vm.repr(first).unwrap().contains(&first.to_string()));
|
||||
assert_eq!(vm.repr(first).unwrap(), vm.str(first).unwrap());
|
||||
assert_eq!(vm.hash(first).unwrap(), vm.hash(first).unwrap());
|
||||
assert!(vm.is_true(first).unwrap());
|
||||
assert!(vm.compare(first, first, CompareOp::Eq).unwrap());
|
||||
assert!(vm.compare(first, second, CompareOp::Ne).unwrap());
|
||||
assert_eq!(
|
||||
vm.compare(first, second, CompareOp::Lt),
|
||||
Err(VmError::UnsupportedOperation("ordering"))
|
||||
);
|
||||
assert_eq!(
|
||||
vm.call(first, &[]),
|
||||
Err(VmError::UnsupportedOperation("call"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_references_control_lifetime_and_copies_are_borrowed() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let owned = resource(&mut vm, &drops, vec![]);
|
||||
let borrowed = owned;
|
||||
assert_eq!(vm.ref_count(borrowed).unwrap(), 1);
|
||||
vm.retain(owned).unwrap();
|
||||
assert_eq!(vm.ref_count(owned).unwrap(), 2);
|
||||
vm.release(owned).unwrap();
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 0);
|
||||
vm.release(owned).unwrap();
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
assert!(matches!(vm.object(borrowed), Err(VmError::InvalidHandle)));
|
||||
assert_eq!(vm.release(borrowed), Err(VmError::InvalidHandle));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_keep_objects_alive_and_delete_releases_them() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let owner = vm.new_object().unwrap();
|
||||
let child = resource(&mut vm, &drops, vec![]);
|
||||
vm.set_attr(owner, "child", Value::Object(child)).unwrap();
|
||||
assert_eq!(vm.ref_count(child).unwrap(), 2);
|
||||
vm.release(child).unwrap();
|
||||
assert_eq!(vm.ref_count(child).unwrap(), 1);
|
||||
assert_eq!(vm.release(child), Err(VmError::NoOwnedReference));
|
||||
assert_eq!(vm.get_attr(owner, "child").unwrap(), Value::Object(child));
|
||||
vm.del_attr(owner, "child").unwrap();
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
vm.get_attr(owner, "child"),
|
||||
Err(VmError::AttributeNotFound("child".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_same_edge_does_not_destroy_the_target() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let owner = vm.new_object().unwrap();
|
||||
let target = vm.new_object().unwrap();
|
||||
vm.set_attr(owner, "child", Value::Object(target)).unwrap();
|
||||
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();
|
||||
assert!(matches!(vm.object(target), Err(VmError::InvalidHandle)));
|
||||
assert_eq!(vm.get_attr(owner, "child").unwrap(), Value::Integer(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_attribute_results_can_be_retained_by_the_host() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let parent = vm.new_object().unwrap();
|
||||
let child = vm.new_object().unwrap();
|
||||
vm.set_attr(parent, "child", Value::Object(child)).unwrap();
|
||||
vm.release(child).unwrap();
|
||||
let Value::Object(borrowed) = vm.get_attr(parent, "child").unwrap() else {
|
||||
panic!("expected an object");
|
||||
};
|
||||
vm.retain(borrowed).unwrap();
|
||||
vm.release(parent).unwrap();
|
||||
assert_eq!(vm.ref_count(borrowed).unwrap(), 1);
|
||||
vm.release(borrowed).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_foreign_and_stale_writes_preserve_the_old_attribute() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let mut other = Vm::new().unwrap();
|
||||
let local = vm.create_instance(vm.root_class()).unwrap();
|
||||
let foreign = other.create_instance(other.root_class()).unwrap();
|
||||
let count = vm.object_count();
|
||||
let owner = vm.new_object().unwrap();
|
||||
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();
|
||||
assert_eq!(
|
||||
vm.create_class("Alien", other.root_class()),
|
||||
vm.set_attr(owner, "value", Value::Object(foreign)),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
assert_eq!(
|
||||
vm.create_instance(other.root_class()),
|
||||
Err(VmError::ForeignHandle)
|
||||
vm.set_attr(owner, "value", Value::Object(stale)),
|
||||
Err(VmError::InvalidHandle)
|
||||
);
|
||||
assert!(matches!(
|
||||
vm.object(foreign.into()),
|
||||
Err(VmError::ForeignHandle)
|
||||
));
|
||||
assert!(matches!(vm.instance(foreign), Err(VmError::ForeignHandle)));
|
||||
for reference in [
|
||||
foreign.into(),
|
||||
other.root_class().into(),
|
||||
other.type_class().into(),
|
||||
] {
|
||||
assert_eq!(vm.type_of(reference), Err(VmError::ForeignHandle));
|
||||
}
|
||||
assert_eq!(
|
||||
vm.set_field(foreign, "x", Value::Nil),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
vm.set_field(local, "x", Value::Integer(7)).unwrap();
|
||||
assert_eq!(
|
||||
vm.set_field(local, "x", Value::Object(foreign.into())),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
assert_eq!(
|
||||
vm.instance(local).unwrap().field("x"),
|
||||
Some(&Value::Integer(7))
|
||||
);
|
||||
assert_eq!(vm.object_count(), count);
|
||||
assert_eq!(vm.get_attr(owner, "value").unwrap(), Value::Integer(1));
|
||||
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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_outliving_a_vm_cannot_alias_a_new_vm() {
|
||||
let old = {
|
||||
let vm = Vm::new().unwrap();
|
||||
vm.root_class()
|
||||
};
|
||||
let vm = Vm::new().unwrap();
|
||||
assert_ne!(old, vm.root_class());
|
||||
assert!(matches!(vm.class(old), Err(VmError::ForeignHandle)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_names_do_not_allocate_and_names_are_not_a_namespace() {
|
||||
fn released_handles_cannot_alias_new_objects_or_new_vms() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
assert_eq!(
|
||||
vm.create_class(" ", vm.root_class()),
|
||||
Err(VmError::EmptyClassName)
|
||||
);
|
||||
for name in ["Object", "Type"] {
|
||||
assert_eq!(
|
||||
vm.create_class(name, vm.root_class()),
|
||||
Err(VmError::ReservedClassName)
|
||||
);
|
||||
}
|
||||
assert_eq!(vm.object_count(), 2);
|
||||
let a = vm.create_class("Label", vm.root_class()).unwrap();
|
||||
let b = vm.create_class("Label", vm.root_class()).unwrap();
|
||||
assert_ne!(a, b);
|
||||
let old = vm.new_object().unwrap();
|
||||
vm.release(old).unwrap();
|
||||
let new = vm.new_object().unwrap();
|
||||
assert_ne!(old, new);
|
||||
assert_eq!(vm.repr(old), Err(VmError::InvalidHandle));
|
||||
let other = Vm::new().unwrap();
|
||||
assert!(matches!(other.object(new), Err(VmError::ForeignHandle)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_cannot_be_used_to_bypass_the_class_factory() {
|
||||
fn boxed_objects_keep_their_addresses_when_the_slot_vector_grows() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let type_class = vm.type_class();
|
||||
let count = vm.object_count();
|
||||
assert_eq!(
|
||||
vm.create_instance(type_class),
|
||||
Err(VmError::UnsupportedMetaclass)
|
||||
);
|
||||
assert_eq!(
|
||||
vm.create_class("CustomType", type_class),
|
||||
Err(VmError::UnsupportedMetaclass)
|
||||
);
|
||||
assert_eq!(vm.object_count(), count);
|
||||
assert_eq!(vm.type_of(type_class.into()).unwrap(), type_class);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_remain_valid_when_the_arena_grows() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let root = vm.root_class();
|
||||
let first = vm.create_instance(root).unwrap();
|
||||
vm.set_field(first, "stable", Value::Bool(true)).unwrap();
|
||||
let first = vm.new_object().unwrap();
|
||||
let address = std::ptr::from_ref(vm.object(first).unwrap());
|
||||
for _ in 0..4096 {
|
||||
vm.create_instance(root).unwrap();
|
||||
vm.new_object().unwrap();
|
||||
}
|
||||
assert_eq!(vm.type_of(first.into()).unwrap(), root);
|
||||
assert_eq!(vm.type_of(root.into()).unwrap(), vm.type_class());
|
||||
assert_eq!(vm.type_of(vm.type_class().into()).unwrap(), vm.type_class());
|
||||
assert_eq!(
|
||||
vm.instance(first).unwrap().field("stable"),
|
||||
Some(&Value::Bool(true))
|
||||
);
|
||||
assert_eq!(vm.class(root).unwrap().name(), "Object");
|
||||
assert_eq!(std::ptr::from_ref(vm.object(first).unwrap()), address);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_reference_chains_are_released_without_recursive_destructors() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let head = vm.new_object().unwrap();
|
||||
let mut tail = head;
|
||||
for _ in 0..4096 {
|
||||
let next = vm.new_object().unwrap();
|
||||
vm.set_attr(tail, "next", Value::Object(next)).unwrap();
|
||||
vm.release(next).unwrap();
|
||||
tail = next;
|
||||
}
|
||||
vm.release(head).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycles_remain_while_rooted_and_are_collected_when_unreachable() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let first = resource(&mut vm, &drops, vec![]);
|
||||
let second = resource(&mut vm, &drops, vec![]);
|
||||
vm.set_attr(first, "next", Value::Object(second)).unwrap();
|
||||
vm.set_attr(second, "next", Value::Object(first)).unwrap();
|
||||
vm.release(second).unwrap();
|
||||
assert_eq!(vm.collect_cycles(), 0);
|
||||
vm.release(first).unwrap();
|
||||
assert_eq!(vm.object_count(), 2);
|
||||
assert_eq!(vm.collect_cycles(), 2);
|
||||
assert_eq!(vm.collect_cycles(), 0);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 2);
|
||||
assert!(matches!(vm.object(first), Err(VmError::InvalidHandle)));
|
||||
assert!(matches!(vm.object(second), Err(VmError::InvalidHandle)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycle_collection_preserves_rooted_targets_and_updates_counts() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let live = vm.new_object().unwrap();
|
||||
let cycle = vm.new_object().unwrap();
|
||||
vm.set_attr(cycle, "self", Value::Object(cycle)).unwrap();
|
||||
vm.set_attr(cycle, "live", Value::Object(live)).unwrap();
|
||||
vm.release(cycle).unwrap();
|
||||
assert_eq!(vm.ref_count(live).unwrap(), 2);
|
||||
assert_eq!(vm.collect_cycles(), 1);
|
||||
assert_eq!(vm.ref_count(live).unwrap(), 1);
|
||||
vm.release(live).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_edges_are_owned_and_duplicate_edges_are_counted() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let target = vm.new_object().unwrap();
|
||||
let holder = resource(&mut vm, &drops, vec![target, target]);
|
||||
assert_eq!(vm.ref_count(target).unwrap(), 3);
|
||||
vm.release(target).unwrap();
|
||||
vm.release(holder).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_edges_participate_in_cycle_tracing() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let record = vm.new_object().unwrap();
|
||||
let native = resource(&mut vm, &drops, vec![record]);
|
||||
vm.set_attr(record, "native", Value::Object(native))
|
||||
.unwrap();
|
||||
vm.release(record).unwrap();
|
||||
vm.release(native).unwrap();
|
||||
assert_eq!(vm.collect_cycles(), 2);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_payload_edges_abort_allocation_without_retaining_valid_edges() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let mut other = Vm::new().unwrap();
|
||||
let local = vm.new_object().unwrap();
|
||||
let foreign = other.new_object().unwrap();
|
||||
assert_eq!(
|
||||
vm.allocate(Resource {
|
||||
drops: drops.clone(),
|
||||
edges: vec![local, foreign],
|
||||
}),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
assert_eq!(vm.ref_count(local).unwrap(), 1);
|
||||
assert_eq!(vm.object_count(), 1);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_payload_operations_override_defaults_without_language_types() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let zero = vm.allocate(Number(0)).unwrap();
|
||||
let first = vm.allocate(Number(42)).unwrap();
|
||||
let equal = vm.allocate(Number(42)).unwrap();
|
||||
assert!(!vm.is_same(first, equal).unwrap());
|
||||
assert!(vm.compare(first, equal, CompareOp::Eq).unwrap());
|
||||
assert!(vm.compare(zero, first, CompareOp::Lt).unwrap());
|
||||
assert_eq!(vm.hash(first).unwrap(), vm.hash(equal).unwrap());
|
||||
assert_eq!(vm.str(first).unwrap(), "42");
|
||||
assert!(!vm.is_true(zero).unwrap());
|
||||
assert!(vm.is_true(first).unwrap());
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ReflectedOrdering;
|
||||
|
||||
impl ObjectPayload for ReflectedOrdering {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"reflected-ordering"
|
||||
}
|
||||
|
||||
fn compare(
|
||||
&self,
|
||||
_other: &dyn ObjectPayload,
|
||||
operation: CompareOp,
|
||||
) -> Result<Option<bool>, VmError> {
|
||||
Ok(Some(operation == CompareOp::Gt))
|
||||
}
|
||||
|
||||
fn hash(&self, _identity: ObjectRef) -> Result<u64, VmError> {
|
||||
Err(VmError::UnsupportedOperation("hash"))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflected_operations_and_explicitly_unsupported_hashing_are_respected() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let left = vm.allocate(Record).unwrap();
|
||||
let right = vm.allocate(ReflectedOrdering).unwrap();
|
||||
assert!(vm.compare(left, right, CompareOp::Lt).unwrap());
|
||||
assert_eq!(vm.hash(right), Err(VmError::UnsupportedOperation("hash")));
|
||||
}
|
||||
|
||||
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")),
|
||||
_ => Err(VmError::InvalidArgument("expected two integers")),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_calls_dispatch_validate_arguments_and_propagate_errors() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
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)
|
||||
);
|
||||
assert_eq!(
|
||||
vm.call(function, &[]),
|
||||
Err(VmError::InvalidArgument("expected two integers"))
|
||||
);
|
||||
assert_eq!(
|
||||
vm.call(function, &[Value::Integer(i64::MAX), Value::Integer(1)]),
|
||||
Err(VmError::InvalidArgument("integer overflow"))
|
||||
);
|
||||
assert_eq!(
|
||||
vm.set_attr(function, "x", Value::Nil),
|
||||
Err(VmError::UnsupportedOperation("attributes"))
|
||||
);
|
||||
let mut other = Vm::new().unwrap();
|
||||
let foreign = other.new_object().unwrap();
|
||||
assert_eq!(
|
||||
vm.call(function, &[Value::Object(foreign)]),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ReturnsObject(ObjectRef);
|
||||
|
||||
impl ObjectPayload for ReturnsObject {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"invalid-return"
|
||||
}
|
||||
|
||||
fn call(&self, _arguments: &[Value]) -> Result<Value, VmError> {
|
||||
Ok(Value::Object(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_results_cannot_smuggle_foreign_or_dead_handles_into_the_vm() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let mut other = Vm::new().unwrap();
|
||||
let foreign = other.new_object().unwrap();
|
||||
let invalid_return = vm.allocate(ReturnsObject(foreign)).unwrap();
|
||||
assert_eq!(vm.call(invalid_return, &[]), Err(VmError::ForeignHandle));
|
||||
let dead = vm.new_object().unwrap();
|
||||
vm.release(dead).unwrap();
|
||||
let invalid_return = vm.allocate(ReturnsObject(dead)).unwrap();
|
||||
assert_eq!(vm.call(invalid_return, &[]), Err(VmError::InvalidHandle));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_the_vm_cleans_up_rooted_objects_and_uncollected_cycles() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
{
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let rooted = resource(&mut vm, &drops, vec![]);
|
||||
let cycle = resource(&mut vm, &drops, vec![]);
|
||||
vm.set_attr(cycle, "self", Value::Object(cycle)).unwrap();
|
||||
vm.release(cycle).unwrap();
|
||||
assert_eq!(vm.ref_count(rooted).unwrap(), 1);
|
||||
}
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user