docs: explain Tessera modules and execution flows in Chinese

This commit is contained in:
2026-11-11 23:36:03 +08:00
parent 4c3fc8b5dd
commit 1fedd21d3c
77 changed files with 1418 additions and 0 deletions
+78
View File
@@ -1,3 +1,7 @@
//! 把 Aster 编译/执行与 Tessera 展示生命周期连接起来。Candidate 拥有 VM 与宿主根,ReplSession 保留实际运行中的全局环境。
//! 完整源码 PUT 使用隔离候选;Console 输入则在已有 VM 上执行,先前发生的写入不等于可以回放或事务回滚。
//! 刷新状态机遍历窗口并逐步推进布局/绘制。完成所有必要轮次才形成文档;取消会释放挂起调用并恢复未提交的 Mount。
//!
//! Compile complete source in a fresh VM or retain a worker-owned Console VM.
//! Console retains mounted native references and publishes immutable frames after successful inputs.
use anyhow::{Result, bail};
@@ -22,6 +26,7 @@ const LIMITS: ExecutionLimits = ExecutionLimits {
const MAX_AST_NODES: usize = 10_000;
const MAX_AST_DEPTH: usize = 64;
/// 把源输入编译并执行为一次独立结果,最终将可展示对象转换为检查后的文档。
pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderDocument> {
if source.len() > MAX_SOURCE_BYTES {
bail!("source exceeds the 1 MiB limit");
@@ -106,6 +111,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
}
/// Evaluate exactly one expression in a disposable VM; never touch the published page.
/// 在隔离执行域求一个表达式结果;不会把结果作为持久 Console 环境发布。
pub fn evaluate(source: &str) -> Result<String> {
if source.len() > MAX_SOURCE_BYTES {
bail!("expression exceeds the 1 MiB limit");
@@ -143,6 +149,7 @@ pub fn evaluate(source: &str) -> Result<String> {
}
}
/// 按 Script/Module 计划编译各根节点,为后续执行准备可加载模板。
fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::CompiledCode>> {
compile_plan_with_globals(
source,
@@ -155,6 +162,7 @@ fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::
)
}
/// 结合已有全局信息编译本轮输入,保留持久 Console 的名称解析上下文。
fn compile_plan_with_globals(
source: &SourceUnit,
plan: &SourcePlan,
@@ -200,31 +208,39 @@ fn compile_plan_with_globals(
/// One real VM, owned only by the existing execution worker. No history replay.
/// The UI bridge shares the same managed object heap and publishes atomic frames.
/// 指定窗口尚未完成的绘制工作,文档与源续体必须保持配对。
struct PendingPaint {
window: u64,
document: RenderDocument,
work: Box<crate::source_paint::Work>,
}
/// 跨 worker 轮次的全窗口刷新状态,保存已完成草稿和当前布局/绘制,直到稳定再发布。
struct RefreshWork {
// 已完成窗口的草稿先留在本轮;所有窗口收敛后才合成一次完整发布。
documents: std::collections::BTreeMap<u64, RenderDocument>,
windows: std::collections::VecDeque<u64>,
current: Option<u64>,
root: Option<std::sync::Arc<crate::ui_bridge::UiNode>>,
// 续体必须保留其 owning VM;取消时显式关闭,不能靠丢弃 Rust 值。
pending: Option<Box<crate::ui_bridge::PendingLayout>>,
paint: Option<Box<PendingPaint>>,
// pass_changed 要求再跑一轮确认稳定,changed 记录整次刷新是否有可发布变化。
pass_start: bool,
pass_changed: bool,
changed: bool,
work: usize,
// 记录本轮尺寸目标,下一次 worker 轮次据此判断是否需要重定向。
viewports: Option<std::collections::BTreeMap<u64, crate::layout::Size>>,
}
/// 刷新仍在进行或已完成;完成也可能没有新文档需要发布。
enum RefreshProgress {
Pending,
Complete(Option<Box<RenderDocument>>),
}
/// 持久源运行时与其桥接会话,保存实际全局对象、代码投影、全窗口文档和挂起刷新。
pub struct ReplSession {
candidate: Candidate,
bridge: ui_bridge::UiBridge,
@@ -238,6 +254,7 @@ pub struct ReplSession {
documents: std::collections::BTreeMap<u64, RenderDocument>,
refresh: Option<RefreshWork>,
}
/// 一次 Console/事件操作的标量显示结果与可选完整文档,避免直接跨线程暴露托管返回值。
pub struct ReplResult {
pub value: String,
pub document: Option<RenderDocument>,
@@ -248,6 +265,7 @@ impl ReplSession {
/// Compile once into an isolated candidate, then keep its actual heap and
/// callback environments alive after the first successful publication.
#[cfg(test)]
/// 测试用同步装载入口:建立完整候选并排空初始刷新,返回真实运行时与完成文档。
pub fn load(
source: &str,
namespace: &str,
@@ -258,6 +276,7 @@ impl ReplSession {
}
#[cfg(test)]
/// 测试用同步装载入口:建立完整候选并排空初始刷新,返回真实运行时与完成文档。
pub fn load_with_viewport(
source: &str,
namespace: &str,
@@ -275,6 +294,7 @@ impl ReplSession {
Ok((runtime, document))
}
/// 建立可由 worker 分轮推进的完整源码候选,初始布局不必在一次调用里排空。
pub fn load_incremental(
source: &str,
namespace: &str,
@@ -297,6 +317,7 @@ impl ReplSession {
Ok((runtime, document))
}
/// 建立隔离候选、安装宿主根并执行完整源码;候选尚未完成布局时不替换活跃程序。
fn prepare_program(
source: &str,
namespace: &str,
@@ -368,6 +389,7 @@ impl ReplSession {
Ok(runtime)
}
/// 建立空的持久 Console 运行时,并安装当前逻辑视口输入。
pub fn new_with_viewport(id: u64, viewport: Option<crate::layout::Size>) -> Result<Self> {
let mut runtime = Self::new(id)?;
runtime
@@ -376,6 +398,7 @@ impl ReplSession {
Ok(runtime)
}
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
pub fn new(id: u64) -> Result<Self> {
let mut candidate = Candidate::new()?;
let globals = candidate.vm.new_dict()?;
@@ -398,10 +421,12 @@ impl ReplSession {
})
}
#[cfg(test)]
/// 同步执行一个 Console 输入并排空刷新,返回标量结果及可选新文档。
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
self.execute_mode(source, namespace, None)
}
/// 执行一次输入的业务部分,再让展示刷新以可恢复工作跨 worker 轮次推进。
pub fn execute_incremental(
&mut self,
source: &str,
@@ -411,6 +436,7 @@ impl ReplSession {
self.execute_mode(source, namespace, Some(viewports))
}
/// 在当前真实 VM 中编译并执行新输入,再按同步或分片模式刷新展示;已发生的业务写入不会被源重放回滚。
fn execute_mode(
&mut self,
source: &str,
@@ -555,14 +581,17 @@ impl ReplSession {
result
}
/// 查询调度器是否仍有需要主动推进的源协程工作。
pub fn has_cooperative_tasks(&self) -> bool {
self.bridge.has_cooperative_tasks()
}
/// 检查是否存在尚未结束的视觉刷新工作,决定能否接收新的业务变更。
pub fn has_pending_refresh(&self) -> bool {
self.refresh.is_some()
}
/// 拒绝在未完成的只读刷新内部再次进行业务变更,防止同一 VM 重入。
fn require_idle_refresh(&self) -> Result<()> {
anyhow::ensure!(
!self.has_pending_refresh(),
@@ -571,6 +600,7 @@ impl ReplSession {
Ok(())
}
/// 在业务变化后开始或继续展示刷新,保证后续输入不会进入未结束的只读视觉调用。
fn refresh_after_mutation(
&mut self,
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
@@ -588,6 +618,7 @@ impl ReplSession {
})
}
/// 同步排空当前刷新状态机,直到全窗口收敛或出现错误。
fn refresh_document(&mut self) -> Result<Option<RenderDocument>> {
loop {
match self.poll_refresh(false)? {
@@ -599,6 +630,7 @@ impl ReplSession {
}
}
/// 推进一次刷新状态机,保存挂起的 Work;只有全窗口收敛时才生成可发布文档。
fn poll_refresh(&mut self, record_yield: bool) -> Result<RefreshProgress> {
let mut work = self.refresh.take().unwrap_or_else(|| RefreshWork {
documents: self.documents.clone(),
@@ -654,7 +686,9 @@ impl ReplSession {
}
}
/// 执行一个刷新步骤:刷新绑定、选择窗口、准备快照、推进布局或绘制,并决定是否需要下一轮。
fn step_refresh(&mut self, work: &mut RefreshWork) -> Result<bool> {
// 阶段一:新一轮先刷新绑定,再取得稳定窗口遍历顺序。
if work.pass_start {
self.bridge.refresh_bindings(&mut self.candidate.vm)?;
work.windows = self.bridge.window_ids()?.into();
@@ -663,6 +697,7 @@ impl ReplSession {
work.pass_start = false;
return Ok(false);
}
// 阶段二:逐个选择窗口;一轮发生变化时再扫描一轮,直到依赖不再引起新帧。
let Some(id) = work.current else {
if let Some(id) = work.windows.pop_front() {
work.current = Some(id);
@@ -675,6 +710,7 @@ impl ReplSession {
return Ok(true);
};
self.bridge.select_window(id)?;
// 已进入 paint 的窗口直接恢复原绘制续体,不重放业务回调或布局。
if let Some(paint) = work.paint.take() {
let PendingPaint {
window,
@@ -686,6 +722,7 @@ impl ReplSession {
.resume_paint_frame(&mut self.candidate.vm, *paint_work)?;
return Self::accept_window_paint(work, window, document, progress);
}
// 阶段三:恢复旧布局,或在快照/依赖确实变化时建立新布局。
let progress = if let Some(pending) = work.pending.take() {
self.bridge
.resume_layout_frame(&mut self.candidate.vm, *pending)?
@@ -704,6 +741,7 @@ impl ReplSession {
}
crate::ui_bridge::LayoutProgress::Complete(frame) => *frame,
};
// 阶段四:几何完成后建立候选文档,再运行 paint;这里尚未向 GUI 发布。
let mut document = RenderDocument {
windows: Default::default(),
source: self.source.clone(),
@@ -732,6 +770,7 @@ impl ReplSession {
Self::accept_window_paint(work, id, document, progress)
}
/// 接收指定窗口的绘制进度,将挂起 Work 保留或把完整文档存入本轮结果。
fn accept_window_paint(
work: &mut RefreshWork,
id: u64,
@@ -757,6 +796,7 @@ impl ReplSession {
Ok(false)
}
/// 收敛后组合所有窗口文档,保留本轮完整结果;没有变化时不额外制造发布。
fn finish_refresh(&mut self, mut work: RefreshWork) -> Result<Option<RenderDocument>> {
self.bridge.finish_closed(&mut self.candidate.vm)?;
let ids = self.bridge.window_ids()?;
@@ -796,6 +836,7 @@ impl ReplSession {
}
#[cfg(test)]
/// 同步更新多个窗口尺寸,复用同一运行时并完成必要刷新。
pub fn resize_windows(
&mut self,
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
@@ -803,6 +844,7 @@ impl ReplSession {
self.resize_windows_incremental(viewports, true)
}
/// 用最新视口替换旧目标,显式取消未完成布局,同时保留已完成窗口结果和已发生的业务效果。
fn retarget_refresh(
&mut self,
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
@@ -846,6 +888,7 @@ impl ReplSession {
Ok(())
}
/// 把各窗口最新尺寸送入同一运行时;视口更新可跨轮次挂起,也可由调用方同步排空。
pub fn resize_windows_incremental(
&mut self,
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
@@ -900,6 +943,7 @@ impl ReplSession {
}
}
/// 在空闲轮次推进一个刷新步骤,完成时执行统一结果收尾。
fn advance_idle_refresh(&mut self) -> Result<Option<RenderDocument>> {
let result = self.poll_refresh(true).map(|progress| match progress {
RefreshProgress::Pending => None,
@@ -908,6 +952,7 @@ impl ReplSession {
self.finish_refresh_update(result)
}
/// 统一处理刷新失败、未发布状态清理和运行时引用回收。
fn finish_refresh_update(
&mut self,
result: Result<Option<RenderDocument>>,
@@ -925,11 +970,13 @@ impl ReplSession {
/// Deliver ready work on the owning VM worker, never from the GUI or a
/// provider thread. A failed callback stops the same shared fault domain.
/// 同步推进可交付任务和必要刷新,供不使用分片 worker 的调用方使用。
pub fn poll_tasks(&mut self) -> Result<Option<RenderDocument>> {
self.poll_tasks_mode(None)
}
/// Idle delivery starts at most one callback, then parks its layout work.
/// 按有界任务交付量推进,再以可挂起刷新处理变化。
pub fn poll_tasks_incremental(
&mut self,
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
@@ -937,6 +984,7 @@ impl ReplSession {
self.poll_tasks_mode(Some(viewports))
}
/// 按本轮预算交付已完成任务或推进协程,再对其业务变化执行相同的展示刷新流程。
fn poll_tasks_mode(
&mut self,
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
@@ -973,12 +1021,14 @@ impl ReplSession {
result
}
/// 取得本轮已稳定运行时的窗口命令,挂起刷新时禁止提前取走。
pub fn take_window_commands(&self) -> Result<Vec<crate::window::Command>> {
self.require_idle_refresh()?;
self.bridge.take_window_commands(&self.candidate.vm)
}
#[cfg(test)]
/// 测试用单窗口尺寸更新入口,遵循与原生尺寸发布相同的校验和刷新规则。
pub fn resize(
&mut self,
viewport: Option<crate::layout::Size>,
@@ -1000,6 +1050,7 @@ impl ReplSession {
result
}
/// 关闭尚未完成的刷新任务,释放续体并恢复未提交 Mount;不能只丢弃 Work 结构。
fn cancel_pending_refresh(&mut self) -> Result<()> {
if let Some(mut work) = self.refresh.take() {
if let Some(paint) = work.paint.take() {
@@ -1017,6 +1068,7 @@ impl ReplSession {
Ok(())
}
/// 有界关闭任务、挂载和窗口,释放运行时根,并报告清理结果。
pub fn shutdown(&mut self) -> Result<(usize, usize, usize)> {
self.cancel_pending_refresh()?;
let callbacks = !self.faulted;
@@ -1024,6 +1076,7 @@ impl ReplSession {
self.bridge.shutdown(&mut self.candidate.vm, callbacks)
}
/// 撤销指定窗口的运行时展示资源,防止后续刷新重新发布它。
pub fn retire_window(&mut self, id: u64) -> Result<()> {
self.require_idle_refresh()?;
// This path is exclusively host cleanup after the domain has stopped.
@@ -1036,23 +1089,28 @@ impl ReplSession {
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)
}
/// 查询当前运行时是否仍接受对应的窗口或拖放目标。
pub fn accepts_tab_drop(&self, input: &crate::events::Input) -> bool {
self.bridge.accepts_tab_drop(&self.candidate.vm, input)
}
/// 查询当前运行时是否仍接受对应的窗口或拖放目标。
pub fn accepts_window(&self, id: u64) -> bool {
self.bridge.accepts_window(id)
}
/// 报告该运行时是否已经停止正常业务执行,供 worker 选择故障清理路径。
pub fn is_faulted(&self) -> bool {
self.faulted
}
#[cfg(test)]
/// 同步分发一次已校验输入并完成展示刷新。
pub fn dispatch(&mut self, input: &crate::events::Input) -> Result<ReplResult> {
self.dispatch_mode(input, None)
}
/// 分发一次输入回调,再把视觉刷新交给 worker 分片推进。
pub fn dispatch_incremental(
&mut self,
input: &crate::events::Input,
@@ -1061,6 +1119,7 @@ impl ReplSession {
self.dispatch_mode(input, Some(viewports))
}
/// 在正确窗口上下文执行输入回调,再刷新展示;故障时停止受影响域并清理未完成工作。
fn dispatch_mode(
&mut self,
input: &crate::events::Input,
@@ -1107,11 +1166,13 @@ impl ReplSession {
}
impl Drop for ReplSession {
/// 在 Rust 所有者离开作用域时执行本类型的配套清理;不能用它代替需要报告错误的显式关闭。
fn drop(&mut self) {
let _ = self.cancel_pending_refresh();
}
}
/// 递归修正代码投影的源行号,使拼接输入仍可定位到原始文本。
fn shift_node_lines(node: &mut CodeNode, offset: usize) {
node.start_line += offset;
node.end_line += offset;
@@ -1119,6 +1180,7 @@ fn shift_node_lines(node: &mut CodeNode, offset: usize) {
shift_node_lines(child, offset);
}
}
/// 把 VM 返回值转换为 Console 的可显示表示,不让借用的托管引用跨线程。
fn value_repr(vm: &Vm, value: &Value) -> Result<String> {
Ok(match value {
Value::Nil => "nil".into(),
@@ -1129,6 +1191,7 @@ fn value_repr(vm: &Vm, value: &Value) -> Result<String> {
})
}
/// 拥有 VM、全局字典与宿主保留根;关闭时按顺序释放,失败也必须收尾。
struct Candidate {
vm: Vm,
roots: Vec<ObjectRef>,
@@ -1136,6 +1199,7 @@ struct Candidate {
}
impl Candidate {
/// 创建独立 VM,先不保留任何宿主根或全局字典;后续安装失败也由该候选负责清理。
fn new() -> Result<Self> {
Ok(Self {
vm: Vm::new()?,
@@ -1144,6 +1208,7 @@ impl Candidate {
})
}
/// 释放候选拥有的宿主根并清理 VM;通过显式关闭保证错误也能被报告。
fn close(&mut self) -> Result<()> {
if let Some(globals) = self.globals.take() {
self.vm.dict_clear(globals)?;
@@ -1160,6 +1225,7 @@ impl Candidate {
}
impl Drop for Candidate {
/// 在 Rust 所有者离开作用域时执行本类型的配套清理;不能用它代替需要报告错误的显式关闭。
fn drop(&mut self) {
// Explicit close reports accounting errors; dropping the fresh VM is
// also the final cleanup boundary on every early return or unwind.
@@ -1167,6 +1233,7 @@ impl Drop for Candidate {
}
}
/// 把 VM 错误与当前源位置/调用栈组合成用户可读的诊断。
pub(crate) fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
let locations = vm
.last_traceback()
@@ -1187,6 +1254,7 @@ pub(crate) fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
}
#[derive(Default)]
/// 编译前的语法节点数量/嵌套预算,限制输入结构复杂度。
struct AstBudget {
depth: usize,
nodes: usize,
@@ -1194,6 +1262,7 @@ struct AstBudget {
impl Visitor for AstBudget {
type Error = anyhow::Error;
/// 更新源结构遍历的深度/数量预算,拒绝超出允许范围的语法树。
fn enter_node(&mut self, _span: Span) -> Result<()> {
self.depth += 1;
self.nodes += 1;
@@ -1202,11 +1271,13 @@ impl Visitor for AstBudget {
}
Ok(())
}
/// 离开当前语法节点时归还嵌套深度;累计节点数保留,不能通过退出子树绕过总量预算。
fn leave_node(&mut self) {
self.depth -= 1;
}
}
/// 把输入语法结构转换为 Sources 工具使用的 CodeNode 层次,保存原始源码位置。
fn architecture(
source: &SourceUnit,
plan: &SourcePlan,
@@ -1246,6 +1317,7 @@ fn architecture(
tree.node(namespace.to_owned(), kind, span, children)
}
/// 建立源文本每行起点表,供字节 span 转换为行列位置。
fn line_starts(source: &str) -> Vec<usize> {
let bytes = source.as_bytes();
let mut starts = vec![0];
@@ -1257,6 +1329,7 @@ fn line_starts(source: &str) -> Vec<usize> {
starts
}
/// 构造 Sources 语法投影所需的源码与定位辅助状态。
struct Architecture {
line_starts: Vec<usize>,
next_id: usize,
@@ -1264,6 +1337,7 @@ struct Architecture {
}
impl Architecture {
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
fn node(&mut self, name: String, kind: &str, span: Span, children: Vec<CodeNode>) -> CodeNode {
let id = self.next_id;
self.next_id += 1;
@@ -1278,6 +1352,7 @@ impl Architecture {
}
}
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
fn declaration(&mut self, declaration: &Decl) -> CodeNode {
match &declaration.kind {
DeclKind::Function(function) => self.function(function),
@@ -1293,6 +1368,7 @@ impl Architecture {
}
}
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
fn function(&mut self, function: &frontend::ast::Function) -> CodeNode {
let children = function
.body
@@ -1308,6 +1384,7 @@ impl Architecture {
)
}
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
fn statement(&mut self, statement: &Stmt) -> CodeNode {
match &statement.kind {
StmtKind::MemberAssignment(assignment) => {
@@ -1351,6 +1428,7 @@ impl Architecture {
}
}
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
fn expression(&mut self, expr: &Expr) -> CodeNode {
let (name, kind, children) = match &expr.kind {
ExprKind::Name(name) => (name.clone(), "name", vec![]),