Check source function annotations and unify managed function identity
This commit is contained in:
@@ -4,19 +4,19 @@
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement)与独立存储 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload、ObjectHeader、EndorObject、Record、NativeFunction |
|
||||
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托 |
|
||||
| [native.rs](native.rs) | NativeContext、上下文原生函数、作用域语言函数工厂、显式能力声明入口、根与非递归委托调用 |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType)与独立存储 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload(含显式函数标记)、ObjectHeader、EndorObject、Record、NativeFunction |
|
||||
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、注解解析/匹配 |
|
||||
| [native.rs](native.rs) | NativeContext、上下文原生函数、作用域语言函数工厂、显式能力声明入口、函数标记、根与非递归委托调用 |
|
||||
| [changes.rs](changes.rs) | 合并变更批次、变更键与有界通知额度 |
|
||||
| [number.rs](number.rs) | Integer/Decimal/Rational/BinaryFloat/Complex 的无损表示和装箱载荷 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边 |
|
||||
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收、后代契约更新的私有借用枚举、只读变更屏障/全调用及嵌套子调用读取跟踪及私有边界测试 |
|
||||
| [store.rs](store.rs) | ObjectStore、空堆创建、对象操作、retain/release 和回收入口 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边、语言函数标记 |
|
||||
| [heap.rs](heap.rs) | 私有 Heap、不可伪造 ObjectRef、稳定 Box、引用事务、迭代释放、循环回收、后代契约更新的私有借用枚举、同类型附加幂等、只读变更屏障/全调用及嵌套子调用读取跟踪及私有边界测试 |
|
||||
| [store.rs](store.rs) | ObjectStore、空堆创建、对象操作、retain/release 和回收入口、弱 Function 类型配置与分配分类 |
|
||||
| [store_builtins.rs](store_builtins.rs) | 载荷校验、代码/函数工厂、Dict/Cell 操作及键语义 |
|
||||
| [instruction.rs](instruction.rs) | Opcode、Instruction、wordcode 编解码、MakeFunction/比较参数与跳转读取接口 |
|
||||
| [code.rs](code.rs) | CodeLayout、EndorCode/EndorCodeObject、共享不可变代码和操作数/控制流/栈验证 |
|
||||
| [error.rs](error.rs) | 对象、代码与执行共用的 VmError(含能力/方法定位的TraitViolation),避免反向依赖 core |
|
||||
| [code.rs](code.rs) | CodeLayout、EndorCode/EndorCodeObject、可选源码签名、共享不可变代码和操作数/控制流/栈验证 |
|
||||
| [error.rs](error.rs) | 对象、代码与执行共用的 VmError(含TraitViolation、UnknownAnnotation、TypeMismatch),避免反向依赖 core |
|
||||
|
||||
对象操作变更同步 [对象模型](../../../docs/runtime/objects.md),内置载荷同步 [基本对象](../../../docs/runtime/builtins.md)。新增操作码需要同时修改本包 instruction.rs/code.rs 和 core 的 eval.rs 分派,见 [字节码 VM](../../../docs/runtime/bytecode.md)。
|
||||
|
||||
|
||||
@@ -208,6 +208,9 @@ impl EndorFunctionObject {
|
||||
}
|
||||
|
||||
impl ObjectPayload for EndorFunctionObject {
|
||||
fn is_function(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -17,6 +17,14 @@ pub struct CodeLayout {
|
||||
pub names: Vec<String>,
|
||||
}
|
||||
|
||||
/// Source declaration metadata, separate from executable slot layout.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SourceSignature {
|
||||
pub parameters: Vec<String>,
|
||||
pub return_type: String,
|
||||
pub method_owner: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EndorCode {
|
||||
bytecode: Vec<u8>,
|
||||
@@ -27,6 +35,7 @@ pub struct EndorCode {
|
||||
name: String,
|
||||
filename: String,
|
||||
first_line: usize,
|
||||
signature: Option<SourceSignature>,
|
||||
}
|
||||
|
||||
impl EndorCode {
|
||||
@@ -73,9 +82,30 @@ impl EndorCode {
|
||||
name: "<code>".into(),
|
||||
filename: "<endor>".into(),
|
||||
first_line: 1,
|
||||
signature: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn with_source_signature(mut self, signature: SourceSignature) -> Result<Self, VmError> {
|
||||
if signature.parameters.len() != self.parameters().len()
|
||||
|| signature.return_type.is_empty()
|
||||
|| signature.parameters.iter().any(String::is_empty)
|
||||
|| signature
|
||||
.method_owner
|
||||
.as_ref()
|
||||
.is_some_and(String::is_empty)
|
||||
{
|
||||
return Err(VmError::InvalidArgument(
|
||||
"source signature does not match code parameters",
|
||||
));
|
||||
}
|
||||
self.signature = Some(signature);
|
||||
Ok(self)
|
||||
}
|
||||
pub fn source_signature(&self) -> Option<&SourceSignature> {
|
||||
self.signature.as_ref()
|
||||
}
|
||||
|
||||
pub fn with_location(
|
||||
mut self,
|
||||
name: impl Into<String>,
|
||||
|
||||
@@ -18,6 +18,13 @@ pub enum VmError {
|
||||
method: String,
|
||||
reason: &'static str,
|
||||
},
|
||||
UnknownAnnotation(String),
|
||||
TypeMismatch {
|
||||
function: String,
|
||||
position: String,
|
||||
expected: String,
|
||||
actual: String,
|
||||
},
|
||||
EmptyCell,
|
||||
InvalidBytecode {
|
||||
offset: usize,
|
||||
@@ -53,6 +60,18 @@ impl fmt::Display for VmError {
|
||||
method,
|
||||
reason,
|
||||
} => write!(f, "trait {capability} method {method}: {reason}"),
|
||||
Self::UnknownAnnotation(name) => {
|
||||
write!(f, "unknown or invalid type annotation: {name}")
|
||||
}
|
||||
Self::TypeMismatch {
|
||||
function,
|
||||
position,
|
||||
expected,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"{function} {position} expects {expected}, received {actual}"
|
||||
),
|
||||
Self::EmptyCell => f.write_str("cell is empty"),
|
||||
Self::InvalidBytecode { offset, reason } => {
|
||||
write!(f, "invalid bytecode at code unit {offset}: {reason}")
|
||||
|
||||
@@ -210,6 +210,9 @@ impl Heap {
|
||||
reference: ObjectRef,
|
||||
type_object: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
if self.get(reference)?.header.type_object == Some(type_object) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.get(reference)?.header.type_object.is_some() {
|
||||
return Err(VmError::InvalidArgument("object already has a type"));
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use builtins::{
|
||||
EndorStringObject, EndorTracebackEntry,
|
||||
};
|
||||
pub use changes::{ChangeBatch, ChangeKey, ObjectChange};
|
||||
pub use code::{CodeLayout, EndorCode, EndorCodeObject};
|
||||
pub use code::{CodeLayout, EndorCode, EndorCodeObject, SourceSignature};
|
||||
pub use error::VmError;
|
||||
pub use heap::{ObjectRef, WeakObjectRef};
|
||||
pub use instruction::{DecodedInstruction, Instruction, Opcode};
|
||||
@@ -45,5 +45,6 @@ pub use object::{
|
||||
};
|
||||
pub use store::ObjectStore;
|
||||
pub use types::{
|
||||
ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement, RootTypes, TypeConstructor,
|
||||
AnnotationType, ClassField, EndorTraitObject, EndorTypeObject, MethodRequirement, RootTypes,
|
||||
TypeConstructor,
|
||||
};
|
||||
|
||||
@@ -211,6 +211,9 @@ impl ContextNativeFunction {
|
||||
}
|
||||
|
||||
impl ObjectPayload for ContextNativeFunction {
|
||||
fn is_function(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ 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 {
|
||||
/// Explicit function category; callable Type objects are not functions.
|
||||
fn is_function(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Ordinary field storage may be indirect, independently of type identity.
|
||||
/// Targets must be traced; retargeting records Contents on the forwarder.
|
||||
fn attribute_target(&self, _store: &crate::ObjectStore) -> Result<Option<ObjectRef>, VmError> {
|
||||
@@ -190,6 +195,9 @@ impl EndorNativeFunctionObject {
|
||||
pub type NativeFunction = EndorNativeFunctionObject;
|
||||
|
||||
impl ObjectPayload for EndorNativeFunctionObject {
|
||||
fn is_function(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::{
|
||||
#[derive(Debug)]
|
||||
pub struct ObjectStore {
|
||||
pub(crate) heap: Heap,
|
||||
function_type: Option<WeakObjectRef>,
|
||||
}
|
||||
|
||||
impl ObjectStore {
|
||||
@@ -125,7 +126,10 @@ impl ObjectStore {
|
||||
}
|
||||
|
||||
pub fn new() -> Result<Self, VmError> {
|
||||
Ok(Self { heap: Heap::new()? })
|
||||
Ok(Self {
|
||||
heap: Heap::new()?,
|
||||
function_type: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn object_count(&self) -> usize {
|
||||
@@ -136,7 +140,40 @@ impl ObjectStore {
|
||||
/// are borrowed; use retain/release to manage additional owned references.
|
||||
pub fn allocate(&mut self, payload: impl ObjectPayload) -> Result<ObjectRef, VmError> {
|
||||
self.validate_builtin(&payload)?;
|
||||
self.heap.allocate(Box::new(payload))
|
||||
let function = payload.is_function();
|
||||
let object = self.heap.allocate(Box::new(payload))?;
|
||||
if function && let Some(weak) = self.function_type {
|
||||
let result = (|| {
|
||||
let definition = self.upgrade(weak)?.ok_or(VmError::InvalidArgument(
|
||||
"configured Function type has expired",
|
||||
))?;
|
||||
let result = self.attach_type(object, definition);
|
||||
self.release(definition)?;
|
||||
result
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
self.release(object)?;
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
pub fn set_function_type(&mut self, definition: ObjectRef) -> Result<(), VmError> {
|
||||
self.payload::<crate::EndorTypeObject>(definition, "Type")?;
|
||||
if self.is_read_only() {
|
||||
return Err(VmError::UnsupportedOperation(
|
||||
"configure Function type during read-only call",
|
||||
));
|
||||
}
|
||||
let weak = self.downgrade(definition)?;
|
||||
if self.function_type.is_some_and(|old| old != weak) {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"Function type is already configured",
|
||||
));
|
||||
}
|
||||
self.function_type = Some(weak);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn new_object(&mut self) -> Result<ObjectRef, VmError> {
|
||||
|
||||
@@ -483,6 +483,9 @@ struct BoundMethod {
|
||||
function: ObjectRef,
|
||||
}
|
||||
impl ObjectPayload for BoundMethod {
|
||||
fn is_function(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn reference_assignment_only(&self) -> bool {
|
||||
true
|
||||
}
|
||||
@@ -726,3 +729,141 @@ impl ObjectStore {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed expected-type descriptor. Frames retain its managed reference
|
||||
/// while validating the return, so rebinding globals cannot release it mid-call.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum AnnotationType {
|
||||
Any,
|
||||
Unit,
|
||||
Number,
|
||||
String,
|
||||
Bool,
|
||||
Function,
|
||||
Type,
|
||||
Trait,
|
||||
Nominal(ObjectRef),
|
||||
Capability(ObjectRef),
|
||||
}
|
||||
impl AnnotationType {
|
||||
pub fn reference(self) -> Option<ObjectRef> {
|
||||
match self {
|
||||
Self::Nominal(reference) | Self::Capability(reference) => Some(reference),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ObjectStore {
|
||||
pub fn annotation_type(
|
||||
&self,
|
||||
function: ObjectRef,
|
||||
name: &str,
|
||||
receiver: Option<ObjectRef>,
|
||||
) -> Result<AnnotationType, VmError> {
|
||||
let data = self.payload::<crate::EndorFunctionObject>(function, "function")?;
|
||||
let signature = self
|
||||
.payload::<crate::EndorCodeObject>(data.code(), "code")?
|
||||
.code()
|
||||
.source_signature();
|
||||
// Bind a method's own class to the definition that actually owns it,
|
||||
// including inherited methods and old instances after REPL redefinition.
|
||||
if signature.and_then(|s| s.method_owner.as_deref()) == Some(name)
|
||||
&& let Some(receiver) = receiver
|
||||
{
|
||||
let mut current = self.type_of(receiver)?;
|
||||
while let Some(definition) = current {
|
||||
let payload = self.payload::<EndorTypeObject>(definition, "Type")?;
|
||||
if payload.name == name
|
||||
&& payload.methods.values().any(|method| *method == function)
|
||||
{
|
||||
return Ok(AnnotationType::Nominal(definition));
|
||||
}
|
||||
current = payload.base;
|
||||
}
|
||||
}
|
||||
let primitive = match name {
|
||||
"Object" => Some(AnnotationType::Any),
|
||||
"Unit" => Some(AnnotationType::Unit),
|
||||
"Number" => Some(AnnotationType::Number),
|
||||
"String" | "Text" => Some(AnnotationType::String),
|
||||
"Bool" => Some(AnnotationType::Bool),
|
||||
"Function" => Some(AnnotationType::Function),
|
||||
"Type" => Some(AnnotationType::Type),
|
||||
"Trait" => Some(AnnotationType::Trait),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(primitive) = primitive {
|
||||
return Ok(primitive);
|
||||
}
|
||||
let value = self
|
||||
.dict_get(data.globals(), &Value::Text(name.into()))?
|
||||
.or(match data.builtins() {
|
||||
Some(builtins) => self.dict_get(builtins, &Value::Text(name.into()))?,
|
||||
None => None,
|
||||
});
|
||||
if let Some(Value::Object(definition)) = value {
|
||||
let payload = self.object(definition)?.payload();
|
||||
if payload.as_any().is::<EndorTypeObject>() {
|
||||
return Ok(AnnotationType::Nominal(definition));
|
||||
}
|
||||
if payload.as_any().is::<EndorTraitObject>() {
|
||||
return Ok(AnnotationType::Capability(definition));
|
||||
}
|
||||
}
|
||||
Err(VmError::UnknownAnnotation(name.into()))
|
||||
}
|
||||
pub fn matches_annotation(
|
||||
&self,
|
||||
value: &Value,
|
||||
expected: AnnotationType,
|
||||
) -> Result<bool, VmError> {
|
||||
if let Value::Object(object) = value {
|
||||
self.object(*object)?;
|
||||
}
|
||||
Ok(match expected {
|
||||
AnnotationType::Any => true,
|
||||
AnnotationType::Unit => matches!(value, Value::Nil),
|
||||
AnnotationType::Number => {
|
||||
matches!(value, Value::Number(_))
|
||||
|| matches!(value,Value::Object(object) if self.object(*object)?.payload().as_any().is::<crate::EndorNumberObject>())
|
||||
}
|
||||
AnnotationType::String => {
|
||||
matches!(value, Value::Text(_))
|
||||
|| matches!(value,Value::Object(object) if self.object(*object)?.payload().as_any().is::<crate::EndorStringObject>())
|
||||
}
|
||||
AnnotationType::Bool => matches!(value, Value::Bool(_)),
|
||||
AnnotationType::Function => {
|
||||
matches!(value,Value::Object(object) if self.object(*object)?.payload().is_function())
|
||||
}
|
||||
AnnotationType::Type => {
|
||||
matches!(value,Value::Object(object) if self.object(*object)?.payload().as_any().is::<EndorTypeObject>())
|
||||
}
|
||||
AnnotationType::Trait => {
|
||||
matches!(value,Value::Object(object) if self.object(*object)?.payload().as_any().is::<EndorTraitObject>())
|
||||
}
|
||||
AnnotationType::Nominal(definition) => match value {
|
||||
Value::Object(object) => self.is_instance(*object, definition)?,
|
||||
_ => false,
|
||||
},
|
||||
AnnotationType::Capability(definition) => match value {
|
||||
Value::Object(object) => self.supports(*object, definition)?,
|
||||
_ => false,
|
||||
},
|
||||
})
|
||||
}
|
||||
pub fn value_type_name(&self, value: &Value) -> Result<String, VmError> {
|
||||
Ok(match value {
|
||||
Value::Nil => "Unit".into(),
|
||||
Value::Bool(_) => "Bool".into(),
|
||||
Value::Number(_) => "Number".into(),
|
||||
Value::Text(_) => "String".into(),
|
||||
Value::Object(object) => match self.type_of(*object)? {
|
||||
Some(definition) => self
|
||||
.payload::<EndorTypeObject>(definition, "Type")?
|
||||
.name
|
||||
.clone(),
|
||||
None => self.object(*object)?.payload().kind_name().into(),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user