docs(objects): explain change notifications and shared errors

This commit is contained in:
2026-11-15 17:19:52 +08:00
parent 9861a6d586
commit 717eab6d32
2 changed files with 63 additions and 6 deletions
+15 -4
View File
@@ -1,26 +1,37 @@
//! Heap 产生、Store/VM 取走、宿主缓存消费的变更通知数据;不保存对象所有权。
//! 通知反映已提交的修改,不是可重放操作日志,也不保证消费时源对象仍存活。
use crate::ObjectRef; use crate::ObjectRef;
/// A precise field change or a replacement of an object's native contents. /// Heap::record_change 用于合并通知的键;同一对象的不同属性仍各自保留。
/// Entries are notifications, never roots; a source can be dead when consumed.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChangeKey { pub enum ChangeKey {
/// Heap 属性写入/删除发布具体字段名;消费者可只失效对应字段的观察。
Attribute(String), Attribute(String),
/// 载荷替换、类型附着或共享引用更新改变整体内容;消费者按内容依赖处理。
Contents, Contents,
} }
/// Heap::take_changes 从内部有序映射生成的单条合并通知,供宿主失效缓存。
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectChange { pub struct ObjectChange {
/// 修改来源的完整借用身份,包含代际;不能当作有效拥有根直接使用。
pub object: ObjectRef, pub object: ObjectRef,
/// 被修改的字段或整体载荷类别。
pub key: ChangeKey, pub key: ChangeKey,
/// 此对象/键在本批最后一次通知的对象版本,不是批次序号。
pub version: u64, pub version: u64,
} }
/// Coalesced changes since the previous drain. Overflow requires the consumer /// Store::take_changes 返回上次取走后累计的合并结果;取走时重置内部批次。
/// to rescan its dependencies, rather than silently missing notifications. /// 溢出会丢弃精确条目并要求全面重验,消费者不能把空 changes 解释为没有修改。
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct ChangeBatch { pub struct ChangeBatch {
/// 精确通知;同一对象/键重复修改仅保留最新版本,排序不表示实际修改先后。
pub changes: Vec<ObjectChange>, pub changes: Vec<ObjectChange>,
/// true 时须全面重验所持依赖,不能仅处理 changes 中的对象。
pub rescan_required: bool, pub rescan_required: bool,
} }
/// Heap::record_change 的唯一对象/键数量上限;更新已有键不额外占用容量。
pub(crate) const MAX_PENDING_CHANGES: usize = 4096; pub(crate) const MAX_PENDING_CHANGES: usize = 4096;
+48 -2
View File
@@ -1,55 +1,97 @@
//! objects 定义、compiler/core 与宿主共用的错误协议,避免底层存储反向依赖 VM 执行器。
//! Display 只生成诊断文本,不恢复对象、不回滚操作,也不等同于托管的异常对象载荷。
use std::fmt; use std::fmt;
/// Shared object/bytecode/execution errors. The established VmError name is /// 覆盖对象、字节码与执行错误;保留 VmError 名称供既有嵌入方匹配。
/// retained for embedders; defining it here avoids a dependency on the VM. /// 各操作用 Result 返回;Clone 复制诊断信息,不复制 VM 状态或托管对象。
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum VmError { pub enum VmError {
/// 宿主等待对象的异步操作失败,携带提供方报告的原因。
AwaitFailed(String), AwaitFailed(String),
/// 宿主等待对象报告取消,与失败原因或暂未就绪区分。
AwaitCancelled, AwaitCancelled,
/// Heap::get 发现句柄属于其他堆;不是本堆对象已过期。
ForeignHandle, ForeignHandle,
/// Heap::get 发现越界、代际不符或空槽;不能再访问该身份。
InvalidHandle, InvalidHandle,
/// Heap::new 的进程级身份计数耗尽,拒绝复用身份。
IdentityExhausted, IdentityExhausted,
/// Heap 引用增量预检溢出,阻止计数绕回。
RefCountOverflow, RefCountOverflow,
/// Heap::release 没有可归还的外部根;内部强边不能当外部根释放。
NoOwnedReference, NoOwnedReference,
/// 属性存储查找/删除未找到字段,携带字段名。
AttributeNotFound(String), AttributeNotFound(String),
/// 载荷不支持操作或当前上下文禁止操作,携带静态操作说明。
UnsupportedOperation(&'static str), UnsupportedOperation(&'static str),
/// 构造或协议校验不满足结构约束,携带静态原因。
InvalidArgument(&'static str), InvalidArgument(&'static str),
/// Store 下转型或执行器要求某种载荷而实际不符,携带预期诊断名称。
ObjectKindMismatch(&'static str), ObjectKindMismatch(&'static str),
/// 能力契约校验失败,定位能力、方法及不兼容原因。
TraitViolation { TraitViolation {
/// 能力名称,用于定位失败契约。
capability: String, capability: String,
/// 被核对的方法名称。
method: String, method: String,
/// 无需动态分配的具体失败原因。
reason: &'static str, reason: &'static str,
}, },
/// 方法替换不满足父级契约,定位定义、方法和原因。
OverrideViolation { OverrideViolation {
/// 方法所属类型定义名称。
definition: String, definition: String,
/// 被核对的方法名称。
method: String, method: String,
/// 无需动态分配的具体失败原因。
reason: &'static str, reason: &'static str,
}, },
/// 类型解析无法接受注解名称;部分延后校验路径可暂缓此错误。
UnknownAnnotation(String), UnknownAnnotation(String),
/// 源码/原生签名或字段校验不匹配,携带调用位置与预期/实际类型诊断。
TypeMismatch { TypeMismatch {
/// 被校验函数或相关诊断主体。
function: String, function: String,
/// 参数、返回值或字段等发生不匹配的位置。
position: String, position: String,
/// 期望类型的可读名称。
expected: String, expected: String,
/// 实际值类型的可读名称。
actual: String, actual: String,
}, },
/// Store::cell_get 读取尚未初始化的闭包槽,不等于槽中存放 Nil。
EmptyCell, EmptyCell,
/// 解码或代码校验拒绝指令,offset 是代码单元偏移,reason 是静态说明。
InvalidBytecode { InvalidBytecode {
/// 字节码代码单元偏移,不是源文本行号。
offset: usize, offset: usize,
/// 无需动态分配的具体失败原因。
reason: &'static str, reason: &'static str,
}, },
/// 执行器读取/删除未绑定局部或相关捕获变量,携带变量名称。
UnboundLocal(String), UnboundLocal(String),
/// 执行器全局/内置查找或删除名称失败,携带名称。
NameNotFound(String), NameNotFound(String),
/// 调用入口数量校验失败,记录函数名、最少/最多及实际位置参数数目。
ArgumentCount { ArgumentCount {
/// 被调用对象的诊断名称。
name: String, name: String,
/// 允许的最少位置参数数。
required: usize, required: usize,
/// 允许的最多位置参数数。
maximum: usize, maximum: usize,
/// 调用方实际提供的位置参数数。
provided: usize, provided: usize,
}, },
/// 执行帧、指令等预算或内部有界计数达到限制,携带具体限制类别。
ExecutionLimit(&'static str), ExecutionLimit(&'static str),
} }
impl fmt::Display for VmError { impl fmt::Display for VmError {
/// 宿主日志、UI 错误文本及标准 Error 展示调用;只借用错误,不消费其中的诊断数据。
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// 按变体生成稳定的可读诊断;结构化匹配应使用变体,不能依赖解析此文本。
match self { match self {
Self::AwaitFailed(message) => write!(f, "await failed: {message}"), Self::AwaitFailed(message) => write!(f, "await failed: {message}"),
Self::AwaitCancelled => f.write_str("await cancelled"), Self::AwaitCancelled => f.write_str("await cancelled"),
@@ -59,6 +101,7 @@ impl fmt::Display for VmError {
Self::RefCountOverflow => f.write_str("object reference count exhausted"), Self::RefCountOverflow => f.write_str("object reference count exhausted"),
Self::NoOwnedReference => f.write_str("no external strong reference to release"), Self::NoOwnedReference => f.write_str("no external strong reference to release"),
Self::AttributeNotFound(name) => write!(f, "attribute not found: {name}"), Self::AttributeNotFound(name) => write!(f, "attribute not found: {name}"),
// 保留具体受限操作,便于区分协议缺失和只读上下文等限制。
Self::UnsupportedOperation(operation) => { Self::UnsupportedOperation(operation) => {
write!(f, "object does not support {operation}") write!(f, "object does not support {operation}")
} }
@@ -69,6 +112,7 @@ impl fmt::Display for VmError {
method, method,
reason, reason,
} => write!(f, "trait {capability} method {method}: {reason}"), } => write!(f, "trait {capability} method {method}: {reason}"),
// 名称来自注解解析,不把它伪装成已经解析的语言类型。
Self::UnknownAnnotation(name) => { Self::UnknownAnnotation(name) => {
write!(f, "unknown or invalid type annotation: {name}") write!(f, "unknown or invalid type annotation: {name}")
} }
@@ -87,6 +131,7 @@ impl fmt::Display for VmError {
"{function} {position} expects {expected}, received {actual}" "{function} {position} expects {expected}, received {actual}"
), ),
Self::EmptyCell => f.write_str("cell is empty"), Self::EmptyCell => f.write_str("cell is empty"),
// 偏移单位与指令解码器一致,避免把代码单元误报为源代码行号。
Self::InvalidBytecode { offset, reason } => { Self::InvalidBytecode { offset, reason } => {
write!(f, "invalid bytecode at code unit {offset}: {reason}") write!(f, "invalid bytecode at code unit {offset}: {reason}")
} }
@@ -106,4 +151,5 @@ impl fmt::Display for VmError {
} }
} }
// 使宿主可通过标准 Error 接口传播/封装;当前未另提供嵌套 source 错误链。
impl std::error::Error for VmError {} impl std::error::Error for VmError {}