2 Commits

8 changed files with 436 additions and 3 deletions
+2
View File
@@ -19,3 +19,5 @@
| 新 VM 公开 API | vm.rs/eval.rs 与 lib.rs 导出 | 所属主题、示例、[tests 导航](../tests/README.md) |
core 不访问对象私有字段或 Heap;执行器只通过受校验的对象存储操作维护帧根。返回 [core](../README.md)。
独立托管调用帧:frame.rs 定义 CoroutineProgress 和私有可追踪帧载荷;eval.rs 提供 new_coroutine/resume_coroutine/cancel_coroutine,暂停帧以托管边保活,恢复时转回执行根。与跨量子只读续算分开,所有权及边界见 docs/runtime/bytecode.md。
+229 -1
View File
@@ -1,10 +1,11 @@
use crate::ExecutionProgress;
use crate::frame::{NativeReturn, StackEntry, SuspendedCall};
use crate::frame::{Coroutine, CoroutineState, NativeReturn, StackEntry, SuspendedCall};
use crate::{
CompareOp, EndorCellObject, EndorCodeObject, EndorFrame, EndorFunctionObject,
EndorStringObject, ExecutionLimits, ExecutionLocation, Instruction, ObjectRef, Opcode, Value,
Vm, VmError,
};
use crate::{CoroutineProgress, ObjectPayload};
use crate::{NativeContext, NativeResult};
enum PreparedCall {
@@ -237,6 +238,233 @@ impl Vm {
Ok(true)
}
/// Prepare a managed independently resumable call. Native delegation may
/// run during preparation; source instructions start only on resume.
/// The returned handle owns one external reference, like every allocation.
pub fn new_coroutine(
&mut self,
function: ObjectRef,
arguments: &[Value],
limits: ExecutionLimits,
) -> Result<ObjectRef, VmError> {
self.check_coroutine_entry()?;
self.last_traceback.clear();
let mut executed = 0;
let prepared = self.prepare_call(function, arguments.to_vec(), &mut executed, limits)?;
let state = match prepared {
PreparedCall::Frame(frame) => {
if limits.max_frames == 0 {
self.clear_frame(frame);
return Err(VmError::ExecutionLimit("frames"));
}
CoroutineState::Frames(std::sync::Arc::new(vec![frame]))
}
PreparedCall::Value(value) => CoroutineState::Ready(value),
};
// Allocate traced edges before releasing the original execution roots.
let coroutine = Coroutine {
state,
limits,
executed,
};
let mut roots = Vec::new();
coroutine.trace(&mut |reference| roots.push(reference));
let result = self.allocate(coroutine);
for root in roots {
self.release(root)?;
}
result
}
fn check_coroutine_entry(&self) -> Result<(), VmError> {
if self.has_suspended_call() || self.objects.is_read_only() {
return Err(VmError::UnsupportedOperation(
"coroutine operation inside read-only execution",
));
}
Ok(())
}
/// Resume one managed call, preserving cumulative hard limits. Other calls
/// and heap writes may execute between Pending results. No prior instruction
/// is replayed. Completion returns an owned value and consumes the frames.
pub fn resume_coroutine(
&mut self,
reference: ObjectRef,
slice: usize,
) -> Result<CoroutineProgress, VmError> {
self.retain(reference)?;
let result = self.resume_coroutine_inner(reference, slice);
self.release(reference)?;
result
}
fn resume_coroutine_inner(
&mut self,
reference: ObjectRef,
slice: usize,
) -> Result<CoroutineProgress, VmError> {
self.check_coroutine_entry()?;
if slice == 0 {
return Err(VmError::InvalidArgument("execution slice must be positive"));
}
let coroutine = self.payload::<Coroutine>(reference, "coroutine")?;
let limits = coroutine.limits;
let mut executed = coroutine.executed;
let state = match &coroutine.state {
CoroutineState::Frames(frames) => CoroutineState::Frames(frames.clone()),
CoroutineState::Ready(value) => CoroutineState::Ready(value.clone()),
_ => return Err(VmError::InvalidArgument("coroutine is running or finished")),
};
let mut roots = Vec::new();
match &state {
CoroutineState::Frames(frames) => {
for frame in frames.iter() {
frame.trace_roots(&mut |root| roots.push(root));
}
}
CoroutineState::Ready(Value::Object(root)) => roots.push(*root),
_ => {}
}
// Transfer edges to execution roots transactionally, before replacing
// the managed payload. Duplicate edges must retain duplicate roots.
let mut retained = Vec::new();
for root in roots {
if let Err(error) = self.retain(root) {
for root in retained {
self.release(root)?;
}
return Err(error);
}
retained.push(root);
}
if let Err(error) = self.replace_payload(
reference,
Coroutine {
state: CoroutineState::Running,
limits,
executed,
},
) {
for root in retained {
self.release(root)?;
}
return Err(error);
}
self.last_traceback.clear();
let mut frames = match state {
CoroutineState::Frames(frames) => {
std::sync::Arc::try_unwrap(frames).expect("private frame storage has one owner")
}
CoroutineState::Ready(value) => {
if let Err(error) = self.replace_payload(
reference,
Coroutine {
state: CoroutineState::Finished,
limits,
executed,
},
) {
self.drop_root(value);
return Err(error);
}
return Ok(CoroutineProgress::Complete {
value,
instructions: executed,
});
}
_ => unreachable!(),
};
let slice_end = executed.saturating_add(slice);
let result = self.eval_frames(&mut frames, limits, &mut executed, slice_end);
if let Ok(None) = result {
let frames = std::sync::Arc::new(frames);
let mut roots = Vec::new();
for frame in frames.iter() {
frame.trace_roots(&mut |root| roots.push(root));
}
let published = self.replace_payload(
reference,
Coroutine {
state: CoroutineState::Frames(frames),
limits,
executed,
},
);
for root in roots {
self.release(root)?;
}
published?;
return Ok(CoroutineProgress::Pending {
instructions: executed,
});
}
if result.is_err() {
self.last_traceback = 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) = frames.pop() {
self.clear_frame(frame);
}
let finished = self.replace_payload(
reference,
Coroutine {
state: CoroutineState::Finished,
limits,
executed,
},
);
match result {
Ok(Some(value)) => {
if let Err(error) = finished {
self.drop_root(value);
return Err(error);
}
Ok(CoroutineProgress::Complete {
value,
instructions: executed,
})
}
Err(error) => {
finished?;
Err(error)
}
Ok(None) => unreachable!(),
}
}
/// Cancellation releases managed frame edges; dropping an unreachable
/// coroutine has the same ownership effect, including cycles through locals.
/// Writes performed by previous quanta are never rolled back.
pub fn cancel_coroutine(&mut self, reference: ObjectRef) -> Result<bool, VmError> {
self.check_coroutine_entry()?;
let coroutine = self.payload::<Coroutine>(reference, "coroutine")?;
if matches!(coroutine.state, CoroutineState::Running) {
return Err(VmError::InvalidArgument("coroutine is running"));
}
if matches!(coroutine.state, CoroutineState::Finished) {
return Ok(false);
}
let limits = coroutine.limits;
let executed = coroutine.executed;
self.replace_payload(
reference,
Coroutine {
state: CoroutineState::Finished,
limits,
executed,
},
)?;
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] {
+71
View File
@@ -113,3 +113,74 @@ pub(crate) struct SuspendedCall {
pub limits: ExecutionLimits,
pub executed: usize,
}
/// Independently parked mutable execution. Unlike read-only slicing, it does
/// not keep a VM-wide heap scope active between quanta.
#[derive(Debug)]
pub enum CoroutineProgress {
Pending { instructions: usize },
Complete { value: Value, instructions: usize },
}
#[derive(Debug)]
pub(crate) enum CoroutineState {
Frames(Arc<Vec<EndorFrame>>),
Ready(Value),
Running,
Finished,
}
#[derive(Debug)]
pub(crate) struct Coroutine {
pub state: CoroutineState,
pub limits: ExecutionLimits,
pub executed: usize,
}
impl EndorFrame {
/// Exactly the references held as execution roots while this frame runs.
/// code/globals/builtins remain reachable through its owning function.
pub(crate) fn trace_roots(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.function);
if let Some(reference) = self.return_type.and_then(|kind| kind.reference()) {
visit(reference);
}
for check in &self.native_returns {
for reference in check.expected.references() {
visit(reference);
}
}
for value in self
.localsplus
.iter()
.flatten()
.chain(self.stack.iter().filter_map(|entry| match entry {
StackEntry::Value(value) => Some(value),
StackEntry::Null => None,
}))
{
if let Value::Object(reference) = value {
visit(*reference);
}
}
}
}
impl crate::ObjectPayload for Coroutine {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"coroutine"
}
fn reference_assignment_only(&self) -> bool {
true
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
match &self.state {
CoroutineState::Frames(frames) => {
for frame in frames.iter() {
frame.trace_roots(visit);
}
}
CoroutineState::Ready(Value::Object(reference)) => visit(*reference),
_ => {}
}
}
}
+3 -1
View File
@@ -42,7 +42,9 @@ mod eval;
mod frame;
mod vm;
pub use frame::{EndorFrame, ExecutionLimits, ExecutionLocation, ExecutionProgress};
pub use frame::{
CoroutineProgress, EndorFrame, ExecutionLimits, ExecutionLocation, ExecutionProgress,
};
// Preserve existing embedding imports; objects owns these definitions.
pub use objects::ObjectStore;
pub use objects::{
+2
View File
@@ -15,3 +15,5 @@
核心对象现由 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)。
execution.rs 同时覆盖宿主可选 assign_from 的全局/局部赋值、别名身份、拒绝替换与执行根清理;不在本地运行。
execution.rs 的 managed_coroutine 用例覆盖交替恢复不重放写入、累计预算错误释放、取消幂等和暂停帧引用环回收;本地只经宿主Clippy编译,不运行测试。
+119
View File
@@ -1503,3 +1503,122 @@ fn suspended_call_cancellation_and_total_budget_restore_read_only_state() {
vm.release(shared).unwrap();
assert_eq!(vm.object_count(), 0);
}
#[test]
fn managed_coroutines_interleave_without_replaying_writes() {
use endor_core::CoroutineProgress;
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
let code = make_code(
&mut vm,
&[
op(Opcode::LoadConst, 0),
op(Opcode::StoreGlobal, 0),
op(Opcode::LoadConst, 1),
op(Opcode::StoreGlobal, 1),
op(Opcode::LoadConst, 2),
simple(Opcode::ReturnValue),
],
vec![text("first"), text("second"), Value::Nil],
CodeLayout {
names: vec!["x".into(), "y".into()],
..CodeLayout::default()
},
);
let function = vm
.new_function("work", code, globals, vec![], vec![])
.unwrap();
let first = vm
.new_coroutine(function, &[], ExecutionLimits::default())
.unwrap();
let second = vm
.new_coroutine(function, &[], ExecutionLimits::default())
.unwrap();
assert!(matches!(
vm.resume_coroutine(first, 2).unwrap(),
CoroutineProgress::Pending { instructions: 2 }
));
assert!(matches!(
vm.resume_coroutine(second, 2).unwrap(),
CoroutineProgress::Pending { instructions: 2 }
));
vm.dict_set(globals, text("x"), text("interleaved"))
.unwrap();
assert!(matches!(
vm.resume_coroutine(first, 16).unwrap(),
CoroutineProgress::Complete {
value: Value::Nil,
instructions: 6
}
));
assert_eq!(
vm.dict_get(globals, &text("x")).unwrap(),
Some(text("interleaved"))
);
assert_eq!(
vm.dict_get(globals, &text("y")).unwrap(),
Some(text("second"))
);
assert!(vm.cancel_coroutine(second).unwrap());
assert!(!vm.cancel_coroutine(second).unwrap());
assert!(vm.resume_coroutine(first, 1).is_err());
for object in [first, second, function, code, globals] {
vm.release(object).unwrap();
}
assert_eq!(vm.object_count(), 0);
}
#[test]
fn parked_coroutine_cycles_are_collectable_without_cancellation() {
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
let code = return_constant(&mut vm, Value::Nil);
let function = vm
.new_function("cycle", code, globals, vec![], vec![])
.unwrap();
let coroutine = vm
.new_coroutine(function, &[], ExecutionLimits::default())
.unwrap();
vm.dict_set(globals, text("task"), Value::Object(coroutine))
.unwrap();
for object in [coroutine, function, code, globals] {
vm.release(object).unwrap();
}
assert!(vm.collect_cycles() > 0);
assert_eq!(vm.object_count(), 0);
}
#[test]
fn managed_coroutine_hard_budget_accumulates_and_error_releases_frames() {
use endor_core::CoroutineProgress;
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
let code = return_constant(&mut vm, Value::Nil);
let function = vm
.new_function("limited", code, globals, vec![], vec![])
.unwrap();
let coroutine = vm
.new_coroutine(
function,
&[],
ExecutionLimits {
max_frames: 4,
max_instructions: 1,
},
)
.unwrap();
assert!(matches!(
vm.resume_coroutine(coroutine, 1).unwrap(),
CoroutineProgress::Pending { instructions: 1 }
));
assert!(matches!(
vm.resume_coroutine(coroutine, 1),
Err(VmError::ExecutionLimit("instructions"))
));
assert!(!vm.last_traceback().is_empty());
assert!(!vm.cancel_coroutine(coroutine).unwrap());
for object in [coroutine, function, code, globals] {
vm.release(object).unwrap();
}
assert_eq!(vm.object_count(), 0);
}
+1 -1
View File
@@ -12,7 +12,7 @@
| 词法、语法、裸赋值和诊断 | [Frontend](runtime/frontend.md) | frontend/src/lexer.peg/grammar.peg |
| ASDL、AST 与编辑器接口 | [AST](runtime/ast.md) | frontend/Endor.asdl |
| 名称分析、编译和装载 | [Compiler](runtime/compiler.md) | compiler/src |
| 字节码、函数、共享引用赋值、可恢复只读分片与限额 | [字节码 VM](runtime/bytecode.md) | objects/src、core/src |
| 字节码、函数、共享引用赋值、可恢复只读分片、独立托管调用帧与限额 | [字节码 VM](runtime/bytecode.md) | objects/src、core/src |
| 引用与 VM 生命周期 | [生命周期](runtime/lifecycle.md) | objects/src、core/src |
| UTF-8 与地区 | [文本编码](runtime/text-encoding.md) | frontend、objects |
| 嵌入及宿主入口 | [使用引擎](operations/README.md) | 独立宿主仓库 |
+9
View File
@@ -186,3 +186,12 @@ fn main() -> Result<(), endor_core::VmError> {
BuildClass(编号 29,无参数)消费四个栈值 `[name, baseType, fieldsDict, methodsDict]`,产生一个受管类对象;验证器按 4 入 1 出检查栈。字段字典按声明顺序保存字段名与注解名,方法字典保存 MakeFunction 创建的函数。VM 先验证基类、字段与方法关系,再创建完整类型;输入根在成功前保持在执行栈上,失败由帧统一清理。
LoadAttr 对实例自有属性返回原值;缺失时沿类型父链找方法并创建绑定方法。绑定方法持有 receiver 和选定的函数,调用时经已有非递归委托路径补入 self。类对象上的方法读取提供未绑定函数;type/name/base 元数据优先。宿主读取继承方法应使用返回拥有式结果的 bind_attr;get_attr 保持借用式读取,类型方法结果为未绑定函数。所有委托消耗同一指令预算。
## 独立托管调用帧
`Vm::new_coroutine(function, arguments, limits)` 返回拥有一份外部根的通用 coroutine 对象;`resume_coroutine(handle, slice)` 返回 `CoroutineProgress::Pending` 或带拥有式结果的 `Complete`。源码指令首次在 resume 执行,原生函数/委托可能在 new 的准备期间执行,仍受硬指令限额约束。该接口目前只提供分片执行基础,不等于 Endor async/await 语法或等待协议。
与只读续算不同,每个 coroutine 把自己的帧保存在同一 VM 的托管对象载荷中,多个调用可独立暂停;Pending 之间可执行普通调用和堆写入,没有跨量子的只读作用域。resume 不重放先前指令,局部槽、栈、返回类型及原生委托契约保持,所有量子共用原始硬指令/帧预算。原生调用仍是原子的,slice 不保证墙钟延迟。读写共享堆,无快照、事务或自动回滚。不能在只读执行/只读暂停期间创建、恢复或取消 coroutine。
暂停时,帧内原本的执行根转为载荷 trace 的托管边(包括重复边);恢复前先保活为执行根,再清空暂停载荷。函数边继续拥有 code/globals/builtins。运行中的 handle 临时保活,不能恢复或取消 Running/已结束帧;完成和错误均消耗帧,错误保留 traceback。`cancel_coroutine(handle)` 对尚未结束帧返回 true 并释放托管边,已结束返回 false;已发生的写入不回滚。调用方最终 release handle 和完成结果。丢弃未完成且不可达的 coroutine 不要求先 cancel,局部/全局指回 coroutine 的环可由正常循环回收处理,不把暂停帧永久登记为 VM 根。调度、任务归属、等待条件及取消策略由宿主实现,网络/GUI不进入内核。