Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fd247aca1f | |||
| f3e1670c58 | |||
| 1aecc7e952 | |||
| ee68a0c54c | |||
| 42c27d083d | |||
| a775d5c827 | |||
| 89b817447e | |||
| ae75c54707 | |||
| 8a2135897e | |||
| 16816c38c7 | |||
| b33d322690 | |||
| e6b27ba7b6 |
@@ -7,3 +7,5 @@
|
||||
| [codegen.rs](codegen.rs) | AST 到函数与类创建指令、嵌套代码模板与源码签名保留、EndorCode 验证、显式 VM 装载与临时根释放 |
|
||||
|
||||
节点定义在 frontend/Endor.asdl;这里匹配生成的 AST,不复制节点类型。源码和调用方提供的 AST 都先分析后生成,不执行 AST。修改名称语义、代码布局或所有权时同步 [编译契约](../../../docs/runtime/compiler.md)、[检查](../tests/README.md) 与 [示例](../examples/README.md)。返回 [compiler](../README.md)。
|
||||
|
||||
analysis.rs遍历Await操作数,codegen.rs发出Await字节码;运行时等待交给VM及宿主。
|
||||
|
||||
@@ -332,7 +332,9 @@ impl Builder {
|
||||
binding,
|
||||
});
|
||||
}
|
||||
ExprKind::Unary { operand, .. } => self.expression(operand, globals)?,
|
||||
ExprKind::Unary { operand, .. } | ExprKind::Await(operand) => {
|
||||
self.expression(operand, globals)?
|
||||
}
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
self.expression(left, globals)?;
|
||||
self.expression(right, globals)?;
|
||||
|
||||
@@ -300,6 +300,10 @@ impl<'a> Emitter<'a> {
|
||||
}
|
||||
self.emit(Opcode::Call, arguments.len())?;
|
||||
}
|
||||
ExprKind::Await(operand) => {
|
||||
self.expression(operand)?;
|
||||
self.simple(Opcode::Await);
|
||||
}
|
||||
ExprKind::Member { object, name } => {
|
||||
self.expression(object)?;
|
||||
self.emit(Opcode::LoadAttr, self.name_index(&name.text))?;
|
||||
|
||||
@@ -19,3 +19,9 @@
|
||||
| 新 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。
|
||||
|
||||
eval.rs的LoadGlobal及可恢复只读结果支持ReadDependency;frame.rs携带精确观察,lib.rs重导出只读观察类型,兼容旧reads对象列表。
|
||||
|
||||
同步call_read_only_precise_with_limits同样返回ReadSet,供宿主精确校验缓存;原call_read_only_with_limits继续返回保守objects列表,预算、结果拥有式引用和失败关闭只读作用域的语义不变。
|
||||
|
||||
+304
-11
@@ -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 {
|
||||
@@ -58,9 +59,23 @@ impl Vm {
|
||||
arguments: &[Value],
|
||||
limits: ExecutionLimits,
|
||||
) -> Result<(Value, Vec<ObjectRef>), VmError> {
|
||||
let (value, reads) =
|
||||
self.call_read_only_precise_with_limits(function, arguments, limits)?;
|
||||
Ok((value, reads.objects))
|
||||
}
|
||||
|
||||
/// Synchronous read-only call with precise observations as well as the
|
||||
/// conservative object list. Result ownership and hard limits match call().
|
||||
/// ReadSet and all identities/value snapshots inside it are borrowed only.
|
||||
pub fn call_read_only_precise_with_limits(
|
||||
&mut self,
|
||||
function: ObjectRef,
|
||||
arguments: &[Value],
|
||||
limits: ExecutionLimits,
|
||||
) -> Result<(Value, crate::ReadSet), VmError> {
|
||||
let scope = self.objects.begin_read_only();
|
||||
let result = self.call_with_limits(function, arguments, limits);
|
||||
let reads = self.objects.end_read_only(scope)?;
|
||||
let reads = self.objects.end_read_only_precise(scope)?;
|
||||
result.map(|value| (value, reads))
|
||||
}
|
||||
|
||||
@@ -87,7 +102,7 @@ impl Vm {
|
||||
}
|
||||
let mut frames = vec![frame];
|
||||
let result = self
|
||||
.eval_frames(&mut frames, limits, &mut executed, usize::MAX)
|
||||
.eval_frames(&mut frames, limits, &mut executed, usize::MAX, false)
|
||||
.map(|value| value.expect("unbounded slice completes or fails"));
|
||||
if result.is_err() {
|
||||
self.last_traceback = frames
|
||||
@@ -130,7 +145,7 @@ impl Vm {
|
||||
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) {
|
||||
let reads = match self.objects.end_read_only_precise(scope) {
|
||||
Ok(reads) => reads,
|
||||
Err(error) => {
|
||||
self.drop_root(value);
|
||||
@@ -139,7 +154,8 @@ impl Vm {
|
||||
};
|
||||
Ok(ExecutionProgress::Complete {
|
||||
value,
|
||||
reads,
|
||||
dependencies: reads.dependencies,
|
||||
reads: reads.objects,
|
||||
instructions: executed,
|
||||
})
|
||||
}
|
||||
@@ -188,7 +204,13 @@ impl Vm {
|
||||
.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);
|
||||
let result = self.eval_frames(
|
||||
&mut call.frames,
|
||||
call.limits,
|
||||
&mut call.executed,
|
||||
slice_end,
|
||||
false,
|
||||
);
|
||||
if let Ok(None) = result {
|
||||
let instructions = call.executed;
|
||||
self.suspended_call = Some(call);
|
||||
@@ -209,11 +231,12 @@ impl Vm {
|
||||
while let Some(frame) = call.frames.pop() {
|
||||
self.clear_frame(frame);
|
||||
}
|
||||
let reads = self.objects.end_read_only(call.scope);
|
||||
let reads = self.objects.end_read_only_precise(call.scope);
|
||||
match (result, reads) {
|
||||
(Ok(Some(value)), Ok(reads)) => Ok(ExecutionProgress::Complete {
|
||||
value,
|
||||
reads,
|
||||
dependencies: reads.dependencies,
|
||||
reads: reads.objects,
|
||||
instructions: call.executed,
|
||||
}),
|
||||
(Ok(Some(value)), Err(error)) => {
|
||||
@@ -237,6 +260,245 @@ 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, true);
|
||||
if let Ok(None) = result {
|
||||
let waiting = frames.last().filter(|frame| frame.waiting).map(|frame| {
|
||||
match Self::top_value(frame).expect("await operand remains on stack") {
|
||||
Value::Object(reference) => reference,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
});
|
||||
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?;
|
||||
if let Some(awaitable) = waiting {
|
||||
return Ok(CoroutineProgress::Waiting {
|
||||
awaitable,
|
||||
instructions: executed,
|
||||
});
|
||||
}
|
||||
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] {
|
||||
@@ -368,6 +630,7 @@ impl Vm {
|
||||
name: data.name().into(),
|
||||
instruction_offset: 0,
|
||||
current_offset: 0,
|
||||
waiting: false,
|
||||
localsplus: vec![None; executable.slot_count()],
|
||||
stack: Vec::with_capacity(executable.stack_size()),
|
||||
executable,
|
||||
@@ -753,6 +1016,7 @@ impl Vm {
|
||||
limits: ExecutionLimits,
|
||||
executed: &mut usize,
|
||||
slice_end: usize,
|
||||
allow_wait: bool,
|
||||
) -> Result<Option<Value>, VmError> {
|
||||
loop {
|
||||
if *executed >= limits.max_instructions {
|
||||
@@ -769,6 +1033,36 @@ impl Vm {
|
||||
let opcode = decoded.instruction.opcode;
|
||||
let argument = decoded.instruction.argument as usize;
|
||||
match opcode {
|
||||
Opcode::Await => {
|
||||
if self.objects.is_read_only() {
|
||||
return Err(VmError::UnsupportedOperation(
|
||||
"await during read-only execution",
|
||||
));
|
||||
}
|
||||
let Value::Object(awaitable) = Self::top_value(frame)? else {
|
||||
return Err(VmError::ObjectKindMismatch("awaitable object"));
|
||||
};
|
||||
match self.object(awaitable)?.payload().poll_await()? {
|
||||
crate::AwaitPoll::Pending => {
|
||||
if !allow_wait {
|
||||
return Err(VmError::UnsupportedOperation(
|
||||
"pending await outside a coroutine",
|
||||
));
|
||||
}
|
||||
// Keep the evaluated operand, never replay its call
|
||||
// or the statements before this await instruction.
|
||||
frame.waiting = true;
|
||||
frame.instruction_offset = decoded.offset;
|
||||
return Ok(None);
|
||||
}
|
||||
crate::AwaitPoll::Ready(value) => {
|
||||
self.retain_value(&value)?;
|
||||
self.discard(frame, 1);
|
||||
frame.stack.push(StackEntry::Value(value));
|
||||
frame.waiting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Opcode::Nop => {}
|
||||
Opcode::LoadConst => {
|
||||
let value = frame.executable.constants()[argument].clone();
|
||||
@@ -799,12 +1093,11 @@ impl Vm {
|
||||
}
|
||||
Opcode::LoadGlobal => {
|
||||
let name = &frame.executable.layout().names[argument];
|
||||
let key = Value::Text(name.clone());
|
||||
let mut value = self.dict_get(frame.globals, &key)?;
|
||||
let mut value = self.objects.dict_get_name(frame.globals, name)?;
|
||||
if value.is_none()
|
||||
&& let Some(builtins) = frame.builtins
|
||||
{
|
||||
value = self.dict_get(builtins, &key)?;
|
||||
value = self.objects.dict_get_name(builtins, name)?;
|
||||
}
|
||||
let value = value.ok_or_else(|| VmError::NameNotFound(name.clone()))?;
|
||||
self.push_borrowed(frame, value)?;
|
||||
|
||||
@@ -38,6 +38,7 @@ pub struct EndorFrame {
|
||||
pub(crate) name: String,
|
||||
pub(crate) instruction_offset: usize,
|
||||
pub(crate) current_offset: usize,
|
||||
pub(crate) waiting: bool,
|
||||
pub(crate) localsplus: Vec<Option<Value>>,
|
||||
pub(crate) stack: Vec<StackEntry>,
|
||||
}
|
||||
@@ -102,6 +103,7 @@ pub enum ExecutionProgress {
|
||||
Complete {
|
||||
value: Value,
|
||||
reads: Vec<ObjectRef>,
|
||||
dependencies: Vec<crate::ReadDependency>,
|
||||
instructions: usize,
|
||||
},
|
||||
}
|
||||
@@ -113,3 +115,83 @@ 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 {
|
||||
Waiting {
|
||||
awaitable: ObjectRef,
|
||||
instructions: usize,
|
||||
},
|
||||
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),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,14 @@ 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::{
|
||||
AnnotationType, ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement, RootTypes,
|
||||
TypeConstructor, TypedMethodRequirement,
|
||||
AnnotationType, AwaitPoll, ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement,
|
||||
RootTypes, TypeConstructor, TypedMethodRequirement,
|
||||
};
|
||||
pub use objects::{
|
||||
CallArity, CallEffect, CallSignature, CallType, ChangeBatch, ChangeKey, CodeLayout, CompareOp,
|
||||
@@ -56,7 +58,7 @@ pub use objects::{
|
||||
EndorNativeCall, EndorNativeFunctionObject, EndorNumber, EndorNumberObject, EndorObject,
|
||||
EndorRational, EndorReal, EndorStringObject, EndorTracebackEntry, Instruction, NativeCall,
|
||||
NativeCallable, NativeContext, NativeFunction, NativeResult, ObjectChange, ObjectHeader,
|
||||
ObjectPayload, ObjectRef, Opcode, ReadAccess, Record, SourceSignature, Value, VmError,
|
||||
WeakObjectRef,
|
||||
ObjectPayload, ObjectRef, Opcode, ReadAccess, ReadDependency, ReadSet, Record, SourceSignature,
|
||||
TrackedReads, Value, VmError, WeakObjectRef,
|
||||
};
|
||||
pub use vm::Vm;
|
||||
|
||||
@@ -15,3 +15,11 @@
|
||||
核心对象现由 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编译,不运行测试。
|
||||
|
||||
execution.rs补AwaitGate,覆盖真实Waiting、前缀写入不重放、等待操作数保活及拥有式对象结果;本地仅编译不执行。
|
||||
|
||||
execution.rs的named_reads/precise_nested_regions覆盖无关键、缺失遮蔽、内建变化、区域传播、保守遍历及观察不保活;仅编译未本地运行。
|
||||
|
||||
named_reads同时比较同步精确入口与可恢复调用的观察,验证旧同步入口仍返回相同保守对象列表;本地仅编译。
|
||||
|
||||
@@ -1503,3 +1503,335 @@ 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);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AwaitGate {
|
||||
ready: Arc<std::sync::atomic::AtomicBool>,
|
||||
value: Value,
|
||||
}
|
||||
impl ObjectPayload for AwaitGate {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"await-gate"
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Value::Object(reference) = self.value {
|
||||
visit(reference);
|
||||
}
|
||||
}
|
||||
fn poll_await(&self) -> Result<endor_core::AwaitPoll, VmError> {
|
||||
Ok(if self.ready.load(Ordering::Acquire) {
|
||||
endor_core::AwaitPoll::Ready(self.value.clone())
|
||||
} else {
|
||||
endor_core::AwaitPoll::Pending
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn await_keeps_operand_and_owned_object_result_without_replaying_prefix() {
|
||||
use endor_core::CoroutineProgress;
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let value = vm.new_object().unwrap();
|
||||
vm.set_attr(value, "marker", text("kept")).unwrap();
|
||||
let gate = vm
|
||||
.allocate(AwaitGate {
|
||||
ready: ready.clone(),
|
||||
value: Value::Object(value),
|
||||
})
|
||||
.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),
|
||||
simple(Opcode::Await),
|
||||
simple(Opcode::ReturnValue),
|
||||
],
|
||||
vec![text("prefix"), Value::Object(gate)],
|
||||
CodeLayout {
|
||||
names: vec!["step".into()],
|
||||
..CodeLayout::default()
|
||||
},
|
||||
);
|
||||
let function = vm
|
||||
.new_function("awaited", code, globals, vec![], vec![])
|
||||
.unwrap();
|
||||
let coroutine = vm
|
||||
.new_coroutine(function, &[], ExecutionLimits::default())
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(vm.resume_coroutine(coroutine, 64).unwrap(), CoroutineProgress::Waiting { awaitable, .. } if awaitable == gate)
|
||||
);
|
||||
vm.release(value).unwrap();
|
||||
vm.release(gate).unwrap();
|
||||
vm.dict_set(globals, text("step"), text("interleaved"))
|
||||
.unwrap();
|
||||
vm.collect_cycles();
|
||||
ready.store(true, Ordering::Release);
|
||||
let CoroutineProgress::Complete { value: result, .. } =
|
||||
vm.resume_coroutine(coroutine, 64).unwrap()
|
||||
else {
|
||||
panic!("ready await must complete")
|
||||
};
|
||||
assert_eq!(
|
||||
vm.dict_get(globals, &text("step")).unwrap(),
|
||||
Some(text("interleaved"))
|
||||
);
|
||||
for object in [coroutine, function, code, globals] {
|
||||
vm.release(object).unwrap();
|
||||
}
|
||||
let Value::Object(reference) = result else {
|
||||
panic!("owned object result")
|
||||
};
|
||||
assert_eq!(vm.get_attr(reference, "marker").unwrap(), text("kept"));
|
||||
vm.release_value(result).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_reads_ignore_unrelated_globals_but_track_missing_shadow_and_payload_kind() {
|
||||
let mut vm = Vm::new().unwrap();
|
||||
let globals = vm.new_dict().unwrap();
|
||||
let builtins = vm.new_dict().unwrap();
|
||||
vm.dict_set(builtins, text("name"), text("builtin"))
|
||||
.unwrap();
|
||||
vm.dict_set(globals, text("__builtins__"), Value::Object(builtins))
|
||||
.unwrap();
|
||||
let code = make_code(
|
||||
&mut vm,
|
||||
&[op(Opcode::LoadGlobal, 0), simple(Opcode::ReturnValue)],
|
||||
vec![],
|
||||
CodeLayout {
|
||||
names: vec!["name".into()],
|
||||
..CodeLayout::default()
|
||||
},
|
||||
);
|
||||
let function = vm
|
||||
.new_function("read-name", code, globals, vec![], vec![])
|
||||
.unwrap();
|
||||
let endor_core::ExecutionProgress::Complete {
|
||||
value,
|
||||
reads,
|
||||
dependencies,
|
||||
..
|
||||
} = vm
|
||||
.start_read_only_call(function, &[], ExecutionLimits::default(), 64)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("complete")
|
||||
};
|
||||
assert_eq!(value, text("builtin"));
|
||||
assert!(reads.contains(&globals) && reads.contains(&builtins));
|
||||
vm.release_value(value).unwrap();
|
||||
vm.dict_set(globals, text("_"), text("unrelated")).unwrap();
|
||||
let (value, synchronous) = vm
|
||||
.call_read_only_precise_with_limits(function, &[], ExecutionLimits::default())
|
||||
.unwrap();
|
||||
assert_eq!(value, text("builtin"));
|
||||
assert_eq!(synchronous.dependencies, dependencies);
|
||||
assert_eq!(synchronous.objects, reads);
|
||||
vm.release_value(value).unwrap();
|
||||
let (value, conservative) = vm
|
||||
.call_read_only_with_limits(function, &[], ExecutionLimits::default())
|
||||
.unwrap();
|
||||
assert_eq!(conservative, reads);
|
||||
vm.release_value(value).unwrap();
|
||||
assert!(
|
||||
dependencies
|
||||
.iter()
|
||||
.all(|dependency| vm.object_store().read_dependency_valid(dependency))
|
||||
);
|
||||
vm.dict_set(globals, text("name"), text("shadow")).unwrap();
|
||||
assert!(
|
||||
dependencies
|
||||
.iter()
|
||||
.any(|dependency| !vm.object_store().read_dependency_valid(dependency))
|
||||
);
|
||||
vm.dict_delete(globals, &text("name")).unwrap();
|
||||
assert!(
|
||||
dependencies
|
||||
.iter()
|
||||
.all(|dependency| vm.object_store().read_dependency_valid(dependency))
|
||||
);
|
||||
vm.dict_set(builtins, text("name"), text("changed"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
dependencies
|
||||
.iter()
|
||||
.any(|dependency| !vm.object_store().read_dependency_valid(dependency))
|
||||
);
|
||||
for object in [function, code, globals, builtins] {
|
||||
vm.release(object).unwrap();
|
||||
}
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
assert!(
|
||||
dependencies
|
||||
.iter()
|
||||
.any(|dependency| !vm.object_store().read_dependency_valid(dependency))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precise_nested_regions_replay_borrowed_dependencies_without_hiding_full_dict_reads() {
|
||||
let mut vm = endor_core::ObjectStore::new().unwrap();
|
||||
let globals = vm.new_dict().unwrap();
|
||||
vm.dict_set(globals, text("name"), text("value")).unwrap();
|
||||
let scope = vm.begin_read_only();
|
||||
let token = vm.begin_read_tracking().unwrap();
|
||||
vm.dict_get_name(globals, "name").unwrap();
|
||||
let tracked = vm.end_read_tracking_precise(token).unwrap();
|
||||
assert!(
|
||||
tracked
|
||||
.accesses
|
||||
.iter()
|
||||
.any(|access| access.object == globals)
|
||||
);
|
||||
for dependency in &tracked.dependencies {
|
||||
assert!(vm.read_dependency_valid(dependency));
|
||||
}
|
||||
let reads = vm.end_read_only_precise(scope).unwrap();
|
||||
vm.dict_set(globals, text("other"), Value::Nil).unwrap();
|
||||
assert!(
|
||||
reads
|
||||
.dependencies
|
||||
.iter()
|
||||
.all(|dependency| vm.read_dependency_valid(dependency))
|
||||
);
|
||||
let scope = vm.begin_read_only();
|
||||
vm.dict_items(globals).unwrap();
|
||||
let reads = vm.end_read_only_precise(scope).unwrap();
|
||||
vm.dict_set(globals, text("third"), Value::Nil).unwrap();
|
||||
assert!(
|
||||
reads
|
||||
.dependencies
|
||||
.iter()
|
||||
.any(|dependency| !vm.read_dependency_valid(dependency))
|
||||
);
|
||||
vm.release(globals).unwrap();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ module Endor {
|
||||
| Number(string spelling)
|
||||
| String(string value)
|
||||
| Symbol(Name name)
|
||||
| Await(Expr operand)
|
||||
| Unary(UnaryOp operation, Expr operand)
|
||||
| Binary(BinaryOp operation, Expr left, Expr right)
|
||||
| Member(Expr object, Name name)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "urn:endor:ast:sha256:ad2ac52943dd26e08395c0d2698861da98bb89c360241c4712c769de86709fd0",
|
||||
"$id": "urn:endor:ast:sha256:c7c10c6a61158810fa55044f1aa79f3558ac18ca3be59cbf7f2499b5add8df5b",
|
||||
"$ref": "#/$defs/AstDocument",
|
||||
"$defs": {
|
||||
"Span": {
|
||||
@@ -27,7 +27,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "urn:endor:ast:sha256:ad2ac52943dd26e08395c0d2698861da98bb89c360241c4712c769de86709fd0"
|
||||
"const": "urn:endor:ast:sha256:c7c10c6a61158810fa55044f1aa79f3558ac18ca3be59cbf7f2499b5add8df5b"
|
||||
},
|
||||
"root": {
|
||||
"$ref": "#/$defs/AstRoot"
|
||||
@@ -591,6 +591,22 @@
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "Await"
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/$defs/Expr"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"kind",
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Generated by scripts/generate_ast.py from Endor.asdl. Do not edit.
|
||||
|
||||
export const AST_SCHEMA_ID = "urn:endor:ast:sha256:ad2ac52943dd26e08395c0d2698861da98bb89c360241c4712c769de86709fd0" as const;
|
||||
export const AST_SCHEMA_ID = "urn:endor:ast:sha256:c7c10c6a61158810fa55044f1aa79f3558ac18ca3be59cbf7f2499b5add8df5b" as const;
|
||||
export interface Span { start: number; end: number; }
|
||||
export type AstDocument = { schema: typeof AST_SCHEMA_ID; root: AstRoot; };
|
||||
export type AstRoot = { kind: "Module"; data: Program; } | { kind: "Expression"; data: Expr; } | { kind: "Interactive"; data: InteractiveInput; };
|
||||
@@ -20,7 +20,7 @@ export type MemberAssignment = { object: Expr; name: Name; value: Expr; span: Sp
|
||||
export type ReturnStatement = { value?: Expr | null; span: Span; };
|
||||
export type InteractiveInput = { statements: Array<Stmt>; span: Span; };
|
||||
export type Expr = { kind: ExprKind; span: Span; };
|
||||
export type ExprKind = { kind: "Name"; data: string; } | { kind: "Number"; data: string; } | { kind: "String"; data: string; } | { kind: "Symbol"; data: Name; } | { kind: "Unary"; data: { operation: UnaryOp; operand: Expr; }; } | { kind: "Binary"; data: { operation: BinaryOp; left: Expr; right: Expr; }; } | { kind: "Member"; data: { object: Expr; name: Name; }; } | { kind: "Call"; data: { callee: Expr; arguments: Array<Expr>; }; };
|
||||
export type ExprKind = { kind: "Name"; data: string; } | { kind: "Number"; data: string; } | { kind: "String"; data: string; } | { kind: "Symbol"; data: Name; } | { kind: "Await"; data: Expr; } | { kind: "Unary"; data: { operation: UnaryOp; operand: Expr; }; } | { kind: "Binary"; data: { operation: BinaryOp; left: Expr; right: Expr; }; } | { kind: "Member"; data: { object: Expr; name: Name; }; } | { kind: "Call"; data: { callee: Expr; arguments: Array<Expr>; }; };
|
||||
export type UnaryOp = "Negate";
|
||||
export type BinaryOp = "Add" | "Subtract" | "Multiply" | "Divide";
|
||||
export interface Visitor {
|
||||
@@ -192,6 +192,9 @@ break;
|
||||
case "Symbol":
|
||||
walkName(node.data, visitor);
|
||||
break;
|
||||
case "Await":
|
||||
walkExpr(node.data, visitor);
|
||||
break;
|
||||
case "Unary":
|
||||
walkUnaryOp(node.data.operation, visitor);
|
||||
walkExpr(node.data.operand, visitor);
|
||||
|
||||
@@ -17,3 +17,5 @@
|
||||
函数体允许独立方法调用等表达式语句;末尾 return 可省略,已有编译器隐式返回 Nil。
|
||||
|
||||
改节点先编辑 ../Endor.asdl,再用 scripts/generate_ast.py 更新 Rust/编辑器产物,契约见 [AST 模型](../../../docs/runtime/ast.md)。改输入适配时同步 [阅读器契约](../../../docs/runtime/reader.md) 与读取错误检查;改词法从 lexer.peg 进入,并同步 token、诊断和错误检查;改语法从 grammar.peg 进入,并同步 AST、[测试](../tests/README.md)、样例与 [前端契约](../../../docs/runtime/frontend.md)。词法与语法两份 PEG 动作均不做 VM 分配、I/O 或修改外部状态,避免回溯造成副作用。返回 [frontend](../README.md)。
|
||||
|
||||
grammar.peg支持await前缀表达式;AST仍从Endor.asdl生成,不能手改generated.rs/visitor.rs/editor产物。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::Spanned;
|
||||
use crate::Span;
|
||||
pub const AST_SCHEMA_ID: &str =
|
||||
"urn:endor:ast:sha256:ad2ac52943dd26e08395c0d2698861da98bb89c360241c4712c769de86709fd0";
|
||||
"urn:endor:ast:sha256:c7c10c6a61158810fa55044f1aa79f3558ac18ca3be59cbf7f2499b5add8df5b";
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AstDocument {
|
||||
@@ -234,6 +234,7 @@ pub enum ExprKind {
|
||||
Number(String),
|
||||
String(String),
|
||||
Symbol(Name),
|
||||
Await(Box<Expr>),
|
||||
Unary {
|
||||
operation: UnaryOp,
|
||||
operand: Box<Expr>,
|
||||
|
||||
@@ -316,6 +316,9 @@ pub fn walk_expr_kind<V: Visitor + ?Sized>(
|
||||
ExprKind::Symbol(value) => {
|
||||
visitor.visit_name(value)?;
|
||||
}
|
||||
ExprKind::Await(value) => {
|
||||
visitor.visit_expr(value)?;
|
||||
}
|
||||
ExprKind::Unary {
|
||||
operation, operand, ..
|
||||
} => {
|
||||
|
||||
@@ -146,6 +146,9 @@ peg::parser! {
|
||||
left:(@) star() right:@ { binary(left, BinaryOp::Multiply, right) }
|
||||
left:(@) slash() right:@ { binary(left, BinaryOp::Divide, right) }
|
||||
--
|
||||
start:keyword("await") operand:@ {
|
||||
Expr { span: start.through(operand.span), kind: ExprKind::Await(Box::new(operand)) }
|
||||
}
|
||||
start:minus() operand:@ {
|
||||
Expr { span: start.through(operand.span), kind: ExprKind::Unary { operation: UnaryOp::Negate, operand: Box::new(operand) } }
|
||||
}
|
||||
|
||||
@@ -23,3 +23,7 @@
|
||||
对象操作变更同步 [对象模型](../../../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)。
|
||||
|
||||
object.rs提供AwaitPoll与ObjectPayload::poll_await;instruction.rs/code.rs验证Await操作数/栈效果,effects.rs将其视为不能证明只读,error.rs承载等待失败/取消。契约见docs/runtime/bytecode.md。
|
||||
|
||||
heap.rs的ReadDependency/ReadSet/TrackedReads记录借用观察,store.rs暴露精确结束/验证,store_builtins.rs按名读取与字典种类验证保留保守API;types.rs/effects.rs使用按名注解/全局解析。
|
||||
|
||||
@@ -394,7 +394,7 @@ fn verify(
|
||||
| Opcode::StoreDeref
|
||||
| Opcode::PopJumpIfFalse
|
||||
| Opcode::PopJumpIfTrue => (1, 1, 0),
|
||||
Opcode::ToBool | Opcode::UnaryNot | Opcode::LoadAttr => (1, 1, 1),
|
||||
Opcode::ToBool | Opcode::UnaryNot | Opcode::LoadAttr | Opcode::Await => (1, 1, 1),
|
||||
Opcode::CompareOp => (2, 2, 1),
|
||||
Opcode::StoreAttr => (2, 2, 0),
|
||||
Opcode::Copy => (argument, 0, 1),
|
||||
|
||||
@@ -123,6 +123,7 @@ impl ObjectStore {
|
||||
let argument = decoded.instruction.argument as usize;
|
||||
let mut stack = states[index].clone().expect("reachable effect state");
|
||||
match opcode {
|
||||
Opcode::Await => return Ok(None),
|
||||
Opcode::LoadConst => stack.push(Fact::value(code.constants()[argument].clone())),
|
||||
Opcode::LoadFast => stack.push(if argument == 0 {
|
||||
receiver.map(Fact::Object).unwrap_or(Fact::Unknown)
|
||||
@@ -130,12 +131,12 @@ impl ObjectStore {
|
||||
Fact::Unknown
|
||||
}),
|
||||
Opcode::LoadGlobal => {
|
||||
let key = Value::Text(code.layout().names[argument].clone());
|
||||
let mut value = self.dict_get(function.globals(), &key)?;
|
||||
let name = &code.layout().names[argument];
|
||||
let mut value = self.dict_get_name(function.globals(), name)?;
|
||||
if value.is_none()
|
||||
&& let Some(builtins) = function.builtins()
|
||||
{
|
||||
value = self.dict_get(builtins, &key)?;
|
||||
value = self.dict_get_name(builtins, name)?;
|
||||
}
|
||||
stack.push(value.map(Fact::value).unwrap_or(Fact::Unknown));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ use std::fmt;
|
||||
/// retained for embedders; defining it here avoids a dependency on the VM.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum VmError {
|
||||
AwaitFailed(String),
|
||||
AwaitCancelled,
|
||||
ForeignHandle,
|
||||
InvalidHandle,
|
||||
IdentityExhausted,
|
||||
@@ -49,6 +51,8 @@ pub enum VmError {
|
||||
impl fmt::Display for VmError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::AwaitFailed(message) => write!(f, "await failed: {message}"),
|
||||
Self::AwaitCancelled => f.write_str("await cancelled"),
|
||||
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"),
|
||||
|
||||
+143
-20
@@ -41,6 +41,8 @@ struct ReadOnly {
|
||||
protected: BTreeSet<ObjectRef>,
|
||||
reads: Mutex<BTreeSet<ObjectRef>>,
|
||||
regions: Mutex<Vec<BTreeMap<ObjectRef, bool>>>,
|
||||
dependencies: Mutex<BTreeMap<ReadKey, ReadDependency>>,
|
||||
dependency_regions: Mutex<Vec<BTreeMap<ReadKey, ReadDependency>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -63,6 +65,49 @@ pub struct ReadAccess {
|
||||
pub content_read: bool,
|
||||
}
|
||||
|
||||
/// Borrowed observations; Object handles never retain the observed graph.
|
||||
/// Named values are immutable comparison snapshots, not managed owning edges.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ReadDependency {
|
||||
Object {
|
||||
object: ObjectRef,
|
||||
version: u64,
|
||||
},
|
||||
DictionaryKind {
|
||||
object: ObjectRef,
|
||||
},
|
||||
Name {
|
||||
object: ObjectRef,
|
||||
name: String,
|
||||
value: Option<crate::Value>,
|
||||
},
|
||||
}
|
||||
impl ReadDependency {
|
||||
pub fn object(&self) -> ObjectRef {
|
||||
match self {
|
||||
Self::Object { object, .. }
|
||||
| Self::DictionaryKind { object }
|
||||
| Self::Name { object, .. } => *object,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum ReadKey {
|
||||
Object(ObjectRef),
|
||||
DictionaryKind(ObjectRef),
|
||||
Name(ObjectRef, String),
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct TrackedReads {
|
||||
pub accesses: Vec<ReadAccess>,
|
||||
pub dependencies: Vec<ReadDependency>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ReadSet {
|
||||
pub objects: Vec<ObjectRef>,
|
||||
pub dependencies: Vec<ReadDependency>,
|
||||
}
|
||||
|
||||
struct ValidationScope<'a> {
|
||||
heap: &'a Heap,
|
||||
thread: ThreadId,
|
||||
@@ -128,23 +173,34 @@ impl Heap {
|
||||
protected,
|
||||
reads: Mutex::new(BTreeSet::new()),
|
||||
regions: Mutex::new(Vec::new()),
|
||||
dependencies: Mutex::new(BTreeMap::new()),
|
||||
dependency_regions: Mutex::new(Vec::new()),
|
||||
});
|
||||
self.read_only.len()
|
||||
}
|
||||
|
||||
pub(crate) fn end_read_only(&mut self, scope: usize) -> Result<Vec<ObjectRef>, VmError> {
|
||||
Ok(self.end_read_only_precise(scope)?.objects)
|
||||
}
|
||||
pub(crate) fn end_read_only_precise(&mut self, scope: usize) -> Result<ReadSet, VmError> {
|
||||
if scope == 0 || scope != self.read_only.len() {
|
||||
return Err(VmError::InvalidArgument("read-only scope nesting mismatch"));
|
||||
}
|
||||
Ok(self
|
||||
.read_only
|
||||
.pop()
|
||||
.unwrap()
|
||||
.reads
|
||||
.into_inner()
|
||||
.expect("read tracker poisoned")
|
||||
.into_iter()
|
||||
.collect())
|
||||
let scope = self.read_only.pop().unwrap();
|
||||
Ok(ReadSet {
|
||||
objects: scope
|
||||
.reads
|
||||
.into_inner()
|
||||
.expect("read tracker poisoned")
|
||||
.into_iter()
|
||||
.collect(),
|
||||
dependencies: scope
|
||||
.dependencies
|
||||
.into_inner()
|
||||
.expect("read tracker poisoned")
|
||||
.into_values()
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn begin_read_tracking(&self) -> Result<usize, VmError> {
|
||||
@@ -153,6 +209,11 @@ impl Heap {
|
||||
))?;
|
||||
let mut regions = scope.regions.lock().expect("read tracker poisoned");
|
||||
regions.push(BTreeMap::new());
|
||||
scope
|
||||
.dependency_regions
|
||||
.lock()
|
||||
.expect("read tracker poisoned")
|
||||
.push(BTreeMap::new());
|
||||
Ok(regions.len())
|
||||
}
|
||||
|
||||
@@ -168,22 +229,32 @@ impl Heap {
|
||||
&self,
|
||||
token: usize,
|
||||
) -> Result<Vec<ReadAccess>, VmError> {
|
||||
Ok(self.end_read_tracking_precise(token)?.accesses)
|
||||
}
|
||||
pub(crate) fn end_read_tracking_precise(&self, token: usize) -> Result<TrackedReads, VmError> {
|
||||
let scope = self.read_only.last().ok_or(VmError::InvalidArgument(
|
||||
"read tracking requires a read-only scope",
|
||||
))?;
|
||||
let mut regions = scope.regions.lock().expect("read tracker poisoned");
|
||||
if token == 0 || token != regions.len() {
|
||||
let mut precise = scope
|
||||
.dependency_regions
|
||||
.lock()
|
||||
.expect("read tracker poisoned");
|
||||
if token == 0 || token != regions.len() || token != precise.len() {
|
||||
return Err(VmError::InvalidArgument("read tracking nesting mismatch"));
|
||||
}
|
||||
Ok(regions
|
||||
.pop()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(object, content_read)| ReadAccess {
|
||||
object,
|
||||
content_read,
|
||||
})
|
||||
.collect())
|
||||
Ok(TrackedReads {
|
||||
accesses: regions
|
||||
.pop()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(object, content_read)| ReadAccess {
|
||||
object,
|
||||
content_read,
|
||||
})
|
||||
.collect(),
|
||||
dependencies: precise.pop().unwrap().into_values().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_read_only(&self) -> bool {
|
||||
@@ -209,7 +280,45 @@ impl Heap {
|
||||
compute()
|
||||
}
|
||||
|
||||
pub(crate) fn record_read(&self, reference: ObjectRef) {
|
||||
pub(crate) fn record_read(&self, reference: ObjectRef, version: u64) {
|
||||
if self.read_only.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.record_observation(reference, ReadKey::Object(reference), || {
|
||||
ReadDependency::Object {
|
||||
object: reference,
|
||||
version,
|
||||
}
|
||||
});
|
||||
}
|
||||
pub(crate) fn record_dictionary_kind(&self, reference: ObjectRef) {
|
||||
self.record_observation(reference, ReadKey::DictionaryKind(reference), || {
|
||||
ReadDependency::DictionaryKind { object: reference }
|
||||
});
|
||||
}
|
||||
pub(crate) fn record_name(
|
||||
&self,
|
||||
reference: ObjectRef,
|
||||
name: &str,
|
||||
value: &Option<crate::Value>,
|
||||
) {
|
||||
if self.read_only.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.record_observation(reference, ReadKey::Name(reference, name.into()), || {
|
||||
ReadDependency::Name {
|
||||
object: reference,
|
||||
name: name.into(),
|
||||
value: value.clone(),
|
||||
}
|
||||
});
|
||||
}
|
||||
fn record_observation(
|
||||
&self,
|
||||
reference: ObjectRef,
|
||||
key: ReadKey,
|
||||
build: impl Fn() -> ReadDependency,
|
||||
) {
|
||||
if self.read_only.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -220,6 +329,20 @@ impl Heap {
|
||||
.contains_key(&std::thread::current().id());
|
||||
for scope in &self.read_only {
|
||||
if scope.protected.contains(&reference) {
|
||||
scope
|
||||
.dependencies
|
||||
.lock()
|
||||
.expect("read tracker poisoned")
|
||||
.entry(key.clone())
|
||||
.or_insert_with(&build);
|
||||
for region in scope
|
||||
.dependency_regions
|
||||
.lock()
|
||||
.expect("read tracker poisoned")
|
||||
.iter_mut()
|
||||
{
|
||||
region.entry(key.clone()).or_insert_with(&build);
|
||||
}
|
||||
scope
|
||||
.reads
|
||||
.lock()
|
||||
|
||||
@@ -35,6 +35,7 @@ pub enum Opcode {
|
||||
BuildMap = 27,
|
||||
MakeFunction = 28,
|
||||
BuildClass = 29,
|
||||
Await = 30,
|
||||
ExtendedArg = 255,
|
||||
}
|
||||
|
||||
@@ -71,6 +72,7 @@ impl Opcode {
|
||||
27 => Self::BuildMap,
|
||||
28 => Self::MakeFunction,
|
||||
29 => Self::BuildClass,
|
||||
30 => Self::Await,
|
||||
255 => Self::ExtendedArg,
|
||||
_ => return None,
|
||||
})
|
||||
@@ -85,6 +87,7 @@ impl Opcode {
|
||||
| Self::ReturnValue
|
||||
| Self::ToBool
|
||||
| Self::UnaryNot
|
||||
| Self::Await
|
||||
| Self::BuildClass
|
||||
)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ pub use builtins::{
|
||||
pub use changes::{ChangeBatch, ChangeKey, ObjectChange};
|
||||
pub use code::{CodeLayout, EndorCode, EndorCodeObject, SourceSignature};
|
||||
pub use error::VmError;
|
||||
pub use heap::{ObjectRef, ReadAccess, WeakObjectRef};
|
||||
pub use heap::{ObjectRef, ReadAccess, ReadDependency, ReadSet, TrackedReads, WeakObjectRef};
|
||||
pub use instruction::{DecodedInstruction, Instruction, Opcode};
|
||||
pub use native::{
|
||||
CallArity, CallEffect, CallSignature, CallType, ContextNativeFunction, NativeCallable,
|
||||
@@ -43,8 +43,8 @@ pub use number::{
|
||||
EndorDecimal, EndorInteger, EndorNumber, EndorNumberObject, EndorRational, EndorReal,
|
||||
};
|
||||
pub use object::{
|
||||
CompareOp, EndorNativeCall, EndorNativeFunctionObject, EndorObject, NativeCall, NativeFunction,
|
||||
ObjectHeader, ObjectPayload, Record, Value,
|
||||
AwaitPoll, CompareOp, EndorNativeCall, EndorNativeFunctionObject, EndorObject, NativeCall,
|
||||
NativeFunction, ObjectHeader, ObjectPayload, Record, Value,
|
||||
};
|
||||
pub use store::ObjectStore;
|
||||
pub use types::{
|
||||
|
||||
@@ -42,6 +42,14 @@ impl CompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-blocking awaitable observation. Ready object values are borrowed from
|
||||
/// the managed graph and must be retained by the consumer before dropping it.
|
||||
#[derive(Debug)]
|
||||
pub enum AwaitPoll {
|
||||
Pending,
|
||||
Ready(Value),
|
||||
}
|
||||
|
||||
/// Rust-side operation interface, not a language type or metaclass.
|
||||
///
|
||||
/// Implementations must report every payload-owned object reference in trace(),
|
||||
@@ -51,6 +59,10 @@ impl CompareOp {
|
||||
/// 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 poll_await(&self) -> Result<AwaitPoll, VmError> {
|
||||
Err(VmError::UnsupportedOperation("await"))
|
||||
}
|
||||
|
||||
/// Explicit function category; callable Type objects are not functions.
|
||||
fn is_function(&self) -> bool {
|
||||
false
|
||||
|
||||
@@ -43,6 +43,29 @@ impl ObjectStore {
|
||||
pub fn end_read_only(&mut self, scope: usize) -> Result<Vec<ObjectRef>, VmError> {
|
||||
self.heap.end_read_only(scope)
|
||||
}
|
||||
pub fn end_read_only_precise(&mut self, scope: usize) -> Result<crate::ReadSet, VmError> {
|
||||
self.heap.end_read_only_precise(scope)
|
||||
}
|
||||
pub fn read_dependency_valid(&self, dependency: &crate::ReadDependency) -> bool {
|
||||
match dependency {
|
||||
crate::ReadDependency::Object { object, version } => {
|
||||
self.change_version(*object).ok() == Some(*version)
|
||||
}
|
||||
crate::ReadDependency::DictionaryKind { object } => {
|
||||
self.dictionary_kind(*object).is_ok()
|
||||
}
|
||||
crate::ReadDependency::Name {
|
||||
object,
|
||||
name,
|
||||
value,
|
||||
} => self
|
||||
.dict_get_name(*object, name)
|
||||
.is_ok_and(|current| current == *value),
|
||||
}
|
||||
}
|
||||
pub fn end_read_tracking_precise(&self, token: usize) -> Result<crate::TrackedReads, VmError> {
|
||||
self.heap.end_read_tracking_precise(token)
|
||||
}
|
||||
/// Track one subcall inside the active read-only scope. Regions nest in
|
||||
/// LIFO order and do not clear the enclosing call's read dependencies.
|
||||
/// Handles returned by end_read_tracking are borrowed, never owning roots.
|
||||
@@ -214,8 +237,10 @@ impl ObjectStore {
|
||||
}
|
||||
|
||||
pub fn object(&self, reference: ObjectRef) -> Result<&EndorObject, VmError> {
|
||||
self.heap.record_read(reference);
|
||||
self.heap.get(reference)
|
||||
let object = self.heap.get(reference)?;
|
||||
self.heap
|
||||
.record_read(reference, object.header().change_version());
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
/// Borrowed storage path: depend on Contents for intermediate objects and
|
||||
|
||||
@@ -20,9 +20,9 @@ impl ObjectStore {
|
||||
"function defaults or closure do not match code",
|
||||
));
|
||||
}
|
||||
self.payload::<EndorDictObject>(function.globals(), "dict")?;
|
||||
self.dictionary_kind(function.globals())?;
|
||||
if let Some(builtins) = function.builtins() {
|
||||
self.payload::<EndorDictObject>(builtins, "dict")?;
|
||||
self.dictionary_kind(builtins)?;
|
||||
}
|
||||
for cell in function.closure() {
|
||||
self.payload::<EndorCellObject>(*cell, "cell")?;
|
||||
@@ -67,10 +67,10 @@ impl ObjectStore {
|
||||
defaults: Vec<Value>,
|
||||
closure: Vec<ObjectRef>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
self.payload::<EndorDictObject>(globals, "dict")?;
|
||||
let builtins = match self.dict_get(globals, &Value::Text("__builtins__".into()))? {
|
||||
self.dictionary_kind(globals)?;
|
||||
let builtins = match self.dict_get_name(globals, "__builtins__")? {
|
||||
Some(Value::Object(reference)) => {
|
||||
self.payload::<EndorDictObject>(reference, "dict")?;
|
||||
self.dictionary_kind(reference)?;
|
||||
Some(reference)
|
||||
}
|
||||
None => None,
|
||||
@@ -101,6 +101,35 @@ impl ObjectStore {
|
||||
.entries())
|
||||
}
|
||||
|
||||
pub(crate) fn dictionary_kind(
|
||||
&self,
|
||||
dictionary: ObjectRef,
|
||||
) -> Result<&EndorDictObject, VmError> {
|
||||
let dict = self
|
||||
.heap
|
||||
.get(dictionary)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.downcast_ref::<EndorDictObject>()
|
||||
.ok_or(VmError::ObjectKindMismatch("dict"))?;
|
||||
self.heap.record_dictionary_kind(dictionary);
|
||||
Ok(dict)
|
||||
}
|
||||
/// Name lookup records both present and missing text keys. General dict_get
|
||||
/// and iteration continue to observe the entire dictionary contents.
|
||||
pub fn dict_get_name(
|
||||
&self,
|
||||
dictionary: ObjectRef,
|
||||
name: &str,
|
||||
) -> Result<Option<Value>, VmError> {
|
||||
let dict = self.dictionary_kind(dictionary)?;
|
||||
let value = self
|
||||
.dict_position(dict, &Value::Text(name.into()))?
|
||||
.map(|index| dict.entries[index].1.clone());
|
||||
self.heap.record_name(dictionary, name, &value);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn dict_get(&self, dictionary: ObjectRef, key: &Value) -> Result<Option<Value>, VmError> {
|
||||
let dict = self.payload::<EndorDictObject>(dictionary, "dict")?;
|
||||
self.key_hash(key)?;
|
||||
@@ -167,19 +196,7 @@ impl ObjectStore {
|
||||
}
|
||||
|
||||
fn key_equal(&self, left: &Value, right: &Value) -> Result<bool, VmError> {
|
||||
let text = |value: &Value| -> Result<Option<String>, VmError> {
|
||||
Ok(match value {
|
||||
Value::Text(text) => Some(text.clone()),
|
||||
Value::Object(reference) => self
|
||||
.object(*reference)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.downcast_ref::<EndorStringObject>()
|
||||
.map(|string| string.as_str().to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
if let (Some(left), Some(right)) = (text(left)?, text(right)?) {
|
||||
if let (Some(left), Some(right)) = (self.key_text(left)?, self.key_text(right)?) {
|
||||
return Ok(left == right);
|
||||
}
|
||||
match (left, right) {
|
||||
@@ -190,6 +207,19 @@ impl ObjectStore {
|
||||
}
|
||||
}
|
||||
|
||||
fn key_text<'a>(&'a self, value: &'a Value) -> Result<Option<&'a str>, VmError> {
|
||||
Ok(match value {
|
||||
Value::Text(text) => Some(text.as_str()),
|
||||
Value::Object(reference) => self
|
||||
.object(*reference)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.downcast_ref::<EndorStringObject>()
|
||||
.map(EndorStringObject::as_str),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_cell(&mut self, value: Option<Value>) -> Result<ObjectRef, VmError> {
|
||||
self.allocate(EndorCellObject::new(value))
|
||||
}
|
||||
|
||||
@@ -1266,9 +1266,9 @@ impl ObjectStore {
|
||||
return Ok(primitive);
|
||||
}
|
||||
let value = self
|
||||
.dict_get(data.globals(), &Value::Text(name.into()))?
|
||||
.dict_get_name(data.globals(), name)?
|
||||
.or(match data.builtins() {
|
||||
Some(builtins) => self.dict_get(builtins, &Value::Text(name.into()))?,
|
||||
Some(builtins) => self.dict_get_name(builtins, name)?,
|
||||
None => None,
|
||||
});
|
||||
if let Some(Value::Object(definition)) = value {
|
||||
|
||||
@@ -5,6 +5,38 @@ use objects::{
|
||||
Value, VmError,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn dictionary_text_and_managed_string_keys_share_entries_and_keep_first_identity() {
|
||||
let mut store = ObjectStore::new().unwrap();
|
||||
let dict = store.new_dict().unwrap();
|
||||
for text in ["", "camera", "中文🙂"] {
|
||||
let key = store.new_string(text).unwrap();
|
||||
store
|
||||
.dict_set(dict, Value::Object(key), Value::Bool(false))
|
||||
.unwrap();
|
||||
store
|
||||
.dict_set(dict, Value::Text(text.into()), Value::Bool(true))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
store.dict_get_name(dict, text).unwrap(),
|
||||
Some(Value::Bool(true))
|
||||
);
|
||||
assert_eq!(
|
||||
store.dict_items(dict).unwrap().last().unwrap().0,
|
||||
Value::Object(key)
|
||||
);
|
||||
assert_eq!(
|
||||
store.dict_get(dict, &Value::Object(key)).unwrap(),
|
||||
Some(Value::Bool(true))
|
||||
);
|
||||
store.release(key).unwrap();
|
||||
assert!(store.dict_delete(dict, &Value::Text(text.into())).unwrap());
|
||||
assert_eq!(store.dict_get_name(dict, text).unwrap(), None);
|
||||
}
|
||||
store.release(dict).unwrap();
|
||||
assert_eq!(store.object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_storage_preserves_identity_validates_edges_and_collects_cycles() {
|
||||
let mut store = ObjectStore::new().unwrap();
|
||||
|
||||
+7
-1
@@ -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) | 独立宿主仓库 |
|
||||
@@ -22,3 +22,9 @@
|
||||
| 后续开发交接 | [交接](contributing/handoff.md) | 实时源码和 Git 状态 |
|
||||
|
||||
目录入口:[architecture](architecture/README.md)、[runtime](runtime/README.md)、[operations](operations/README.md)、[contributing](contributing/README.md)。宿主部署、文件信息和数据库正文已移至 Hestia,命令行与实际输出报告已移至 Lyra;本仓库不保留重复正文。研究资料仍在忽略的 work/research,不提交。
|
||||
|
||||
Await入口:语法见runtime/frontend.md,名称与发码见runtime/compiler.md,等待/恢复与所有权见runtime/bytecode.md,宿主协议见runtime/objects.md。
|
||||
|
||||
按名全局依赖、缺失键遮蔽与兼容保守读取见runtime/native-calls.md的精确只读观察章节。
|
||||
|
||||
同步与可恢复只读调用的精确ReadSet及旧对象列表兼容语义统一见[runtime/native-calls.md](runtime/native-calls.md)。
|
||||
|
||||
@@ -186,3 +186,21 @@ 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不进入内核。
|
||||
|
||||
|
||||
## Await 等待边界
|
||||
|
||||
`Await`(opcode 30,无参数)把栈顶 awaitable 换成结果,验证栈效果为1入1出。`ObjectPayload::poll_await()` 是非阻塞、无副作用的宿主协议,默认不支持;返回 Pending 或 Ready(借用 Value),也可返回 AwaitFailed(String)/AwaitCancelled。引擎验证 Ready 句柄并先retain结果,再释放原操作数;不可信宿主仍需遵守借用与非阻塞契约。Await 不被保守效果分析证明为只读,运行时也拒绝只读阶段。
|
||||
|
||||
在独立coroutine中,Pending保持已求值的栈顶、当前帧和返回契约,返回CoroutineProgress::Waiting { awaitable, instructions };awaitable是由暂停帧保活的借用身份。宿主等待条件满足后再次resume,仅重查同一个Await,不重放操作数表达式、前缀写入或IO请求。每次实际执行Await计入同一硬预算;宿主不应对未就绪对象反复resume来轮询。完成结果与错误沿普通执行/清理路径传播。非coroutine调用允许立即Ready的await,Pending则明确报错,不阻塞线程。调度、取消传播和循环等待检测属于宿主;本引擎不依赖Tessera Task。
|
||||
|
||||
LoadGlobal按文本名字分别观察函数globals及缺失时的captured builtins,不因无关全局写入而失效。可恢复只读Complete新增dependencies,reads保留兼容保守列表;精确验证/所有权见native-calls.md。
|
||||
|
||||
@@ -58,3 +58,6 @@ lyra run [--entry name] <file|-> 编译模块、执行初始化、调用无参
|
||||
|
||||
|
||||
类方法使用显式首参数 self;编译器检查本类重复字段/方法和缺少 self。方法代码仍是共享的普通代码对象,参数/返回注解和声明类名随代码保存,由宿主开关选择运行时检查。BuildClass 在 VM 中检查继承字段冲突和原生分配边界;构造失败不发布类型到目标全局名。默认基类 Object 须由宿主通过 CompileOptions 声明并在运行全局中提供,编译器不自行引导类型。普通类构造和继承分派见[类型机制](types.md)。
|
||||
|
||||
|
||||
Await表达式参与普通名称/初始化分析,先编译operand,再发出无参数Await opcode。该链路保存实际结果的栈位置,不通过回放函数实现等待;没有新增async声明或静态awaitable类型检查。语法与运行上下文见frontend及bytecode主题。
|
||||
|
||||
@@ -82,3 +82,6 @@ use、namespace、trait、agent、完整类型语法、条件/循环、比较
|
||||
|
||||
|
||||
源码类实现子集采用 `class Name: Base { field: TypeName function method(self: Name): ResultType { ... } }`;基类可省略,执行环境须提供 Object。成员函数沿用既有 function 语法,接收者 self 为显式首参数。普通类字段按基类字段、再本类字段的顺序接收位置构造实参。这里记录实现范围,不确认语言文档中的全部候选构造语法;详细限制见[名义类型](types.md)。
|
||||
|
||||
|
||||
`await expression` 解析为 ExprKind::Await(operand),优先级与前缀负号同级,成员/调用绑定更紧;例如await task.result()等待该调用的返回对象,(await task).field先等待task。await按表达式前缀位置识别,不引入async函数声明。执行是否允许等待由调用上下文决定,见字节码VM的Await章节。
|
||||
|
||||
@@ -113,3 +113,8 @@ Delegated 在替换兼容中视为未知整体效果,与源码未知效果一
|
||||
|
||||
|
||||
ContextNativeFunction::implementation<T: NativeCallable>() 只借用当前具体宿主实现,不执行或复制载荷,也不改变捕获/签名的托管边。NativeCallable 继承Any(原有static要求保持);宿主可据自己的实现类型/操作识别原生快速路径,不能只凭函数句柄或当前可变类型方法表认定原生身份。替换载荷后查询跟随新实现,旧类型查询返回None;宿主缓存仍须订阅函数对象版本变化。此接口不暴露可变借用,不替代原生类型/数量/效果检查。
|
||||
|
||||
|
||||
精确只读观察:end_read_only_precise返回ReadSet,兼容objects列表并提供ReadDependency;end_read_tracking_precise返回区域的ReadAccess与相同观察。Object依赖验证对象版本;DictionaryKind只验证存活/字典载荷;Name验证文本键的存在与值身份/表示。缺失名字也被记录,因此后续全局遮蔽内建名会失效;相同值删除/重建后可恢复有效,这是值观察而非“发生过写入”的通知。dict_get_name用于全局/注解/__builtins__名字查询,普通dict_get、dict_items和其他内容读取仍保守依赖整个对象。read_dependency_valid在只读区域内检查时会重记相同观察,使缓存命中仍向外传播依赖。所有对象句柄(包括Name中的Value::Object)均借用,不增加GC根;立即字符串/数字保留比较快照,值不写回业务对象。现有end_read_only/end_read_tracking/details仍返回保守对象列表,不自动替调用方放宽缓存。类型验证字典通过DictionaryKind观察,不把只验证载荷种类误当读取所有条目。
|
||||
|
||||
同步宿主可调用Vm::call_read_only_precise_with_limits(function, arguments, limits),返回拥有式Value及借用式ReadSet(objects与dependencies)。它与可恢复只读调用提供同样的名字观察,不创建新的调度器;单次调用仍同步执行并受正常硬预算约束,不能等待Pending await。旧call_read_only_with_limits委托同一执行逻辑,只返回ReadSet.objects,兼容原有保守宿主。成功或执行错误均先关闭只读作用域;不提供panic捕获。
|
||||
|
||||
@@ -105,3 +105,6 @@ compare 的反向规则是 Lt 对应 Gt、Le 对应 Ge,Eq/Ne 保持不变。
|
||||
尚未实现:Python type 兼容、trait 和描述符、任意 VM 重入调用上下文、自动/分代/增量 GC、语言终结器/复活、完整资源限额和 VM 快照;独立 frontend 已提供阅读器、lexer/parser 与 AST,基础源码执行由独立 [Compiler](compiler.md) 接入,见 [源码前端](frontend.md);执行器已有帧数和指令数限额。数据库仅为未来特殊类提供按需连接,普通对象或宿主基础信息不自动持久化,详见 [数据库特殊类](https://gitea.entroia.com/Zayden-Jung/endorphin-hestia-server/src/branch/main/docs/runtime/database-objects.md)。
|
||||
|
||||
验证范围与执行约定见 [验证](../operations/validation.md)。
|
||||
|
||||
|
||||
ObjectPayload::poll_await是通用非阻塞等待观察协议,默认UnsupportedOperation。AwaitPoll::Ready的对象结果是借用,调用方须在放弃awaitable前retain;协议不允许内部阻塞/IO/修改对象。完整指令和恢复契约见bytecode.md。
|
||||
|
||||
Reference in New Issue
Block a user