docs: 逐模块细化中文逻辑注释并覆盖测试与示例

This commit is contained in:
2026-11-12 10:31:35 +08:00
parent d29a1be329
commit cd23e70db1
123 changed files with 2664 additions and 249 deletions
+58 -6
View File
@@ -26,7 +26,9 @@ pub struct Mount {
// 已发布几何与每次出现的滚动位置分开保存,同一 Block 的多个位置互不覆盖。
pub geometry: MountGeometry,
pub scroll_offset: [f32; 2],
// 最后同步的布局版本,Bounds 查询会一并返回,便于调用方识别几何属于哪轮发布。
pub version: u64,
// false 后禁止依赖当前几何的操作;外部即使还持有 Mount 对象也不能把它当活动出现。
pub mounted: bool,
// Mount 可以拥有任务;退役后任务交付还要检查 owner 是否仍有效。
pub tasks: Option<ObjectRef>,
@@ -53,6 +55,7 @@ impl ObjectPayload for Mount {
true
}
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
// 仅 block 和 tasks 是 payload 的强拥有边;page/parent/child/sibling 是弱边,不参与 trace。
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
visit(self.block);
if let Some(tasks) = self.tasks {
@@ -86,6 +89,7 @@ enum Query {
struct Method {
signature: endor_core::CallSignature,
owner: ObjectRef,
// 方法对象拥有 Mount,但不能经桌面反向保活整个窗口;需要桌面能力时再 upgrade。
desktop: WeakObjectRef,
query: Query,
}
@@ -95,7 +99,7 @@ impl NativeCallable for Method {
fn signature(&self) -> Option<endor_core::CallSignature> {
Some(self.signature.clone())
}
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
/// 适配器已绑定 Mount;坐标测试/转换与scrollTo/By接受两个数,其余层次/几何/焦点查询零参。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(
if matches!(
@@ -114,9 +118,10 @@ impl NativeCallable for Method {
))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
/// 读取具体出现位置,先检查仍挂载与几何可用性,再执行层次、坐标、焦点、滚动或拾取操作,避免使用已退役上下文。
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
// 层次查询允许观察已经脱离的对象(通常得到 Nil);几何、焦点、滚动、拾取等必须仍挂接。
if !mount.mounted
&& matches!(
self.query,
@@ -135,6 +140,7 @@ impl NativeCallable for Method {
{
return Err(VmError::InvalidArgument("Mount is no longer attached"));
}
// 除 VM 元数据检查外入口再核对实际参数数目;二维坐标/位移操作取两个 Number,其余零参。
let arity = if matches!(
self.query,
Query::HitTest
@@ -153,6 +159,7 @@ impl NativeCallable for Method {
}
let value = match self.query {
Query::ToView | Query::ToLocal => {
// 布局期间几何尚未提交,坐标转换不能把临时 bounds 与上帧投影混用。
if mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"coordinate conversion requires committed geometry",
@@ -164,6 +171,7 @@ impl NativeCallable for Method {
);
let point =
if matches!(self.query, Query::ToView) {
// ToView 先将局部点加节点原点,再套二维 view;若在世界面板内,还继续向外投影到页面。
let point = mount.geometry.view.unwrap_or_default().point(
crate::geometry::Point::new(
point.x + mount.geometry.x,
@@ -176,6 +184,7 @@ impl NativeCallable for Method {
.as_ref()
.map_or(Some(point), |panel| panel.project_point(point))
} else {
// ToLocal 先撤销面板和视图投影,再减节点几何原点;不可逆时返回 Nil,而非虚构坐标。
mount.geometry.logical_point(point).map(|point| {
crate::geometry::Point::new(
point.x - mount.geometry.x,
@@ -183,6 +192,7 @@ impl NativeCallable for Method {
)
})
};
// 转换成功才分配名义 Point;失败返回 Nil,不把无效数值写进结果属性。
if let Some(point) = point {
let result = cx.new_object()?;
let desktop = cx.upgrade(self.desktop)?.ok_or(VmError::InvalidArgument(
@@ -196,6 +206,7 @@ impl NativeCallable for Method {
Value::Nil
}
}
// 同一滚动入口区分绝对位置和相对增量,钳制、挂接状态与写屏障交由 scroll::set 统一执行。
Query::ScrollTo | Query::ScrollBy => {
crate::scroll::set(
cx,
@@ -231,6 +242,7 @@ impl NativeCallable for Method {
),
)?
}
// 返回帧中已钳制的有效位置与最大偏移,不直接暴露可能尚未投影的 scroll_offset 原值。
Query::ScrollPosition => {
let p = mount
.geometry
@@ -243,6 +255,8 @@ impl NativeCallable for Method {
Value::Object(result)
}
Query::Bounds => {
// 布局只读调用中可查询当前安排阶段的临时 bounds;测量时尚无 bounds,明确报错。
// 非布局期则读取最后提交的 MountGeometry。
let geometry = if let Some(layout) = &mount.layout {
layout
.lock()
@@ -260,6 +274,7 @@ impl NativeCallable for Method {
]
};
let bounds = cx.new_object()?;
// 从本方法返回签名取得 Bounds 的名义类型,避免生成一个仅字段相似的普通对象。
let endor_core::CallType::Single(endor_core::AnnotationType::Nominal(definition)) =
&self.signature.returns
else {
@@ -281,6 +296,7 @@ impl NativeCallable for Method {
)?;
Value::Object(bounds)
}
// 请求焦点先让出现进入可见范围,再检查可聚焦资格并写入桌面请求;后续发布负责实际生效。
Query::Focus => {
crate::scroll::into_view(cx, self.owner, self.desktop)?;
if !mount.geometry.interactive {
@@ -297,12 +313,14 @@ impl NativeCallable for Method {
cx.set_attr(desktop, "focusRequested", Value::Bool(true))?;
Value::Nil
}
// 这里是 Mount 已提交几何的 contains 查询;源 Block 的 hitTest 覆盖由 source_hit 驱动另行执行。
Query::HitTest => {
if mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"Mount hitTest is unavailable during layout",
));
}
// 命中坐标只要求 Number 可转有限 f32;与 scroll::coordinate 不同,此处不限制绝对值至一百万。
let number = |value: &Value| -> Result<f32, VmError> {
let Value::Number(number) = value else {
return Err(VmError::InvalidArgument(
@@ -331,6 +349,7 @@ impl NativeCallable for Method {
Query::Page => mount.page,
_ => unreachable!(),
};
// 弱链接不存在或目标已回收都返回 Nil;升级本身失败才传播 VM 错误。
weak.map(|weak| cx.upgrade(weak))
.transpose()?
.flatten()
@@ -350,6 +369,7 @@ fn mount_signature(
) -> Result<endor_core::CallSignature, VmError> {
use endor_core::{AnnotationType as T, CallEffect, CallSignature, CallType};
let nominal = |name| crate::ui_bridge::desktop_type(store, name, desktop).map(T::Nominal);
// 层次、拾取和坐标转换可能没有结果,使用 nullable 名义类型;变更操作返回 Unit。
let returns = match query {
Query::Bounds => nominal("Bounds")?.into(),
Query::Parent | Query::FirstChild | Query::NextSibling => {
@@ -362,6 +382,7 @@ fn mount_signature(
Query::ScrollPosition => T::Any.into(),
_ => T::Unit.into(),
};
// 滚动、相机拟合和焦点会写业务/桌面属性,声明 Mutating;其余查询允许在只读协议中调用。
let effect = if matches!(
query,
Query::ScrollTo | Query::ScrollBy | Query::ScrollIntoView | Query::FitView | Query::Focus
@@ -391,6 +412,7 @@ fn mount_signature(
#[derive(Debug, Default, Clone)]
/// 活动出现的弱索引。真实托管拥有关系在 desktop 的挂载字典中,索引不能充当隐藏 GC 根。
pub struct MountTable {
// Mount ID 到托管弱身份,真实强拥有者是 desktop.mounts 字典;order 单独保存原布局顺序。
pub active: HashMap<u64, WeakObjectRef>,
order: Vec<u64>,
}
@@ -404,6 +426,7 @@ struct Sync {
old: HashMap<u64, WeakObjectRef>,
old_order: Vec<u64>,
frame: Frame,
// true 为布局准备阶段,安装临时 Context 并保留已有滚动偏移;false 为几何提交,清 Context。
preparing: bool,
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
}
@@ -417,13 +440,14 @@ struct LifecycleCall {
unmount: bool,
}
impl NativeCallable for LifecycleCall {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
/// Block、Mount 与用户钩子都已捕获,生命周期序列无参调用此适配器。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
/// 卸载时先取消 Mount 所有任务,再以 Block/Mount 为实参请求 VM 执行用户 onMount/onUnmount,不在 Rust 中直接运行源体。
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
// 用户 onUnmount 运行前先取消该出现拥有的任务,防止退役后继续交付旧工作。
if self.unmount {
crate::tasks::cancel_owner(cx, self.mount)?;
}
@@ -449,6 +473,7 @@ fn lifecycle_call(
.store()
.lookup_method(definition, name)?
.ok_or(VmError::InvalidArgument("Block has no lifecycle method"))?;
// 生命周期包装显式捕获函数、Block、Mount,使序列执行到回调前这些对象不会被回收。
cx.allocate(ContextNativeFunction::new(
name,
LifecycleCall {
@@ -462,13 +487,14 @@ fn lifecycle_call(
}
impl NativeCallable for Sync {
/// 声明宿主可调用对象接受的参数个数,供 VM 在执行前检查。
/// 展示同步步骤从捕获的帧与弱节点表读取输入,无需外部实参。
fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0))
}
/// VM 调入本宿主能力的入口;按所属操作解码参数并返回托管值或后续调用。
/// 把弱业务身份升级为本轮对象映射,再同步帧中出现位置到托管 Mount,建立结构/几何与待通知生命周期。
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
// 帧只含 Block 字符串身份,先将弱节点表升级为本次同步可用的实际对象映射。
let mut blocks = HashMap::new();
for weak in &self.nodes {
if let Some(block) = cx.upgrade(*weak)? {
@@ -493,6 +519,7 @@ impl NativeCallable for Sync {
.map(|weak| cx.upgrade(*weak))
.transpose()?
.flatten();
// Mount ID 相同仍不足以复用:必须仍挂接、页面相同、真实 Block 相同,防止身份误归属。
let reusable = if let Some(old) = old {
let mount = cx.store().payload::<Mount>(old, "Mount")?;
(mount.mounted && mount.page == page && mount.block == block).then_some(old)
@@ -516,6 +543,7 @@ impl NativeCallable for Sync {
layout: None,
})?;
crate::ui_bridge::attach_desktop_type(cx, object, "Mount", self.desktop)?;
// 每个新 Mount 安装捕获自身的原生方法;captures 中只放 Mount,桌面仍保留弱身份。
for (name, query) in [
("bounds", Query::Bounds),
("scrollTo", Query::ScrollTo),
@@ -552,6 +580,7 @@ impl NativeCallable for Sync {
};
objects.insert(geometry.id, object);
}
// 先建立全部 Mount,再第二遍补链接,保证 parent/child/sibling 无论先后都能找到目标身份。
let root = cx.new_dict()?;
for geometry in &self.frame.mounts {
let object = objects[&geometry.id];
@@ -566,6 +595,7 @@ impl NativeCallable for Sync {
first_child: link(geometry.first_child)?,
next_sibling: link(geometry.next_sibling)?,
geometry: geometry.clone(),
// 准备阶段沿用用户滚动状态;提交阶段以帧中有效偏移为准,非滚动容器归零。
scroll_offset: if self.preparing {
cx.store().payload::<Mount>(object, "Mount")?.scroll_offset
} else {
@@ -573,6 +603,7 @@ impl NativeCallable for Sync {
},
version: self.frame.layout_version,
mounted: true,
// 临时 Context 只有原生派生数据,无托管根;提交时置 None,表示几何可供外部查询。
layout: if self.preparing {
Some(Arc::new(Mutex::new(crate::layout::Context::default())))
} else {
@@ -580,6 +611,7 @@ impl NativeCallable for Sync {
},
};
let old = cx.store().payload::<Mount>(object, "Mount")?;
// 只在上下文、几何、版本、链接或公开挂接属性确实需更新时替换 payload,减少无关变更日志。
if self.preparing
|| old.layout.is_some()
|| !old.mounted
@@ -602,6 +634,7 @@ impl NativeCallable for Sync {
Value::Number((self.frame.layout_version as i64).into()),
)?;
}
// 新字典逐项拥有活动 Mount;弱链接本身不负责让整棵出现树存活。
cx.dict_set(
root,
Value::Text(geometry.id.to_string()),
@@ -611,12 +644,14 @@ impl NativeCallable for Sync {
let mut hooks = Vec::new();
// Layout records are preorder; reversing guarantees children unmount
// before their parents. A Page change creates fresh Mount contexts.
// 旧帧按父先子后记录,逆序退役保证孩子 onUnmount 在父之前;复用对象不退役。
for id in self.old_order.iter().rev() {
let weak = self.old[id];
if let Some(object) = cx.upgrade(weak)?
&& objects.get(id) != Some(&object)
{
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
// 先撤销挂接和全部关系,再安排回调;onUnmount 不能继续使用失效几何或沿旧链操作。
mount.mounted = false;
mount.layout = None;
mount.parent = None;
@@ -627,9 +662,11 @@ impl NativeCallable for Sync {
hooks.push(lifecycle_call(cx, object, "onUnmount")?);
}
}
// 新建顺序沿帧先序,onMount 默认父先子后;全部旧退役回调排在新挂载回调之前。
for object in created {
hooks.push(lifecycle_call(cx, object, "onMount")?);
}
// 同步只返回生命周期序列,不在此处立即执行用户回调;调用方决定在后续阶段何时运行。
let driver = if hooks.is_empty() {
None
} else {
@@ -644,6 +681,7 @@ impl NativeCallable for Sync {
.into_iter()
.map(|(id, object)| Ok((id, cx.store().downgrade(object)?)))
.collect::<Result<HashMap<_, _>, VmError>>()?;
// 先让桌面拥有新字典,再公布原生弱索引;返回的驱动保持待退役对象直到回调结束。
cx.set_attr(self.desktop, "mounts", Value::Object(root))?;
*self
.output
@@ -661,6 +699,7 @@ impl NativeCallable for Sync {
pub struct Checkpoint {
table: MountTable,
dictionary: Option<ObjectRef>,
// 保存 payload 与 mounted/layoutVersion 两项公开属性;None 表示原先没有属性,回滚要删除。
states: Vec<(ObjectRef, Mount, Option<Value>, Option<Value>)>,
roots: Vec<ObjectRef>,
}
@@ -669,6 +708,7 @@ impl Checkpoint {
/// 释放检查点为回滚临时保留的托管根,成功提交后不再需要这些引用。
pub fn release(self, vm: &mut Vm) -> Result<(), VmError> {
let mut result = Ok(());
// 逆序释放所有临时根,单项失败仍继续尝试余下根,最终返回最后一次释放错误。
for root in self.roots.into_iter().rev() {
if let Err(error) = vm.release(root) {
result = Err(error);
@@ -685,6 +725,7 @@ impl Checkpoint {
table: &mut MountTable,
) -> Result<(), VmError> {
let result = (|| {
// 回滚先识别本轮新增的出现并将其脱离,再恢复原有 Mount payload、公开属性和桌面拥有字典。
let old: std::collections::HashSet<_> =
self.states.iter().map(|state| state.0).collect();
for weak in table.ordered() {
@@ -702,6 +743,7 @@ impl Checkpoint {
}
Ok::<_, VmError>(())
})();
// 保存处理结果后先释放 upgrade 根,再传播处理错误,避免失败路径遗留临时强引用。
vm.release(object)?;
result?;
}
@@ -709,6 +751,7 @@ impl Checkpoint {
for (object, mount, mounted, version) in &self.states {
vm.replace_payload(*object, mount.clone())?;
for (name, value) in [("mounted", mounted), ("layoutVersion", version)] {
// 原属性存在则恢复旧值,不存在则 del_attr;已缺失可忽略,其余删除错误仍要传播。
if let Some(value) = value {
vm.set_attr(*object, name, value.clone())?;
} else {
@@ -730,6 +773,7 @@ impl Checkpoint {
*table = self.table.clone();
Ok(())
})();
// 恢复过程失败也要释放检查点根;先尝试两项操作,再按恢复错误优先的顺序返回。
let released = self.release(vm);
result?;
released
@@ -746,6 +790,7 @@ impl MountTable {
Err(error) => return Err(error),
};
let mut roots = Vec::new();
// 保留旧字典,避免准备阶段 desktop.mounts 换成新字典后旧出现提前回收,导致无法恢复。
if let Some(dictionary) = dictionary {
vm.retain(dictionary)?;
roots.push(dictionary);
@@ -759,6 +804,7 @@ impl MountTable {
let result = (|| {
for weak in self.ordered() {
if let Some(object) = vm.upgrade(weak)? {
// upgrade 已提供一个拥有根,直接记录待释放列表,不重复 retain;随后读取失败也会统一清理。
checkpoint.roots.push(object);
let mount = vm.payload::<Mount>(object, "Mount")?.clone();
let mut attributes = Vec::new();
@@ -768,6 +814,7 @@ impl MountTable {
Err(VmError::AttributeNotFound(_)) => None,
Err(error) => return Err(error),
};
// 公开属性理论上可能持有对象,快照保存 Value 本身不会自动增加 VM 根,须额外 retain。
if let Some(Value::Object(object)) = &value {
vm.retain(*object)?;
checkpoint.roots.push(*object);
@@ -784,6 +831,7 @@ impl MountTable {
}
Ok::<_, VmError>(())
})();
// 检查点创建到一半失败时释放已经取得的根,不返回一个不完整且可能泄漏的检查点。
if let Err(error) = result {
checkpoint.release(vm)?;
return Err(error);
@@ -811,6 +859,7 @@ impl MountTable {
result?;
}
}
// 故障退役不执行用户回调;将 desktop.mounts 换成空字典,再清除原生索引,撤销桌面拥有关系。
let dictionary = vm.new_dict()?;
let result = vm.set_attr(desktop, "mounts", Value::Object(dictionary));
vm.release(dictionary)?;
@@ -839,6 +888,7 @@ impl MountTable {
preparing: bool,
) -> Result<Option<ObjectRef>, VmError> {
let output = Arc::new(Mutex::new(HashMap::new()));
// 同步入口显式保活桌面与可选页面;旧表和节点表本身仍是弱索引,不增加隐式根。
let mut captures = vec![desktop];
captures.extend(page);
let function = vm.allocate(ContextNativeFunction::new(
@@ -855,9 +905,11 @@ impl MountTable {
},
captures,
))?;
// 先保存调用结果再释放同步入口,错误时同样清理;只有成功后才替换活动索引与顺序。
let result = vm.call(function, &[]);
vm.release(function)?;
let result = result?;
// 从共享输出移动弱表而不是克隆;生命周期驱动若存在则作为拥有结果交给调用方释放。
self.active = std::mem::take(
&mut *output
.lock()