diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index e9db79a..185c663 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -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) diff --git a/.gitignore b/.gitignore index 9a1f8e6..1333141 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/CHANGELOG.md b/CHANGELOG.md index a0a87b5..80151df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 可随内容增高。 diff --git a/Cargo.lock b/Cargo.lock index 6c7382e..ff658ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 3a9e205..cbb1dd3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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] diff --git a/crates/marqdo-wasm/Cargo.toml b/crates/marqdo-wasm/Cargo.toml new file mode 100644 index 0000000..86429f8 --- /dev/null +++ b/crates/marqdo-wasm/Cargo.toml @@ -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" diff --git a/crates/marqdo-wasm/README.md b/crates/marqdo-wasm/README.md new file mode 100644 index 0000000..778c1f4 --- /dev/null +++ b/crates/marqdo-wasm/README.md @@ -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). diff --git a/crates/marqdo-wasm/src/lib.rs b/crates/marqdo-wasm/src/lib.rs new file mode 100644 index 0000000..72c9b90 --- /dev/null +++ b/crates/marqdo-wasm/src/lib.rs @@ -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"); + } +} diff --git a/doc/roadmap/browser-wasm.md b/doc/roadmap/browser-wasm.md index 30edceb..45335a0 100644 --- a/doc/roadmap/browser-wasm.md +++ b/doc/roadmap/browser-wasm.md @@ -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`(及可选虚拟 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 | diff --git a/examples/browser-hello/README.md b/examples/browser-hello/README.md new file mode 100644 index 0000000..b7c38b9 --- /dev/null +++ b/examples/browser-hello/README.md @@ -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) diff --git a/examples/browser-hello/index.html b/examples/browser-hello/index.html new file mode 100644 index 0000000..5431b75 --- /dev/null +++ b/examples/browser-hello/index.html @@ -0,0 +1,82 @@ + + + + + + Marqdo browser hello (WASM C1) + + + +

Marqdo

+

浏览器内 WASM 解释器(路线 C / C1):源码是 .mq.md,无业务手写 JS。

+ + +
+ +
+
loading wasm…
+ + + diff --git a/examples/browser-hello/loader.js b/examples/browser-hello/loader.js new file mode 100644 index 0000000..eee4891 --- /dev/null +++ b/examples/browser-hello/loader.js @@ -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(); diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index 912d7e5..3f18401 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -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()) + } + } } } diff --git a/src/host/mod.rs b/src/host/mod.rs index 3f13f23..a2d7e93 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -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, /// Concurrent subtasks (`lib/subtask`): file / function / foreign. + #[cfg_attr(not(feature = "exec-host"), allow(dead_code))] pub(crate) subtasks: HashMap, pub subtask_seq: u64, } diff --git a/src/host/net.rs b/src/host/net.rs index f70430f..7ad5666 100644 --- a/src/host/net.rs +++ b/src/host/net.rs @@ -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, String> { let Some(h) = headers else { return Ok(Vec::new()); @@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result, } } +#[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( mut reader: R, echo: bool, @@ -755,6 +766,7 @@ fn read_sse_body_to_events( } /// 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, diff --git a/src/host/plugin_stub.rs b/src/host/plugin_stub.rs new file mode 100644 index 0000000..ea8d084 --- /dev/null +++ b/src/host/plugin_stub.rs @@ -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, + pub data: *mut (), +} + +pub fn with_lib_path_call(_hook: LibPathCall, body: impl FnOnce() -> R) -> R { + body() +} + +#[derive(Clone)] +pub struct RegisteredFn { + pub params: Vec, +} + +#[derive(Debug, Default, Clone)] +pub struct PluginState; + +impl PluginState { + pub fn get(&self, _name: &str) -> Option<&RegisteredFn> { + None + } + + pub fn list_names(&self) -> Vec { + Vec::new() + } +} + +pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result { + Err("plugin.load unavailable in browser wasm".into()) +} + +pub fn unload(_ctx: &mut HostContext) -> Result { + Err("plugin.unload unavailable in browser wasm".into()) +} + +pub fn list(_ctx: &HostContext) -> Result { + Ok(Value::List(Vec::new())) +} + +pub fn call_registered( + _ctx: &mut HostContext, + name: &str, + _bound: &HashMap, +) -> Result { + Err(format!("plugin `{name}` unavailable in browser wasm")) +} diff --git a/src/host/subtask_stub.rs b/src/host/subtask_stub.rs new file mode 100644 index 0000000..0a9a7a1 --- /dev/null +++ b/src/host/subtask_stub.rs @@ -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) {} diff --git a/src/host/sys.rs b/src/host/sys.rs index 7197d9d..681a96b 100644 --- a/src/host/sys.rs +++ b/src/host/sys.rs @@ -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 { 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 { + #[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 Result { - 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 { - 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 { @@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result { } } 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) } diff --git a/src/input_feed.rs b/src/input_feed.rs index 544f172..e93ebee 100644 --- a/src/input_feed.rs +++ b/src/input_feed.rs @@ -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 { 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 { let prompt = normalize_prompt(prompt); let _guard = TermGuard::enter_cbreak()?; @@ -290,7 +293,7 @@ fn read_stdin_line_interactive(prompt: &str) -> Result { } } -#[cfg(not(unix))] +#[cfg(not(all(unix, feature = "tty")))] fn read_stdin_line_interactive(prompt: &str) -> Result { let prompt = normalize_prompt(prompt); print!("{prompt}"); diff --git a/src/lib.rs b/src/lib.rs index 35ed71b..c9eb031 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 { } } } + +/// Run source text in-memory (browser wasm / tests). Imports resolve via embedded `lib/` only. +pub fn run_source(source: &str, opts: &RunOptions) -> Result { + 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"); + } +} diff --git a/src/load.rs b/src/load.rs index 19557a1..14ae0d9 100644 --- a/src/load.rs +++ b/src/load.rs @@ -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, 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 { + let mut visited = HashSet::new(); + load_module_from_source_inner(source, "", &mut visited) +} + +fn load_module_from_source_inner( + source: &str, + label: &str, + visited: &mut HashSet, +) -> Result { + 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) -> Result { + 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)]