Extract the Nexus runtime from Tessera
This commit is contained in:
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)?,
|
||||
})
|
||||
}
|
||||
Vendored
+411
@@ -0,0 +1,411 @@
|
||||
//! 后台文件/网络 provider。线程池只携带纯数据、取消控制与弱 Task 身份,不持有 VM。
|
||||
//! Lease 由托管任务拥有,释放会撤销交付资格并取消可取消的后台工作;已经完成的结果还要由 VM worker 检查归属后才能交付。
|
||||
//! 并发、队列、读取字节数、超时和 URL 协议均有边界,避免 provider 绕过运行时资源限制。
|
||||
//!
|
||||
//! 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};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
process::{Child, Command, Stdio},
|
||||
sync::{
|
||||
Arc, Mutex, OnceLock,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
mpsc::{SyncSender, sync_channel},
|
||||
},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
// 文件与 HTTP 返回文本最多 1 MiB,最终必须为有效 UTF-8;长度按字节计算。
|
||||
const MAX_TEXT: usize = 1024 * 1024;
|
||||
// 每个运行时的租约额度,独立于全进程 4 个执行线程和 64 项工作队列。
|
||||
const MAX_ACTIVE: usize = 16;
|
||||
// 全进程实际执行 OS I/O 的线程数;排队不等于已占一个执行线程。
|
||||
const WORKERS: usize = 4;
|
||||
// 工作队列全局上限,try_send 失败直接反馈给提交方,不让 VM 阻塞等空位。
|
||||
const QUEUE: usize = 64;
|
||||
// 成功/失败都只传字符串;不能把 VmError 内部可能关联的托管值或 VM 句柄送入后台线程。
|
||||
type Completion = Result<String, String>;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
/// provider 共享的就绪结果与并发计数;内容只有纯数据和弱任务身份。
|
||||
struct Shared {
|
||||
// worker 写入、take_ready 排空,Lease::drop 也会移除本任务的晚到/未取结果。
|
||||
ready: Mutex<HashMap<WeakObjectRef, Completion>>,
|
||||
// 统计当前活租约而非正在执行的 OS 操作;完成结果被取走前,租约仍可能占用名额。
|
||||
active: AtomicUsize,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// 某个运行时拥有的后台 provider 能力,负责提交和取走完成结果。
|
||||
pub struct Provider {
|
||||
// Arc 可供后台 Job 访问邮箱,不代表 Job 拥有 Task 或能延长交付租约。
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
#[derive(Debug, Default)]
|
||||
/// 后台工作取消标记与可取消子进程,不拥有托管 VM。
|
||||
struct Control {
|
||||
// Release/Acquire 传播取消资格;最终写邮箱时还需在 ready 锁内再次检查。
|
||||
cancelled: AtomicBool,
|
||||
process: Mutex<Option<Child>>,
|
||||
}
|
||||
impl Control {
|
||||
/// Lease 析构调用,可在 VM/租约线程执行;只撤资格/kill,不在调用线程 wait 进程退出。
|
||||
fn cancel(&self) {
|
||||
// 先撤销结果交付资格,再尝试终止当前子进程;文件读取无法用此标记中断,只能丢弃晚到结果。
|
||||
self.cancelled.store(true, Ordering::Release);
|
||||
if let Ok(mut process) = self.process.lock()
|
||||
&& let Some(child) = process.as_mut()
|
||||
{
|
||||
// Reaping belongs to the provider worker, never the VM thread.
|
||||
// VM/租约线程这里只 kill,不 wait;子进程回收由持有 Reaper 的 I/O worker 完成,避免阻塞 VM。
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 后台工作种类及其纯文本参数,源调用的类型检查在提交前完成。
|
||||
pub enum Request {
|
||||
// 本地路径已在任务创建时做类型/长度校验,worker 再检查实际文件类型和大小。
|
||||
ReadText(String),
|
||||
// URL 会由 fetch_text 再验证 HTTP(S)/authority,传输不用 shell 解释。
|
||||
FetchText(String),
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// 仅托管 Task 拥有的交付租约;释放它会取消后台资格并清理晚到结果。
|
||||
pub struct Lease {
|
||||
// 归还名额与移除结果所需共享状态;不持有任务本体,避免后台根反向保活源程序。
|
||||
shared: Arc<Shared>,
|
||||
// 带代际的弱身份用于邮箱键,Task 死亡后不能让旧结果命中复用槽位的新任务。
|
||||
task: WeakObjectRef,
|
||||
// 取消后台进程/晚到交付的纯原生控制对象,后台 Job 只共享它而不共享 Lease。
|
||||
control: Arc<Control>,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
/// 最后一个 Arc<Lease> 释放时撤销交付资格、删除待交付结果并归还一次并发额度;后台 Job 不延长租约。
|
||||
fn drop(&mut self) {
|
||||
// 租约释放立即取消交付资格;后台 OS 读取即使稍后结束,也不能再次唤醒旧 Task。
|
||||
self.control.cancel();
|
||||
if let Ok(mut ready) = self.shared.ready.lock() {
|
||||
// 删除已到邮箱的结果;worker 同锁复查 cancelled,所以取消之后也不能重新留下结果。
|
||||
ready.remove(&self.task);
|
||||
}
|
||||
// Lease 包在 Arc 中,只有最后一个拥有者释放才析构并归还一次额度;Job 不持有 Lease。
|
||||
self.shared.active.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
/// 线程池队列中的纯数据工作,关联弱任务身份、控制和共享完成表。
|
||||
struct Job {
|
||||
// 操作种类及参数只含拥有字符串,不借用 VM 对象属性或源参数切片。
|
||||
request: Request,
|
||||
// 只用于交付结果地址,后台从不尝试升级弱引用。
|
||||
task: WeakObjectRef,
|
||||
// 共享取消状态/进程槽,让租约销毁可终止传输;Job 不持 Lease,因此不阻止取消。
|
||||
control: Arc<Control>,
|
||||
// 结果写入对应 Provider 的 mailbox,不把不同运行时结果混入一个全局表。
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
impl Provider {
|
||||
/// tasks 的 I/O 创建路径调用,原子预占额度、建立 RAII Lease 并非阻塞入队,返回交付资格而非执行结果。
|
||||
pub fn submit(
|
||||
&self,
|
||||
task: WeakObjectRef,
|
||||
request: Request,
|
||||
replacing: bool,
|
||||
) -> Result<Arc<Lease>, VmError> {
|
||||
// 原子更新同时完成检查和预占,防止并发提交都观察到剩余名额而超配。
|
||||
// replacing 允许替换期间临时多一个租约,旧任务取消后回到正常上限。
|
||||
self.shared
|
||||
.active
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |active| {
|
||||
// replacing 只放宽一次替换的瞬时名额,不为普通提交永久提升每运行时上限。
|
||||
(active < MAX_ACTIVE + usize::from(replacing)).then_some(active + 1)
|
||||
})
|
||||
.map_err(|_| VmError::ExecutionLimit("16 I/O tasks per runtime"))?;
|
||||
// 预占后立即建立 RAII 租约;线程池不可用或队列发送失败时,局部 lease 析构会归还名额。
|
||||
let lease = Arc::new(Lease {
|
||||
shared: self.shared.clone(),
|
||||
task,
|
||||
control: Arc::new(Control::default()),
|
||||
});
|
||||
// 池初始化也可能失败;lease 已建立,任何后续 ? 都会归还预占额度。
|
||||
let sender = pool().map_err(|_| VmError::InvalidArgument("I/O provider unavailable"))?;
|
||||
// 非阻塞入队,不让调用 VM 等待后台吞吐;Job 只带参数、弱任务身份和原生取消/结果状态。
|
||||
sender
|
||||
.try_send(Job {
|
||||
request,
|
||||
task,
|
||||
control: lease.control.clone(),
|
||||
shared: self.shared.clone(),
|
||||
})
|
||||
.map_err(|_| VmError::ExecutionLimit("I/O provider queue full or unavailable"))?;
|
||||
Ok(lease)
|
||||
}
|
||||
/// Scheduler::poll 在 VM worker 调用,排空此 Provider 的已就绪纯数据,不在邮箱锁中执行源回调。
|
||||
// 一次 drain 所有已就绪结果;移走纯数据不代表任务仍可交付,VM worker 还需检查弱身份和归属。
|
||||
pub fn take_ready(&self) -> Result<Vec<(WeakObjectRef, Completion)>, VmError> {
|
||||
Ok(self
|
||||
.shared
|
||||
.ready
|
||||
.lock()
|
||||
.map_err(|_| VmError::InvalidArgument("I/O mailbox poisoned"))?
|
||||
.drain()
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
/// Provider::submit 调用,懒初始化全进程线程池;返回借用的 SyncSender,不为每个 VM 新建 I/O 线程。
|
||||
fn pool() -> Result<&'static SyncSender<Job>, &'static str> {
|
||||
// 全进程只初始化一次,初始化失败也会记住失败结果;后续 submit 返回 unavailable,不反复创建线程。
|
||||
static POOL: OnceLock<Result<SyncSender<Job>, String>> = OnceLock::new();
|
||||
POOL.get_or_init(|| {
|
||||
// 队列只承载 Job;容量限制排队任务,不代替 Provider 自己的 MAX_ACTIVE 租约预算。
|
||||
let (sender, receiver) = sync_channel::<Job>(QUEUE);
|
||||
// std Receiver 不可 Clone,短锁共享接收端;拿到一个 Job 后放锁再并行执行 I/O。
|
||||
let receiver = Arc::new(Mutex::new(receiver));
|
||||
for index in 0..WORKERS {
|
||||
// 每线程持接收端 Arc,不持任何 Provider/Task 的租约,空闲时阻塞 recv 而非轮询。
|
||||
let receiver = receiver.clone();
|
||||
thread::Builder::new()
|
||||
.name(format!("tessera-io-{index}"))
|
||||
.spawn(move || {
|
||||
loop {
|
||||
// std mpsc Receiver 通过 Mutex 共享;锁只覆盖取任务,实际 I/O 在离开该 match 后并行执行。
|
||||
let job = match receiver.lock() {
|
||||
Ok(receiver) => receiver.recv(),
|
||||
// 接收锁损坏时终止该线程,不在不可靠队列状态上继续读任务。
|
||||
Err(_) => break,
|
||||
};
|
||||
let Ok(job) = job else {
|
||||
// 所有 sender 已断开就退出;这不是一个可重试的临时“队列为空”。
|
||||
break;
|
||||
};
|
||||
// 执行前先跳过已取消队列项,避免启动无用文件读取或 curl。
|
||||
if job.control.cancelled.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
// 只进行原生文件/HTTP 操作,失败也编码成纯文本 Completion,留给 VM 线程交付。
|
||||
let result = match &job.request {
|
||||
Request::ReadText(path) => read_text(path),
|
||||
Request::FetchText(url) => fetch_text(url, &job.control),
|
||||
};
|
||||
// 持有 ready 锁后再次检查取消,与 Lease::drop 的取消/移除配合,防止取消后重新留下晚到结果。
|
||||
if let Ok(mut ready) = job.shared.ready.lock()
|
||||
&& !job.control.cancelled.load(Ordering::Acquire)
|
||||
{
|
||||
// 与 Lease::drop 用同一 ready 锁封住取消/插入竞争,晚到结果不能重新激活旧 Task。
|
||||
ready.insert(job.task, result);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
Ok(sender)
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(|_| "I/O provider unavailable")
|
||||
}
|
||||
/// pool 的 ReadText 分支在后台调用,返回受字节预算限制的 UTF-8 文本或可交付错误字符串。
|
||||
fn read_text(path: &str) -> Completion {
|
||||
// 先按路径检查普通文件和已知长度,及早拒绝目录/超大源;实际打开后还会复核文件类型。
|
||||
let metadata = std::fs::metadata(path).map_err(|error| error.to_string())?;
|
||||
if !metadata.is_file() {
|
||||
return Err("text source must be a regular file".into());
|
||||
}
|
||||
if metadata.len() > MAX_TEXT as u64 {
|
||||
// 提交线程已校验路径字符串,这里依据实际文件长度提前拒绝,避免明显超限请求进入读取阶段。
|
||||
return Err("text source exceeds 1 MiB".into());
|
||||
}
|
||||
// 路径检查与打开之间可能变化,所以打开后再次检查句柄实际指向的对象类型。
|
||||
let file = File::open(path).map_err(|error| error.to_string())?;
|
||||
if !file
|
||||
.metadata()
|
||||
.map_err(|error| error.to_string())?
|
||||
.is_file()
|
||||
{
|
||||
return Err("text source must be a regular file".into());
|
||||
}
|
||||
// 原始字节最后才严格转 UTF-8,不用有损替换悄悄改写用户文件内容。
|
||||
let mut bytes = Vec::new();
|
||||
// 再用流读取硬上限检测增长中的文件:多读一个字节即可判断超限,不能只依赖之前 metadata 长度。
|
||||
file.take(MAX_TEXT as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if bytes.len() > MAX_TEXT {
|
||||
// metadata 后文件仍可能增长,因此按实际读到的字节数再核验;多读的那个探测字节不会作为正文交付。
|
||||
return Err("text source exceeds 1 MiB".into());
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| "text source must be UTF-8".into())
|
||||
}
|
||||
|
||||
/// tasks 创建 fetchText 与 fetch_text 真正传输前都会调用,拒绝错误协议、过长 URL、控制字符和 userinfo。
|
||||
/// 这是受限文本 GET 接口的基本格式检查,不负责完整 URL 规范化,也不声明网络地址访问授权。
|
||||
pub fn valid_url(url: &str) -> bool {
|
||||
// 控制字符必须在写 curl config 前拒绝,否则换行等可能破坏单个 url 配置项边界。
|
||||
if url.len() > 8192 || url.chars().any(char::is_control) {
|
||||
return false;
|
||||
}
|
||||
let Some((scheme, rest)) = url.split_once("://") else {
|
||||
// 只接受有显式 scheme 的 URL,不让 curl 猜协议或把路径当作另一类资源地址。
|
||||
return false;
|
||||
};
|
||||
if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
|
||||
// scheme 不区分大小写,但必须是明确 HTTP(S);拒绝 file 等其他 curl 可处理协议,不依赖调用方只传网页地址。
|
||||
return false;
|
||||
}
|
||||
// 仅检查协议与 authority 基本约束;@ 禁止 userinfo 凭据,空白禁止模糊主机部分。
|
||||
// 这不是完整 URL 解析器,具体 HTTP 解析仍由 curl 负责。
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||
!authority.is_empty() && !authority.contains('@') && !authority.chars().any(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// fetch_text 仅在 I/O worker 上创建的清理守卫;任何提前返回都取走、kill/wait 尚未回收的子进程。
|
||||
struct Reaper<'a>(&'a Control);
|
||||
impl Drop for Reaper<'_> {
|
||||
/// 取走残留 curl 子进程后尝试 kill/wait,保证失败或取消路径也回收进程,且不持控制锁等待。
|
||||
fn drop(&mut self) {
|
||||
// 从控制槽取出子进程后释放锁,再 kill/wait;只有实际留下的进程才需要回收。
|
||||
let child = self.0.process.lock().ok().and_then(|mut slot| slot.take());
|
||||
if let Some(mut child) = child {
|
||||
// 两项清理都尽力尝试,kill 的错误不跳过 wait;进程可能已经退出,回收仍由这个后台 worker 完成。
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// pool 的 FetchText 分支调用,用系统 curl 做有界 HTTP GET;所有等待与进程回收都发生在后台线程。
|
||||
fn fetch_text(url: &str, control: &Control) -> Completion {
|
||||
if !valid_url(url) {
|
||||
return Err("invalid HTTP(S) URL".into());
|
||||
}
|
||||
#[cfg(unix)]
|
||||
// Unix 固定系统路径,不从用户 PATH 选择任意同名可执行文件。
|
||||
let executable = "/usr/bin/curl";
|
||||
#[cfg(not(unix))]
|
||||
// 非 Unix 使用系统环境可解析的 curl.exe,找不到时反馈明确的传输不可用错误。
|
||||
let executable = "curl.exe";
|
||||
// 参数数组直接交给进程 API,URL 另外经 stdin 配置传入,全程不经 shell 拼接。
|
||||
let mut child = Command::new(executable)
|
||||
// --disable 放首项关闭 curlrc,--globoff 禁用 URL 展开,首次请求与重定向均限制 HTTP(S)。
|
||||
// 限制重定向数、连接/总超时和下载大小;--compressed 后仍会用下面字节读取上限限制解压文本。
|
||||
.args([
|
||||
"--disable",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--globoff",
|
||||
"--location",
|
||||
"--max-redirs",
|
||||
"5",
|
||||
"--proto",
|
||||
"=http,https",
|
||||
"--proto-redir",
|
||||
"=http,https",
|
||||
"--max-time",
|
||||
"30",
|
||||
"--connect-timeout",
|
||||
"10",
|
||||
"--max-filesize",
|
||||
"1048576",
|
||||
"--compressed",
|
||||
"--fail",
|
||||
"--write-out",
|
||||
"\n%{http_code}",
|
||||
"--config",
|
||||
"-",
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|_| "HTTP transport unavailable: system curl is required".to_owned())?;
|
||||
// 取走管道后把 Child 放入共享 Control,取消线程可随时 kill;Reaper 覆盖其后的所有提前返回。
|
||||
// 管道配置是上方 spawn 的内部前提,take 后分别归配置写入和正文读取负责。
|
||||
let mut input = child.stdin.take().expect("piped stdin");
|
||||
// 取走 stdout 后 Child 仍可放入共享进程槽供取消线程 kill。
|
||||
let output = child.stdout.take().expect("piped stdout");
|
||||
match control.process.lock() {
|
||||
Ok(mut slot) => *slot = Some(child),
|
||||
Err(_) => {
|
||||
// 尚未安装 Reaper 且不能存入共享槽,当前线程必须亲自 kill/wait 清理已启动子进程。
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("HTTP process lock poisoned".into());
|
||||
}
|
||||
}
|
||||
// 从这里起即使写配置/读正文/解析状态失败,也会通过 Drop 回收进程而不留下僵尸。
|
||||
let _reaper = Reaper(control);
|
||||
if control.cancelled.load(Ordering::Acquire) {
|
||||
return Err("request cancelled".into());
|
||||
}
|
||||
// URL 经 curl 配置的引号/反斜杠转义后走 stdin,避免出现在进程参数;这里不经过 shell。
|
||||
let escaped = url.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
writeln!(input, "url = \"{escaped}\"").map_err(|_| "HTTP transport input failed".to_owned())?;
|
||||
// 关闭 stdin 表示配置结束,否则 curl 可能继续等待输入,无法开始/完成请求。
|
||||
drop(input);
|
||||
// stdout 同时含正文与 curl --write-out 状态尾,预算须为尾部保留四字节。
|
||||
let mut bytes = Vec::new();
|
||||
output
|
||||
// 预留结尾换行和三位状态码共 4 字节,再额外读 1 字节探测正文超限。
|
||||
.take(MAX_TEXT as u64 + 5)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "HTTP response read failed".to_owned())?;
|
||||
if bytes.len() > MAX_TEXT + 4 {
|
||||
// 四字节属于 curl 追加的换行/状态码尾部,超过正文预算加尾部即拒绝;Reaper 随返回回收仍可能运行的 curl。
|
||||
return Err("HTTP text exceeds 1 MiB".into());
|
||||
}
|
||||
// 读完输出后用 try_wait 检查退出;等待间隔先释放 process 锁,让其他线程仍可取消进程。
|
||||
let status = loop {
|
||||
// 短暂持锁查询 child 状态;睡眠前释放槽锁,让 Lease::drop 仍可及时 kill。
|
||||
let mut slot = control
|
||||
.process
|
||||
.lock()
|
||||
.map_err(|_| "HTTP process lock poisoned".to_owned())?;
|
||||
// 槽内 Child 在本请求结束前应存在;缺项是状态错误,不继续对另一进程等待。
|
||||
let child = slot.as_mut().ok_or("HTTP process missing")?;
|
||||
if let Some(status) = child
|
||||
.try_wait()
|
||||
.map_err(|_| "HTTP transport wait failed".to_owned())?
|
||||
{
|
||||
// try_wait 已回收退出状态,移除 Child 后 Reaper 析构不会再次 kill/wait 同一个进程。
|
||||
slot.take();
|
||||
break status;
|
||||
}
|
||||
drop(slot);
|
||||
thread::sleep(Duration::from_millis(2));
|
||||
};
|
||||
if control.cancelled.load(Ordering::Acquire) {
|
||||
// 完成传输并不自动取得交付资格,取消优先于刚读到的正常 HTTP 返回值。
|
||||
return Err("request cancelled".into());
|
||||
}
|
||||
// --write-out 的末尾四字节应是换行加三位状态码;checked_sub 处理空/短输出,不直接倒数切片。
|
||||
let code = bytes
|
||||
.len()
|
||||
.checked_sub(4)
|
||||
.and_then(|offset| (bytes[offset] == b'\n').then_some(&bytes[offset + 1..]))
|
||||
.and_then(|digits| std::str::from_utf8(digits).ok())
|
||||
.and_then(|digits| digits.parse::<u16>().ok());
|
||||
// 已知 HTTP 3xx/4xx/5xx 优先以 HTTP 错误报告,其他 curl 非零状态再映射为超时、大小或传输失败。
|
||||
if let Some(code) = code
|
||||
&& code >= 300
|
||||
{
|
||||
return Err(format!("HTTP {code}"));
|
||||
}
|
||||
if !status.success() {
|
||||
// 区分 curl 的超时/大小错误,其余保留退出码供诊断;信号终止没有普通退出码。
|
||||
return Err(match status.code() {
|
||||
Some(28) => "HTTP request timed out".into(),
|
||||
Some(63) => "HTTP text exceeds 1 MiB".into(),
|
||||
Some(code) => format!("HTTP transport failed (curl {code})"),
|
||||
None => "HTTP transport terminated".into(),
|
||||
});
|
||||
}
|
||||
if !code.is_some_and(|code| (200..300).contains(&code)) {
|
||||
// 即使 curl 成功退出,也须有完整且为 2xx 的状态尾;没有状态不能把截断/异常输出当作成功正文。
|
||||
return Err("HTTP response status unavailable".into());
|
||||
}
|
||||
// 确认 2xx 与成功退出后才剥去协议附加状态尾部,再严格解码 UTF-8 正文。
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
String::from_utf8(bytes).map_err(|_| "HTTP text must be UTF-8".into())
|
||||
}
|
||||
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}")
|
||||
}
|
||||
}
|
||||
Vendored
+282
@@ -0,0 +1,282 @@
|
||||
//! 区分完整 Module 与顶层 Script,并保留输入源码位置。
|
||||
//! 解析包装或片段拼接产生的 span 偏移要递归修正,保证诊断和 Sources 视图仍指向用户原始行列。
|
||||
//!
|
||||
//! Nexus PreparedProgram 与 VmSession::prepare_input 调用 parse,再按 roots 进行 AST 预算检查与编译。
|
||||
//! 语句、词法和 AST 定义属于 Aster;这里只把完整源码组织成 Module 或连续 Interactive 输入。
|
||||
//! 片段先用局部字节位置解析,shift_* 递归加回起点,编译错误和 Sources 浏览才能仍对应原文件。
|
||||
use anyhow::Result;
|
||||
use frontend::{
|
||||
ParseMode, SourceUnit, Span, TokenKind,
|
||||
ast::{AstRoot, Decl, DeclKind, Expr, ExprKind, InteractiveInput, Stmt, StmtKind},
|
||||
};
|
||||
|
||||
/// 待编译输入是完整模块还是顶层脚本;两者保留不同根结构但使用统一后续接口。
|
||||
pub enum SourcePlan {
|
||||
// 保留 Aster 完整模块根,后续作为一个编译/执行单元,不拆开函数或类的定义体。
|
||||
Module(AstRoot),
|
||||
// 顶层脚本按完整交互输入连续执行;各段仍共享所属运行时的全局环境,而非各建一个 VM。
|
||||
Script(Vec<AstRoot>),
|
||||
}
|
||||
|
||||
impl SourcePlan {
|
||||
/// PreparedProgram/prepare_input 的 AST 预算访问和 compile_plan 调用,借用统一根切片,不克隆 AST 或重新解析。
|
||||
pub fn roots(&self) -> &[AstRoot] {
|
||||
match self {
|
||||
// 单模块以单元素切片适配,让调用方不必维护两套遍历分支。
|
||||
Self::Module(root) => std::slice::from_ref(root),
|
||||
// 脚本直接保留原输入段顺序,声明和后续使用语句的先后关系不能重排。
|
||||
Self::Script(roots) => roots,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PreparedProgram/prepare_input 的源码准备入口调用,优先接受完整 Module,失败则按顶层换行候选边界拼出 Aster 可解析的交互输入。
|
||||
/// 模块解析失败本身不立即作为最终错误:普通顶层脚本本就需要走后面的 Interactive 解析路径。
|
||||
/// 这里只产出 AST 计划,不执行已接受的片段;Nexus 先完成所有根的预算检查和编译,再进入源代码执行。
|
||||
pub fn parse(source: &SourceUnit) -> Result<SourcePlan> {
|
||||
// 完整模块优先;只有模块解析失败才退回连续交互输入模式,宿主不自行实现 Endor 语法。
|
||||
if let Ok(module) = frontend::parse_source_ast(source, ParseMode::Module) {
|
||||
// 模块成功就不再按行切分,避免破坏跨行声明与完整模块语义。
|
||||
return Ok(SourcePlan::Module(module));
|
||||
}
|
||||
// 一次词法分析获得原始字节 span,候选分段依赖 token 之间的实际换行而非直接按行切字符串。
|
||||
let tokens = frontend::lex_source(source)?;
|
||||
// 只保存已被 Aster 成功接受的交互根,失败候选不留下半棵 AST。
|
||||
let mut roots = Vec::new();
|
||||
// start 为当前待解析片段在原文件中的字节起点,仅在候选成功时前移。
|
||||
let mut start = 0;
|
||||
// 深度只是候选边界启发式;括号失配是否合法仍由 Aster 判定,不在宿主偷偷修正。
|
||||
let mut depth = 0_i64;
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
// 追踪圆/花括号嵌套,括号内换行不能直接结束输入;最终语法是否合法仍交给 Aster。
|
||||
match token.kind {
|
||||
// token 已由词法器识别,字符串/注释里的括号不会当作结构括号改变深度。
|
||||
TokenKind::LeftParen | TokenKind::LeftBrace => depth += 1,
|
||||
TokenKind::RightParen | TokenKind::RightBrace => depth -= 1,
|
||||
// 其他 token 不改变边界嵌套,不能靠普通字符扫描替代此判断。
|
||||
_ => {}
|
||||
}
|
||||
// token 尾为原文本字节位置,用它取与下一 token 之间的空白/注释区域查换行。
|
||||
let end = token.span.end;
|
||||
// 末尾 token 总是尝试解析;非末尾要求顶层换行,且下一 token 不像成员访问、调用或算术续接。
|
||||
let boundary = tokens.get(index + 1).is_none_or(|next| {
|
||||
// 尚在括号内,或下一 token 明显续接上个表达式时,不尝试提前提交当前交互片段。
|
||||
depth == 0
|
||||
&& source.text()[end..next.span.start].contains(['\r', '\n'])
|
||||
&& !matches!(
|
||||
next.kind,
|
||||
TokenKind::Dot
|
||||
| TokenKind::LeftParen
|
||||
| TokenKind::Plus
|
||||
| TokenKind::Minus
|
||||
| TokenKind::Star
|
||||
| TokenKind::Slash
|
||||
)
|
||||
});
|
||||
if !boundary {
|
||||
// 保留 start,之后尝试更长的片段;不是丢弃当前 token 对应源码。
|
||||
continue;
|
||||
}
|
||||
// 当前片段从上一次成功边界 start 开始,保留期间的空白与注释;解析器看到的是片段局部字节位置。
|
||||
match frontend::parse_ast(&source.text()[start..end], ParseMode::Interactive) {
|
||||
Ok(mut root) => {
|
||||
// Interactive 模式的成功根必须为 Interactive;违反是前端接口不变量错误。
|
||||
let AstRoot::Interactive(input) = &mut root else {
|
||||
unreachable!("interactive mode");
|
||||
};
|
||||
// 成功后递归加回 start,把整个 AST 的局部 span 转成原文件位置,再推进下一段起点。
|
||||
shift_input(input, start);
|
||||
roots.push(root);
|
||||
start = end;
|
||||
}
|
||||
// 错误恰在片段末尾且还有 token 时,视为可能未完成的交互输入,保持 start 不动继续拼接。
|
||||
Err(diagnostic) if index + 1 < tokens.len() && diagnostic.span.start == end - start => {
|
||||
// 只有“诊断正好指向片段末尾”才暂缓,下一候选会连同当前片段一起再交 Aster 解析。
|
||||
}
|
||||
Err(mut diagnostic) => {
|
||||
// 其他语法错误立即恢复原始偏移,再用 SourceUnit 添加原文件来源与行列诊断。
|
||||
shift_span(&mut diagnostic.span, start);
|
||||
return Err(source.annotate(diagnostic).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
// 没有接受任何片段时,再把完整输入交给前端校验;是否为空输入/注释及是否可接受,仍由前端定义。
|
||||
if roots.is_empty() {
|
||||
// 不自造宿主错误字符串;失败则保留前端诊断,成功也不把这次仅用于校验的根追加到 roots。
|
||||
frontend::parse_source_ast(source, ParseMode::Interactive)?;
|
||||
}
|
||||
Ok(SourcePlan::Script(roots))
|
||||
}
|
||||
|
||||
/// 下方所有 shift_* 调用的基本操作,给单个半开字节范围加偏移,不递归、不改变源码内容。
|
||||
fn shift_span(span: &mut Span, offset: usize) {
|
||||
// span 采用原文本字节偏移,start/end 同增 offset 保持长度;不是按字符数或行数偏移。
|
||||
span.start += offset;
|
||||
span.end += offset;
|
||||
}
|
||||
|
||||
/// parse 在接受一个 Interactive 根后调用,平移交互根范围,再把语句交给 shift_statement 递归。
|
||||
fn shift_input(input: &mut InteractiveInput, offset: usize) {
|
||||
shift_span(&mut input.span, offset);
|
||||
// 根范围之外,逐条语句递归处理所有内层节点,避免错误只在顶层位置正确。
|
||||
for statement in &mut input.statements {
|
||||
shift_statement(statement, offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// shift_input/函数体/分支体的递归入口,按语句种类平移自己的范围和所有内嵌表达式/声明。
|
||||
fn shift_statement(statement: &mut Stmt, offset: usize) {
|
||||
shift_span(&mut statement.span, offset);
|
||||
match &mut statement.kind {
|
||||
StmtKind::If(branch) => {
|
||||
// If 节点、条件、then 块各有独立 span,平移外层 Stmt 不能自动更新它们。
|
||||
shift_span(&mut branch.span, offset);
|
||||
shift_expression(&mut branch.condition, offset);
|
||||
shift_span(&mut branch.body.span, offset);
|
||||
for s in &mut branch.body.statements {
|
||||
// then 内可能继续嵌套 if/while/声明,不能只调整第一层语句外框。
|
||||
shift_statement(s, offset);
|
||||
}
|
||||
if let Some(body) = &mut branch.otherwise {
|
||||
// else 可省略;存在时块范围和其中每条语句都使用同一个原片段偏移。
|
||||
shift_span(&mut body.span, offset);
|
||||
for s in &mut body.statements {
|
||||
shift_statement(s, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::While(loop_) => {
|
||||
// while 条件和循环体均可含更深的调用/控制流,沿各自 AST 子结构递归而非重新扫描文本。
|
||||
shift_span(&mut loop_.span, offset);
|
||||
shift_expression(&mut loop_.condition, offset);
|
||||
shift_span(&mut loop_.body.span, offset);
|
||||
for s in &mut loop_.body.statements {
|
||||
shift_statement(s, offset);
|
||||
}
|
||||
}
|
||||
StmtKind::Binding(binding) => {
|
||||
// 新绑定独立保存名字和右值范围,诊断未定义符号时需要内部表达式位置正确。
|
||||
shift_span(&mut binding.span, offset);
|
||||
shift_span(&mut binding.name.span, offset);
|
||||
shift_expression(&mut binding.value, offset);
|
||||
}
|
||||
StmtKind::Assignment(assignment) => {
|
||||
// 赋值不同于声明,但同样保留名字与右值两个来源范围,不能仅平移整个语句。
|
||||
shift_span(&mut assignment.span, offset);
|
||||
shift_span(&mut assignment.name.span, offset);
|
||||
shift_expression(&mut assignment.value, offset);
|
||||
}
|
||||
// 成员赋值同时包含目标对象表达式、成员名和右值,三部分都要恢复原始位置。
|
||||
StmtKind::MemberAssignment(assignment) => {
|
||||
shift_span(&mut assignment.span, offset);
|
||||
shift_span(&mut assignment.name.span, offset);
|
||||
shift_expression(&mut assignment.object, offset);
|
||||
shift_expression(&mut assignment.value, offset);
|
||||
}
|
||||
StmtKind::Return(returned) => {
|
||||
// return 自身 span 必须平移;无返回表达式的 Unit 返回不能访问不存在的 value。
|
||||
shift_span(&mut returned.span, offset);
|
||||
if let Some(expression) = &mut returned.value {
|
||||
// 返回值可以是任意复合调用/算术表达式,继续下钻到全部名称和实参。
|
||||
shift_expression(expression, offset);
|
||||
}
|
||||
}
|
||||
// 表达式语句复用完整表达式递归,避免调用参数中的错误仍显示片段局部行列。
|
||||
StmtKind::Expression(expression) => shift_expression(expression, offset),
|
||||
// 顶层/局部声明转交类与函数专用入口,处理参数、类型名及函数体。
|
||||
StmtKind::Declaration(declaration) => shift_declaration(declaration, offset),
|
||||
}
|
||||
}
|
||||
|
||||
/// shift_statement 在声明语句中调用,平移 Decl 外层,再区分函数定义与类定义的内部位置。
|
||||
fn shift_declaration(declaration: &mut Decl, offset: usize) {
|
||||
shift_span(&mut declaration.span, offset);
|
||||
match &mut declaration.kind {
|
||||
// 普通函数和类方法使用相同函数结构,统一由 shift_function 平移签名和函数体。
|
||||
DeclKind::Function(function) => shift_function(function, offset),
|
||||
// 类的名称、基类、字段类型和方法均保存独立 span,不能仅移动声明外层范围。
|
||||
DeclKind::Class(class) => {
|
||||
shift_span(&mut class.span, offset);
|
||||
shift_span(&mut class.name.span, offset);
|
||||
if let Some(base) = &mut class.base {
|
||||
// 无显式基类时不新增默认基类 span,保留前端原始 AST 的可选结构。
|
||||
shift_span(&mut base.span, offset);
|
||||
}
|
||||
for field in &mut class.fields {
|
||||
// 字段节点整体、字段名、类型名分别保存位置,错误类型注解必须指回原文件。
|
||||
shift_span(&mut field.span, offset);
|
||||
shift_span(&mut field.name.span, offset);
|
||||
shift_span(&mut field.type_name.span, offset);
|
||||
}
|
||||
for method in &mut class.methods {
|
||||
// 方法体可能包含更多声明,沿同一套递归入口继续处理。
|
||||
shift_function(method, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// shift_declaration 调用,平移函数名、参数/返回注解和函数体,供编译器类型错误使用原输入坐标。
|
||||
fn shift_function(function: &mut frontend::ast::Function, offset: usize) {
|
||||
shift_span(&mut function.span, offset);
|
||||
shift_span(&mut function.name.span, offset);
|
||||
shift_span(&mut function.return_type.span, offset);
|
||||
// 参数自身、名称、类型各有范围;函数返回类型和函数体范围也独立移动。
|
||||
for parameter in &mut function.parameters {
|
||||
shift_span(&mut parameter.span, offset);
|
||||
shift_span(&mut parameter.name.span, offset);
|
||||
shift_span(&mut parameter.type_name.span, offset);
|
||||
}
|
||||
shift_span(&mut function.body.span, offset);
|
||||
for statement in &mut function.body.statements {
|
||||
// 函数体内每条语句继续按 kind 递归,不能用整体函数范围覆盖内部诊断。
|
||||
shift_statement(statement, offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// 语句/函数递归助手调用,平移表达式与名称成员的范围;语义值和运算符本身保持不变。
|
||||
fn shift_expression(expression: &mut Expr, offset: usize) {
|
||||
shift_span(&mut expression.span, offset);
|
||||
match &mut expression.kind {
|
||||
// 这些叶节点只用表达式外层 span;Symbol/Member 的名称还保存额外 span,需继续调整。
|
||||
ExprKind::Name(_) | ExprKind::Number(_) | ExprKind::String(_) => {}
|
||||
ExprKind::Symbol(name) => shift_span(&mut name.span, offset),
|
||||
ExprKind::Unary { operand, .. } | ExprKind::Await(operand) => {
|
||||
// unary 与 await 都只有一个子表达式,操作符来源已在外层表达式 span 覆盖。
|
||||
shift_expression(operand, offset)
|
||||
}
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
// 两侧都可能含复合表达式,不能只调整最终报错概率更高的右侧。
|
||||
shift_expression(left, offset);
|
||||
shift_expression(right, offset);
|
||||
}
|
||||
ExprKind::Member { object, name } => {
|
||||
// object 可能是调用返回值,name 则是独立标识符,分别调整两类来源。
|
||||
shift_expression(object, offset);
|
||||
shift_span(&mut name.span, offset);
|
||||
}
|
||||
// 调用目标可继续是成员/调用等复合表达式;逐个递归实参而非只改整个 Call 的范围。
|
||||
ExprKind::Call { callee, arguments } => {
|
||||
shift_expression(callee, offset);
|
||||
for argument in arguments {
|
||||
// 保持实参顺序和值不变,只平移每个实参树内部保存的字节位置。
|
||||
shift_expression(argument, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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