Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7217bbde97 |
Generated
+11
@@ -433,6 +433,16 @@ version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b"
|
||||
|
||||
[[package]]
|
||||
name = "endorphin-nexus-runtime"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"compiler",
|
||||
"core",
|
||||
"frontend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -1775,6 +1785,7 @@ dependencies = [
|
||||
"compiler",
|
||||
"core",
|
||||
"cosmic-text",
|
||||
"endorphin-nexus-runtime",
|
||||
"frontend",
|
||||
"objc2 0.5.2",
|
||||
"objc2-app-kit",
|
||||
|
||||
@@ -12,6 +12,8 @@ license = "MIT OR Apache-2.0"
|
||||
[dependencies]
|
||||
# 应用边界的错误聚合与上下文,保留底层失败原因。
|
||||
anyhow = "1.0"
|
||||
# 本地通用运行时库,由 Tessera 注册 UI 能力,暂不建立 Nexus 独立远程仓库。
|
||||
nexus = { package = "endorphin-nexus-runtime", path = "vendor/nexus" }
|
||||
# Aster 字节码编译器,把前端结果交给同一套 VM 执行。
|
||||
compiler = { path = "vendor/aster/crates/compiler" }
|
||||
# 系统字体发现、塑形与换行,用于测量和软件文字绘制。
|
||||
|
||||
@@ -22,6 +22,17 @@ experimental `namespace` / `export scene` / `render` parser has been removed.
|
||||
Host UI integration lives in Tessera; Aster needs no Tessera-specific changes.
|
||||
Lyra CLI and Hestia Server are independent hosts and are not application dependencies.
|
||||
|
||||
### Local Nexus extraction
|
||||
|
||||
The execution core now lives in the local Rust library [Nexus](vendor/nexus/README.md):
|
||||
Tessera → Nexus → Aster, in the same GUI process. Tessera registers UI capabilities
|
||||
through host interfaces. `vendor/nexus` is an ordinary local source directory,
|
||||
with no independent Git history or remote repository yet. See the
|
||||
[extraction boundaries and validation status](docs/architecture/nexus-extraction.md).
|
||||
Local verification passed: Nexus tests and Clippy, Tessera tests (190 passed; one
|
||||
optional performance benchmark ignored) and Clippy, and Aster's complete check script.
|
||||
HTTP tests require loopback-listener access and passed when rerun outside the restricted sandbox.
|
||||
|
||||
## Endor manuscript example
|
||||
|
||||
[illustrated-manuscript.endor](examples/illustrated-manuscript.endor) implements
|
||||
|
||||
@@ -23,6 +23,10 @@ UML 已渲染为普通 PNG 图片,直接嵌入各篇说明,不依赖 Mermaid
|
||||
|
||||
[放大组件图 SVG](uml/rendered/components.svg)
|
||||
|
||||
## 本地 Nexus 抽取
|
||||
|
||||
通用运行时现已在 `vendor/nexus` 作为 GUI 进程内 library 接入,宿主能力经接口注册。当前实现、仍属于 Tessera 的 worker/窗口发布适配,以及未执行的编译/运行回归见 [Nexus 抽取边界](nexus-extraction.md)。本页原有五目录说明和 UML 记录此前 Tessera 内部整理,新增边界以该抽取文档为准。
|
||||
|
||||
## 先抓住四个概念
|
||||
|
||||
1. **对象是程序状态**:共享内容留在 Aster 管理的对象堆内;切换标签不靠重放源码恢复对象。
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
| `src/system_ui/mod.rs` | [src/shell/system_ui/mod.rs](../../src/shell/system_ui/mod.rs) | 管理控件模块导出 |
|
||||
| `src/system_ui/theme.rs` | [src/shell/system_ui/theme.rs](../../src/shell/system_ui/theme.rs) | 管理表面颜色和主题 |
|
||||
| `src/system_ui/widgets.rs` | [src/shell/system_ui/widgets.rs](../../src/shell/system_ui/widgets.rs) | 宿主可复用控件绘制 |
|
||||
| `src/tabs.rs` | [src/shell/tabs.rs](../../src/shell/tabs.rs) | 共享标签绘制/命中、密集布局、滚动、拖放及动画 |
|
||||
| `src/tabs/hover.rs` | [src/shell/tabs/hover.rs](../../src/shell/tabs/hover.rs) | 标签、关闭和加号的颜色过渡 |
|
||||
| `src/tabs/motion.rs` | [src/shell/tabs/motion.rs](../../src/shell/tabs/motion.rs) | 标签布局动画及 hover 重绘期限 |
|
||||
| `src/tabs.rs` | [src/shell/tabs.rs](../../src/shell/tabs.rs) | 当前保留页面标签的不可变 ID/标题/选中状态投影;导航由 sidebar 绘制 |
|
||||
| `src/tabs/hover.rs` | 已删除 | 当前没有独立的旧标签 hover 动画模块 |
|
||||
| `src/tabs/motion.rs` | 已删除 | 当前没有独立的旧标签布局动画模块 |
|
||||
|
||||
## runtime
|
||||
|
||||
@@ -37,10 +37,10 @@
|
||||
| `src/api/tests.rs` | [src/runtime/api/tests.rs](../../src/runtime/api/tests.rs) | 保留原 API 测试;只调整嵌入示例路径,不执行测试 |
|
||||
| `src/endor_host.rs` | [src/runtime/endor_host.rs](../../src/runtime/endor_host.rs) | 候选/活跃 VM、编译执行、增量刷新、清理和诊断 |
|
||||
| `src/endor_host/tests.rs` | [src/runtime/endor_host/tests.rs](../../src/runtime/endor_host/tests.rs) | 保留原宿主测试;只调整嵌入示例路径,不执行测试 |
|
||||
| `src/endor_script.rs` | [src/runtime/endor_script.rs](../../src/runtime/endor_script.rs) | 组织 Aster Script/Module 输入及原始源码范围 |
|
||||
| `src/endor_script.rs` | [vendor/nexus/src/source.rs](../../vendor/nexus/src/source.rs) | 组织 Aster Script/Module 输入及原始源码范围 |
|
||||
| `src/event_dispatch.rs` | [src/runtime/event_dispatch.rs](../../src/runtime/event_dispatch.rs) | 托管事件、订阅和 capture/target/bubble 分发 |
|
||||
| `src/events.rs` | [src/runtime/events.rs](../../src/runtime/events.rs) | 原生输入的有界 loopback 传输 |
|
||||
| `src/io_tasks.rs` | [src/runtime/io_tasks.rs](../../src/runtime/io_tasks.rs) | 有界文件/HTTP provider、纯数据完成消息和取消 |
|
||||
| `src/io_tasks.rs` | [vendor/nexus/src/io_tasks.rs](../../vendor/nexus/src/io_tasks.rs) | 有界文件/HTTP provider、纯数据完成消息和取消 |
|
||||
| `src/tasks.rs` | [src/runtime/tasks.rs](../../src/runtime/tasks.rs) | 托管 Task、owner/key 取消和协作任务调度 |
|
||||
| `src/vm_sequence.rs` | [src/runtime/vm_sequence.rs](../../src/runtime/vm_sequence.rs) | 共享 VM 调用序列及同帧迭代驱动 |
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Nexus 本地抽取边界
|
||||
|
||||
目标依赖为 **Tessera → Nexus → Aster**。Nexus 是 GUI 进程内 Rust library,不是另起进程;Tessera 的 bridge 仍可显式使用同一版本的 Aster 类型。Tessera 通过 `HostRegistration` 向 Nexus 的 owning VM 注册 UI 能力,Nexus 不导入 Tessera 模块。
|
||||
|
||||
本地库暂放 `vendor/nexus`,包名 `endorphin-nexus-runtime`。它是普通源码目录,没有独立 Git 或远程仓库。后续是否建仓、所有者和可见性需用户另行授权。迁移在 Tessera 的独立工作分支上提交。
|
||||
|
||||
当前 Tessera 适配分支为 `codex/nexus-runtime`,从注释交付 `6d1ffdb` 建立,依赖 Tessera PR #10 与其引用的 Aster PR #3。经 Gitea 当前状态核对,两个注释 PR 均已合并;本次没有执行 PR 合并或向 main 推送。
|
||||
|
||||
## 已抽取
|
||||
|
||||
| 原实现 | Nexus 实现 | Tessera 保留的适配 |
|
||||
| --- | --- | --- |
|
||||
| `runtime/endor_script.rs` | `source.rs` | 调用方直接引用 Nexus;原 GUI 转发模块及无用别名已删除 |
|
||||
| `runtime/io_tasks.rs` | `io_tasks.rs` | 任务引擎直接使用 Nexus provider;原 GUI 转发模块及无用别名已删除 |
|
||||
| `runtime/vm_sequence.rs` | `vm_sequence.rs` | `FunctionHost` 适配桌面 Function 名义身份及 `<tessera>` 诊断来源 |
|
||||
| `endor_host::Candidate` 与错误映射 | `VmSession`、`runtime_error` | UI 会话借用同一 Aster VM,视觉刷新状态仍由 Tessera 持有 |
|
||||
| AST 预算、计划编译与 `evaluate` | `budget.rs`、`program.rs` | UI 编译前显式提供宿主全局名;隔离表达式不安装 UI |
|
||||
| `runtime/tasks.rs` 通用任务引擎 | `tasks.rs` | `TaskHost` 适配 owner 作用域、展示资格和 Task 类型;原 install/cancel_owner 签名保持不变 |
|
||||
| Console 计数、原文历史和来源 | `ConsoleHistory`、`AcceptedInput`;共享 `source::line_starts` | Tessera 只读历史建立 Sources 投影;接受凭据消费一次后进入真实 VM |
|
||||
| 完整程序准备与顶层执行 | `PreparedProgram`、`VmSession::execute_program` | 显式提供宿主名称,`main` 查找/调用与页面策略仍由 Tessera 决定;保留 Session/Execution 两种代码根生命周期 |
|
||||
| 宿主调用返回值清理 | `VmSession::with_call_result` | 在回调内解释返回值,刷新/展示返回错误也归还返回根 |
|
||||
| Console 输入准备与执行循环 | `console.rs` 的 `PreparedInput`、`VmSession::prepare_input/execute_input` | 先完整编译,再保留宿主清理、输入记录、代码投影、刷新、错误标注及发布的原次序 |
|
||||
| 新会话 UI 安装 | `HostRegistration` 调用协议 | `bridge/nexus_host.rs` 实现注册,领域类型/窗口能力仍由 Tessera 定义 |
|
||||
|
||||
搬移保留原有源码位置、预算值、指令顺序、根清理次序、I/O 线程池/租约与诊断文本。Cargo 使用相邻同一份 `vendor/aster`,不引入注册表的第二套语言实现。锁文件只新增本地包及其引用,没有升级已有依赖。
|
||||
|
||||
## Tessera 保留的宿主边界
|
||||
|
||||
| 模块 | 保留原因 | Nexus 接口 |
|
||||
| --- | --- | --- |
|
||||
| `runtime/api.rs` 与 `api/worker.rs` | 有界 HTTP/原生请求、回应端、submission/namespace、文档/窗口命令的一致发布;worker 线程组合这些宿主协议 | 通过 `endor_host` 使用 Nexus 会话,原子执行后只继续 UI 刷新;不另建通用语言队列 |
|
||||
| `runtime/api/guide.rs` | Tessera 的在线路由和 UI API 文档 | 不属于运行时内核 |
|
||||
| `runtime/events.rs` | 窗口/会话/布局版本/Mount 信封、原生手势合并和版本追随 | 不跨线程传递 VM 根 |
|
||||
| `runtime/event_dispatch.rs` | capture/target/bubble、Event/Subscription 和 Mount 路由等 UI 协议 | 复用 Nexus 调用序列,不另写解释器 |
|
||||
| `runtime/endor_host.rs` | UI 入口策略、代码树、布局/绘制续体、故障画面、文档和窗口生命周期 | 完整准备、输入历史、执行与 VM 根清理由 Nexus 负责;宿主经显式访问接口接入 |
|
||||
| `runtime/tasks.rs`、`vm_sequence.rs` | UI owner 的有效性和名义类型附着 | `TaskHost`、`FunctionHost` |
|
||||
|
||||
`api/worker.rs` 不直接使用 VM、代码模板装载或指令执行接口;其继续状态携带的是 Tessera 请求、UI 刷新元数据或独立候选。请求队列的容量、关闭优先级和发布复核继续在 Tessera,Nexus 不依赖 `tiny_http`、`winit`、NamespaceState 或窗口输入结构。
|
||||
|
||||
`ConsoleHistory` 统一持有累计次数、AST 总量、原文和输入来源;Sources 的 CodeNode 与发布文档仍由 Tessera 生成。接受凭据拥有准备结果,只能借用它生成投影并消费执行;输入失败后的历史和预算不回滚。原文本追加和 CRLF/CR 字节行索引在字段访问替换后与原实现逐 token 等价。宿主开始执行前的纯历史记录和原程序 CodeNode 转移现为两个相邻步骤,不改变业务执行或发布顺序。
|
||||
|
||||
## 交付边界
|
||||
|
||||
Tessera 的适配改动与 Nexus 源码一并保存在 `codex/nexus-runtime` 分支。Nexus 作为 Tessera 仓库内的 Rust 库交付。
|
||||
|
||||
源码复核中记录的既有行为问题保留为后续独立工作,不在本次迁移中夹带效果分析或 Scene3D 依赖算法改动。本次不声称所有潜在行为问题均已解决。
|
||||
|
||||
## 验证状态
|
||||
|
||||
源码分段和 I/O 按完整实现搬移;驱动引入宿主函数类型适配。任务引擎的 owner/key、协程、await、配额和取消顺序保留;三个 UI 策略函数逐 token 对照未变,通用引擎在还原显式宿主接口替换后逐 token 等价。`TaskHost` 不可藏有未 trace 的托管句柄,原生函数通过 captures 保活注册域;Scheduler 仅借用该域,宿主必须在释放域前停止使用调度器。为兼容现有诊断,任务 payload 的 `tessera-task` 类别文本暂保持原值。
|
||||
|
||||
持久执行循环、显示值转换和真实全局名称枚举在调整候选/输入字段访问后逐 token 等价。`PreparedInput` 私有字段保持原文、AST 与模板同源,消费后不能由该对象重复执行;它不携带 VM 根。模板也不携带目标堆根,提前在执行返回时释放编译准备数据不会释放已加载的代码/函数身份。宿主在准备和执行之间不得另行改动全局名称契约。库入口另外检查输入字节数,未初始化环境返回错误,累计预算使用饱和加法以拒绝异常大的外部计数。
|
||||
|
||||
完整程序的两种执行循环在代入代码根策略后分别与原路径逐 token 等价,宿主全局名称集合不变。`with_call_result` 额外修复宿主刷新/展示返回错误时可能跳过 main 返回根释放的路径;这项清理加强单独由析构可观察的回归覆盖,不作为纯搬移宣称等价。GUI 改用显式会话访问接口的前后整文件 token 对照,在还原 accessor 和十处回收闭包后通过。
|
||||
|
||||
原同帧循环回归随实现进入 Nexus;新增无 UI 宿主测试覆盖注册、部分安装失败的资源清理、脚本跨片全局和原文跨度。另有 `tests/tasks.rs` 使用普通对象宿主覆盖同 key 替换、真实回调次数、资格撤销、终态作用域清理和退出门闩。`tests/console.rs` 覆盖持久全局/函数身份、编译失败无副作用、运行失败保留先前写入和预算拒绝。`tests/program.rs` 覆盖两种代码根策略、装载不隐式调用入口、失败写入和宿主错误返回根清理。`tests/history.rs` 覆盖接受/失败历史、256 次输入、累计 AST、完整源码字节预算及 Unicode/CRLF/CR 位置。
|
||||
|
||||
2026-11-15 用户明确授权本次本机编译和测试,已执行:
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| Nexus `cargo test --offline --manifest-path vendor/nexus/Cargo.toml` | 14 个集成测试、1 个单元测试通过 |
|
||||
| Nexus `cargo clippy --offline --manifest-path vendor/nexus/Cargo.toml --all-targets -- -D warnings` | 通过 |
|
||||
| Tessera `cargo test --offline --locked` | 179 通过、11 个 HTTP 用例受沙箱端口权限限制失败、1 个可选基准忽略 |
|
||||
| Tessera HTTP 组允许回环网络后重跑 | 16/16 通过;与首轮合并覆盖全部 190 个常规测试 |
|
||||
| Tessera `cargo clippy --offline --locked --all-targets -- -D warnings` | 通过 |
|
||||
| Aster `CARGO_NET_OFFLINE=true sh scripts/check.sh` | 生成器一致性、4 个 Python 回归、Rust/PEG 格式、workspace 测试/文档测试及全部目标 Clippy 均通过 |
|
||||
|
||||
首次联网依赖解析因 DNS 失败,随后使用本机缓存完成离线编译。Tessera 首次测试编译发现测试转发器缺少显式 `VmError` 导入,补齐后编译和回归通过。实际执行结果不包含手动操作原生 GUI、可选性能基准或分发打包;示例、绘制像素、任务、窗口和输入协议由现有集成回归覆盖。
|
||||
@@ -10,7 +10,7 @@
|
||||
4. [桥接层](../src/bridge/ui_bridge.rs)、[Block](../src/model/block.rs) 与 [Mount](../src/model/mount.rs):区分共享业务对象、每次出现和展示事务。
|
||||
5. [快照](../src/model/snapshot.rs)、[源布局](../src/render/source_layout.rs) 和 [源绘制](../src/render/source_paint.rs):理解依赖缓存、只读执行及挂起工作。
|
||||
6. [二维视口](../src/render/viewport.rs)、[3D](../src/render/scene3d.rs) 和 [面板映射](../src/render/scene3d/panel.rs):理解布局/世界/视图的边界。
|
||||
7. [任务](../src/runtime/tasks.rs)、[provider](../src/runtime/io_tasks.rs) 和 [事件传播](../src/runtime/event_dispatch.rs):理解异步交付资格与生命周期。
|
||||
7. [任务](../src/runtime/tasks.rs)、[provider](../vendor/nexus/src/io_tasks.rs) 和 [事件传播](../src/runtime/event_dispatch.rs):理解异步交付资格与生命周期。
|
||||
|
||||
## 阅读时需要保留的边界
|
||||
|
||||
@@ -74,10 +74,10 @@
|
||||
| [src/runtime/api/worker.rs](../src/runtime/api/worker.rs) | 唯一串行执行 VM 的 API worker。保留活跃运行时,另建 PUT 候选,并在候选完整成功后切换发布。 |
|
||||
| [src/runtime/endor_host.rs](../src/runtime/endor_host.rs) | 把 Aster 编译/执行与 Tessera 展示生命周期连接起来。Candidate 拥有 VM 与宿主根,ReplSession 保留实际运行中的全局环境。 |
|
||||
| [src/runtime/endor_host/tests.rs](../src/runtime/endor_host/tests.rs) | 说明全部运行时测试和辅助函数的场景/断言,并解释新主线性能基准的 DPI 分组、预热、三类计时边界和统计方式。 |
|
||||
| [src/runtime/endor_script.rs](../src/runtime/endor_script.rs) | 区分完整 Module 与顶层 Script,并保留输入源码位置。 |
|
||||
| [vendor/nexus/src/source.rs](../vendor/nexus/src/source.rs) | 区分完整 Module 与顶层 Script,并保留输入源码位置。 |
|
||||
| [src/runtime/event_dispatch.rs](../src/runtime/event_dispatch.rs) | 托管事件与订阅的传播实现。Connection 持有回调引用,Event 保存目标、阶段与停止传播状态。 |
|
||||
| [src/runtime/events.rs](../src/runtime/events.rs) | 原生窗口输入到执行 worker 的纯数据传输。Input 只含窗口/会话/版本/Mount 身份及有限坐标。 |
|
||||
| [src/runtime/io_tasks.rs](../src/runtime/io_tasks.rs) | 后台文件/网络 provider。线程池只携带纯数据、取消控制与弱 Task 身份,不持有 VM。 |
|
||||
| [vendor/nexus/src/io_tasks.rs](../vendor/nexus/src/io_tasks.rs) | 后台文件/网络 provider。线程池只携带纯数据、取消控制与弱 Task 身份,不持有 VM。 |
|
||||
| [src/runtime/mod.rs](../src/runtime/mod.rs) | 运行时模块入口。VM 生命周期、API、源程序组织、事件与异步任务在这里组合。 |
|
||||
| [src/runtime/tasks.rs](../src/runtime/tasks.rs) | owner/key 管理的异步任务与协作式源函数调度。弱索引用于查找,回调、等待对象和协程帧是托管图中的真实边。 |
|
||||
| [src/runtime/vm_sequence.rs](../src/runtime/vm_sequence.rs) | 构造共享 VM 调用序列与同帧循环驱动的字节码。 |
|
||||
@@ -171,3 +171,7 @@
|
||||
- 对工具脚本使用 `node --check` 和 `sh -n`,只检查语法,不执行渲染、构建或打包;Cargo 配置另以 TOML 解析核对。
|
||||
- 检查固定行号的示例夹具、测试依赖的源码替换片段和 `git diff --check`。这些检查能证明注释外代码保持一致及语法可解析,不能替代运行时回归结果。
|
||||
- 本次未执行编译、GUI 回归、Clippy 或 rustdoc;需要构建的验证应在用户已确认的远程 runner 上运行,不能把未执行步骤写成通过。实际交付结果记录在 PR 中。
|
||||
|
||||
## Nexus 本地抽取后的注释入口
|
||||
|
||||
通用实现与调用关系已转到 [Nexus 源码导航](../vendor/nexus/README.md):`source`、`program`、`console`、`session`、`budget`、`tasks`、`io_tasks` 和 `vm_sequence`。Tessera 保留 UI 宿主策略及刷新/发布。原 `runtime/endor_script.rs`、`runtime/io_tasks.rs` 转发入口已删除;迁移细节与待运行的回归见 [抽取边界](architecture/nexus-extraction.md)。
|
||||
|
||||
+7
-6
@@ -9,11 +9,13 @@
|
||||
| 目录 | 责任 |
|
||||
| --- | --- |
|
||||
| `shell/` | 原生工作区、窗口输入、标签、开发工具和独立宿主管理控件 |
|
||||
| `runtime/` | 本机 API、串行 VM 执行、事件和异步任务 |
|
||||
| `runtime/` | Tessera 运行时适配:本机 API/worker、UI 输入与发布;通用执行由 Nexus 提供 |
|
||||
| `model/` | 托管对象、绑定、Mount、窗口语义、依赖与发布值 |
|
||||
| `render/` | 几何、布局、source/native 视觉协议、绘制、命中、字体和软件渲染 |
|
||||
| `bridge/` | Endor 类型/方法与宿主能力及展示刷新之间的连接 |
|
||||
|
||||
通用源码、编译、Console 历史/预算、VM 根、任务和驱动实现见 [本地 Nexus](../vendor/nexus/README.md);[抽取边界](../docs/architecture/nexus-extraction.md)区分实现接入与尚未执行的编译/回归。
|
||||
|
||||
## shell
|
||||
|
||||
| 模块 | 职责 |
|
||||
@@ -33,13 +35,11 @@
|
||||
| 模块 | 职责 |
|
||||
| --- | --- |
|
||||
| [api](runtime/api.rs) | HTTP 请求路由、队列、请求观察和响应;worker/指南拆为子模块 |
|
||||
| [endor_host](runtime/endor_host.rs) | 候选/活跃 VM、编译执行、增量刷新、清理和诊断 |
|
||||
| [endor_script](runtime/endor_script.rs) | 组织 Aster Script/Module 输入及原始源码范围 |
|
||||
| [endor_host](runtime/endor_host.rs) | 组合 Nexus 会话与 Tessera UI 桥接,维护代码投影、增量刷新和发布 |
|
||||
| [events](runtime/events.rs) | 原生输入的有界 loopback 传输 |
|
||||
| [event_dispatch](runtime/event_dispatch.rs) | 托管事件、订阅和 capture/target/bubble 分发 |
|
||||
| [io_tasks](runtime/io_tasks.rs) | 有界文件/HTTP provider、纯数据完成消息和取消 |
|
||||
| [tasks](runtime/tasks.rs) | 托管 Task、owner/key 取消和协作任务调度 |
|
||||
| [vm_sequence](runtime/vm_sequence.rs) | 共享 VM 调用序列及同帧迭代驱动 |
|
||||
| [tasks](runtime/tasks.rs) | 为 Nexus 任务引擎提供 UI owner 作用域、窗口/页面资格和 Task 类型 |
|
||||
| [vm_sequence](runtime/vm_sequence.rs) | 为 Nexus 的共享调用驱动附着 Tessera Function 名义类型 |
|
||||
|
||||
## model
|
||||
|
||||
@@ -76,6 +76,7 @@
|
||||
|
||||
| 模块 | 职责 |
|
||||
| --- | --- |
|
||||
| [nexus_host](bridge/nexus_host.rs) | 向 Nexus 的真实 VM 注册 UI 领域类型与全局能力 |
|
||||
| [ui_bridge](bridge/ui_bridge.rs) | Endor 宿主类型、窗口展示会话、布局/绘制发布协调 |
|
||||
|
||||
## 主要入口和运行约束
|
||||
|
||||
@@ -319,7 +319,7 @@ impl NativeCallable for Function {
|
||||
Value::Object(resource)
|
||||
}
|
||||
ReadText => {
|
||||
// 同步读取小型资源文本供模型初始化使用;后台异步读取仍走 runtime/io_tasks 的接口。
|
||||
// 同步读取小型资源文本供模型初始化使用;后台异步读取由 Nexus io_tasks 的 provider 和任务引擎处理。
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid("load resources outside paint/layout"));
|
||||
}
|
||||
|
||||
@@ -8,3 +8,6 @@ pub(crate) mod ui_bridge;
|
||||
/// 注册图片、字体、文字流与避让形状能力,并把托管绘制参数解码为可跨线程使用的不可变资源。
|
||||
/// ui_bridge 安装时调用注册入口,source_paint 解码 image 命令时复用图像检查。
|
||||
pub(crate) mod graphics;
|
||||
|
||||
/// 实现 Nexus 宿主注册协议,把 Tessera UI 类型与全局能力安装到同一 VM。
|
||||
pub(crate) mod nexus_host;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! Tessera 向 Nexus 注册 UI 能力的唯一生产安装适配器;Nexus 不引用本模块或 UiBridge。
|
||||
use anyhow::Result;
|
||||
use endor_core::{ObjectRef, Vm};
|
||||
|
||||
/// 每个新会话安装一份 UI 类型/方法域,实际根交给 Nexus 会话统一持有和清理。
|
||||
pub(crate) struct UiHost;
|
||||
|
||||
impl nexus::HostRegistration for UiHost {
|
||||
type Installed = super::ui_bridge::UiBridge;
|
||||
|
||||
/// Nexus 在已建立 globals 的 owning VM 上调用;失败由会话 Drop 清理半完成安装根。
|
||||
fn register(
|
||||
&self,
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
globals: ObjectRef,
|
||||
) -> Result<Self::Installed> {
|
||||
// 类型、原生方法、任务域仍由 Tessera 定义,不把其 UI 规则移入通用库。
|
||||
let bridge = super::ui_bridge::install(vm, roots)?;
|
||||
// 全局别名引用刚安装的同一批名义对象,不为每条脚本重新创建类型域。
|
||||
bridge.install_globals(vm, globals)?;
|
||||
Ok(bridge)
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -21,9 +21,7 @@ pub(crate) use render::{
|
||||
box_model, display_list, geometry, layout, native_visual, page, scene, scene3d, scroll,
|
||||
software_renderer, source_hit, source_layout, source_paint, text, viewport,
|
||||
};
|
||||
pub(crate) use runtime::{
|
||||
api, endor_host, endor_script, event_dispatch, events, io_tasks, tasks, vm_sequence,
|
||||
};
|
||||
pub(crate) use runtime::{api, endor_host, event_dispatch, events, tasks, vm_sequence};
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) use shell::native_chrome;
|
||||
pub(crate) use shell::{
|
||||
|
||||
+151
-573
File diff suppressed because it is too large
Load Diff
+224
-182
File diff suppressed because it is too large
Load Diff
+4
-7
@@ -1,22 +1,19 @@
|
||||
//! 运行时模块入口。VM 生命周期、API、源程序组织、事件与异步任务在这里组合。
|
||||
//! main 调用 api::start 建立服务;worker 通过 endor_host 操作所属 VM,events 客户端将原生输入排队交付。
|
||||
//! 任务后台只完成纯数据 I/O,结果是否仍可交付以及如何回到源回调,由串行运行时检查和推进。
|
||||
//! 通用源码/编译、持久输入执行、VM 根清理、任务、I/O 和驱动实现逐步移入 Nexus;这里保留应用组合与兼容适配路径。
|
||||
//!
|
||||
// 目录确定模块归属;main 中的 crate 根别名保持内部调用路径稳定。
|
||||
/// 提供 HTTP 路由、有界请求队列与串行 worker,协调候选 VM 和已发布 namespace。
|
||||
pub(crate) mod api;
|
||||
/// 拥有真实 Aster VM 会话,组合源执行、增量刷新、事件、任务和资源清理。
|
||||
/// 通过 Nexus VmSession 持有真实 Aster VM,适配 UI 源执行、增量刷新、事件、任务和资源清理。
|
||||
pub(crate) mod endor_host;
|
||||
/// 识别并组织 Endor 源输入,保留原始诊断位置,支持脚本和兼容入口形式。
|
||||
pub(crate) mod endor_script;
|
||||
/// 在 VM 中执行捕获/目标/冒泡路由,处理监听器断开、传播停止与事件结果。
|
||||
/// 监听器错误会中断序列;末尾 Finish 是正常路径步骤,不是确保异常后仍运行的 finally。
|
||||
pub(crate) mod event_dispatch;
|
||||
/// 定义原生输入信封与有界客户端,将窗口输入送往运行时而不跨线程调用源函数。
|
||||
pub(crate) mod events;
|
||||
/// 执行后台文件/HTTP 文本读取,使用租约拒绝取消后的交付;后台不操作 VM 对象。
|
||||
pub(crate) mod io_tasks;
|
||||
/// 维护 owner/key 任务身份、定时器、协作执行与 await 依赖,统一处理替换和取消。
|
||||
/// 为 Nexus 任务引擎适配 UI owner 作用域、窗口页面资格及 Task 类型,保留原安装/取消入口。
|
||||
pub(crate) mod tasks;
|
||||
/// 封装可恢复 VM 工作的推进次序,使源布局/绘制在预算内保留同一续体而不重放。
|
||||
/// 为 Nexus 的调用序列驱动适配桌面 Function 类型,使布局/绘制保留同一续体而不重放。
|
||||
pub(crate) mod vm_sequence;
|
||||
|
||||
+41
-1185
File diff suppressed because it is too large
Load Diff
+32
-211
@@ -1,93 +1,42 @@
|
||||
//! 构造共享 VM 调用序列与同帧循环驱动的字节码。
|
||||
//! 用托管函数串联步骤,避免为每个布局节点反复创建独立解释器调用;重复驱动会保留同一个执行帧和预算域。
|
||||
//!
|
||||
//! mount::synchronize 与 event_dispatch::dispatch 用 build 串起生命周期/事件回调。
|
||||
//! source_layout/source_paint 用 repeat_call 循环推进出现位置,并用 collect_and_continue 收集单次源调用结果。
|
||||
//! 本模块只生成驱动字节码和托管函数,不在 Rust 中自行解释语句,也不替调用方重置 VM 预算。
|
||||
//! 原生调用返回 Invoke 后,VM 在既有帧循环中执行驱动,因此可挂起工作仍有明确的 owning VM。
|
||||
//! build 串联的是普通调用序列,任一步报错便中断后续步骤;末项不是 finally,错误时临时根/检查点仍须由所属工作收尾路径释放。
|
||||
use endor_core::{
|
||||
CodeLayout, EndorCode, EndorCodeObject, Instruction, NativeContext, ObjectRef, Opcode, Value,
|
||||
VmError,
|
||||
};
|
||||
//! Tessera 的 Nexus 驱动适配:保留原调用签名,桌面 Function 绑定仍由 UI bridge 执行。
|
||||
use endor_core::{NativeContext, ObjectRef, Value, VmError};
|
||||
|
||||
/// 将零参数调用列表编成一个托管驱动,按输入顺序执行,返回最后一次调用的值。
|
||||
/// 空列表返回 Nil。所有调用都在调用者的 VM 预算内运行,避免宿主逐个调用时重置预算。
|
||||
/// name 用于诊断位置;desktop 用来给生成函数挂接桌面 Function 类型。
|
||||
/// 调用者是 Mount 生命周期同步和事件路由;返回值是驱动函数身份,不是已经执行完的最后结果。
|
||||
/// 只在同步驱动构造期间借用 desktop,实际生成函数由其名义类型边保活领域定义。
|
||||
struct DesktopFunctions(ObjectRef);
|
||||
impl nexus::vm_sequence::FunctionHost for DesktopFunctions {
|
||||
/// Nexus 在驱动创建后调用,保持原先类型附着和错误传播顺序。
|
||||
fn attach_function(
|
||||
&self,
|
||||
cx: &mut NativeContext<'_>,
|
||||
function: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
crate::ui_bridge::attach_desktop_type(cx, function, "Function", self.0)
|
||||
}
|
||||
/// 保持既有 Tessera 原生驱动回溯标签,移动实现不改变诊断来源。
|
||||
fn source_name(&self) -> &'static str {
|
||||
"<tessera>"
|
||||
}
|
||||
}
|
||||
|
||||
/// Mount/事件适配调用;通用序列指令及根关系由 Nexus 生成,不重置 VM 执行预算。
|
||||
pub fn build(
|
||||
cx: &mut NativeContext<'_>,
|
||||
calls: Vec<ObjectRef>,
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 每个函数放入常量池。LoadConst/PushNull/Call 组成零参数调用,
|
||||
// 中间结果由 PopTop 丢弃;最后结果留在栈顶交给 ReturnValue。
|
||||
// 每个中间调用至多四条指令,额外空间覆盖空序列和 ReturnValue;只是预留容量,不是指令预算。
|
||||
let mut instructions = Vec::with_capacity(calls.len() * 4 + 2);
|
||||
// 常量池强持有每个 callable,驱动存活期间不依赖调用方的 Rust Vec 保活。
|
||||
let mut constants: Vec<Value> = calls.into_iter().map(Value::Object).collect();
|
||||
for index in 0..constants.len() {
|
||||
// LoadConst 放函数,PushNull 建立 VM Call 所需前缀,Call 0 执行无显式实参的回调。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32));
|
||||
instructions.push(Instruction::simple(Opcode::PushNull));
|
||||
instructions.push(Instruction::new(Opcode::Call, 0));
|
||||
if index + 1 != constants.len() {
|
||||
// 只丢中间结果,避免把最后一个结果也弹掉而让 ReturnValue 面对空栈。
|
||||
instructions.push(Instruction::simple(Opcode::PopTop));
|
||||
}
|
||||
}
|
||||
// 没有调用时也必须给 ReturnValue 提供合法栈顶,不能返回一个空栈。
|
||||
if constants.is_empty() {
|
||||
constants.push(Value::Nil);
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
}
|
||||
instructions.push(Instruction::simple(Opcode::ReturnValue));
|
||||
// 编码阶段校验字节码布局,诊断位置使用宿主 name 而不是伪造用户源码行列。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, "<tessera>", 1);
|
||||
// NativeContext 暂持代码根,输出函数会通过托管边继续拥有代码与常量。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 驱动只读取常量,无需共享用户字典,空私有 globals 不污染 REPL 或主模块。
|
||||
let globals = cx.new_dict()?;
|
||||
// 函数作为本次原生调用的输出被提升,其余临时拥有根由 NativeContext 退出时释放。
|
||||
let driver = cx.new_function(name, code, globals)?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, driver, "Function", desktop)?;
|
||||
Ok(driver)
|
||||
nexus::vm_sequence::build(cx, calls, name, &DesktopFunctions(desktop))
|
||||
}
|
||||
|
||||
/// source_layout/source_paint 安装一轮出现遍历时调用,生成固定大小的重复驱动,不按节点数展开字节码。
|
||||
/// callback 每次返回 Bool,false 退出;同帧回跳让所有出现和委托源函数共用当前 VM 的执行预算。
|
||||
/// 源布局/绘制适配调用,生成固定大小、同一帧回跳的重复驱动。
|
||||
pub fn repeat_call(
|
||||
cx: &mut NativeContext<'_>,
|
||||
callback: ObjectRef,
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 内部 Advance 回调约定返回 Bool;repeat_while 生成的是 VM 真值条件跳转,不额外验证返回值必须是 Bool。
|
||||
// 退出后显式返回 Nil,回调的继续条件不会泄露为驱动返回值。
|
||||
let mut instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
];
|
||||
repeat_while(&mut instructions)?;
|
||||
// 条件已由 PopJumpIfFalse 消费;退出时重新装 Nil,不能把最后条件冒充业务返回值。
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
driver(
|
||||
cx,
|
||||
instructions,
|
||||
vec![Value::Object(callback), Value::Nil],
|
||||
name,
|
||||
desktop,
|
||||
)
|
||||
nexus::vm_sequence::repeat_call(cx, callback, name, &DesktopFunctions(desktop))
|
||||
}
|
||||
|
||||
/// source_layout/source_paint 的推进回调调用,为当前出现生成“调用源方法→collector 收结果→返回 true”的助手。
|
||||
/// 每次只捕获当前源函数/实参,不预先为全部节点建立助手帧;外层重复驱动再决定下一次出现。
|
||||
/// 单次源调用的收集器适配;保持 collector/function/实参顺序和原生输出根协议。
|
||||
pub fn collect_and_continue(
|
||||
cx: &mut NativeContext<'_>,
|
||||
collector: ObjectRef,
|
||||
@@ -96,140 +45,12 @@ pub fn collect_and_continue(
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 常量布局固定为 collector、function、各实参、true。
|
||||
// function 或 collector 失败时不会装入最终 true,外层循环也不会自动跳过失败节点;本助手不捕获或重试源错误。
|
||||
// 先把 collector 的调用前缀压栈,再执行 function,使其返回值直接成为 collector 的唯一实参。
|
||||
// count 同时确定 Call 的显式参数数和 true 常量的池位置,不能把 collector 的一参计入它。
|
||||
let count = arguments.len();
|
||||
// 先保存两个 callable,再追加业务实参;这份强边关系使源调用挂起期间输入仍可达。
|
||||
let mut constants = vec![Value::Object(collector), Value::Object(function)];
|
||||
constants.extend(arguments);
|
||||
constants.push(Value::Bool(true));
|
||||
// 先压 collector 的调用前缀,再压 function 的调用前缀;内部返回值自然成为外部单一实参。
|
||||
let mut instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
];
|
||||
for index in 0..count {
|
||||
// 参数常量从 2 开始,0/1 已被 collector/function 占用,保持源方法原始实参顺序。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32 + 2));
|
||||
}
|
||||
// 收集器返回值不参与外层调度;丢弃后返回 true,通知重复驱动继续取下一项。
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::Call, count as u32),
|
||||
Instruction::new(Opcode::Call, 1),
|
||||
Instruction::simple(Opcode::PopTop),
|
||||
Instruction::new(Opcode::LoadConst, count as u32 + 2),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
driver(cx, instructions, constants, name, desktop)
|
||||
}
|
||||
|
||||
/// repeat_call/collect_and_continue 的共同分配助手,把已组装指令与常量变成有宿主 Function 类型的 callable。
|
||||
fn driver(
|
||||
cx: &mut NativeContext<'_>,
|
||||
instructions: Vec<Instruction>,
|
||||
constants: Vec<Value>,
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 编码常量池与指令后带上宿主诊断位置;字节码有效性由 Aster 的代码构造接口检查。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, "<tessera>", 1);
|
||||
// NativeContext 跟踪临时代码根;函数的 trace 边持有代码,不能只靠 Rust ObjectRef 数值保活。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 生成驱动不查用户名字,私有 globals 隔离它的空命名环境。
|
||||
let globals = cx.new_dict()?;
|
||||
// 返回函数根由原生输出机制提升,代码和 globals 的临时根在域结束后可安全清理。
|
||||
let function = cx.new_function(name, code, globals)?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, function, "Function", desktop)?;
|
||||
Ok(function)
|
||||
}
|
||||
|
||||
/// repeat_call 和本模块测试调用,在现有指令尾部追加消费 Bool 条件的分支与回跳。
|
||||
/// true 回到本驱动偏移零,false 跳过回跳指令;不新建调用帧,因此不会用递归栈模拟循环。
|
||||
pub fn repeat_while(instructions: &mut Vec<Instruction>) -> Result<(), VmError> {
|
||||
// 跳转单位是编码后的双字节 code unit,不是 Instruction 数量。
|
||||
// 大操作数会生成 EXTENDED_ARG,因此必须编码后计算实际长度。
|
||||
let body = Instruction::encode_all(instructions)?.len() / 2;
|
||||
// 先用最短零操作数估计回跳宽度,下面迭代直到最终操作数与编码宽度自洽。
|
||||
let mut back = Instruction::new(Opcode::JumpBackward, 0);
|
||||
// 回跳距离包含自身宽度;而距离变大又可能扩大自身编码宽度。
|
||||
// 迭代到宽度/距离一致后,false 跳过回跳指令,true 回到整个驱动的起点。
|
||||
loop {
|
||||
// units 是当前回跳指令实际占用的 code unit,可能因 EXTENDED_ARG 大于一。
|
||||
let units = Instruction::encode_all(&[back])?.len() / 2;
|
||||
// 距离覆盖原 body、一个条件分支和回跳自身;目标为开头,不是仅回到上一个 Call。
|
||||
let distance = u32::try_from(body + 1 + units)
|
||||
.map_err(|_| VmError::ExecutionLimit("layout bytecode"))?;
|
||||
if back.argument == distance {
|
||||
// 已收敛时 false 跳过 units 个单元,true 落到 JumpBackward 回到开头。
|
||||
instructions.push(Instruction::new(Opcode::PopJumpIfFalse, units as u32));
|
||||
instructions.push(back);
|
||||
return Ok(());
|
||||
}
|
||||
// 更新操作数后再次编码量宽度;不能只计算一次,跨 255 等边界可能新增 EXTENDED_ARG。
|
||||
back.argument = distance;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use endor_core::{ExecutionLimits, Vm};
|
||||
#[test]
|
||||
/// Rust 测试框架调用,构造大于单字节跳距的循环,分别验证退出、指令预算及无泄漏清理。
|
||||
fn repeated_bytecode_handles_extended_operands_and_keeps_one_frame() {
|
||||
// 300 个 Nop 强制跨越单字节跳转距离:false 应正常退出;true 应耗尽指令预算,
|
||||
// 而非耗尽帧预算,从而验证循环确实复用同一个执行帧。
|
||||
for condition in [false, true] {
|
||||
// Nop 扩大 body 编码长度,与实际布局节点数量无关,直接覆盖回跳扩展操作数的边界。
|
||||
let mut instructions = vec![Instruction::simple(Opcode::Nop); 300];
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
repeat_while(&mut instructions).unwrap();
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
// 条件从常量池读取,false 分支跳过回跳后装入 Nil 并正常返回。
|
||||
let code = EndorCode::from_instructions(
|
||||
&instructions,
|
||||
vec![Value::Bool(condition), Value::Nil],
|
||||
CodeLayout::default(),
|
||||
)
|
||||
.unwrap();
|
||||
// 每种条件独立 VM,统计回收时不受另一轮遗留对象影响。
|
||||
let mut vm = Vm::new().unwrap();
|
||||
// 将纯代码值注册到 VM,执行结束后显式释放此拥有根。
|
||||
let code = vm.new_code(code).unwrap();
|
||||
// 空全局字典满足执行接口,不引入额外用户对象。
|
||||
let globals = vm.new_dict().unwrap();
|
||||
// 故意只允许一帧:如果实现递归重复而非同帧跳转,会得到错误的帧数耗尽。
|
||||
let result = vm.execute_with_limits(
|
||||
code,
|
||||
globals,
|
||||
ExecutionLimits {
|
||||
max_frames: 1,
|
||||
max_instructions: 1000,
|
||||
},
|
||||
);
|
||||
if condition {
|
||||
// true 永不自然退出,应耗尽 instructions 而非 frames,证明循环复用了同一帧。
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(VmError::ExecutionLimit("instructions"))
|
||||
));
|
||||
} else {
|
||||
// false 只走一次 body 然后返回 Nil,证明分支跳过长度包含完整扩展回跳指令。
|
||||
assert_eq!(result.unwrap(), Value::Nil);
|
||||
}
|
||||
vm.release(code).unwrap();
|
||||
vm.release(globals).unwrap();
|
||||
// 释放代码与全局字典后执行循环回收,确认生成的常量/函数没有遗留托管对象。
|
||||
vm.collect_cycles();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
}
|
||||
nexus::vm_sequence::collect_and_continue(
|
||||
cx,
|
||||
collector,
|
||||
function,
|
||||
arguments,
|
||||
name,
|
||||
&DesktopFunctions(desktop),
|
||||
)
|
||||
}
|
||||
|
||||
Vendored
+1
@@ -3,6 +3,7 @@
|
||||
| Entry | Purpose |
|
||||
| --- | --- |
|
||||
| `README.md` | Source checkout, version selection, and update instructions |
|
||||
| [nexus](nexus/README.md) | Local `endorphin-nexus-runtime` Rust library; ordinary source directory, no separate Git or remote yet |
|
||||
| [aster](aster/README.md) | `endorphin-aster-vm` source submodule; provides the Endor frontend, compiler, objects, and VM |
|
||||
|
||||
## Checkout
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "compiler"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"core",
|
||||
"frontend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"objects",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "endorphin-nexus-runtime"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"compiler",
|
||||
"core",
|
||||
"frontend",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "frontend"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"peg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objects"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0aad070be5b63aa72103f2fcdd70a83adbd5e90112ce5b574171ff1c65501773"
|
||||
dependencies = [
|
||||
"peg-macros",
|
||||
"peg-runtime",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg-macros"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd8ef6825cae95355031ae26a99b616a2a21f22ba2de0197c43dfb05acbe7ee"
|
||||
dependencies = [
|
||||
"peg-runtime",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peg-runtime"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7011d97b484a5ebdc4b1fdb3b12d5e4bbbea56e9d22b688f2e79e04b65a7d8a6"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
# 本地 Nexus Rust library;暂未初始化独立 Git,也没有远程仓库。
|
||||
[package]
|
||||
name = "endorphin-nexus-runtime"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
description = "Host-extensible Endor runtime built on Aster"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
# 运行时边界的错误聚合;UI 类型与窗口依赖由宿主自行维护。
|
||||
anyhow = "1.0"
|
||||
# 与 Tessera 显式依赖同一份 Aster,避免托管句柄来自不同版本/堆实现。
|
||||
compiler = { path = "../aster/crates/compiler" }
|
||||
endor_core = { package = "core", path = "../aster/crates/core" }
|
||||
frontend = { path = "../aster/crates/frontend" }
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
# Endorphin Nexus Runtime(本地抽取中)
|
||||
|
||||
这是 GUI 进程内运行的 Rust library,包名为 `endorphin-nexus-runtime`。目前放在 `vendor/nexus` 普通目录,尚未初始化独立 Git,也没有远程仓库。后续建仓需另获用户明确授权。
|
||||
|
||||
依赖方向为 Tessera → Nexus → Aster。Nexus 通过相邻的 `vendor/aster` 使用与 Tessera 相同版本的语言 crate,没有 Tessera、窗口或渲染依赖。`HostRegistration` 由 Tessera 的 `bridge/nexus_host.rs` 实现,为同一个 owning VM 注册 UI 类型和全局能力。
|
||||
|
||||
当前已抽取源码分段/位置修正、计划编译与隔离表达式求值、AST 预算、VM 根清理、I/O provider、同帧调用序列以及定时/I/O/协作任务引擎。持久输入通过 `VmSession::prepare_input` 完整准备后,再由 `execute_input` 消费执行,保留原全局对象和最后值 `_`。任务宿主通过 `TaskHost` 提供作用域存储、资格检查与名义类型,通用引擎不检查 UI payload。Tessera 保留任务/驱动的 UI 策略适配;源码和 I/O 的无用转发模块已删除。
|
||||
|
||||
完整程序由 `PreparedProgram` 统一准备并执行,`main`/页面策略由宿主决定;`with_call_result` 负责宿主处理后的返回根清理。会话 VM/根表/环境字段已限制在库内,宿主通过显式借用和根转交接口接入。`ConsoleHistory` 管理累计预算、原文和接受凭据;UI 代码投影仍由 Tessera 生成。HTTP/原生 worker 属于 Tessera 的宿主组合,不放入通用语言库。实现已接入,并已完成本次本地编译与回归。窗口、Mount 路由、布局/绘制刷新、文档发布与 UI API 属于 Tessera 适配,不能靠 Nexus 反向依赖来搬运。
|
||||
|
||||
`tests/host_registration.rs` 覆盖无 UI 宿主注册、部分失败清理、源码计划的跨片全局与跨度;`tests/tasks.rs` 通过普通对象宿主覆盖同键替换、交付前资格撤销及退出门闩;`tests/console.rs` 覆盖持久输入和编译/执行失败边界;`tests/program.rs` 覆盖完整装载及宿主处理错误后的清理;`tests/history.rs` 覆盖历史与累计限额;原驱动循环回归随实现保留。本次已获明确本机编译/测试授权:14 个集成回归与 1 个单元回归全部通过,所有目标 Clippy(警告视为错误)通过。Tessera 的 190 个常规测试均覆盖通过,1 个可选性能基准忽略;Aster 完整检查脚本通过。首次沙箱运行中的 11 个 HTTP 用例因禁止监听本地端口失败,允许回环网络后该组 16 个测试全部通过。
|
||||
|
||||
后续验证应分别执行 Tessera 的集成测试和 `cargo test --manifest-path vendor/nexus/Cargo.toml`。Tessera 单独执行 `cargo test` 不会自动运行依赖库 Nexus 的单元/集成测试;不能把它的通过替代本库验证。
|
||||
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
//! 执行前语法结构预算;脚本各根共享累计节点数,位置与语法节点由 Aster 提供。
|
||||
use anyhow::{Result, bail};
|
||||
use frontend::{Span, ast::visitor::Visitor};
|
||||
|
||||
/// 一份输入最多访问的 AST 节点数,与运行指令预算分开。
|
||||
pub const MAX_AST_NODES: usize = 10_000;
|
||||
/// 单个根的嵌套路径上限,leave_node 归还深度。
|
||||
pub const MAX_AST_DEPTH: usize = 64;
|
||||
|
||||
#[derive(Default)]
|
||||
/// 编译前的语法节点数量/嵌套预算,限制输入结构复杂度。
|
||||
pub struct AstBudget {
|
||||
// 当前递归路径深度,leave_node 归还;不能与累计节点数共用一个计数。
|
||||
depth: usize,
|
||||
// 已访问节点总量,多个 Script 根共享累计,leave_node 不减少。
|
||||
nodes: usize,
|
||||
}
|
||||
|
||||
impl Visitor for AstBudget {
|
||||
type Error = anyhow::Error;
|
||||
/// PreparedProgram::compile、VmSession::prepare_input 与 evaluate 调用 Aster Visitor;进入任意节点时共用本检查。
|
||||
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 {
|
||||
// 在加载/执行代码前停止,防止巨大源码结构绕过仅约束运行指令的 LIMITS。
|
||||
bail!("Aster AST exceeds the 64-level or 10000-node host budget");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// 离开当前语法节点时归还嵌套深度;累计节点数保留,不能通过退出子树绕过总量预算。
|
||||
fn leave_node(&mut self) {
|
||||
self.depth -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl AstBudget {
|
||||
/// 宿主累计 Console/程序结构预算时读取已检查节点总量,不改变遍历状态。
|
||||
pub fn nodes(&self) -> usize {
|
||||
self.nodes
|
||||
}
|
||||
}
|
||||
Vendored
+280
@@ -0,0 +1,280 @@
|
||||
//! 持久输入的完整编译与同 VM 执行;不包含窗口、代码浏览树、文档发布或 UI 刷新。
|
||||
//! Tessera 在 prepare_input 成功后处理宿主清理与输入记录,再消费 PreparedInput 执行一次。
|
||||
//! 编译失败不执行任何片段;运行失败不回滚已经完成的全局写入或外部副作用。
|
||||
use crate::{
|
||||
DEFAULT_LIMITS as LIMITS, MAX_SOURCE_BYTES, VmSession,
|
||||
budget::{AstBudget, MAX_AST_NODES},
|
||||
program::compile_plan,
|
||||
runtime_error,
|
||||
source::{self, SourcePlan},
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{ExecutionLimits, Value, Vm};
|
||||
use frontend::{
|
||||
EndorReader, SourceUnit,
|
||||
ast::{AstRoot, StmtKind, visitor::Visitor},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
/// 已接受输入的计数与原文历史,不保留 VM 句柄或任何 UI 投影。
|
||||
/// prepare 只验证/编译;宿主完成前置清理后 accept,再执行已接受输入,失败也不回滚历史。
|
||||
pub struct ConsoleHistory {
|
||||
// 接受的 Console 输入数;从完整程序开始时仍为零。
|
||||
inputs: usize,
|
||||
// 完整程序加所有已接受输入的节点总量,不因一次执行错误而退回。
|
||||
ast_nodes: usize,
|
||||
// 完整程序原文和输入分隔记录;运行时不通过回放它恢复业务堆。
|
||||
source: String,
|
||||
}
|
||||
|
||||
/// 已接受输入的拥有型凭据,保留同一准备结果及投影位置;不携带 VM 根。
|
||||
pub struct AcceptedInput {
|
||||
// 转移准备结果的所有权,避免同一准备值被重复接受或执行。
|
||||
input: PreparedInput,
|
||||
// 一基输入号,与来源标签和 transcript 分隔注释一致。
|
||||
number: usize,
|
||||
// 当前输入局部一基行号需要增加的偏移;分隔注释也占一行。
|
||||
line_offset: usize,
|
||||
}
|
||||
impl AcceptedInput {
|
||||
/// 宿主生成代码投影时借用已接受的同一份原文和 AST。
|
||||
pub fn input(&self) -> &PreparedInput {
|
||||
&self.input
|
||||
}
|
||||
/// 投影建立后执行已接受输入;消费凭据且不取回准备结果,避免被再次接受或重放。
|
||||
pub fn execute(self, runtime: &mut VmSession) -> Result<String> {
|
||||
runtime.execute_input(self.input)
|
||||
}
|
||||
/// 宿主建立投影身份或响应输入编号时读取。
|
||||
pub fn number(&self) -> usize {
|
||||
self.number
|
||||
}
|
||||
/// 宿主平移输入投影时读取,保留 CRLF、CR 和末尾空行规则。
|
||||
pub fn line_offset(&self) -> usize {
|
||||
self.line_offset
|
||||
}
|
||||
}
|
||||
impl ConsoleHistory {
|
||||
/// 完整程序加载成功后建立历史;AST 预算从完整程序计数开始,Console 输入数从零开始。
|
||||
pub fn from_program(program: &crate::program::PreparedProgram) -> Self {
|
||||
Self {
|
||||
inputs: 0,
|
||||
ast_nodes: program.ast_nodes(),
|
||||
source: program.source().text().to_owned(),
|
||||
}
|
||||
}
|
||||
/// 宿主发布文档时借用原文,不允许适配层直接改写预算所依据的文本。
|
||||
pub fn source(&self) -> &str {
|
||||
&self.source
|
||||
}
|
||||
/// 已接受的输入数,执行失败不会使编号重用。
|
||||
pub fn inputs(&self) -> usize {
|
||||
self.inputs
|
||||
}
|
||||
/// 已接受输入及原程序累计的结构量,供宿主统计或检查。
|
||||
pub fn ast_nodes(&self) -> usize {
|
||||
self.ast_nodes
|
||||
}
|
||||
|
||||
/// 先限制原始输入,再限制累计次数和含分隔余量的字节预算;不修改历史。
|
||||
fn check_input(&self, text: &str) -> Result<()> {
|
||||
if text.len() > MAX_SOURCE_BYTES {
|
||||
bail!("input exceeds 1 MiB");
|
||||
}
|
||||
// 80 字节余量沿用原 Console 契约,涵盖输入注释与换行;饱和加法也拒绝异常的大外部状态。
|
||||
if self.inputs >= 256
|
||||
|| self
|
||||
.source
|
||||
.len()
|
||||
.saturating_add(text.len())
|
||||
.saturating_add(80)
|
||||
> MAX_SOURCE_BYTES
|
||||
{
|
||||
bail!("console session exceeds 256 inputs or 1 MiB; reset the session to continue");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// 同步串行宿主调用:完整编译前不记输入号,也不改文本;使用 VM 当前真实 globals。
|
||||
pub fn prepare(
|
||||
&self,
|
||||
runtime: &VmSession,
|
||||
session_id: u64,
|
||||
text: &str,
|
||||
) -> Result<PreparedInput> {
|
||||
self.check_input(text)?;
|
||||
// 来源使用下一接受号,但准备失败不消耗它;完整原文仍交给同一个 SourceUnit。
|
||||
let source = EndorReader::from_text(
|
||||
format!("console session {} input {}", session_id, self.inputs + 1),
|
||||
text,
|
||||
);
|
||||
runtime.prepare_input(source, self.ast_nodes)
|
||||
}
|
||||
/// 消费完整准备结果并立即记历史,调用方随后执行;串行宿主不得把准备结果跨历史错配。
|
||||
pub fn accept(&mut self, input: PreparedInput) -> Result<AcceptedInput> {
|
||||
// 再检查当前预算,避免宿主在 prepare 与 accept 之间接受其他输入后绕过限额。
|
||||
self.check_input(input.source().text())?;
|
||||
if self.ast_nodes.saturating_add(input.ast_nodes()) > MAX_AST_NODES {
|
||||
bail!("console session exceeds 10000 AST nodes; reset the session to continue");
|
||||
}
|
||||
// 所有检查成功才一起推进编号与结构计数;之后的执行错误仍占用本次预算。
|
||||
self.inputs += 1;
|
||||
self.ast_nodes += input.ast_nodes();
|
||||
// 仅给已有文本补分隔行,不修改被编译输入本身的换行与跨度。
|
||||
if !self.source.is_empty() && !self.source.ends_with('\n') {
|
||||
self.source.push('\n');
|
||||
}
|
||||
// 与代码投影共用字节行首规则,CRLF 只记一次,孤立 CR 也计行。
|
||||
let line_offset = crate::source::line_starts(&self.source).len();
|
||||
// 显式输入分隔让 Sources 可对应编号;它不作为本次 VM 执行的源文本。
|
||||
self.source
|
||||
.push_str(&format!("// Console input {}\n", self.inputs));
|
||||
self.source.push_str(input.source().text());
|
||||
// 只为下一条 transcript 记录补尾换行;当前执行仍读取准备结果中的独立原文。
|
||||
if !self.source.ends_with('\n') {
|
||||
self.source.push('\n');
|
||||
}
|
||||
Ok(AcceptedInput {
|
||||
input,
|
||||
number: self.inputs,
|
||||
line_offset,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 一份已经完整编译的输入;字段私有,确保 AST、原文、编译片段与节点计数来自同一次准备。
|
||||
/// 不保存托管根或 VM 句柄;准备和执行之间宿主不得另行改变全局名称契约。
|
||||
pub struct PreparedInput {
|
||||
// 拥有原始 UTF-8 快照,宿主可用它生成诊断和源码浏览投影。
|
||||
source: SourceUnit,
|
||||
// AST 片段与 compiled 同源同序,执行时不重新解析或回放历史。
|
||||
plan: SourcePlan,
|
||||
// 模板还不拥有 VM 代码对象,load 后的代码根只跨一次执行。
|
||||
compiled: Vec<compiler::CompiledCode>,
|
||||
// 当前输入的累计结构量,宿主接受输入时才合并到会话计数。
|
||||
ast_nodes: usize,
|
||||
}
|
||||
impl PreparedInput {
|
||||
/// 宿主记录原文和来源,不规范化文本或更改编译时的跨度。
|
||||
pub fn source(&self) -> &SourceUnit {
|
||||
&self.source
|
||||
}
|
||||
/// 宿主创建纯数据代码投影时借用 AST,不暴露可被错配的独立模板列表。
|
||||
pub fn plan(&self) -> &SourcePlan {
|
||||
&self.plan
|
||||
}
|
||||
/// 成功准备不等于接受输入;调用方在宿主清理成功后再累计此值。
|
||||
pub fn ast_nodes(&self) -> usize {
|
||||
self.ast_nodes
|
||||
}
|
||||
}
|
||||
impl VmSession {
|
||||
/// 用实际 globals 中的名称完整编译输入;不改业务堆,也不更新宿主的历史或计数。
|
||||
pub fn prepare_input(
|
||||
&self,
|
||||
source: SourceUnit,
|
||||
ast_nodes_used: usize,
|
||||
) -> Result<PreparedInput> {
|
||||
// 公共库入口也检查原文字节预算,不能依赖某个 GUI 调用方预先检查。
|
||||
if source.text().len() > MAX_SOURCE_BYTES {
|
||||
bail!("input exceeds 1 MiB");
|
||||
}
|
||||
// plan 保留完整模块或同源交互片段;这里不执行已解析的任何前半段。
|
||||
let plan = source::parse(&source)?;
|
||||
// 输入内共享计数器,结构预算成功后才枚举真实全局名和编译。
|
||||
let mut budget = AstBudget::default();
|
||||
for ast in plan.roots() {
|
||||
budget.visit_ast_root(ast)?;
|
||||
}
|
||||
if ast_nodes_used.saturating_add(budget.nodes()) > MAX_AST_NODES {
|
||||
bail!("console session exceeds 10000 AST nodes; reset the session to continue");
|
||||
}
|
||||
// 查询所属会话的借用环境身份;缺少初始化是调用契约错误,不能偷偷建立新环境。
|
||||
let globals = self
|
||||
.globals
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime globals not initialized"))?;
|
||||
// 只复制字符串名称;不把托管 Value 或对象根藏在编译准备结果中。
|
||||
let names = self
|
||||
.vm
|
||||
.dict_items(globals)?
|
||||
.iter()
|
||||
.filter_map(|(key, _)| {
|
||||
if let Value::Text(name) = key {
|
||||
Some(name.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// 先完整编译所有片段,成功后把原文/AST/模板一起交还,不改变历史或业务绑定。
|
||||
let compiled = compile_plan(&source, &plan, names)?;
|
||||
Ok(PreparedInput {
|
||||
source,
|
||||
plan,
|
||||
compiled,
|
||||
ast_nodes: budget.nodes(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 消费已准备输入,在当前真实 globals 上执行并保留最后值到 _;仅返回纯文本给宿主。
|
||||
/// 宿主应先记录已接受输入,执行后再安排 UI 刷新;错误不表示此前语句已经撤销。
|
||||
pub fn execute_input(&mut self, input: PreparedInput) -> Result<String> {
|
||||
// 继续操作相同真实字典,不从历史原文回放或创建替代业务对象。
|
||||
let globals = self
|
||||
.globals
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime globals not initialized"))?;
|
||||
// 多根均分本次硬预算,不让后续片段每个都获得完整一百万条指令。
|
||||
let limits = ExecutionLimits {
|
||||
max_instructions: LIMITS.max_instructions / input.compiled.len().max(1),
|
||||
..LIMITS
|
||||
};
|
||||
// 依次覆盖为最后一个片段的可显示值;本局部只保存字符串,不延长任意返回对象寿命。
|
||||
let mut rendered_value = "nil".to_owned();
|
||||
for (ast, template) in input.plan.roots().iter().zip(&input.compiled) {
|
||||
// 代码根只跨一次 execute,先暂存 Result 再 release(code),失败也有清理。
|
||||
let code = template.load(&mut self.vm)?;
|
||||
// VM 执行真实 globals,不把本轮 AST 当快照去覆盖旧业务状态。
|
||||
let executed = self
|
||||
.vm
|
||||
.execute_with_limits(code, globals, limits)
|
||||
.map_err(|error| runtime_error(&self.vm, error));
|
||||
self.vm.release(code)?;
|
||||
// execute 返回拥有根,后面 repr/全局 _ 更新是否成功都必须释放这份根。
|
||||
let value = executed?;
|
||||
// 绑定/赋值语句展示其新变量实际值,普通表达式展示返回值;不是仅显示该语句执行的 Unit。
|
||||
let display = if let AstRoot::Interactive(input) = ast {
|
||||
match &input.statements[0].kind {
|
||||
StmtKind::Binding(binding) => self
|
||||
.vm
|
||||
.dict_get(globals, &Value::Text(binding.name.text.clone()))?
|
||||
.unwrap_or_else(|| value.clone()),
|
||||
StmtKind::Assignment(assignment) => self
|
||||
.vm
|
||||
.dict_get(globals, &Value::Text(assignment.name.text.clone()))?
|
||||
.unwrap_or_else(|| value.clone()),
|
||||
_ => value.clone(),
|
||||
}
|
||||
} else {
|
||||
value.clone()
|
||||
};
|
||||
// 先算 repr 并把实际最后值写入全局 _,保留未命名 UI 对象;随后释放 execute 返回根,错误也逐项传播。
|
||||
let repr = value_repr(&self.vm, &display);
|
||||
// _ 的字典强边独立保留最后值,避免匿名 Block 在 Console 显示后马上丢失身份。
|
||||
let retained = self.vm.dict_set(globals, Value::Text("_".into()), display);
|
||||
self.vm.release_value(value)?;
|
||||
retained?;
|
||||
rendered_value = repr?;
|
||||
}
|
||||
Ok(rendered_value)
|
||||
}
|
||||
}
|
||||
|
||||
/// execute_input 在保存全局 _ 前调用,把真实返回值/新绑定值转成显示字符串;返回根仍由调用者释放。
|
||||
fn value_repr(vm: &Vm, value: &Value) -> Result<String> {
|
||||
Ok(match value {
|
||||
Value::Nil => "nil".into(),
|
||||
Value::Bool(v) => v.to_string(),
|
||||
Value::Text(v) => format!("{v:?}"),
|
||||
Value::Number(v) => v.to_string(),
|
||||
Value::Object(v) => vm.repr(*v)?,
|
||||
})
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
//! Lease 由托管任务拥有,释放会撤销交付资格并取消可取消的后台工作;已经完成的结果还要由 VM worker 检查归属后才能交付。
|
||||
//! 并发、队列、读取字节数、超时和 URL 协议均有边界,避免 provider 绕过运行时资源限制。
|
||||
//!
|
||||
//! runtime::tasks 为 readText/fetchText 创建 Task 时调用 Provider::submit,并把返回 Lease 放进 Task payload。
|
||||
//! Nexus tasks 为 readText/fetchText 创建 Task 时调用 Provider::submit,并把返回 Lease 放进 Task payload。
|
||||
//! Scheduler 轮询 Provider::take_ready 后在 owning VM 中核验弱身份、owner/key 与取消状态,再调用源回调。
|
||||
//! 所有 Provider 共用一个全进程有界线程池;每个运行时仍有自己的结果邮箱与租约额度,不互读 Task 堆。
|
||||
use endor_core::{VmError, WeakObjectRef};
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
//! GUI 进程内的通用 Endor 运行时库,依赖 Aster,不依赖 Tessera 的模型、窗口或渲染器。
|
||||
//! 宿主向 VmSession 注册能力;源码组织、编译、根清理和驱动字节码由本库实现。
|
||||
//! 本地抽取仍在进行;持久输入准备/执行已进入本库,输入历史、UI 发布及 worker 组合仍由 Tessera 承接。
|
||||
|
||||
/// 编译前结构预算;多段脚本共享同一个访问器累计计数。
|
||||
pub mod budget;
|
||||
/// 持久输入的完整准备与同 VM 执行,返回纯文本并保留真实全局身份。
|
||||
pub mod console;
|
||||
/// 纯数据后台读取及租约取消,不在线程池中操作 VM。
|
||||
pub mod io_tasks;
|
||||
/// 无 UI 名称假设的源码计划编译与隔离表达式执行。
|
||||
pub mod program;
|
||||
mod session;
|
||||
/// 原文分段、AST 根及跨度平移;具体语法由 Aster 定义。
|
||||
pub mod source;
|
||||
/// 通用定时、I/O、协作任务调度;宿主通过 TaskHost 提供对象生命周期规则。
|
||||
pub mod tasks;
|
||||
/// VM 内调用序列与循环驱动,函数名义身份交由宿主注册接口处理。
|
||||
pub mod vm_sequence;
|
||||
|
||||
pub use program::evaluate;
|
||||
pub use session::{HostRegistration, VmSession, runtime_error};
|
||||
|
||||
/// 默认源执行硬预算,脚本调用方按片段数分摊,不为每段重置全部额度。
|
||||
pub const DEFAULT_LIMITS: endor_core::ExecutionLimits = endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
};
|
||||
/// 原始输入字节上限,不以 Unicode 字符数或 AST 节点数替代。
|
||||
pub const MAX_SOURCE_BYTES: usize = 1_048_576;
|
||||
Vendored
+236
@@ -0,0 +1,236 @@
|
||||
//! 无 UI 假设的源码编译与隔离表达式执行;宿主显式提供可见全局名,库不安装窗口能力。
|
||||
use crate::{
|
||||
DEFAULT_LIMITS as LIMITS, MAX_SOURCE_BYTES, VmSession, budget::AstBudget, runtime_error,
|
||||
source::SourcePlan,
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{ExecutionLimits, Value};
|
||||
use frontend::{
|
||||
EndorReader, SourceUnit,
|
||||
ast::{AstRoot, DeclKind, Stmt, StmtKind, visitor::Visitor},
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// 完整程序的不可拆分准备结果,不携带已加载代码或任何 VM 根。
|
||||
/// 宿主在建立候选 VM 前准备它,并借用原文/AST 生成自己的浏览投影。
|
||||
pub struct PreparedProgram {
|
||||
// 原始文本和来源,编译元数据与宿主投影使用同一份快照。
|
||||
source: SourceUnit,
|
||||
// 区分完整模块与脚本片段,决定执行预算分配以及宿主是否调用入口函数。
|
||||
plan: SourcePlan,
|
||||
// 每片模板对应相同位置的 AST 根,不允许宿主单独替换其中一侧。
|
||||
compiled: Vec<compiler::CompiledCode>,
|
||||
// 整份源码的结构计数,宿主后续 Console 输入在此基础上累计。
|
||||
ast_nodes: usize,
|
||||
}
|
||||
impl PreparedProgram {
|
||||
/// 显式宿主全局名只用于静态编译;所有语法和代码生成仍由 Aster 完成。
|
||||
pub fn compile(source: SourceUnit, globals: BTreeSet<String>) -> Result<Self> {
|
||||
// 在解析或分配模板前限制原始 UTF-8 字节,避免执行预算无法约束的前端开销。
|
||||
if source.text().len() > MAX_SOURCE_BYTES {
|
||||
bail!("source exceeds the 1 MiB limit");
|
||||
}
|
||||
// 完整模块保持一个根,顶层脚本保留源序片段;原文和跨度仍属于同一快照。
|
||||
let plan = crate::source::parse(&source)?;
|
||||
// 所有片段累计结构预算,失败时还没有目标 VM 或部分业务写入。
|
||||
let mut budget = AstBudget::default();
|
||||
for ast in plan.roots() {
|
||||
budget.visit_ast_root(ast)?;
|
||||
}
|
||||
// 所有根成功编译才返回准备结果;宿主此时尚未创建/改写候选 VM。
|
||||
let compiled = compile_plan(&source, &plan, globals)?;
|
||||
Ok(Self {
|
||||
source,
|
||||
plan,
|
||||
compiled,
|
||||
ast_nodes: budget.nodes(),
|
||||
})
|
||||
}
|
||||
/// 宿主展示原文/诊断时借用,不改行尾或字节跨度。
|
||||
pub fn source(&self) -> &SourceUnit {
|
||||
&self.source
|
||||
}
|
||||
/// 宿主自行决定模块入口/页面策略,本库不调用约定名称 main。
|
||||
pub fn plan(&self) -> &SourcePlan {
|
||||
&self.plan
|
||||
}
|
||||
/// 后续持久输入的累计预算起点;不包括宿主 UI 投影节点。
|
||||
pub fn ast_nodes(&self) -> usize {
|
||||
self.ast_nodes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
/// 装载代码根的生命周期,保留原一次性候选与持久执行两条路径的清理策略。
|
||||
pub enum CodeRetention {
|
||||
/// 代码根加入会话根表,close 逆序释放;即使执行失败也由会话清理。
|
||||
Session,
|
||||
/// 代码仅跨当前片段执行,错误也先释放它再传播。
|
||||
Execution,
|
||||
}
|
||||
impl VmSession {
|
||||
/// 在现有全局环境执行完整定义/脚本,不自动调用 main、打开窗口或解释最后返回值。
|
||||
pub fn execute_program(
|
||||
&mut self,
|
||||
program: &PreparedProgram,
|
||||
retention: CodeRetention,
|
||||
) -> Result<()> {
|
||||
// 使用所属会话已拥有的字典;这是借用身份,执行函数不新增第二份全局根。
|
||||
let globals = self
|
||||
.globals
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime globals not initialized"))?;
|
||||
// 模块一个单元使用完整预算;脚本将同一硬预算均分给全部片段。
|
||||
let limits = match program.plan() {
|
||||
SourcePlan::Module(_) => LIMITS,
|
||||
SourcePlan::Script(_) => ExecutionLimits {
|
||||
max_instructions: LIMITS.max_instructions / program.compiled.len().max(1),
|
||||
..LIMITS
|
||||
},
|
||||
};
|
||||
// 严格按片段源序装载执行,前段失败即停止;不自动执行宿主约定的入口。
|
||||
for template in &program.compiled {
|
||||
// load 返回目标堆中的代码拥有根,由下方选定的生命周期策略归还。
|
||||
let code = template.load(&mut self.vm)?;
|
||||
if retention == CodeRetention::Session {
|
||||
// 先登记拥有根再执行,部分执行失败时根仍可被 close 找到。
|
||||
self.roots.push(code);
|
||||
}
|
||||
// 暂存成功/错误,让 Execution 策略在传播错误前也能归还代码根。
|
||||
let executed = self
|
||||
.vm
|
||||
.execute_with_limits(code, globals, limits)
|
||||
.map_err(|error| runtime_error(&self.vm, error));
|
||||
if retention == CodeRetention::Execution {
|
||||
// 暂存 Result 使失败执行也经过代码根归还,保持持久加载路径的顺序。
|
||||
self.vm.release(code)?;
|
||||
}
|
||||
// 顶层返回值不作为隐式展示根;宿主稍后自行处理约定入口的返回结果。
|
||||
self.vm.release_value(executed?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// PreparedProgram::compile、VmSession::prepare_input 和独立编译测试调用,按源序编译全部根,支持模块与声明前向引用。
|
||||
pub fn compile_plan(
|
||||
source: &SourceUnit,
|
||||
plan: &SourcePlan,
|
||||
mut globals: BTreeSet<String>,
|
||||
) -> Result<Vec<compiler::CompiledCode>> {
|
||||
// 先收集全部函数/类声明名以支持前向引用;普通绑定仍按源码执行次序逐段加入已知全局名。
|
||||
for root in plan.roots() {
|
||||
if let AstRoot::Interactive(input) = root {
|
||||
// 完整模块的声明可见性由 Aster 自己处理;只有拆成多个交互根时宿主需预收集声明名。
|
||||
for statement in &input.statements {
|
||||
if let StmtKind::Declaration(decl) = &statement.kind {
|
||||
// 只预声明函数/类,不提前把任意赋值名当作已存在业务值。
|
||||
let name = match &decl.kind {
|
||||
DeclKind::Function(function) => &function.name,
|
||||
DeclKind::Class(class) => &class.name,
|
||||
};
|
||||
globals.insert(name.text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 每个根保留一个模板,执行顺序必须与原根切片一一对应,不能按名字排序。
|
||||
let mut compiled = Vec::with_capacity(plan.roots().len());
|
||||
/// 本函数在每段成功编译后调用,递归收集后续段可能引用的绑定名,不执行或预测条件真值。
|
||||
fn assigned(statement: &Stmt, globals: &mut BTreeSet<String>) {
|
||||
match &statement.kind {
|
||||
StmtKind::Binding(b) => {
|
||||
// 绑定给后续片段的静态名称解析提供名字;字典中的真实值仍在执行时建立。
|
||||
globals.insert(b.name.text.clone());
|
||||
}
|
||||
StmtKind::Assignment(a) => {
|
||||
// 顶层赋值也可能引入名字,按 Aster 交互语义让后续段可以编译引用。
|
||||
globals.insert(a.name.text.clone());
|
||||
}
|
||||
StmtKind::If(b) => {
|
||||
// 两个分支都收集“可能声明”名字,不在编译阶段决定哪条路径会执行。
|
||||
for s in &b.body.statements {
|
||||
assigned(s, globals);
|
||||
}
|
||||
if let Some(other) = &b.otherwise {
|
||||
// else 中的潜在绑定也要让后续片段可编译引用,但这里不预先在 globals 字典创建实际值。
|
||||
for s in &other.statements {
|
||||
assigned(s, globals);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::While(b) => {
|
||||
// 循环体可能写入全局;是否真正执行一次由 VM 决定,宿主不展开循环。
|
||||
for s in &b.body.statements {
|
||||
assigned(s, globals);
|
||||
}
|
||||
}
|
||||
// 表达式、return、成员赋值等不引入新的普通全局名;函数内部作用域由语言编译器处理。
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for root in plan.roots() {
|
||||
// 每段得到当前已知全局集合快照,先编译再把本段绑定加入下一段上下文。
|
||||
let options = compiler::CompileOptions {
|
||||
globals: globals.iter().cloned().collect(),
|
||||
};
|
||||
compiled.push(
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(compiled)
|
||||
}
|
||||
|
||||
/// api::worker 的 evaluate 请求调用,在一次性无 UI 全局的隔离 VM 求单表达式,返回可显示字符串。
|
||||
pub fn evaluate(source: &str) -> Result<String> {
|
||||
if source.len() > MAX_SOURCE_BYTES {
|
||||
bail!("expression exceeds the 1 MiB limit");
|
||||
}
|
||||
// 独立来源名明确区别于持久 Console transcript,不读取其历史或对象堆。
|
||||
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)?;
|
||||
// 默认全局只有语言内置,不为 evaluate 暗中安装 ui 或活程序用户全局。
|
||||
let compiled = compiler::compile_ast(&ast, &source, &compiler::CompileOptions::default())
|
||||
.map_err(|error| source.annotate(error))?;
|
||||
// 独立候选统一持有执行根,表达式失败也由 close 释放整个域。
|
||||
let mut candidate = VmSession::new()?;
|
||||
// 暂存执行/格式化错误,保证外层 close 不因这里的 ? 被跳过。
|
||||
let result = (|| {
|
||||
// 表达式全局环境为空的新字典,不能用运行时 namespace 文档代替真实 globals。
|
||||
let globals = candidate.vm.new_dict()?;
|
||||
candidate.globals = Some(globals);
|
||||
candidate.roots.push(globals);
|
||||
// 模板加载到此 VM 后才有真实代码对象,拥有根记入 Candidate。
|
||||
let code = compiled.load(&mut candidate.vm)?;
|
||||
candidate.roots.push(code);
|
||||
// 一次有界执行产生拥有返回值,字符串化后显式释放。
|
||||
let value = candidate
|
||||
.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(),
|
||||
Value::Text(v) => format!("{v:?}"),
|
||||
Value::Number(v) => v.to_string(),
|
||||
Value::Object(v) => candidate.vm.repr(*v)?,
|
||||
};
|
||||
candidate.vm.release_value(value)?;
|
||||
Ok(rendered)
|
||||
})();
|
||||
// 先尝试关闭候选,再合并执行和清理结果,不能只因表达式已有字符串结果就跳过清理。
|
||||
let cleanup = candidate.close();
|
||||
match (result, cleanup) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(e), _) | (_, Err(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
Vendored
+157
@@ -0,0 +1,157 @@
|
||||
//! owning VM 与外部根的生命周期;只负责语言运行域,不包含视觉发布或窗口关闭策略。
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{ExecutionLimits, ObjectRef, Value, Vm, VmError};
|
||||
|
||||
/// 宿主向 Nexus 会话安装领域能力,返回的适配状态仍由宿主持有。
|
||||
/// register 内分配且需长期保活的根必须登记 roots;失败由会话 close/Drop 收尾。
|
||||
pub trait HostRegistration {
|
||||
/// 宿主自己的能力状态,Nexus 不解释其中窗口、布局或业务协议。
|
||||
type Installed;
|
||||
/// owning 线程调用,globals 借用;注册到字典的对象由实际内部强边保活。
|
||||
fn register(
|
||||
&self,
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
globals: ObjectRef,
|
||||
) -> Result<Self::Installed>;
|
||||
}
|
||||
|
||||
/// 拥有 VM、全局字典与宿主保留根;关闭时按顺序释放,失败也必须收尾。
|
||||
pub struct VmSession {
|
||||
// 实际解释器/托管堆,仅执行 worker 线程操作,不放入共享 NamespaceState。
|
||||
pub(crate) vm: Vm,
|
||||
// 宿主安装期间保留的拥有根,close 逆序 pop;ObjectRef Rust 数值本身没有自动 release 行为。
|
||||
pub(crate) roots: Vec<ObjectRef>,
|
||||
// 主全局字典也在 roots 中,先清字典断业务根,再统一释放根,避免闭包环残留。
|
||||
pub(crate) globals: Option<ObjectRef>,
|
||||
}
|
||||
|
||||
impl VmSession {
|
||||
/// 创建独立 VM,先不保留任何宿主根或全局字典;后续安装失败也由该候选负责清理。
|
||||
pub fn new() -> Result<Self> {
|
||||
Ok(Self {
|
||||
vm: Vm::new()?,
|
||||
roots: Vec::new(),
|
||||
globals: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 宿主读取所属 VM;借用不会转移堆或根的拥有权。
|
||||
pub fn vm(&self) -> &Vm {
|
||||
&self.vm
|
||||
}
|
||||
|
||||
/// 宿主在 owning 线程推进领域调用/续体;不得替换 VM 或绕过返回值的 release 契约。
|
||||
pub fn vm_mut(&mut self) -> &mut Vm {
|
||||
&mut self.vm
|
||||
}
|
||||
|
||||
/// 借用主环境身份,清理由会话负责;宿主不能覆盖或取走全局拥有根。
|
||||
pub fn globals(&self) -> Option<ObjectRef> {
|
||||
self.globals
|
||||
}
|
||||
|
||||
/// 把调用方已经拥有的一份根转交会话;不会额外 retain,也不能传入只有借用权的句柄。
|
||||
pub fn keep_root(&mut self, root: ObjectRef) {
|
||||
self.roots.push(root);
|
||||
}
|
||||
|
||||
/// 为受信任宿主的安装/回收提供短时共同借用,不转移 VM 或根表的拥有权。
|
||||
/// 宿主移除根时必须同步归还对应拥有引用;不得替换 VM、保存这些可变引用或隐式复制根。
|
||||
pub fn with_host<R>(&mut self, host: impl FnOnce(&mut Vm, &mut Vec<ObjectRef>) -> R) -> R {
|
||||
host(&mut self.vm, &mut self.roots)
|
||||
}
|
||||
|
||||
/// 宿主建立会话主环境,登记一份拥有根;重复调用拒绝,避免覆盖未清理的环境。
|
||||
pub fn create_globals(&mut self) -> Result<ObjectRef> {
|
||||
// 环境身份只能在同一会话初始化一次,业务重绑定通过字典操作进行。
|
||||
if self.globals.is_some() {
|
||||
bail!("runtime globals already initialized");
|
||||
}
|
||||
// 分配成功后同时保存清理入口和拥有根,安装宿主失败时 Drop 仍可收尾。
|
||||
let globals = self.vm.new_dict()?;
|
||||
self.globals = Some(globals);
|
||||
self.roots.push(globals);
|
||||
Ok(globals)
|
||||
}
|
||||
|
||||
/// Tessera/其他宿主注册其领域能力;Nexus 只调用接口,不引用宿主具体类型。
|
||||
pub fn register_host<H: HostRegistration>(&mut self, host: &H) -> Result<H::Installed> {
|
||||
// 必须先有真实主环境;不在库中猜测 ui、窗口、页面等宿主名字。
|
||||
let globals = self
|
||||
.globals
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime globals not initialized"))?;
|
||||
host.register(&mut self.vm, &mut self.roots, globals)
|
||||
}
|
||||
|
||||
/// 调用后把返回值借给宿主处理;处理成功或返回错误,都先归还 VM 返回的拥有根。
|
||||
/// handler 如需保留对象必须建立真实托管边或显式 retain;不能把借用 ObjectRef 当拥有结果带出。
|
||||
pub fn with_call_result<R>(
|
||||
&mut self,
|
||||
callee: ObjectRef,
|
||||
args: &[Value],
|
||||
limits: ExecutionLimits,
|
||||
handler: impl FnOnce(&mut Vm, &Value) -> Result<R>,
|
||||
) -> Result<R> {
|
||||
// VM 成功返回时 value 拥有一份根;先在这里保存,宿主处理不得接管或跳过其归还责任。
|
||||
let value = self
|
||||
.vm
|
||||
.call_with_limits(callee, args, limits)
|
||||
.map_err(|error| runtime_error(&self.vm, error))?;
|
||||
// 先保存宿主处理结果,避免其中的 ? 跳过返回根释放;清理失败优先传播。
|
||||
let handled = handler(&mut self.vm, &value);
|
||||
self.vm.release_value(value)?;
|
||||
handled
|
||||
}
|
||||
|
||||
/// compile/evaluate 显式调用,VmSession::drop 兜底调用;按拥有顺序拆根并验证堆没有遗留对象。
|
||||
pub fn close(&mut self) -> Result<()> {
|
||||
// 清全局字典先断业务对象可达根,再逆序释放宿主分配根;最后执行循环回收并验证对象计数归零。
|
||||
if let Some(globals) = self.globals.take() {
|
||||
// take 使重复 close 不重复清同一身份;先断用户全局再释放类型/函数等宿主根。
|
||||
self.vm.dict_clear(globals)?;
|
||||
}
|
||||
// pop 逐项移出确保再次 close 不重复释放已成功处理的根;错误仍交显式关闭调用方报告。
|
||||
while let Some(root) = self.roots.pop() {
|
||||
self.vm.release(root)?;
|
||||
}
|
||||
self.vm.collect_cycles();
|
||||
if self.vm.object_count() != 0 {
|
||||
// 源程序返回了纯数据也不掩盖资源泄漏,显式 close 会把这个错误报告给调用者。
|
||||
bail!("candidate VM retained objects after cleanup");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for VmSession {
|
||||
/// 析构调用 VmSession.close 释放候选根和 VM,覆盖提前返回/异常展开;析构不能向调用者报告清理错误。
|
||||
fn drop(&mut self) {
|
||||
// 显式 close 可以报告引用计数/清理错误;Drop 则保证提前返回和异常展开仍经过最终清理边界。
|
||||
let _ = self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// 本模块和 bridge/tasks 的 VM 错误映射调用,立即取 last_traceback 拼成纯文本,避免后续调用覆盖故障栈。
|
||||
pub fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
|
||||
// 错误发生后立即读取 VM traceback,保留函数、源文件与指令偏移;无栈信息时直接保留原 VmError。
|
||||
let locations = vm
|
||||
.last_traceback()
|
||||
.iter()
|
||||
.map(|frame| {
|
||||
// 每帧保留来源文件、函数名和指令位置,不把托管异常对象直接跨线程交付。
|
||||
format!(
|
||||
"{}:{} in {} (instruction {})",
|
||||
frame.filename, frame.first_line, frame.function, frame.instruction_offset
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if locations.is_empty() {
|
||||
// 无 VM 栈时保留原始 VmError,不能凭当前源码猜一个错误行号。
|
||||
error.into()
|
||||
} else {
|
||||
// 含栈则附加每帧可读位置,Console/API 不需读取 VM 就能展示错误。
|
||||
anyhow::anyhow!("{error}\n{locations}")
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -1,7 +1,7 @@
|
||||
//! 区分完整 Module 与顶层 Script,并保留输入源码位置。
|
||||
//! 解析包装或片段拼接产生的 span 偏移要递归修正,保证诊断和 Sources 视图仍指向用户原始行列。
|
||||
//!
|
||||
//! runtime::endor_host 的一次性 compile 和持久会话加载调用 parse,再按 roots 进行 AST 预算检查与编译。
|
||||
//! Nexus PreparedProgram 与 VmSession::prepare_input 调用 parse,再按 roots 进行 AST 预算检查与编译。
|
||||
//! 语句、词法和 AST 定义属于 Aster;这里只把完整源码组织成 Module 或连续 Interactive 输入。
|
||||
//! 片段先用局部字节位置解析,shift_* 递归加回起点,编译错误和 Sources 浏览才能仍对应原文件。
|
||||
use anyhow::Result;
|
||||
@@ -19,7 +19,7 @@ pub enum SourcePlan {
|
||||
}
|
||||
|
||||
impl SourcePlan {
|
||||
/// endor_host 的 AST 预算访问和 compile_plan 调用,借用统一根切片,不克隆 AST 或重新解析。
|
||||
/// PreparedProgram/prepare_input 的 AST 预算访问和 compile_plan 调用,借用统一根切片,不克隆 AST 或重新解析。
|
||||
pub fn roots(&self) -> &[AstRoot] {
|
||||
match self {
|
||||
// 单模块以单元素切片适配,让调用方不必维护两套遍历分支。
|
||||
@@ -30,9 +30,9 @@ impl SourcePlan {
|
||||
}
|
||||
}
|
||||
|
||||
/// endor_host 执行入口调用,优先接受完整 Module,失败则按顶层换行候选边界拼出 Aster 可解析的交互输入。
|
||||
/// PreparedProgram/prepare_input 的源码准备入口调用,优先接受完整 Module,失败则按顶层换行候选边界拼出 Aster 可解析的交互输入。
|
||||
/// 模块解析失败本身不立即作为最终错误:普通顶层脚本本就需要走后面的 Interactive 解析路径。
|
||||
/// 这里只产出 AST 计划,不执行已接受的片段;endor_host 先完成所有根的预算检查和编译,再进入源代码执行。
|
||||
/// 这里只产出 AST 计划,不执行已接受的片段;Nexus 先完成所有根的预算检查和编译,再进入源代码执行。
|
||||
pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
// 完整模块优先;只有模块解析失败才退回连续交互输入模式,宿主不自行实现 Endor 语法。
|
||||
if let Ok(module) = frontend::parse_source_ast(source, ParseMode::Module) {
|
||||
@@ -265,3 +265,18 @@ fn shift_expression(expression: &mut Expr, offset: usize) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// architecture/execute_mode 调用,建立字节偏移→行号的搜索索引,兼容 CRLF、LF 和孤立 CR。
|
||||
pub fn line_starts(source: &str) -> Vec<usize> {
|
||||
// Span 使用 UTF-8 字节单位,所以不用 chars().enumerate() 的字符索引匹配它。
|
||||
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')) {
|
||||
// 记录换行符之后的下一行首,CRLF 只在 LF 分支记录一次,空末行也有可定位起点。
|
||||
starts.push(offset + 1);
|
||||
}
|
||||
}
|
||||
starts
|
||||
}
|
||||
Vendored
+1259
File diff suppressed because it is too large
Load Diff
Vendored
+249
@@ -0,0 +1,249 @@
|
||||
//! 构造共享 VM 调用序列与同帧循环驱动的字节码。
|
||||
//! 用托管函数串联步骤,避免为每个布局节点反复创建独立解释器调用;重复驱动会保留同一个执行帧和预算域。
|
||||
//!
|
||||
//! mount::synchronize 与 event_dispatch::dispatch 用 build 串起生命周期/事件回调。
|
||||
//! source_layout/source_paint 用 repeat_call 循环推进出现位置,并用 collect_and_continue 收集单次源调用结果。
|
||||
//! 本模块只生成驱动字节码和托管函数,不在 Rust 中自行解释语句,也不替调用方重置 VM 预算。
|
||||
//! 原生调用返回 Invoke 后,VM 在既有帧循环中执行驱动,因此可挂起工作仍有明确的 owning VM。
|
||||
//! build 串联的是普通调用序列,任一步报错便中断后续步骤;末项不是 finally,错误时临时根/检查点仍须由所属工作收尾路径释放。
|
||||
use endor_core::{
|
||||
CodeLayout, EndorCode, EndorCodeObject, Instruction, NativeContext, ObjectRef, Opcode, Value,
|
||||
VmError,
|
||||
};
|
||||
|
||||
/// 驱动生成后由宿主附着领域 Function 身份;回调在原分配顺序中的最后一步执行。
|
||||
pub trait FunctionHost {
|
||||
/// owning VM 调用;function 是 NativeContext 临时根,不能在这里移交或重复释放。
|
||||
fn attach_function(
|
||||
&self,
|
||||
cx: &mut NativeContext<'_>,
|
||||
function: ObjectRef,
|
||||
) -> Result<(), VmError>;
|
||||
/// 字节码错误回溯的宿主来源标签,不访问磁盘或参与名称解析。
|
||||
fn source_name(&self) -> &'static str {
|
||||
"<nexus>"
|
||||
}
|
||||
}
|
||||
|
||||
/// 将零参数调用列表编成一个托管驱动,按输入顺序执行,返回最后一次调用的值。
|
||||
/// 空列表返回 Nil。所有调用都在调用者的 VM 预算内运行,避免宿主逐个调用时重置预算。
|
||||
/// name 用于诊断位置;host 负责来源标签及生成函数的领域名义身份。
|
||||
/// 调用者是 Mount 生命周期同步和事件路由;返回值是驱动函数身份,不是已经执行完的最后结果。
|
||||
pub fn build(
|
||||
cx: &mut NativeContext<'_>,
|
||||
calls: Vec<ObjectRef>,
|
||||
name: &'static str,
|
||||
host: &impl FunctionHost,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 每个函数放入常量池。LoadConst/PushNull/Call 组成零参数调用,
|
||||
// 中间结果由 PopTop 丢弃;最后结果留在栈顶交给 ReturnValue。
|
||||
// 每个中间调用至多四条指令,额外空间覆盖空序列和 ReturnValue;只是预留容量,不是指令预算。
|
||||
let mut instructions = Vec::with_capacity(calls.len() * 4 + 2);
|
||||
// 常量池强持有每个 callable,驱动存活期间不依赖调用方的 Rust Vec 保活。
|
||||
let mut constants: Vec<Value> = calls.into_iter().map(Value::Object).collect();
|
||||
for index in 0..constants.len() {
|
||||
// LoadConst 放函数,PushNull 建立 VM Call 所需前缀,Call 0 执行无显式实参的回调。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32));
|
||||
instructions.push(Instruction::simple(Opcode::PushNull));
|
||||
instructions.push(Instruction::new(Opcode::Call, 0));
|
||||
if index + 1 != constants.len() {
|
||||
// 只丢中间结果,避免把最后一个结果也弹掉而让 ReturnValue 面对空栈。
|
||||
instructions.push(Instruction::simple(Opcode::PopTop));
|
||||
}
|
||||
}
|
||||
// 没有调用时也必须给 ReturnValue 提供合法栈顶,不能返回一个空栈。
|
||||
if constants.is_empty() {
|
||||
constants.push(Value::Nil);
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
}
|
||||
instructions.push(Instruction::simple(Opcode::ReturnValue));
|
||||
// 编码阶段校验字节码布局,诊断位置使用宿主 name 而不是伪造用户源码行列。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, host.source_name(), 1);
|
||||
// NativeContext 暂持代码根,输出函数会通过托管边继续拥有代码与常量。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 驱动只读取常量,无需共享用户字典,空私有 globals 不污染 REPL 或主模块。
|
||||
let globals = cx.new_dict()?;
|
||||
// 函数作为本次原生调用的输出被提升,其余临时拥有根由 NativeContext 退出时释放。
|
||||
let driver = cx.new_function(name, code, globals)?;
|
||||
host.attach_function(cx, driver)?;
|
||||
Ok(driver)
|
||||
}
|
||||
|
||||
/// source_layout/source_paint 安装一轮出现遍历时调用,生成固定大小的重复驱动,不按节点数展开字节码。
|
||||
/// callback 每次返回 Bool,false 退出;同帧回跳让所有出现和委托源函数共用当前 VM 的执行预算。
|
||||
pub fn repeat_call(
|
||||
cx: &mut NativeContext<'_>,
|
||||
callback: ObjectRef,
|
||||
name: &'static str,
|
||||
host: &impl FunctionHost,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 内部 Advance 回调约定返回 Bool;repeat_while 生成的是 VM 真值条件跳转,不额外验证返回值必须是 Bool。
|
||||
// 退出后显式返回 Nil,回调的继续条件不会泄露为驱动返回值。
|
||||
let mut instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
];
|
||||
repeat_while(&mut instructions)?;
|
||||
// 条件已由 PopJumpIfFalse 消费;退出时重新装 Nil,不能把最后条件冒充业务返回值。
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
driver(
|
||||
cx,
|
||||
instructions,
|
||||
vec![Value::Object(callback), Value::Nil],
|
||||
name,
|
||||
host,
|
||||
)
|
||||
}
|
||||
|
||||
/// source_layout/source_paint 的推进回调调用,为当前出现生成“调用源方法→collector 收结果→返回 true”的助手。
|
||||
/// 每次只捕获当前源函数/实参,不预先为全部节点建立助手帧;外层重复驱动再决定下一次出现。
|
||||
pub fn collect_and_continue(
|
||||
cx: &mut NativeContext<'_>,
|
||||
collector: ObjectRef,
|
||||
function: ObjectRef,
|
||||
arguments: Vec<Value>,
|
||||
name: &'static str,
|
||||
host: &impl FunctionHost,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 常量布局固定为 collector、function、各实参、true。
|
||||
// function 或 collector 失败时不会装入最终 true,外层循环也不会自动跳过失败节点;本助手不捕获或重试源错误。
|
||||
// 先把 collector 的调用前缀压栈,再执行 function,使其返回值直接成为 collector 的唯一实参。
|
||||
// count 同时确定 Call 的显式参数数和 true 常量的池位置,不能把 collector 的一参计入它。
|
||||
let count = arguments.len();
|
||||
// 先保存两个 callable,再追加业务实参;这份强边关系使源调用挂起期间输入仍可达。
|
||||
let mut constants = vec![Value::Object(collector), Value::Object(function)];
|
||||
constants.extend(arguments);
|
||||
constants.push(Value::Bool(true));
|
||||
// 先压 collector 的调用前缀,再压 function 的调用前缀;内部返回值自然成为外部单一实参。
|
||||
let mut instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
];
|
||||
for index in 0..count {
|
||||
// 参数常量从 2 开始,0/1 已被 collector/function 占用,保持源方法原始实参顺序。
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32 + 2));
|
||||
}
|
||||
// 收集器返回值不参与外层调度;丢弃后返回 true,通知重复驱动继续取下一项。
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::Call, count as u32),
|
||||
Instruction::new(Opcode::Call, 1),
|
||||
Instruction::simple(Opcode::PopTop),
|
||||
Instruction::new(Opcode::LoadConst, count as u32 + 2),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
driver(cx, instructions, constants, name, host)
|
||||
}
|
||||
|
||||
/// repeat_call/collect_and_continue 的共同分配助手,把已组装指令与常量变成有宿主 Function 类型的 callable。
|
||||
fn driver(
|
||||
cx: &mut NativeContext<'_>,
|
||||
instructions: Vec<Instruction>,
|
||||
constants: Vec<Value>,
|
||||
name: &'static str,
|
||||
host: &impl FunctionHost,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
// 编码常量池与指令后带上宿主诊断位置;字节码有效性由 Aster 的代码构造接口检查。
|
||||
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
|
||||
.with_location(name, host.source_name(), 1);
|
||||
// NativeContext 跟踪临时代码根;函数的 trace 边持有代码,不能只靠 Rust ObjectRef 数值保活。
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
// 生成驱动不查用户名字,私有 globals 隔离它的空命名环境。
|
||||
let globals = cx.new_dict()?;
|
||||
// 返回函数根由原生输出机制提升,代码和 globals 的临时根在域结束后可安全清理。
|
||||
let function = cx.new_function(name, code, globals)?;
|
||||
host.attach_function(cx, function)?;
|
||||
Ok(function)
|
||||
}
|
||||
|
||||
/// repeat_call 和本模块测试调用,在现有指令尾部追加消费 Bool 条件的分支与回跳。
|
||||
/// true 回到本驱动偏移零,false 跳过回跳指令;不新建调用帧,因此不会用递归栈模拟循环。
|
||||
pub fn repeat_while(instructions: &mut Vec<Instruction>) -> Result<(), VmError> {
|
||||
// 跳转单位是编码后的双字节 code unit,不是 Instruction 数量。
|
||||
// 大操作数会生成 EXTENDED_ARG,因此必须编码后计算实际长度。
|
||||
let body = Instruction::encode_all(instructions)?.len() / 2;
|
||||
// 先用最短零操作数估计回跳宽度,下面迭代直到最终操作数与编码宽度自洽。
|
||||
let mut back = Instruction::new(Opcode::JumpBackward, 0);
|
||||
// 回跳距离包含自身宽度;而距离变大又可能扩大自身编码宽度。
|
||||
// 迭代到宽度/距离一致后,false 跳过回跳指令,true 回到整个驱动的起点。
|
||||
loop {
|
||||
// units 是当前回跳指令实际占用的 code unit,可能因 EXTENDED_ARG 大于一。
|
||||
let units = Instruction::encode_all(&[back])?.len() / 2;
|
||||
// 距离覆盖原 body、一个条件分支和回跳自身;目标为开头,不是仅回到上一个 Call。
|
||||
let distance = u32::try_from(body + 1 + units)
|
||||
.map_err(|_| VmError::ExecutionLimit("layout bytecode"))?;
|
||||
if back.argument == distance {
|
||||
// 已收敛时 false 跳过 units 个单元,true 落到 JumpBackward 回到开头。
|
||||
instructions.push(Instruction::new(Opcode::PopJumpIfFalse, units as u32));
|
||||
instructions.push(back);
|
||||
return Ok(());
|
||||
}
|
||||
// 更新操作数后再次编码量宽度;不能只计算一次,跨 255 等边界可能新增 EXTENDED_ARG。
|
||||
back.argument = distance;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use endor_core::{ExecutionLimits, Vm};
|
||||
#[test]
|
||||
/// Rust 测试框架调用,构造大于单字节跳距的循环,分别验证退出、指令预算及无泄漏清理。
|
||||
fn repeated_bytecode_handles_extended_operands_and_keeps_one_frame() {
|
||||
// 300 个 Nop 强制跨越单字节跳转距离:false 应正常退出;true 应耗尽指令预算,
|
||||
// 而非耗尽帧预算,从而验证循环确实复用同一个执行帧。
|
||||
for condition in [false, true] {
|
||||
// Nop 扩大 body 编码长度,与实际布局节点数量无关,直接覆盖回跳扩展操作数的边界。
|
||||
let mut instructions = vec![Instruction::simple(Opcode::Nop); 300];
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
repeat_while(&mut instructions).unwrap();
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
// 条件从常量池读取,false 分支跳过回跳后装入 Nil 并正常返回。
|
||||
let code = EndorCode::from_instructions(
|
||||
&instructions,
|
||||
vec![Value::Bool(condition), Value::Nil],
|
||||
CodeLayout::default(),
|
||||
)
|
||||
.unwrap();
|
||||
// 每种条件独立 VM,统计回收时不受另一轮遗留对象影响。
|
||||
let mut vm = Vm::new().unwrap();
|
||||
// 将纯代码值注册到 VM,执行结束后显式释放此拥有根。
|
||||
let code = vm.new_code(code).unwrap();
|
||||
// 空全局字典满足执行接口,不引入额外用户对象。
|
||||
let globals = vm.new_dict().unwrap();
|
||||
// 故意只允许一帧:如果实现递归重复而非同帧跳转,会得到错误的帧数耗尽。
|
||||
let result = vm.execute_with_limits(
|
||||
code,
|
||||
globals,
|
||||
ExecutionLimits {
|
||||
max_frames: 1,
|
||||
max_instructions: 1000,
|
||||
},
|
||||
);
|
||||
if condition {
|
||||
// true 永不自然退出,应耗尽 instructions 而非 frames,证明循环复用了同一帧。
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(VmError::ExecutionLimit("instructions"))
|
||||
));
|
||||
} else {
|
||||
// false 只走一次 body 然后返回 Nil,证明分支跳过长度包含完整扩展回跳指令。
|
||||
assert_eq!(result.unwrap(), Value::Nil);
|
||||
}
|
||||
vm.release(code).unwrap();
|
||||
vm.release(globals).unwrap();
|
||||
// 释放代码与全局字典后执行循环回收,确认生成的常量/函数没有遗留托管对象。
|
||||
vm.collect_cycles();
|
||||
assert_eq!(vm.object_count(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+128
@@ -0,0 +1,128 @@
|
||||
//! 无 UI 的持久输入回归,覆盖实际全局身份、准备阶段无副作用、失败边界和返回对象拥有关系。
|
||||
//! 测试通过真实 VM 和借用/拥有根观察结果,不依赖 GUI 或历史回放。
|
||||
use endor_core::Value;
|
||||
use endorphin_nexus_runtime::{VmSession, budget::MAX_AST_NODES};
|
||||
use frontend::EndorReader;
|
||||
|
||||
/// 新建只有真实全局字典的运行时,不安装任何 GUI 能力或重放历史输入。
|
||||
fn session() -> VmSession {
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
runtime.create_globals().unwrap();
|
||||
runtime
|
||||
}
|
||||
|
||||
/// 独立来源标记用于检查运行错误仍指向当前输入,而非累计浏览 transcript。
|
||||
fn execute(runtime: &mut VmSession, name: &str, text: &str) -> String {
|
||||
let input = runtime
|
||||
.prepare_input(EndorReader::from_text(name, text), 0)
|
||||
.unwrap();
|
||||
runtime.execute_input(input).unwrap()
|
||||
}
|
||||
|
||||
/// 读取借用字典值,只用于观察;不会给对象额外建立拥有根。
|
||||
fn global(runtime: &VmSession, name: &str) -> Option<Value> {
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(runtime.globals().unwrap(), &Value::Text(name.into()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 新输入使用原全局字典;准备成功也不执行,代码模板释放后函数仍可从全局被调用。
|
||||
fn persistent_inputs_preserve_bindings_and_function_identity() {
|
||||
let mut runtime = session();
|
||||
let input = runtime
|
||||
.prepare_input(EndorReader::from_text("first", "counter = 1"), 0)
|
||||
.unwrap();
|
||||
assert!(input.ast_nodes() > 0);
|
||||
assert_eq!(input.source().text(), "counter = 1");
|
||||
assert_eq!(input.plan().roots().len(), 1);
|
||||
assert_eq!(global(&runtime, "counter"), None);
|
||||
assert_eq!(runtime.execute_input(input).unwrap(), "1");
|
||||
assert_eq!(
|
||||
execute(&mut runtime, "second", "counter = counter + 1"),
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
global(&runtime, "counter"),
|
||||
Some(Value::Number(2_i64.into()))
|
||||
);
|
||||
execute(
|
||||
&mut runtime,
|
||||
"definition",
|
||||
"function identity(value: Number): Number { return value }",
|
||||
);
|
||||
// 表达式结果是函数对象;_ 必须建立真实强边,不能只保留 repr 或 Rust 句柄。
|
||||
let display = execute(&mut runtime, "function value", "identity");
|
||||
assert!(!display.is_empty());
|
||||
assert_eq!(global(&runtime, "_"), global(&runtime, "identity"));
|
||||
assert_eq!(execute(&mut runtime, "call", "identity(counter)"), "2");
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 全部片段编译成功前不执行;执行期失败保留前段写入,错误仍携带独立输入来源。
|
||||
fn compile_failure_is_preflight_but_runtime_failure_keeps_prior_writes() {
|
||||
let mut runtime = session();
|
||||
execute(&mut runtime, "initial", "counter = 1");
|
||||
assert!(
|
||||
runtime
|
||||
.prepare_input(
|
||||
EndorReader::from_text("compile failure", "counter = 8\nnotDeclared"),
|
||||
0
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
global(&runtime, "counter"),
|
||||
Some(Value::Number(1_i64.into()))
|
||||
);
|
||||
let input = runtime
|
||||
.prepare_input(
|
||||
EndorReader::from_text("headless execution failure", "counter = 9\n1 / 0"),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
let error = runtime.execute_input(input).unwrap_err().to_string();
|
||||
assert!(error.contains("division by zero"));
|
||||
assert!(error.contains("headless execution failure"));
|
||||
assert_eq!(
|
||||
global(&runtime, "counter"),
|
||||
Some(Value::Number(9_i64.into()))
|
||||
);
|
||||
// 失败输入并未导致历史重放,后续输入继续操作同一当前全局值。
|
||||
assert_eq!(execute(&mut runtime, "after failure", "counter + 1"), "10");
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 累计节点和输入字节预算在准备阶段失败,既不更新 _ 也不写业务变量。
|
||||
fn source_and_cumulative_ast_limits_do_not_execute_partial_inputs() {
|
||||
let mut runtime = session();
|
||||
execute(&mut runtime, "initial", "counter = 3");
|
||||
for used in [MAX_AST_NODES, usize::MAX] {
|
||||
assert!(
|
||||
runtime
|
||||
.prepare_input(
|
||||
EndorReader::from_text("over AST budget", "counter = 8"),
|
||||
used
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let large = " ".repeat(endorphin_nexus_runtime::MAX_SOURCE_BYTES + 1);
|
||||
let error = runtime
|
||||
.prepare_input(EndorReader::from_text("over source budget", large), 0)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.to_string().contains("input exceeds 1 MiB"));
|
||||
assert_eq!(
|
||||
global(&runtime, "counter"),
|
||||
Some(Value::Number(3_i64.into()))
|
||||
);
|
||||
assert_eq!(global(&runtime, "_"), Some(Value::Number(3_i64.into())));
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
Vendored
+117
@@ -0,0 +1,117 @@
|
||||
//! Console 历史与累计预算的无 UI 契约回归;需在获授权构建环境编译执行。
|
||||
use endor_core::Value;
|
||||
use endorphin_nexus_runtime::{
|
||||
MAX_SOURCE_BYTES, VmSession, budget::MAX_AST_NODES, console::ConsoleHistory,
|
||||
program::PreparedProgram,
|
||||
};
|
||||
use frontend::EndorReader;
|
||||
|
||||
/// 创建真实环境但不安装 UI;历史本身没有管理对象或回放职责。
|
||||
fn session() -> VmSession {
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
runtime.create_globals().unwrap();
|
||||
runtime
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 解析/编译失败不接受输入;运行错误发生在接受之后,历史和前段写入都保留。
|
||||
fn only_accepted_inputs_enter_history_and_execution_errors_remain_recorded() {
|
||||
let mut runtime = session();
|
||||
let mut history = ConsoleHistory::default();
|
||||
assert!(
|
||||
history
|
||||
.prepare(&runtime, 7, "value = 1\nunknownName")
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(history.inputs(), 0);
|
||||
assert_eq!(history.ast_nodes(), 0);
|
||||
assert_eq!(history.source(), "");
|
||||
let input = history.prepare(&runtime, 7, "value = 9\n1 / 0").unwrap();
|
||||
assert_eq!(
|
||||
format!("{}", input.source().origin()),
|
||||
"console session 7 input 1"
|
||||
);
|
||||
let cost = input.ast_nodes();
|
||||
let accepted = history.accept(input).unwrap();
|
||||
assert_eq!(accepted.number(), 1);
|
||||
assert_eq!(accepted.line_offset(), 1);
|
||||
assert!(accepted.execute(&mut runtime).is_err());
|
||||
assert_eq!(history.inputs(), 1);
|
||||
assert_eq!(history.ast_nodes(), cost);
|
||||
assert_eq!(history.source(), "// Console input 1\nvalue = 9\n1 / 0\n");
|
||||
assert_eq!(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(runtime.globals().unwrap(), &Value::Text("value".into()))
|
||||
.unwrap(),
|
||||
Some(Value::Number(9_i64.into()))
|
||||
);
|
||||
runtime.close().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 输入次数与 AST 总量分别限制,失败准备不增加计数或追加分隔注释。
|
||||
fn input_count_and_cumulative_ast_budgets_are_shared_by_headless_hosts() {
|
||||
let mut runtime = session();
|
||||
let mut history = ConsoleHistory::default();
|
||||
// 简单表达式不触发 AST/字节上限,因此第 257 次明确检验次数门槛。
|
||||
for number in 1..=256 {
|
||||
let input = history.prepare(&runtime, 1, "1").unwrap();
|
||||
let accepted = history.accept(input).unwrap();
|
||||
assert_eq!(accepted.number(), number);
|
||||
}
|
||||
let before = history.source().to_owned();
|
||||
assert!(history.prepare(&runtime, 1, "1").is_err());
|
||||
assert_eq!(history.inputs(), 256);
|
||||
assert_eq!(history.source(), before);
|
||||
// 每个输入有多个浅层语句,避开单输入深度限制,实际检验跨输入累计结构量。
|
||||
let mut history = ConsoleHistory::default();
|
||||
let text = "value = 1\n".repeat(50);
|
||||
let cost = history.prepare(&runtime, 2, &text).unwrap().ast_nodes();
|
||||
let allowed = MAX_AST_NODES / cost;
|
||||
assert!(allowed < 256);
|
||||
for _ in 0..allowed {
|
||||
let input = history.prepare(&runtime, 2, &text).unwrap();
|
||||
history.accept(input).unwrap();
|
||||
}
|
||||
let before = history.source().to_owned();
|
||||
let error = history.prepare(&runtime, 2, &text).err().unwrap();
|
||||
assert!(error.to_string().contains("10000 AST nodes"));
|
||||
assert_eq!(history.inputs(), allowed);
|
||||
assert_eq!(history.ast_nodes(), cost * allowed);
|
||||
assert_eq!(history.source(), before);
|
||||
runtime.close().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 完整源码、Unicode 与 CRLF/CR 原文保持;输入偏移按共享字节行首规则计算,累计字节预算含程序文本。
|
||||
fn program_history_preserves_source_and_enforces_the_combined_byte_budget() {
|
||||
let mut runtime = session();
|
||||
let raw = "base = 1\r\nlabel = \"中\"\r";
|
||||
let program =
|
||||
PreparedProgram::compile(EndorReader::from_text("program", raw), Default::default())
|
||||
.unwrap();
|
||||
let mut history = ConsoleHistory::from_program(&program);
|
||||
assert_eq!(history.inputs(), 0);
|
||||
assert_eq!(history.ast_nodes(), program.ast_nodes());
|
||||
assert_eq!(history.source(), raw);
|
||||
let input = history.prepare(&runtime, 8, "\"新\"\r\n").unwrap();
|
||||
let accepted = history.accept(input).unwrap();
|
||||
assert_eq!(accepted.line_offset(), 3);
|
||||
assert_eq!(
|
||||
history.source(),
|
||||
format!("{raw}\n// Console input 1\n\"新\"\r\n")
|
||||
);
|
||||
assert_eq!(accepted.execute(&mut runtime).unwrap(), "\"新\"");
|
||||
// 近上限的有效程序只包含长注释和一个表达式;新输入要计算既有文本和固定分隔余量。
|
||||
let raw = format!("//{}\n1", "x".repeat(MAX_SOURCE_BYTES - 20));
|
||||
let program = PreparedProgram::compile(
|
||||
EndorReader::from_text("large program", raw),
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let history = ConsoleHistory::from_program(&program);
|
||||
assert!(history.prepare(&runtime, 9, "1").is_err());
|
||||
assert_eq!(history.inputs(), 0);
|
||||
runtime.close().unwrap();
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
//! 不依赖 Tessera 的 Nexus 宿主契约回归;需在获授权的构建环境编译/执行。
|
||||
//! 验证宿主注册、半完成安装清理、脚本跨片名称和原文位置,而不是复制私有实现断言。
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{ObjectPayload, ObjectRef, Value, Vm};
|
||||
use endorphin_nexus_runtime as nexus;
|
||||
use frontend::{
|
||||
EndorReader,
|
||||
ast::{Spanned, visitor::Visitor},
|
||||
};
|
||||
use nexus::{HostRegistration, VmSession, budget::AstBudget, program::compile_plan};
|
||||
use std::{
|
||||
any::Any,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
/// 由假宿主分配的资源,析构计数在 VM 外可观察,不携带 UI 类型或托管出边。
|
||||
struct Capability(Arc<AtomicUsize>);
|
||||
impl Drop for Capability {
|
||||
/// 最后强边移除时真正释放资源;根归还与 Rust 句柄复制不应增加此计数。
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
impl ObjectPayload for Capability {
|
||||
/// Aster 载荷下转型入口,独立于宿主的名义类型注册。
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
/// 为错误/诊断提供类别,不让测试依赖 Tessera 的类型名。
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"test-capability"
|
||||
}
|
||||
}
|
||||
|
||||
/// 只依赖 Nexus/Aster 的假宿主;可在分配并登记根后故意失败,观察安装失败的收尾。
|
||||
struct Host {
|
||||
drops: Arc<AtomicUsize>,
|
||||
fail: bool,
|
||||
}
|
||||
impl HostRegistration for Host {
|
||||
type Installed = ObjectRef;
|
||||
/// Nexus 调用注册接口,宿主向实际 globals 安装能力,返回借用身份供测试检查。
|
||||
fn register(
|
||||
&self,
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
globals: ObjectRef,
|
||||
) -> Result<ObjectRef> {
|
||||
// 先登记拥有根,后续字典安装或故意失败都不能丢掉清理责任。
|
||||
let capability = vm.allocate(Capability(self.drops.clone()))?;
|
||||
roots.push(capability);
|
||||
// 错误发生在能力根创建之后,检验会话能清理半完成注册。
|
||||
if self.fail {
|
||||
bail!("host registration failed");
|
||||
}
|
||||
vm.dict_set(
|
||||
globals,
|
||||
Value::Text("capability".into()),
|
||||
Value::Object(capability),
|
||||
)?;
|
||||
Ok(capability)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 宿主通过接口注册后,全局真实持有同一能力;close 释放根和字典边,重复 close 无副作用。
|
||||
fn host_registration_uses_the_owned_vm_and_cleans_its_resources() {
|
||||
// 计数器不在 VM 内,资源销毁后仍可用于观察。
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
// 空会话不暗中安装 ui 或任何宿主对象。
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
// 主环境拥有根由 Nexus 会话登记,宿主只收到借用句柄。
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
// Installed 身份借用会话根,不能再把它当成独立拥有结果释放。
|
||||
let capability = runtime
|
||||
.register_host(&Host {
|
||||
drops: drops.clone(),
|
||||
fail: false,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(globals, &Value::Text("capability".into()))
|
||||
.unwrap(),
|
||||
Some(Value::Object(capability))
|
||||
);
|
||||
assert_eq!(runtime.vm().ref_count(capability).unwrap(), 2);
|
||||
runtime.close().unwrap();
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 缺环境时不进入宿主;重复环境初始化不分配;宿主部分失败留下的根仍由会话 close 清理。
|
||||
fn failed_registration_and_repeated_initialization_preserve_cleanup() {
|
||||
// 假宿主每次实际分配一个可计数资源。
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
// 没有 globals 的会话应在调用宿主之前拒绝注册。
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.register_host(&Host {
|
||||
drops: drops.clone(),
|
||||
fail: false
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
runtime.create_globals().unwrap();
|
||||
assert!(runtime.create_globals().is_err());
|
||||
assert_eq!(runtime.vm().object_count(), 1);
|
||||
assert!(
|
||||
runtime
|
||||
.register_host(&Host {
|
||||
drops: drops.clone(),
|
||||
fail: true
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 脚本根保留原文跨度并按源序编译,后段读取前段建立的真实全局,不需要 UI 注册。
|
||||
fn script_compilation_preserves_spans_and_shared_globals_without_ui() {
|
||||
// 两个顶层交互片段,第二片段依赖前面的赋值名称。
|
||||
let source = EndorReader::from_text("headless", "value = 2\nvalue + 3");
|
||||
// Nexus 组织输入,词法/语法与 AST 节点继续由 Aster 提供。
|
||||
let plan = nexus::source::parse(&source).unwrap();
|
||||
assert_eq!(plan.roots().len(), 2);
|
||||
assert!(plan.roots()[1].span().start >= "value = 2\n".len());
|
||||
// 所有片段共享预算访问器,退出子树不重置累计节点数。
|
||||
let mut budget = AstBudget::default();
|
||||
for root in plan.roots() {
|
||||
budget.visit_ast_root(root).unwrap();
|
||||
}
|
||||
assert!(budget.nodes() > 0);
|
||||
// 空宿主名称集仍允许后续片段引用前段赋值,实际值由 VM 执行建立。
|
||||
let templates = compile_plan(&source, &plan, Default::default()).unwrap();
|
||||
// 一份 owning VM 和 globals 贯穿各片段,执行后归还每次返回的根。
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
for (index, template) in templates.iter().enumerate() {
|
||||
// 加载的代码根交给运行时清理,既不跨 VM 复用也不留下测试外根。
|
||||
let code = template.load(runtime.vm_mut()).unwrap();
|
||||
runtime.keep_root(code);
|
||||
// 第一段赋值为 Nil,第二段求值应得到精确整数五。
|
||||
let value = runtime
|
||||
.vm_mut()
|
||||
.execute_with_limits(code, globals, nexus::DEFAULT_LIMITS)
|
||||
.unwrap();
|
||||
if index == 1 {
|
||||
assert_eq!(value, Value::Number(5_i64.into()));
|
||||
}
|
||||
runtime.vm_mut().release_value(value).unwrap();
|
||||
}
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
assert!(nexus::evaluate("ui").is_err());
|
||||
assert_eq!(nexus::evaluate("0.1 + 0.2 == 0.3").unwrap(), "true");
|
||||
}
|
||||
Vendored
+193
@@ -0,0 +1,193 @@
|
||||
//! 完整程序装载与宿主返回值处理的无 UI 回归;需在获授权环境编译、执行。
|
||||
//! 使用可观察原生回调/析构检查入口策略和拥有根,避免依赖 Tessera 的页面实现。
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{
|
||||
CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload,
|
||||
ObjectRef, Value, VmError,
|
||||
};
|
||||
use endorphin_nexus_runtime::{
|
||||
DEFAULT_LIMITS, VmSession,
|
||||
program::{CodeRetention, PreparedProgram},
|
||||
};
|
||||
use frontend::EndorReader;
|
||||
use std::{
|
||||
any::Any,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
/// main 显式调用才递增,装载定义或检查源码不应触发该宿主能力。
|
||||
struct Mark(Arc<AtomicUsize>);
|
||||
impl NativeCallable for Mark {
|
||||
/// 宿主能力使用确定零参契约。
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
Some(CallArity::exact(0))
|
||||
}
|
||||
/// 返回纯数值给源 main,计数留在 VM 外观察。
|
||||
fn invoke(
|
||||
&self,
|
||||
_cx: &mut NativeContext<'_>,
|
||||
_args: &[Value],
|
||||
) -> Result<NativeResult, VmError> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(NativeResult::Return(Value::Number(7_i64.into())))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解码读取的借用对象身份,不建立或释放根。
|
||||
fn object(value: Value) -> ObjectRef {
|
||||
let Value::Object(value) = value else {
|
||||
panic!("expected object")
|
||||
};
|
||||
value
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 两种代码根策略都只执行模块定义;main 何时调用由宿主决定,装载的函数在代码根释放后仍有效。
|
||||
fn module_loading_preserves_function_identity_without_calling_main() {
|
||||
let program = PreparedProgram::compile(
|
||||
EndorReader::from_text(
|
||||
"headless module",
|
||||
"function main(): Number { return mark() }",
|
||||
),
|
||||
["mark".to_owned()].into_iter().collect(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(program.ast_nodes() > 0);
|
||||
for retention in [CodeRetention::Execution, CodeRetention::Session] {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
let mark = runtime
|
||||
.vm_mut()
|
||||
.allocate(ContextNativeFunction::new(
|
||||
"mark",
|
||||
Mark(calls.clone()),
|
||||
vec![],
|
||||
))
|
||||
.unwrap();
|
||||
runtime.keep_root(mark);
|
||||
runtime
|
||||
.vm_mut()
|
||||
.dict_set(globals, Value::Text("mark".into()), Value::Object(mark))
|
||||
.unwrap();
|
||||
runtime.execute_program(&program, retention).unwrap();
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
let main = object(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(globals, &Value::Text("main".into()))
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
let value = runtime
|
||||
.with_call_result(main, &[], DEFAULT_LIMITS, |_vm, value| {
|
||||
Ok(value.clone()) // 此处返回标量,不把借用的托管对象带出。
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(value, Value::Number(7_i64.into()));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 脚本中途出错不回滚前段写入,两种代码根清理路径都必须能关闭至空堆。
|
||||
fn script_failure_keeps_completed_writes_and_releases_both_code_policies() {
|
||||
let program = PreparedProgram::compile(
|
||||
EndorReader::from_text(
|
||||
"headless program failure",
|
||||
"total = 1\ntotal = total + 1\n1 / 0",
|
||||
),
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for retention in [CodeRetention::Execution, CodeRetention::Session] {
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let globals = runtime.create_globals().unwrap();
|
||||
let error = runtime
|
||||
.execute_program(&program, retention)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("headless program failure"));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.vm()
|
||||
.dict_get(globals, &Value::Text("total".into()))
|
||||
.unwrap(),
|
||||
Some(Value::Number(2_i64.into()))
|
||||
);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// 每个真正返回的新对象拥有独立析构事件,验证宿主处理失败后的根也被归还。
|
||||
struct Returned(Arc<AtomicUsize>);
|
||||
impl ObjectPayload for Returned {
|
||||
/// 支持 Aster 载荷识别,不引入额外托管出边。
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
/// 测试诊断类别,与 UI 名义类型无关。
|
||||
fn kind_name(&self) -> &'static str {
|
||||
"returned-test-object"
|
||||
}
|
||||
}
|
||||
impl Drop for Returned {
|
||||
/// 真实拥有根归零时计数;仅 drop Rust Value 不会触发此回调。
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 模拟 main 返回新对象,返回前没有其他拥有边。
|
||||
struct Allocate(Arc<AtomicUsize>);
|
||||
impl NativeCallable for Allocate {
|
||||
/// 与宿主调用的空实参数量一致。
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
Some(CallArity::exact(0))
|
||||
}
|
||||
/// NativeContext 把分配根提升为返回根,Nexus 的处理接口负责后续归还。
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let result = cx.allocate(Returned(self.0.clone()))?;
|
||||
Ok(NativeResult::Return(Value::Object(result)))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 成功/错误宿主处理都可在返回对象存活期间访问它,处理结束后立即释放唯一返回根。
|
||||
fn host_result_errors_release_the_returned_object() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let callee = runtime
|
||||
.vm_mut()
|
||||
.allocate(ContextNativeFunction::new(
|
||||
"allocate",
|
||||
Allocate(drops.clone()),
|
||||
vec![],
|
||||
))
|
||||
.unwrap();
|
||||
runtime.keep_root(callee);
|
||||
let baseline = runtime.vm().object_count();
|
||||
for fail in [false, true] {
|
||||
let result: Result<()> =
|
||||
runtime.with_call_result(callee, &[], DEFAULT_LIMITS, |vm, value| {
|
||||
assert!(vm.object(object(value.clone())).is_ok());
|
||||
if fail {
|
||||
bail!("host presentation failed");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(result.is_err(), fail);
|
||||
assert_eq!(runtime.vm().object_count(), baseline);
|
||||
}
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 2);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
Vendored
+243
@@ -0,0 +1,243 @@
|
||||
//! 无 UI 的任务宿主回归:同键替换、资格变化和退出门闩必须由真实 VM/API 路径体现。
|
||||
//! 测试不启动 GUI、文件读取或网络请求,宿主资格由普通对象属性提供。
|
||||
use endor_core::{
|
||||
CallArity, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef,
|
||||
ObjectStore, TypeConstructor, Value, Vm, VmError,
|
||||
};
|
||||
use endorphin_nexus_runtime::{
|
||||
VmSession,
|
||||
tasks::{self, Scheduler, TaskHost},
|
||||
};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
/// 普通对象宿主只用属性保存作用域和资格,不知道 Block、Mount、Window 或 desktop。
|
||||
struct PlainHost;
|
||||
impl TaskHost for PlainHost {
|
||||
/// 未提交过任务时返回 None;已有作用域必须是字典。
|
||||
fn scope(&self, store: &ObjectStore, owner: ObjectRef) -> Result<Option<ObjectRef>, VmError> {
|
||||
match store.get_attr(owner, "taskScope") {
|
||||
Ok(Value::Object(scope)) => {
|
||||
store.dict_items(scope)?;
|
||||
Ok(Some(scope))
|
||||
}
|
||||
Err(VmError::AttributeNotFound(_)) => Ok(None),
|
||||
Ok(_) => Err(VmError::InvalidArgument("invalid test scope")),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
/// 由写屏障建立真实拥有边,测试结束时可交给 VM 正常回收。
|
||||
fn install_scope(
|
||||
&self,
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
scope: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
cx.set_attr(owner, "taskScope", Value::Object(scope))
|
||||
}
|
||||
/// 外部修改普通布尔字段即可撤销交付资格,不借用 Tessera 的任何模型。
|
||||
fn eligible(
|
||||
&self,
|
||||
store: &ObjectStore,
|
||||
owner: ObjectRef,
|
||||
_context: ObjectRef,
|
||||
) -> Result<bool, VmError> {
|
||||
Ok(store.get_attr(owner, "eligible")? == Value::Bool(true))
|
||||
}
|
||||
/// 所有任务共享宿主注册的精确类型身份。
|
||||
fn task_type(&self, store: &ObjectStore, context: ObjectRef) -> Result<ObjectRef, VmError> {
|
||||
object(store.get_attr(context, "Task")?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// VM 外的计数器观察真正回调次数,零参/Unit 契约与 after 要求一致。
|
||||
struct Count(Arc<AtomicUsize>);
|
||||
impl NativeCallable for Count {
|
||||
/// 明确接受零个参数,不能依赖旧原生函数缺少元数据的兼容路径。
|
||||
fn arity(&self) -> Option<CallArity> {
|
||||
Some(CallArity::exact(0))
|
||||
}
|
||||
/// 每次真正执行递增一次,取消和状态查询不得触发它。
|
||||
fn invoke(
|
||||
&self,
|
||||
_cx: &mut NativeContext<'_>,
|
||||
_args: &[Value],
|
||||
) -> Result<NativeResult, VmError> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(NativeResult::Return(Value::Nil))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解码借用或拥有的对象值;此函数不改变根计数,调用方按来源管理拥有权。
|
||||
fn object(value: Value) -> Result<ObjectRef, VmError> {
|
||||
match value {
|
||||
Value::Object(value) => Ok(value),
|
||||
_ => Err(VmError::InvalidArgument("expected test object")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 所有创建根交给 VmSession;api/context/owner 是会话根的借用身份。
|
||||
fn setup() -> (
|
||||
VmSession,
|
||||
Scheduler,
|
||||
ObjectRef,
|
||||
ObjectRef,
|
||||
ObjectRef,
|
||||
Arc<AtomicUsize>,
|
||||
) {
|
||||
let mut runtime = VmSession::new().unwrap();
|
||||
let types = runtime.vm_mut().bootstrap_types().unwrap();
|
||||
runtime.keep_root(types.object);
|
||||
runtime.keep_root(types.type_type);
|
||||
let definition = runtime
|
||||
.vm_mut()
|
||||
.new_type("Task", types.object, TypeConstructor::Abstract)
|
||||
.unwrap();
|
||||
runtime.keep_root(definition);
|
||||
let context = runtime.vm_mut().new_object().unwrap();
|
||||
runtime.keep_root(context);
|
||||
runtime
|
||||
.vm_mut()
|
||||
.set_attr(context, "Task", Value::Object(definition))
|
||||
.unwrap();
|
||||
let api = runtime.vm_mut().new_object().unwrap();
|
||||
runtime.keep_root(api);
|
||||
let owner = runtime.vm_mut().new_object().unwrap();
|
||||
runtime.keep_root(owner);
|
||||
runtime
|
||||
.vm_mut()
|
||||
.set_attr(owner, "eligible", Value::Bool(true))
|
||||
.unwrap();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let callback = runtime
|
||||
.vm_mut()
|
||||
.allocate(ContextNativeFunction::new(
|
||||
"count",
|
||||
Count(calls.clone()),
|
||||
vec![],
|
||||
))
|
||||
.unwrap();
|
||||
runtime.keep_root(callback);
|
||||
let scheduler = runtime
|
||||
.with_host(|vm, roots| tasks::install(vm, roots, api, context, Arc::new(PlainHost)))
|
||||
.unwrap();
|
||||
(runtime, scheduler, api, owner, callback, calls)
|
||||
}
|
||||
|
||||
/// 通过安装的公开 API 创建零延时任务;返回根交给会话,避免旧 token 因替换而提前回收。
|
||||
fn after(
|
||||
runtime: &mut VmSession,
|
||||
api: ObjectRef,
|
||||
owner: ObjectRef,
|
||||
callback: ObjectRef,
|
||||
key: &str,
|
||||
) -> ObjectRef {
|
||||
let function = object(runtime.vm().get_attr(api, "after").unwrap()).unwrap();
|
||||
let task = object(
|
||||
runtime
|
||||
.vm_mut()
|
||||
.call(
|
||||
function,
|
||||
&[
|
||||
Value::Object(owner),
|
||||
Value::Text(key.into()),
|
||||
Value::Number(0_i64.into()),
|
||||
Value::Object(callback),
|
||||
],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
runtime.keep_root(task);
|
||||
task
|
||||
}
|
||||
|
||||
/// 经真实类型方法绑定读取状态,不直接检查 Nexus 的私有 Task 载荷。
|
||||
fn query(vm: &mut Vm, task: ObjectRef, name: &str) -> Value {
|
||||
let bound = object(vm.bind_attr(task, name).unwrap()).unwrap();
|
||||
let result = vm.call(bound, &[]);
|
||||
vm.release(bound).unwrap();
|
||||
result.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 替换旧 token 后只有新任务执行一次;终态 token 可继续查询,拥有字典已经清空。
|
||||
fn same_key_replacement_only_delivers_the_new_identity() {
|
||||
let (mut runtime, scheduler, api, owner, callback, calls) = setup();
|
||||
let old = after(&mut runtime, api, owner, callback, "same");
|
||||
let new = after(&mut runtime, api, owner, callback, "same");
|
||||
assert_eq!(
|
||||
query(runtime.vm_mut(), old, "status"),
|
||||
Value::Text("cancelled".into())
|
||||
);
|
||||
// 取消被替换的旧 token 不得删除新任务的 owner/key 身份。
|
||||
assert_eq!(query(runtime.vm_mut(), old, "cancel"), Value::Bool(false));
|
||||
assert_eq!(query(runtime.vm_mut(), new, "active"), Value::Bool(true));
|
||||
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 1);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
query(runtime.vm_mut(), new, "status"),
|
||||
Value::Text("completed".into())
|
||||
);
|
||||
assert_eq!(query(runtime.vm_mut(), new, "result"), Value::Nil);
|
||||
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 0);
|
||||
let scope = PlainHost
|
||||
.scope(runtime.vm().object_store(), owner)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.vm()
|
||||
.object_store()
|
||||
.dict_items(scope)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
scheduler.quiesce(runtime.vm_mut()).unwrap();
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// 交付前撤销资格阻止回调,轮询执行取消;退出门闩在重新取得资格后仍拒绝提交。
|
||||
fn host_lifecycle_and_shutdown_prevent_late_delivery() {
|
||||
let (mut runtime, scheduler, api, owner, callback, calls) = setup();
|
||||
let task = after(&mut runtime, api, owner, callback, "late");
|
||||
runtime
|
||||
.vm_mut()
|
||||
.set_attr(owner, "eligible", Value::Bool(false))
|
||||
.unwrap();
|
||||
assert_eq!(query(runtime.vm_mut(), task, "active"), Value::Bool(false));
|
||||
assert_eq!(scheduler.poll(runtime.vm_mut(), 64).unwrap(), 1);
|
||||
assert_eq!(
|
||||
query(runtime.vm_mut(), task, "status"),
|
||||
Value::Text("cancelled".into())
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
scheduler.quiesce(runtime.vm_mut()).unwrap();
|
||||
runtime
|
||||
.vm_mut()
|
||||
.set_attr(owner, "eligible", Value::Bool(true))
|
||||
.unwrap();
|
||||
let function = object(runtime.vm().get_attr(api, "after").unwrap()).unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.vm_mut()
|
||||
.call(
|
||||
function,
|
||||
&[
|
||||
Value::Object(owner),
|
||||
Value::Text("forbidden".into()),
|
||||
Value::Number(0_i64.into()),
|
||||
Value::Object(callback),
|
||||
]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
runtime.close().unwrap();
|
||||
assert_eq!(runtime.vm().object_count(), 0);
|
||||
}
|
||||
Reference in New Issue
Block a user