Enforce native type signatures and effects across delegated calls
This commit is contained in:
@@ -4,10 +4,10 @@
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType/CallArity/ReadAccess)与独立存储 rustdoc 示例 |
|
||||
| [lib.rs](lib.rs) | 包边界、对象类型/ObjectStore 公开导出(含Trait/MethodRequirement/SourceSignature/AnnotationType/CallArity/CallSignature/CallEffect/ReadAccess)与独立存储 rustdoc 示例 |
|
||||
| [object.rs](object.rs) | Value、CompareOp、ObjectPayload(含显式函数标记)、ObjectHeader、EndorObject、Record、可发布数量元数据的 NativeFunction |
|
||||
| [types.rs](types.rs) | 托管名义类型、显式 Object/Type 引导、继承查询、受管方法表/接收者绑定、类字段、显式Trait定义/声明/方法参数约束、原生构造委托、统一源码/原生/绑定方法参数区间查询与能力验证、声明环境托管边、字段构造/写入检查与标记为校验读取的注解解析/匹配 |
|
||||
| [native.rs](native.rs) | NativeContext、CallArity 元数据与调用前数量检查、上下文原生函数、作用域语言函数工厂、显式能力声明入口、函数标记、根与非递归委托调用 |
|
||||
| [native.rs](native.rs) | NativeContext、CallArity/CallSignature 类型与效果元数据、调用前检查、签名类型强边、上下文原生函数、作用域语言函数工厂、显式能力声明入口、函数标记、根与非递归委托调用 |
|
||||
| [changes.rs](changes.rs) | 合并变更批次、变更键与有界通知额度 |
|
||||
| [number.rs](number.rs) | Integer/Decimal/Rational/BinaryFloat/Complex 的无损表示和装箱载荷 |
|
||||
| [builtins.rs](builtins.rs) | String、Dict、Cell、Function、BaseException 载荷与 trace 边、语言函数标记 |
|
||||
|
||||
@@ -35,7 +35,10 @@ pub use code::{CodeLayout, EndorCode, EndorCodeObject, SourceSignature};
|
||||
pub use error::VmError;
|
||||
pub use heap::{ObjectRef, ReadAccess, WeakObjectRef};
|
||||
pub use instruction::{DecodedInstruction, Instruction, Opcode};
|
||||
pub use native::{CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult};
|
||||
pub use native::{
|
||||
CallArity, CallEffect, CallSignature, ContextNativeFunction, NativeCallable, NativeContext,
|
||||
NativeResult,
|
||||
};
|
||||
pub use number::{
|
||||
EndorDecimal, EndorInteger, EndorNumber, EndorNumberObject, EndorRational, EndorReal,
|
||||
};
|
||||
|
||||
@@ -50,10 +50,141 @@ impl CallArity {
|
||||
}
|
||||
}
|
||||
|
||||
/// Declared host effect. ReadOnly may allocate results but must not mutate
|
||||
/// existing objects or perform external I/O. Unknown legacy calls remain unknown.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CallEffect {
|
||||
ReadOnly,
|
||||
Mutating,
|
||||
External,
|
||||
}
|
||||
|
||||
/// Immutable native contract, including an explicit receiver where applicable.
|
||||
/// Missing fixed slots are covered by variadic; optionality comes from arity.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CallSignature {
|
||||
pub arity: CallArity,
|
||||
pub parameters: Vec<crate::AnnotationType>,
|
||||
pub variadic: Option<crate::AnnotationType>,
|
||||
pub returns: crate::AnnotationType,
|
||||
pub effect: CallEffect,
|
||||
}
|
||||
impl CallSignature {
|
||||
pub fn exact(
|
||||
parameters: Vec<crate::AnnotationType>,
|
||||
returns: crate::AnnotationType,
|
||||
effect: CallEffect,
|
||||
) -> Self {
|
||||
Self {
|
||||
arity: CallArity::exact(parameters.len()),
|
||||
parameters,
|
||||
variadic: None,
|
||||
returns,
|
||||
effect,
|
||||
}
|
||||
}
|
||||
pub fn references(&self) -> impl Iterator<Item = ObjectRef> + '_ {
|
||||
self.parameters
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(self.variadic)
|
||||
.chain([self.returns])
|
||||
.filter_map(crate::AnnotationType::reference)
|
||||
}
|
||||
pub fn validate(&self, store: &ObjectStore) -> Result<(), VmError> {
|
||||
self.arity.validate()?;
|
||||
if self.parameters.len() > self.arity.maximum
|
||||
|| (self.variadic.is_none() && self.parameters.len() != self.arity.maximum)
|
||||
{
|
||||
return Err(VmError::InvalidArgument("incomplete native signature"));
|
||||
}
|
||||
for expected in self
|
||||
.parameters
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(self.variadic)
|
||||
.chain([self.returns])
|
||||
{
|
||||
match expected {
|
||||
crate::AnnotationType::Nominal(reference) => {
|
||||
store.payload::<crate::EndorTypeObject>(reference, "Type")?;
|
||||
}
|
||||
crate::AnnotationType::Capability(reference) => {
|
||||
store.payload::<crate::EndorTraitObject>(reference, "Trait")?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn check_arguments(
|
||||
&self,
|
||||
store: &ObjectStore,
|
||||
name: &str,
|
||||
arguments: &[Value],
|
||||
) -> Result<(), VmError> {
|
||||
self.validate(store)?;
|
||||
self.arity.check(name.into(), arguments.len())?;
|
||||
if store.is_read_only() && self.effect != CallEffect::ReadOnly {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"native effect is forbidden during read-only execution",
|
||||
));
|
||||
}
|
||||
for (index, value) in arguments.iter().enumerate() {
|
||||
let expected = self
|
||||
.parameters
|
||||
.get(index)
|
||||
.copied()
|
||||
.or(self.variadic)
|
||||
.ok_or(VmError::InvalidArgument("incomplete native signature"))?;
|
||||
self.check_value(
|
||||
store,
|
||||
name,
|
||||
format!("parameter {}", index + 1),
|
||||
value,
|
||||
expected,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn check_return(
|
||||
&self,
|
||||
store: &ObjectStore,
|
||||
name: &str,
|
||||
value: &Value,
|
||||
) -> Result<(), VmError> {
|
||||
self.check_value(store, name, "return".into(), value, self.returns)
|
||||
}
|
||||
fn check_value(
|
||||
&self,
|
||||
store: &ObjectStore,
|
||||
name: &str,
|
||||
position: String,
|
||||
value: &Value,
|
||||
expected: crate::AnnotationType,
|
||||
) -> Result<(), VmError> {
|
||||
if !store.matches_annotation(value, expected)? {
|
||||
return Err(VmError::TypeMismatch {
|
||||
function: name.into(),
|
||||
position,
|
||||
expected: store.annotation_type_name(expected)?,
|
||||
actual: store.value_type_name(value)?,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub trait NativeCallable: fmt::Debug + Send + Sync + 'static {
|
||||
/// Immutable resolved types; referenced definitions must be traced by the
|
||||
/// payload. ContextNativeFunction snapshots and traces them automatically.
|
||||
fn signature(&self) -> Option<CallSignature> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Optional positional contract. Missing metadata remains an explicit legacy gap.
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
None
|
||||
self.signature().map(|signature| signature.arity)
|
||||
}
|
||||
|
||||
fn invoke(
|
||||
@@ -197,16 +328,29 @@ impl<'a> NativeContext<'a> {
|
||||
arguments.len(),
|
||||
)?;
|
||||
}
|
||||
let signature = store.native_signature(function)?;
|
||||
let name = store.object(function)?.payload().kind_name().to_owned();
|
||||
if let Some(signature) = &signature {
|
||||
signature.check_arguments(store, &name, arguments)?;
|
||||
}
|
||||
let mut context = Self {
|
||||
store,
|
||||
roots: Vec::new(),
|
||||
callee: function,
|
||||
};
|
||||
context.protect(&Value::Object(function))?;
|
||||
if let Some(signature) = &signature {
|
||||
for reference in signature.references() {
|
||||
context.protect(&Value::Object(reference))?;
|
||||
}
|
||||
}
|
||||
for argument in arguments {
|
||||
context.protect(argument)?;
|
||||
}
|
||||
let result = callable.invoke(&mut context, arguments)?;
|
||||
if let (Some(signature), NativeResult::Return(value)) = (&signature, &result) {
|
||||
signature.check_return(context.store(), &name, value)?;
|
||||
}
|
||||
let transferred_from = context.roots.len();
|
||||
match &result {
|
||||
NativeResult::Return(value) => context.protect(value)?,
|
||||
@@ -242,6 +386,7 @@ pub struct ContextNativeFunction {
|
||||
name: &'static str,
|
||||
callable: Arc<dyn NativeCallable>,
|
||||
captures: Vec<ObjectRef>,
|
||||
signature: Option<CallSignature>,
|
||||
}
|
||||
|
||||
impl ContextNativeFunction {
|
||||
@@ -252,6 +397,7 @@ impl ContextNativeFunction {
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
signature: callable.signature(),
|
||||
callable: Arc::new(callable),
|
||||
captures,
|
||||
}
|
||||
@@ -272,10 +418,18 @@ impl ObjectPayload for ContextNativeFunction {
|
||||
self.name
|
||||
}
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(signature) = &self.signature {
|
||||
for reference in signature.references() {
|
||||
visit(reference);
|
||||
}
|
||||
}
|
||||
for capture in &self.captures {
|
||||
visit(*capture);
|
||||
}
|
||||
}
|
||||
fn call_signature(&self) -> Option<CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
fn native_callable(&self) -> Option<Arc<dyn NativeCallable>> {
|
||||
Some(self.callable.clone())
|
||||
}
|
||||
|
||||
@@ -118,6 +118,11 @@ pub trait ObjectPayload: Any + fmt::Debug + Send + Sync {
|
||||
/// validates/retains the result before exposing it as an owned call result.
|
||||
/// Language functions are dispatched by Vm's frame evaluator instead.
|
||||
/// Positional metadata for native call protocols; source code is queried by the store.
|
||||
fn call_signature(&self) -> Option<crate::CallSignature> {
|
||||
self.native_callable()
|
||||
.and_then(|callable| callable.signature())
|
||||
}
|
||||
|
||||
fn call_arity(&self) -> Option<crate::CallArity> {
|
||||
self.native_callable().and_then(|callable| callable.arity())
|
||||
}
|
||||
@@ -182,6 +187,7 @@ pub struct EndorNativeFunctionObject {
|
||||
name: String,
|
||||
function: NativeCall,
|
||||
arity: Option<crate::CallArity>,
|
||||
signature: Option<crate::CallSignature>,
|
||||
}
|
||||
|
||||
impl EndorNativeFunctionObject {
|
||||
@@ -190,12 +196,18 @@ impl EndorNativeFunctionObject {
|
||||
name: name.into(),
|
||||
function,
|
||||
arity: None,
|
||||
signature: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
pub fn with_signature(mut self, signature: crate::CallSignature) -> Self {
|
||||
self.arity = Some(signature.arity);
|
||||
self.signature = Some(signature);
|
||||
self
|
||||
}
|
||||
pub fn with_arity(mut self, arity: crate::CallArity) -> Self {
|
||||
self.arity = Some(arity);
|
||||
self
|
||||
@@ -224,6 +236,16 @@ impl ObjectPayload for EndorNativeFunctionObject {
|
||||
Ok(format!("<native-function {}>", self.name))
|
||||
}
|
||||
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
if let Some(signature) = &self.signature {
|
||||
for reference in signature.references() {
|
||||
visit(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn call_signature(&self) -> Option<crate::CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
fn call_arity(&self) -> Option<crate::CallArity> {
|
||||
self.arity
|
||||
}
|
||||
|
||||
@@ -434,6 +434,26 @@ impl ObjectStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validated direct native metadata. Bound methods delegate to their actual
|
||||
/// target, so receiver slots remain explicit here. Returned handles are borrowed.
|
||||
pub fn native_signature(
|
||||
&self,
|
||||
function: ObjectRef,
|
||||
) -> Result<Option<crate::CallSignature>, VmError> {
|
||||
let payload = self.object(function)?.payload();
|
||||
let signature = payload.call_signature();
|
||||
if let Some(signature) = &signature {
|
||||
signature.validate(self)?;
|
||||
if payload
|
||||
.call_arity()
|
||||
.is_some_and(|arity| arity != signature.arity)
|
||||
{
|
||||
return Err(VmError::InvalidArgument("native signature arity mismatch"));
|
||||
}
|
||||
}
|
||||
Ok(signature)
|
||||
}
|
||||
|
||||
/// Unified source/native positional interval, after any bound receivers.
|
||||
/// None means no published native metadata (including generic Type construction).
|
||||
pub fn call_arity(&self, function: ObjectRef) -> Result<Option<crate::CallArity>, VmError> {
|
||||
@@ -462,7 +482,9 @@ impl ObjectStore {
|
||||
maximum,
|
||||
))
|
||||
} else {
|
||||
payload.call_arity()
|
||||
self.native_signature(current)?
|
||||
.map(|signature| signature.arity)
|
||||
.or_else(|| payload.call_arity())
|
||||
};
|
||||
return arity
|
||||
.map(|arity| {
|
||||
@@ -1040,6 +1062,26 @@ impl ObjectStore {
|
||||
},
|
||||
})
|
||||
}
|
||||
pub fn annotation_type_name(&self, expected: AnnotationType) -> Result<String, VmError> {
|
||||
Ok(match expected {
|
||||
AnnotationType::Any => "Object".into(),
|
||||
AnnotationType::Unit => "Unit".into(),
|
||||
AnnotationType::Number => "Number".into(),
|
||||
AnnotationType::String => "String".into(),
|
||||
AnnotationType::Bool => "Bool".into(),
|
||||
AnnotationType::Function => "Function".into(),
|
||||
AnnotationType::Type => "Type".into(),
|
||||
AnnotationType::Trait => "Trait".into(),
|
||||
AnnotationType::Nominal(reference) => self
|
||||
.payload::<EndorTypeObject>(reference, "Type")?
|
||||
.name
|
||||
.clone(),
|
||||
AnnotationType::Capability(reference) => self
|
||||
.payload::<EndorTraitObject>(reference, "Trait")?
|
||||
.name
|
||||
.clone(),
|
||||
})
|
||||
}
|
||||
pub fn value_type_name(&self, value: &Value) -> Result<String, VmError> {
|
||||
Ok(match value {
|
||||
Value::Nil => "Unit".into(),
|
||||
|
||||
Reference in New Issue
Block a user