Check source function annotations and unify managed function identity

This commit is contained in:
2026-10-21 22:38:22 +08:00
parent eb60212428
commit 6346041f77
27 changed files with 568 additions and 40 deletions
+3 -3
View File
@@ -5,9 +5,9 @@
| 文件 | 职责 |
| --- | --- |
| [lib.rs](lib.rs) | VM 类型导出、objects 类型兼容重导出、宿主调用与字节码 rustdoc 示例 |
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作和宿主 new_class 和显式Trait注册/关系查询显式委托给 objects |
| [frame.rs](frame.rs) | EndorFrame、栈条目、执行位置元数据、ExecutionLimits |
| [eval.rs](eval.rs) | execute/call、只读调用与依赖结果、参数绑定、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
| [vm.rs](vm.rs) | Vm 拥有 ObjectStore 与错误位置记录;对象操作和宿主 new_class 和显式Trait注册/关系查询显式委托给 objects;源码检查开关与函数类型配置 |
| [frame.rs](frame.rs) | EndorFrame、栈条目、返回类型执行根、执行位置元数据、ExecutionLimits |
| [eval.rs](eval.rs) | execute/call、只读调用与依赖结果、参数绑定、可选注解检查、帧切换、取指分派、MakeFunction、结果根转移与失败清理 |
## 常见修改入口
+56
View File
@@ -135,6 +135,10 @@ impl Vm {
}
self.release(frame.function)
.expect("frame owns its function root");
if let Some(reference) = frame.return_type.and_then(|kind| kind.reference()) {
self.release(reference)
.expect("frame owns its return type root");
}
}
fn prepare_frame(
@@ -161,8 +165,45 @@ impl Vm {
for value in arguments {
self.validate_value(value)?;
}
let mut return_type = None;
if self.source_type_checks
&& let Some(signature) = executable.source_signature()
{
let receiver = arguments.first().and_then(|value| match value {
Value::Object(object) => Some(*object),
_ => None,
});
for (index, expected_name) in signature.parameters.iter().enumerate() {
let value = arguments
.get(index)
.unwrap_or_else(|| &data.defaults()[index - required]);
let expected = self
.objects
.annotation_type(function, expected_name, receiver)?;
if !self.objects.matches_annotation(value, expected)? {
return Err(VmError::TypeMismatch {
function: data.name().into(),
position: format!("parameter {}", executable.parameters()[index]),
expected: expected_name.clone(),
actual: self.objects.value_type_name(value)?,
});
}
}
return_type = Some(self.objects.annotation_type(
function,
&signature.return_type,
receiver,
)?);
}
self.retain(function)?;
if let Some(reference) = return_type.and_then(|kind| kind.reference())
&& let Err(error) = self.retain(reference)
{
self.release(function)?;
return Err(error);
}
let mut frame = EndorFrame {
return_type,
function,
previous: None,
code: data.code(),
@@ -614,6 +655,21 @@ impl Vm {
}
Opcode::ReturnValue => {
let result = Self::top_value(frame)?;
if let Some(expected) = frame.return_type
&& !self.objects.matches_annotation(&result, expected)?
{
return Err(VmError::TypeMismatch {
function: frame.name.clone(),
position: "return".into(),
expected: frame
.executable
.source_signature()
.expect("checked source signature")
.return_type
.clone(),
actual: self.objects.value_type_name(&result)?,
});
}
frame.stack.pop();
self.clear_frame(frames.pop().unwrap());
if let Some(caller) = frames.last_mut() {
+1
View File
@@ -15,6 +15,7 @@ pub(crate) enum StackEntry {
#[derive(Debug)]
pub struct EndorFrame {
pub(crate) function: ObjectRef,
pub(crate) return_type: Option<crate::AnnotationType>,
/// Index of the caller in the execution's frame vector, never a pointer.
pub(crate) previous: Option<usize>,
pub(crate) code: ObjectRef,
+6 -5
View File
@@ -45,16 +45,17 @@ mod vm;
pub use frame::{EndorFrame, ExecutionLimits, ExecutionLocation};
// Preserve existing embedding imports; objects owns these definitions.
pub use objects::ObjectStore;
pub use objects::{
AnnotationType, ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement, RootTypes,
TypeConstructor,
};
pub use objects::{
ChangeBatch, ChangeKey, CodeLayout, CompareOp, ContextNativeFunction, DecodedInstruction,
EndorBaseExceptionObject, EndorCellObject, EndorCode, EndorCodeObject, EndorDecimal,
EndorDictObject, EndorFunctionObject, EndorInteger, EndorNativeCall, EndorNativeFunctionObject,
EndorNumber, EndorNumberObject, EndorObject, EndorRational, EndorReal, EndorStringObject,
EndorTracebackEntry, Instruction, NativeCall, NativeCallable, NativeContext, NativeFunction,
NativeResult, ObjectChange, ObjectHeader, ObjectPayload, ObjectRef, Opcode, Record, Value,
VmError, WeakObjectRef,
};
pub use objects::{
ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement, RootTypes, TypeConstructor,
NativeResult, ObjectChange, ObjectHeader, ObjectPayload, ObjectRef, Opcode, Record,
SourceSignature, Value, VmError, WeakObjectRef,
};
pub use vm::Vm;
+15
View File
@@ -11,9 +11,23 @@ use crate::{
pub struct Vm {
pub(crate) objects: ObjectStore,
pub(crate) last_traceback: Vec<ExecutionLocation>,
pub(crate) source_type_checks: bool,
}
impl Vm {
pub fn set_source_type_checks(&mut self, enabled: bool) -> Result<(), VmError> {
if self.objects.is_read_only() {
return Err(VmError::UnsupportedOperation(
"configure source type checks during read-only call",
));
}
self.source_type_checks = enabled;
Ok(())
}
pub fn set_function_type(&mut self, definition: ObjectRef) -> Result<(), VmError> {
self.objects.set_function_type(definition)
}
pub fn new_trait(
&mut self,
name: impl Into<String>,
@@ -134,6 +148,7 @@ impl Vm {
Ok(Self {
objects: ObjectStore::new()?,
last_traceback: Vec::new(),
source_type_checks: false,
})
}
+1 -1
View File
@@ -7,7 +7,7 @@
| [runtime.rs](runtime.rs) | 空堆启动、默认操作、引用/借用、属性原子性、稳定地址、长链/循环、原生回调、VM 销毁 |
| [builtins.rs](builtins.rs) | 无损 Number、Unicode 字符串、Dict 顺序与键、Cell、函数环境/共享代码、异常数据 |
| [execution.rs](execution.rs) | wordcode 与校验、控制流、参数/默认值、嵌套帧、字节码函数创建/默认值/环境捕获、闭包、返回值存活、失败清理、限额 |
| [types.rs](types.rs) | 名义身份、继承与实例关系、类型边保活/循环回收、只读类型元数据与外来句柄、显式Trait身份/继承/参数约束及后代更新原子性;仅远端执行 |
| [types.rs](types.rs) | 名义身份、继承与实例关系、类型边保活/循环回收、只读类型元数据与外来句柄、显式Trait身份/继承/参数约束及后代更新原子性;统一函数分类与返回类型错误根清理;仅远端执行 |
| [native_context.rs](native_context.rs) | 原生作用域根、分配失败清理、委托、只读结果分配/写入拒绝/依赖与失败恢复、弱引用过期及有界变更;仅远端执行 |
核心对象现由 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)。
+131
View File
@@ -198,3 +198,134 @@ fn late_trait_registration_and_ancestor_updates_validate_existing_descendants()
Err(VmError::ForeignHandle)
);
}
#[test]
fn configured_function_identity_covers_source_native_and_bound_methods() {
use endor_core::{NativeFunction, SourceSignature};
let mut vm = Vm::new().unwrap();
let roots = vm.bootstrap_types().unwrap();
let function_type = vm
.new_type("Function", roots.object, TypeConstructor::Abstract)
.unwrap();
vm.set_function_type(function_type).unwrap();
let source = contract_method(&mut vm, 1);
let native = vm
.allocate(NativeFunction::new("native", |_| Ok(Value::Nil)))
.unwrap();
assert!(vm.is_instance(source, function_type).unwrap());
assert!(vm.is_instance(native, function_type).unwrap());
vm.attach_type(source, function_type).unwrap();
let class = vm
.new_class(
"Data",
roots.object,
vec![],
[("read".into(), source)].into(),
)
.unwrap();
let Value::Object(instance) = vm.call(class, &[]).unwrap() else {
panic!("instance required");
};
let Value::Object(bound) = vm.bind_attr(instance, "read").unwrap() else {
panic!("method required");
};
assert!(vm.is_instance(bound, function_type).unwrap());
assert!(!vm.is_instance(class, function_type).unwrap());
assert!(vm.set_function_type(class).is_err());
let invalid = endor_core::EndorCode::from_instructions(
&[
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 0),
endor_core::Instruction::simple(endor_core::Opcode::ReturnValue),
],
vec![Value::Nil],
endor_core::CodeLayout::default(),
)
.unwrap()
.with_source_signature(SourceSignature {
parameters: vec!["Number".into()],
return_type: "Unit".into(),
method_owner: None,
});
assert!(invalid.is_err());
for object in [
source,
native,
class,
instance,
bound,
function_type,
roots.object,
roots.type_type,
] {
vm.release(object).unwrap();
}
vm.collect_cycles();
assert_eq!(vm.object_count(), 0);
}
#[test]
fn failed_nominal_return_releases_value_and_captured_type_roots() {
use endor_core::{
CodeLayout, EndorCode, EndorCodeObject, Instruction, Opcode, SourceSignature,
};
let mut vm = Vm::new().unwrap();
vm.set_source_type_checks(true).unwrap();
let roots = vm.bootstrap_types().unwrap();
let expected = vm
.new_type("Expected", roots.object, TypeConstructor::Record)
.unwrap();
let other = vm
.new_type("Other", roots.object, TypeConstructor::Record)
.unwrap();
let Value::Object(value) = vm.call(other, &[]).unwrap() else {
panic!("instance required");
};
let globals = vm.new_dict().unwrap();
vm.dict_set(
globals,
Value::Text("Expected".into()),
Value::Object(expected),
)
.unwrap();
let code = EndorCode::from_instructions(
&[
Instruction::new(Opcode::LoadConst, 0),
Instruction::simple(Opcode::ReturnValue),
],
vec![Value::Object(value)],
CodeLayout::default(),
)
.unwrap()
.with_source_signature(SourceSignature {
parameters: vec![],
return_type: "Expected".into(),
method_owner: None,
})
.unwrap();
let code = vm.allocate(EndorCodeObject::new(code)).unwrap();
let function = vm
.new_function("bad return", code, globals, vec![], vec![])
.unwrap();
let before_type = vm.ref_count(expected).unwrap();
let before_value = vm.ref_count(value).unwrap();
assert!(matches!(
vm.call(function, &[]),
Err(VmError::TypeMismatch { .. })
));
assert_eq!(vm.ref_count(expected).unwrap(), before_type);
assert_eq!(vm.ref_count(value).unwrap(), before_value);
for object in [
function,
code,
globals,
value,
expected,
other,
roots.object,
roots.type_type,
] {
vm.release(object).unwrap();
}
vm.collect_cycles();
assert_eq!(vm.object_count(), 0);
}