refactor: extract core objects into a standalone package
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m34s
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m34s
This commit is contained in:
+3
-2
@@ -4,14 +4,15 @@
|
||||
|
||||
| 目录 | 包名/产物 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| [core](core/README.md) | core,库 endor_core | 零外部依赖的对象运行时、堆与字节码 VM |
|
||||
| [core](core/README.md) | core,库 endor_core | VM、执行帧与字节码求值循环,仅依赖本地 objects |
|
||||
| [objects](objects/README.md) | objects | 零依赖的核心对象、对象存储、代码对象与指令数据/静态验证 |
|
||||
| [frontend](frontend/README.md) | frontend | Endor 阅读器、手写 lexer、token PEG parser、基础函数/表达式 AST,不执行源码 |
|
||||
| [host](host/README.md) | host | UTF-8 JSON 文件基础信息,与数据库分离 |
|
||||
| [storage](storage/README.md) | storage | 为数据库特殊类保留的显式连接适配,不提供基础信息存储 |
|
||||
| [cli](cli/README.md) | cli,二进制 cli | 引导演示、源码解析与文件信息命令,不使用数据库 |
|
||||
| [server](server/README.md) | server,二进制 server | HTTP 宿主与文件版本信息,不使用数据库 |
|
||||
|
||||
CLI 依赖 Core、Frontend 与 Host,Server 依赖 Core 与 Host,二者不依赖 Storage;Frontend 依赖 peg,不依赖 Core;Core 与 Storage 也互不依赖。未来特殊类的宿主实现按需依赖 Storage,见 [数据库对象](../docs/runtime/database-objects.md)。
|
||||
CLI 依赖 Core、Frontend 与 Host,Server 依赖 Core 与 Host,二者不依赖 Storage;Frontend 依赖 peg,不依赖 Core;Core 只依赖本地 Objects;Objects 不依赖 Core 或第三方包,二者均不依赖 Storage。未来特殊类的宿主实现按需依赖 Storage,见 [数据库对象](../docs/runtime/database-objects.md)。
|
||||
|
||||
Endor 的解释执行流程与平台资源版本方向见 [执行与版本模型](../docs/architecture/execution-and-versions.md)。Frontend 到 AST 与 Core 执行字节码目前仍是两段独立能力,后续需要连接内部字节码生成;版本锁、平台资源后端和持久化字节码缓存均未实现。
|
||||
|
||||
|
||||
@@ -9,5 +9,8 @@ license.workspace = true
|
||||
[lib]
|
||||
name = "endor_core"
|
||||
|
||||
[dependencies]
|
||||
objects.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
# core
|
||||
|
||||
Endor VM 内核,保持零外部依赖。负责 EndorObject、堆、代际句柄、引用计数/循环回收、基本载荷和小型 wordcode 执行器。公共 Rust API 从 src/lib.rs 导出。Cargo 包名为 core,Rust 引用名为 endor_core,由 Cargo.toml 的 [lib] 设置,避免与标准库 core 重名。
|
||||
Endor VM 包,仅负责 Vm、执行帧、调用协议和 wordcode 求值循环。依赖本地 [objects](../objects/README.md) 管理对象与堆,没有第三方依赖。Cargo 包名为 core,Rust 引用名为 endor_core,避免与标准库 core 重名。
|
||||
|
||||
| 内容 | 入口 |
|
||||
| --- | --- |
|
||||
| Cargo.toml | 包元数据、endor_core 库目标和工作区 lint;没有外部依赖 |
|
||||
| [src](src/README.md) | 文件职责、公开接口和常见修改位置 |
|
||||
| [tests](tests/README.md) | 对象、基本载荷、执行语义与生命周期检查 |
|
||||
| Cargo.toml | endor_core 库目标、本地 objects 依赖和工作区 lint |
|
||||
| [src](src/README.md) | VM、内部执行帧、求值循环和对象操作委托 |
|
||||
| [tests](tests/README.md) | 原有对象入口的兼容行为、调用/执行语义与生命周期 |
|
||||
|
||||
内核通过 Vm::new 从空堆启动;代码对象和全局字典由宿主显式创建,再 execute/call。内核没有环境变量探测、数据库、HTTP、Python type 系统或源码解析;源码阅读器与 lexer/parser 在独立 [frontend](../frontend/README.md) 包中,AST 到字节码生成尚未实现。解释执行与平台版本方向见 [执行与版本模型](../../docs/architecture/execution-and-versions.md)。
|
||||
Vm::new 创建独立 ObjectStore 和空执行状态;代码对象、全局字典和函数仍按宿主需要显式创建,再 execute/call。EndorObject、Number、ObjectRef、内置载荷、代码对象/指令定义与 VmError 在 objects 中实现;endor_core 保留这些类型的兼容重导出,既有 Vm 对象方法委托到 ObjectStore。
|
||||
|
||||
对象结果所有权见 [生命周期](../../docs/runtime/lifecycle.md),对象/字节码设计见 [运行时](../../docs/runtime/README.md),限额与 UTF-8 边界见 [配置](../../docs/operations/configuration.md)。本地不构建或运行测试,验证入口见 [验证](../../docs/operations/validation.md)。返回 [工作区](../README.md)。
|
||||
没有 Python type/元类或语言根类。网络、数据库和进程环境属于宿主,源码阅读器与 lexer/parser 属于 [frontend](../frontend/README.md),AST 到字节码生成尚未实现,见 [执行与版本模型](../../docs/architecture/execution-and-versions.md)。
|
||||
|
||||
返回值所有权见 [生命周期](../../docs/runtime/lifecycle.md),执行契约见 [字节码 VM](../../docs/runtime/bytecode.md)。本地不构建或测试,见 [验证](../../docs/operations/validation.md)。返回 [工作区](../README.md)。
|
||||
|
||||
+12
-20
@@ -1,29 +1,21 @@
|
||||
# Core 源码导航
|
||||
# Core VM 源码导航
|
||||
|
||||
本目录解释实现文件如何分工;跨文件的设计规则只在 [运行时文档](../../../docs/runtime/README.md) 维护。公开 API 的最终导出入口是 lib.rs。
|
||||
本目录只实现 VM、内部执行帧和 wordcode 求值循环。核心对象、对象堆、内置载荷、指令与代码对象数据属于独立 [objects/src](../../objects/src/README.md)。
|
||||
|
||||
| 文件 | 内容 |
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 声明模块、公开类型导出、对象和字节码 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload、ObjectHeader、EndorObject、Record、NativeFunction |
|
||||
| [heap.rs](heap.rs) | ObjectRef、稳定 Box 槽位、代际验证、引用事务、迭代释放、显式循环收集;含私有边界测试 |
|
||||
| [vm.rs](vm.rs) | Vm/VmError、构造和对象操作入口、retain/release、循环回收入口 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边 |
|
||||
| [number.rs](number.rs) | EndorNumber、Integer/Decimal/Rational/BinaryFloat/Complex 表示及装箱载荷 |
|
||||
| [vm_builtins.rs](vm_builtins.rs) | 内置载荷校验、代码/函数工厂、Dict/Cell 操作、键语义和可变引用更新 |
|
||||
| [instruction.rs](instruction.rs) | Opcode、逻辑指令、EXTENDED_ARG 编解码、MakeFunction 计数构造、指令位置与比较参数 |
|
||||
| [code.rs](code.rs) | CodeLayout、EndorCode、共享 EndorCodeObject、操作数/控制流/栈校验 |
|
||||
| [lib.rs](lib.rs) | VM 类型导出、objects 类型兼容重导出、宿主调用与字节码 rustdoc 示例 |
|
||||
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作显式委托给 objects |
|
||||
| [frame.rs](frame.rs) | EndorFrame、栈条目、执行位置元数据、ExecutionLimits |
|
||||
| [eval.rs](eval.rs) | execute/call、参数绑定、帧切换、取指分派、字节码创建函数、结果根转移与失败清理 |
|
||||
| [eval.rs](eval.rs) | execute/call、参数绑定、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
|
||||
|
||||
## 常见修改入口
|
||||
|
||||
| 要修改什么 | 涉及文件 | 同步说明 |
|
||||
| 要修改什么 | 涉及位置 | 同步说明 |
|
||||
| --- | --- | --- |
|
||||
| 对象公共操作或头部 | object.rs、vm.rs、heap.rs | [对象模型](../../../docs/runtime/objects.md) |
|
||||
| 内置载荷、无损数字或容器行为 | builtins.rs/number.rs、vm_builtins.rs | [基本对象](../../../docs/runtime/builtins.md) |
|
||||
| 新操作码 | instruction.rs、code.rs 的参数和栈验证、eval.rs 分派 | [字节码 VM](../../../docs/runtime/bytecode.md)、execution 测试 |
|
||||
| 调用、闭包或返回值根管理 | frame.rs、eval.rs、函数 trace | [生命周期](../../../docs/runtime/lifecycle.md)、builtins 与 execution 测试 |
|
||||
| 新公开 API | 对应实现模块与 lib.rs 导出 | 所属主题、示例、[tests 导航](../tests/README.md) |
|
||||
| 对象表示、分配、引用或内置对象行为 | objects/src;兼容方法需要时同步 vm.rs 委托 | [对象模型](../../../docs/runtime/objects.md)、[基本对象](../../../docs/runtime/builtins.md) |
|
||||
| 新操作码或代码布局 | objects 的 instruction.rs/code.rs、core 的 eval.rs | [字节码 VM](../../../docs/runtime/bytecode.md)、execution 检查 |
|
||||
| 调用、闭包或返回值根管理 | frame.rs、eval.rs、objects 的函数 trace | [生命周期](../../../docs/runtime/lifecycle.md) |
|
||||
| 新 VM 公开 API | vm.rs/eval.rs 与 lib.rs 导出 | 所属主题、示例、[tests 导航](../tests/README.md) |
|
||||
|
||||
复制 ObjectRef/Value 不增加引用;不能在自定义载荷中擅自改变已登记的托管边。对象 API 不暴露原始指针或句柄索引构造。返回 [core](../README.md)。
|
||||
core 不访问对象私有字段或 Heap;执行器只通过受校验的对象存储操作维护帧根。返回 [core](../README.md)。
|
||||
|
||||
+12
-8
@@ -1,11 +1,14 @@
|
||||
use crate::code::jump_target;
|
||||
use crate::frame::StackEntry;
|
||||
use crate::instruction::{compare_operation, function_counts, invalid};
|
||||
use crate::{
|
||||
CompareOp, EndorCellObject, EndorCodeObject, EndorFrame, EndorFunctionObject,
|
||||
EndorStringObject, ExecutionLimits, ExecutionLocation, ObjectRef, Opcode, Value, Vm, VmError,
|
||||
EndorStringObject, ExecutionLimits, ExecutionLocation, Instruction, ObjectRef, Opcode, Value,
|
||||
Vm, VmError,
|
||||
};
|
||||
|
||||
fn invalid(offset: usize, reason: &'static str) -> VmError {
|
||||
VmError::InvalidBytecode { offset, reason }
|
||||
}
|
||||
|
||||
impl Vm {
|
||||
/// Execute a code object in a globals dictionary. Like CPython's EvalCode
|
||||
/// entry path, this constructs a temporary function and enters its frame.
|
||||
@@ -315,7 +318,7 @@ impl Vm {
|
||||
}
|
||||
|
||||
fn make_function(&mut self, frame: &EndorFrame, argument: u32) -> Result<ObjectRef, VmError> {
|
||||
let (default_count, closure_count) = function_counts(argument);
|
||||
let (default_count, closure_count) = Instruction::function_counts(argument);
|
||||
let Value::Object(code) = Self::top_value(frame)? else {
|
||||
return Err(VmError::ObjectKindMismatch("code"));
|
||||
};
|
||||
@@ -494,13 +497,13 @@ impl Vm {
|
||||
}
|
||||
}
|
||||
Opcode::JumpForward | Opcode::JumpBackward => {
|
||||
frame.instruction_offset = jump_target(decoded)?
|
||||
frame.instruction_offset = decoded.jump_target()?
|
||||
}
|
||||
Opcode::PopJumpIfFalse | Opcode::PopJumpIfTrue => {
|
||||
let truth = self.value_is_true(&Self::top_value(frame)?)?;
|
||||
self.discard(frame, 1);
|
||||
if truth == (opcode == Opcode::PopJumpIfTrue) {
|
||||
frame.instruction_offset = jump_target(decoded)?;
|
||||
frame.instruction_offset = decoded.jump_target()?;
|
||||
}
|
||||
}
|
||||
Opcode::ToBool | Opcode::UnaryNot => {
|
||||
@@ -520,7 +523,7 @@ impl Vm {
|
||||
let result = self.compare_values(
|
||||
&left,
|
||||
&right,
|
||||
compare_operation(decoded.instruction.argument).unwrap(),
|
||||
Instruction::compare_operation(decoded.instruction.argument).unwrap(),
|
||||
)?;
|
||||
self.discard(frame, 2);
|
||||
frame.stack.push(StackEntry::Value(Value::Bool(result)));
|
||||
@@ -555,7 +558,8 @@ impl Vm {
|
||||
}
|
||||
Opcode::MakeFunction => {
|
||||
let function = self.make_function(frame, decoded.instruction.argument)?;
|
||||
let (defaults, closure) = function_counts(decoded.instruction.argument);
|
||||
let (defaults, closure) =
|
||||
Instruction::function_counts(decoded.instruction.argument);
|
||||
self.discard(frame, defaults + closure + 1);
|
||||
frame.stack.push(StackEntry::Value(Value::Object(function)));
|
||||
}
|
||||
|
||||
+9
-22
@@ -1,4 +1,4 @@
|
||||
//! Embeddable object runtime and a small wordcode interpreter. No parser or
|
||||
//! Embeddable wordcode VM backed by the independent objects crate. No parser or
|
||||
//! Python language type system; wordcode is not CPython bytecode compatible.
|
||||
//!
|
||||
//! ```
|
||||
@@ -38,30 +38,17 @@
|
||||
//! # Ok::<(), endor_core::VmError>(())
|
||||
//! ```
|
||||
|
||||
mod builtins;
|
||||
mod code;
|
||||
mod eval;
|
||||
mod frame;
|
||||
mod heap;
|
||||
mod instruction;
|
||||
mod number;
|
||||
mod object;
|
||||
mod vm;
|
||||
mod vm_builtins;
|
||||
|
||||
pub use builtins::{
|
||||
EndorBaseExceptionObject, EndorCellObject, EndorDictObject, EndorFunctionObject,
|
||||
EndorStringObject, EndorTracebackEntry,
|
||||
};
|
||||
pub use code::{CodeLayout, EndorCode, EndorCodeObject};
|
||||
pub use frame::{EndorFrame, ExecutionLimits, ExecutionLocation};
|
||||
pub use heap::ObjectRef;
|
||||
pub use instruction::{DecodedInstruction, Instruction, Opcode};
|
||||
pub use number::{
|
||||
EndorDecimal, EndorInteger, EndorNumber, EndorNumberObject, EndorRational, EndorReal,
|
||||
// Preserve existing embedding imports; objects owns these definitions.
|
||||
pub use objects::{
|
||||
CodeLayout, CompareOp, DecodedInstruction, EndorBaseExceptionObject, EndorCellObject,
|
||||
EndorCode, EndorCodeObject, EndorDecimal, EndorDictObject, EndorFunctionObject, EndorInteger,
|
||||
EndorNativeCall, EndorNativeFunctionObject, EndorNumber, EndorNumberObject, EndorObject,
|
||||
EndorRational, EndorReal, EndorStringObject, EndorTracebackEntry, Instruction, NativeCall,
|
||||
NativeFunction, ObjectHeader, ObjectPayload, ObjectRef, Opcode, Record, Value, VmError,
|
||||
};
|
||||
pub use object::{
|
||||
CompareOp, EndorNativeCall, EndorNativeFunctionObject, EndorObject, NativeCall, NativeFunction,
|
||||
ObjectHeader, ObjectPayload, Record, Value,
|
||||
};
|
||||
pub use vm::{Vm, VmError};
|
||||
pub use vm::Vm;
|
||||
|
||||
+106
-106
@@ -1,138 +1,74 @@
|
||||
use std::fmt;
|
||||
use objects::ObjectStore;
|
||||
|
||||
use crate::heap::Heap;
|
||||
use crate::{CompareOp, EndorObject, ExecutionLocation, ObjectPayload, ObjectRef, Record, Value};
|
||||
use crate::{
|
||||
CompareOp, EndorCode, EndorNumber, EndorObject, ExecutionLocation, ObjectPayload, ObjectRef,
|
||||
Value, VmError,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VmError {
|
||||
ForeignHandle,
|
||||
InvalidHandle,
|
||||
IdentityExhausted,
|
||||
RefCountOverflow,
|
||||
NoOwnedReference,
|
||||
AttributeNotFound(String),
|
||||
UnsupportedOperation(&'static str),
|
||||
InvalidArgument(&'static str),
|
||||
ObjectKindMismatch(&'static str),
|
||||
EmptyCell,
|
||||
InvalidBytecode {
|
||||
offset: usize,
|
||||
reason: &'static str,
|
||||
},
|
||||
UnboundLocal(String),
|
||||
NameNotFound(String),
|
||||
ArgumentCount {
|
||||
name: String,
|
||||
required: usize,
|
||||
maximum: usize,
|
||||
provided: usize,
|
||||
},
|
||||
ExecutionLimit(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for VmError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
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),
|
||||
Self::ObjectKindMismatch(expected) => write!(f, "expected {expected} object"),
|
||||
Self::EmptyCell => f.write_str("cell is empty"),
|
||||
Self::InvalidBytecode { offset, reason } => {
|
||||
write!(f, "invalid bytecode at code unit {offset}: {reason}")
|
||||
}
|
||||
Self::UnboundLocal(name) => write!(f, "local variable is unbound: {name}"),
|
||||
Self::NameNotFound(name) => write!(f, "name not found: {name}"),
|
||||
Self::ArgumentCount {
|
||||
name,
|
||||
required,
|
||||
maximum,
|
||||
provided,
|
||||
} => write!(
|
||||
f,
|
||||
"{name} expects {required}..={maximum} positional arguments, received {provided}"
|
||||
),
|
||||
Self::ExecutionLimit(limit) => write!(f, "execution limit reached: {limit}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VmError {}
|
||||
|
||||
/// Runtime owner. Construction creates an empty heap, without language classes,
|
||||
/// metaclasses or a Python type system. Dropping it releases all host resources.
|
||||
/// Owns the object store and execution state. Object representation, allocation,
|
||||
/// reference accounting and builtin operations live in the objects crate.
|
||||
#[derive(Debug)]
|
||||
pub struct Vm {
|
||||
pub(crate) heap: Heap,
|
||||
objects: ObjectStore,
|
||||
pub(crate) last_traceback: Vec<ExecutionLocation>,
|
||||
}
|
||||
|
||||
impl Vm {
|
||||
pub fn new() -> Result<Self, VmError> {
|
||||
Ok(Self {
|
||||
heap: Heap::new()?,
|
||||
objects: ObjectStore::new()?,
|
||||
last_traceback: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn object_count(&self) -> usize {
|
||||
self.heap.len()
|
||||
self.objects.object_count()
|
||||
}
|
||||
|
||||
/// 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))
|
||||
self.objects.allocate(payload)
|
||||
}
|
||||
|
||||
pub fn new_object(&mut self) -> Result<ObjectRef, VmError> {
|
||||
self.allocate(Record)
|
||||
self.objects.new_object()
|
||||
}
|
||||
|
||||
pub fn object(&self, reference: ObjectRef) -> Result<&EndorObject, VmError> {
|
||||
self.heap.get(reference)
|
||||
self.objects.object(reference)
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
self.heap.retain(reference)
|
||||
self.objects.retain(reference)
|
||||
}
|
||||
|
||||
pub fn release(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
self.heap.release(reference)
|
||||
self.objects.release(reference)
|
||||
}
|
||||
|
||||
pub fn ref_count(&self, reference: ObjectRef) -> Result<usize, VmError> {
|
||||
Ok(self.heap.get(reference)?.header().ref_count())
|
||||
self.objects.ref_count(reference)
|
||||
}
|
||||
|
||||
pub fn is_same(&self, left: ObjectRef, right: ObjectRef) -> Result<bool, VmError> {
|
||||
self.heap.get(left)?;
|
||||
self.heap.get(right)?;
|
||||
Ok(left == right)
|
||||
self.objects.is_same(left, right)
|
||||
}
|
||||
|
||||
pub fn repr(&self, reference: ObjectRef) -> Result<String, VmError> {
|
||||
self.heap.get(reference)?.payload().repr(reference)
|
||||
self.objects.repr(reference)
|
||||
}
|
||||
|
||||
pub fn str(&self, reference: ObjectRef) -> Result<String, VmError> {
|
||||
self.heap.get(reference)?.payload().str(reference)
|
||||
self.objects.str(reference)
|
||||
}
|
||||
|
||||
pub fn is_true(&self, reference: ObjectRef) -> Result<bool, VmError> {
|
||||
self.heap.get(reference)?.payload().is_true()
|
||||
self.objects.is_true(reference)
|
||||
}
|
||||
|
||||
pub fn hash(&self, reference: ObjectRef) -> Result<u64, VmError> {
|
||||
self.heap.get(reference)?.payload().hash(reference)
|
||||
self.objects.hash(reference)
|
||||
}
|
||||
|
||||
pub fn compare(
|
||||
@@ -141,25 +77,13 @@ impl Vm {
|
||||
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")),
|
||||
}
|
||||
self.objects.compare(left, right, operation)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
self.objects.get_attr(reference, name)
|
||||
}
|
||||
|
||||
/// Object-valued attributes own internal strong references independently
|
||||
@@ -170,23 +94,99 @@ impl Vm {
|
||||
name: impl Into<String>,
|
||||
value: Value,
|
||||
) -> Result<(), VmError> {
|
||||
self.heap.set_attr(reference, name.into(), value)
|
||||
self.objects.set_attr(reference, name, value)
|
||||
}
|
||||
|
||||
pub fn del_attr(&mut self, reference: ObjectRef, name: &str) -> Result<(), VmError> {
|
||||
self.heap.del_attr(reference, name)
|
||||
self.objects.del_attr(reference, name)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_value(&self, value: &Value) -> Result<(), VmError> {
|
||||
if let Value::Object(reference) = value {
|
||||
self.heap.get(*reference)?;
|
||||
}
|
||||
Ok(())
|
||||
self.objects.validate_value(value)
|
||||
}
|
||||
|
||||
/// Explicit full collection. Execution slots use owned roots, so values
|
||||
/// on live execution stacks participate in the same root accounting.
|
||||
pub fn collect_cycles(&mut self) -> usize {
|
||||
self.heap.collect_cycles()
|
||||
self.objects.collect_cycles()
|
||||
}
|
||||
|
||||
pub fn payload<T: ObjectPayload>(
|
||||
&self,
|
||||
reference: ObjectRef,
|
||||
expected: &'static str,
|
||||
) -> Result<&T, VmError> {
|
||||
self.objects.payload::<T>(reference, expected)
|
||||
}
|
||||
|
||||
pub fn new_string(&mut self, text: impl Into<String>) -> Result<ObjectRef, VmError> {
|
||||
self.objects.new_string(text)
|
||||
}
|
||||
|
||||
pub fn new_code(&mut self, code: EndorCode) -> Result<ObjectRef, VmError> {
|
||||
self.objects.new_code(code)
|
||||
}
|
||||
|
||||
pub fn new_function(
|
||||
&mut self,
|
||||
name: impl Into<String>,
|
||||
code: ObjectRef,
|
||||
globals: ObjectRef,
|
||||
defaults: Vec<Value>,
|
||||
closure: Vec<ObjectRef>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
self.objects
|
||||
.new_function(name, code, globals, defaults, closure)
|
||||
}
|
||||
|
||||
pub fn new_number(&mut self, number: EndorNumber) -> Result<ObjectRef, VmError> {
|
||||
self.objects.new_number(number)
|
||||
}
|
||||
|
||||
pub fn new_dict(&mut self) -> Result<ObjectRef, VmError> {
|
||||
self.objects.new_dict()
|
||||
}
|
||||
|
||||
/// Returns borrowed keys and values in insertion order.
|
||||
pub fn dict_items(&self, dictionary: ObjectRef) -> Result<&[(Value, Value)], VmError> {
|
||||
self.objects.dict_items(dictionary)
|
||||
}
|
||||
|
||||
pub fn dict_get(&self, dictionary: ObjectRef, key: &Value) -> Result<Option<Value>, VmError> {
|
||||
self.objects.dict_get(dictionary, key)
|
||||
}
|
||||
|
||||
pub fn dict_set(
|
||||
&mut self,
|
||||
dictionary: ObjectRef,
|
||||
key: Value,
|
||||
value: Value,
|
||||
) -> Result<(), VmError> {
|
||||
self.objects.dict_set(dictionary, key, value)
|
||||
}
|
||||
|
||||
pub fn dict_delete(&mut self, dictionary: ObjectRef, key: &Value) -> Result<bool, VmError> {
|
||||
self.objects.dict_delete(dictionary, key)
|
||||
}
|
||||
|
||||
pub fn dict_clear(&mut self, dictionary: ObjectRef) -> Result<(), VmError> {
|
||||
self.objects.dict_clear(dictionary)
|
||||
}
|
||||
|
||||
pub fn new_cell(&mut self, value: Option<Value>) -> Result<ObjectRef, VmError> {
|
||||
self.objects.new_cell(value)
|
||||
}
|
||||
|
||||
/// Reads a borrowed value; an empty cell is not Value::Nil.
|
||||
pub fn cell_get(&self, cell: ObjectRef) -> Result<Value, VmError> {
|
||||
self.objects.cell_get(cell)
|
||||
}
|
||||
|
||||
pub fn cell_set(&mut self, cell: ObjectRef, value: Value) -> Result<(), VmError> {
|
||||
self.objects.cell_set(cell, value)
|
||||
}
|
||||
|
||||
pub fn cell_clear(&mut self, cell: ObjectRef) -> Result<(), VmError> {
|
||||
self.objects.cell_clear(cell)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,4 @@
|
||||
| [builtins.rs](builtins.rs) | 无损 Number、Unicode 字符串、Dict 顺序与键、Cell、函数环境/共享代码、异常数据 |
|
||||
| [execution.rs](execution.rs) | wordcode 与校验、控制流、参数/默认值、嵌套帧、字节码函数创建/默认值/环境捕获、闭包、返回值存活、失败清理、限额 |
|
||||
|
||||
堆内部伪造句柄与计数溢出检查在 src/heap.rs,公开示例由 src/lib.rs rustdoc 提供。文件职责见 [src](../src/README.md),检查方式和结果边界见 [验证](../../../docs/operations/validation.md)。本地不执行测试;存在测试文件不代表某次提交已通过。返回 [core](../README.md)。
|
||||
核心对象现由 objects 定义,本目录保留既有 endor_core 导入与 Vm 方法的兼容性检查。独立对象存储检查见 [objects/tests](../../objects/tests/README.md)。堆内部伪造句柄与计数溢出检查在 objects 的 src/heap.rs,公开示例由 src/lib.rs rustdoc 提供。文件职责见 [src](../src/README.md),检查方式和结果边界见 [验证](../../../docs/operations/validation.md)。本地不执行测试;存在测试文件不代表某次提交已通过。返回 [core](../README.md)。
|
||||
|
||||
@@ -9,4 +9,4 @@
|
||||
| [tests](tests/README.md) | Unicode、优先级、函数、完整输入与错误位置验证 |
|
||||
| [examples](examples/README.md) | 可交给 cli parse 的源码样例 |
|
||||
|
||||
宿主通过 EndorReader 读取字符串、流、文件或注入的 URI provider,取得 SourceUnit 后调用 lex_source、parse_source、parse_source_expression;低层 lex、parse、parse_expression 仍保留。读取契约见 [Endor 阅读器](../../docs/runtime/reader.md)。Core 仍为零外部依赖;后续把 AST 转成已有字节码并交给 VM 解释执行;这是平台内部准备步骤,尚未接通。资源修订、依赖锁和解释器统一升级的设计方向见 [执行与版本模型](../../docs/architecture/execution-and-versions.md)。返回 [工作区](../README.md)。
|
||||
宿主通过 EndorReader 读取字符串、流、文件或注入的 URI provider,取得 SourceUnit 后调用 lex_source、parse_source、parse_source_expression;低层 lex、parse、parse_expression 仍保留。读取契约见 [Endor 阅读器](../../docs/runtime/reader.md)。Objects 保持零依赖,Core 仅依赖本地 Objects;后续把 AST 转成已有字节码并交给 VM 解释执行;这是平台内部准备步骤,尚未接通。资源修订、依赖锁和解释器统一升级的设计方向见 [执行与版本模型](../../docs/architecture/execution-and-versions.md)。返回 [工作区](../README.md)。
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "objects"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,15 @@
|
||||
# objects
|
||||
|
||||
Endor 核心对象与对象存储包,零外部依赖,不依赖 core。包含 EndorObject、ObjectPayload、Value、ObjectRef、Number、字符串/字典/Cell/函数/异常载荷,以及代码对象与 wordcode 数据定义、编解码和静态验证。没有 Python type/元类或语言根类。
|
||||
|
||||
| 内容 | 职责 |
|
||||
| --- | --- |
|
||||
| Cargo.toml | objects 包元数据和工作区 lint;无依赖 |
|
||||
| [src](src/README.md) | 对象定义、私有堆、ObjectStore、对象工厂、字节码数据与共享错误 |
|
||||
| [tests](tests/README.md) | 不依赖 VM 的对象存储、事务失败、回收和共享代码检查 |
|
||||
|
||||
ObjectStore 独立拥有空堆,负责对象分配、代际校验、引用计数、循环回收、属性与内置容器操作;底层 Heap、句柄字段和可变载荷替换仍为私有实现。代码对象只保存及验证执行数据,求值循环与调用帧属于 [core](../core/README.md)。共享 VmError 定义在本包,保留现有名称以避免对象操作接口依赖 VM。
|
||||
|
||||
新代码可以直接从 objects 引用对象类型;endor_core 继续重导出现有类型,Vm 的对象方法委托给本包,原有宿主入口保持可用。复制句柄不增加引用;独立 ObjectStore 的对象句柄不能交给另一存储或 VM 使用。
|
||||
|
||||
设计与所有权见 [对象模型](../../docs/runtime/objects.md)、[基本对象](../../docs/runtime/builtins.md) 和 [生命周期](../../docs/runtime/lifecycle.md)。本地不构建或测试,运行检查交给指定远端,见 [验证](../../docs/operations/validation.md)。返回 [工作区](../README.md)。
|
||||
@@ -0,0 +1,20 @@
|
||||
# Objects 源码导航
|
||||
|
||||
公开导出集中在 lib.rs;本目录只负责对象与执行数据,不包含 VM 调度或取指分派。全局契约见 [运行时文档](../../../docs/runtime/README.md)。
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出与独立存储 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload、ObjectHeader、EndorObject、Record、NativeFunction |
|
||||
| [number.rs](number.rs) | Integer/Decimal/Rational/BinaryFloat/Complex 的无损表示和装箱载荷 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边 |
|
||||
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收及私有边界测试 |
|
||||
| [store.rs](store.rs) | ObjectStore、空堆创建、对象操作、retain/release 和回收入口 |
|
||||
| [store_builtins.rs](store_builtins.rs) | 载荷校验、代码/函数工厂、Dict/Cell 操作及键语义 |
|
||||
| [instruction.rs](instruction.rs) | Opcode、Instruction、wordcode 编解码、MakeFunction/比较参数与跳转读取接口 |
|
||||
| [code.rs](code.rs) | CodeLayout、EndorCode/EndorCodeObject、共享不可变代码和操作数/控制流/栈验证 |
|
||||
| [error.rs](error.rs) | 对象、代码与执行共用的 VmError,避免反向依赖 core |
|
||||
|
||||
对象操作变更同步 [对象模型](../../../docs/runtime/objects.md),内置载荷同步 [基本对象](../../../docs/runtime/builtins.md)。新增操作码需要同时修改本包 instruction.rs/code.rs 和 core 的 eval.rs 分派,见 [字节码 VM](../../../docs/runtime/bytecode.md)。
|
||||
|
||||
Heap、ObjectRef 字段、对象头计数和可变容器字段不向包外开放;公开代码读取接口不允许改写已登记的常量和托管边。检查入口见 [tests](../tests/README.md)。返回 [objects](../README.md)。
|
||||
@@ -121,17 +121,23 @@ impl EndorCode {
|
||||
pub fn slot_count(&self) -> usize {
|
||||
self.layout.locals.len() + self.layout.free_variables.len()
|
||||
}
|
||||
pub(crate) fn is_cell_slot(&self, slot: usize) -> bool {
|
||||
/// Whether a local/free slot holds a managed closure cell.
|
||||
pub fn is_cell_slot(&self, slot: usize) -> bool {
|
||||
is_cell_slot(&self.layout, slot)
|
||||
}
|
||||
pub(crate) fn slot_name(&self, slot: usize) -> &str {
|
||||
/// Name of a local/free slot used by validated instructions.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the slot is outside this code's local/free-variable layout.
|
||||
pub fn slot_name(&self, slot: usize) -> &str {
|
||||
if slot < self.layout.locals.len() {
|
||||
&self.layout.locals[slot]
|
||||
} else {
|
||||
&self.layout.free_variables[slot - self.layout.locals.len()]
|
||||
}
|
||||
}
|
||||
pub(crate) fn instruction_at(&self, offset: usize) -> Result<DecodedInstruction, VmError> {
|
||||
/// Look up a logical instruction by its code-unit offset.
|
||||
pub fn instruction_at(&self, offset: usize) -> Result<DecodedInstruction, VmError> {
|
||||
instruction_index(&self.instructions, offset)
|
||||
.map(|index| self.instructions[index])
|
||||
.ok_or_else(|| {
|
||||
@@ -159,7 +165,10 @@ impl EndorCodeObject {
|
||||
pub fn code(&self) -> &EndorCode {
|
||||
&self.code
|
||||
}
|
||||
pub(crate) fn shared_code(&self) -> Arc<EndorCode> {
|
||||
/// Share immutable executable data without copying constants or wordcode.
|
||||
/// This Rust Arc does not retain heap objects referenced by constants;
|
||||
/// callers must keep the managed code object rooted while using them.
|
||||
pub fn shared_code(&self) -> Arc<EndorCode> {
|
||||
Arc::clone(&self.code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::fmt;
|
||||
|
||||
/// Shared object/bytecode/execution errors. The established VmError name is
|
||||
/// retained for embedders; defining it here avoids a dependency on the VM.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VmError {
|
||||
ForeignHandle,
|
||||
InvalidHandle,
|
||||
IdentityExhausted,
|
||||
RefCountOverflow,
|
||||
NoOwnedReference,
|
||||
AttributeNotFound(String),
|
||||
UnsupportedOperation(&'static str),
|
||||
InvalidArgument(&'static str),
|
||||
ObjectKindMismatch(&'static str),
|
||||
EmptyCell,
|
||||
InvalidBytecode {
|
||||
offset: usize,
|
||||
reason: &'static str,
|
||||
},
|
||||
UnboundLocal(String),
|
||||
NameNotFound(String),
|
||||
ArgumentCount {
|
||||
name: String,
|
||||
required: usize,
|
||||
maximum: usize,
|
||||
provided: usize,
|
||||
},
|
||||
ExecutionLimit(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for VmError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
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),
|
||||
Self::ObjectKindMismatch(expected) => write!(f, "expected {expected} object"),
|
||||
Self::EmptyCell => f.write_str("cell is empty"),
|
||||
Self::InvalidBytecode { offset, reason } => {
|
||||
write!(f, "invalid bytecode at code unit {offset}: {reason}")
|
||||
}
|
||||
Self::UnboundLocal(name) => write!(f, "local variable is unbound: {name}"),
|
||||
Self::NameNotFound(name) => write!(f, "name not found: {name}"),
|
||||
Self::ArgumentCount {
|
||||
name,
|
||||
required,
|
||||
maximum,
|
||||
provided,
|
||||
} => write!(
|
||||
f,
|
||||
"{name} expects {required}..={maximum} positional arguments, received {provided}"
|
||||
),
|
||||
Self::ExecutionLimit(limit) => write!(f, "execution limit reached: {limit}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VmError {}
|
||||
@@ -127,6 +127,16 @@ impl Instruction {
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode a comparison operand; None denotes an invalid operand.
|
||||
pub fn compare_operation(argument: u32) -> Option<CompareOp> {
|
||||
compare_operation(argument)
|
||||
}
|
||||
|
||||
/// Decode the default-value and closure-cell counts of MAKE_FUNCTION.
|
||||
pub fn function_counts(argument: u32) -> (usize, usize) {
|
||||
function_counts(argument)
|
||||
}
|
||||
|
||||
/// Encodes 8-bit operands directly and prefixes up to three EXTENDED_ARG
|
||||
/// code units for larger operands. Each code unit is [opcode, operand].
|
||||
pub fn encode_all(instructions: &[Self]) -> Result<Vec<u8>, VmError> {
|
||||
@@ -157,6 +167,22 @@ pub struct DecodedInstruction {
|
||||
pub instruction: Instruction,
|
||||
}
|
||||
|
||||
impl DecodedInstruction {
|
||||
/// Resolve a jump relative to the end of this logical instruction.
|
||||
pub fn jump_target(self) -> Result<usize, VmError> {
|
||||
if !matches!(
|
||||
self.instruction.opcode,
|
||||
Opcode::JumpForward
|
||||
| Opcode::JumpBackward
|
||||
| Opcode::PopJumpIfFalse
|
||||
| Opcode::PopJumpIfTrue
|
||||
) {
|
||||
return Err(invalid(self.offset, "instruction is not a jump"));
|
||||
}
|
||||
crate::code::jump_target(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(bytes: &[u8]) -> Result<Vec<DecodedInstruction>, VmError> {
|
||||
if bytes.is_empty() || !bytes.len().is_multiple_of(2) {
|
||||
return Err(invalid(
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Core Endor objects, values, validated executable data and object storage.
|
||||
//! This crate has no VM evaluator or external dependencies. Handles, reference
|
||||
//! accounting and mutable payload replacement remain encapsulated here.
|
||||
//!
|
||||
//! ```
|
||||
//! use objects::{ObjectStore, Value};
|
||||
//! let mut store = ObjectStore::new()?;
|
||||
//! let object = store.new_object()?;
|
||||
//! store.set_attr(object, "name", Value::Text("Endor".into()))?;
|
||||
//! assert_eq!(store.get_attr(object, "name")?, Value::Text("Endor".into()));
|
||||
//! store.release(object)?;
|
||||
//! assert_eq!(store.object_count(), 0);
|
||||
//! # Ok::<(), objects::VmError>(())
|
||||
//! ```
|
||||
|
||||
mod builtins;
|
||||
mod code;
|
||||
mod error;
|
||||
mod heap;
|
||||
mod instruction;
|
||||
mod number;
|
||||
mod object;
|
||||
mod store;
|
||||
mod store_builtins;
|
||||
|
||||
pub use builtins::{
|
||||
EndorBaseExceptionObject, EndorCellObject, EndorDictObject, EndorFunctionObject,
|
||||
EndorStringObject, EndorTracebackEntry,
|
||||
};
|
||||
pub use code::{CodeLayout, EndorCode, EndorCodeObject};
|
||||
pub use error::VmError;
|
||||
pub use heap::ObjectRef;
|
||||
pub use instruction::{DecodedInstruction, Instruction, Opcode};
|
||||
pub use number::{
|
||||
EndorDecimal, EndorInteger, EndorNumber, EndorNumberObject, EndorRational, EndorReal,
|
||||
};
|
||||
pub use object::{
|
||||
CompareOp, EndorNativeCall, EndorNativeFunctionObject, EndorObject, NativeCall, NativeFunction,
|
||||
ObjectHeader, ObjectPayload, Record, Value,
|
||||
};
|
||||
pub use store::ObjectStore;
|
||||
@@ -0,0 +1,125 @@
|
||||
use crate::heap::Heap;
|
||||
use crate::{CompareOp, EndorObject, ObjectPayload, ObjectRef, Record, Value, VmError};
|
||||
|
||||
/// Object storage independent of the VM evaluator. Construction creates an empty
|
||||
/// heap; dropping it releases all objects and their host resources. Mutable
|
||||
/// access is limited to operations that validate and account for owned edges.
|
||||
#[derive(Debug)]
|
||||
pub struct ObjectStore {
|
||||
pub(crate) heap: Heap,
|
||||
}
|
||||
|
||||
impl ObjectStore {
|
||||
pub fn new() -> Result<Self, VmError> {
|
||||
Ok(Self { heap: Heap::new()? })
|
||||
}
|
||||
|
||||
pub fn object_count(&self) -> usize {
|
||||
self.heap.len()
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
pub fn new_object(&mut self) -> Result<ObjectRef, VmError> {
|
||||
self.allocate(Record)
|
||||
}
|
||||
|
||||
pub fn object(&self, reference: ObjectRef) -> Result<&EndorObject, VmError> {
|
||||
self.heap.get(reference)
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, reference: ObjectRef) -> Result<(), VmError> {
|
||||
self.heap.retain(reference)
|
||||
}
|
||||
|
||||
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")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
reference: ObjectRef,
|
||||
name: impl Into<String>,
|
||||
value: Value,
|
||||
) -> Result<(), VmError> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// Validate a borrowed object handle without taking an owned reference.
|
||||
pub fn validate_value(&self, value: &Value) -> Result<(), VmError> {
|
||||
if let Value::Object(reference) = value {
|
||||
self.heap.get(*reference)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Explicit full collection. Execution slots use owned roots, so values
|
||||
/// on live execution stacks participate in the same root accounting.
|
||||
pub fn collect_cycles(&mut self) -> usize {
|
||||
self.heap.collect_cycles()
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@ use std::hash::{Hash, Hasher};
|
||||
use crate::{
|
||||
CompareOp, EndorBaseExceptionObject, EndorCellObject, EndorCode, EndorCodeObject,
|
||||
EndorDictObject, EndorFunctionObject, EndorNumber, EndorNumberObject, EndorStringObject,
|
||||
ObjectPayload, ObjectRef, Value, Vm, VmError,
|
||||
ObjectPayload, ObjectRef, ObjectStore, Value, VmError,
|
||||
};
|
||||
|
||||
impl Vm {
|
||||
impl ObjectStore {
|
||||
pub(crate) fn validate_builtin(&self, payload: &dyn ObjectPayload) -> Result<(), VmError> {
|
||||
if let Some(function) = payload.as_any().downcast_ref::<EndorFunctionObject>() {
|
||||
let code = self
|
||||
@@ -0,0 +1,9 @@
|
||||
# Objects 独立行为检查
|
||||
|
||||
本目录只依赖 objects 公共 API,不依赖 core 或 VM 求值器。
|
||||
|
||||
| 文件 | 覆盖 |
|
||||
| --- | --- |
|
||||
| [store.rs](store.rs) | 稳定地址、跨存储句柄拒绝与更新原子性、Dict/Cell 循环回收、函数校验失败无泄漏、共享代码与常量生命周期 |
|
||||
|
||||
非法句柄索引、槽位代数与计数溢出仍在 src/heap.rs 的私有单元测试内,不开放句柄构造器。VM 委托 API 与求值行为继续由 [core/tests](../../core/tests/README.md) 检查。随工作区在指定远端运行,本地不测试;现有测试源码不代表已通过,见 [验证](../../../docs/operations/validation.md)。返回 [objects](../README.md)。
|
||||
@@ -0,0 +1,96 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use objects::{
|
||||
CodeLayout, EndorCode, EndorCodeObject, EndorFunctionObject, Instruction, ObjectStore, Opcode,
|
||||
Value, VmError,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn standalone_storage_preserves_identity_validates_edges_and_collects_cycles() {
|
||||
let mut store = ObjectStore::new().unwrap();
|
||||
let mut other = ObjectStore::new().unwrap();
|
||||
let dictionary = store.new_dict().unwrap();
|
||||
let cell = store.new_cell(Some(Value::Object(dictionary))).unwrap();
|
||||
let foreign = other.new_object().unwrap();
|
||||
let address = store.object(dictionary).unwrap() as *const _;
|
||||
let key = Value::Text("cell".into());
|
||||
|
||||
store
|
||||
.dict_set(dictionary, key.clone(), Value::Object(cell))
|
||||
.unwrap();
|
||||
assert_eq!(store.object(dictionary).unwrap() as *const _, address);
|
||||
assert_eq!(
|
||||
store.dict_set(dictionary, key.clone(), Value::Object(foreign)),
|
||||
Err(VmError::ForeignHandle)
|
||||
);
|
||||
assert_eq!(
|
||||
store.dict_get(dictionary, &key).unwrap(),
|
||||
Some(Value::Object(cell))
|
||||
);
|
||||
assert_eq!(store.ref_count(cell).unwrap(), 2);
|
||||
store.release(dictionary).unwrap();
|
||||
store.release(cell).unwrap();
|
||||
assert_eq!(store.collect_cycles(), 2);
|
||||
assert_eq!(store.object_count(), 0);
|
||||
assert!(matches!(store.object(cell), Err(VmError::InvalidHandle)));
|
||||
other.release(foreign).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_function_factories_validate_and_own_shared_executable_data() {
|
||||
let mut store = ObjectStore::new().unwrap();
|
||||
let constant = store.new_string("kept by code").unwrap();
|
||||
let globals = store.new_dict().unwrap();
|
||||
let code = EndorCode::from_instructions(
|
||||
&[
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
],
|
||||
vec![Value::Object(constant)],
|
||||
CodeLayout::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let code = store.new_code(code).unwrap();
|
||||
let before = store.object_count();
|
||||
assert_eq!(
|
||||
store.new_function("bad", code, globals, vec![Value::Nil], vec![]),
|
||||
Err(VmError::InvalidArgument(
|
||||
"function defaults or closure do not match code"
|
||||
))
|
||||
);
|
||||
assert_eq!(store.object_count(), before);
|
||||
assert_eq!(store.ref_count(code).unwrap(), 1);
|
||||
let first = store
|
||||
.new_function("first", code, globals, vec![], vec![])
|
||||
.unwrap();
|
||||
let second = store
|
||||
.new_function("second", code, globals, vec![], vec![])
|
||||
.unwrap();
|
||||
let first_code = store
|
||||
.payload::<EndorFunctionObject>(first, "function")
|
||||
.unwrap()
|
||||
.code();
|
||||
let second_code = store
|
||||
.payload::<EndorFunctionObject>(second, "function")
|
||||
.unwrap()
|
||||
.code();
|
||||
let first_executable = store
|
||||
.payload::<EndorCodeObject>(first_code, "code")
|
||||
.unwrap()
|
||||
.shared_code();
|
||||
let second_executable = store
|
||||
.payload::<EndorCodeObject>(second_code, "code")
|
||||
.unwrap()
|
||||
.shared_code();
|
||||
assert!(Arc::ptr_eq(&first_executable, &second_executable));
|
||||
drop(first_executable);
|
||||
drop(second_executable);
|
||||
store.release(constant).unwrap();
|
||||
store.release(code).unwrap();
|
||||
store.release(globals).unwrap();
|
||||
assert_eq!(store.str(constant).unwrap(), "kept by code");
|
||||
store.release(first).unwrap();
|
||||
assert_eq!(store.ref_count(code).unwrap(), 1);
|
||||
store.release(second).unwrap();
|
||||
assert_eq!(store.object_count(), 0);
|
||||
}
|
||||
Reference in New Issue
Block a user