merge: resolve manuscript conflicts with latest main comments
This commit is contained in:
+74
-10
@@ -33,6 +33,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
}
|
||||
let source = EndorReader::from_text(format!("{namespace} [submission {submission}]"), source);
|
||||
let plan = endor_script::parse(&source)?;
|
||||
// 各 Script 根共享 AST 计数预算,不能通过拆成很多交互片段绕过整份源码节点上限。
|
||||
let mut budget = AstBudget::default();
|
||||
for ast in plan.roots() {
|
||||
budget.visit_ast_root(ast)?;
|
||||
@@ -46,6 +47,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
candidate.roots.push(globals);
|
||||
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
|
||||
bridge.install_globals(&mut candidate.vm, globals)?;
|
||||
// Script 多段分别执行,指令总额按片段数均分;Module 作为整体获得完整预算,避免每段都重获一百万。
|
||||
let limits = match &plan {
|
||||
SourcePlan::Module(_) => LIMITS,
|
||||
SourcePlan::Script(_) => ExecutionLimits {
|
||||
@@ -67,6 +69,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
SourcePlan::Script(_) => bridge
|
||||
.rendered(&candidate.vm)?
|
||||
.ok_or_else(|| anyhow::anyhow!("script must call ui.page().render(root)"))?,
|
||||
// 模块先执行定义再调用 main;若 main 未显式 render,可将其返回值转换成展示根。
|
||||
SourcePlan::Module(_) => {
|
||||
let entry = candidate
|
||||
.vm
|
||||
@@ -88,6 +91,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
Some(root) => Ok(root),
|
||||
None => ui_bridge::snapshot(&candidate.vm, &value),
|
||||
});
|
||||
// 提取快照结果先暂存,成功或失败都释放 main 返回值的拥有根,再传播快照错误。
|
||||
candidate.vm.release_value(value)?;
|
||||
snapshot?
|
||||
}
|
||||
@@ -102,6 +106,7 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
document.validate()?;
|
||||
Ok(document)
|
||||
})();
|
||||
// 独立构建在成功与错误路径都显式释放宿主根/回收堆;返回成功文档也要求 cleanup 成功。
|
||||
let cleanup = candidate.close();
|
||||
match (result, cleanup) {
|
||||
(Ok(document), Ok(())) => Ok(document),
|
||||
@@ -117,6 +122,7 @@ pub fn evaluate(source: &str) -> Result<String> {
|
||||
bail!("expression exceeds the 1 MiB limit");
|
||||
}
|
||||
let source = EndorReader::from_text("console expression", source);
|
||||
// 隔离 evaluate 只接受一个表达式,默认编译选项不安装 ui 桥接,也不读已发布程序的 globals。
|
||||
let ast = frontend::parse_source_ast(&source, frontend::ParseMode::Expression)?;
|
||||
AstBudget::default().visit_ast_root(&ast)?;
|
||||
let compiled = compiler::compile_ast(&ast, &source, &compiler::CompileOptions::default())
|
||||
@@ -132,6 +138,7 @@ pub fn evaluate(source: &str) -> Result<String> {
|
||||
.vm
|
||||
.execute_with_limits(code, globals, LIMITS)
|
||||
.map_err(|error| runtime_error(&candidate.vm, error))?;
|
||||
// 只把标量或对象 repr 字符串交回 API,真实 Value 随一次性 VM 清理,不跨线程交付托管引用。
|
||||
let rendered = match &value {
|
||||
Value::Nil => "nil".to_owned(),
|
||||
Value::Bool(v) => v.to_string(),
|
||||
@@ -171,6 +178,7 @@ fn compile_plan_with_globals(
|
||||
// Match Aster module behavior for function forward references. Bindings are
|
||||
// added in source order; every executable statement still uses Aster's own
|
||||
// single-input Interactive compiler and the candidate's shared globals.
|
||||
// 先收集全部函数/类声明名以支持前向引用;普通绑定仍按源码执行次序逐段加入已知全局名。
|
||||
for root in plan.roots() {
|
||||
if let AstRoot::Interactive(input) = root {
|
||||
for statement in &input.statements {
|
||||
@@ -219,6 +227,7 @@ fn compile_plan_with_globals(
|
||||
compiler::compile_ast(root, source, &options)
|
||||
.map_err(|error| source.annotate(error))?,
|
||||
);
|
||||
// 每段编译成功才把绑定/赋值名字加入下一段编译上下文,语法与代码生成都继续委托 Aster。
|
||||
if let AstRoot::Interactive(input) = root {
|
||||
for statement in &input.statements {
|
||||
assigned(statement, &mut globals);
|
||||
@@ -240,6 +249,7 @@ struct PendingPaint {
|
||||
/// 跨 worker 轮次的全窗口刷新状态,保存已完成草稿和当前布局/绘制,直到稳定再发布。
|
||||
struct RefreshWork {
|
||||
// 已完成窗口的草稿先留在本轮;所有窗口收敛后才合成一次完整发布。
|
||||
// RefreshWork 先克隆最近完整文档作为草稿基线,各窗口更新暂存于此;全轮稳定前不写共享 NamespaceState。
|
||||
documents: std::collections::BTreeMap<u64, RenderDocument>,
|
||||
windows: std::collections::VecDeque<u64>,
|
||||
current: Option<u64>,
|
||||
@@ -271,6 +281,7 @@ pub struct ReplSession {
|
||||
ast_nodes: usize,
|
||||
source: String,
|
||||
nodes: Vec<CodeNode>,
|
||||
// 回调/渲染失败后置位,拒绝继续普通业务输入;保留画面不表示堆还能安全执行。
|
||||
faulted: bool,
|
||||
program_root: Option<CodeNode>,
|
||||
documents: std::collections::BTreeMap<u64, RenderDocument>,
|
||||
@@ -330,6 +341,7 @@ impl ReplSession {
|
||||
.into_iter()
|
||||
.collect();
|
||||
let document = runtime.refresh_after_mutation(Some(&viewports))?;
|
||||
// 初始刷新若已完成必须确实有 Page 文档才可接受候选;仍挂起则把整个运行时交 worker 下一量子继续。
|
||||
if !runtime.has_pending_refresh() {
|
||||
anyhow::ensure!(document.is_some(), "program did not publish a Page");
|
||||
runtime
|
||||
@@ -361,6 +373,7 @@ impl ReplSession {
|
||||
runtime
|
||||
.bridge
|
||||
.set_viewport(&mut runtime.candidate.vm, viewport)?;
|
||||
// 完整程序代码在候选自己的真实 globals 中执行,之后保留该堆用于事件与 Console,不通过重放历史恢复状态。
|
||||
let globals = runtime.candidate.globals.expect("program globals");
|
||||
let limits = if matches!(plan, SourcePlan::Script(_)) {
|
||||
ExecutionLimits {
|
||||
@@ -394,6 +407,7 @@ impl ReplSession {
|
||||
.vm
|
||||
.call_with_limits(main, &[], LIMITS)
|
||||
.map_err(|error| runtime_error(&runtime.candidate.vm, error))?;
|
||||
// main 已主动打开 Page 时尊重其选择;否则把返回值经展示协议打开,不能重复创建第二个默认页面。
|
||||
let opened = if runtime.bridge.has_page()? {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -407,6 +421,7 @@ impl ReplSession {
|
||||
}
|
||||
runtime.source = source.into();
|
||||
runtime.ast_nodes = budget.nodes;
|
||||
// 保存完整程序的 Sources 投影,后续 Console 追加时可移入交互记录树;不把 AST 投影当可执行堆对象。
|
||||
runtime.program_root = Some(architecture(&unit, &plan, namespace, submission));
|
||||
Ok(runtime)
|
||||
}
|
||||
@@ -420,7 +435,7 @@ impl ReplSession {
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
/// 构造本类型并初始化其状态;资源建立和默认字段以函数体为准。
|
||||
/// 建立真实持久 VM、全局字典与 UI 桥接根,尚未执行用户输入或产生窗口帧。
|
||||
pub fn new(id: u64) -> Result<Self> {
|
||||
let mut candidate = Candidate::new()?;
|
||||
let globals = candidate.vm.new_dict()?;
|
||||
@@ -474,6 +489,7 @@ impl ReplSession {
|
||||
if source.len() > MAX_SOURCE_BYTES {
|
||||
bail!("input exceeds 1 MiB");
|
||||
}
|
||||
// 持久 Console 限制累计输入次数、源码文本和稍后的 AST 总节点数,用户需显式重置才能重新获得预算。
|
||||
if self.inputs >= 256 || self.source.len() + source.len() + 80 > MAX_SOURCE_BYTES {
|
||||
bail!("console session exceeds 256 inputs or 1 MiB; reset the session to continue");
|
||||
}
|
||||
@@ -490,6 +506,7 @@ impl ReplSession {
|
||||
bail!("console session exceeds 10000 AST nodes; reset the session to continue");
|
||||
}
|
||||
let globals = self.candidate.globals.expect("live console globals");
|
||||
// 从实际 globals 枚举已有名称供增量编译,支持前次输入创建的真实对象,而非靠解析历史猜名称。
|
||||
let names = self
|
||||
.candidate
|
||||
.vm
|
||||
@@ -509,6 +526,7 @@ impl ReplSession {
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
// 解析/编译全部成功后才记本轮输入与源码;之后运行失败仍可能保留此前语句副作用,不做事务回滚。
|
||||
self.inputs += 1;
|
||||
self.ast_nodes += budget.nodes;
|
||||
if let Some(root) = self.program_root.take() {
|
||||
@@ -517,6 +535,7 @@ impl ReplSession {
|
||||
if !self.source.is_empty() && !self.source.ends_with('\n') {
|
||||
self.source.push('\n');
|
||||
}
|
||||
// 交互源码前加 Console input 注释分隔,投影节点行号再整体平移到累计 transcript 中。
|
||||
let offset = line_starts(&self.source).len();
|
||||
self.source
|
||||
.push_str(&format!("// Console input {}\n", self.inputs));
|
||||
@@ -549,6 +568,7 @@ impl ReplSession {
|
||||
self.candidate.vm.release(code)?;
|
||||
let value = executed?;
|
||||
// Keep the actual last result accessible as `_`, including unnamed UI objects.
|
||||
// 绑定/赋值语句展示其新变量实际值,普通表达式展示返回值;不是仅显示该语句执行的 Unit。
|
||||
let display = if let AstRoot::Interactive(input) = ast {
|
||||
match &input.statements[0].kind {
|
||||
StmtKind::Binding(binding) => self
|
||||
@@ -566,6 +586,7 @@ impl ReplSession {
|
||||
} else {
|
||||
value.clone()
|
||||
};
|
||||
// 先算 repr 并把实际最后值写入全局 _,保留未命名 UI 对象;随后释放 execute 返回根,错误也逐项传播。
|
||||
let repr = value_repr(&self.candidate.vm, &display);
|
||||
let retained =
|
||||
self.candidate
|
||||
@@ -588,6 +609,7 @@ impl ReplSession {
|
||||
input: self.inputs,
|
||||
})
|
||||
})();
|
||||
// 失败丢弃未发布展示请求和原生命令,保留已执行业务写入,并在代码投影上明确标记非事务语义。
|
||||
if result.is_err() {
|
||||
self.take_window_commands()?;
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
@@ -596,6 +618,7 @@ impl ReplSession {
|
||||
.push_str(" (error; earlier statements may remain live)");
|
||||
}
|
||||
}
|
||||
// 未完成只读续体仍持有临时结果,不在中途执行完整 reclaim;等刷新结束后再回收不可达宿主根。
|
||||
if !self.has_pending_refresh() {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
@@ -627,6 +650,7 @@ impl ReplSession {
|
||||
&mut self,
|
||||
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
|
||||
) -> Result<Option<RenderDocument>> {
|
||||
// 无增量视口参数的测试/同步入口排空状态机;worker 提供目标视口时只推进一次并记录重定向依据。
|
||||
let Some(viewports) = viewports else {
|
||||
return self.refresh_document();
|
||||
};
|
||||
@@ -654,6 +678,7 @@ impl ReplSession {
|
||||
|
||||
/// 推进一次刷新状态机,保存挂起的 Work;只有全窗口收敛时才生成可发布文档。
|
||||
fn poll_refresh(&mut self, record_yield: bool) -> Result<RefreshProgress> {
|
||||
// 从 self 取出工作以便可变推进,挂起时放回;首次从已发布各窗口文档克隆初始草稿。
|
||||
let mut work = self.refresh.take().unwrap_or_else(|| RefreshWork {
|
||||
documents: self.documents.clone(),
|
||||
windows: Default::default(),
|
||||
@@ -681,6 +706,7 @@ impl ReplSession {
|
||||
self.refresh = Some(work);
|
||||
Ok(RefreshProgress::Pending)
|
||||
}
|
||||
// 收敛后统一组合文档,再恢复主窗口选择;收尾失败也标故障,不把失败草稿当已发布帧。
|
||||
Ok(true) => {
|
||||
let result = self.finish_refresh(work);
|
||||
self.bridge.select_window(crate::window::MAIN_WINDOW)?;
|
||||
@@ -691,6 +717,8 @@ impl ReplSession {
|
||||
}
|
||||
Err(error) => {
|
||||
self.faulted = true;
|
||||
// 错误时必须显式取消 paint/layout 的 owning VM 续体并恢复检查点,不能仅丢弃 Rust 工作结构。
|
||||
// 进入 paint 后只恢复其原续体和配对文档,不重复布局,也不重跑输入业务语句。
|
||||
if let Some(paint) = work.paint.take() {
|
||||
self.bridge.cancel_paint_frame(
|
||||
&mut self.candidate.vm,
|
||||
@@ -711,6 +739,7 @@ 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();
|
||||
@@ -725,6 +754,7 @@ impl ReplSession {
|
||||
work.current = Some(id);
|
||||
return Ok(false);
|
||||
}
|
||||
// 任何窗口本轮生成新帧,就再扫描一轮检查依赖和挂载回调是否又引起变化,直到整轮无变化。
|
||||
if work.pass_changed {
|
||||
work.pass_start = true;
|
||||
return Ok(false);
|
||||
@@ -780,6 +810,7 @@ impl ReplSession {
|
||||
};
|
||||
document.frame.session = self.id;
|
||||
document.validate()?;
|
||||
// 跨所有窗口和稳定轮次累计布局工作,空帧也计一,防止持续无几何变化请求绕过收敛预算。
|
||||
work.work += document.frame.mounts.len().max(1);
|
||||
if work.work > 200_000 {
|
||||
bail!("layout dependencies did not stabilize within the rendering work budget");
|
||||
@@ -810,6 +841,7 @@ impl ReplSession {
|
||||
crate::source_paint::Progress::Complete(draft) => {
|
||||
document.frame = draft.frame;
|
||||
document.validate()?;
|
||||
// 只有整个绘制 Complete 且验证通过才替换当前窗口草稿;Pending 保留配对文档和 Work,不对 GUI 可见。
|
||||
work.documents.insert(id, document);
|
||||
work.pass_changed = true;
|
||||
work.changed = true;
|
||||
@@ -820,6 +852,7 @@ impl ReplSession {
|
||||
|
||||
/// 收敛后组合所有窗口文档,保留本轮完整结果;没有变化时不额外制造发布。
|
||||
fn finish_refresh(&mut self, mut work: RefreshWork) -> Result<Option<RenderDocument>> {
|
||||
// 收敛后完成已关闭窗口退役并删其旧文档;没有实际变化时不制造额外 revision。
|
||||
self.bridge.finish_closed(&mut self.candidate.vm)?;
|
||||
let ids = self.bridge.window_ids()?;
|
||||
work.documents.retain(|id, _| ids.contains(id));
|
||||
@@ -840,12 +873,14 @@ impl ReplSession {
|
||||
..Default::default()
|
||||
});
|
||||
main.source = self.source.clone();
|
||||
// 优先采用源码与当前 transcript 相同的窗口代码投影,避免主窗口未重绘时 Sources 仍展示旧输入树。
|
||||
main.root = work
|
||||
.documents
|
||||
.values()
|
||||
.find(|document| document.source == self.source)
|
||||
.and_then(|document| document.root.clone())
|
||||
.or(main.root);
|
||||
// 副窗口统一挂到主文档 windows 一层,子文档自身不再嵌套副窗口,最终 validate 检查完整跨线程值。
|
||||
main.windows = work
|
||||
.documents
|
||||
.iter()
|
||||
@@ -874,6 +909,7 @@ impl ReplSession {
|
||||
let Some(mut work) = self.refresh.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
// 记录实际取消了哪类续体用于诊断;已完成窗口草稿和已发生业务副作用不会因此回滚。
|
||||
let cancelled = work.pending.is_some();
|
||||
let cancelled_paint = work.paint.is_some();
|
||||
if let Some(paint) = work.paint.take()
|
||||
@@ -899,6 +935,7 @@ impl ReplSession {
|
||||
// Keep completed window drafts and callback effects. Only the pending
|
||||
// window's speculative Mount state was restored. A new external target
|
||||
// begins a fresh convergence budget, not a continuation of a bad cycle.
|
||||
// 重新从全窗口稳定轮开始,清当前选择/旧根并重置此次外部尺寸目标的收敛工作预算;草稿 documents 保留。
|
||||
work.windows.clear();
|
||||
work.current = None;
|
||||
work.root = None;
|
||||
@@ -919,6 +956,7 @@ impl ReplSession {
|
||||
if self.faulted {
|
||||
bail!("runtime stopped after a callback or rendering failure");
|
||||
}
|
||||
// 仅目标视口集合确实不同才取消重定向;同一目标的下一 worker 轮继续原续体,不重复从头布局。
|
||||
let retarget = self
|
||||
.refresh
|
||||
.as_ref()
|
||||
@@ -927,6 +965,7 @@ impl ReplSession {
|
||||
if retarget {
|
||||
self.retarget_refresh(viewports)?;
|
||||
}
|
||||
// 同目标 drain=true 同步排空旧刷新并保存完整结果;drain=false 只推进一量子,不能先执行新的尺寸变更。
|
||||
let previous = if self.has_pending_refresh() && !retarget {
|
||||
if drain {
|
||||
let result = self.refresh_document();
|
||||
@@ -939,6 +978,7 @@ impl ReplSession {
|
||||
};
|
||||
let ids = self.bridge.window_ids()?;
|
||||
let mut changed = false;
|
||||
// 仅更新桥接仍注册的窗口;旧 GUI 尺寸记录不应在新域里隐式创建窗口资源。
|
||||
for (id, viewport) in viewports {
|
||||
if ids.contains(id) {
|
||||
self.bridge.select_window(*id)?;
|
||||
@@ -948,6 +988,7 @@ impl ReplSession {
|
||||
}
|
||||
}
|
||||
self.bridge.select_window(crate::window::MAIN_WINDOW)?;
|
||||
// 尺寸没变且无挂起工作则直接返回先前已完成文档,避免制造无意义新帧。
|
||||
if !changed && !self.has_pending_refresh() {
|
||||
return Ok(previous);
|
||||
}
|
||||
@@ -1011,10 +1052,12 @@ impl ReplSession {
|
||||
&mut self,
|
||||
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
|
||||
) -> Result<Option<RenderDocument>> {
|
||||
// 异步回调不能插入只读布局/绘制续体中,即使后台邮箱已有结果也等刷新空闲边界。
|
||||
if self.has_pending_refresh() {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.faulted {
|
||||
// 故障域不执行任何新用户任务,仅取消已有任务并在确实移除工作后回收引用。
|
||||
if self.bridge.cancel_tasks(&mut self.candidate.vm)? > 0 {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
@@ -1023,6 +1066,7 @@ impl ReplSession {
|
||||
}
|
||||
let mut completed = false;
|
||||
let result = (|| {
|
||||
// worker 增量轮至多启动一个任务推进,给前台输入和窗口刷新公平机会;同步路径单轮允许64项。
|
||||
let limit = if viewports.is_some() { 1 } else { 64 };
|
||||
if self.bridge.poll_tasks(&mut self.candidate.vm, limit)? == 0 {
|
||||
return Ok(None);
|
||||
@@ -1036,6 +1080,7 @@ impl ReplSession {
|
||||
self.take_window_commands()?;
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
}
|
||||
// 任务推进或失败后才需回收,并且不能在仍有只读续体时清理其临时根。
|
||||
if (completed || result.is_err()) && !self.has_pending_refresh() {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
@@ -1092,6 +1137,7 @@ impl ReplSession {
|
||||
|
||||
/// 有界关闭任务、挂载和窗口,释放运行时根,并报告清理结果。
|
||||
pub fn shutdown(&mut self) -> Result<(usize, usize, usize)> {
|
||||
// 先取消视觉续体恢复挂载检查点,再判断原域是否允许正常关闭回调,随后标故障禁止后续普通执行。
|
||||
self.cancel_pending_refresh()?;
|
||||
let callbacks = !self.faulted;
|
||||
self.faulted = true;
|
||||
@@ -1104,6 +1150,7 @@ impl ReplSession {
|
||||
// This path is exclusively host cleanup after the domain has stopped.
|
||||
// No language functions, layout, paint or lifecycle hooks may run here.
|
||||
self.faulted = true;
|
||||
// 专用退役只清宿主资源,不调源生命周期;删除已缓存文档和窗口命令,避免后续重发该副窗口。
|
||||
self.bridge.retire_window(&mut self.candidate.vm, id)?;
|
||||
self.documents.remove(&id);
|
||||
let _ = self.take_window_commands()?;
|
||||
@@ -1151,12 +1198,14 @@ impl ReplSession {
|
||||
if self.faulted {
|
||||
bail!("runtime stopped after a callback or rendering failure");
|
||||
}
|
||||
// 即使绕过 HTTP 入口直接调用,也再校验会话身份;共享窗口数值 ID 不提供跨 VM 权限。
|
||||
if input.session != self.id {
|
||||
bail!("event belongs to another runtime session");
|
||||
}
|
||||
if !self.accepts_tab_drop(input) {
|
||||
bail!("drop targets an obsolete presentation");
|
||||
}
|
||||
// 将 ui.window/viewport 等隐式上下文切到事件所属窗口,分发后统一恢复主窗口。
|
||||
self.bridge.select_window(input.window)?;
|
||||
let result = (|| {
|
||||
self.bridge.dispatch(&mut self.candidate.vm, input)?;
|
||||
@@ -1176,6 +1225,7 @@ impl ReplSession {
|
||||
self.bridge.select_window(crate::window::MAIN_WINDOW)?;
|
||||
if result.is_err() {
|
||||
self.take_window_commands()?;
|
||||
// 回调失败属于共享 VM 故障,不只关闭单个按钮;丢弃未发布命令与 pending 请求,但不重放已执行写入。
|
||||
self.faulted = true;
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
}
|
||||
@@ -1188,8 +1238,9 @@ impl ReplSession {
|
||||
}
|
||||
|
||||
impl Drop for ReplSession {
|
||||
/// 在 Rust 所有者离开作用域时执行本类型的配套清理;不能用它代替需要报告错误的显式关闭。
|
||||
/// 析构兜底取消会话中未完成的布局/绘制续体;需要观察清理错误或运行退出钩子的路径仍须显式 shutdown。
|
||||
fn drop(&mut self) {
|
||||
// Drop 最后兜底取消未完成视觉工作,错误无法从析构返回;需要报告清理错误的路径必须显式 shutdown。
|
||||
let _ = self.cancel_pending_refresh();
|
||||
}
|
||||
}
|
||||
@@ -1232,9 +1283,11 @@ impl Candidate {
|
||||
|
||||
/// 释放候选拥有的宿主根并清理 VM;通过显式关闭保证错误也能被报告。
|
||||
fn close(&mut self) -> Result<()> {
|
||||
// 清全局字典先断业务对象可达根,再逆序释放宿主分配根;最后执行循环回收并验证对象计数归零。
|
||||
if let Some(globals) = self.globals.take() {
|
||||
self.vm.dict_clear(globals)?;
|
||||
}
|
||||
// pop 逐项移出确保再次 close 不重复释放已成功处理的根;错误仍交显式关闭调用方报告。
|
||||
while let Some(root) = self.roots.pop() {
|
||||
self.vm.release(root)?;
|
||||
}
|
||||
@@ -1247,16 +1300,16 @@ impl Candidate {
|
||||
}
|
||||
|
||||
impl Drop for Candidate {
|
||||
/// 在 Rust 所有者离开作用域时执行本类型的配套清理;不能用它代替需要报告错误的显式关闭。
|
||||
/// 析构调用 Candidate.close 释放候选根和 VM,覆盖提前返回/异常展开;析构不能向调用者报告清理错误。
|
||||
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.
|
||||
// 显式 close 可以报告引用计数/清理错误;Drop 则保证提前返回和异常展开仍经过最终清理边界。
|
||||
let _ = self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// 把 VM 错误与当前源位置/调用栈组合成用户可读的诊断。
|
||||
pub(crate) fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
|
||||
// 错误发生后立即读取 VM traceback,保留函数、源文件与指令偏移;无栈信息时直接保留原 VmError。
|
||||
let locations = vm
|
||||
.last_traceback()
|
||||
.iter()
|
||||
@@ -1286,6 +1339,7 @@ impl Visitor for AstBudget {
|
||||
type Error = anyhow::Error;
|
||||
/// 更新源结构遍历的深度/数量预算,拒绝超出允许范围的语法树。
|
||||
fn enter_node(&mut self, _span: Span) -> Result<()> {
|
||||
// 每次进入节点累计总数和当前深度;leave 只归还深度,整份输入总量不会因退出子树重置。
|
||||
self.depth += 1;
|
||||
self.nodes += 1;
|
||||
if self.depth > MAX_AST_DEPTH || self.nodes > MAX_AST_NODES {
|
||||
@@ -1306,6 +1360,7 @@ fn architecture(
|
||||
namespace: &str,
|
||||
submission: u64,
|
||||
) -> CodeNode {
|
||||
// CodeNode ID 由 namespace/submission 和本次递增序号构成,只是 Sources 投影身份,不是托管对象地址。
|
||||
let mut tree = Architecture {
|
||||
line_starts: line_starts(source.text()),
|
||||
next_id: 0,
|
||||
@@ -1327,6 +1382,7 @@ fn architecture(
|
||||
}
|
||||
}
|
||||
let roots = plan.roots();
|
||||
// 整体范围取首根起点至末根终点,Script 的多个交互片段在原始文本中的 span 已恢复偏移。
|
||||
let span = Span::new(
|
||||
roots.first().map_or(0, |root| root.span().start),
|
||||
roots.last().map_or(0, |root| root.span().end),
|
||||
@@ -1342,6 +1398,7 @@ fn architecture(
|
||||
/// 建立源文本每行起点表,供字节 span 转换为行列位置。
|
||||
fn line_starts(source: &str) -> Vec<usize> {
|
||||
let bytes = source.as_bytes();
|
||||
// 按字节扫描行终止符,CRLF 仅在 LF 记一次,孤立 CR 也换行;空文本仍保留第1行起点0。
|
||||
let mut starts = vec![0];
|
||||
for (offset, byte) in bytes.iter().enumerate() {
|
||||
if *byte == b'\n' || (*byte == b'\r' && bytes.get(offset + 1) != Some(&b'\n')) {
|
||||
@@ -1359,10 +1416,11 @@ struct Architecture {
|
||||
}
|
||||
|
||||
impl Architecture {
|
||||
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
|
||||
/// 分配本投影内节点 ID,并将半开字节 span 映射为1基起止行,组装 CodeNode。
|
||||
fn node(&mut self, name: String, kind: &str, span: Span, children: Vec<CodeNode>) -> CodeNode {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
// partition_point 返回不大于 offset 的行首数量,天然得到1基行号;span.end 是半开端,先减1找最后实际字符行。
|
||||
let line = |offset| self.line_starts.partition_point(|start| *start <= offset);
|
||||
CodeNode {
|
||||
id: format!("{}:ast-{id}", self.identity),
|
||||
@@ -1374,11 +1432,12 @@ impl Architecture {
|
||||
}
|
||||
}
|
||||
|
||||
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
|
||||
/// 区分函数与类声明;类下先投影字段,再投影方法。
|
||||
fn declaration(&mut self, declaration: &Decl) -> CodeNode {
|
||||
match &declaration.kind {
|
||||
DeclKind::Function(function) => self.function(function),
|
||||
DeclKind::Class(class) => {
|
||||
// 类投影先列字段再列方法;只复制显示名称和范围,不把声明 AST 当可执行对象保存。
|
||||
let mut children: Vec<_> = class
|
||||
.fields
|
||||
.iter()
|
||||
@@ -1390,8 +1449,9 @@ impl Architecture {
|
||||
}
|
||||
}
|
||||
|
||||
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
|
||||
/// 将函数声明及其体内语句投影为一个带源码范围的 function 节点。
|
||||
fn function(&mut self, function: &frontend::ast::Function) -> CodeNode {
|
||||
// 函数投影按函数体语句顺序递归展开,不单独生成参数节点;展示范围仍覆盖完整函数声明。
|
||||
let children = function
|
||||
.body
|
||||
.statements
|
||||
@@ -1406,7 +1466,7 @@ impl Architecture {
|
||||
)
|
||||
}
|
||||
|
||||
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
|
||||
/// 按赋值、返回、表达式和声明种类构建 Sources 层次,保留真实子表达式关系。
|
||||
fn statement(&mut self, statement: &Stmt) -> CodeNode {
|
||||
match &statement.kind {
|
||||
StmtKind::If(branch) => {
|
||||
@@ -1422,6 +1482,7 @@ impl Architecture {
|
||||
children.extend(loop_.body.statements.iter().map(|s| self.statement(s)));
|
||||
self.node("while".into(), "while", statement.span, children)
|
||||
}
|
||||
// 成员赋值投影两个子表达式:目标对象和右值,成员名作为本节点显示名称。
|
||||
StmtKind::MemberAssignment(assignment) => {
|
||||
let object = self.expression(&assignment.object);
|
||||
let value = self.expression(&assignment.value);
|
||||
@@ -1463,13 +1524,15 @@ impl Architecture {
|
||||
}
|
||||
}
|
||||
|
||||
/// 将相应语法结构投影为带源码范围的 CodeNode,供 Sources 展示和定位。
|
||||
/// 递归投影表达式层次,用简短文本作显示名,并保留完整原始 span。
|
||||
fn expression(&mut self, expr: &Expr) -> CodeNode {
|
||||
let (name, kind, children) = match &expr.kind {
|
||||
ExprKind::Name(name) => (name.clone(), "name", vec![]),
|
||||
ExprKind::Number(value) => (value.clone(), "number", vec![]),
|
||||
// 字符串展示名最多40个 Unicode 字符,但 span 保留整段字面量,截断标签不影响源码选择范围。
|
||||
ExprKind::String(value) => (value.chars().take(40).collect(), "string", vec![]),
|
||||
ExprKind::Symbol(name) => (name.text.clone(), "symbol", vec![]),
|
||||
// 当前代码投影把 Unary 和 Await 共用 unary/negate 显示标签;这是展示简化,不表示 await 执行成取负。
|
||||
ExprKind::Unary { operand, .. } | ExprKind::Await(operand) => {
|
||||
("negate".into(), "unary", vec![self.expression(operand)])
|
||||
}
|
||||
@@ -1482,6 +1545,7 @@ impl Architecture {
|
||||
(name.text.clone(), "member", vec![self.expression(object)])
|
||||
}
|
||||
ExprKind::Call { callee, arguments } => {
|
||||
// 调用目标作为首个孩子,随后按原顺序列实参,Sources 可以区分调用表达式和参数层次。
|
||||
let mut children = vec![self.expression(callee)];
|
||||
children.extend(arguments.iter().map(|expr| self.expression(expr)));
|
||||
("call".into(), "call", children)
|
||||
|
||||
Reference in New Issue
Block a user