feat(wasm): C0/C1 browser Marqdo interpreter on wasm32
Feature-gate host/CLI deps for wasm-core, add run_source, and ship crates/marqdo-wasm with a raw mq_run ABI plus examples/browser-hello. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
f2fd4fb34e
commit
a75b7a1c87
22 files changed
+904
-151
No files matched your search
@@ -27,6 +27,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
|
||||
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
|
||||
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
|
||||
10. **Browser (route C):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); official `loader.js` is host glue only — do not invent a second JS app language for product code.
|
||||
|
||||
## Markup → meaning (v0.2)
|
||||
|
||||
|
||||
@@ -39,6 +39,10 @@ spike/.pytest_cache/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Built browser WASM (rebuild via crates/marqdo-wasm README)
|
||||
/examples/browser-hello/marqdo_wasm.wasm
|
||||
/examples/browser-hello/pkg/
|
||||
|
||||
# Local sqlite / scratch
|
||||
/data/
|
||||
/tmp/
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **浏览器 Marqdo(路线 C)设计锁定**:[ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design/browser-marqdo-wasm.md](doc/design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md)(WASM 解释器,非编译到 JS)。
|
||||
- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。
|
||||
- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。
|
||||
|
||||
### Fixed
|
||||
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
|
||||
|
||||
Generated
+8
@@ -1040,6 +1040,14 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-wasm"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"marqdo",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo_plugin_agent"
|
||||
version = "0.1.0"
|
||||
|
||||
+31
-8
@@ -10,25 +10,48 @@ repository = "https://github.com/cflmy/marqdo"
|
||||
[[bin]]
|
||||
name = "marqdo"
|
||||
path = "src/main.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[features]
|
||||
default = ["native"]
|
||||
native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"]
|
||||
cli = ["dep:clap"]
|
||||
view = ["dep:tiny_http"]
|
||||
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize"]
|
||||
plugin-host = ["dep:libloading"]
|
||||
exec-host = []
|
||||
fs-host = []
|
||||
tty = ["dep:libc"]
|
||||
wasm-core = []
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
clap = { version = "=4.4.18", features = ["derive"] }
|
||||
clap = { version = "=4.4.18", features = ["derive"], optional = true }
|
||||
pulldown-cmark = "0.12"
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
tiny_http = "0.12"
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024).
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] }
|
||||
idna_adapter = "=1.1.0"
|
||||
zeroize = "=1.8.1"
|
||||
libloading = "=0.8.6"
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true }
|
||||
idna_adapter = { version = "=1.1.0", optional = true }
|
||||
zeroize = { version = "=1.8.1", optional = true }
|
||||
libloading = { version = "=0.8.6", optional = true }
|
||||
include_dir = "0.7"
|
||||
libc = "0.2"
|
||||
libc = { version = "0.2", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI).
|
||||
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
|
||||
|
||||
[workspace]
|
||||
members = ["plugins/demo", "plugins/agent", "plugins/web", "plugins/quantum"]
|
||||
members = [
|
||||
"plugins/demo",
|
||||
"plugins/agent",
|
||||
"plugins/web",
|
||||
"plugins/quantum",
|
||||
"crates/marqdo-wasm",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "marqdo-wasm"
|
||||
version = "0.3.1"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||
repository = "https://github.com/cflmy/marqdo"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Marqdo browser WASM (route C)
|
||||
|
||||
Raw `cdylib` exports — no `wasm-bindgen` CLI required.
|
||||
|
||||
```bash
|
||||
# from repo root
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
|
||||
cp target/wasm32-unknown-unknown/release/marqdo_wasm.wasm examples/browser-hello/
|
||||
```
|
||||
|
||||
Open `examples/browser-hello/index.html` via a local static server (ES modules / fetch need http).
|
||||
|
||||
See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Browser export surface for Marqdo (ADR 0002 / C1).
|
||||
//!
|
||||
//! Raw `cdylib` ABI (no wasm-bindgen CLI required):
|
||||
//! - `mq_alloc` / `mq_dealloc` — JS writes UTF-8 source into linear memory
|
||||
//! - `mq_run` — `(ptr, len) -> ptr` to a length-prefixed UTF-8 JSON result
|
||||
//!
|
||||
//! Result JSON: `{ ok, stdout, error, value }`.
|
||||
|
||||
use std::alloc::{alloc, dealloc, Layout};
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
|
||||
use marqdo::{run_source, RunOptions};
|
||||
|
||||
/// Allocate `size` bytes in WASM linear memory (alignment 1).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_alloc(size: usize) -> *mut u8 {
|
||||
if size == 0 {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let layout = match Layout::from_size_align(size, 1) {
|
||||
Ok(l) => l,
|
||||
Err(_) => return ptr::null_mut(),
|
||||
};
|
||||
unsafe { alloc(layout) }
|
||||
}
|
||||
|
||||
/// Free a buffer previously returned by [`mq_alloc`] or [`mq_run`].
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
|
||||
if ptr.is_null() || size == 0 {
|
||||
return;
|
||||
}
|
||||
let layout = match Layout::from_size_align(size, 1) {
|
||||
Ok(l) => l,
|
||||
Err(_) => return,
|
||||
};
|
||||
unsafe { dealloc(ptr, layout) }
|
||||
}
|
||||
|
||||
/// Run Marqdo source. Input: UTF-8 at `ptr..ptr+len`.
|
||||
/// Output: heap buffer = little-endian `u32` byte length + UTF-8 JSON.
|
||||
/// Caller must `mq_dealloc` the returned pointer with `4 + json_len`.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_run(ptr: *const u8, len: usize) -> *mut u8 {
|
||||
let source = if ptr.is_null() || len == 0 {
|
||||
""
|
||||
} else {
|
||||
match std::str::from_utf8(unsafe { slice::from_raw_parts(ptr, len) }) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
return pack_json(&serde_json::json!({
|
||||
"ok": false,
|
||||
"stdout": "",
|
||||
"error": format!("source is not utf-8: {e}"),
|
||||
"value": null,
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
pack_json(&run_to_json(source))
|
||||
}
|
||||
|
||||
/// Package version (NUL-terminated C string in static memory — do not free).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn mq_version() -> *const u8 {
|
||||
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr()
|
||||
}
|
||||
|
||||
fn run_to_json(source: &str) -> serde_json::Value {
|
||||
let mut opts = RunOptions::default();
|
||||
opts.allow_fs_write = false;
|
||||
opts.allow_exec = false;
|
||||
opts.allow_net = false;
|
||||
opts.sleep_limit_ms = Some(0);
|
||||
|
||||
match run_source(source, &opts) {
|
||||
Ok(cap) => serde_json::json!({
|
||||
"ok": true,
|
||||
"stdout": cap.stdout,
|
||||
"error": null,
|
||||
"value": cap.value.as_display(),
|
||||
}),
|
||||
Err(e) => serde_json::json!({
|
||||
"ok": false,
|
||||
"stdout": "",
|
||||
"error": format!("{e:#}"),
|
||||
"value": null,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn pack_json(v: &serde_json::Value) -> *mut u8 {
|
||||
let s = v.to_string();
|
||||
let bytes = s.as_bytes();
|
||||
let total = 4 + bytes.len();
|
||||
let out = mq_alloc(total);
|
||||
if out.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
unsafe {
|
||||
let len = bytes.len() as u32;
|
||||
ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4);
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_hello_json() {
|
||||
let v = run_to_json("# main\n\n> print text=Hello World!\n");
|
||||
assert_eq!(v["ok"], true);
|
||||
assert_eq!(v["stdout"], "Hello World!\n");
|
||||
}
|
||||
}
|
||||
+33
-58
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **进行中**(设计已锁定) |
|
||||
| 状态 | **进行中**(C0–C1 已落地;C2 示例页已有) |
|
||||
| 日期 | 2026-09-01 |
|
||||
| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) |
|
||||
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) |
|
||||
@@ -16,9 +16,9 @@
|
||||
|
||||
| 阶段 | 内容 | 状态 |
|
||||
|------|------|------|
|
||||
| **C0** | 设计锁定;Cargo feature 骨架;`wasm32` **check** 通过(可空跑) | **docs done · impl next** |
|
||||
| **C1** | `run_source` + wasm-bindgen 导出;hello 打印;无 DOM | pending |
|
||||
| **C2** | 官方 loader + `examples/browser-hello`;可选 `marqdo wasm build`;head 挂载约定 | pending |
|
||||
| **C0** | 设计锁定;Cargo feature 骨架;`wasm32` **check** 通过 | **done** |
|
||||
| **C1** | `run_source` + `crates/marqdo-wasm`(`mq_run` ABI);hello 打印 | **done** |
|
||||
| **C2** | 官方 loader + `examples/browser-hello`;可选 CLI 糖;head 挂载约定 | **partial**(示例+loader 已有) |
|
||||
| **C3** | 交互装配(事件表 → 回调);最小 DOM 读写宿主 | pending |
|
||||
| **C4** | `fetch`/定时器异步模型 ADR + 首版桥 | pending |
|
||||
| **C5** | bytecode 后端可选;体积优化;与 view 调试对齐 | pending |
|
||||
@@ -29,46 +29,47 @@
|
||||
|
||||
**目标:** native 默认行为不变;存在 `--features wasm-core --no-default-features` 使核心在 `wasm32-unknown-unknown` 上 `cargo check`。
|
||||
|
||||
**任务:**
|
||||
**已落地:**
|
||||
|
||||
1. ADR + 设计文(本文相关)已合入。
|
||||
2. `Cargo.toml` features:`cli`/`view`/`net-host`/`plugin-host`/`exec-host`/`fs-host`/`wasm-core`。
|
||||
3. `cfg` 隔离:`view`、`ext_cli`、`version_check`(ureq)、`host::{net,plugin,foreign,subtask}` 等。
|
||||
4. `input_feed` TTY/`libc` 仅非 wasm。
|
||||
5. CI 或本地脚本:`rustup target add wasm32-unknown-unknown && cargo check -p marqdo --target wasm32-unknown-unknown --no-default-features --features wasm-core`。
|
||||
- Features:`native`(默认)、`wasm-core`、`view`/`net-host`/`plugin-host`/`exec-host`/`fs-host`/`tty`/`cli`
|
||||
- 可选依赖:`ureq`、`libloading`、`tiny_http`、`libc`、`clap`
|
||||
- `run_source` / `load_module_from_source`(embedded `lib/`)
|
||||
|
||||
**验收:** 上述 check 退出 0;全量 `cargo test`(默认 features)仍绿。
|
||||
**验收:**
|
||||
|
||||
```bash
|
||||
cargo check -p marqdo --target wasm32-unknown-unknown --no-default-features --features wasm-core
|
||||
cargo test --test gold structure_hello
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## C1 — 内存执行闭环
|
||||
|
||||
**目标:** JS/wasm 调用 `run_source`,跑 `# main` + `> print`,拿回 stdout。
|
||||
**目标:** 浏览器/测试调用 `run_source`,跑 `# main` + `> print`,拿回 stdout。
|
||||
|
||||
**任务:**
|
||||
**已落地:**
|
||||
|
||||
1. `pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture>`(及可选虚拟 imports)。
|
||||
2. crate `crates/marqdo-wasm`:`#[wasm_bindgen] pub fn run(source: &str) -> String`(JSON:`{ok,stdout,error}`)。
|
||||
3. 嵌入 `lib/` 只读导入可用。
|
||||
4. 拒绝 fs/exec/plugin/net 并返回明确错误字符串。
|
||||
5. 金样:至少 `hello` 结构子集在 native `run_source` 单测通过。
|
||||
- `pub fn run_source`(tree + bytecode)
|
||||
- crate `crates/marqdo-wasm`:`mq_alloc` / `mq_dealloc` / `mq_run` / `mq_version`(长度前缀 JSON,无需 wasm-bindgen CLI)
|
||||
- 浏览器默认关 fs 写 / exec / net
|
||||
|
||||
**验收:** wasm 实例化后 `run(hello_source)` 得到 `Hello World!`。
|
||||
**验收:**
|
||||
|
||||
```bash
|
||||
cargo test -p marqdo-wasm
|
||||
cargo test --lib run_source_hello
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## C2 — 示例页与挂载
|
||||
|
||||
**目标:** 静态 HTML 打开即可跑 Marqdo;文档说明如何嵌入站点。
|
||||
**目标:** 静态 HTML 打开即可跑 Marqdo。
|
||||
|
||||
**任务:**
|
||||
|
||||
1. `examples/browser-hello/`:`index.html` + loader + 构建说明。
|
||||
2. (可选)`marqdo wasm build` 包装 `wasm-pack`。
|
||||
3. 与 W8 `page.head`:文档示例挂 `type=module` + wasm(实现可后置)。
|
||||
4. README / tutorial 短节。
|
||||
|
||||
**验收:** 按 README 本地 `python -m http.server`(或等价)打开示例见打印结果。
|
||||
**已有:** `examples/browser-hello/`(`index.html` + `loader.js` + README)。
|
||||
**仍缺:** `marqdo wasm build` CLI 糖;`page.head` 文档示例挂载。
|
||||
|
||||
---
|
||||
|
||||
@@ -76,14 +77,7 @@
|
||||
|
||||
**目标:** 无手写业务 JS 的点击 → Marqdo 函数 → 改页面。
|
||||
|
||||
**任务:**
|
||||
|
||||
1. 宿主:`dom_text_set` / `dom_text_get` / `add_listener`(经 bindgen)。
|
||||
2. L1 `ext/web` 或 `ext/browser`:`交互装配` / `wire_events`。
|
||||
3. 示例:按钮计数或问候。
|
||||
4. 设计补一节返回值指令格式(若 Map 驱 DOM)。
|
||||
|
||||
**验收:** 示例页点击按钮,DOM 文本变化;网络面板无第三方业务脚本(仅官方 loader)。
|
||||
(见设计 §6)
|
||||
|
||||
---
|
||||
|
||||
@@ -91,28 +85,11 @@
|
||||
|
||||
**目标:** 受控 `fetch`(及 sleep)不阻塞语言谎言。
|
||||
|
||||
**任务:**
|
||||
|
||||
1. 短 ADR:续体 / 回调表 / Promise 桥选型。
|
||||
2. `浏览器.请求` 首版 + 金样/示例。
|
||||
3. 能力开关默认关,示例显式开。
|
||||
|
||||
**验收:** 示例请求公共 HTTP(或 mock)并把正文写回 DOM。
|
||||
|
||||
---
|
||||
|
||||
## C5 — 硬化
|
||||
|
||||
**目标:** 可选项生产化。
|
||||
|
||||
**任务:**
|
||||
|
||||
1. `--backend bytecode` 在 wasm 对齐。
|
||||
2. `wasm-opt`、code splitting 评估。
|
||||
3. view / 静态页调试:加载同一 wasm 跑片段(呼应 `next-phase.md`)。
|
||||
4. 体积与启动预算写入设计文。
|
||||
|
||||
**验收:** 文档中的预算表 + CI 双后端子集金样。
|
||||
**目标:** bytecode、体积、`view` 调试对齐。
|
||||
|
||||
---
|
||||
|
||||
@@ -121,15 +98,13 @@
|
||||
```
|
||||
C0 ──► C1 ──► C2 ──► C3 ──► C4
|
||||
│ │
|
||||
└──── C5 ◄─────┘(可与 C4 部分并行)
|
||||
└──── C5 ◄─────┘
|
||||
```
|
||||
|
||||
服务端 `ext/web` W0–W8 **不阻塞** C0–C2;C3 与 head/assets 集成最顺。
|
||||
|
||||
---
|
||||
|
||||
## 进度记录
|
||||
|
||||
| 日期 | 记录 |
|
||||
|------|------|
|
||||
| 2026-09-01 | ADR 0002 + 设计锁定;路线图开篇;开始 C0/C1 实现 |
|
||||
| 2026-09-01 | ADR 0002 + 设计锁定;C0 feature-gate;C1 `run_source` + `marqdo-wasm` + browser-hello |
|
||||
@@ -0,0 +1,16 @@
|
||||
# browser-hello(WASM C1)
|
||||
|
||||
在浏览器里跑 Marqdo `print`(路线 C)。
|
||||
|
||||
```bash
|
||||
# 仓库根目录
|
||||
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release
|
||||
cp target/wasm32-unknown-unknown/release/marqdo_wasm.wasm examples/browser-hello/
|
||||
|
||||
cd examples/browser-hello
|
||||
python3 -m http.server 8765
|
||||
# 打开 http://127.0.0.1:8765/
|
||||
```
|
||||
|
||||
- `loader.js` 仅为官方宿主桥(分配内存 / 调 `mq_run`),不是业务语言。
|
||||
- 设计:[browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)
|
||||
@@ -0,0 +1,82 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo browser hello (WASM C1)</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #1a1f1c;
|
||||
--paper: #e8efe6;
|
||||
--accent: #2f6f4e;
|
||||
--muted: #5a6b60;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(1200px 600px at 10% -10%, #c5dcc8 0%, transparent 55%),
|
||||
linear-gradient(165deg, #f3f7f2, var(--paper));
|
||||
padding: 2rem clamp(1rem, 4vw, 3rem);
|
||||
}
|
||||
h1 {
|
||||
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(1.6rem, 3vw, 2.2rem);
|
||||
margin: 0 0 0.35rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.5rem; max-width: 36rem; }
|
||||
label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 0.35rem; }
|
||||
textarea {
|
||||
width: min(40rem, 100%);
|
||||
min-height: 10rem;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border: 1px solid #b7c7bb;
|
||||
border-radius: 2px;
|
||||
background: rgba(255,255,255,0.7);
|
||||
font-family: "IBM Plex Mono", ui-monospace, monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
button {
|
||||
margin-top: 0.85rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
border: 0;
|
||||
background: var(--accent);
|
||||
color: #f5faf6;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled { opacity: 0.5; cursor: wait; }
|
||||
pre {
|
||||
margin-top: 1.25rem;
|
||||
width: min(40rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。</p>
|
||||
<label for="src">程序</label>
|
||||
<textarea id="src"># main
|
||||
|
||||
> print text=Hello from browser WASM!
|
||||
</textarea>
|
||||
<div>
|
||||
<button id="run" disabled>运行</button>
|
||||
</div>
|
||||
<pre id="out">loading wasm…</pre>
|
||||
<script type="module" src="./loader.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Thin loader for marqdo_wasm.wasm (C1 raw ABI).
|
||||
* Not application logic — only host bridge.
|
||||
*/
|
||||
|
||||
const DEFAULT_SRC = `# main
|
||||
|
||||
> print text=Hello from browser WASM!
|
||||
`;
|
||||
|
||||
function readCString(memory, ptr) {
|
||||
const bytes = new Uint8Array(memory.buffer);
|
||||
let end = ptr;
|
||||
while (bytes[end] !== 0) end += 1;
|
||||
return new TextDecoder().decode(bytes.subarray(ptr, end));
|
||||
}
|
||||
|
||||
function runSource(exports, source) {
|
||||
const encoded = new TextEncoder().encode(source);
|
||||
const inPtr = exports.mq_alloc(encoded.length || 1);
|
||||
if (!inPtr) throw new Error("mq_alloc failed");
|
||||
new Uint8Array(exports.memory.buffer, inPtr, encoded.length).set(encoded);
|
||||
const outPtr = exports.mq_run(inPtr, encoded.length);
|
||||
exports.mq_dealloc(inPtr, encoded.length || 1);
|
||||
if (!outPtr) throw new Error("mq_run returned null");
|
||||
const view = new DataView(exports.memory.buffer);
|
||||
const jsonLen = view.getUint32(outPtr, true);
|
||||
const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen);
|
||||
const text = new TextDecoder().decode(jsonBytes);
|
||||
exports.mq_dealloc(outPtr, 4 + jsonLen);
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const out = document.getElementById("out");
|
||||
const btn = document.getElementById("run");
|
||||
const src = document.getElementById("src");
|
||||
if (!src.value.trim()) src.value = DEFAULT_SRC;
|
||||
|
||||
const wasmPath = "./marqdo_wasm.wasm";
|
||||
const res = await fetch(wasmPath);
|
||||
if (!res.ok) {
|
||||
out.classList.add("err");
|
||||
out.textContent =
|
||||
`failed to fetch ${wasmPath} (${res.status}).\n` +
|
||||
`Build: cargo build -p marqdo-wasm --target wasm32-unknown-unknown --release\n` +
|
||||
`Copy: cp target/wasm32-unknown-unknown/release/marqdo_wasm.wasm examples/browser-hello/`;
|
||||
return;
|
||||
}
|
||||
const { instance } = await WebAssembly.instantiateStreaming(res, {});
|
||||
const exports = instance.exports;
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
out.classList.remove("err");
|
||||
out.textContent = `marqdo-wasm ${ver} ready.\n`;
|
||||
btn.disabled = false;
|
||||
|
||||
btn.addEventListener("click", () => {
|
||||
try {
|
||||
const result = runSource(exports, src.value);
|
||||
out.classList.toggle("err", !result.ok);
|
||||
out.textContent = result.ok
|
||||
? (result.stdout || "(empty stdout)") +
|
||||
(result.value && result.value !== "None" ? `\n[return] ${result.value}` : "")
|
||||
: result.error || "error";
|
||||
} catch (e) {
|
||||
out.classList.add("err");
|
||||
out.textContent = String(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
+223
-51
@@ -2,7 +2,11 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
|
||||
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
#[cfg(feature = "plugin-host")]
|
||||
use crate::host::plugin;
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -648,22 +652,52 @@ pub fn call_host(
|
||||
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
|
||||
HostFn::JsonKeys => json::keys(require(bound, "value")?),
|
||||
HostFn::JsonQuote => json::quote(require(bound, "text")?),
|
||||
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?, bound.get("headers")),
|
||||
HostFn::HttpPost => net::http_post(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
),
|
||||
HostFn::HttpPostSse => net::http_post_sse(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
bound.get("echo"),
|
||||
),
|
||||
HostFn::HttpGet => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_get unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::HttpPost => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_post(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_post unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::HttpPostSse => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_post_sse(
|
||||
ctx,
|
||||
require(bound, "url")?,
|
||||
require(bound, "body")?,
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
bound.get("echo"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_post_sse unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::OpenAiSseParse => {
|
||||
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
|
||||
}
|
||||
@@ -671,14 +705,24 @@ pub fn call_host(
|
||||
crate::host::event_bus::publish(require(bound, "event")?);
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
HostFn::HttpRequest => net::http_request(
|
||||
ctx,
|
||||
require(bound, "method")?,
|
||||
require(bound, "url")?,
|
||||
bound.get("body"),
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
),
|
||||
HostFn::HttpRequest => {
|
||||
#[cfg(feature = "net-host")]
|
||||
{
|
||||
net::http_request(
|
||||
ctx,
|
||||
require(bound, "method")?,
|
||||
require(bound, "url")?,
|
||||
bound.get("body"),
|
||||
bound.get("content_type"),
|
||||
bound.get("headers"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("http_request unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
|
||||
HostFn::Pi => math::pi(),
|
||||
HostFn::EConst => math::e_const(),
|
||||
@@ -756,33 +800,111 @@ pub fn call_host(
|
||||
bound.get("path"),
|
||||
bound.get("grid"),
|
||||
),
|
||||
HostFn::ForeignSetCmd => foreign::set_cmd(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "cmd")?,
|
||||
bound.get("args"),
|
||||
),
|
||||
HostFn::ForeignRun => foreign::run(ctx, require(bound, "code")?, bound.get("stdin")),
|
||||
HostFn::ForeignRunLang => foreign::run_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
),
|
||||
HostFn::ForeignLangs => foreign::langs(ctx),
|
||||
HostFn::PluginLoad => plugin::load(ctx, require(bound, "path")?),
|
||||
HostFn::PluginUnload => plugin::unload(ctx),
|
||||
HostFn::PluginList => plugin::list(ctx),
|
||||
HostFn::ForeignSetCmd => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::set_cmd(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "cmd")?,
|
||||
bound.get("args"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignRun => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignRunLang => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignLangs => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::langs(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
}
|
||||
HostFn::PluginLoad => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::load(ctx, require(bound, "path")?)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("plugin.load unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::PluginUnload => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::unload(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Err("plugin.unload unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::PluginList => {
|
||||
#[cfg(feature = "plugin-host")]
|
||||
{
|
||||
plugin::list(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
}
|
||||
HostFn::ExtNativePath => {
|
||||
let name = require(bound, "name")?;
|
||||
let s = match name {
|
||||
Value::Text(t) => t.as_str(),
|
||||
_ => return Err("name must be text".into()),
|
||||
};
|
||||
Ok(match crate::ext_cli::installed_native_path(s) {
|
||||
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
|
||||
None => Value::None,
|
||||
})
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
Ok(match crate::ext_cli::installed_native_path(s) {
|
||||
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
#[cfg(not(feature = "cli"))]
|
||||
{
|
||||
let _ = s;
|
||||
Ok(Value::None)
|
||||
}
|
||||
}
|
||||
HostFn::MapSet => {
|
||||
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
|
||||
@@ -899,11 +1021,61 @@ pub fn call_host(
|
||||
bound.get("line"),
|
||||
)
|
||||
}
|
||||
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
|
||||
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
|
||||
HostFn::SubtaskSpawn => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::spawn(ctx, bound)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskPoll => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::poll(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskJoin => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::join(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskKill => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::kill(ctx, require(bound, "id")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::SubtaskWaitAll => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
subtask::wait_all(ctx)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Err("subtask unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,21 @@ pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
mod fs;
|
||||
pub(crate) mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
#[path = "plugin_stub.rs"]
|
||||
pub mod plugin;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod subtask;
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
#[path = "subtask_stub.rs"]
|
||||
pub mod subtask;
|
||||
mod sys;
|
||||
mod time;
|
||||
@@ -80,6 +89,7 @@ pub struct HostContext {
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
|
||||
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
|
||||
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub subtask_seq: u64,
|
||||
}
|
||||
|
||||
+14
-2
@@ -1,10 +1,14 @@
|
||||
//! HTTP host primitives (HTTP and HTTPS via ureq).
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::io::Write;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::io::{BufRead, BufReader};
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
#[cfg(feature = "net-host")]
|
||||
use crate::host::HostContext;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
@@ -13,6 +17,7 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
|
||||
let Some(h) = headers else {
|
||||
return Ok(Vec::new());
|
||||
@@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn http_exchange(
|
||||
method: &str,
|
||||
url: &str,
|
||||
@@ -84,6 +90,7 @@ fn http_exchange(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn response_map(status: u16, body: String) -> Value {
|
||||
Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
@@ -91,6 +98,7 @@ fn response_map(status: u16, body: String) -> Value {
|
||||
])
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_get(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
@@ -105,6 +113,7 @@ pub fn http_get(
|
||||
Ok(response_map(status, body))
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_post(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
@@ -127,6 +136,7 @@ pub fn http_post(
|
||||
}
|
||||
|
||||
/// Generic request: method + url + optional body / content_type / headers.
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_request(
|
||||
ctx: &HostContext,
|
||||
method: &Value,
|
||||
@@ -630,6 +640,7 @@ pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result<Value, Str
|
||||
Ok(Value::List(openai_chat_sse_events(text, echo)?))
|
||||
}
|
||||
|
||||
#[cfg(feature = "net-host")]
|
||||
fn read_sse_body_to_events<R: BufRead>(
|
||||
mut reader: R,
|
||||
echo: bool,
|
||||
@@ -755,6 +766,7 @@ fn read_sse_body_to_events<R: BufRead>(
|
||||
}
|
||||
|
||||
/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps.
|
||||
#[cfg(feature = "net-host")]
|
||||
pub fn http_post_sse(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub const ABI_VERSION: u32 = 2;
|
||||
pub const ABI_VERSION_MIN: u32 = 1;
|
||||
|
||||
/// Hook: resolve bare `lib.member` (unused without native plugins).
|
||||
pub struct LibPathCall {
|
||||
pub call: fn(*mut (), &str) -> Result<Value, String>,
|
||||
pub data: *mut (),
|
||||
}
|
||||
|
||||
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
|
||||
body()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegisteredFn {
|
||||
pub params: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct PluginState;
|
||||
|
||||
impl PluginState {
|
||||
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn list_names(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
|
||||
Err("plugin.load unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Err("plugin.unload unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
|
||||
pub fn call_registered(
|
||||
_ctx: &mut HostContext,
|
||||
name: &str,
|
||||
_bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
Err(format!("plugin `{name}` unavailable in browser wasm"))
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
|
||||
|
||||
use crate::host::HostContext;
|
||||
|
||||
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Handle;
|
||||
|
||||
pub fn kill_all(_ctx: &mut HostContext) {}
|
||||
+17
-1
@@ -1,5 +1,6 @@
|
||||
//! System / process host primitives.
|
||||
|
||||
#[cfg(feature = "exec-host")]
|
||||
use std::process::Command;
|
||||
|
||||
use crate::host::HostContext;
|
||||
@@ -97,10 +98,24 @@ pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
|
||||
if ctx.soft_side_effects {
|
||||
return Err(format!("exit {c} (soft mode does not terminate process)"));
|
||||
}
|
||||
std::process::exit(c as i32);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err(format!("exit {c} unavailable in browser wasm"));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::process::exit(c as i32);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, cmd, args);
|
||||
return Err("exec unavailable in browser wasm".into());
|
||||
}
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
if !ctx.allow_exec() {
|
||||
return Err("exec denied by host policy".into());
|
||||
}
|
||||
@@ -123,6 +138,7 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
|
||||
.status()
|
||||
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(1) as i64))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+37
-13
@@ -1,7 +1,8 @@
|
||||
//! Time host primitives.
|
||||
|
||||
use std::thread;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::time::Duration;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
|
||||
@@ -9,19 +10,34 @@ use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn now_unix() -> Result<Value, String> {
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_unix: {e}"))?
|
||||
.as_secs();
|
||||
Ok(Value::Int(secs as i64))
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
|
||||
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_unix: {e}"))?
|
||||
.as_secs();
|
||||
Ok(Value::Int(secs as i64))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now_ms() -> Result<Value, String> {
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_ms: {e}"))?
|
||||
.as_millis();
|
||||
Ok(Value::Int(ms as i64))
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_ms: {e}"))?
|
||||
.as_millis();
|
||||
Ok(Value::Int(ms as i64))
|
||||
}
|
||||
}
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
@@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
thread::sleep(Duration::from_millis(n));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(n));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = Duration::from_millis(n);
|
||||
// Browser wasm has no blocking sleep; ignore (C0/C1).
|
||||
}
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
+11
-8
@@ -3,7 +3,9 @@
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::io::{self, BufRead, Read, Write};
|
||||
use std::io::{self, BufRead, Write};
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -146,11 +148,11 @@ fn strip_block_indent(line: &str) -> String {
|
||||
}
|
||||
|
||||
pub fn stdin_is_tty() -> bool {
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
{
|
||||
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(all(unix, feature = "tty")))]
|
||||
{
|
||||
false
|
||||
}
|
||||
@@ -181,13 +183,13 @@ fn normalize_prompt(prompt: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
struct TermGuard {
|
||||
fd: i32,
|
||||
original: libc::termios,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
impl TermGuard {
|
||||
fn enter_cbreak() -> Result<Self> {
|
||||
let fd = libc::STDIN_FILENO;
|
||||
@@ -206,7 +208,7 @@ impl TermGuard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
impl Drop for TermGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
@@ -215,6 +217,7 @@ impl Drop for TermGuard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
|
||||
let mut out = io::stdout().lock();
|
||||
// CR + clear whole line, then reprint (fixes CJK backspace display desync).
|
||||
@@ -224,7 +227,7 @@ fn redraw_line(prompt: &str, buf: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Interactive line editor: UTF-8 char backspace + full-line redraw.
|
||||
#[cfg(unix)]
|
||||
#[cfg(all(unix, feature = "tty"))]
|
||||
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
let prompt = normalize_prompt(prompt);
|
||||
let _guard = TermGuard::enter_cbreak()?;
|
||||
@@ -290,7 +293,7 @@ fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(all(unix, feature = "tty")))]
|
||||
fn read_stdin_line_interactive(prompt: &str) -> Result<String> {
|
||||
let prompt = normalize_prompt(prompt);
|
||||
print!("{prompt}");
|
||||
|
||||
+73
-1
@@ -8,10 +8,12 @@ pub mod ast;
|
||||
pub mod builtin;
|
||||
pub mod bytecode;
|
||||
pub mod capture;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod catalog;
|
||||
pub mod debug;
|
||||
pub mod diagnostics;
|
||||
pub mod embedded_lib;
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod ext_cli;
|
||||
pub mod foreign;
|
||||
pub mod formula;
|
||||
@@ -23,7 +25,9 @@ pub mod lex;
|
||||
pub mod load;
|
||||
pub mod parse;
|
||||
pub mod value;
|
||||
#[cfg(feature = "net-host")]
|
||||
pub mod version_check;
|
||||
#[cfg(feature = "view")]
|
||||
pub mod view;
|
||||
|
||||
use std::path::Path;
|
||||
@@ -36,7 +40,7 @@ use crate::bytecode::{compile_module, Vm};
|
||||
use crate::capture::RunCapture;
|
||||
use crate::interp::Interpreter;
|
||||
use crate::lex::{classify_source, format_lines_dump};
|
||||
use crate::load::load_module;
|
||||
use crate::load::{load_module, load_module_from_source};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Backend {
|
||||
@@ -293,3 +297,71 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only.
|
||||
pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
|
||||
if source.trim().is_empty() {
|
||||
bail!("source is empty");
|
||||
}
|
||||
let stdin_lines = crate::input_feed::effective_stdin(source, &opts.stdin_lines);
|
||||
let module = load_module_from_source(source)?;
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut host = HostContext::for_capture(None, opts.host_caps());
|
||||
host.set_entry_source(None, source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
}
|
||||
if let Some(lim) = opts.sleep_limit_ms {
|
||||
host.sleep_limit_ms = Some(lim);
|
||||
}
|
||||
let mut interp = Interpreter::with_capture(None, false)
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = interp.run_module(&module)?;
|
||||
let plots = interp.take_plots();
|
||||
Ok(RunCapture {
|
||||
stdout: interp.captured_stdout,
|
||||
value,
|
||||
plots,
|
||||
bindings: interp.entry_bindings,
|
||||
})
|
||||
}
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(None, &module)?;
|
||||
let mut host = HostContext::for_capture(None, opts.host_caps());
|
||||
host.set_entry_source(None, source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
}
|
||||
if let Some(lim) = opts.sleep_limit_ms {
|
||||
host.sleep_limit_ms = Some(lim);
|
||||
}
|
||||
let mut vm = Vm::with_capture(None)
|
||||
.with_stdin(stdin_lines)
|
||||
.with_host(host);
|
||||
let value = vm.run(&program)?;
|
||||
let plots = vm.take_plots();
|
||||
Ok(RunCapture {
|
||||
stdout: vm.captured_stdout,
|
||||
value,
|
||||
plots,
|
||||
bindings: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_source_hello() {
|
||||
let cap = run_source("# main\n\n> print text=Hello World!\n", &RunOptions::default())
|
||||
.expect("run_source");
|
||||
assert_eq!(cap.stdout, "Hello World!\n");
|
||||
}
|
||||
}
|
||||
+57
-8
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
use crate::ast::{Function, Module};
|
||||
use crate::ast::Module;
|
||||
use crate::diagnostics::Diagnostic;
|
||||
use crate::embedded_lib;
|
||||
use crate::parse::parse_source;
|
||||
@@ -212,14 +212,63 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kept for tests / tooling that expect a flat list (local tops only).
|
||||
#[allow(dead_code)]
|
||||
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
|
||||
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
|
||||
*existing = fun;
|
||||
} else {
|
||||
into.push(fun);
|
||||
/// Load a module from source text. Imports may only resolve to the embedded
|
||||
/// `lib/…` stdlib (no filesystem / `ext/` for this MVP path).
|
||||
pub fn load_module_from_source(source: &str) -> Result<Module> {
|
||||
let mut visited = HashSet::new();
|
||||
load_module_from_source_inner(source, "<memory>", &mut visited)
|
||||
}
|
||||
|
||||
fn load_module_from_source_inner(
|
||||
source: &str,
|
||||
label: &str,
|
||||
visited: &mut HashSet<PathBuf>,
|
||||
) -> Result<Module> {
|
||||
let key = PathBuf::from(label);
|
||||
if !visited.insert(key.clone()) {
|
||||
bail!("circular import involving {label}");
|
||||
}
|
||||
|
||||
let result = (|| {
|
||||
let mut module = parse_source(source).map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
|
||||
let imports = module.imports.clone();
|
||||
let mut import_modules = HashMap::new();
|
||||
for imp in imports {
|
||||
let dep = load_embedded_import(&imp.path, visited)?;
|
||||
if import_modules.contains_key(&imp.bind) {
|
||||
bail!("duplicate import bind `{}` while loading {label}", imp.bind);
|
||||
}
|
||||
import_modules.insert(imp.bind, dep);
|
||||
}
|
||||
module.import_modules = import_modules;
|
||||
crate::inherit::validate_inheritance(&module)
|
||||
.map_err(|e| anyhow::anyhow!("{label}: {e}"))?;
|
||||
Ok(module)
|
||||
})();
|
||||
|
||||
visited.remove(&key);
|
||||
result
|
||||
}
|
||||
|
||||
fn load_embedded_import(rel: &str, visited: &mut HashSet<PathBuf>) -> Result<Module> {
|
||||
let rel = rel.replace('\\', "/");
|
||||
let rest = if let Some(r) = rel.strip_prefix("lib/") {
|
||||
r.to_string()
|
||||
} else if let Some(r) = rel.strip_prefix("std/") {
|
||||
r.to_string()
|
||||
} else if embedded_lib::read_file(&rel).is_some() {
|
||||
rel.clone()
|
||||
} else {
|
||||
bail!(
|
||||
"import `{rel}` is not an embedded lib/ path — \
|
||||
run_source only resolves embedded stdlib (lib/…); filesystem and ext/ imports are unsupported"
|
||||
);
|
||||
};
|
||||
let Some(dep_source) = embedded_lib::read_file(&rest) else {
|
||||
bail!("embedded lib not found: lib/{rest}");
|
||||
};
|
||||
let label = format!("lib/{rest}");
|
||||
load_module_from_source_inner(&dep_source, &label, visited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in new issue
Block a user