feat: retain read-only execution frames across instruction slices

This commit is contained in:
2026-10-23 00:59:23 +08:00
parent e511e393d9
commit 1c729b4128
9 changed files with 298 additions and 10 deletions
+3 -3
View File
@@ -5,9 +5,9 @@
| 文件 | 职责 |
| --- | --- |
| [lib.rs](lib.rs) | VM 类型导出、objects 类型兼容重导出(含 ReadAccess/CallSignature/CallType/CallEffect)、宿主调用与字节码 rustdoc 示例 |
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作和宿主 new_class 和显式/类型化Trait注册/关系查询显式委托给 objects;函数/字段检查统一开关、统一参数区间/已知调用效果查询与函数类型配置 |
| [frame.rs](frame.rs) | EndorFrame、栈条目、源码与原生委托返回契约执行根、执行位置元数据、ExecutionLimits |
| [eval.rs](eval.rs) | execute/call、只读调用与依赖结果、参数绑定、原生实现前数量/类型/效果检查和原生/类型化Trait委托返回检查、可选注解/动态覆写兼容检查、源码类字段环境绑定、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore、错误位置记录与挂起的只读执行状态;对象操作和宿主 new_class 和显式/类型化Trait注册/关系查询显式委托给 objects;函数/字段检查统一开关、统一参数区间/已知调用效果查询与函数类型配置 |
| [frame.rs](frame.rs) | EndorFrame、栈条目、源码与原生委托返回契约执行根、执行位置元数据、ExecutionLimits、ExecutionProgress 与 VM 内续算帧状态 |
| [eval.rs](eval.rs) | execute/call、只读调用/可恢复分片/取消与依赖结果、参数绑定、原生实现前数量/类型/效果检查和原生/类型化Trait委托返回检查、可选注解/动态覆写兼容检查、源码类字段环境绑定、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
## 常见修改入口
+147 -4
View File
@@ -1,4 +1,5 @@
use crate::frame::{NativeReturn, StackEntry};
use crate::ExecutionProgress;
use crate::frame::{NativeReturn, StackEntry, SuspendedCall};
use crate::{
CompareOp, EndorCellObject, EndorCodeObject, EndorFrame, EndorFunctionObject,
EndorStringObject, ExecutionLimits, ExecutionLocation, Instruction, ObjectRef, Opcode, Value,
@@ -69,6 +70,11 @@ impl Vm {
arguments: &[Value],
limits: ExecutionLimits,
) -> Result<Value, VmError> {
if self.suspended_call.is_some() {
return Err(VmError::UnsupportedOperation(
"call while read-only execution is suspended",
));
}
self.last_traceback.clear();
let mut executed = 0;
let frame = match self.prepare_call(function, arguments.to_vec(), &mut executed, limits)? {
@@ -80,7 +86,9 @@ impl Vm {
return Err(VmError::ExecutionLimit("frames"));
}
let mut frames = vec![frame];
let result = self.eval_frames(&mut frames, limits, &mut executed);
let result = self
.eval_frames(&mut frames, limits, &mut executed, usize::MAX)
.map(|value| value.expect("unbounded slice completes or fails"));
if result.is_err() {
self.last_traceback = frames
.iter()
@@ -98,6 +106,137 @@ impl Vm {
result
}
/// Begin a resumable read-only call. One VM owns at most one continuation.
/// A slice is a soft instruction quantum: native callbacks and delegation
/// complete atomically and remain subject to the cumulative hard limits.
pub fn start_read_only_call(
&mut self,
function: ObjectRef,
arguments: &[Value],
limits: ExecutionLimits,
slice: usize,
) -> Result<ExecutionProgress, VmError> {
if slice == 0 {
return Err(VmError::InvalidArgument("execution slice must be positive"));
}
if self.suspended_call.is_some() || self.objects.is_read_only() {
return Err(VmError::UnsupportedOperation(
"start suspended call inside another execution",
));
}
self.last_traceback.clear();
let scope = self.objects.begin_read_only();
let mut executed = 0;
let prepared = self.prepare_call(function, arguments.to_vec(), &mut executed, limits);
match prepared {
Ok(PreparedCall::Value(value)) => {
let reads = match self.objects.end_read_only(scope) {
Ok(reads) => reads,
Err(error) => {
self.drop_root(value);
return Err(error);
}
};
Ok(ExecutionProgress::Complete {
value,
reads,
instructions: executed,
})
}
Ok(PreparedCall::Frame(frame)) => {
if limits.max_frames == 0 {
self.clear_frame(frame);
self.objects.end_read_only(scope)?;
return Err(VmError::ExecutionLimit("frames"));
}
self.suspended_call = Some(SuspendedCall {
frames: vec![frame],
scope,
limits,
executed,
});
// Preparation counts toward the first quantum as well.
self.resume_read_only_to(slice)
}
Err(error) => {
self.objects.end_read_only(scope)?;
Err(error)
}
}
}
pub fn has_suspended_call(&self) -> bool {
self.suspended_call.is_some()
}
/// Resume existing frames, never replay earlier instructions. The read-only
/// scope remains active across Pending; preexisting heap writes stay barred.
pub fn resume_read_only_call(&mut self, slice: usize) -> Result<ExecutionProgress, VmError> {
if slice == 0 {
return Err(VmError::InvalidArgument("execution slice must be positive"));
}
let executed = self
.suspended_call
.as_ref()
.ok_or(VmError::InvalidArgument("no suspended call"))?
.executed;
self.resume_read_only_to(executed.saturating_add(slice))
}
fn resume_read_only_to(&mut self, slice_end: usize) -> Result<ExecutionProgress, VmError> {
let mut call = self
.suspended_call
.take()
.ok_or(VmError::InvalidArgument("no suspended call"))?;
let result = self.eval_frames(&mut call.frames, call.limits, &mut call.executed, slice_end);
if let Ok(None) = result {
let instructions = call.executed;
self.suspended_call = Some(call);
return Ok(ExecutionProgress::Pending { instructions });
}
if result.is_err() {
self.last_traceback = call
.frames
.iter()
.map(|frame| ExecutionLocation {
function: frame.name.clone(),
filename: frame.executable.filename().into(),
first_line: frame.executable.first_line(),
instruction_offset: frame.current_offset,
})
.collect();
}
while let Some(frame) = call.frames.pop() {
self.clear_frame(frame);
}
let reads = self.objects.end_read_only(call.scope);
match (result, reads) {
(Ok(Some(value)), Ok(reads)) => Ok(ExecutionProgress::Complete {
value,
reads,
instructions: call.executed,
}),
(Ok(Some(value)), Err(error)) => {
self.drop_root(value);
Err(error)
}
(Err(error), _) => Err(error),
(Ok(None), _) => unreachable!(),
}
}
/// Release all retained execution roots and close the read-only scope.
pub fn cancel_read_only_call(&mut self) -> Result<bool, VmError> {
let Some(mut call) = self.suspended_call.take() else {
return Ok(false);
};
while let Some(frame) = call.frames.pop() {
self.clear_frame(frame);
}
self.objects.end_read_only(call.scope)?;
Ok(true)
}
/// Outer-to-inner execution locations from the last failed call/execute.
/// These are copied metadata, not heap references or language exceptions.
pub fn last_traceback(&self) -> &[ExecutionLocation] {
@@ -613,11 +752,15 @@ impl Vm {
frames: &mut Vec<EndorFrame>,
limits: ExecutionLimits,
executed: &mut usize,
) -> Result<Value, VmError> {
slice_end: usize,
) -> Result<Option<Value>, VmError> {
loop {
if *executed >= limits.max_instructions {
return Err(VmError::ExecutionLimit("instructions"));
}
if *executed >= slice_end {
return Ok(None);
}
*executed += 1;
let frame = frames.last_mut().expect("an evaluation frame is active");
let decoded = frame.executable.instruction_at(frame.instruction_offset)?;
@@ -782,7 +925,7 @@ impl Vm {
if let Some(caller) = frames.last_mut() {
caller.stack.push(StackEntry::Value(result));
} else {
return Ok(result);
return Ok(Some(result));
}
}
Opcode::JumpForward | Opcode::JumpBackward => {
+22
View File
@@ -91,3 +91,25 @@ impl Default for ExecutionLimits {
}
}
}
/// A read-only call either retains its VM-owned continuation or returns an
/// owned value plus borrowed read dependencies. Instruction counts accumulate.
#[derive(Debug)]
pub enum ExecutionProgress {
Pending {
instructions: usize,
},
Complete {
value: Value,
reads: Vec<ObjectRef>,
instructions: usize,
},
}
#[derive(Debug)]
pub(crate) struct SuspendedCall {
pub frames: Vec<EndorFrame>,
pub scope: usize,
pub limits: ExecutionLimits,
pub executed: usize,
}
+1 -1
View File
@@ -42,7 +42,7 @@ mod eval;
mod frame;
mod vm;
pub use frame::{EndorFrame, ExecutionLimits, ExecutionLocation};
pub use frame::{EndorFrame, ExecutionLimits, ExecutionLocation, ExecutionProgress};
// Preserve existing embedding imports; objects owns these definitions.
pub use objects::ObjectStore;
pub use objects::{
+2
View File
@@ -12,6 +12,7 @@ pub struct Vm {
pub(crate) objects: ObjectStore,
pub(crate) last_traceback: Vec<ExecutionLocation>,
pub(crate) source_type_checks: bool,
pub(crate) suspended_call: Option<crate::frame::SuspendedCall>,
}
impl Vm {
@@ -166,6 +167,7 @@ impl Vm {
objects: ObjectStore::new()?,
last_traceback: Vec::new(),
source_type_checks: false,
suspended_call: None,
})
}